Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

fix(delivery): reject stale artifacts after failed deliver (#380)

GuYueFangYuan548f3b9e0e3a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index eb581b0e..2fb170b4 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -158,6 +158,24 @@ jobs:
Expand-Archive -Path archify.zip -DestinationPath $packageRoot
- name: Validate packaged skill without installing dependencies
run: node scripts/package-smoke.mjs
+ - name: Install delivery-lock test dependencies
+ if: runner.os != 'Linux'
+ run: npm ci --ignore-scripts
+ working-directory: archify
+ - name: Verify delivery-lock ownership with real subprocesses
+ if: runner.os != 'Linux'
+ run: >-
+ node --test
+ --test-name-pattern="cli: portable delivery lock:"
+ test/cli.test.mjs
+ working-directory: archify
+ - name: Verify macOS opener stays behind delivery-lock release
+ if: runner.os == 'macOS'
+ run: >-
+ node --test
+ --test-name-pattern="cli: lock release failure does not invoke the requested opener"
+ test/cli.test.mjs
+ working-directory: archify
windows-test-portability:
name: Windows test portability
diff --git a/README.md b/README.md
index 643dc75c..833221ec 100644
--- a/README.md
+++ b/README.md
@@ -201,7 +201,7 @@ Archify is not a general-purpose drawing editor or a Mermaid theme. It turns tec
| **Generate** | The agent creates typed JSON IR from your description. |
| **Validate** | Bundled validators and layout rules check the source; failures identify the exact local repair in machine-readable JSON. |
| **Preview (optional)** | A loopback-only desktop session watches one source and reloads only verified revisions; failures keep the last-good artifact. |
-| **Deliver** | A same-directory candidate is rendered and checked; only a passing artifact atomically replaces the target, then optional `--open` launches that exact file. |
+| **Deliver** | A checked artifact/provenance pair becomes current only after its journal finalizes and lock releases; optional `--open` runs afterward. |
| **Iterate** | The agent updates the source while unrelated structure stays stable. |
Useful repository commands:
@@ -218,7 +218,7 @@ node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tm
`preview` is an explicit loopback-only desktop mode: it watches one JSON file on a random `127.0.0.1` port, keeps the last verified output through failures, stops with Ctrl-C, and adds no generated-HTML runtime. Use `--no-open` for tests or manual URL opening.
-`deliver --open` is an opt-in one-shot handoff after commit. Opener failure preserves success; JSON remains on stdout and the absolute fallback path goes to stderr.
+`deliver --open` runs only after commit, journal finalization, and lock release. Opener failure preserves success; JSON stays on stdout and the absolute fallback path goes to stderr.
On failure, `validate --json` and `deliver --json` emit one JSON object. Apply only each `diagnostics[]` subject's `supportedFixes`, within the Skill's two correction rounds; visual review remains separate.
diff --git a/README_EN.md b/README_EN.md
index 643dc75c..833221ec 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -201,7 +201,7 @@ Archify is not a general-purpose drawing editor or a Mermaid theme. It turns tec
| **Generate** | The agent creates typed JSON IR from your description. |
| **Validate** | Bundled validators and layout rules check the source; failures identify the exact local repair in machine-readable JSON. |
| **Preview (optional)** | A loopback-only desktop session watches one source and reloads only verified revisions; failures keep the last-good artifact. |
-| **Deliver** | A same-directory candidate is rendered and checked; only a passing artifact atomically replaces the target, then optional `--open` launches that exact file. |
+| **Deliver** | A checked artifact/provenance pair becomes current only after its journal finalizes and lock releases; optional `--open` runs afterward. |
| **Iterate** | The agent updates the source while unrelated structure stays stable. |
Useful repository commands:
@@ -218,7 +218,7 @@ node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tm
`preview` is an explicit loopback-only desktop mode: it watches one JSON file on a random `127.0.0.1` port, keeps the last verified output through failures, stops with Ctrl-C, and adds no generated-HTML runtime. Use `--no-open` for tests or manual URL opening.
-`deliver --open` is an opt-in one-shot handoff after commit. Opener failure preserves success; JSON remains on stdout and the absolute fallback path goes to stderr.
+`deliver --open` runs only after commit, journal finalization, and lock release. Opener failure preserves success; JSON stays on stdout and the absolute fallback path goes to stderr.
On failure, `validate --json` and `deliver --json` emit one JSON object. Apply only each `diagnostics[]` subject's `supportedFixes`, within the Skill's two correction rounds; visual review remains separate.
diff --git a/README_ZH.md b/README_ZH.md
index eaf2432d..a07fb29b 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -197,7 +197,7 @@ Archify 不是通用绘图编辑器,也不是 Mermaid 主题;它负责把技
| **生成** | Agent 根据描述创建 Typed JSON IR。 |
| **校验** | 内置 Validator 和布局规则检查源文件;失败时用机器可读 JSON 指出准确的局部修复。 |
| **预览(可选)** | 仅 loopback 的桌面会话监听一个源文件,只刷新验证版本;失败时保留最后好图。 |
-| **交付** | 在目标同目录生成并检查候选;只有通过门禁的结果才原子替换目标文件,随后可选用 `--open` 打开这个确切成品。 |
+| **交付** | 成品/凭据对只有在恢复日志完成收尾且交付锁释放后才成为当前版本;随后才可选用 `--open`。 |
| **迭代** | Agent 修改源文件,不干扰无关结构。 |
仓库常用命令:
@@ -214,7 +214,7 @@ node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tm
`preview` 是显式启用的桌面创作模式,不是默认后台服务:它只在随机端口监听 `127.0.0.1`,只观察指定 JSON,失败时保留上一份验证输出,并通过 Ctrl-C 停止。测试或准备手动打开打印出的本地 URL 时可加 `--no-open`。生成的 HTML 不会携带 Preview Runtime。
-`deliver --open` 适合一次性的本地交互交付。它默认关闭,并且只在验证成品原子提交后执行;系统无法打开时,交付仍保持成功,JSON 只写 stdout,stderr 会给出可手动打开的绝对路径。
+`deliver --open` 只在提交、恢复日志收尾和锁释放后执行。系统无法打开时,交付仍保持成功,JSON 只写 stdout,stderr 会给出可手动打开的绝对路径。
失败时,`validate --json` 和 `deliver --json` 仍然只输出一个 JSON 对象。读取 `diagnostics[]`,只修改其中 `subject` 指向的对象,并使用 `supportedFixes` 列出的修复方式;不要整图重写,也不要突破 Skill 最多两轮的聚焦修复上限。确定性诊断仍不等于视觉复核。
diff --git a/archify.zip b/archify.zip
index 46bf5927..72fc7abb 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/SKILL.md b/archify/SKILL.md
index 0328d3bd..72a93f09 100644
--- a/archify/SKILL.md
+++ b/archify/SKILL.md
@@ -32,7 +32,7 @@ Use this bounded path for ordinary generation. Do not read the optional Viewer R
node bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality showcase --json
```
- A non-zero exit can never be described as success. A failed delivery preserves any previous output, so do not run `visual-check` on that path: it would inspect the stale last-good artifact, not the failed candidate. If validation fails, change only the diagnosed `subject`, verify `evidence`, choose from `supportedFixes`, and rerun. Continue focused correction while the objective error count reaches a new minimum. If two consecutive rounds do not improve that best count, stop and report the unresolved diagnostics truthfully.
+ A non-zero exit can never be described as success. Continue to the strict delivery gate below only after `deliver` exits zero. If validation fails, change only the diagnosed `subject`, verify `evidence`, choose from `supportedFixes`, and rerun. Continue focused correction while the objective error count reaches a new minimum. If two consecutive rounds do not improve that best count, stop and report the unresolved diagnostics truthfully.
## Update awareness
@@ -99,12 +99,21 @@ Read `references/authoring-contract.md` only when you need field enums, spacing
## Delivery
-Use `validate` during repair and `deliver` once for final acceptance. Delivery freezes the exact specification bytes into a private same-directory snapshot, renders and checks that snapshot, atomically commits the HTML, and reports SHA-256 plus byte counts for both specification and artifact. This is deterministic artifact evidence; it does not exercise the Viewer in a browser.
+Use `validate` during repair and `deliver` once for final acceptance. This is deterministic artifact evidence; it does not exercise the Viewer in a browser. After `deliver` exits zero, require current delivery evidence before handoff:
-After delivery, collect bounded desktop evidence without modifying or rerendering the trusted HTML:
+```bash
+node bin/archify.mjs check <output.html> --require-provenance
+```
+
+Read `references/delivery-contract.md` whenever `deliver`, strict `check`, or
+`visual-check` fails; provenance is not current; recovery metadata remains; or
+the same output path needs another delivery. That file is the canonical source
+for provenance, serialization, recovery, receipt, and browser-evidence rules.
+
+After the strict `check` above exits zero, collect bounded desktop evidence without modifying or rerendering the trusted HTML:
```bash
-node bin/archify.mjs visual-check <output.html> --json
+node bin/archify.mjs visual-check <output.html> --json --require-provenance
```
For workflow viewport overflow, read [Workflow viewport repair](references/authoring-contract.md#workflow-viewport-repair) before the next layout edit.
@@ -119,7 +128,7 @@ Add `--open` only when the user wants an immediate local preview. For an active
node bin/archify.mjs preview <type> <input>.json <output>.html --quality showcase
```
-Never start preview by default. Read `references/delivery-contract.md` when using preview, repository evidence, export receipts, visual review, or post-commit opening.
+Never start preview by default. Read `references/delivery-contract.md` when using preview, repository evidence, export receipts, visual review, or post-delivery opening.
For separately authored overview/detail diagrams, read [layered reading](references/layered-reading.md) and use its explicit atlas manifest. Prefer existing Focus, Views and Story when one topology can explain the detail.
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index 61995e94..5278ffb1 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -1,7 +1,7 @@
#!/usr/bin/env node
import { spawnSync } from 'node:child_process';
-import { createHash } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -12,6 +12,649 @@ const skillRoot = path.resolve(__dirname, '..');
const TYPES = new Set(['architecture', 'workflow', 'sequence', 'dataflow', 'lifecycle']);
+function deliveryProvenancePath(artifactPath) {
+ const artifact = path.resolve(artifactPath);
+ return `${artifact.replace(/\.html?$/i, '')}.delivery.json`;
+}
+
+function deliveryPendingPath(artifactPath) {
+ return deliveryProvenancePath(artifactPath).replace(/\.json$/, '-pending.json');
+}
+
+function deliveryLockPath(artifactPath) {
+ return deliveryProvenancePath(artifactPath).replace(/\.json$/, '-lock.json');
+}
+
+function processIsRunning(pid) {
+ if (!Number.isInteger(pid) || pid <= 0) return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (error) {
+ return error.code !== 'ESRCH';
+ }
+}
+
+const deliveryOwnershipStates = new WeakMap();
+
+function deliveryOwnershipFailure(state, operation, reason, evidence = {}) {
+ const error = new Error(`Delivery ownership was lost while attempting to ${operation}: ${reason}`);
+ error.deliveryOwnershipCode = 'delivery/ownership-lost';
+ error.deliveryOwnershipDetails = {
+ operation,
+ lock: state?.lockPath,
+ expectedReceiptId: state?.receiptId,
+ reason,
+ ...evidence,
+ };
+ if (state && state.phase !== 'released') state.phase = 'lost';
+ return error;
+}
+
+function deliveryOwnershipState(ownership, operation) {
+ const state = deliveryOwnershipStates.get(ownership);
+ if (!state) throw deliveryOwnershipFailure(undefined, operation, 'the ownership capability is invalid');
+ if (state.phase === 'lost' || state.phase === 'released') {
+ throw deliveryOwnershipFailure(state, operation, `the capability is already ${state.phase}`);
+ }
+ return state;
+}
+
+function sameFileIdentity(actual, expected) {
+ const hasIdentity = (entry) => entry.ino !== 0 && entry.ino !== 0n;
+ return hasIdentity(actual)
+ && hasIdentity(expected)
+ && actual.dev === expected.dev
+ && actual.ino === expected.ino;
+}
+
+function assertDeliveryOwnership(ownership, operation, { allowInitializing = false, pending = 'ignore' } = {}) {
+ const state = deliveryOwnershipState(ownership, operation);
+ let lockEntry;
+ try {
+ lockEntry = fs.lstatSync(state.lockPath);
+ } catch (error) {
+ throw deliveryOwnershipFailure(state, operation, 'the owned lock entry can no longer be inspected', {
+ ...(error?.code ? { systemCode: error.code } : {}),
+ });
+ }
+ if (!lockEntry.isFile() || !sameFileIdentity(lockEntry, state.lockIdentity)) {
+ throw deliveryOwnershipFailure(state, operation, 'the lock path no longer names the entry created by this attempt');
+ }
+ if (state.phase !== 'initializing' || !allowInitializing) {
+ let lock;
+ try {
+ lock = JSON.parse(fs.readFileSync(state.lockPath, 'utf8'));
+ } catch (error) {
+ throw deliveryOwnershipFailure(state, operation, 'the owned lock receipt can no longer be verified', {
+ ...(error?.code ? { systemCode: error.code } : {}),
+ });
+ }
+ if (lock?.schemaVersion !== 1 || lock.receiptId !== state.receiptId || lock.pid !== state.pid) {
+ throw deliveryOwnershipFailure(state, operation, 'the lock receipt no longer matches this attempt', {
+ ...(typeof lock?.receiptId === 'string' ? { observedReceiptId: lock.receiptId } : {}),
+ });
+ }
+ }
+ if (pending !== 'ignore') {
+ const pendingPath = deliveryPendingPath(state.output);
+ let pendingEntry;
+ try {
+ pendingEntry = fs.lstatSync(pendingPath);
+ } catch (error) {
+ if (pending === 'absent' && error.code === 'ENOENT') return state;
+ throw deliveryOwnershipFailure(state, operation, 'the owned delivery journal can no longer be inspected', {
+ journal: pendingPath,
+ ...(error?.code ? { systemCode: error.code } : {}),
+ });
+ }
+ if (pending === 'absent') {
+ throw deliveryOwnershipFailure(state, operation, 'the finalized delivery journal was recreated', { journal: pendingPath });
+ }
+ if (!state.pendingIdentity || !pendingEntry.isFile() || !sameFileIdentity(pendingEntry, state.pendingIdentity)) {
+ throw deliveryOwnershipFailure(state, operation, 'the delivery journal no longer names the entry created by this attempt', {
+ journal: pendingPath,
+ });
+ }
+ if (pending === 'owned' || pending === 'identity') {
+ let journalSource;
+ try {
+ journalSource = fs.readFileSync(pendingPath, 'utf8');
+ } catch (error) {
+ // An unreadable journal is a commit/finalization failure. The unchanged
+ // lock and journal identities still permit a guarded rollback.
+ if (pending === 'owned') throw error;
+ return state;
+ }
+ let journal;
+ try {
+ journal = JSON.parse(journalSource);
+ } catch {
+ throw deliveryOwnershipFailure(state, operation, 'the delivery journal receipt is malformed', {
+ journal: pendingPath,
+ });
+ }
+ if (journal?.receiptId !== state.receiptId) {
+ throw deliveryOwnershipFailure(state, operation, 'the delivery journal receipt belongs to another attempt', {
+ journal: pendingPath,
+ ...(typeof journal?.receiptId === 'string' ? { observedReceiptId: journal.receiptId } : {}),
+ });
+ }
+ }
+ }
+ return state;
+}
+
+function releaseDeliveryOwnership(ownership, { allowInitializing = false } = {}) {
+ const current = deliveryOwnershipState(ownership, 'release the delivery lock');
+ const pending = current.phase === 'finalized'
+ ? 'absent'
+ : current.pendingIdentity
+ ? 'identity'
+ : 'ignore';
+ const state = assertDeliveryOwnership(ownership, 'release the delivery lock', { allowInitializing, pending });
+ try {
+ fs.unlinkSync(state.lockPath);
+ } catch (cause) {
+ if (cause.code === 'ENOENT') {
+ throw deliveryOwnershipFailure(state, 'release the delivery lock', 'the owned lock disappeared before it could be removed', {
+ systemCode: cause.code,
+ });
+ }
+ const error = new Error(`Could not release delivery lock "${state.lockPath}": ${cause.message}`);
+ error.code = cause.code;
+ error.deliveryOwnershipCode = 'delivery/lock-release';
+ error.deliveryOwnershipDetails = {
+ operation: 'release the delivery lock',
+ lock: state.lockPath,
+ expectedReceiptId: state.receiptId,
+ reason: cause.message,
+ };
+ throw error;
+ }
+ state.phase = 'released';
+}
+
+function acquireDeliveryLock(output, receiptId, inputPath, pathsAlias, recordInitializationFailure) {
+ const lockPath = deliveryLockPath(output);
+ try {
+ const existingLock = fs.lstatSync(lockPath);
+ if (!existingLock.isFile()) {
+ throw Object.assign(new Error(`Unrecognized delivery lock at "${lockPath}"; inspect the existing entry before retrying.`), {
+ deliveryLockCode: 'delivery/lock-invalid',
+ });
+ }
+ } catch (error) {
+ if (error.deliveryLockCode) throw error;
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') {
+ throw Object.assign(new Error(`Unrecognized delivery lock at "${lockPath}"; inspect the existing entry before retrying.`), {
+ deliveryLockCode: 'delivery/lock-invalid',
+ });
+ }
+ }
+ if (pathsAlias(lockPath, inputPath)) {
+ throw Object.assign(new Error('Delivery lock path aliases the input specification; choose another output path.'), {
+ deliveryLockCode: 'delivery/lock-path-conflict',
+ });
+ }
+ let descriptor;
+ let ownership;
+ try {
+ descriptor = fs.openSync(lockPath, 'wx', 0o600);
+ const lockIdentity = fs.fstatSync(descriptor);
+ ownership = Object.freeze({});
+ deliveryOwnershipStates.set(ownership, {
+ output: path.resolve(output),
+ lockPath,
+ receiptId,
+ pid: process.pid,
+ lockIdentity,
+ phase: 'initializing',
+ });
+ fs.writeFileSync(descriptor, `${JSON.stringify({ schemaVersion: 1, receiptId, pid: process.pid })}\n`);
+ deliveryOwnershipStates.get(ownership).phase = 'owned';
+ fs.closeSync(descriptor);
+ descriptor = undefined;
+ return ownership;
+ } catch (error) {
+ if (descriptor !== undefined) {
+ try {
+ fs.closeSync(descriptor);
+ } catch (closeError) {
+ error.lockCleanupError = closeError.message;
+ }
+ }
+ if (ownership) {
+ try {
+ assertDeliveryOwnership(ownership, 'record a lock initialization failure', { allowInitializing: true });
+ error.deliveryFailureRecord = recordInitializationFailure?.(error, ownership);
+ releaseDeliveryOwnership(ownership, { allowInitializing: true });
+ } catch (cleanupError) {
+ if (cleanupError.deliveryOwnershipCode) {
+ cleanupError.deliveryOwnershipDetails = {
+ ...(cleanupError.deliveryOwnershipDetails || {}),
+ initializationError: error.message,
+ ...(error?.code ? { initializationSystemCode: error.code } : {}),
+ };
+ if (cleanupError.deliveryOwnershipCode === 'delivery/lock-release' && error.deliveryFailureRecord) {
+ cleanupError.deliveryFailureRecord = error.deliveryFailureRecord;
+ }
+ throw cleanupError;
+ }
+ error.lockCleanupError = cleanupError.message;
+ }
+ throw error;
+ }
+ if (error.code !== 'EEXIST') throw error;
+ let lock;
+ try {
+ if (!fs.lstatSync(lockPath).isFile()) throw new Error('Not a regular lock file.');
+ lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
+ if (lock?.schemaVersion !== 1 || !Number.isSafeInteger(lock.pid) || lock.pid <= 0
+ || typeof lock.receiptId !== 'string'
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(lock.receiptId)) {
+ throw new Error('Unrecognized delivery lock.');
+ }
+ } catch {
+ throw Object.assign(new Error(`Unrecognized delivery lock at "${lockPath}"; inspect the existing entry before retrying.`), {
+ deliveryLockCode: 'delivery/lock-invalid',
+ });
+ }
+ if (processIsRunning(lock.pid)) {
+ throw Object.assign(new Error(`Another delivery attempt owns "${output}" through lock "${lockPath}".`), {
+ deliveryLockCode: 'delivery/concurrent-attempt',
+ });
+ }
+ throw Object.assign(new Error(`A stale delivery lock remains at "${lockPath}"; recover it serially before retrying.`), {
+ deliveryLockCode: 'delivery/lock-stale',
+ deliveryLockOwner: { pid: lock.pid, receiptId: lock.receiptId },
+ });
+ }
+}
+
+function pathEntryExists(file) {
+ try {
+ fs.lstatSync(file);
+ return true;
+ } catch (error) {
+ if (error.code === 'ENOENT' || error.code === 'ENOTDIR') return false;
+ throw error;
+ }
+}
+
+function artifactIdentity(artifact) {
+ return { sha256: createHash('sha256').update(artifact).digest('hex'), bytes: artifact.byteLength };
+}
+
+function beginDeliveryAttempt({ ownership, input, pathsAlias }) {
+ const state = assertDeliveryOwnership(ownership, 'begin the delivery journal', { allowInitializing: true });
+ const { output, receiptId } = state;
+ const journal = deliveryPendingPath(output);
+ for (const protectedPath of [input, output, deliveryProvenancePath(output)].filter(Boolean)) {
+ if (pathsAlias(journal, protectedPath)) throw new Error('Delivery journal aliases an input or output.');
+ }
+ writeDeliveryProvenance(journal, {
+ schemaVersion: 1, command: 'deliver', status: 'pending', receiptId,
+ input, output: path.resolve(output),
+ }, {
+ beforeReplace: () => assertDeliveryOwnership(ownership, 'create the delivery journal', { allowInitializing: true }),
+ });
+ assertDeliveryOwnership(ownership, 'finish creating the delivery journal', { allowInitializing: true });
+ let pendingIdentity;
+ try {
+ pendingIdentity = fs.lstatSync(journal);
+ } catch (error) {
+ throw deliveryOwnershipFailure(state, 'finish creating the delivery journal', 'the new journal identity cannot be captured', {
+ journal,
+ ...(error?.code ? { systemCode: error.code } : {}),
+ });
+ }
+ let pending;
+ try {
+ pending = JSON.parse(fs.readFileSync(journal, 'utf8'));
+ } catch (error) {
+ throw deliveryOwnershipFailure(state, 'finish creating the delivery journal', 'the new journal cannot be verified', {
+ journal,
+ ...(error?.code ? { systemCode: error.code } : {}),
+ });
+ }
+ if (!pendingIdentity.isFile() || pending.receiptId !== receiptId) {
+ throw deliveryOwnershipFailure(state, 'finish creating the delivery journal', 'the new journal belongs to another attempt', {
+ journal,
+ ...(typeof pending?.receiptId === 'string' ? { observedReceiptId: pending.receiptId } : {}),
+ });
+ }
+ assertDeliveryOwnership(ownership, 'finish creating the delivery journal', { allowInitializing: true });
+ state.pendingIdentity = pendingIdentity;
+}
+
+function writeDeliveryProvenance(file, value, { beforeReplace } = {}) {
+ const stagingDirectory = fs.mkdtempSync(path.join(path.dirname(file), '.archify-provenance-'));
+ const temporary = path.join(stagingDirectory, path.basename(file));
+ try {
+ fs.writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { flag: 'wx' });
+ beforeReplace?.();
+ fs.renameSync(temporary, file);
+ } finally {
+ fs.rmSync(stagingDirectory, { recursive: true, force: true });
+ }
+}
+
+function recordDeliveryFailure(options) {
+ const {
+ output, stage, input, error, receiptId, pathsAlias, ownership: suppliedOwnership,
+ releaseOwnership: shouldReleaseSuppliedOwnership = false,
+ } = options;
+ if (!output || !/\.html?$/i.test(output)) return { ok: true, status: 'not-applicable' };
+ let ownership = suppliedOwnership;
+ let acquiredHere = false;
+ if (!ownership) {
+ try {
+ ownership = acquireDeliveryLock(
+ output,
+ receiptId,
+ input,
+ pathsAlias,
+ (lockError, initializingOwnership) => recordDeliveryFailure({
+ ...options,
+ error: `Could not start delivery for "${output}": ${lockError.message}`,
+ ownership: initializingOwnership,
+ releaseOwnership: false,
+ }),
+ );
+ acquiredHere = true;
+ } catch (lockError) {
+ return {
+ ...(lockError.deliveryFailureRecord || { ok: false, status: 'unrecorded' }),
+ lockError,
+ };
+ }
+ }
+ const state = deliveryOwnershipStates.get(ownership);
+ let recorded;
+ // Keep independent evidence even when the artifact is unreadable or the
+ // provenance target is locked, aliases the input, or cannot be replaced.
+ let journalError;
+ if (!state?.pendingIdentity) {
+ try {
+ beginDeliveryAttempt({ ownership, input, pathsAlias });
+ } catch (cause) {
+ if (cause.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ recorded = { ok: false, status: 'unrecorded', ownershipError: cause };
+ }
+ journalError = cause;
+ }
+ }
+ if (!recorded) {
+ let artifact;
+ try {
+ artifact = fs.readFileSync(output);
+ } catch (readError) {
+ if (readError.code === 'ENOENT' || readError.code === 'ENOTDIR') {
+ recorded = { ok: true, status: 'absent' };
+ }
+ // A failed marker does not need an artifact hash to invalidate old evidence.
+ }
+ if (!recorded) {
+ const provenancePath = deliveryProvenancePath(output);
+ let aliasesProtectedPath;
+ try {
+ aliasesProtectedPath = (input && pathsAlias(provenancePath, input))
+ || pathsAlias(provenancePath, output);
+ } catch (aliasError) {
+ recorded = {
+ ok: false,
+ status: 'unrecorded',
+ diagnostic: diagnostic({
+ code: 'delivery/provenance-path-resolution',
+ message: 'Delivery failure provenance could not resolve its target safely.',
+ subject: { output: path.resolve(output), provenance: provenancePath },
+ evidence: {
+ reason: aliasError.message,
+ ...(aliasError?.code ? { systemCode: aliasError.code } : {}),
+ },
+ supportedFixes: ['remove the sidecar path conflict or symbolic-link cycle, then rerun deliver'],
+ }),
+ };
+ }
+ if (!recorded && aliasesProtectedPath) {
+ recorded = {
+ ok: false,
+ status: 'unrecorded',
+ diagnostic: diagnostic({
+ code: 'delivery/provenance-target-alias',
+ message: 'Delivery failure provenance could not be recorded without replacing an input or the artifact.',
+ subject: { output: path.resolve(output), provenance: provenancePath },
+ evidence: { ...(input ? { input: path.resolve(input) } : {}) },
+ supportedFixes: ['choose an output whose .delivery.json sidecar is distinct from every input and the HTML artifact'],
+ }),
+ };
+ }
+ if (!recorded) {
+ try {
+ writeDeliveryProvenance(provenancePath, {
+ schemaVersion: 1,
+ receiptId,
+ status: 'failed',
+ command: 'deliver',
+ stage,
+ input,
+ output: path.resolve(output),
+ ...(artifact ? { artifact: artifactIdentity(artifact) } : {}),
+ error,
+ }, {
+ beforeReplace: () => assertDeliveryOwnership(ownership, 'record failed delivery provenance', {
+ allowInitializing: true,
+ pending: state?.pendingIdentity ? 'owned' : 'ignore',
+ }),
+ });
+ recorded = { ok: true, status: 'failed' };
+ } catch (writeError) {
+ if (writeError.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ recorded = { ok: false, status: 'unrecorded', ownershipError: writeError };
+ } else {
+ recorded = {
+ ok: false,
+ status: 'unrecorded',
+ diagnostic: diagnostic({
+ code: 'delivery/provenance-write',
+ message: 'The failed delivery could not persist its stale-artifact marker.',
+ subject: { output: path.resolve(output), provenance: provenancePath },
+ evidence: {
+ reason: writeError.message,
+ ...(writeError?.code ? { systemCode: writeError.code } : {}),
+ failureJournalRecorded: !journalError,
+ ...(journalError ? { journalError: journalError.message } : {}),
+ },
+ supportedFixes: ['restore write access to the output directory, then rerun deliver before trusting the artifact'],
+ }),
+ };
+ }
+ }
+ }
+ }
+ }
+ if (acquiredHere || shouldReleaseSuppliedOwnership) {
+ try {
+ releaseDeliveryOwnership(ownership, { allowInitializing: true });
+ } catch (lockError) {
+ if (lockError.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ const ownershipError = recorded.ownershipError || lockError;
+ if (options.recoveryDirectory) {
+ ownershipError.deliveryCommitDetails = {
+ ...(ownershipError.deliveryCommitDetails || {}),
+ recoveryRequired: true,
+ recoveryDirectory: options.recoveryDirectory,
+ recoverableBackups: [],
+ };
+ }
+ return {
+ ...recorded,
+ ok: false,
+ status: 'unrecorded',
+ ownershipError,
+ lockError,
+ };
+ }
+ return { ...recorded, lockError: recorded.ownershipError || lockError };
+ }
+ }
+ return recorded;
+}
+
+function deliverySuccessProvenance(receipt) {
+ return {
+ schemaVersion: 1,
+ receiptId: receipt.receiptId,
+ status: 'current',
+ command: 'deliver',
+ type: receipt.type,
+ input: receipt.input,
+ output: receipt.output,
+ specification: receipt.specification,
+ artifact: receipt.artifact,
+ };
+}
+
+function inspectDeliveryProvenance(artifactPath, artifact, { requireProvenance = false } = {}) {
+ const sidecar = deliveryProvenancePath(artifactPath);
+ const pending = deliveryPendingPath(artifactPath);
+ const lock = deliveryLockPath(artifactPath);
+ try {
+ if (pathEntryExists(pending)) {
+ return {
+ ok: false, status: 'failed',
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-failed',
+ message: 'A delivery attempt is unfinished or failed; complete a successful deliver before trusting this artifact.',
+ subject: { artifact: path.resolve(artifactPath), provenance: sidecar },
+ evidence: { pendingJournal: pending, found: true },
+ supportedFixes: ['finish any active delivery, then rerun deliver successfully; retain the pending journal until recovery succeeds'],
+ })],
+ };
+ }
+ } catch (error) {
+ return invalidProvenance(artifactPath, pending, error.message);
+ }
+ try {
+ if (pathEntryExists(lock)) {
+ return {
+ ok: false, status: 'locked',
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-locked',
+ message: 'Delivery ownership is unresolved while the output lock remains; complete or recover delivery before trusting this artifact.',
+ subject: { artifact: path.resolve(artifactPath), lock },
+ evidence: { deliveryLock: lock, found: true },
+ supportedFixes: ['finish the active delivery or inspect and recover the preserved lock, then rerun deliver successfully'],
+ })],
+ };
+ }
+ } catch (error) {
+ return invalidProvenance(artifactPath, lock, error.message);
+ }
+ let found;
+ try {
+ found = pathEntryExists(sidecar);
+ } catch (error) {
+ return invalidProvenance(artifactPath, sidecar, error.message);
+ }
+ if (!found) {
+ if (!requireProvenance) return { ok: true, status: 'unknown' };
+ const message = 'Delivery provenance is required, but the artifact has no .delivery.json sidecar.';
+ return {
+ ok: false,
+ status: 'unknown',
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-required',
+ message,
+ subject: { artifact: path.resolve(artifactPath), provenance: sidecar },
+ evidence: { required: true, found: false },
+ supportedFixes: ['rerun deliver for the current specification, then retry with --require-provenance'],
+ })],
+ };
+ }
+ let receipt;
+ try {
+ if (!fs.lstatSync(sidecar).isFile()) throw new Error('Delivery provenance must be a regular file, not a symbolic link or directory.');
+ receipt = JSON.parse(fs.readFileSync(sidecar, 'utf8'));
+ const identityValid = (value) => value && typeof value.sha256 === 'string' && /^[0-9a-f]{64}$/.test(value.sha256)
+ && Number.isSafeInteger(value.bytes) && value.bytes >= 0;
+ if (!receipt || typeof receipt !== 'object' || Array.isArray(receipt)
+ || receipt.schemaVersion !== 1 || receipt.command !== 'deliver'
+ || typeof receipt.receiptId !== 'string'
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(receipt.receiptId)
+ || typeof receipt.output !== 'string' || !path.isAbsolute(receipt.output) || path.resolve(receipt.output) !== path.resolve(artifactPath)
+ || typeof receipt.input !== 'string' || !path.isAbsolute(receipt.input)
+ || !['current', 'failed'].includes(receipt.status)
+ || (receipt.status === 'current' && (!TYPES.has(receipt.type)
+ || !identityValid(receipt.specification) || !identityValid(receipt.artifact)))
+ || (receipt.status === 'failed' && typeof receipt.stage !== 'string')) {
+ throw new Error('Delivery provenance does not conform to the supported receipt schema.');
+ }
+ } catch (error) {
+ const message = `Could not read delivery provenance: ${error.message}`;
+ return {
+ ok: false,
+ status: 'invalid',
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-invalid',
+ message,
+ subject: { artifact: path.resolve(artifactPath), provenance: sidecar },
+ evidence: { reason: error.message },
+ supportedFixes: ['rerun deliver to replace the invalid provenance sidecar'],
+ })],
+ };
+ }
+ const actualSha256 = createHash('sha256').update(artifact).digest('hex');
+ if (receipt.status === 'failed') {
+ const message = 'The artifact is stale because the latest delivery attempt failed.';
+ return {
+ ok: false,
+ status: 'failed',
+ receiptId: receipt.receiptId,
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-failed',
+ message,
+ subject: { artifact: path.resolve(artifactPath), provenance: sidecar },
+ evidence: { stage: receipt.stage, deliveryReceiptId: receipt.receiptId },
+ supportedFixes: ['repair the specification and complete a successful deliver before checking this artifact'],
+ })],
+ };
+ }
+ if (receipt.artifact?.sha256 !== actualSha256 || receipt.artifact?.bytes !== artifact.byteLength) {
+ const message = 'The artifact bytes do not match their delivery provenance.';
+ return {
+ ok: false,
+ status: 'mismatch',
+ receiptId: receipt.receiptId,
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-mismatch',
+ message,
+ subject: { artifact: path.resolve(artifactPath), provenance: sidecar },
+ evidence: {
+ expectedSha256: receipt.artifact?.sha256,
+ actualSha256,
+ expectedBytes: receipt.artifact?.bytes,
+ actualBytes: artifact.byteLength,
+ },
+ supportedFixes: ['restore the delivered artifact or rerun deliver to create a matching artifact and provenance pair'],
+ })],
+ };
+ }
+ return { ok: true, status: 'current', receiptId: receipt.receiptId, artifact: receipt.artifact };
+}
+
+function invalidProvenance(artifactPath, sidecar, reason) {
+ return {
+ ok: false, status: 'invalid',
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-invalid', message: 'Delivery provenance could not be verified.',
+ subject: { artifact: artifactPath, provenance: sidecar }, evidence: { reason },
+ supportedFixes: ['restore access to the delivery records, then rerun deliver successfully'],
+ })],
+ };
+}
+
function usage() {
return `Usage:
archify render <type> <input.json> [output.html] [--quality standard|showcase] [--repo-root path]
@@ -22,8 +665,8 @@ function usage() {
archify migrate workflow <old.json> <new.json> --to-schema 2 [--json] [--repo-root path]
archify atlas <manifest.json> <output.html> [--json]
archify inspect <type> <input.json>
- archify check <output.html>
- archify visual-check <output.html> [--json] [--out-dir <dir>]
+ archify check <output.html> [--require-provenance]
+ archify visual-check <output.html> [--json] [--require-provenance] [--out-dir <dir>]
archify guide [scenario or question] [--json] [--lang en|zh]
archify brands [name, alias, domain, or category] [--json]
archify brands capture <url> [--json]
@@ -179,6 +822,43 @@ function diagnostic({ code, message, subject = {}, evidence = {}, supportedFixes
};
}
+function deliveryLockFailureDiagnostic(output, error) {
+ const code = error.deliveryOwnershipCode || error.deliveryLockCode || 'delivery/lock-acquire';
+ return diagnostic({
+ code,
+ message: code === 'delivery/lock-release'
+ ? `Delivery lock could not be released for "${output}": ${error.message}`
+ : code === 'delivery/ownership-lost'
+ ? `Delivery ownership was lost for "${output}": ${error.message}`
+ : `Could not start delivery for "${output}": ${error.message}`,
+ subject: { output, lock: deliveryLockPath(output) },
+ evidence: {
+ reason: error.message,
+ ...(error.code ? { systemCode: error.code } : {}),
+ ...(error.lockCleanupError ? { cleanupError: error.lockCleanupError } : {}),
+ ...(error.deliveryLockOwner || {}),
+ ...(error.deliveryOwnershipDetails || {}),
+ ...(error.deliveryCommitDetails || {}),
+ },
+ supportedFixes: code === 'delivery/concurrent-attempt'
+ ? ['wait for the active delivery to finish, then retry']
+ : code === 'delivery/lock-stale'
+ ? [
+ 'confirm no delivery attempt is active for this output',
+ `remove only the preserved lock "${deliveryLockPath(output)}", then rerun deliver successfully`,
+ ]
+ : code === 'delivery/lock-path-conflict'
+ ? ['choose an output whose lock path is distinct from the input specification']
+ : code === 'delivery/lock-invalid'
+ ? ['inspect and preserve the unrecognized lock entry, or choose another output path']
+ : code === 'delivery/ownership-lost'
+ ? ['leave the replacement lock and journal untouched, inspect the reported owner, then retry only after that attempt finishes or is recovered']
+ : code === 'delivery/lock-release'
+ ? ['preserve the reported lock, restore permission to remove that exact entry, then recover serially before retrying']
+ : ['resolve the reported filesystem error and any lock cleanup error, then retry'],
+ });
+}
+
function inputDiagnostic(error, inputPath) {
const isSyntax = error instanceof SyntaxError;
return diagnostic({
@@ -445,6 +1125,119 @@ function commitComparePair({ htmlCandidate, receiptCandidate, outputPath, receip
}
}
+function commitDeliveryPair({ htmlCandidate, provenanceCandidate, outputPath, provenancePath, stagingDirectory, ownership }) {
+ const targets = [
+ { label: 'HTML artifact', target: outputPath, candidate: htmlCandidate, backup: path.join(stagingDirectory, '.previous-output') },
+ { label: 'delivery provenance', target: provenancePath, candidate: provenanceCandidate, backup: path.join(stagingDirectory, '.previous-provenance') },
+ ];
+ assertDeliveryOwnership(ownership, 'start the delivery pair commit', { pending: 'owned' });
+ for (const item of targets) {
+ if (!fs.existsSync(item.target)) continue;
+ const existing = fs.lstatSync(item.target);
+ if (!existing.isFile()) {
+ const error = new Error(`Existing ${item.label} target is not a regular file.`);
+ error.deliveryCommitDetails = {
+ target: item.target,
+ targetType: existing.isDirectory() ? 'directory' : 'non-file',
+ };
+ throw error;
+ }
+ }
+
+ const backedUp = [];
+ const retainedBackups = new Set();
+ const committed = [];
+ try {
+ for (const item of targets) {
+ if (!fs.existsSync(item.target)) continue;
+ assertDeliveryOwnership(ownership, `back up the ${item.label}`, { pending: 'owned' });
+ fs.renameSync(item.target, item.backup);
+ backedUp.push(item);
+ retainedBackups.add(item);
+ }
+ for (const item of targets) {
+ assertDeliveryOwnership(ownership, `commit the ${item.label}`, { pending: 'owned' });
+ fs.renameSync(item.candidate, item.target);
+ committed.push(item);
+ }
+ // Finalization is part of the commit: keep the old files recoverable until
+ // the journal has been removed and checkers can accept the new artifact.
+ const state = assertDeliveryOwnership(ownership, 'finalize the delivery journal', { pending: 'owned' });
+ fs.unlinkSync(deliveryPendingPath(outputPath));
+ assertDeliveryOwnership(ownership, 'finish finalizing the delivery journal', { pending: 'absent' });
+ state.pendingIdentity = undefined;
+ state.phase = 'finalized';
+ return {
+ recoverableBackups: [...retainedBackups].map((item) => ({ label: item.label, path: item.backup })),
+ };
+ } catch (cause) {
+ const recoveryDetails = () => ({
+ recoveryRequired: true,
+ recoveryDirectory: stagingDirectory,
+ recoverableBackups: [...retainedBackups].map((item) => ({ label: item.label, path: item.backup })),
+ });
+ if (cause.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ cause.deliveryCommitDetails = { ...(cause.deliveryCommitDetails || {}), ...recoveryDetails() };
+ throw cause;
+ }
+ const rollbackErrors = [];
+ const recoverableBackups = [];
+ try {
+ for (const item of [...committed].reverse()) {
+ try {
+ assertDeliveryOwnership(ownership, `roll back the ${item.label}`, { pending: 'identity' });
+ fs.rmSync(item.target, { force: true });
+ } catch (error) {
+ if (error.deliveryOwnershipCode === 'delivery/ownership-lost') throw error;
+ rollbackErrors.push(`${item.label}: remove failed (${error.message})`);
+ }
+ }
+ for (const item of [...backedUp].reverse()) {
+ try {
+ assertDeliveryOwnership(ownership, `restore the previous ${item.label}`, { pending: 'identity' });
+ if (fs.existsSync(item.target)) fs.rmSync(item.target, { force: true });
+ assertDeliveryOwnership(ownership, `restore the previous ${item.label}`, { pending: 'identity' });
+ fs.renameSync(item.backup, item.target);
+ retainedBackups.delete(item);
+ } catch (error) {
+ if (error.deliveryOwnershipCode === 'delivery/ownership-lost') throw error;
+ rollbackErrors.push(`${item.label}: restore failed (${error.message})`);
+ // A failed restoration leaves this exact backup at its source path.
+ // Record it without probing the failing recovery path again.
+ recoverableBackups.push({ label: item.label, path: item.backup });
+ }
+ }
+ assertDeliveryOwnership(ownership, 'finish the delivery rollback', { pending: 'identity' });
+ } catch (rollbackError) {
+ if (rollbackError.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ rollbackError.deliveryCommitDetails = {
+ ...(rollbackError.deliveryCommitDetails || {}),
+ commitError: {
+ reason: cause.message,
+ ...(cause?.code ? { systemCode: cause.code } : {}),
+ },
+ ...recoveryDetails(),
+ };
+ throw rollbackError;
+ }
+ rollbackErrors.push(rollbackError.message);
+ }
+ const error = new Error(rollbackErrors.length
+ ? 'Delivery pair commit failed and its previous files could not be fully restored.'
+ : 'Delivery pair commit failed; the previous files were restored.');
+ error.deliveryCommitDetails = {
+ reason: cause.message,
+ ...(rollbackErrors.length ? {
+ rollbackErrors,
+ recoveryRequired: true,
+ recoveryDirectory: stagingDirectory,
+ recoverableBackups,
+ } : {}),
+ };
+ throw error;
+ }
+}
+
function renderValidatedArchitecture(inputPath, outputPath, quality, repoRoot) {
const render = runNode([rendererPath('architecture'), inputPath, outputPath], {
stdio: 'pipe',
@@ -808,17 +1601,19 @@ function commandRender(args) {
if (result.status !== 0) exitFrom(result);
}
-function reportArtifactFailure({ command, json, stage, type, input, output, error, diagnostics = [], status = 1, checker }) {
+function reportArtifactFailure({ command, json, stage, type, input, output, error, diagnostics = [], status = 1, checker, receiptId, provenance }) {
const receipt = {
schemaVersion: 1,
ok: false,
command,
+ ...(receiptId ? { receiptId } : {}),
stage,
type,
input,
...(output === undefined ? {} : { output }),
error,
diagnostics,
+ ...(provenance ? { provenance } : {}),
...(checker ? { checker } : {}),
};
if (json) console.log(JSON.stringify(receipt, null, 2));
@@ -826,8 +1621,51 @@ function reportArtifactFailure({ command, json, stage, type, input, output, erro
process.exitCode = status;
}
-function reportDeliveryFailure(options) {
- reportArtifactFailure({ ...options, command: 'deliver' });
+function writeDeliveryFailureReceipt(options) {
+ const receiptId = options.receiptId || randomUUID();
+ const recorded = recordDeliveryFailure({ ...options, receiptId });
+ const ownershipOrLockError = recorded.ownershipError || recorded.lockError;
+ if (ownershipOrLockError) {
+ const failureWasRecorded = recorded.status && recorded.status !== 'unrecorded';
+ const lockOrOwnershipFailure = Boolean(
+ ownershipOrLockError.deliveryLockCode
+ || ownershipOrLockError.deliveryOwnershipCode,
+ );
+ reportArtifactFailure({
+ ...options,
+ command: 'deliver',
+ receiptId,
+ status: 1,
+ error: lockOrOwnershipFailure
+ ? `Could not safely continue delivery for "${options.output}": ${ownershipOrLockError.message}`
+ : options.error,
+ ...(failureWasRecorded ? { provenance: recorded.status } : {}),
+ diagnostics: lockOrOwnershipFailure
+ ? [
+ deliveryLockFailureDiagnostic(options.output, ownershipOrLockError),
+ ...(options.diagnostics || []),
+ ...(recorded.diagnostic ? [recorded.diagnostic] : []),
+ ]
+ : [
+ ...(options.diagnostics || []),
+ deliveryLockFailureDiagnostic(options.output, ownershipOrLockError),
+ ...(recorded.diagnostic ? [recorded.diagnostic] : []),
+ ],
+ });
+ return recorded;
+ }
+ const diagnostics = [
+ ...(options.diagnostics || []),
+ ...(recorded.diagnostic ? [recorded.diagnostic] : []),
+ ];
+ reportArtifactFailure({
+ ...options,
+ command: 'deliver',
+ receiptId,
+ provenance: recorded.status,
+ diagnostics,
+ });
+ return recorded;
}
function reportValidateFailure(options) {
@@ -887,7 +1725,26 @@ async function commandDeliver(args) {
supportedFixes: ['use: archify deliver <type> <input.json> [output.html] [options]'],
});
const renderer = rendererPath(type);
- const { resolveOutputPath } = await import('../renderers/shared/output-path.mjs');
+ const { pathsAlias, resolveOutputPath } = await import('../renderers/shared/output-path.mjs');
+ const receiptId = randomUUID();
+ let deliveryOwnership;
+ let recoveryRequired = false;
+ let stagingDirectory;
+ const reportDeliveryFailure = (options) => {
+ const ownership = deliveryOwnership;
+ deliveryOwnership = undefined;
+ const recorded = writeDeliveryFailureReceipt({
+ ...options,
+ pathsAlias,
+ receiptId,
+ ownership,
+ releaseOwnership: Boolean(ownership),
+ recoveryDirectory: stagingDirectory,
+ });
+ if (ownership && (recorded?.ownershipError || recorded?.lockError)?.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ recoveryRequired = true;
+ }
+ };
const inputPath = path.resolve(input);
let specification;
let diagram;
@@ -912,6 +1769,7 @@ async function commandDeliver(args) {
? diagram.meta.output
: undefined;
let outputPath;
+ let provenancePath;
try {
({ outputPath } = resolveOutputPath({
requestedOutput,
@@ -919,9 +1777,17 @@ async function commandDeliver(args) {
defaultOutput: `${type}.html`,
inputPaths: [inputPath],
}));
+ ({ outputPath: provenancePath } = resolveOutputPath({
+ requestedOutput: deliveryProvenancePath(outputPath),
+ defaultOutput: deliveryProvenancePath(outputPath),
+ requiredExtension: '.json',
+ inputPaths: [inputPath],
+ inputDescription: 'the delivery input',
+ otherOutputPaths: [outputPath],
+ }));
} catch (error) {
const attemptedOutput = path.resolve(requestedOutput || authoredOutput || `${type}.html`);
- reportDeliveryFailure({
+ const failure = {
json,
stage: 'prepare',
type,
@@ -935,7 +1801,12 @@ async function commandDeliver(args) {
evidence: { ...(error?.code ? { systemCode: error.code } : {}) },
supportedFixes: ['choose a safe output path and retry'],
})],
- });
+ };
+ if (outputPath) {
+ reportDeliveryFailure(failure);
+ } else {
+ reportArtifactFailure({ ...failure, command: 'deliver', receiptId });
+ }
return;
}
const outputDirectory = path.dirname(outputPath);
@@ -964,7 +1835,6 @@ async function commandDeliver(args) {
// Keep the candidate beside the target so the final rename is one
// same-filesystem commit. A render or artifact-check failure never touches
// an existing trusted output.
- let stagingDirectory;
try {
stagingDirectory = fs.mkdtempSync(path.join(outputDirectory, '.archify-delivery-'));
} catch (error) {
@@ -988,8 +1858,72 @@ async function commandDeliver(args) {
}
const candidatePath = path.join(stagingDirectory, path.basename(outputPath));
const specificationSnapshotPath = path.join(stagingDirectory, 'specification.snapshot.json');
+ const provenanceCandidatePath = path.join(stagingDirectory, 'delivery-provenance.json');
+ let commitRecoveryBackups = [];
try {
+ try {
+ deliveryOwnership = acquireDeliveryLock(
+ outputPath,
+ receiptId,
+ inputPath,
+ pathsAlias,
+ (lockError, initializingOwnership) => recordDeliveryFailure({
+ output: outputPath,
+ stage: 'prepare',
+ input: inputPath,
+ error: `Could not start delivery for "${outputPath}": ${lockError.message}`,
+ receiptId,
+ pathsAlias,
+ ownership: initializingOwnership,
+ }),
+ );
+ } catch (error) {
+ const message = `Could not start delivery for "${outputPath}": ${error.message}`;
+ const recorded = error.deliveryFailureRecord;
+ reportArtifactFailure({
+ command: 'deliver', json, stage: 'prepare', type, input: inputPath, output: outputPath, receiptId,
+ error: message,
+ ...(recorded ? { provenance: recorded.status } : {}),
+ diagnostics: [
+ deliveryLockFailureDiagnostic(outputPath, error),
+ ...(recorded?.diagnostic ? [recorded.diagnostic] : []),
+ ],
+ });
+ return;
+ }
+
+ try {
+ beginDeliveryAttempt({ ownership: deliveryOwnership, input: inputPath, pathsAlias });
+ } catch (error) {
+ if (error.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ deliveryOwnership = undefined;
+ recoveryRequired = true;
+ error.deliveryCommitDetails = {
+ recoveryRequired: true,
+ recoveryDirectory: stagingDirectory,
+ recoverableBackups: [],
+ };
+ reportArtifactFailure({
+ command: 'deliver', json, stage: 'prepare', type, input: inputPath, output: outputPath, receiptId,
+ error: `Could not persist the delivery attempt before rendering: ${error.message}`,
+ diagnostics: [deliveryLockFailureDiagnostic(outputPath, error)],
+ });
+ return;
+ }
+ reportDeliveryFailure({
+ json, stage: 'prepare', type, input: inputPath, output: outputPath,
+ error: 'Could not persist the delivery attempt before rendering.',
+ diagnostics: [diagnostic({
+ code: 'delivery/journal-write', message: 'Could not persist the delivery attempt before rendering.',
+ subject: { output: outputPath, journal: deliveryPendingPath(outputPath) },
+ evidence: { reason: error.message },
+ supportedFixes: ['choose a writable output directory with a journal path distinct from the input'],
+ })],
+ });
+ return;
+ }
+
try {
fs.writeFileSync(specificationSnapshotPath, specification, { flag: 'wx' });
} catch (error) {
@@ -1123,6 +2057,7 @@ async function commandDeliver(args) {
const engineeringProfile = engineeringProfileFromArtifact(artifact);
const receipt = {
schemaVersion: 1,
+ receiptId,
ok: true,
command: 'deliver',
type,
@@ -1157,11 +2092,45 @@ async function commandDeliver(args) {
};
try {
- resolveOutputPath({
+ fs.writeFileSync(
+ provenanceCandidatePath,
+ `${JSON.stringify(deliverySuccessProvenance(receipt), null, 2)}\n`,
+ { flag: 'wx' },
+ );
+ } catch (error) {
+ reportDeliveryFailure({
+ json,
+ stage: 'commit',
+ type,
+ input: inputPath,
+ output: outputPath,
+ error: `Could not prepare delivery provenance for "${outputPath}": ${error.message}`,
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-prepare',
+ message: 'Could not prepare the artifact-bound delivery provenance.',
+ subject: { output: outputPath },
+ evidence: { reason: error.message },
+ supportedFixes: ['choose a writable output directory and rerun deliver'],
+ })],
+ });
+ return;
+ }
+
+ try {
+ const currentOutputPath = resolveOutputPath({
requestedOutput,
authoredOutput,
defaultOutput: `${type}.html`,
inputPaths: [inputPath],
+ otherOutputPaths: [provenancePath],
+ }).outputPath;
+ resolveOutputPath({
+ requestedOutput: deliveryProvenancePath(currentOutputPath),
+ defaultOutput: deliveryProvenancePath(currentOutputPath),
+ requiredExtension: '.json',
+ inputPaths: [inputPath],
+ inputDescription: 'the delivery input',
+ otherOutputPaths: [currentOutputPath],
});
} catch (error) {
reportDeliveryFailure({
@@ -1183,9 +2152,34 @@ async function commandDeliver(args) {
}
try {
- fs.renameSync(candidatePath, outputPath);
+ const committed = commitDeliveryPair({
+ htmlCandidate: candidatePath,
+ provenanceCandidate: provenanceCandidatePath,
+ outputPath,
+ provenancePath,
+ stagingDirectory,
+ ownership: deliveryOwnership,
+ });
+ commitRecoveryBackups = committed.recoverableBackups;
} catch (error) {
+ if (error.deliveryOwnershipCode === 'delivery/ownership-lost' && !error.deliveryCommitDetails) {
+ error.deliveryCommitDetails = {
+ recoveryRequired: true,
+ recoveryDirectory: stagingDirectory,
+ recoverableBackups: [],
+ };
+ }
+ recoveryRequired = error.deliveryCommitDetails?.recoveryRequired === true;
const message = `Could not commit verified delivery "${outputPath}": ${error.message}`;
+ if (error.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ deliveryOwnership = undefined;
+ reportArtifactFailure({
+ command: 'deliver', json, stage: 'commit', type, input: inputPath, output: outputPath, receiptId,
+ error: message,
+ diagnostics: [deliveryLockFailureDiagnostic(outputPath, error)],
+ });
+ return;
+ }
reportDeliveryFailure({
json,
stage: 'commit',
@@ -1197,13 +2191,39 @@ async function commandDeliver(args) {
code: 'delivery/commit',
message,
subject: { output: outputPath },
- evidence: { ...(error?.code ? { systemCode: error.code } : {}), reason: error.message },
- supportedFixes: ['choose a replaceable file target on the same writable filesystem'],
+ evidence: {
+ ...(error?.code ? { systemCode: error.code } : {}),
+ reason: error.message,
+ ...(error.deliveryCommitDetails || {}),
+ },
+ supportedFixes: ['choose replaceable regular-file artifact and provenance targets on the same writable filesystem'],
})],
});
return;
}
+ try {
+ releaseDeliveryOwnership(deliveryOwnership);
+ deliveryOwnership = undefined;
+ } catch (error) {
+ deliveryOwnership = undefined;
+ if (error.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ recoveryRequired = true;
+ error.deliveryCommitDetails = {
+ recoveryRequired: true,
+ recoveryDirectory: stagingDirectory,
+ recoverableBackups: commitRecoveryBackups,
+ };
+ }
+ const message = `Delivery committed, but its lock could not be released for "${outputPath}": ${error.message}`;
+ reportArtifactFailure({
+ command: 'deliver', json, stage: 'release', type, input: inputPath, output: outputPath, receiptId,
+ error: message,
+ diagnostics: [deliveryLockFailureDiagnostic(outputPath, error)],
+ });
+ return;
+ }
+
if (open) {
try {
const { openArtifact } = await import('./open-artifact.mjs');
@@ -1232,10 +2252,34 @@ async function commandDeliver(args) {
if (receipt.open?.status === 'opened') console.log(`opened ${outputPath}`);
}
} finally {
- try {
- fs.rmSync(stagingDirectory, { recursive: true, force: true });
- } catch (error) {
- console.error(`Warning: could not remove delivery staging directory "${stagingDirectory}": ${error.message}`);
+ if (deliveryOwnership) {
+ try {
+ releaseDeliveryOwnership(deliveryOwnership, { allowInitializing: true });
+ } catch (error) {
+ if (error.deliveryOwnershipCode === 'delivery/ownership-lost') {
+ recoveryRequired = true;
+ error.deliveryCommitDetails = {
+ ...(error.deliveryCommitDetails || {}),
+ recoveryRequired: true,
+ recoveryDirectory: stagingDirectory,
+ recoverableBackups: commitRecoveryBackups,
+ };
+ }
+ console.error(formatDiagnostics(
+ `Delivery cleanup could not release its lock for "${outputPath}".`,
+ [deliveryLockFailureDiagnostic(outputPath, error)],
+ ));
+ process.exitCode = 1;
+ }
+ }
+ if (recoveryRequired) {
+ console.error(`Recovery required: delivery backups were retained at "${stagingDirectory}".`);
+ } else {
+ try {
+ fs.rmSync(stagingDirectory, { recursive: true, force: true });
+ } catch (error) {
+ console.error(`Warning: could not remove delivery staging directory "${stagingDirectory}": ${error.message}`);
+ }
}
}
}
@@ -1272,48 +2316,180 @@ async function commandPreview(args) {
}
}
+function inspectArtifactDeliveryProvenance(artifactPath, requireProvenance) {
+ let artifact;
+ try {
+ artifact = fs.readFileSync(artifactPath);
+ } catch (error) {
+ return {
+ ok: false, status: 'unknown',
+ diagnostics: [diagnostic({
+ code: 'input/artifact-unreadable', message: `Could not read the HTML artifact: ${error.message}`,
+ subject: { artifact: artifactPath },
+ evidence: { reason: error.message, ...(error.code ? { systemCode: error.code } : {}) },
+ supportedFixes: ['provide an existing readable .html artifact, then rerun the checker'],
+ })],
+ };
+ }
+ return { ...inspectDeliveryProvenance(artifactPath, artifact, { requireProvenance }), artifact: artifactIdentity(artifact) };
+}
+
+function verifyDeliveryUnchanged(artifactPath, expected, checkedArtifact) {
+ const current = inspectArtifactDeliveryProvenance(artifactPath, false);
+ if (current && !current.ok) return current;
+ if (!current || !expected || current.status !== expected.status || current.receiptId !== expected.receiptId
+ || current.artifact.sha256 !== expected.artifact.sha256 || current.artifact.bytes !== expected.artifact.bytes
+ || checkedArtifact.sha256 !== expected.artifact.sha256 || checkedArtifact.bytes !== expected.artifact.bytes) {
+ return {
+ ok: false, status: 'mismatch',
+ diagnostics: [diagnostic({
+ code: 'delivery/provenance-mismatch', message: 'The artifact or delivery record changed during inspection.',
+ subject: { artifact: artifactPath },
+ evidence: { expected: expected?.artifact, checked: checkedArtifact, current: current?.artifact },
+ supportedFixes: ['finish delivery and other writes before rerunning the checker'],
+ })],
+ };
+ }
+ return current;
+}
+
+function provenanceFailureReceipt({ command, artifactPath, provenance }) {
+ const error = provenance.diagnostics[0].message;
+ return {
+ schemaVersion: 1,
+ ok: false,
+ command,
+ ...(command === 'visual-check' ? {
+ evidenceKind: 'automated-browser',
+ status: 'fail',
+ visualReview: 'pending',
+ } : {}),
+ provenance: provenance.status,
+ ...(provenance.receiptId ? { deliveryReceiptId: provenance.receiptId } : {}),
+ artifact: { path: artifactPath },
+ error,
+ ...(command === 'check' ? { file: artifactPath, diagnostic: error } : {}),
+ diagnostics: provenance.diagnostics,
+ };
+}
+
function commandCheck(args) {
- const unknown = args.find((arg) => arg.startsWith('--'));
+ const knownOptions = new Set(['--require-provenance']);
+ const unknown = args.find((arg) => arg.startsWith('--') && !knownOptions.has(arg));
if (unknown) fail(`Unknown check option "${unknown}".`);
- const [html] = args;
- if (!html || args.length !== 1) fail(usage());
- const result = runNode([path.join(skillRoot, 'scripts/check-render-output.mjs'), html]);
- if (result.status !== 0) exitFrom(result);
+ const requireProvenance = args.includes('--require-provenance');
+ const positional = args.filter((arg) => !knownOptions.has(arg));
+ const [html] = positional;
+ if (!html || positional.length !== 1) fail(usage());
+ const artifactPath = path.resolve(html);
+ const provenance = inspectArtifactDeliveryProvenance(artifactPath, requireProvenance);
+ if (provenance && !provenance.ok) {
+ console.log(JSON.stringify(provenanceFailureReceipt({ command: 'check', artifactPath, provenance }), null, 2));
+ process.exitCode = 1;
+ return;
+ }
+ const result = runNode([path.join(skillRoot, 'scripts/check-render-output.mjs'), html], { stdio: 'pipe' });
+ if (result.error) {
+ console.error(result.error.message);
+ process.exitCode = 1;
+ return;
+ }
+ if (result.stdout) {
+ try {
+ const receipt = JSON.parse(result.stdout);
+ if (provenance) {
+ const verified = verifyDeliveryUnchanged(artifactPath, provenance, receipt.artifact || {});
+ if (!verified.ok) {
+ console.log(JSON.stringify(provenanceFailureReceipt({ command: 'check', artifactPath, provenance: verified }), null, 2));
+ process.exitCode = 1;
+ return;
+ }
+ receipt.provenance = provenance.status;
+ if (provenance.receiptId) receipt.deliveryReceiptId = provenance.receiptId;
+ }
+ console.log(JSON.stringify(receipt, null, 2));
+ } catch {
+ process.stdout.write(result.stdout);
+ }
+ }
+ if (result.stderr) process.stderr.write(result.stderr);
+ if (result.status !== 0) process.exitCode = result.status ?? 1;
}
async function commandVisualCheck(rawArgs) {
const { rest: args, outDir } = extractOutDirArgs(rawArgs);
const json = args.includes('--json');
- const knownOptions = new Set(['--json']);
+ const requireProvenance = args.includes('--require-provenance');
+ const knownOptions = new Set(['--json', '--require-provenance']);
const unknown = args.filter((arg) => arg.startsWith('--') && !knownOptions.has(arg));
if (unknown.length) fail(`Unknown visual-check option "${unknown[0]}".`, 1);
const positional = args.filter((arg) => !knownOptions.has(arg));
if (positional.length !== 1) fail(usage(), 1);
+ const artifactPath = path.resolve(positional[0]);
+ const provenance = inspectArtifactDeliveryProvenance(artifactPath, requireProvenance);
let runVisualCheck;
+ let persistVisualCheckFailure;
try {
- ({ runVisualCheck } = await import('./visual-check.mjs'));
+ ({ runVisualCheck, persistVisualCheckFailure } = await import('./visual-check.mjs'));
} catch (error) {
fail(`Could not load visual-check: ${error.message}`, 1);
}
+ if (provenance && !provenance.ok) {
+ const receipt = persistVisualCheckFailure(artifactPath,
+ provenanceFailureReceipt({ command: 'visual-check', artifactPath, provenance }),
+ { outDir });
+ if (json) console.log(JSON.stringify(receipt, null, 2));
+ else {
+ console.error(formatDiagnostics(`automated browser evidence failed: ${receipt.error}`, receipt.diagnostics));
+ console.error('perceptual visual review pending');
+ }
+ process.exitCode = 1;
+ return;
+ }
let result;
try {
- result = await runVisualCheck({ artifactPath: positional[0], outDir });
+ result = await runVisualCheck({
+ artifactPath: positional[0],
+ outDir,
+ ...(provenance ? { deliveryProvenance: provenance } : {}),
+ verifyArtifact: (bytes) => {
+ const verified = verifyDeliveryUnchanged(artifactPath, provenance, artifactIdentity(bytes));
+ if (!verified.ok) {
+ const error = new Error(verified.diagnostics[0].message);
+ error.deliveryProvenance = verified;
+ error.archifyDiagnostics = verified.diagnostics;
+ throw error;
+ }
+ },
+ });
} catch (error) {
- if (json) {
- console.log(JSON.stringify({
+ const failure = persistVisualCheckFailure(artifactPath, {
schemaVersion: 1,
ok: false,
command: 'visual-check',
evidenceKind: 'automated-browser',
status: 'fail',
visualReview: 'pending',
+ ...(provenance ? {
+ provenance: provenance.status,
+ ...(provenance.receiptId ? { deliveryReceiptId: provenance.receiptId } : {}),
+ } : {}),
artifact: { path: path.resolve(positional[0]) },
error: error.message,
- }, null, 2));
+ diagnostics: [diagnostic({
+ code: 'viewer/visual-check-input',
+ message: 'visual-check could not read a valid HTML input or prepare its evidence files.',
+ subject: { artifact: path.resolve(positional[0]) },
+ evidence: { reason: error.message, ...(error.code ? { systemCode: error.code } : {}) },
+ supportedFixes: ['provide an existing readable .html artifact and a writable directory for evidence files'],
+ })],
+ }, { outDir });
+ if (json) {
+ console.log(JSON.stringify(failure, null, 2));
} else {
- console.error(`automated browser evidence failed: ${error.message}`);
+ console.error(formatDiagnostics(`automated browser evidence failed: ${failure.error}`, failure.diagnostics));
console.error('perceptual visual review pending');
}
process.exitCode = 1;
diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjs
index 79b05385..cffde512 100644
--- a/archify/bin/visual-check.mjs
+++ b/archify/bin/visual-check.mjs
@@ -694,7 +694,7 @@ function observationDiagnostics({ artifact, allObservations, readabilityObservat
return diagnostics;
}
-function baseReceipt({ artifactPath, artifact, outputs, chrome }) {
+function baseReceipt({ artifactPath, artifact, outputs, chrome, deliveryProvenance }) {
return {
schemaVersion: 1,
ok: false,
@@ -702,6 +702,10 @@ function baseReceipt({ artifactPath, artifact, outputs, chrome }) {
evidenceKind: 'automated-browser',
status: 'fail',
visualReview: 'pending',
+ ...(deliveryProvenance ? {
+ provenance: deliveryProvenance.status,
+ ...(deliveryProvenance.receiptId ? { deliveryReceiptId: deliveryProvenance.receiptId } : {}),
+ } : {}),
artifact: {
path: artifactPath,
sha256: sha256(artifact),
@@ -727,12 +731,52 @@ function persistReceipt(outputs, receipt) {
writeAtomic(outputs.receipt, `${JSON.stringify(receipt, null, 2)}\n`);
}
+export function persistVisualCheckFailure(artifactPath, failure, { outDir } = {}) {
+ const outputs = sidecarPaths(artifactPath, { outDir });
+ const receipt = {
+ ...failure,
+ ok: false, status: 'fail',
+ containment: { status: 'fail', viewports: [] },
+ captures: { status: 'fail', screenshots: [], contactSheet: null },
+ sidecars: {
+ ...(path.dirname(outputs.receipt) !== path.dirname(path.resolve(artifactPath))
+ ? { directory: path.dirname(outputs.receipt) } : {}),
+ receipt: path.basename(outputs.receipt),
+ contactSheet: path.basename(outputs.contactSheet),
+ },
+ };
+ const errors = [];
+ try { fs.mkdirSync(path.dirname(outputs.receipt), { recursive: true }); } catch (error) {
+ errors.push({ file: path.dirname(outputs.receipt), reason: error.message });
+ }
+ for (const file of [outputs.receipt, outputs.contactSheet, ...outputs.screenshots.map((entry) => entry.path)]) {
+ try { fs.rmSync(file, { force: true }); } catch (error) { errors.push({ file, reason: error.message }); }
+ }
+ const reportErrors = () => {
+ receipt.diagnostics = [...(failure.diagnostics || []), failureDiagnostic({
+ code: 'viewer/evidence-write', message: 'Previous visual evidence could not be fully invalidated or replaced.',
+ subject: { artifact: path.resolve(artifactPath) }, evidence: { errors },
+ supportedFixes: ['restore write access to the evidence files and rerun visual-check'],
+ })];
+ };
+ if (errors.length) reportErrors();
+ try {
+ persistReceipt(outputs, receipt);
+ } catch (error) {
+ errors.push({ file: outputs.receipt, reason: error.message });
+ reportErrors();
+ }
+ return receipt;
+}
+
export async function runVisualCheck({
artifactPath,
outDir,
chromePath,
resolveChrome = findChrome,
browserFactory = async (resolvedChrome) => new ChromeVisualBrowser(resolvedChrome),
+ deliveryProvenance,
+ verifyArtifact,
} = {}) {
if (!artifactPath) throw new Error('visual-check requires one delivered HTML artifact.');
const artifact = path.resolve(artifactPath);
@@ -740,6 +784,16 @@ export async function runVisualCheck({
const artifactBytes = fs.readFileSync(artifact);
const outputs = sidecarPaths(artifact, { outDir });
fs.mkdirSync(path.dirname(outputs.receipt), { recursive: true });
+ try {
+ verifyArtifact?.(artifactBytes);
+ } catch (error) {
+ return { exitCode: EXIT.fail, receipt: persistVisualCheckFailure(artifact, {
+ schemaVersion: 1, command: 'visual-check', evidenceKind: 'automated-browser', visualReview: 'pending',
+ artifact: { path: artifact, sha256: sha256(artifactBytes), bytes: artifactBytes.byteLength },
+ provenance: error.deliveryProvenance?.status, error: error.message,
+ diagnostics: error.archifyDiagnostics || [],
+ }, { outDir }) };
+ }
cleanupCaptureSidecars(outputs);
safeUnlink(outputs.receipt);
@@ -751,6 +805,7 @@ export async function runVisualCheck({
chrome: resolvedChrome
? { status: 'available', executable: resolvedChrome }
: { status: 'unavailable', executable: null },
+ deliveryProvenance,
});
if (!resolvedChrome) {
@@ -805,6 +860,7 @@ export async function runVisualCheck({
}
const afterBytes = fs.readFileSync(artifact);
+ verifyArtifact?.(afterBytes);
if (sha256(afterBytes) !== receipt.artifact.sha256 || afterBytes.byteLength !== receipt.artifact.bytes) {
throw new Error('The delivered artifact changed while visual-check was running.');
}
@@ -842,7 +898,6 @@ export async function runVisualCheck({
persistReceipt(outputs, receipt);
return { exitCode: receipt.ok ? EXIT.pass : EXIT.fail, receipt };
} catch (error) {
- cleanupCaptureSidecars(outputs);
receipt.status = 'fail';
receipt.ok = false;
receipt.error = error.message;
@@ -852,15 +907,15 @@ export async function runVisualCheck({
receipt.captures.status = 'fail';
receipt.captures.screenshots = [];
receipt.captures.contactSheet = null;
- receipt.diagnostics = [failureDiagnostic({
+ if (error.deliveryProvenance) receipt.provenance = error.deliveryProvenance.status;
+ receipt.diagnostics = error.archifyDiagnostics || [failureDiagnostic({
code: 'viewer/visual-check-runtime',
message: 'visual-check could not complete its Chrome inspection.',
subject: { artifact },
evidence: { reason: error.message },
supportedFixes: ['resolve the reported Chrome inspection error, then rerun visual-check'],
})];
- persistReceipt(outputs, receipt);
- return { exitCode: EXIT.fail, receipt };
+ return { exitCode: EXIT.fail, receipt: persistVisualCheckFailure(artifact, receipt, { outDir }) };
} finally {
if (browser?.close) await browser.close();
}
diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.md
index e8ffa88d..e0261ddf 100644
--- a/archify/references/delivery-contract.md
+++ b/archify/references/delivery-contract.md
@@ -11,6 +11,90 @@ their existing rule codes. Use the advertised `validate --json` or
Unexpected implementation failures retain debugging information in human
mode and remain `internal/unclassified` in machine receipts.
+Each output has three independent delivery metadata paths:
+
+- `<output-stem>.delivery.json` records the latest completed attempt.
+- `<output-stem>.delivery-pending.json` is the recovery journal for an attempt
+ in progress.
+- `<output-stem>.delivery-lock.json` serializes attempts targeting the same
+ output.
+
+`deliver` acquires the lock by exclusive `open(..., "wx")` before creating or
+replacing the recovery journal. A successful exclusive create yields an
+internal opaque ownership capability bound to that attempt. Journal creation,
+failed-provenance recording, pair commit, rollback, journal finalization, and
+lock release each verify the current capability inside the operation that
+would mutate shared state. A rejected contender does not create a journal or
+write failed provenance.
+
+An existing lock is handled without automatic recovery:
+
+| Observed lock state | Required `deliver` result |
+| --- | --- |
+| No directory entry | Attempt exclusive creation; only its success grants ownership. |
+| Valid schema-v1 lock whose PID is running, or whose death cannot be established | Exit 1 with `delivery/concurrent-attempt`; preserve every shared path. |
+| Valid schema-v1 lock whose PID is known to have exited | Exit 1 with `delivery/lock-stale`; preserve the lock, artifact, journal, and current provenance exactly. |
+| Unreadable, malformed, symlink, dangling symlink, directory, or other non-regular lock entry | Exit 1 with `delivery/lock-invalid`; preserve the entry and every other shared path. |
+| An acquired capability no longer matches the current lock or journal | Exit 1 with `delivery/ownership-lost`; stop all shared-path mutation. |
+| The matching owner cannot remove its lock | Exit 1 with `delivery/lock-release`; preserve the lock. |
+
+A `delivery/lock-stale` diagnostic identifies the absolute output and lock
+paths plus the original PID and receipt ID. Recovery is deliberately explicit
+and serial: stop all delivery attempts for that output, confirm that no active
+delivery owns it and that the reported stale entry has not been replaced,
+remove only the reported lock, then rerun `deliver`. Do not remove the artifact,
+current provenance, or pending journal as part of stale-lock recovery.
+
+The lock protocol targets Node.js 18 or later on a local filesystem with
+cooperating Archify processes. PID, receipt, and file-identity comparisons are
+defensive checks, not an atomic compare-and-swap. This contract does not claim
+distributed-lock correctness on NFS, SMB, or other network filesystems, and it
+cannot prevent an external process that ignores the protocol from replacing
+shared paths.
+
+After ownership is established, `deliver` creates the journal before rendering
+and keeps it through the recoverable HTML/sidecar pair commit. It removes the
+journal only after that commit completes. A validation, render, or pair-commit
+failure, or a process interruption, may therefore leave a journal. The journal
+is a safety barrier: `check` and `visual-check` fail closed when any directory
+entry exists at the journal or lock path, including an unreadable file,
+symlink, or dangling symlink. Run deliveries targeting the same output path
+serially; one attempt must finish or be recovered before another begins.
+
+A successful sidecar has `schemaVersion: 1`, `status: "current"`,
+`command: "deliver"`, a unique `receiptId`, the diagram `type`, an absolute
+`input` path, an absolute `output` path matching the inspected
+artifact, and specification/artifact SHA-256 and byte counts. Checkers treat a
+missing, malformed, unsupported, or inconsistent field as invalid. They also
+reject a sidecar symlink, including a dangling one. A checker binds provenance
+to the artifact bytes it actually checks and verifies that binding again before
+reporting success; a concurrent byte change fails.
+
+If a currently verified owner fails after an older HTML exists, Archify writes
+a new `status: "failed"` sidecar and leaves the journal until recovery is
+complete. An unreadable old HTML does not prevent that marker; its artifact hash
+and byte count may be absent. If the sidecar is locked or otherwise unwritable,
+Archify keeps the prior sidecar rather than deleting evidence, and the journal
+prevents checkers from trusting it. A rejected concurrent, stale, or invalid
+lock attempt does not write failed provenance. If ownership is lost, Archify
+reports `delivery/ownership-lost`, does not overwrite or remove the successor's
+artifact, provenance, journal, or lock, and does not claim recorded failed
+provenance; a failure receipt may report `provenance: "unrecorded"`. If every
+metadata path is unavailable, the same unrecorded status applies; no tool can
+preserve that fact across processes. Restore metadata-path access and complete
+a successful `deliver` before trusting the output.
+
+Artifacts with no sidecar, journal, or lock remain supported for backward
+compatibility and for the lower-level `render` command. Their checker receipts
+report `provenance: "unknown"`; use `--require-provenance` to turn that state
+into a non-zero failure when the workflow requires a successfully delivered
+artifact:
+
+```bash
+node bin/archify.mjs check <output.html> --require-provenance
+node bin/archify.mjs visual-check <output.html> --json --require-provenance
+```
+
Use `validate` after every candidate edit. CLI HTML output paths must end in `.html`, including after symbolic-link resolution.
Compare receipt paths must end in `.json`. Explicit CLI paths may be absolute or
outside the current working directory; authored `meta.output` remains confined
@@ -19,19 +103,50 @@ to that directory. A type mismatch fails before writing with
accidental file-type overwrites; they do not sandbox explicit CLI directories
or prevent replacement of an existing artifact of the expected type.
-Use final atomic delivery only after the candidate is frozen:
+Use final verified delivery only after the candidate is frozen:
```bash
node bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality showcase --json
```
-Deliver reads the specification once, writes those exact bytes to a private same-directory candidate snapshot, renders that snapshot, runs the complete artifact checker, and only replaces the target after all artifact checks pass. The JSON receipt includes SHA-256 and byte counts for both `specification` and `artifact`. Renderer, checker, receipt, or commit failure exits non-zero, removes private state, preserves the previous trusted artifact, and never invokes an opener.
-
-Run `visual-check` only after `deliver` exits zero for the current candidate. If
-delivery fails and the output path already exists, that path still names the
-previous trusted artifact; running `visual-check` then would measure and capture
-stale output, not the rejected candidate. Report the delivery diagnostics and
-repair the source before collecting new visual evidence.
+Deliver reads the specification once, writes those exact bytes to a private same-directory candidate snapshot, renders that snapshot, runs the complete artifact checker, and only replaces the target after all artifact checks pass. The JSON receipt includes SHA-256 and byte counts for both `specification` and `artifact`.
+
+The pair commit is recoverable, not a claim that two filesystem paths change
+atomically or are durable across power loss. Journal finalization is part of
+that commit: a caught failure while verifying or removing the journal rolls
+back the replaced files when possible and while ownership remains current. If
+ownership is lost, the old attempt immediately stops renaming, rolling back,
+finalizing the journal, recording failure provenance, or cleaning up shared
+paths. Any private staging or recoverable backups remain available and are
+identified by the failure diagnostic. If restoration fails for another reason,
+the failure receipt likewise identifies retained backups for recovery. A
+process interruption can leave the journal, backups, or private staging behind;
+checkers then fail closed. Follow the reported recovery evidence before rerunning
+`deliver` serially on the same output. A failed attempt exits non-zero and never invokes an opener; it never
+authorizes visual evidence collection.
+
+If exclusive creation succeeds but lock initialization fails, Archify may
+record failed provenance and remove the incomplete lock only while its
+capability still identifies that exact entry. A replacement is preserved.
+Filesystem and cleanup errors are reported separately from an active concurrent
+delivery. An active, stale, unrecognized, or otherwise preserved lock
+independently prevents checkers from accepting the prior artifact. Fix the
+reported filesystem error before retrying, and use another output path if the
+lock path contains unrelated data.
+
+Lock release is part of delivery completion. If the artifact/provenance pair
+has committed and the journal has finalized but the matching lock cannot be
+removed, `deliver` exits 1 with `delivery/lock-release`, preserves the lock,
+does not print a success receipt, and does not invoke an opener. The preserved
+lock keeps strict checkers fail-closed. Only after pair commit, journal
+finalization, and lock release all succeed may `deliver` exit zero, print its
+success receipt, or run `--open`.
+
+Run strict `check` after `deliver` exits zero. Run `visual-check` only after that
+strict check exits zero. A failed marker, recovery journal, or delivery lock
+makes both commands fail before accepting the preserved HTML; report the
+diagnostics and complete a successful recovery delivery before collecting new
+visual evidence.
The delivery interface exposes three separate claims:
@@ -65,7 +180,7 @@ After delivery, inspect the exact trusted HTML without rerendering or modifying
it:
```bash
-node bin/archify.mjs visual-check <output.html> --json
+node bin/archify.mjs visual-check <output.html> --json --require-provenance
```
The zero-dependency command uses Chrome/Chromium through the DevTools pipe. It
@@ -97,9 +212,20 @@ environmental failure through the supported command in a browser-capable
execution context when practical. Keep the packaged transport unchanged unless
the failure reproduces through that seam in a capable environment.
+A provenance failure exits before browser inspection. That early exit removes
+stale screenshots and the contact sheet, then persists a failed visual-check
+receipt bound to the attempted artifact. If any stale-evidence cleanup or
+failure-receipt write cannot complete, the diagnostic names that incomplete
+cleanup; do not present remaining sidecars as current evidence.
+
## Optional opening
-Add `--open` only when the user wants an immediate local preview. It runs after that atomic commit, uses one argument-array OS opener with a five-second bound, and records `open.status`. Keep it off for CI, unattended agents, and non-interactive environments. Failure or unsupported opening does not invalidate delivery; its status proves only whether the local opener invocation succeeded.
+Add `--open` only when the user wants an immediate local preview. It runs after
+the verified pair commit has completed, its recovery journal has been removed,
+and the delivery lock has been released successfully. It uses one argument-array
+OS opener with a five-second bound and records `open.status`. Keep it off for CI, unattended agents, and non-interactive
+environments. Failure or unsupported opening does not invalidate delivery; its
+status proves only whether the local opener invocation succeeded.
## Last-Good Live Preview
diff --git a/archify/scripts/check-render-output.mjs b/archify/scripts/check-render-output.mjs
index 9d10fdb6..5a30d460 100644
--- a/archify/scripts/check-render-output.mjs
+++ b/archify/scripts/check-render-output.mjs
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import fs from 'node:fs';
+import { createHash } from 'node:crypto';
import path from 'node:path';
import { collectAmbiguousCorridors, collectBorderRuns, collectLabelCanvasOverflow, collectLabelRouteClearance, collectRouteRhythmIssues, describeLabelCanvasOverflow, formatRect, minimumLabelRouteClearance, routeBudgetMetrics } from '../renderers/shared/geometry.mjs';
import {
@@ -19,8 +20,11 @@ if (!input || input === '-h' || input === '--help') {
const htmlPath = path.resolve(input);
let html;
+let artifact;
try {
- html = fs.readFileSync(htmlPath, 'utf8');
+ const bytes = fs.readFileSync(htmlPath);
+ html = bytes.toString('utf8');
+ artifact = { sha256: createHash('sha256').update(bytes).digest('hex'), bytes: bytes.byteLength };
} catch (err) {
console.error(JSON.stringify({
ok: false,
@@ -324,7 +328,7 @@ if (svgMatches.length === 1) {
}
const ok = checks.every((check) => check.ok) && composition.status !== 'fail';
-console.log(JSON.stringify({ ok, file: htmlPath, checks, composition }, null, 2));
+console.log(JSON.stringify({ ok, file: htmlPath, artifact, checks, composition }, null, 2));
// Let pending stdout writes drain: large receipts are asynchronous when piped.
process.exitCode = ok ? 0 : 1;
diff --git a/archify/test/authored-straight-routes.test.mjs b/archify/test/authored-straight-routes.test.mjs
index 77dadf01..37fadbde 100644
--- a/archify/test/authored-straight-routes.test.mjs
+++ b/archify/test/authored-straight-routes.test.mjs
@@ -75,8 +75,9 @@ for (const [type, { document, collection, points, d }] of Object.entries(cases))
assertPassed(run('deliver', type, input, output, '--json'));
assert.equal(fs.readFileSync(output, 'utf8'), html, 'delivery must retain the rendered geometry');
- fs.writeFileSync(output, html.replace(' data-composition-route="straight"', ''));
- const unmarked = run('check', output);
+ const unmarkedOutput = path.join(tmp, `${type}-${quality}-unmarked.html`);
+ fs.writeFileSync(unmarkedOutput, html.replace(' data-composition-route="straight"', ''));
+ const unmarked = run('check', unmarkedOutput);
assert.equal(unmarked.status, 1);
assert.equal(orthogonalCheck(unmarked).ok, false, 'same geometry without authored intent must still fail');
});
diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjs
index a6df58d7..c4f64f9a 100644
--- a/archify/test/cli.test.mjs
+++ b/archify/test/cli.test.mjs
@@ -5,7 +5,7 @@ import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { extractSvgs, parseXml } from './helpers/xml.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -25,6 +25,56 @@ function sha256(file) {
return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
}
+function deliveryPendingPath(file) {
+ return file.replace(/\.html?$/i, '.delivery-pending.json');
+}
+
+function successorDeliveryState({ receiptId, input, output, pid = process.pid }) {
+ return {
+ artifact: '<!doctype html><title>successor artifact</title>\n',
+ lock: `${JSON.stringify({ schemaVersion: 1, receiptId, pid })}\n`,
+ pending: `${JSON.stringify({
+ schemaVersion: 1,
+ command: 'deliver',
+ status: 'pending',
+ receiptId,
+ input: path.resolve(input),
+ output: path.resolve(output),
+ }, null, 2)}\n`,
+ provenance: `${JSON.stringify({
+ schemaVersion: 1,
+ receiptId,
+ status: 'failed',
+ command: 'deliver',
+ stage: 'successor',
+ input: path.resolve(input),
+ output: path.resolve(output),
+ error: 'successor owns this failure record',
+ }, null, 2)}\n`,
+ };
+}
+
+function visualEvidencePaths(file) {
+ const base = file.replace(/\.html?$/i, '.visual-check');
+ return {
+ receipt: `${base}.json`,
+ contactSheet: `${base}.html`,
+ screenshots: [
+ `${base}.1440x900.light.png`,
+ `${base}.1440x900.dark.png`,
+ `${base}.2048x1320.light.png`,
+ `${base}.2048x1320.dark.png`,
+ ],
+ };
+}
+
+function assertCheckFailureReceipt(receipt, file, codePattern) {
+ assert.equal(receipt.ok, false);
+ assert.equal(receipt.file, path.resolve(file));
+ assert.ok(Array.isArray(receipt.diagnostics));
+ assert.match(receipt.diagnostics[0].code, codePattern);
+}
+
function makeFakeOpeners(name, { exitCode = 0 } = {}) {
const bin = path.join(tmp, name);
const log = path.join(bin, 'open-log.json');
@@ -321,6 +371,22 @@ test('cli: visual-check --out-dir writes the receipt into that directory, not be
assert.equal(fs.existsSync(out.replace(/\.html$/, '.visual-check.json')), false, 'no receipt should land beside the artifact when --out-dir is set');
});
+test('cli: visual-check --out-dir redirects failed provenance evidence', () => {
+ const out = path.join(tmp, 'visual-check-outdir-provenance.html');
+ const outDir = path.join(tmp, 'visual-check-outdir-provenance-evidence');
+ fs.writeFileSync(out, '<!doctype html><html><body>not delivered</body></html>');
+
+ const result = run(['visual-check', out, '--json', '--require-provenance', '--out-dir', outDir]);
+
+ assert.equal(result.status, 1, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(receipt.status, 'fail');
+ assert.equal(receipt.sidecars.directory, outDir);
+ assert.match(receipt.diagnostics[0].code, /^delivery\/provenance-/);
+ assert.equal(fs.existsSync(path.join(outDir, 'visual-check-outdir-provenance.visual-check.json')), true);
+ assert.equal(fs.existsSync(out.replace(/\.html$/, '.visual-check.json')), false);
+});
+
test('cli: visual-check rejects --out-dir with no value', () => {
const out = path.join(tmp, 'visual-check-outdir-missing-value.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
@@ -615,14 +681,16 @@ test('cli: deliver preserves the previous artifact when the final check fails',
});
test('cli: deliver reports renderer failure as json and preserves the previous artifact', () => {
+ const validInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
const input = path.join(tmp, 'invalid-delivery.workflow.json');
- const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/agent-tool-call.workflow.json'), 'utf8'));
+ const source = JSON.parse(fs.readFileSync(validInput, 'utf8'));
source.nodes[0].unexpected = true;
fs.writeFileSync(input, JSON.stringify(source));
const out = path.join(tmp, 'renderer-failure-preserved.html');
- const trustedPriorArtifact = '<!doctype html><title>last known good</title>\n';
- fs.writeFileSync(out, trustedPriorArtifact);
+ const delivered = run(['deliver', 'workflow', validInput, out, '--json']);
+ assert.equal(delivered.status, 0, delivered.stderr);
+ const trustedPriorArtifact = fs.readFileSync(out);
const result = run(['deliver', 'workflow', input, out, '--json']);
assert.equal(result.status, 1);
@@ -630,7 +698,1971 @@ test('cli: deliver reports renderer failure as json and preserves the previous a
assert.equal(failure.ok, false);
assert.equal(failure.stage, 'render');
assert.match(failure.error, /schema validation failed/i);
- assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);
+ assert.deepEqual(fs.readFileSync(out), trustedPriorArtifact);
+ const provenance = JSON.parse(fs.readFileSync(out.replace(/\.html$/, '.delivery.json'), 'utf8'));
+ assert.equal(provenance.status, 'failed');
+ assert.equal(provenance.stage, 'render');
+ assert.equal(provenance.artifact.sha256, sha256(out));
+ assert.equal(provenance.receiptId, failure.receiptId);
+
+ const checked = run(['check', out]);
+ assert.equal(checked.status, 1);
+ const checkReceipt = JSON.parse(checked.stdout);
+ assert.equal(checkReceipt.provenance, 'failed');
+ assert.equal(checkReceipt.diagnostics[0].code, 'delivery/provenance-failed');
+
+ const visual = run(['visual-check', out, '--json']);
+ assert.equal(visual.status, 1);
+ const visualReceipt = JSON.parse(visual.stdout);
+ assert.equal(visualReceipt.provenance, 'failed');
+ assert.equal(visualReceipt.diagnostics[0].code, 'delivery/provenance-failed');
+});
+
+test('cli: a later successful delivery replaces stale provenance with an artifact-bound receipt', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-provenance-recovers.html');
+ fs.writeFileSync(out, '<!doctype html><title>old artifact</title>\n');
+ fs.writeFileSync(out.replace(/\.html$/, '.delivery.json'), JSON.stringify({ status: 'failed' }));
+
+ const delivered = run(['deliver', 'workflow', input, out, '--json']);
+ assert.equal(delivered.status, 0, delivered.stderr);
+ const receipt = JSON.parse(delivered.stdout);
+ const provenance = JSON.parse(fs.readFileSync(out.replace(/\.html$/, '.delivery.json'), 'utf8'));
+ assert.equal(provenance.status, 'current');
+ assert.match(receipt.receiptId, /^[0-9a-f-]{36}$/i);
+ assert.equal(provenance.receiptId, receipt.receiptId);
+ assert.deepEqual(provenance.specification, receipt.specification);
+ assert.deepEqual(provenance.artifact, receipt.artifact);
+ const currentCheck = run(['check', out]);
+ assert.equal(currentCheck.status, 0);
+ assert.equal(JSON.parse(currentCheck.stdout).provenance, 'current');
+ assert.equal(JSON.parse(currentCheck.stdout).deliveryReceiptId, receipt.receiptId);
+
+ fs.appendFileSync(out, '<!-- changed after delivery -->');
+ const checked = run(['check', out]);
+ assert.equal(checked.status, 1);
+ const mismatch = JSON.parse(checked.stdout);
+ assert.equal(mismatch.provenance, 'mismatch');
+ assert.equal(mismatch.diagnostics[0].code, 'delivery/provenance-mismatch');
+});
+
+test('cli: delivery pair rollback restores the previous HTML and marks it stale', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-pair-rollback.html');
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const initial = run(['deliver', 'workflow', input, out, '--json']);
+ assert.equal(initial.status, 0, initial.stderr);
+ const priorArtifact = fs.readFileSync(out);
+
+ const wrapper = path.join(tmp, 'fail-provenance-commit.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const renameSync = fs.renameSync;
+fs.renameSync = (source, target) => {
+ if (String(source).endsWith('delivery-provenance.json')) {
+ const error = new Error('injected provenance rename failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return renameSync(source, target);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(result.status, 1);
+ assert.equal(JSON.parse(result.stdout).stage, 'commit');
+ assert.match(result.stdout, /previous files were restored/);
+ assert.deepEqual(fs.readFileSync(out), priorArtifact);
+ assert.equal(JSON.parse(fs.readFileSync(provenancePath, 'utf8')).status, 'failed');
+ const checked = run(['check', out]);
+ assert.equal(checked.status, 1);
+ assert.equal(JSON.parse(checked.stdout).provenance, 'failed');
+});
+
+for (const failureMode of ['journal-read', 'journal-unlink', 'journal-unlink-and-restore']) {
+ test(`cli: delivery finalization failure preserves previous bytes or recovery backup (${failureMode})`, () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacement = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, `${failureMode}.html`);
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const previousHash = sha256(out);
+ const wrapper = path.join(tmp, `${failureMode}.mjs`);
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const renameSync = fs.renameSync;
+let pairCommitted = false;
+fs.renameSync = (source, target) => {
+ if (${JSON.stringify(failureMode)} === 'journal-unlink-and-restore' && String(source).endsWith('.previous-output')) {
+ throw Object.assign(new Error('injected restore failure'), { code: 'EACCES' });
+ }
+ const result = renameSync(source, target);
+ if (String(source).endsWith('delivery-provenance.json')) pairCommitted = true;
+ return result;
+};
+const method = ${JSON.stringify(failureMode)} === 'journal-read' ? 'readFileSync' : 'unlinkSync';
+const original = fs[method];
+fs[method] = (file, ...args) => {
+ if (pairCommitted && String(file) === ${JSON.stringify(deliveryPendingPath(out))}) {
+ throw Object.assign(new Error('injected journal finalization failure'), { code: 'EACCES' });
+ }
+ return original(file, ...args);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacement)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+ assert.equal(result.status, 1, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(receipt.stage, 'commit');
+ assert.equal(receipt.diagnostics[0].code, 'delivery/commit');
+ assert.equal(fs.existsSync(deliveryPendingPath(out)), true);
+ if (failureMode === 'journal-unlink-and-restore') {
+ const evidence = receipt.diagnostics[0].evidence;
+ assert.equal(evidence.recoveryRequired, true);
+ const backup = evidence.recoverableBackups.find((entry) => entry.label === 'HTML artifact');
+ assert.ok(backup);
+ assert.equal(sha256(backup.path), previousHash);
+ } else {
+ assert.equal(sha256(out), previousHash);
+ assert.equal(run(['check', out, '--require-provenance']).status, 1);
+ }
+ const retry = run(['deliver', 'workflow', replacement, out, '--json']);
+ assert.equal(retry.status, 0, retry.stderr || retry.stdout);
+ assert.equal(run(['check', out, '--require-provenance']).status, 0);
+ });
+}
+
+test('cli: delivery pair rollback retains recoverable backups when restoration fails', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-pair-recovery-required.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const priorArtifact = fs.readFileSync(out);
+
+ const wrapper = path.join(tmp, 'fail-delivery-rollback-restore.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const renameSync = fs.renameSync;
+fs.renameSync = (source, target) => {
+ if (String(source).endsWith('delivery-provenance.json')) {
+ const error = new Error('injected provenance rename failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ if (String(source).endsWith('.previous-output') && String(target) === ${JSON.stringify(out)}) {
+ const error = new Error('injected output restore failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return renameSync(source, target);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(result.status, 1);
+ const failure = JSON.parse(result.stdout);
+ const evidence = failure.diagnostics[0].evidence;
+ assert.equal(evidence.recoveryRequired, true);
+ assert.match(result.stderr, /Recovery required: delivery backups were retained/);
+ assert.equal(fs.existsSync(evidence.recoveryDirectory), true);
+ const outputBackup = evidence.recoverableBackups.find((entry) => entry.label === 'HTML artifact');
+ assert.ok(outputBackup);
+ assert.deepEqual(fs.readFileSync(outputBackup.path), priorArtifact);
+});
+
+test('cli: delivery pair rollback retains backups when recovery-path inspection fails', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-pair-recovery-inspection-failure.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const priorArtifact = fs.readFileSync(out);
+
+ const wrapper = path.join(tmp, 'fail-delivery-recovery-inspection.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const renameSync = fs.renameSync;
+const lstatSync = fs.lstatSync;
+let outputRestoreFailed = false;
+fs.renameSync = (source, target) => {
+ if (String(source).endsWith('delivery-provenance.json')) {
+ const error = new Error('injected provenance rename failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ if (String(source).endsWith('.previous-output') && String(target) === ${JSON.stringify(out)}) {
+ outputRestoreFailed = true;
+ const error = new Error('injected output restore failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return renameSync(source, target);
+};
+fs.lstatSync = (target, options) => {
+ if (outputRestoreFailed && String(target).endsWith('.previous-output')) {
+ const error = new Error('injected recovery inspection failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return lstatSync(target, options);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(result.status, 1);
+ const failure = JSON.parse(result.stdout);
+ const evidence = failure.diagnostics[0].evidence;
+ assert.equal(evidence.recoveryRequired, true);
+ assert.match(result.stderr, /Recovery required: delivery backups were retained/);
+ assert.equal(fs.existsSync(evidence.recoveryDirectory), true);
+ const outputBackup = evidence.recoverableBackups.find((entry) => entry.label === 'HTML artifact');
+ assert.ok(outputBackup);
+ assert.deepEqual(fs.readFileSync(outputBackup.path), priorArtifact);
+});
+
+test('cli: portable delivery lock: a process exit requires explicit stale-lock recovery before rerun', () => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'interrupted-delivery-pair.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const initialSha256 = sha256(out);
+
+ const wrapper = path.join(tmp, 'interrupt-after-html-commit.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const renameSync = fs.renameSync;
+fs.renameSync = (source, target) => {
+ const result = renameSync(source, target);
+ if (String(target) === ${JSON.stringify(out)} && String(source).includes('.archify-delivery-')) {
+ process.exit(86);
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const interrupted = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(interrupted.status, 86);
+ assert.notEqual(sha256(out), initialSha256);
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ assert.equal(fs.existsSync(pendingPath), true);
+ for (const args of [
+ ['check', out],
+ ['check', out, '--require-provenance'],
+ ]) {
+ const checked = run(args);
+ assert.equal(checked.status, 1, checked.stderr || checked.stdout);
+ assertCheckFailureReceipt(
+ JSON.parse(checked.stdout),
+ out,
+ /^delivery\/provenance-failed$/,
+ );
+ }
+
+ const artifactBeforeRecovery = fs.readFileSync(out);
+ const pendingBeforeRecovery = fs.readFileSync(pendingPath);
+ const lockBeforeRecovery = fs.readFileSync(lockPath);
+ const provenanceExisted = fs.existsSync(provenancePath);
+ const provenanceBeforeRecovery = provenanceExisted ? fs.readFileSync(provenancePath) : undefined;
+ const rejected = run(['deliver', 'workflow', replacementInput, out, '--json']);
+ assert.equal(rejected.status, 1, rejected.stderr || rejected.stdout);
+ assert.equal(JSON.parse(rejected.stdout).diagnostics[0].code, 'delivery/lock-stale');
+ assert.deepEqual(fs.readFileSync(out), artifactBeforeRecovery);
+ assert.deepEqual(fs.readFileSync(pendingPath), pendingBeforeRecovery);
+ assert.deepEqual(fs.readFileSync(lockPath), lockBeforeRecovery);
+ assert.equal(fs.existsSync(provenancePath), provenanceExisted);
+ if (provenanceExisted) assert.deepEqual(fs.readFileSync(provenancePath), provenanceBeforeRecovery);
+
+ // Manual recovery is deliberately outside the delivery protocol: after
+ // confirming the recorded PID exited, remove only the reported stale lock.
+ fs.unlinkSync(lockPath);
+ const recovered = run(['deliver', 'workflow', replacementInput, out, '--json']);
+ assert.equal(recovered.status, 0, recovered.stderr || recovered.stdout);
+ assert.equal(fs.existsSync(deliveryPendingPath(out)), false);
+ for (const args of [
+ ['check', out],
+ ['check', out, '--require-provenance'],
+ ]) {
+ const checked = run(args);
+ assert.equal(checked.status, 0, checked.stderr || checked.stdout);
+ assert.equal(JSON.parse(checked.stdout).provenance, 'current');
+ }
+});
+
+test('cli: concurrent deliveries cannot replace the active attempt ownership', async (t) => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'concurrent-delivery.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const ready = path.join(tmp, 'concurrent-delivery.ready');
+ const release = path.join(tmp, 'concurrent-delivery.release');
+ const wrapper = path.join(tmp, 'hold-active-delivery.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const writeFileSync = fs.writeFileSync;
+fs.writeFileSync = (file, value, options) => {
+ const result = writeFileSync(file, value, options);
+ if (String(file).endsWith('specification.snapshot.json')) {
+ writeFileSync(${JSON.stringify(ready)}, 'ready');
+ while (!fs.existsSync(${JSON.stringify(release)})) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const active = spawn(process.execPath, [wrapper], { cwd: skillRoot, stdio: ['ignore', 'pipe', 'pipe'] });
+ const activeExitPromise = new Promise((resolve) => {
+ active.once('close', (code, signal) => resolve({ code, signal }));
+ });
+ t.after(() => {
+ if (!fs.existsSync(release)) fs.writeFileSync(release, 'release');
+ if (active.exitCode === null && active.signalCode === null) active.kill();
+ });
+ let activeStdout = '';
+ let activeStderr = '';
+ active.stdout.on('data', (chunk) => { activeStdout += chunk; });
+ active.stderr.on('data', (chunk) => { activeStderr += chunk; });
+ const deadline = Date.now() + 5000;
+ while (!fs.existsSync(ready) && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ assert.equal(fs.existsSync(ready), true, 'active delivery did not reach the overlap point');
+
+ const rejected = run(['deliver', 'workflow', initialInput, out, '--json']);
+ assert.equal(rejected.status, 1);
+ const rejection = JSON.parse(rejected.stdout);
+ assert.equal(rejection.diagnostics[0].code, 'delivery/concurrent-attempt');
+ assert.equal('provenance' in rejection, false);
+
+ fs.writeFileSync(release, 'release');
+ const activeExit = await activeExitPromise;
+ assert.deepEqual(activeExit, { code: 0, signal: null }, activeStderr);
+ const activeReceipt = JSON.parse(activeStdout);
+ const provenance = JSON.parse(fs.readFileSync(out.replace(/\.html$/, '.delivery.json'), 'utf8'));
+ assert.equal(provenance.status, 'current');
+ assert.equal(provenance.receiptId, activeReceipt.receiptId);
+ assert.equal(fs.existsSync(out.replace(/\.html$/, '.delivery-lock.json')), false);
+});
+
+test('cli: a pre-lock failure cannot replace an active delivery attempt', async (t) => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'concurrent-pre-lock-failure.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const initialProvenance = fs.readFileSync(out.replace(/\.html$/, '.delivery.json'), 'utf8');
+ const ready = path.join(tmp, 'concurrent-pre-lock-failure.ready');
+ const release = path.join(tmp, 'concurrent-pre-lock-failure.release');
+ const activeWrapper = path.join(tmp, 'hold-active-pre-lock-delivery.mjs');
+ fs.writeFileSync(activeWrapper, `
+import fs from 'node:fs';
+const writeFileSync = fs.writeFileSync;
+fs.writeFileSync = (file, value, options) => {
+ const result = writeFileSync(file, value, options);
+ if (String(file).endsWith('specification.snapshot.json')) {
+ writeFileSync(${JSON.stringify(ready)}, 'ready');
+ while (!fs.existsSync(${JSON.stringify(release)})) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const active = spawn(process.execPath, [activeWrapper], { cwd: skillRoot, stdio: ['ignore', 'pipe', 'pipe'] });
+ const activeExitPromise = new Promise((resolve) => {
+ active.once('close', (code, signal) => resolve({ code, signal }));
+ });
+ t.after(() => {
+ if (!fs.existsSync(release)) fs.writeFileSync(release, 'release');
+ if (active.exitCode === null && active.signalCode === null) active.kill();
+ });
+ let activeStdout = '';
+ let activeStderr = '';
+ active.stdout.on('data', (chunk) => { activeStdout += chunk; });
+ active.stderr.on('data', (chunk) => { activeStderr += chunk; });
+ const deadline = Date.now() + 5000;
+ while (!fs.existsSync(ready) && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ assert.equal(fs.existsSync(ready), true, 'active delivery did not reach the overlap point');
+ const activePending = fs.readFileSync(deliveryPendingPath(out), 'utf8');
+
+ const failingWrapper = path.join(tmp, 'fail-before-delivery-lock.mjs');
+ fs.writeFileSync(failingWrapper, `
+import fs from 'node:fs';
+const mkdtempSync = fs.mkdtempSync;
+fs.mkdtempSync = (prefix, options) => {
+ if (String(prefix).endsWith('.archify-delivery-')) {
+ const error = new Error('injected candidate setup failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return mkdtempSync(prefix, options);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(initialInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const rejected = spawnSync(process.execPath, [failingWrapper], { cwd: skillRoot, encoding: 'utf8' });
+ const rejection = JSON.parse(rejected.stdout);
+ const pendingAfterRejection = fs.readFileSync(deliveryPendingPath(out), 'utf8');
+ const provenanceAfterRejection = fs.readFileSync(out.replace(/\.html$/, '.delivery.json'), 'utf8');
+
+ fs.writeFileSync(release, 'release');
+ const activeExit = await activeExitPromise;
+
+ assert.equal(rejected.status, 1);
+ assert.equal(rejection.diagnostics[0].code, 'delivery/concurrent-attempt');
+ assert.equal('provenance' in rejection, false);
+ assert.equal(pendingAfterRejection, activePending);
+ assert.equal(provenanceAfterRejection, initialProvenance);
+ assert.deepEqual(activeExit, { code: 0, signal: null }, activeStderr);
+ assert.equal(JSON.parse(activeStdout).ok, true);
+});
+
+test('cli: portable delivery lock: a stale entry is preserved when a pre-lock failure is reported', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'stale-lock-pre-lock-failure.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const artifactBefore = fs.readFileSync(out);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const provenanceBefore = fs.readFileSync(provenancePath);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const stagingBefore = fs.readdirSync(path.dirname(out))
+ .filter((entry) => entry.startsWith('.archify-delivery-')).sort();
+ const exited = spawnSync(process.execPath, ['-e', '']);
+ assert.equal(exited.status, 0);
+ const staleLock = `${JSON.stringify({
+ schemaVersion: 1,
+ receiptId: '00000000-0000-4000-8000-000000000000',
+ pid: exited.pid,
+ })}\n`;
+ fs.writeFileSync(lockPath, staleLock);
+ const wrapper = path.join(tmp, 'fail-after-stale-delivery-lock.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const mkdtempSync = fs.mkdtempSync;
+fs.mkdtempSync = (prefix, options) => {
+ if (String(prefix).endsWith('.archify-delivery-')) {
+ const error = new Error('injected candidate setup failure');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return mkdtempSync(prefix, options);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/lock-stale');
+ assert.equal('provenance' in receipt, false);
+ assert.equal(receipt.diagnostics[0].subject.output, path.resolve(out));
+ assert.equal(receipt.diagnostics[0].subject.lock, lockPath);
+ assert.equal(receipt.diagnostics[0].evidence.pid, exited.pid);
+ assert.equal(receipt.diagnostics[0].evidence.receiptId, '00000000-0000-4000-8000-000000000000');
+ assert.ok(receipt.diagnostics[0].supportedFixes.some((fix) => /confirm no delivery attempt is active/i.test(fix)));
+ assert.ok(receipt.diagnostics[0].supportedFixes.some((fix) => fix.includes(lockPath)));
+ assert.deepEqual(fs.readFileSync(out), artifactBefore);
+ assert.deepEqual(fs.readFileSync(provenancePath), provenanceBefore);
+ assert.equal(fs.existsSync(deliveryPendingPath(out)), false);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), staleLock);
+ assert.deepEqual(
+ fs.readdirSync(path.dirname(out)).filter((entry) => entry.startsWith('.archify-delivery-')).sort(),
+ stagingBefore,
+ );
+});
+
+test('cli: portable delivery lock: simultaneous stale-lock contenders both fail closed', async (t) => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'simultaneous-stale-lock-contenders.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const artifactBefore = fs.readFileSync(out);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const provenanceBefore = fs.readFileSync(provenancePath);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const stagingBefore = fs.readdirSync(path.dirname(out))
+ .filter((entry) => entry.startsWith('.archify-delivery-')).sort();
+ const exited = spawnSync(process.execPath, ['-e', '']);
+ assert.equal(exited.status, 0);
+ const staleLock = `${JSON.stringify({
+ schemaVersion: 1,
+ receiptId: '00000000-0000-4000-8000-000000000000',
+ pid: exited.pid,
+ })}\n`;
+ fs.writeFileSync(lockPath, staleLock);
+ const release = path.join(tmp, 'release-stale-lock-contenders');
+
+ const contenders = ['a', 'b'].map((label) => {
+ const ready = path.join(tmp, `stale-lock-contender-${label}.ready`);
+ const wrapper = path.join(tmp, `stale-lock-contender-${label}.mjs`);
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const processKill = process.kill.bind(process);
+process.kill = (pid, signal) => {
+ if (pid === ${JSON.stringify(exited.pid)} && signal === 0) {
+ fs.writeFileSync(${JSON.stringify(ready)}, 'ready');
+ while (!fs.existsSync(${JSON.stringify(release)})) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
+ }
+ throw Object.assign(new Error('No such process'), { code: 'ESRCH' });
+ }
+ return processKill(pid, signal);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const child = spawn(process.execPath, [wrapper], { cwd: skillRoot, stdio: ['ignore', 'pipe', 'pipe'] });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
+ const exitedPromise = new Promise((resolve) => {
+ child.once('close', (code, signal) => resolve({ code, signal, stdout, stderr }));
+ });
+ return { child, ready, exitedPromise };
+ });
+ t.after(() => {
+ if (!fs.existsSync(release)) fs.writeFileSync(release, 'release');
+ for (const { child } of contenders) {
+ if (child.exitCode === null && child.signalCode === null) child.kill();
+ }
+ });
+
+ const deadline = Date.now() + 5000;
+ while (contenders.some(({ ready }) => !fs.existsSync(ready)) && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ assert.equal(contenders.every(({ ready }) => fs.existsSync(ready)), true, 'both contenders did not inspect the stale lock');
+ fs.writeFileSync(release, 'release');
+ const results = await Promise.all(contenders.map(({ exitedPromise }) => exitedPromise));
+
+ for (const result of results) {
+ assert.deepEqual({ code: result.code, signal: result.signal }, { code: 1, signal: null }, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/lock-stale');
+ assert.equal('provenance' in receipt, false);
+ }
+ assert.deepEqual(fs.readFileSync(out), artifactBefore);
+ assert.deepEqual(fs.readFileSync(provenancePath), provenanceBefore);
+ assert.equal(fs.existsSync(deliveryPendingPath(out)), false);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), staleLock);
+ assert.deepEqual(
+ fs.readdirSync(path.dirname(out)).filter((entry) => entry.startsWith('.archify-delivery-')).sort(),
+ stagingBefore,
+ );
+});
+
+test('cli: portable delivery lock: lost ownership prevents failure provenance writes', () => {
+ const validInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const invalidInput = path.join(tmp, 'lost-delivery-ownership.workflow.json');
+ const invalid = JSON.parse(fs.readFileSync(validInput, 'utf8'));
+ invalid.nodes[0].unexpected = true;
+ fs.writeFileSync(invalidInput, JSON.stringify(invalid));
+ const out = path.join(tmp, 'lost-delivery-ownership.html');
+ assert.equal(run(['deliver', 'workflow', validInput, out, '--json']).status, 0);
+ const artifactBefore = fs.readFileSync(out);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const provenanceBefore = fs.readFileSync(provenancePath);
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successorReceiptId = '11111111-1111-4111-8111-111111111111';
+ const successorLock = `${JSON.stringify({
+ schemaVersion: 1,
+ receiptId: successorReceiptId,
+ pid: process.pid,
+ })}\n`;
+ const successorPending = `${JSON.stringify({
+ schemaVersion: 1,
+ command: 'deliver',
+ status: 'pending',
+ receiptId: successorReceiptId,
+ input: path.resolve(validInput),
+ output: path.resolve(out),
+ }, null, 2)}\n`;
+ const successorProvenance = `${JSON.stringify({
+ schemaVersion: 1,
+ receiptId: successorReceiptId,
+ status: 'failed',
+ command: 'deliver',
+ stage: 'successor',
+ input: path.resolve(validInput),
+ output: path.resolve(out),
+ error: 'successor owns this failure record',
+ }, null, 2)}\n`;
+ const wrapper = path.join(tmp, 'lose-delivery-ownership.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const renameSync = fs.renameSync;
+const writeFileSync = fs.writeFileSync;
+let replaced = false;
+fs.renameSync = (source, target) => {
+ const result = renameSync(source, target);
+ if (!replaced && String(target) === ${JSON.stringify(pendingPath)} && String(source).includes('.archify-provenance-')) {
+ replaced = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.lost-owner`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successorLock)});
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successorPending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successorProvenance)});
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(invalidInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.ok, false);
+ assert.ok(receipt.diagnostics.some((entry) => entry.code === 'delivery/ownership-lost'));
+ assert.ok(!('provenance' in receipt) || receipt.provenance === 'unrecorded');
+ assert.deepEqual(fs.readFileSync(out), artifactBefore);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successorProvenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successorLock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successorPending);
+});
+
+test('cli: portable delivery lock: failure provenance ownership loss reports retained recovery state', () => {
+ const validInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const invalidInput = path.join(tmp, 'failure-provenance-ownership-loss.workflow.json');
+ const invalid = JSON.parse(fs.readFileSync(validInput, 'utf8'));
+ invalid.nodes[0].unexpected = true;
+ fs.writeFileSync(invalidInput, JSON.stringify(invalid));
+ const out = path.join(tmp, 'failure-provenance-ownership-loss.html');
+ assert.equal(run(['deliver', 'workflow', validInput, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '15151515-1515-4515-8515-151515151515',
+ input: validInput,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'failure-provenance-ownership-loss.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import path from 'node:path';
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+let successorInstalled = false;
+fs.writeFileSync = (file, ...args) => {
+ const result = writeFileSync(file, ...args);
+ if (!successorInstalled
+ && path.basename(String(file)) === ${JSON.stringify(path.basename(provenancePath))}
+ && path.basename(path.dirname(String(file))).startsWith('.archify-provenance-')) {
+ successorInstalled = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(invalidInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.ok(!('provenance' in receipt) || receipt.provenance === 'unrecorded');
+ assert.equal(receipt.diagnostics[0].evidence.recoveryRequired, true);
+ assert.equal(fs.existsSync(receipt.diagnostics[0].evidence.recoveryDirectory), true);
+ assert.deepEqual(receipt.diagnostics[0].evidence.recoverableBackups, []);
+ assert.match(failed.stderr, /Recovery required: delivery backups were retained/);
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: journal creation cannot overwrite a successor', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'lost-ownership-before-journal-rename.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '12121212-1212-4212-8212-121212121212',
+ input,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'lose-ownership-before-journal-rename.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import path from 'node:path';
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+let replaced = false;
+fs.writeFileSync = (file, ...args) => {
+ const result = writeFileSync(file, ...args);
+ if (!replaced && path.basename(String(file)) === ${JSON.stringify(path.basename(pendingPath))}
+ && path.basename(path.dirname(String(file))).startsWith('.archify-provenance-')) {
+ replaced = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal('provenance' in receipt, false);
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: an unverifiable new journal loses ownership', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'unverifiable-new-journal.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const artifactBefore = fs.readFileSync(out);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const provenanceBefore = fs.readFileSync(provenancePath);
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const wrapper = path.join(tmp, 'unverifiable-new-journal.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const lstatSync = fs.lstatSync;
+let injected = false;
+fs.lstatSync = (file, ...args) => {
+ if (!injected && String(file) === ${JSON.stringify(pendingPath)} && fs.existsSync(file)) {
+ injected = true;
+ throw Object.assign(new Error('injected journal identity failure'), { code: 'EACCES' });
+ }
+ return lstatSync(file, ...args);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal(receipt.diagnostics[0].evidence.systemCode, 'EACCES');
+ assert.equal('provenance' in receipt, false);
+ assert.deepEqual(fs.readFileSync(out), artifactBefore);
+ assert.deepEqual(fs.readFileSync(provenancePath), provenanceBefore);
+ assert.equal(fs.existsSync(pendingPath), true);
+ assert.equal(fs.existsSync(lockPath), true);
+});
+
+test('cli: portable delivery lock: release loss cannot claim failed provenance', () => {
+ const validInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const invalidInput = path.join(tmp, 'release-loss-after-failure.workflow.json');
+ const invalid = JSON.parse(fs.readFileSync(validInput, 'utf8'));
+ invalid.nodes[0].unexpected = true;
+ fs.writeFileSync(invalidInput, JSON.stringify(invalid));
+ const out = path.join(tmp, 'release-loss-after-failure.html');
+ assert.equal(run(['deliver', 'workflow', validInput, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '13131313-1313-4313-8313-131313131313',
+ input: validInput,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'lose-ownership-after-failure-provenance.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+let replaced = false;
+fs.renameSync = (source, target) => {
+ const result = renameSync(source, target);
+ if (!replaced && String(target) === ${JSON.stringify(provenancePath)}
+ && String(source).includes('.archify-provenance-')) {
+ replaced = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(invalidInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.ok(!('provenance' in receipt) || receipt.provenance === 'unrecorded');
+ assert.equal(receipt.diagnostics[0].evidence.recoveryRequired, true);
+ assert.equal(fs.existsSync(receipt.diagnostics[0].evidence.recoveryDirectory), true);
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: commit entry preserves a successor owner', () => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'lost-ownership-before-commit.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '22222222-2222-4222-8222-222222222222',
+ input: replacementInput,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'lose-ownership-before-commit.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import path from 'node:path';
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+let replaced = false;
+fs.writeFileSync = (file, ...args) => {
+ const result = writeFileSync(file, ...args);
+ if (!replaced && path.basename(String(file)) === 'delivery-provenance.json'
+ && path.basename(path.dirname(String(file))).startsWith('.archify-delivery-')) {
+ replaced = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal('provenance' in receipt, false);
+ assert.equal(receipt.diagnostics[0].evidence.recoveryRequired, true);
+ assert.equal(fs.existsSync(receipt.diagnostics[0].evidence.recoveryDirectory), true);
+ assert.match(failed.stderr, /Recovery required: delivery backups were retained/);
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: rollback stops after ownership is lost', () => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'lost-ownership-before-rollback.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const priorArtifact = fs.readFileSync(out);
+ const priorProvenance = fs.readFileSync(provenancePath);
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '33333333-3333-4333-8333-333333333333',
+ input: replacementInput,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'lose-ownership-before-rollback.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import path from 'node:path';
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+let replaced = false;
+fs.renameSync = (source, target) => {
+ if (!replaced && path.basename(String(source)) === 'delivery-provenance.json'
+ && path.basename(path.dirname(String(source))).startsWith('.archify-delivery-')) {
+ replaced = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ throw Object.assign(new Error('injected provenance commit failure'), { code: 'EACCES' });
+ }
+ return renameSync(source, target);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal(receipt.diagnostics[0].evidence.recoveryRequired, true);
+ assert.equal(receipt.diagnostics[0].evidence.commitError.reason, 'injected provenance commit failure');
+ assert.equal(receipt.diagnostics[0].evidence.commitError.systemCode, 'EACCES');
+ assert.ok(receipt.diagnostics[0].evidence.recoverableBackups.length >= 1);
+ const outputBackup = receipt.diagnostics[0].evidence.recoverableBackups
+ .find((entry) => entry.label === 'HTML artifact');
+ const provenanceBackup = receipt.diagnostics[0].evidence.recoverableBackups
+ .find((entry) => entry.label === 'delivery provenance');
+ assert.deepEqual(fs.readFileSync(outputBackup.path), priorArtifact);
+ assert.deepEqual(fs.readFileSync(provenanceBackup.path), priorProvenance);
+ assert.match(failed.stderr, /Recovery required: delivery backups were retained/);
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: finalization preserves a successor owner', () => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'lost-ownership-before-finalization.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const priorArtifact = fs.readFileSync(out);
+ const priorProvenance = fs.readFileSync(provenancePath);
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '44444444-4444-4444-8444-444444444444',
+ input: replacementInput,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'lose-ownership-before-finalization.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+import path from 'node:path';
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+let replaced = false;
+fs.renameSync = (source, target) => {
+ const result = renameSync(source, target);
+ if (!replaced && path.basename(String(source)) === 'delivery-provenance.json'
+ && path.basename(path.dirname(String(source))).startsWith('.archify-delivery-')) {
+ replaced = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal(receipt.diagnostics[0].evidence.recoveryRequired, true);
+ const outputBackup = receipt.diagnostics[0].evidence.recoverableBackups
+ .find((entry) => entry.label === 'HTML artifact');
+ const provenanceBackup = receipt.diagnostics[0].evidence.recoverableBackups
+ .find((entry) => entry.label === 'delivery provenance');
+ assert.deepEqual(fs.readFileSync(outputBackup.path), priorArtifact);
+ assert.deepEqual(fs.readFileSync(provenanceBackup.path), priorProvenance);
+ assert.match(failed.stderr, /Recovery required: delivery backups were retained/);
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: release preserves a successor owner', () => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'lost-ownership-before-release.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const priorArtifact = fs.readFileSync(out);
+ const priorProvenance = fs.readFileSync(provenancePath);
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '55555555-5555-4555-8555-555555555555',
+ input: replacementInput,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'lose-ownership-before-release.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+const unlinkSync = fs.unlinkSync;
+const lstatSync = fs.lstatSync;
+let journalFinalized = false;
+let replaced = false;
+fs.unlinkSync = (file, ...args) => {
+ const result = unlinkSync(file, ...args);
+ if (String(file) === ${JSON.stringify(pendingPath)}) journalFinalized = true;
+ return result;
+};
+fs.lstatSync = (file, ...args) => {
+ try {
+ return lstatSync(file, ...args);
+ } catch (error) {
+ if (!replaced && journalFinalized && String(file) === ${JSON.stringify(pendingPath)} && error.code === 'ENOENT') {
+ replaced = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ }
+ throw error;
+ }
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.stage, 'release');
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal(receipt.diagnostics[0].evidence.recoveryRequired, true);
+ const outputBackup = receipt.diagnostics[0].evidence.recoverableBackups
+ .find((entry) => entry.label === 'HTML artifact');
+ const provenanceBackup = receipt.diagnostics[0].evidence.recoverableBackups
+ .find((entry) => entry.label === 'delivery provenance');
+ assert.deepEqual(fs.readFileSync(outputBackup.path), priorArtifact);
+ assert.deepEqual(fs.readFileSync(provenanceBackup.path), priorProvenance);
+ assert.match(failed.stderr, /Recovery required: delivery backups were retained/);
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: release rejects a recreated journal', () => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'recreated-journal-before-release.html');
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '66666666-6666-4666-8666-666666666666',
+ input: replacementInput,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'recreate-journal-before-release.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const writeFileSync = fs.writeFileSync;
+const unlinkSync = fs.unlinkSync;
+const lstatSync = fs.lstatSync;
+let journalFinalized = false;
+let postFinalizeLockChecks = 0;
+let journalRecreated = false;
+fs.unlinkSync = (file, ...args) => {
+ const result = unlinkSync(file, ...args);
+ if (String(file) === ${JSON.stringify(pendingPath)}) journalFinalized = true;
+ return result;
+};
+fs.lstatSync = (file, ...args) => {
+ if (journalFinalized && String(file) === ${JSON.stringify(lockPath)}) {
+ postFinalizeLockChecks += 1;
+ if (postFinalizeLockChecks === 2) {
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)}, { flag: 'wx' });
+ journalRecreated = true;
+ }
+ }
+ if (journalRecreated && String(file).includes('.previous-')) {
+ throw Object.assign(new Error('injected recovery backup inspection failure'), { code: 'EACCES' });
+ }
+ return lstatSync(file, ...args);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(replacementInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.stage, 'release');
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal(receipt.diagnostics[0].evidence.recoveryRequired, true);
+ assert.ok(receipt.diagnostics[0].evidence.recoverableBackups.length >= 1);
+ assert.equal(fs.existsSync(receipt.diagnostics[0].evidence.recoveryDirectory), true);
+ assert.equal(fs.existsSync(receipt.diagnostics[0].evidence.recoverableBackups[0].path), true);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+ assert.equal(fs.existsSync(lockPath), true);
+ const strict = run(['check', out, '--require-provenance']);
+ assert.equal(strict.status, 1, strict.stderr || strict.stdout);
+ assert.equal(JSON.parse(strict.stdout).diagnostics[0].code, 'delivery/provenance-failed');
+});
+
+test('cli: portable delivery lock: release failure cannot claim delivery success', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-lock-release-failure.html');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const wrapper = path.join(tmp, 'delivery-lock-release-failure.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const unlinkSync = fs.unlinkSync;
+let journalFinalized = false;
+fs.unlinkSync = (file, ...args) => {
+ if (String(file) === ${JSON.stringify(lockPath)} && journalFinalized) {
+ throw Object.assign(new Error('injected lock release failure'), { code: 'EACCES' });
+ }
+ const result = unlinkSync(file, ...args);
+ if (String(file) === ${JSON.stringify(pendingPath)}) journalFinalized = true;
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.ok, false);
+ assert.equal(receipt.stage, 'release');
+ assert.equal(receipt.diagnostics[0].code, 'delivery/lock-release');
+ assert.equal(fs.existsSync(pendingPath), false);
+ const lock = JSON.parse(fs.readFileSync(lockPath, 'utf8'));
+ const provenance = JSON.parse(fs.readFileSync(provenancePath, 'utf8'));
+ assert.equal(provenance.status, 'current');
+ assert.equal(lock.receiptId, provenance.receiptId);
+ const strict = run(['check', out, '--require-provenance']);
+ assert.equal(strict.status, 1, strict.stderr || strict.stdout);
+ assert.equal(JSON.parse(strict.stdout).diagnostics[0].code, 'delivery/provenance-locked');
+});
+
+test('cli: portable delivery lock: failure-path release errors override the renderer status', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-failure-lock-release.html');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const previousHash = sha256(out);
+ const wrapper = path.join(tmp, 'delivery-failure-lock-release.mjs');
+ fs.writeFileSync(wrapper, `
+import childProcess from 'node:child_process';
+import fs from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
+const spawnSync = childProcess.spawnSync;
+let rendererFailed = false;
+childProcess.spawnSync = (executable, args, options) => {
+ if (!rendererFailed && String(args?.[0]).includes('render-workflow.mjs')) {
+ rendererFailed = true;
+ return { status: 7, stdout: '', stderr: '' };
+ }
+ return spawnSync(executable, args, options);
+};
+syncBuiltinESMExports();
+const unlinkSync = fs.unlinkSync;
+fs.unlinkSync = (file, ...args) => {
+ if (String(file) === ${JSON.stringify(lockPath)}) {
+ throw Object.assign(new Error('injected failure-path lock release error'), { code: 'EACCES' });
+ }
+ return unlinkSync(file, ...args);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.ok, false);
+ assert.equal(receipt.stage, 'render');
+ assert.equal(receipt.provenance, 'failed');
+ assert.equal(receipt.diagnostics[0].code, 'delivery/lock-release');
+ assert.equal(receipt.diagnostics[1].code, 'internal/unclassified');
+ assert.doesNotMatch(receipt.diagnostics[0].message, /committed/i);
+ assert.equal(fs.existsSync(lockPath), true);
+ assert.equal(fs.existsSync(pendingPath), true);
+ assert.equal(JSON.parse(fs.readFileSync(provenancePath, 'utf8')).status, 'failed');
+ assert.equal(sha256(out), previousHash);
+});
+
+test('cli: portable delivery lock: final cleanup preserves an unexpected primary failure when release also fails', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-unexpected-release-failure.html');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const wrapper = path.join(tmp, 'delivery-unexpected-release-failure.mjs');
+ const stagingBefore = fs.readdirSync(path.dirname(out))
+ .filter((entry) => entry.startsWith('.archify-delivery-'))
+ .sort();
+ fs.writeFileSync(wrapper, `
+import childProcess from 'node:child_process';
+import fs from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
+const spawnSync = childProcess.spawnSync;
+childProcess.spawnSync = (executable, args, options) => {
+ if (String(args?.[0]).includes('render-workflow.mjs')) {
+ throw new Error('injected unexpected renderer dispatch failure');
+ }
+ return spawnSync(executable, args, options);
+};
+syncBuiltinESMExports();
+const unlinkSync = fs.unlinkSync;
+fs.unlinkSync = (file, ...args) => {
+ if (String(file) === ${JSON.stringify(lockPath)}) {
+ throw Object.assign(new Error('injected final lock release failure'), { code: 'EACCES' });
+ }
+ return unlinkSync(file, ...args);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ assert.match(failed.stderr, /injected unexpected renderer dispatch failure/);
+ assert.match(failed.stderr, /\[delivery\/lock-release\]/);
+ assert.match(failed.stderr, /injected final lock release failure/);
+ assert.equal(fs.existsSync(lockPath), true);
+ assert.equal(fs.existsSync(pendingPath), true);
+ assert.deepEqual(
+ fs.readdirSync(path.dirname(out))
+ .filter((entry) => entry.startsWith('.archify-delivery-'))
+ .sort(),
+ stagingBefore,
+ );
+});
+
+test('cli: portable delivery lock: final cleanup preserves successor state after unexpected ownership loss', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-unexpected-ownership-loss.html');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const successor = successorDeliveryState({
+ receiptId: '16161616-1616-4616-8616-161616161616',
+ input,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'delivery-unexpected-ownership-loss.mjs');
+ const stagingBefore = new Set(fs.readdirSync(path.dirname(out))
+ .filter((entry) => entry.startsWith('.archify-delivery-')));
+ fs.writeFileSync(wrapper, `
+import childProcess from 'node:child_process';
+import fs from 'node:fs';
+import { syncBuiltinESMExports } from 'node:module';
+const spawnSync = childProcess.spawnSync;
+childProcess.spawnSync = (executable, args, options) => {
+ if (String(args?.[0]).includes('render-workflow.mjs')) {
+ for (const [target, contents] of ${JSON.stringify([
+ [lockPath, successor.lock],
+ [pendingPath, successor.pending],
+ [provenancePath, successor.provenance],
+ ])}) {
+ if (fs.existsSync(target)) fs.renameSync(target, \`${'${target}'}.owner-a\`);
+ fs.writeFileSync(target, contents, { flag: 'wx' });
+ }
+ throw new Error('injected unexpected failure after successor takeover');
+ }
+ return spawnSync(executable, args, options);
+};
+syncBuiltinESMExports();
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ assert.match(failed.stderr, /injected unexpected failure after successor takeover/);
+ assert.match(failed.stderr, /\[delivery\/ownership-lost\]/);
+ assert.match(failed.stderr, /Recovery required:/);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ const recoveryDirectories = fs.readdirSync(path.dirname(out))
+ .filter((entry) => entry.startsWith('.archify-delivery-') && !stagingBefore.has(entry));
+ assert.equal(recoveryDirectories.length, 1);
+ assert.equal(fs.existsSync(path.join(path.dirname(out), recoveryDirectories[0], 'specification.snapshot.json')), true);
+});
+
+test('cli: lock release failure does not invoke the requested opener', (t) => {
+ if (process.platform === 'win32') {
+ t.skip('fake open and xdg-open executables cover POSIX opener dispatch');
+ return;
+ }
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'delivery-lock-release-no-open.html');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const fake = makeFakeOpeners('delivery-lock-release-no-open');
+ const wrapper = path.join(tmp, 'delivery-lock-release-no-open.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const unlinkSync = fs.unlinkSync;
+let journalFinalized = false;
+fs.unlinkSync = (file, ...args) => {
+ if (String(file) === ${JSON.stringify(lockPath)} && journalFinalized) {
+ throw Object.assign(new Error('injected lock release failure'), { code: 'EACCES' });
+ }
+ const result = unlinkSync(file, ...args);
+ if (String(file) === ${JSON.stringify(pendingPath)}) journalFinalized = true;
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json', '--open'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], {
+ cwd: skillRoot,
+ encoding: 'utf8',
+ env: fake.env,
+ });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ assert.equal(JSON.parse(failed.stdout).diagnostics[0].code, 'delivery/lock-release');
+ assert.equal(fs.existsSync(fake.log), false);
+});
+
+for (const failureMode of ['empty-write', 'partial-write', 'close', 'replacement', 'zero-identity-replacement', 'cleanup-failure']) {
+ test(`cli: portable delivery lock: failed lock initialization is cleaned up and delivery can retry (${failureMode})`, () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, `lock-init-${failureMode}.html`);
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const previousHash = sha256(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const wrapper = path.join(tmp, `lock-init-${failureMode}.mjs`);
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const openSync = fs.openSync;
+let lockDescriptor;
+fs.openSync = (file, ...args) => {
+ const descriptor = openSync(file, ...args);
+ if (String(file) === ${JSON.stringify(lockPath)}) lockDescriptor = descriptor;
+ return descriptor;
+};
+const mode = ${JSON.stringify(failureMode)};
+const method = mode === 'close' ? 'closeSync' : 'writeFileSync';
+const original = fs[method];
+if (mode === 'zero-identity-replacement') {
+ const fstatSync = fs.fstatSync;
+ const lstatSync = fs.lstatSync;
+ fs.fstatSync = (descriptor, ...args) => {
+ const entry = fstatSync(descriptor, ...args);
+ return descriptor === lockDescriptor ? { ...entry, ino: 0 } : entry;
+ };
+ fs.lstatSync = (file, ...args) => {
+ const entry = lstatSync(file, ...args);
+ return String(file) === ${JSON.stringify(lockPath)}
+ ? { ...entry, ino: 0, isFile: () => entry.isFile() }
+ : entry;
+ };
+}
+if (mode === 'cleanup-failure') {
+ const unlinkSync = fs.unlinkSync;
+ fs.unlinkSync = (file, ...args) => {
+ if (String(file) === ${JSON.stringify(lockPath)}) throw Object.assign(new Error('injected lock cleanup failure'), { code: 'EACCES' });
+ return unlinkSync(file, ...args);
+ };
+}
+let injected = false;
+fs[method] = (descriptor, ...args) => {
+ if (descriptor === lockDescriptor && !injected) {
+ injected = true;
+ if (mode === 'partial-write') original(descriptor, '{');
+ if (mode === 'replacement' || mode === 'zero-identity-replacement') {
+ fs.renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owned`)});
+ original(${JSON.stringify(lockPath)}, 'unrelated replacement');
+ }
+ throw Object.assign(new Error('injected lock initialization failure'), { code: 'ENOSPC' });
+ }
+ return original(descriptor, ...args);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+ assert.equal(result.status, 1, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ const replacementMode = failureMode === 'replacement' || failureMode === 'zero-identity-replacement';
+ const expectedDiagnostic = replacementMode
+ ? 'delivery/ownership-lost'
+ : failureMode === 'cleanup-failure'
+ ? 'delivery/lock-release'
+ : 'delivery/lock-acquire';
+ assert.equal(receipt.diagnostics[0].code, expectedDiagnostic);
+ if (replacementMode || failureMode === 'cleanup-failure') {
+ assert.equal(receipt.diagnostics[0].evidence.initializationSystemCode, 'ENOSPC');
+ } else {
+ assert.equal(receipt.diagnostics[0].evidence.systemCode, 'ENOSPC');
+ }
+ assert.equal(sha256(out), previousHash);
+ const expectedProvenanceCode = replacementMode
+ ? /^delivery\/provenance-locked$/
+ : /^delivery\/provenance-failed$/;
+ for (const args of [
+ ['check', out],
+ ['check', out, '--require-provenance'],
+ ]) {
+ const checked = run(args);
+ assert.equal(checked.status, 1, checked.stderr || checked.stdout);
+ assertCheckFailureReceipt(JSON.parse(checked.stdout), out, expectedProvenanceCode);
+ }
+ if (replacementMode) {
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), 'unrelated replacement');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 1);
+ return;
+ }
+ if (failureMode === 'cleanup-failure') {
+ assert.equal(fs.existsSync(lockPath), true);
+ assert.equal(receipt.provenance, 'failed');
+ assert.equal(receipt.diagnostics[0].evidence.systemCode, 'EACCES');
+ assert.match(receipt.diagnostics[0].evidence.reason, /injected lock cleanup failure/);
+ assert.doesNotMatch(receipt.diagnostics[0].message, /committed/i);
+ return;
+ }
+ assert.equal(fs.existsSync(lockPath), false);
+ const retry = run(['deliver', 'workflow', input, out, '--json']);
+ assert.equal(retry.status, 0, retry.stderr || retry.stdout);
+ assert.equal(run(['check', out, '--require-provenance']).status, 0);
+ });
+}
+
+test('cli: portable delivery lock: initialization ownership loss cannot claim failed provenance', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'lock-init-ownership-loss.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const pendingPath = deliveryPendingPath(out);
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ const successor = successorDeliveryState({
+ receiptId: '14141414-1414-4414-8414-141414141414',
+ input,
+ output: out,
+ });
+ const wrapper = path.join(tmp, 'lock-init-ownership-loss.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const openSync = fs.openSync;
+const writeFileSync = fs.writeFileSync;
+const renameSync = fs.renameSync;
+let lockDescriptor;
+let initializationFailed = false;
+let successorInstalled = false;
+fs.openSync = (file, ...args) => {
+ const descriptor = openSync(file, ...args);
+ if (String(file) === ${JSON.stringify(lockPath)}) lockDescriptor = descriptor;
+ return descriptor;
+};
+fs.writeFileSync = (file, ...args) => {
+ if (file === lockDescriptor && !initializationFailed) {
+ initializationFailed = true;
+ throw Object.assign(new Error('injected lock initialization failure'), { code: 'ENOSPC' });
+ }
+ return writeFileSync(file, ...args);
+};
+fs.renameSync = (source, target) => {
+ const result = renameSync(source, target);
+ if (!successorInstalled && initializationFailed
+ && String(target) === ${JSON.stringify(provenancePath)}
+ && String(source).includes('.archify-provenance-')) {
+ successorInstalled = true;
+ renameSync(${JSON.stringify(lockPath)}, ${JSON.stringify(`${lockPath}.owner-a`)});
+ writeFileSync(${JSON.stringify(lockPath)}, ${JSON.stringify(successor.lock)}, { flag: 'wx' });
+ writeFileSync(${JSON.stringify(pendingPath)}, ${JSON.stringify(successor.pending)});
+ writeFileSync(${JSON.stringify(provenancePath)}, ${JSON.stringify(successor.provenance)});
+ writeFileSync(${JSON.stringify(out)}, ${JSON.stringify(successor.artifact)});
+ }
+ return result;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+
+ const failed = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.ok(!('provenance' in receipt) || receipt.provenance === 'unrecorded');
+ assert.equal(receipt.diagnostics[0].evidence.initializationSystemCode, 'ENOSPC');
+ assert.equal(fs.readFileSync(out, 'utf8'), successor.artifact);
+ assert.equal(fs.readFileSync(provenancePath, 'utf8'), successor.provenance);
+ assert.equal(fs.readFileSync(lockPath, 'utf8'), successor.lock);
+ assert.equal(fs.readFileSync(pendingPath, 'utf8'), successor.pending);
+});
+
+test('cli: portable delivery lock: a raw acquisition error does not obscure the input diagnosis', () => {
+ const input = path.join(tmp, 'invalid-input-before-lock.json');
+ const out = path.join(tmp, 'missing-output-parent', 'invalid-input.html');
+ fs.writeFileSync(input, '{ invalid json');
+
+ const failed = run(['deliver', 'workflow', input, out, '--json']);
+
+ assert.equal(failed.status, 1, failed.stderr || failed.stdout);
+ const receipt = JSON.parse(failed.stdout);
+ assert.equal(receipt.stage, 'input');
+ assert.equal(receipt.diagnostics[0].code, 'input/json-parse');
+ assert.equal(receipt.diagnostics[1].code, 'delivery/lock-acquire');
+ assert.equal(receipt.diagnostics[1].evidence.systemCode, 'ENOENT');
+ assert.equal(fs.existsSync(out), false);
+});
+
+test('cli: delivery lock cannot replace its input specification', () => {
+ const input = path.join(tmp, 'lock-input-alias.delivery-lock.json');
+ const source = fs.readFileSync(path.join(skillRoot, 'examples/agent-tool-call.workflow.json'));
+ fs.writeFileSync(input, source);
+ const out = input.replace(/\.delivery-lock\.json$/, '.html');
+ const result = run(['deliver', 'workflow', input, out, '--json']);
+ assert.equal(result.status, 1);
+ assert.deepEqual(fs.readFileSync(input), source);
+ assert.equal(fs.existsSync(out), false);
+ assert.equal('provenance' in JSON.parse(result.stdout), false);
+ assert.equal(JSON.parse(result.stdout).diagnostics[0].code, 'delivery/lock-path-conflict');
+});
+
+test('cli: portable delivery lock: a symlink lock is invalid even when it targets the input', (t) => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'symlink-lock-to-input.html');
+ const lockPath = out.replace(/\.html$/, '.delivery-lock.json');
+ try {
+ fs.symlinkSync(input, lockPath, 'file');
+ } catch (error) {
+ if (error.code === 'EPERM' || error.code === 'EACCES') {
+ t.skip('symlink creation requires permission');
+ return;
+ }
+ throw error;
+ }
+
+ const result = run(['deliver', 'workflow', input, out, '--json']);
+
+ assert.equal(result.status, 1, result.stderr || result.stdout);
+ assert.equal(JSON.parse(result.stdout).diagnostics[0].code, 'delivery/lock-invalid');
+ assert.equal(fs.lstatSync(lockPath).isSymbolicLink(), true);
+ assert.equal(fs.readlinkSync(lockPath), input);
+ assert.equal(fs.existsSync(out), false);
+});
+
+test('cli: an unrecognized delivery lock preserves user data and invalidates the previous artifact', () => {
+ const initialInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'unrecognized-lock.html');
+ const lock = out.replace(/\.html$/, '.delivery-lock.json');
+ const bytes = Buffer.from(JSON.stringify({ schemaVersion: 1, sentinel: 'user data' }));
+ assert.equal(run(['deliver', 'workflow', initialInput, out, '--json']).status, 0);
+ const previousHash = sha256(out);
+ fs.writeFileSync(lock, bytes);
+ const result = run(['deliver', 'workflow', replacementInput, out, '--json']);
+ assert.equal(result.status, 1);
+ assert.deepEqual(fs.readFileSync(lock), bytes);
+ assert.equal(sha256(out), previousHash);
+ assert.equal(JSON.parse(result.stdout).diagnostics[0].code, 'delivery/lock-invalid');
+ for (const args of [
+ ['check', out],
+ ['check', out, '--require-provenance'],
+ ]) {
+ const checked = run(args);
+ assert.equal(checked.status, 1, checked.stderr || checked.stdout);
+ assertCheckFailureReceipt(JSON.parse(checked.stdout), out, /^delivery\/provenance-locked$/);
+ }
+ for (const args of [
+ ['visual-check', out, '--json'],
+ ['visual-check', out, '--json', '--require-provenance'],
+ ]) {
+ const checked = run(args);
+ assert.equal(checked.status, 1, checked.stderr || checked.stdout);
+ const receipt = JSON.parse(checked.stdout);
+ assert.equal(receipt.provenance, 'locked');
+ assert.equal(receipt.diagnostics[0].code, 'delivery/provenance-locked');
+ }
+});
+
+test('cli: delivery provenance cannot replace its input specification', () => {
+ const input = path.join(tmp, 'provenance-input-alias.delivery.json');
+ const source = fs.readFileSync(path.join(skillRoot, 'examples/agent-tool-call.workflow.json'));
+ fs.writeFileSync(input, source);
+ const out = input.replace(/\.delivery\.json$/, '.html');
+
+ const result = run(['deliver', 'workflow', input, out, '--json']);
+
+ assert.equal(result.status, 1);
+ const failure = JSON.parse(result.stdout);
+ assert.equal(failure.stage, 'prepare');
+ assert.equal(failure.diagnostics[0].code, 'output/input-alias');
+ assert.deepEqual(fs.readFileSync(input), source);
+ assert.equal(fs.existsSync(out), false);
+});
+
+test('cli: rejected authored output does not write provenance outside the working directory', () => {
+ const parent = path.join(tmp, 'rejected-authored-output');
+ const workingDirectory = path.join(parent, 'work');
+ fs.mkdirSync(workingDirectory, { recursive: true });
+ const input = path.join(workingDirectory, 'input.workflow.json');
+ const diagram = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/agent-tool-call.workflow.json'), 'utf8'));
+ diagram.meta = { ...diagram.meta, output: '../victim.html' };
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ const victim = path.join(parent, 'victim.html');
+ const sidecar = path.join(parent, 'victim.delivery.json');
+ const pending = path.join(parent, 'victim.delivery-pending.json');
+ const artifactBytes = Buffer.from('<!doctype html><title>untouched</title>\n');
+ const sidecarBytes = Buffer.from('{"status":"current","sentinel":true}\n');
+ fs.writeFileSync(victim, artifactBytes);
+ fs.writeFileSync(sidecar, sidecarBytes);
+
+ const result = run(['deliver', 'workflow', input, '--json'], { cwd: workingDirectory });
+
+ assert.equal(result.status, 1);
+ const failure = JSON.parse(result.stdout);
+ assert.equal(failure.diagnostics[0].code, 'output/meta-outside-cwd');
+ assert.deepEqual(fs.readFileSync(victim), artifactBytes);
+ assert.deepEqual(fs.readFileSync(sidecar), sidecarBytes);
+ assert.equal(fs.existsSync(pending), false);
+ assert.equal('provenance' in failure, false);
+});
+
+test('cli: a failed provenance marker write and invalidation still leave a fail-closed journal', () => {
+ const validInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const invalidInput = path.join(tmp, 'marker-write-failure.workflow.json');
+ const invalid = JSON.parse(fs.readFileSync(validInput, 'utf8'));
+ invalid.nodes[0].unexpected = true;
+ fs.writeFileSync(invalidInput, JSON.stringify(invalid));
+ const out = path.join(tmp, 'marker-write-failure.html');
+ const provenancePath = out.replace(/\.html$/, '.delivery.json');
+ const pendingPath = deliveryPendingPath(out);
+ assert.equal(run(['deliver', 'workflow', validInput, out, '--json']).status, 0);
+ const priorProvenance = fs.readFileSync(provenancePath);
+
+ const wrapper = path.join(tmp, 'fail-marker-write.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const renameSync = fs.renameSync;
+const rmSync = fs.rmSync;
+fs.renameSync = (source, target) => {
+ if (String(source).includes('.archify-provenance-') && String(target) === ${JSON.stringify(provenancePath)}) {
+ const error = new Error('injected failure marker rename error');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return renameSync(source, target);
+};
+fs.rmSync = (target, options) => {
+ if (String(target) === ${JSON.stringify(provenancePath)}) {
+ const error = new Error('injected current provenance removal error');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return rmSync(target, options);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(invalidInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(result.status, 1);
+ const failure = JSON.parse(result.stdout);
+ assert.equal(failure.provenance, 'unrecorded');
+ assert.ok(failure.diagnostics.some((entry) => entry.code === 'delivery/provenance-write'));
+ assert.deepEqual(fs.readFileSync(provenancePath), priorProvenance);
+ assert.equal(fs.existsSync(pendingPath), true);
+ const permissive = run(['check', out]);
+ assert.equal(permissive.status, 1);
+ assertCheckFailureReceipt(
+ JSON.parse(permissive.stdout),
+ out,
+ /^delivery\/provenance-failed$/,
+ );
+ const strict = run(['check', out, '--require-provenance']);
+ assert.equal(strict.status, 1);
+ assertCheckFailureReceipt(
+ JSON.parse(strict.stdout),
+ out,
+ /^delivery\/provenance-failed$/,
+ );
+});
+
+test('cli: using the existing receipt as input preserves it and invalidates the previous delivery', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'receipt-as-input.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const sidecar = out.replace(/\.html$/, '.delivery.json');
+ const prior = fs.readFileSync(sidecar);
+ const failed = run(['deliver', 'workflow', sidecar, out, '--json']);
+ assert.equal(failed.status, 1);
+ assert.equal(JSON.parse(failed.stdout).provenance, 'unrecorded');
+ assert.deepEqual(fs.readFileSync(sidecar), prior);
+ for (const flags of [[], ['--require-provenance']]) {
+ const checked = run(['check', out, ...flags]);
+ assert.equal(checked.status, 1);
+ assert.equal(JSON.parse(checked.stdout).provenance, 'failed');
+ }
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ assert.equal(run(['check', out, '--require-provenance']).status, 0);
+});
+
+test('cli: visual-check input errors identify the artifact rather than Chrome', () => {
+ for (const input of [path.join(tmp, 'missing-visual.html'), path.join(tmp, 'wrong-visual.txt')]) {
+ if (input.endsWith('.txt')) fs.writeFileSync(input, '<html></html>');
+ const base = input.replace(/\.html?$/i, '') + '.visual-check';
+ fs.writeFileSync(`${base}.json`, JSON.stringify({ ok: true, status: 'pass' }));
+ fs.writeFileSync(`${base}.html`, 'old contact sheet');
+ fs.writeFileSync(`${base}.1440x900.light.png`, 'old screenshot');
+ const result = run(['visual-check', input, '--json']);
+ assert.equal(result.status, 1);
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(receipt.diagnostics[0].code, input.endsWith('.txt') ? 'viewer/visual-check-input' : 'input/artifact-unreadable');
+ assert.equal(receipt.diagnostics[0].subject.artifact, input);
+ assert.match(receipt.diagnostics[0].supportedFixes[0], /readable.*html/);
+ assert.equal(JSON.parse(fs.readFileSync(`${base}.json`)).status, 'fail');
+ assert.equal(fs.existsSync(`${base}.html`), false);
+ assert.equal(fs.existsSync(`${base}.1440x900.light.png`), false);
+ }
+});
+
+test('cli: unreadable preserved artifact still leaves a journal that blocks later checks', () => {
+ const validInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const invalidInput = path.join(tmp, 'unreadable-preserved-artifact.workflow.json');
+ const invalid = JSON.parse(fs.readFileSync(validInput, 'utf8'));
+ invalid.nodes[0].unexpected = true;
+ fs.writeFileSync(invalidInput, JSON.stringify(invalid));
+ const out = path.join(tmp, 'unreadable-preserved-artifact.html');
+ assert.equal(run(['deliver', 'workflow', validInput, out, '--json']).status, 0);
+
+ const wrapper = path.join(tmp, 'unreadable-preserved-artifact-wrapper.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const readFileSync = fs.readFileSync;
+fs.readFileSync = (file, ...args) => {
+ if (String(file) === ${JSON.stringify(out)}) {
+ const error = new Error('injected unreadable preserved artifact');
+ error.code = 'EACCES';
+ throw error;
+ }
+ return readFileSync(file, ...args);
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(invalidInput)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(result.status, 1);
+ assert.equal(fs.existsSync(deliveryPendingPath(out)), true);
+ const checked = run(['check', out, '--require-provenance']);
+ assert.equal(checked.status, 1);
+ assertCheckFailureReceipt(
+ JSON.parse(checked.stdout),
+ out,
+ /^delivery\/provenance-failed$/,
+ );
+});
+
+test('cli: provenance strictness distinguishes lower-level render output from delivered output', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'unknown-provenance.html');
+ assert.equal(run(['render', 'workflow', input, out]).status, 0);
+
+ const permissive = run(['check', out]);
+ assert.equal(permissive.status, 0);
+ assert.equal(JSON.parse(permissive.stdout).provenance, 'unknown');
+
+ const strict = run(['check', out, '--require-provenance']);
+ assert.equal(strict.status, 1);
+ assert.equal(JSON.parse(strict.stdout).diagnostics[0].code, 'delivery/provenance-required');
+
+ const visualStrict = run(['visual-check', out, '--json', '--require-provenance']);
+ assert.equal(visualStrict.status, 1);
+ assert.equal(JSON.parse(visualStrict.stdout).diagnostics[0].code, 'delivery/provenance-required');
+});
+
+test('cli: strict provenance rejects null, incomplete current, and unsupported-schema sidecars', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'malformed-current-provenance.html');
+ const sidecar = out.replace(/\.html$/, '.delivery.json');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ const valid = JSON.parse(fs.readFileSync(sidecar, 'utf8'));
+ const incompleteCurrent = { ...valid };
+ delete incompleteCurrent.receiptId;
+ const unsupportedSchema = { ...valid, schemaVersion: 999 };
+
+ for (const [name, value] of [
+ ['null', null],
+ ['incomplete-current', incompleteCurrent],
+ ['unsupported-schema', unsupportedSchema],
+ ]) {
+ fs.writeFileSync(sidecar, `${JSON.stringify(value)}\n`);
+ const checked = run(['check', out, '--require-provenance']);
+ assert.equal(checked.status, 1, `${name}: ${checked.stderr || checked.stdout}`);
+ assertCheckFailureReceipt(
+ JSON.parse(checked.stdout),
+ out,
+ /^delivery\/provenance-invalid$/,
+ );
+ }
+});
+
+test('cli: a dangling delivery sidecar is invalid rather than absent', t => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const out = path.join(tmp, 'dangling-provenance.html');
+ const sidecar = out.replace(/\.html$/, '.delivery.json');
+ assert.equal(run(['render', 'workflow', input, out]).status, 0);
+ try {
+ fs.symlinkSync(path.join(tmp, 'missing-provenance-target.json'), sidecar, 'file');
+ } catch (error) {
+ if (['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) {
+ t.skip('symlink creation requires permission');
+ return;
+ }
+ throw error;
+ }
+
+ for (const args of [
+ ['check', out],
+ ['check', out, '--require-provenance'],
+ ]) {
+ const checked = run(args);
+ assert.equal(checked.status, 1, checked.stderr || checked.stdout);
+ assertCheckFailureReceipt(
+ JSON.parse(checked.stdout),
+ out,
+ /^delivery\/provenance-invalid$/,
+ );
+ }
+});
+
+test('cli: strict check cannot attach prior provenance after the artifact changes mid-check', () => {
+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const replacementInput = path.join(skillRoot, 'examples/incident-response.workflow.json');
+ const out = path.join(tmp, 'provenance-check-race.html');
+ const replacement = path.join(tmp, 'provenance-check-race-replacement.html');
+ assert.equal(run(['deliver', 'workflow', input, out, '--json']).status, 0);
+ assert.equal(run(['render', 'workflow', replacementInput, replacement]).status, 0);
+ const originalSha256 = sha256(out);
+ assert.notEqual(sha256(replacement), originalSha256);
+
+ const wrapper = path.join(tmp, 'provenance-check-race-wrapper.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const readFileSync = fs.readFileSync;
+let replaced = false;
+fs.readFileSync = (file, ...args) => {
+ const value = readFileSync(file, ...args);
+ if (!replaced && String(file) === ${JSON.stringify(out)}) {
+ replaced = true;
+ fs.copyFileSync(${JSON.stringify(replacement)}, ${JSON.stringify(out)});
+ }
+ return value;
+};
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'check', ${JSON.stringify(out)}, '--require-provenance'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const checked = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+
+ assert.equal(checked.status, 1, checked.stderr || checked.stdout);
+ assert.notEqual(sha256(out), originalSha256);
+ assertCheckFailureReceipt(
+ JSON.parse(checked.stdout),
+ out,
+ /^delivery\/(?:provenance-mismatch|artifact-changed)$/,
+ );
+});
+
+test('cli: failed visual provenance preflight replaces stale evidence with a persisted failure receipt', () => {
+ const validInput = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');
+ const invalidInput = path.join(tmp, 'visual-preflight-failure.workflow.json');
+ const invalid = JSON.parse(fs.readFileSync(validInput, 'utf8'));
+ invalid.nodes[0].unexpected = true;
+ fs.writeFileSync(invalidInput, JSON.stringify(invalid));
+ const out = path.join(tmp, 'visual-preflight-failure.html');
+ assert.equal(run(['deliver', 'workflow', validInput, out, '--json']).status, 0);
+ assert.equal(run(['deliver', 'workflow', invalidInput, out, '--json']).status, 1);
+
+ const evidence = visualEvidencePaths(out);
+ fs.writeFileSync(evidence.receipt, '{"sentinel":"stale receipt"}\n');
+ fs.writeFileSync(evidence.contactSheet, '<!doctype html><title>stale contact sheet</title>\n');
+ for (const screenshot of evidence.screenshots) fs.writeFileSync(screenshot, 'stale screenshot');
+
+ const visual = run(['visual-check', out, '--json', '--require-provenance']);
+
+ assert.equal(visual.status, 1, visual.stderr || visual.stdout);
+ const receipt = JSON.parse(visual.stdout);
+ assert.equal(receipt.ok, false);
+ assert.equal(receipt.command, 'visual-check');
+ assert.equal(receipt.status, 'fail');
+ assert.equal(receipt.artifact.path, path.resolve(out));
+ assert.match(receipt.diagnostics[0].code, /^delivery\/provenance-failed$/);
+ assert.equal(fs.existsSync(evidence.contactSheet), false);
+ assert.equal(evidence.screenshots.every((file) => !fs.existsSync(file)), true);
+ const persisted = JSON.parse(fs.readFileSync(evidence.receipt, 'utf8'));
+ assert.equal(persisted.command, 'visual-check');
+ assert.equal(persisted.status, 'fail');
+ assert.equal(persisted.artifact.path, path.resolve(out));
+ assert.equal(persisted.diagnostics[0].code, receipt.diagnostics[0].code);
+});
+
+test('cli: provenance writes cannot follow the former predictable temporary symlink', t => {
+ const input = path.join(tmp, 'invalid-provenance-symlink.workflow.json');
+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/agent-tool-call.workflow.json'), 'utf8'));
+ source.nodes[0].unexpected = true;
+ fs.writeFileSync(input, JSON.stringify(source));
+ const out = path.join(tmp, 'provenance-symlink.html');
+ const sentinel = path.join(tmp, 'provenance-symlink-sentinel.txt');
+ const sentinelContents = 'must not be overwritten';
+ fs.writeFileSync(out, '<!doctype html><title>trusted</title>\n');
+ fs.writeFileSync(sentinel, sentinelContents);
+
+ const wrapper = path.join(tmp, 'provenance-symlink-wrapper.mjs');
+ fs.writeFileSync(wrapper, `
+import fs from 'node:fs';
+const sidecar = ${JSON.stringify(out.replace(/\.html$/, '.delivery.json'))};
+try {
+ fs.symlinkSync(${JSON.stringify(sentinel)}, sidecar + '.tmp-' + process.pid, 'file');
+} catch (error) {
+ if (['EPERM', 'EACCES', 'ENOTSUP'].includes(error.code)) process.exit(77);
+ throw error;
+}
+process.argv = [process.execPath, ${JSON.stringify(cli)}, 'deliver', 'workflow', ${JSON.stringify(input)}, ${JSON.stringify(out)}, '--json'];
+await import(${JSON.stringify(pathToFileURL(cli).href)});
+`);
+ const result = spawnSync(process.execPath, [wrapper], { cwd: skillRoot, encoding: 'utf8' });
+ if (result.status === 77) {
+ t.skip('symlink creation requires permission');
+ return;
+ }
+ assert.equal(result.status, 1);
+ assert.equal(fs.readFileSync(sentinel, 'utf8'), sentinelContents);
+ assert.equal(JSON.parse(fs.readFileSync(out.replace(/\.html$/, '.delivery.json'), 'utf8')).status, 'failed');
});
test('cli: deliver reports unreadable input as json without touching the target', () => {
@@ -717,6 +2749,10 @@ test('cli: check rejects unknown options and extra positionals', () => {
assert.equal(unknown.status, 2);
assert.match(unknown.stderr, /Unknown check option "--json"/);
+ const strict = run(['check', '--require-provenance', out]);
+ assert.equal(strict.status, 1);
+ assert.equal(JSON.parse(strict.stdout).diagnostics[0].code, 'delivery/provenance-required');
+
const extra = run(['check', out, 'ignored-extra']);
assert.equal(extra.status, 2);
assert.match(extra.stderr, /Usage:/);
diff --git a/archify/test/delivery-contract.test.mjs b/archify/test/delivery-contract.test.mjs
index e280d0bf..a273f32d 100644
--- a/archify/test/delivery-contract.test.mjs
+++ b/archify/test/delivery-contract.test.mjs
@@ -26,6 +26,36 @@ test('skill keeps deterministic delivery, automated browser evidence, and percep
assert.match(delivery, /manual browser record[\s\S]*all four exact viewport measurements, both endpoint themes, and an artifact-bound record/i);
});
+test('strict provenance check must succeed before visual-check', () => {
+ const workflows = [
+ {
+ name: 'SKILL.md',
+ section: skill.match(/After `deliver` exits zero, require current delivery evidence before handoff:[\s\S]*?node bin\/archify\.mjs visual-check <output\.html> --json --require-provenance/)?.[0] ?? '',
+ check: 'node bin/archify.mjs check <output.html> --require-provenance',
+ visualCheck: 'node bin/archify.mjs visual-check <output.html> --json --require-provenance',
+ },
+ {
+ name: 'delivery contract',
+ section: delivery.match(/Run strict `check` after `deliver` exits zero\.[\s\S]*?before collecting new\s+visual evidence\./)?.[0] ?? '',
+ check: 'strict `check`',
+ visualCheck: '`visual-check`',
+ },
+ ];
+
+ for (const { name, section, check, visualCheck } of workflows) {
+ const checkIndex = section.indexOf(check);
+ const visualCheckIndex = section.indexOf(visualCheck);
+
+ assert.notEqual(checkIndex, -1, `${name}: strict check command is documented`);
+ assert.ok(checkIndex < visualCheckIndex, `${name}: strict check command precedes visual-check`);
+ assert.match(
+ section,
+ /(?:after the strict `check` above exits zero[\s\S]{0,300}visual-check|visual-check`? only after that\s+strict check exits zero)/i,
+ `${name}: visual-check requires a successful strict check`,
+ );
+ }
+});
+
test('handoff browser evidence mirrors only the automated visual-check outcome', () => {
assert.match(delivery, /`browser_evidence`[\s\S]*records only the outcome of this automated command/i);
assert.match(delivery, /`passed`[\s\S]*exit 0[\s\S]*receipt `status: "pass"`/i);
@@ -36,17 +66,19 @@ test('handoff browser evidence mirrors only the automated visual-check outcome',
assert.match(delivery, /manual browser record[\s\S]*never changes `browser_evidence`/i);
});
-test('skill uses atomic verified delivery for the final artifact', () => {
+test('skill uses recoverable verified delivery for the final artifact', () => {
assert.match(delivery, /archify\.mjs deliver <type>/);
assert.match(delivery, /same-directory candidate/i);
assert.match(delivery, /only replaces the target after.*artifact checks pass/i);
+ assert.match(delivery, /journal[\s\S]*checkers then fail closed/i);
assert.match(delivery, /never claim that the deterministic receipt includes visual review/i);
});
test('skill keeps optional opening behind the verified commit and outside automation', () => {
assert.match(delivery, /Add `--open` only when the user wants an immediate local preview/);
- assert.match(delivery, /runs after that atomic commit/);
- assert.match(delivery, /Keep it off for CI, unattended agents, and non-interactive environments/);
+ assert.match(delivery, /runs after[\s\S]*verified pair commit[\s\S]*journal has been\s+removed/);
+ assert.match(delivery, /journal has been removed[\s\S]*delivery lock has been released successfully/);
+ assert.match(delivery, /Keep it off for CI, unattended agents, and non-interactive\s+environments/);
assert.match(delivery, /never invokes an opener/);
assert.match(delivery, /status proves only whether the local opener invocation succeeded/);
});
diff --git a/archify/test/finder-browser.test.mjs b/archify/test/finder-browser.test.mjs
index 95abccd0..5d75835a 100644
--- a/archify/test/finder-browser.test.mjs
+++ b/archify/test/finder-browser.test.mjs
@@ -9,7 +9,11 @@ import { ChromeVisualBrowser, findChrome } from '../bin/visual-check.mjs';
import { createViewerClick } from './helpers/viewer-click.mjs';
const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const chrome = process.env.ARCHIFY_CHROME ? findChrome() : null;
+const chromeConfigured = Object.prototype.hasOwnProperty.call(process.env, 'ARCHIFY_CHROME');
+const chrome = chromeConfigured ? findChrome() : null;
+if (chromeConfigured && !chrome) {
+ throw new Error(`ARCHIFY_CHROME does not resolve to an executable browser: ${process.env.ARCHIFY_CHROME}`);
+}
test('Finder preserves search, keyboard, contextual Route selection and cleanup', {
skip: chrome ? false : 'Set ARCHIFY_CHROME to run real-browser Finder checks.',
diff --git a/archify/test/output-path.test.mjs b/archify/test/output-path.test.mjs
index 51a54518..28eea13a 100644
--- a/archify/test/output-path.test.mjs
+++ b/archify/test/output-path.test.mjs
@@ -339,7 +339,8 @@ console.log(JSON.stringify({
assert.equal(status, 1, stderr);
const receipt = JSON.parse(stdout);
assert.equal(receipt.stage, 'commit');
- assert.equal(receipt.diagnostics[0].code, 'output/input-alias');
+ assert.equal(receipt.diagnostics[0].code, 'delivery/ownership-lost');
+ assert.equal(receipt.diagnostics[1].code, 'output/input-alias');
assert.deepEqual(fs.readFileSync(input), source);
});
diff --git a/archify/test/reader-layout-browser.test.mjs b/archify/test/reader-layout-browser.test.mjs
index f5f46b33..9ac63a88 100644
--- a/archify/test/reader-layout-browser.test.mjs
+++ b/archify/test/reader-layout-browser.test.mjs
@@ -8,7 +8,11 @@ import { fileURLToPath, pathToFileURL } from 'node:url';
import { ChromeVisualBrowser, findChrome } from '../bin/visual-check.mjs';
const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
-const chromePath = process.env.ARCHIFY_CHROME ? findChrome() : null;
+const chromeConfigured = Object.prototype.hasOwnProperty.call(process.env, 'ARCHIFY_CHROME');
+const chromePath = chromeConfigured ? findChrome() : null;
+if (chromeConfigured && !chromePath) {
+ throw new Error(`ARCHIFY_CHROME does not resolve to an executable browser: ${process.env.ARCHIFY_CHROME}`);
+}
const cases = {
architecture: 'web-app.architecture.json',
workflow: 'agent-tool-call.workflow.json',
diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjs
index d3af56b6..01f148fc 100644
--- a/archify/test/visual-check.test.mjs
+++ b/archify/test/visual-check.test.mjs
@@ -12,6 +12,7 @@ import {
ChromeVisualBrowser,
VISUAL_CHECK_VIEWPORTS,
chromeVisualBrowserArgs,
+ persistVisualCheckFailure,
runVisualCheck,
sidecarPaths,
} from '../bin/visual-check.mjs';
@@ -174,12 +175,15 @@ test('visual-check records four containment viewports and four endpoint theme ca
const result = await runVisualCheck({
artifactPath: input,
chromePath: '/fake/chrome',
+ deliveryProvenance: { status: 'current', receiptId: 'delivery-receipt-123' },
browserFactory: async () => browser,
});
assert.equal(result.exitCode, 0);
assert.equal(result.receipt.status, 'pass');
assert.equal(result.receipt.evidenceKind, 'automated-browser');
+ assert.equal(result.receipt.provenance, 'current');
+ assert.equal(result.receipt.deliveryReceiptId, 'delivery-receipt-123');
assert.deepEqual(result.receipt.diagnostics, []);
assert.equal(result.receipt.visualReview, 'pending');
assert.equal(result.receipt.viewerChrome.status, 'pass');
@@ -199,6 +203,7 @@ test('visual-check records four containment viewports and four endpoint theme ca
const outputs = sidecarPaths(input);
assert.equal(fs.existsSync(outputs.receipt), true);
+ assert.equal(JSON.parse(fs.readFileSync(outputs.receipt, 'utf8')).deliveryReceiptId, 'delivery-receipt-123');
assert.equal(fs.existsSync(outputs.contactSheet), true);
assert.equal(outputs.screenshots.every((entry) => fs.existsSync(entry.path)), true);
const contactSheet = fs.readFileSync(outputs.contactSheet, 'utf8');
@@ -283,6 +288,112 @@ test('visual-check returns 1 and preserves evidence when any viewport overflows'
assert.equal(fs.existsSync(sidecarPaths(input).contactSheet), true);
});
+test('visual-check refuses changed delivery evidence before launching a browser', async () => {
+ const input = artifact('changed-before-browser.html');
+ const outDir = path.join(tmp, 'changed-before-browser-evidence');
+ const outputs = sidecarPaths(input, { outDir });
+ fs.mkdirSync(outDir, { recursive: true });
+ fs.writeFileSync(outputs.contactSheet, 'old evidence');
+ for (const entry of outputs.screenshots) fs.writeFileSync(entry.path, png);
+ let launched = false;
+ const result = await runVisualCheck({
+ artifactPath: input,
+ outDir,
+ verifyArtifact: () => {
+ const error = new Error('delivery changed');
+ error.deliveryProvenance = { status: 'mismatch' };
+ error.archifyDiagnostics = [{ code: 'delivery/provenance-mismatch' }];
+ throw error;
+ },
+ browserFactory: async () => { launched = true; return fakeBrowser(); },
+ });
+ assert.equal(launched, false);
+ assert.equal(result.exitCode, 1);
+ assert.equal(result.receipt.provenance, 'mismatch');
+ assert.equal(result.receipt.sidecars.directory, outDir);
+ assert.equal(JSON.parse(fs.readFileSync(outputs.receipt)).status, 'fail');
+ assert.equal(fs.existsSync(outputs.contactSheet), false);
+ assert.ok(outputs.screenshots.every((entry) => !fs.existsSync(entry.path)));
+ assert.equal(fs.existsSync(sidecarPaths(input).receipt), false);
+});
+
+test('visual-check persists cleanup errors in its failure receipt', () => {
+ const input = artifact('uncleanable-evidence.html');
+ const outputs = sidecarPaths(input);
+ fs.mkdirSync(outputs.screenshots[0].path);
+ const receipt = persistVisualCheckFailure(input, {
+ schemaVersion: 1, command: 'visual-check', artifact: { path: input },
+ error: 'delivery failed', diagnostics: [{ code: 'delivery/provenance-failed' }],
+ });
+ const saved = JSON.parse(fs.readFileSync(outputs.receipt));
+ assert.deepEqual(saved.diagnostics, receipt.diagnostics);
+ assert.equal(saved.diagnostics[1].code, 'viewer/evidence-write');
+ assert.equal(saved.diagnostics[1].evidence.errors[0].file, outputs.screenshots[0].path);
+ assert.equal(saved.status, 'fail');
+});
+
+test('visual-check rechecks delivery evidence after capture and discards screenshots on failure', async () => {
+ const input = artifact('changed-during-browser.html');
+ let failedDelivery = false;
+ const before = fs.readFileSync(input);
+ const result = await runVisualCheck({
+ artifactPath: input,
+ chromePath: '/fake/chrome',
+ deliveryProvenance: { status: 'current', receiptId: 'previous-receipt' },
+ verifyArtifact: (bytes) => {
+ assert.deepEqual(bytes, before);
+ if (failedDelivery) {
+ const error = new Error('Another delivery failed during capture.');
+ error.deliveryProvenance = { status: 'failed' };
+ error.archifyDiagnostics = [{ code: 'delivery/provenance-failed' }];
+ throw error;
+ }
+ },
+ browserFactory: async () => { failedDelivery = true; return fakeBrowser(); },
+ });
+ assert.equal(result.exitCode, 1);
+ assert.equal(result.receipt.provenance, 'failed');
+ assert.equal(result.receipt.diagnostics[0].code, 'delivery/provenance-failed');
+ const outputs = sidecarPaths(input);
+ assert.equal(JSON.parse(fs.readFileSync(outputs.receipt)).status, 'fail');
+ assert.equal(fs.existsSync(outputs.contactSheet), false);
+ assert.ok(outputs.screenshots.every((entry) => !fs.existsSync(entry.path)));
+});
+
+test('visual-check records cleanup errors after post-capture provenance failure', async () => {
+ const input = artifact('changed-with-uncleanable-browser-evidence.html');
+ const outputs = sidecarPaths(input);
+ let verificationCount = 0;
+ const result = await runVisualCheck({
+ artifactPath: input,
+ chromePath: '/fake/chrome',
+ deliveryProvenance: { status: 'current', receiptId: 'previous-receipt' },
+ verifyArtifact: () => {
+ verificationCount += 1;
+ if (verificationCount === 2) {
+ fs.rmSync(outputs.screenshots[0].path);
+ fs.mkdirSync(outputs.screenshots[0].path);
+ const error = new Error('Another delivery failed during capture.');
+ error.deliveryProvenance = { status: 'failed' };
+ error.archifyDiagnostics = [{ code: 'delivery/provenance-failed' }];
+ throw error;
+ }
+ },
+ browserFactory: async () => fakeBrowser(),
+ });
+
+ assert.equal(result.exitCode, 1);
+ assert.equal(result.receipt.provenance, 'failed');
+ assert.deepEqual(result.receipt.diagnostics.map((entry) => entry.code), [
+ 'delivery/provenance-failed',
+ 'viewer/evidence-write',
+ ]);
+ assert.equal(result.receipt.diagnostics[1].evidence.errors[0].file, outputs.screenshots[0].path);
+ const saved = JSON.parse(fs.readFileSync(outputs.receipt));
+ assert.deepEqual(saved.diagnostics, result.receipt.diagnostics);
+ assert.equal(saved.status, 'fail');
+});
+
test('visual-check returns 1 when the real reader projects node text below 6px', async () => {
const input = artifact('unreadable.html');
const result = await runVisualCheck({