Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
feat: add atomic verified delivery (#37)
tt-a1i277073900da8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9823bc54..e10e7ba2 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -52,7 +52,7 @@ jobs:- uses: actions/checkout@v4- name: Rebuild archify.zip and compare contentsrun: |- scripts/build-zip.sh /tmp/fresh.zip+ (cd /tmp && "$GITHUB_WORKSPACE/scripts/build-zip.sh" fresh.zip)mkdir /tmp/fresh /tmp/checkedunzip -q /tmp/fresh.zip -d /tmp/freshunzip -q archify.zip -d /tmp/checked@@ -86,6 +86,7 @@ jobs:node bin/archify.mjs examplesnode bin/archify.mjs render workflow examples/agent-tool-call.workflow.json /tmp/workflow.htmlnode bin/archify.mjs check /tmp/workflow.html+ node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmp/workflow-delivered.html --quality showcase --jsonnode bin/archify.mjs validate architecture examples/web-app.architecture.json --jsonnode bin/archify.mjs validate workflow examples/agent-tool-call.workflow.json --jsondiff --git a/CHANGELOG.md b/CHANGELOG.mdindex ad8a1889..8e493e1c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,7 @@ All notable changes are documented here. Format loosely follows [Keep a Changelo## [Unreleased]### Added+- **Atomic Verified Delivery.** The zero-dependency CLI now exposes `archify deliver <type> <input.json> [output.html]`: it renders into a unique candidate beside the target, runs the existing eight artifact and composition checks, computes an exact byte count and SHA-256 receipt, and atomically replaces the target only after every deterministic gate passes. `--json` returns stable success or input/prepare/render/check/receipt/commit failure facts for agents and CI. Any failure removes the candidate and preserves the previous artifact byte-for-byte. Existing `render`, `validate`, and `check` behavior remains available for iteration and diagnosis; no schema, renderer, layout, viewer, dependency, network, storage, export, or mobile surface changed. The ZIP builder now also resolves caller-relative output paths before entering its temporary staging directory, and CI exercises that exact packaged path.- **Live Visual Style Try-on.** Every generated artifact now exposes one compact `Style` control and <kbd>S</kbd> shortcut that cycles the existing Classic, Signal Flow, and Blueprint presets over the exact same authored topology. The page and canonical SVG update together, so an explicit reader choice reaches PNG/JPEG/WebP/SVG/WebM export without moving a node or relationship. The authored preset remains the reload default; no preference, URL, source JSON, schema, layout, dependency, fourth style, or dedicated mobile surface is added, and passive embeds/print remain control-free. A same-topology regression proves canonical SVG geometry is identical across all three presets.- **Ambiguous Relationship Corridor Gate.** Unrelated relationships that overlap along the same orthogonal lane for at least 8px now produce exact `composition/ambiguous-corridor` evidence instead of silently reading as a false merge or branch. `standard` keeps dense engineering diagrams renderable and records the finding as a warning; `showcase` rejects it before write and in the final artifact check. Relationships sharing a semantic endpoint, point touches, and shorter overlaps remain legal. Two canonical outer-rail routes were repaired without heuristic rerouting, all five renderers share the same detector, and Proof Lab grows to 88/88 checks with zero corridor debt.- **Artifact-to-install start loop.** The existing viewer footer now offers one restrained, viewer-only `Create yours` link carrying only the typed diagram mode and suppressing its document referrer. A focused bilingual `/start` page turns that mode into canonical install commands, one exact bounded prompt, required evidence, and a verified Proof Lab example without receiving repository content, diagram data, titles, paths, or source JSON; print and canonical exports remain clean.diff --git a/README.md b/README.mdindex 2682660c..f7e7ac35 100644--- a/README.md+++ b/README.md@@ -140,7 +140,7 @@ Architecture examples: [`web-app`](examples/web-app.html) · [`Archify pipeline`- **Layout judgment over generic auto-layout** — the agent chooses hierarchy, spacing, routes, and emphasis for the story.- **Typed JSON IR** — every renderer-backed mode has a schema and reproducible source.-- **Validation before delivery** — schema, layout, HTML/SVG, route, and optional showcase checks catch broken output.+- **Atomic validation before delivery** — schema, layout, HTML/SVG, route, and optional showcase checks must all pass before a final artifact replaces the last known good output.- **Truthful interaction** — focus, routes, role comparison, and stories reuse authored nodes and relationships instead of inventing topology.- **Portable by default** — the result is one HTML file; exports remain full-diagram and free of temporary viewer state.@@ -152,8 +152,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. |-| **Render** | The selected renderer produces standalone HTML and SVG. |-| **Check** | Artifact checks reject malformed geometry and unsafe routes. |+| **Deliver** | A same-directory candidate is rendered and checked; only a passing artifact atomically replaces the target. || **Iterate** | The agent updates the source while unrelated structure stays stable. |Useful repository commands:@@ -163,9 +162,8 @@ cd archifynode bin/archify.mjs doctornode bin/archify.mjs demo /tmp/archify-demonode bin/archify.mjs guide "Show CI/CD checks, approval, deploy, and rollback"-node bin/archify.mjs render workflow examples/agent-tool-call.workflow.json /tmp/workflow.htmlnode bin/archify.mjs validate workflow examples/agent-tool-call.workflow.json --quality showcase --json-node bin/archify.mjs check /tmp/workflow.html+node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase --json```Optional motion and presentation styling are explicit:diff --git a/README_EN.md b/README_EN.mdindex 2682660c..f7e7ac35 100644--- a/README_EN.md+++ b/README_EN.md@@ -140,7 +140,7 @@ Architecture examples: [`web-app`](examples/web-app.html) · [`Archify pipeline`- **Layout judgment over generic auto-layout** — the agent chooses hierarchy, spacing, routes, and emphasis for the story.- **Typed JSON IR** — every renderer-backed mode has a schema and reproducible source.-- **Validation before delivery** — schema, layout, HTML/SVG, route, and optional showcase checks catch broken output.+- **Atomic validation before delivery** — schema, layout, HTML/SVG, route, and optional showcase checks must all pass before a final artifact replaces the last known good output.- **Truthful interaction** — focus, routes, role comparison, and stories reuse authored nodes and relationships instead of inventing topology.- **Portable by default** — the result is one HTML file; exports remain full-diagram and free of temporary viewer state.@@ -152,8 +152,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. |-| **Render** | The selected renderer produces standalone HTML and SVG. |-| **Check** | Artifact checks reject malformed geometry and unsafe routes. |+| **Deliver** | A same-directory candidate is rendered and checked; only a passing artifact atomically replaces the target. || **Iterate** | The agent updates the source while unrelated structure stays stable. |Useful repository commands:@@ -163,9 +162,8 @@ cd archifynode bin/archify.mjs doctornode bin/archify.mjs demo /tmp/archify-demonode bin/archify.mjs guide "Show CI/CD checks, approval, deploy, and rollback"-node bin/archify.mjs render workflow examples/agent-tool-call.workflow.json /tmp/workflow.htmlnode bin/archify.mjs validate workflow examples/agent-tool-call.workflow.json --quality showcase --json-node bin/archify.mjs check /tmp/workflow.html+node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase --json```Optional motion and presentation styling are explicit:diff --git a/README_ZH.md b/README_ZH.mdindex 79f78891..fdc9c19e 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -136,7 +136,7 @@ Architecture 示例:[`Web App`](examples/web-app.html) · [`Archify Pipeline`]- **用布局判断代替通用自动布局** —— Agent 根据故事选择层级、留白、线路和强调关系。- **Typed JSON IR** —— 每种 Renderer 模式都有 Schema 和可复现的源文件。-- **交付前校验** —— Schema、布局、HTML/SVG、线路和可选 Showcase 检查会拦截坏结果。+- **原子交付前校验** —— Schema、布局、HTML/SVG、线路和可选 Showcase 检查必须全部通过,成品才会替换上一份可信结果。- **交互不编造拓扑** —— 聚焦、路径、角色对比和故事都复用作者定义的节点与关系。- **结果默认便携** —— 一个 HTML 文件即可分享;导出永远是完整原图,不携带临时 Viewer 状态。@@ -148,8 +148,7 @@ Archify 不是通用绘图编辑器,也不是 Mermaid 主题;它负责把技|---|---|| **生成** | Agent 根据描述创建 Typed JSON IR。 || **校验** | 内置 Validator 和布局规则检查源文件。 |-| **渲染** | 对应 Renderer 生成独立 HTML 和 SVG。 |-| **检查** | Artifact 门禁拒绝错误几何和不安全线路。 |+| **交付** | 在目标同目录生成并检查候选;只有通过门禁的结果才原子替换目标文件。 || **迭代** | Agent 修改源文件,不干扰无关结构。 |仓库常用命令:@@ -159,9 +158,8 @@ cd archifynode bin/archify.mjs doctornode bin/archify.mjs demo /tmp/archify-demonode bin/archify.mjs guide "展示 CI/CD 检查、审批、部署和回滚"-node bin/archify.mjs render workflow examples/agent-tool-call.workflow.json /tmp/workflow.htmlnode bin/archify.mjs validate workflow examples/agent-tool-call.workflow.json --quality showcase --json-node bin/archify.mjs check /tmp/workflow.html+node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase --json```动态和演示样式需要显式选择:diff --git a/ROADMAP.md b/ROADMAP.mdindex a123f356..25f710f4 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -1,8 +1,10 @@# Archify Roadmap-As of v2.11.0, the coordinate-stability work has shipped as JSON IR plus typed renderers for architecture, workflow, sequence, data-flow, and lifecycle diagrams. Workflow diagrams now also have phase/group/exception-lane structure, happy-path linting, trace animation, and route-crossing guards. The shared viewer adds deterministic semantic node IDs, optional author-controlled relationship IDs with durable `#relation=` links, a pre-click Intent Trace for exact one-hop traffic, a two-endpoint Route Probe with an inspectable Route Journey over deterministic shortest authored paths, searchable Node Finder navigation, read-only one-hop focus with a renderer-owned Semantic Passport and copyable focus link, a runtime-built Semantic Radar for desktop viewport navigation, bounded typed guided views with a visible Named Chapter Rail, pre-commit Chapter Delta Preview, Shared Anchor Handoff, and path-aware Semantic Story Beats, a reader-controlled Live/Still Motion Governor, share-ready one-shot chapters with a title/route/step/state/progress cue, a viewport-filling Presentation Stage, Semantic Camera framing, pan/zoom, three reader-switchable visual presets, and browser-native WebM export. A generated Proof Lab publishes 11 live scenario artifacts with their exact sources, three named reader views, 88 artifact checks, and named composition receipts; its preview grid stays static while deliberate proof links play one named chapter once. The landing-page Live Proof Stage promotes three of those generated artifacts into the first bounded motion proof, and the README motion reel carries the same proof-first story onto GitHub without claiming SVG animation support. A question-first scenario guide maps concrete user needs to those 11 bounded recipes across the five modes, with one shared source for CLI and GitHub Pages and direct proof navigation. A unified CLI (`bin/archify.mjs`) wraps guide, render, validate, check, and examples. This file records the design decisions that led there, plus the ideas that were explicitly declined. The original v2.4 / v2.5 backlog (export-scale URL param, color-blind palette, gzip+base64 share links) was considered and dropped — see [Not planned](#not-planned) for the rationale on each.+As of v2.11.0, the coordinate-stability work has shipped as JSON IR plus typed renderers for architecture, workflow, sequence, data-flow, and lifecycle diagrams. Workflow diagrams now also have phase/group/exception-lane structure, happy-path linting, trace animation, and route-crossing guards. The shared viewer adds deterministic semantic node IDs, optional author-controlled relationship IDs with durable `#relation=` links, a pre-click Intent Trace for exact one-hop traffic, a two-endpoint Route Probe with an inspectable Route Journey over deterministic shortest authored paths, searchable Node Finder navigation, read-only one-hop focus with a renderer-owned Semantic Passport and copyable focus link, a runtime-built Semantic Radar for desktop viewport navigation, bounded typed guided views with a visible Named Chapter Rail, pre-commit Chapter Delta Preview, Shared Anchor Handoff, and path-aware Semantic Story Beats, a reader-controlled Live/Still Motion Governor, share-ready one-shot chapters with a title/route/step/state/progress cue, a viewport-filling Presentation Stage, Semantic Camera framing, pan/zoom, three reader-switchable visual presets, and browser-native WebM export. A generated Proof Lab publishes 11 live scenario artifacts with their exact sources, three named reader views, 88 artifact checks, and named composition receipts; its preview grid stays static while deliberate proof links play one named chapter once. The landing-page Live Proof Stage promotes three of those generated artifacts into the first bounded motion proof, and the README motion reel carries the same proof-first story onto GitHub without claiming SVG animation support. A question-first scenario guide maps concrete user needs to those 11 bounded recipes across the five modes, with one shared source for CLI and GitHub Pages and direct proof navigation. A unified CLI (`bin/archify.mjs`) wraps guide, render, deliver, validate, check, and examples. This file records the design decisions that led there, plus the ideas that were explicitly declined. The original v2.4 / v2.5 backlog (export-scale URL param, color-blind palette, gzip+base64 share links) was considered and dropped — see [Not planned](#not-planned) for the rationale on each.-The latest visual slice adds Live Visual Style Try-on. Every ordinary generated artifact can cycle Classic, Signal Flow, and Blueprint with one compact toolbar control or <kbd>S</kbd>; the document root and canonical SVG change in lockstep, so the reader can export the deliberately selected treatment while node and relationship geometry stays byte-identical. The authored preset remains the reload default, and embed/print remain control-free. No preference storage, URL state, source mutation, schema, layout algorithm, dependency, fourth style, or dedicated mobile surface was added. A same-topology cross-preset regression turns the useful Fireworks style-matrix idea into a stability gate rather than a catalogue-expansion excuse.+The latest stability slice adds Atomic Verified Delivery. `archify deliver` writes the selected renderer into a unique same-directory candidate, applies all existing artifact and composition checks, builds an exact byte/SHA-256 receipt, and uses one rename as the only commit point. Input, prepare, render, check, receipt, and commit failures return named machine-readable stages, remove the candidate, and preserve any previous artifact byte-for-byte. Installed skills without `node_modules` retain the same contract across all five modes. Existing iteration commands remain compatible, while schema, renderer geometry, viewer behavior, dependencies, network, storage, exports, and mobile scope remain unchanged.++The previous visual slice added Live Visual Style Try-on. Every ordinary generated artifact can cycle Classic, Signal Flow, and Blueprint with one compact toolbar control or <kbd>S</kbd>; the document root and canonical SVG change in lockstep, so the reader can export the deliberately selected treatment while node and relationship geometry stays byte-identical. The authored preset remains the reload default, and embed/print remain control-free. No preference storage, URL state, source mutation, schema, layout algorithm, dependency, fourth style, or dedicated mobile surface was added. A same-topology cross-preset regression turns the useful Fireworks style-matrix idea into a stability gate rather than a catalogue-expansion excuse.The previous renderer slice added an Ambiguous Relationship Corridor Gate across all five modes. It identifies unrelated orthogonal relationships that share at least 8px of the same lane—the geometry that can visually invent a merge or branch—while preserving shared-endpoint fan-out/merge, point touches, and shorter overlaps. `standard` emits exact relationship/segment/coordinate warnings; `showcase` rejects the same evidence before write and in the final artifact check. Two canonical routes moved to clear outer rails, Gallery now reports 88/88 checks with zero corridor debt, and the change adds no heuristic rerouting, schema, layout algorithm, dependency, or mobile surface.diff --git a/archify.zip b/archify.zipindex 7b8281b7..a5cd0d45 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex 50ea23f2..62c05b3d 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -74,9 +74,9 @@ All five modes follow the same loop:1. **Read first**: the schema (`schemas/<type>.schema.json`) and the complete worked example (`examples/*.{architecture,workflow,sequence,dataflow,lifecycle}.json`) — copy its patterns instead of guessing field shapes.2. Write `<name>.<type>.json`.-3. Render: `node bin/archify.mjs render <type> <input>.json <output>.html` (paths relative to this skill's folder).-4. Validate the generated artifact: `node bin/archify.mjs validate <type> <input>.json --json`, explicitly add `--quality standard` for dense engineering diagrams or `--quality showcase` for polished delivery, or check an existing HTML file with `node bin/archify.mjs check <output>.html`. This catches malformed SVG output, non-finite SVG values, two-point diagonal arrows, arrows crossing the legend, and profile-aware relationship crossing/corridor ambiguity.-5. If either step fails, the error names the JSON path or the fix (thresholds, valid ranges, which knob to change). Fix the JSON and re-run; never edit the renderer.+3. Preflight while iterating: `node bin/archify.mjs validate <type> <input>.json --json`, explicitly adding `--quality standard` for dense engineering diagrams or `--quality showcase` for polished delivery. Use `render` plus `check` separately only when diagnosing a candidate.+4. Commit the final artifact with `node bin/archify.mjs deliver <type> <input>.json <output>.html --json` and the chosen `--quality`. Deliver renders a unique same-directory candidate, runs the complete artifact checker, computes the exact byte count and SHA-256 receipt, and only replaces the target after all artifact checks pass. Renderer, checker, receipt, or commit failure returns non-zero, removes the candidate, and preserves the previous target unchanged.+5. If any step fails, the error names the JSON path or the fix (thresholds, valid ranges, which knob to change). Fix the JSON and re-run; never edit the renderer.Schema violations exit non-zero with path-prefixed messages like `/nodes/3 (id/label: "router") must NOT have additional properties`. The renderers additionally fail fast on established layout problems: node/state overlap (including cross-lane), labels colliding with nodes or other labels, labels wider than their node, out-of-range columns/rows, too-short edges, and legends outside the viewBox. A relationship passing through an unrelated opaque semantic node is always a hard correctness failure, even when neither `meta.quality_profile` nor CLI `--quality` is present: paint order must never make one authored relationship look like a different topology. The shared Clean Flow Gate reports `clean-flow/edge-through-node`, the exact collection/index and optional relationship ID, obstacle ID, first intersecting segment, 2px clearance, and supported routing/placement knobs before output is written. Stricter composition preferences remain profile-aware. For new or edited work, choose `standard` or `showcase` explicitly; structural container-border rules apply to both explicit profiles, unrelated proper X crossings and unrelated collinear overlaps of at least 8px warn in `standard` and fail in `showcase`, and showcase also fails any sub-8px route segment and sub-16px interior turn while preserving ordinary 8–15px endpoint stubs. Collinear corridors are not proper crossings; the separate `composition/ambiguous-corridor` rule exempts relationships with a shared semantic endpoint, point touches, and overlaps below 8px. Source/target boxes are endpoints; boundaries, lanes, stages, lifecycle bands, sequence segments/lifelines/activations, and other containers remain intentional pass-through geometry. CJK text is measured at double width automatically.@@ -346,6 +346,8 @@ Typography inherits JetBrains Mono from the SVG root. Sizes: 11–12px componentTreat the first render as a candidate, not an automatic final result. After deterministic render, validate, and artifact checks pass, inspect the final browser artifact and a canonical raster export when an image reader is available. Check clipping, text fit, hierarchy, whitespace, misleading routes, label placement, and dark/light readability. Make a maximum of two focused correction rounds; change only the diagnosed coordinates, labels, routes, spacing, or viewBox, then rerun render, validate, and check after every round.+Use `deliver` for every final replacement, including after a visual correction. Its JSON receipt proves only deterministic renderer and artifact-check facts; never claim that the deterministic receipt includes visual review. Perceptual review remains the separate truthful receipt below.+Finish with a truthful receipt:```textdiff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex 76bfaa9d..6ee841a4 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -14,6 +15,7 @@ const TYPES = new Set(['architecture', 'workflow', 'sequence', 'dataflow', 'lifefunction usage() {return `Usage:archify render <type> <input.json> [output.html] [--quality standard|showcase]+ archify deliver <type> <input.json> [output.html] [--json] [--quality standard|showcase]archify validate <type> <input.json> [--json] [--layout-json] [--quality standard|showcase]archify inspect <type> <input.json>archify check <output.html>@@ -85,6 +87,210 @@ function commandRender(args) {if (result.status !== 0) exitFrom(result);}+function reportDeliveryFailure({ json, stage, type, input, output, error, status = 1, checker }) {+ const receipt = {+ schemaVersion: 1,+ ok: false,+ command: 'deliver',+ stage,+ type,+ input,+ output,+ error,+ ...(checker ? { checker } : {}),+ };+ if (json) console.log(JSON.stringify(receipt, null, 2));+ else console.error(error);+ process.exitCode = status;+}++function commandDeliver(args) {+ const qualityArgs = extractQualityArgs(args);+ const json = qualityArgs.rest.includes('--json');+ const unknown = qualityArgs.rest.filter((arg) => arg.startsWith('--') && arg !== '--json');+ if (unknown.length) fail(`Unknown deliver option "${unknown[0]}".`);+ const positional = qualityArgs.rest.filter((arg) => arg !== '--json');+ const [type, input, requestedOutput] = positional;+ if (!type || !input || positional.length > 3) fail(usage());++ const renderer = rendererPath(type);+ const inputPath = path.resolve(input);+ let diagram;+ try {+ diagram = JSON.parse(fs.readFileSync(inputPath, 'utf8'));+ } catch (error) {+ reportDeliveryFailure({+ json,+ stage: 'input',+ type,+ input: inputPath,+ output: path.resolve(requestedOutput || `${type}.html`),+ error: `Could not read delivery input "${inputPath}": ${error.message}`,+ });+ return;+ }++ const authoredOutput = typeof diagram?.meta?.output === 'string' && diagram.meta.output+ ? diagram.meta.output+ : `${type}.html`;+ const outputPath = path.resolve(requestedOutput || authoredOutput);+ const outputDirectory = path.dirname(outputPath);+ try {+ fs.mkdirSync(outputDirectory, { recursive: true });+ } catch (error) {+ reportDeliveryFailure({+ json,+ stage: 'prepare',+ type,+ input: inputPath,+ output: outputPath,+ error: `Could not create delivery directory "${outputDirectory}": ${error.message}`,+ });+ return;+ }++ // 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) {+ reportDeliveryFailure({+ json,+ stage: 'prepare',+ type,+ input: inputPath,+ output: outputPath,+ error: `Could not create a delivery candidate beside "${outputPath}": ${error.message}`,+ });+ return;+ }+ const candidatePath = path.join(stagingDirectory, path.basename(outputPath));++ try {+ const render = runNode([renderer, inputPath, candidatePath], {+ stdio: 'pipe',+ env: qualityArgs.quality ? { ARCHIFY_QUALITY_PROFILE: qualityArgs.quality } : undefined,+ });+ if (render.status !== 0) {+ if (render.stderr) process.stderr.write(render.stderr);+ if (render.stdout) process.stderr.write(render.stdout);+ reportDeliveryFailure({+ json,+ stage: 'render',+ type,+ input: inputPath,+ output: outputPath,+ error: (render.stderr || render.stdout || 'Renderer failed without a diagnostic.').trim(),+ status: render.status ?? 1,+ });+ return;+ }++ const check = runNode([path.join(skillRoot, 'scripts/check-render-output.mjs'), candidatePath], {+ stdio: 'pipe',+ });+ if (check.status !== 0) {+ if (check.stderr) process.stderr.write(check.stderr);+ let checker;+ try {+ checker = JSON.parse(check.stdout);+ checker.file = outputPath;+ } catch {+ checker = { ok: false, file: outputPath, diagnostic: check.stdout.trim() };+ }+ reportDeliveryFailure({+ json,+ stage: 'check',+ type,+ input: inputPath,+ output: outputPath,+ error: 'Final artifact check failed; the previous artifact was preserved.',+ status: check.status ?? 1,+ checker,+ });+ return;+ }++ let result;+ try {+ result = JSON.parse(check.stdout);+ } catch (error) {+ reportDeliveryFailure({+ json,+ stage: 'receipt',+ type,+ input: inputPath,+ output: outputPath,+ error: `Could not parse the successful artifact-check receipt: ${error.message}`,+ });+ return;+ }+ let artifact;+ try {+ artifact = fs.readFileSync(candidatePath);+ } catch (error) {+ reportDeliveryFailure({+ json,+ stage: 'receipt',+ type,+ input: inputPath,+ output: outputPath,+ error: `Could not read the verified delivery candidate: ${error.message}`,+ });+ return;+ }+ const receipt = {+ schemaVersion: 1,+ ok: true,+ command: 'deliver',+ type,+ input: inputPath,+ output: outputPath,+ artifact: {+ sha256: createHash('sha256').update(artifact).digest('hex'),+ bytes: artifact.byteLength,+ },+ validation: {+ checksPassed: result.checks.filter((checkItem) => checkItem.ok).length,+ checkCount: result.checks.length,+ compositionProfile: result.composition.profile,+ compositionStatus: result.composition.status,+ errors: result.composition.summary.errors,+ warnings: result.composition.summary.warnings,+ },+ };++ try {+ fs.renameSync(candidatePath, outputPath);+ } catch (error) {+ reportDeliveryFailure({+ json,+ stage: 'commit',+ type,+ input: inputPath,+ output: outputPath,+ error: `Could not commit verified delivery "${outputPath}": ${error.message}`,+ });+ return;+ }++ if (json) {+ console.log(JSON.stringify(receipt, null, 2));+ } else {+ console.log(`delivered ${type} ${outputPath}`);+ console.log(`${receipt.validation.checksPassed}/${receipt.validation.checkCount} artifact checks; composition ${receipt.validation.compositionProfile}: ${receipt.validation.compositionStatus}; sha256 ${receipt.artifact.sha256.slice(0, 12)}`);+ }+ } finally {+ try {+ fs.rmSync(stagingDirectory, { recursive: true, force: true });+ } catch (error) {+ console.error(`Warning: could not remove delivery staging directory "${stagingDirectory}": ${error.message}`);+ }+ }+}+function commandCheck(args) {const [html] = args;if (!html) fail(usage());@@ -345,6 +551,9 @@ switch (command) {case 'render':commandRender(args);break;+ case 'deliver':+ commandDeliver(args);+ break;case 'validate':commandValidate(args);break;diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjsindex e2ddb387..b9a52892 100644--- a/archify/test/cli.test.mjs+++ b/archify/test/cli.test.mjs@@ -1,6 +1,7 @@import { test } from 'node:test';import assert from 'node:assert/strict';import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -19,6 +20,10 @@ function run(args, options = {}) {});}+function sha256(file) {+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');+}+function copyInstalledSkill(target) {fs.cpSync(skillRoot, target, {recursive: true,@@ -38,6 +43,7 @@ test('cli: help lists commands and diagram types', () => {const result = run(['--help']);assert.equal(result.status, 0, result.stderr);assert.match(result.stdout, /archify render <type>/);+ assert.match(result.stdout, /archify deliver <type>/);assert.match(result.stdout, /archify guide \[scenario or question\]/);assert.match(result.stdout, /archify doctor/);assert.match(result.stdout, /archify demo \[output-directory\]/);@@ -188,6 +194,190 @@ test('cli: render writes a diagram html file', () => {assert.match(fs.readFileSync(out, 'utf8'), /Agent Tool Call Workflow/);});+test('cli: deliver atomically writes a checked artifact and structured receipt', () => {+ const out = path.join(tmp, 'delivered-workflow.html');+ const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');+ const result = run(['deliver', 'workflow', input, out, '--quality', 'showcase', '--json']);++ assert.equal(result.status, 0, result.stderr);+ assert.equal(fs.existsSync(out), true);+ assert.match(fs.readFileSync(out, 'utf8'), /Agent Tool Call Workflow/);++ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.schemaVersion, 1);+ assert.equal(receipt.ok, true);+ assert.equal(receipt.command, 'deliver');+ assert.equal(receipt.type, 'workflow');+ assert.equal(receipt.input, input);+ assert.equal(receipt.output, out);+ assert.match(receipt.artifact.sha256, /^[a-f0-9]{64}$/);+ assert.equal(receipt.artifact.sha256, sha256(out));+ assert.equal(receipt.artifact.bytes, fs.statSync(out).size);+ assert.deepEqual(receipt.validation, {+ checksPassed: 8,+ checkCount: 8,+ compositionProfile: 'showcase',+ compositionStatus: 'pass',+ errors: 0,+ warnings: 0,+ });+});++test('cli: deliver preserves the renderer default output contract', () => {+ const workingDirectory = path.join(tmp, 'delivery-default-output');+ fs.mkdirSync(workingDirectory, { recursive: true });+ const input = path.join(workingDirectory, 'source.architecture.json');+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));+ source.meta.output = 'verified-default.html';+ fs.writeFileSync(input, JSON.stringify(source));++ const result = run(['deliver', 'architecture', input, '--json'], { cwd: workingDirectory });+ assert.equal(result.status, 0, result.stderr);+ const receipt = JSON.parse(result.stdout);+ assert.equal(receipt.output, path.join(fs.realpathSync(workingDirectory), 'verified-default.html'));+ assert.equal(fs.existsSync(receipt.output), true);+});++test('cli: deliver works from an installed skill without node_modules', () => {+ const installedRoot = path.join(tmp, 'installed-deliver-skill');+ copyInstalledSkill(installedRoot);+ const installedCli = path.join(installedRoot, 'bin/archify.mjs');+ const cases = {+ architecture: 'web-app.architecture.json',+ workflow: 'agent-tool-call.workflow.json',+ sequence: 'cache-miss-request.sequence.json',+ dataflow: 'product-analytics.dataflow.json',+ lifecycle: 'agent-run.lifecycle.json',+ };++ for (const [type, example] of Object.entries(cases)) {+ const input = path.join(installedRoot, 'examples', example);+ const out = path.join(tmp, `installed-${type}-delivery.html`);+ const result = spawnSync(process.execPath, [installedCli, 'deliver', type, input, out, '--json'], {+ cwd: installedRoot,+ encoding: 'utf8',+ });++ assert.equal(result.status, 0, `${type}: ${result.stderr}`);+ assert.equal(JSON.parse(result.stdout).validation.checkCount, 8, type);+ assert.equal(fs.existsSync(out), true, type);+ }+});++test('cli: deliver preserves the previous artifact when the final check fails', () => {+ const installedRoot = path.join(tmp, 'broken-deliver-skill');+ copyInstalledSkill(installedRoot);+ const installedCli = path.join(installedRoot, 'bin/archify.mjs');+ const templatePath = path.join(installedRoot, 'assets/template.html');+ const template = fs.readFileSync(templatePath, 'utf8');+ fs.writeFileSync(templatePath, template.replace('</body>', '<svg aria-label="accidental second svg"></svg>\n</body>'));++ const input = path.join(installedRoot, 'examples/web-app.architecture.json');+ const out = path.join(tmp, 'preserved-delivery.html');+ const trustedPriorArtifact = '<!doctype html><title>trusted prior artifact</title>\n';+ fs.writeFileSync(out, trustedPriorArtifact);++ const result = spawnSync(process.execPath, [installedCli, 'deliver', 'architecture', input, out, '--json'], {+ cwd: installedRoot,+ encoding: 'utf8',+ });++ assert.equal(result.status, 1);+ const failure = JSON.parse(result.stdout);+ assert.equal(failure.ok, false);+ assert.equal(failure.stage, 'check');+ assert.equal(failure.checker.checks.find((entry) => entry.name === 'single_svg').ok, false);+ assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);+ assert.deepEqual(+ fs.readdirSync(path.dirname(out)).filter((name) => name.includes('.archify-delivery-')),+ [],+ );+});++test('cli: deliver reports renderer failure as json and preserves the previous artifact', () => {+ 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'));+ 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 result = run(['deliver', 'workflow', input, out, '--json']);+ assert.equal(result.status, 1);+ const failure = JSON.parse(result.stdout);+ 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);+});++test('cli: deliver reports unreadable input as json without touching the target', () => {+ const input = path.join(tmp, 'malformed-delivery.json');+ fs.writeFileSync(input, '{not valid json');+ const out = path.join(tmp, 'malformed-input-preserved.html');+ const trustedPriorArtifact = '<!doctype html><title>still trusted</title>\n';+ fs.writeFileSync(out, trustedPriorArtifact);++ const result = run(['deliver', 'architecture', input, out, '--json']);+ assert.equal(result.status, 1);+ const failure = JSON.parse(result.stdout);+ assert.equal(failure.ok, false);+ assert.equal(failure.stage, 'input');+ assert.match(failure.error, /Could not read delivery input/);+ assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);+});++test('cli: invalid source output metadata still fails inside the renderer', () => {+ const workingDirectory = path.join(tmp, 'invalid-output-metadata');+ fs.mkdirSync(workingDirectory, { recursive: true });+ const input = path.join(workingDirectory, 'source.architecture.json');+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));+ source.meta.output = 17;+ fs.writeFileSync(input, JSON.stringify(source));+ const out = path.join(workingDirectory, 'architecture.html');+ const trustedPriorArtifact = '<!doctype html><title>metadata did not replace me</title>\n';+ fs.writeFileSync(out, trustedPriorArtifact);++ const result = run(['deliver', 'architecture', input, '--json'], { cwd: workingDirectory });+ assert.equal(result.status, 1);+ const failure = JSON.parse(result.stdout);+ assert.equal(failure.stage, 'render');+ assert.match(failure.error, /schema validation failed/i);+ assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);+});++test('cli: deliver reports commit failure without a false success receipt', () => {+ const input = path.join(skillRoot, 'examples/web-app.architecture.json');+ const outputDirectory = path.join(tmp, 'commit-target-is-a-directory');+ fs.mkdirSync(outputDirectory, { recursive: true });++ const result = run(['deliver', 'architecture', input, outputDirectory, '--json']);+ assert.equal(result.status, 1);+ const failure = JSON.parse(result.stdout);+ assert.equal(failure.ok, false);+ assert.equal(failure.stage, 'commit');+ assert.match(failure.error, /Could not commit verified delivery/);+ assert.equal(fs.statSync(outputDirectory).isDirectory(), true);+ assert.equal(fs.readdirSync(outputDirectory).length, 0);+});++test('cli: deliver reports preparation failure as json without touching the blocker', () => {+ const input = path.join(skillRoot, 'examples/web-app.architecture.json');+ const blockingFile = path.join(tmp, 'delivery-parent-is-a-file');+ fs.writeFileSync(blockingFile, 'do not replace me');+ const out = path.join(blockingFile, 'cannot-write.html');++ const result = run(['deliver', 'architecture', input, out, '--json']);+ assert.equal(result.status, 1);+ const failure = JSON.parse(result.stdout);+ assert.equal(failure.ok, false);+ assert.equal(failure.stage, 'prepare');+ assert.match(failure.error, /Could not create delivery directory/);+ assert.equal(fs.readFileSync(blockingFile, 'utf8'), 'do not replace me');+});+test('cli: check validates rendered html', () => {const out = path.join(tmp, 'workflow-check.html');const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');@@ -214,7 +404,7 @@ test('cli: validate emits structured json without keeping html output', () => {assert.deepEqual(new Set(fs.readdirSync(tmp)), before);});-test('cli: --quality overrides the source profile for render and validate', () => {+test('cli: --quality overrides the source profile for render, validate, and deliver', () => {const input = path.join(skillRoot, 'examples/agent-tool-call.workflow.json');const out = path.join(tmp, 'workflow-standard.html');const rendered = run(['render', 'workflow', input, out, '--quality', 'standard']);@@ -224,6 +414,11 @@ test('cli: --quality overrides the source profile for render and validate', () =const validated = run(['validate', 'workflow', input, '--quality=standard', '--json']);assert.equal(validated.status, 0, validated.stderr);assert.equal(JSON.parse(validated.stdout).composition.profile, 'standard');++ const deliveredOut = path.join(tmp, 'workflow-delivered-standard.html');+ const delivered = run(['deliver', 'workflow', input, deliveredOut, '--quality=standard', '--json']);+ assert.equal(delivered.status, 0, delivered.stderr);+ assert.equal(JSON.parse(delivered.stdout).validation.compositionProfile, 'standard');});test('cli: rejects an unknown quality profile', () => {diff --git a/archify/test/delivery-contract.test.mjs b/archify/test/delivery-contract.test.mjsindex 954d9a9e..6eaa0c07 100644--- a/archify/test/delivery-contract.test.mjs+++ b/archify/test/delivery-contract.test.mjs@@ -14,3 +14,10 @@ test('skill requires a bounded and truthful perceptual delivery receipt', () =>assert.match(skill, /maximum of two focused correction rounds/i);assert.match(skill, /never report `visual_review: passed` without inspecting/i);});++test('skill uses atomic verified delivery for the final artifact', () => {+ assert.match(skill, /archify\.mjs deliver <type>/);+ assert.match(skill, /same-directory candidate/i);+ assert.match(skill, /only replaces the target after.*artifact checks pass/i);+ assert.match(skill, /never claim that the deterministic receipt includes visual review/i);+});diff --git a/scripts/build-zip.sh b/scripts/build-zip.shindex d6fbe41d..9662edf5 100755--- a/scripts/build-zip.sh+++ b/scripts/build-zip.sh@@ -5,6 +5,9 @@ set -euo pipefailrepo_root="$(cd "$(dirname "$0")/.." && pwd)"out="${1:-$repo_root/archify.zip}"+if [[ "$out" != /* ]]; then+ out="$(pwd)/$out"+fi# Stage a clean copy: node_modules never ships; test/ is repo-only (the golden# harness compares against ../examples at the repo root, which does not exist