Skip to content

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

[verified] feat: add last-good live preview

tt-a1i87c65d6fdb21
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6711437f..84499028 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
+- **Last-Good Live Preview.** The zero-dependency CLI now exposes `archify preview <type> <input.json> [output.html]` for an explicit desktop authoring loop. A random `127.0.0.1` status shell watches one named JSON source with content-digest polling plus bounded event debounce, snapshots each stable generation's exact bytes, runs that immutable input through the existing renderer, composition gates, artifact checker, and SHA-256 receipt, then rechecks the named source digest at the atomic commit point so only the latest passing artifact can reload. Invalid, deleted, half-written, failed, or superseded candidates keep the prior verified diagram visible and byte-identical while reporting the real generation and failure stage; repairs recover automatically, identical source bytes do not rebuild, and identical artifact bytes do not reload. The server rejects external Host values, arbitrary paths, and write methods; canonical future-path checks prevent input/output aliasing; `--no-open` supports tests or manual URL handoff; SIGINT/SIGTERM allow a bounded graceful drain, terminate a stuck delivery, and then remove the loopback server and private same-directory staging directory. All five renderers and an installed ZIP without `node_modules` are covered. Preview state never enters the self-contained HTML or any canonical export, and no schema, renderer, layout, viewer runtime, dependency, hosted network, storage, or mobile product surface changed.
- **Route Share Card export.** A resolved Route Probe now reveals one contextual **Export → Route Share Card** item that downloads the exact shortest authored path as a 1200×630 PNG while retaining the complete diagram as dimmed context. The exporter consumes Route Probe's ordered node list and stable edge keys directly, applies only static `data-share-route-*` decoration to a finite canonical clone, and never re-runs pathfinding or carries Journey position, motion overlay, camera, Focus, Lens, or Story state. Clear, unreachable, stale, duplicate, and conflicting snapshots fail closed; five-renderer and parallel-edge browser smoke prove exact route identity, full-context retention, PNG pixels, and Journey-state invariance. The receipt remains `format=share-card`, adds `variant=route`, reports `canonical=false` plus `route-state-clean=true`, and the next ordinary export clears the variant. The first slice is download-only and adds no format, schema, layout, dependency, URL, storage, or mobile product surface.
- **Clean Label Gate.** Relationship label masks are now measured against every other authored relationship route across all five typed renderers and again in the final HTML checker. `standard` records sub-2px clearance as an exact warning, while `showcase` rejects sub-4px clearance before write and at delivery with both relationship identities, the hit segment, label rectangle, measured distance, threshold, and supported repair controls. A label's own path fragments remain exempt, but shared source/target fan-out does not hide another route. The one real Event Stream collision moved to a clear authored label position, and Proof Lab now publishes 99/99 checks with zero label-route debt. No auto-layout, route rewrite, schema, viewer, export, dependency, or mobile surface was added.
- **Copy Share Card.** The Export menu can now copy the existing canonical 1200×630 Share Card directly as `image/png`, reusing one rasterization promise and preserving the current theme, preset, full-diagram containment, and cleanup contract. A successful clipboard write records the same exact dimensions, bytes, and canonical receipt as download. Unsupported image clipboard APIs disable only the copy action; Share Card download and full-diagram Copy PNG remain unchanged. Real Chrome smoke coverage reads back the copied PNG signature and dimensions without adding a toolbar button, dependency, server, storage, schema, layout, or mobile surface.
diff --git a/README.md b/README.md
index 8b7c936c..6c05bae6 100644
--- a/README.md
+++ b/README.md
@@ -145,6 +145,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; shared automatic endpoints spread deterministically instead of piling arrows on one midpoint.
- **Typed JSON IR** — every renderer-backed mode has a schema and reproducible source.
- **Atomic validation before delivery** — schema, layout, HTML/SVG, route, and label-to-route clearance checks must all pass before a showcase artifact replaces the last known good output.
+- **Last-good live preview** — an optional desktop loop watches one JSON file, refreshes only after the latest candidate passes every gate, and keeps the previous verified diagram visible when a save is incomplete or invalid.
- **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.
@@ -156,6 +157,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. |
+| **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. |
| **Iterate** | The agent updates the source while unrelated structure stays stable. |
@@ -167,10 +169,13 @@ node bin/archify.mjs doctor
node bin/archify.mjs demo /tmp/archify-demo
node bin/archify.mjs guide "Show CI/CD checks, approval, deploy, and rollback"
node bin/archify.mjs validate workflow examples/agent-tool-call.workflow.json --quality showcase --json
+node bin/archify.mjs preview workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase
node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase --open --json
```
-Use `--open` for an interactive local handoff. It is off by default, runs only after the verified artifact is committed, and never turns a successful delivery into a failure when the OS opener is unavailable; JSON stays on stdout and the absolute manual-open path goes to stderr.
+`preview` is an explicit desktop authoring mode, not a default background service: it binds only to `127.0.0.1` on a random port, watches the one named JSON file, preserves the last verified output through failures, and stops with Ctrl-C. Add `--no-open` for tests or when you will open the printed local URL yourself. It adds no runtime to the generated HTML.
+
+Use `deliver --open` for a one-shot interactive local handoff. It is off by default, runs only after the verified artifact is committed, and never turns a successful delivery into a failure when the OS opener is unavailable; JSON stays on stdout and the absolute manual-open path goes to stderr.
Optional motion and presentation styling are explicit:
diff --git a/README_EN.md b/README_EN.md
index 8b7c936c..6c05bae6 100644
--- a/README_EN.md
+++ b/README_EN.md
@@ -145,6 +145,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; shared automatic endpoints spread deterministically instead of piling arrows on one midpoint.
- **Typed JSON IR** — every renderer-backed mode has a schema and reproducible source.
- **Atomic validation before delivery** — schema, layout, HTML/SVG, route, and label-to-route clearance checks must all pass before a showcase artifact replaces the last known good output.
+- **Last-good live preview** — an optional desktop loop watches one JSON file, refreshes only after the latest candidate passes every gate, and keeps the previous verified diagram visible when a save is incomplete or invalid.
- **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.
@@ -156,6 +157,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. |
+| **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. |
| **Iterate** | The agent updates the source while unrelated structure stays stable. |
@@ -167,10 +169,13 @@ node bin/archify.mjs doctor
node bin/archify.mjs demo /tmp/archify-demo
node bin/archify.mjs guide "Show CI/CD checks, approval, deploy, and rollback"
node bin/archify.mjs validate workflow examples/agent-tool-call.workflow.json --quality showcase --json
+node bin/archify.mjs preview workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase
node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase --open --json
```
-Use `--open` for an interactive local handoff. It is off by default, runs only after the verified artifact is committed, and never turns a successful delivery into a failure when the OS opener is unavailable; JSON stays on stdout and the absolute manual-open path goes to stderr.
+`preview` is an explicit desktop authoring mode, not a default background service: it binds only to `127.0.0.1` on a random port, watches the one named JSON file, preserves the last verified output through failures, and stops with Ctrl-C. Add `--no-open` for tests or when you will open the printed local URL yourself. It adds no runtime to the generated HTML.
+
+Use `deliver --open` for a one-shot interactive local handoff. It is off by default, runs only after the verified artifact is committed, and never turns a successful delivery into a failure when the OS opener is unavailable; JSON stays on stdout and the absolute manual-open path goes to stderr.
Optional motion and presentation styling are explicit:
diff --git a/README_ZH.md b/README_ZH.md
index 2973c557..a4d69da4 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -141,6 +141,7 @@ Architecture 示例:[`Web App`](examples/web-app.html) · [`Archify Pipeline`]
- **用布局判断代替通用自动布局** —— Agent 根据故事选择层级、留白、线路和强调关系;共享的自动端点会确定性展开,不再让多支箭头堆在同一个中点。
- **Typed JSON IR** —— 每种 Renderer 模式都有 Schema 和可复现的源文件。
- **原子交付前校验** —— Schema、布局、HTML/SVG、线路和标签到其他路径的净空检查必须全部通过,Showcase 成品才会替换上一份可信结果。
+- **保留最后好图的实时预览** —— 可选桌面循环只监听一个 JSON;只有最新候选通过全部门禁才刷新,半写入或无效保存时继续显示上一份验证成品。
- **交互不编造拓扑** —— 聚焦、路径、角色对比和故事都复用作者定义的节点与关系。
- **结果默认便携** —— 一个 HTML 文件即可分享;导出永远是完整原图,不携带临时 Viewer 状态。
@@ -152,6 +153,7 @@ Archify 不是通用绘图编辑器,也不是 Mermaid 主题;它负责把技
|---|---|
| **生成** | Agent 根据描述创建 Typed JSON IR。 |
| **校验** | 内置 Validator 和布局规则检查源文件。 |
+| **预览(可选)** | 仅 loopback 的桌面会话监听一个源文件,只刷新验证版本;失败时保留最后好图。 |
| **交付** | 在目标同目录生成并检查候选;只有通过门禁的结果才原子替换目标文件,随后可选用 `--open` 打开这个确切成品。 |
| **迭代** | Agent 修改源文件,不干扰无关结构。 |
@@ -163,10 +165,13 @@ node bin/archify.mjs doctor
node bin/archify.mjs demo /tmp/archify-demo
node bin/archify.mjs guide "展示 CI/CD 检查、审批、部署和回滚"
node bin/archify.mjs validate workflow examples/agent-tool-call.workflow.json --quality showcase --json
+node bin/archify.mjs preview workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase
node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmp/workflow.html --quality showcase --open --json
```
-`--open` 只适合本地交互式交付。它默认关闭,并且只在验证成品原子提交后执行;系统无法打开时,交付仍保持成功,JSON 只写 stdout,stderr 会给出可手动打开的绝对路径。
+`preview` 是显式启用的桌面创作模式,不是默认后台服务:它只在随机端口监听 `127.0.0.1`,只观察指定 JSON,失败时保留上一份验证输出,并通过 Ctrl-C 停止。测试或准备手动打开打印出的本地 URL 时可加 `--no-open`。生成的 HTML 不会携带 Preview Runtime。
+
+`deliver --open` 适合一次性的本地交互交付。它默认关闭,并且只在验证成品原子提交后执行;系统无法打开时,交付仍保持成功,JSON 只写 stdout,stderr 会给出可手动打开的绝对路径。
动态和演示样式需要显式选择:
diff --git a/ROADMAP.md b/ROADMAP.md
index c3478a65..370f6c29 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -1,6 +1,8 @@
# 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, a contain-only 1200×630 Share Card, a route-focused 1200×630 Route Share Card variant, and browser-native WebM export. A generated Proof Lab publishes 11 live scenario artifacts with their exact sources, three named reader views, 99 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, with an optional verified post-commit open for interactive local handoff. 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, a contain-only 1200×630 Share Card, a route-focused 1200×630 Route Share Card variant, and browser-native WebM export. A generated Proof Lab publishes 11 live scenario artifacts with their exact sources, three named reader views, 99 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, preview, deliver, validate, check, and examples, with optional last-good desktop preview and verified post-commit open handoffs. 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 authoring slice adds Last-Good Live Preview. `archify preview <type> <input.json> [output.html]` binds one random IPv4 loopback port, opens one desktop status shell, and combines content-digest polling with directory watching so editor rename bursts and missed native notifications converge on the same source bytes. Every generation snapshots those exact bytes, then runs the existing atomic `deliver` pipeline into a private same-directory staging area; immediately before rename, preview rereads the named source digest, so only the latest passing SHA-256 receipt may replace the output and advance the iframe revision. Invalid, missing, half-written, failed, or superseded candidates update an exact stage diagnostic while the last verified artifact stays visible and byte-stable. Identical sources do not rebuild, identical artifacts do not reload, canonical future-path checks reject input/output aliases, external hosts and write requests are rejected, shutdown gives an active delivery a bounded graceful drain before terminating a stuck process and removing the server and staging directory, and installed ZIP skills keep the zero-dependency contract across all five modes. Preview is explicit, desktop-only, and local: no server state, port, path, error, or reload token enters HTML, SVG, raster, WebM, Share Card, schema, renderer, layout, storage, hosted network, or mobile scope.
The latest sharing slice adds a contextual Route Share Card Export item to a completed Route Probe. It consumes the exact ordered node and stable-edge snapshot already resolved by the viewer, then applies only static `data-share-route-*` decoration to a finite canonical clone before reusing the existing 1200×630 Share Card canvas. The complete diagram remains as dimmed context; Journey position, animation overlays, camera, Focus, Lens, and Story never enter the asset. Clear, unreachable, stale, duplicate, or conflicting state fails closed. Browser smoke now covers all five renderer modes, a parallel authored edge, non-empty PNG pixels, immutable live SVG, and identical route-source fingerprints across Journey positions. The receipt remains `format=share-card`, uses `variant=route`, reports scoped route cleanup rather than claiming canonical output, and is cleared by the next ordinary export. The first slice is download-only and adds no new format, schema, layout, dependency, URL, storage, or mobile surface.
diff --git a/archify.zip b/archify.zip
index def70181..567797d8 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/SKILL.md b/archify/SKILL.md
index 8d7c5f8c..937d7685 100644
--- a/archify/SKILL.md
+++ b/archify/SKILL.md
@@ -79,8 +79,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. 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. 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` without changing delivery success when opening fails or is unsupported. Keep it off for CI, unattended agents, and non-interactive environments. Renderer, checker, receipt, or commit failure returns non-zero, removes the candidate, preserves the previous target unchanged, and never invokes an opener.
-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.
+4. When the user wants an active desktop authoring loop, offer the optional `node bin/archify.mjs preview <type> <input>.json <output>.html --quality <profile>` command. It opens one loopback-only status shell and watches that single explicit source; each stable content digest is bound to an immutable private snapshot, that snapshot runs through the existing verified delivery pipeline, and the named source digest is checked again immediately before atomic commit so only the latest fully passing candidate advances the browser revision. Invalid, half-written, deleted, or superseded input reports its real stage while the previous verified revision remains on screen and on disk. Identical source bytes do not rebuild, identical artifact bytes do not reload, and input/output aliases must fail before watching or commit. Preview is explicit and interactive: never start it by default for one-shot requests, CI, unattended agents, remote sharing, or mobile use; use `--no-open` only when the user will open the printed URL themselves or automation is testing the loop. Stop it with Ctrl-C before final handoff; shutdown may drain an active delivery only for a bounded grace period and must terminate a stuck child before removing private state. Its local server, generation state, diagnostics, source path, and port must never enter the generated artifact or any export.
+5. 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. Add `--open` only when the user wants an immediate local preview of that one-shot delivery: it runs after that atomic commit, uses one argument-array OS opener with a five-second bound, and records `open.status` without changing delivery success when opening fails or is unsupported. Keep it off for CI, unattended agents, and non-interactive environments. Renderer, checker, receipt, or commit failure returns non-zero, removes the candidate, preserves the previous target unchanged, and never invokes an opener.
+6. 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. The Clean Label Gate measures each renderer's actual relationship-label mask against every other authored route: sub-2px clearance is a `standard` warning, while sub-4px clearance fails `showcase` before write and in the final artifact check. A label's own relationship fragments are exempt, but shared source/target fan-out is not; fix with `labelAt`, `labelDx`/`labelDy`, `labelSegment`, route/via/channel controls, or message `y` in sequence diagrams. 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.
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index 2fdda04b..b187c949 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -16,6 +16,7 @@ function usage() {
return `Usage:
archify render <type> <input.json> [output.html] [--quality standard|showcase]
archify deliver <type> <input.json> [output.html] [--json] [--open] [--quality standard|showcase]
+ archify preview <type> <input.json> [output.html] [--no-open] [--quality standard|showcase]
archify validate <type> <input.json> [--json] [--layout-json] [--quality standard|showcase]
archify inspect <type> <input.json>
archify check <output.html>
@@ -311,6 +312,36 @@ async function commandDeliver(args) {
}
}
+async function commandPreview(args) {
+ const qualityArgs = extractQualityArgs(args);
+ const noOpen = qualityArgs.rest.includes('--no-open');
+ const knownOptions = new Set(['--no-open']);
+ const unknown = qualityArgs.rest.filter((arg) => arg.startsWith('--') && !knownOptions.has(arg));
+ if (unknown.length) fail(`Unknown preview option "${unknown[0]}".`);
+ const positional = qualityArgs.rest.filter((arg) => !knownOptions.has(arg));
+ const [type, input, output] = positional;
+ if (!type || !input || positional.length > 3) fail(usage());
+ rendererPath(type);
+
+ let runPreview;
+ try {
+ ({ runPreview } = await import('./preview.mjs'));
+ } catch (error) {
+ fail(`Could not load live preview: ${error.message}`, 1);
+ }
+ try {
+ await runPreview({
+ type,
+ input,
+ output,
+ quality: qualityArgs.quality,
+ open: !noOpen,
+ });
+ } catch (error) {
+ fail(`Could not start live preview: ${error.message}`, 1);
+ }
+}
+
function commandCheck(args) {
const [html] = args;
if (!html) fail(usage());
@@ -347,6 +378,13 @@ async function commandDoctor() {
missing: fs.existsSync(examplesRenderer) ? 0 : 1,
});
+ const previewRuntime = path.join(skillRoot, 'bin/preview.mjs');
+ checks.push({
+ label: 'Live preview runtime',
+ ok: fs.existsSync(previewRuntime),
+ missing: fs.existsSync(previewRuntime) ? 0 : 1,
+ });
+
const scenarioGuide = path.join(skillRoot, 'recipes/scenarios.mjs');
checks.push({
label: 'Scenario recipe guide',
@@ -574,6 +612,9 @@ switch (command) {
case 'deliver':
await commandDeliver(args);
break;
+ case 'preview':
+ await commandPreview(args);
+ break;
case 'validate':
commandValidate(args);
break;
diff --git a/archify/bin/open-artifact.mjs b/archify/bin/open-artifact.mjs
index d7f066a5..878f6b4c 100644
--- a/archify/bin/open-artifact.mjs
+++ b/archify/bin/open-artifact.mjs
@@ -27,15 +27,14 @@ const OPENERS = {
},
};
-export function openArtifact(target, options = {}) {
- const absoluteTarget = path.resolve(target);
+function launchTarget(target, options = {}) {
const platform = options.platform || process.platform;
const opener = OPENERS[platform];
if (!opener) {
return {
requested: true,
status: 'unsupported',
- target: absoluteTarget,
+ target,
method: null,
};
}
@@ -43,7 +42,7 @@ export function openArtifact(target, options = {}) {
const spawn = options.spawn || spawnSync;
let result;
try {
- result = spawn(opener.command, opener.args(absoluteTarget), {
+ result = spawn(opener.command, opener.args(target), {
encoding: 'utf8',
shell: false,
stdio: 'ignore',
@@ -61,7 +60,27 @@ export function openArtifact(target, options = {}) {
return {
requested: true,
status,
- target: absoluteTarget,
+ target,
method: opener.method,
};
}
+
+export function openArtifact(target, options = {}) {
+ return launchTarget(path.resolve(target), options);
+}
+
+export function openLoopbackUrl(target, options = {}) {
+ let url;
+ try {
+ url = new URL(target);
+ } catch {
+ throw new TypeError('Preview URL must be a valid loopback HTTP URL.');
+ }
+ if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || !url.port) {
+ throw new TypeError('Preview URL must be a loopback URL using http://127.0.0.1:<port>.');
+ }
+ if (url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
+ throw new TypeError('Preview URL must target the loopback preview root.');
+ }
+ return launchTarget(url.href, options);
+}
diff --git a/archify/bin/preview.mjs b/archify/bin/preview.mjs
new file mode 100644
index 00000000..4bfceee5
--- /dev/null
+++ b/archify/bin/preview.mjs
@@ -0,0 +1,649 @@
+import { spawn } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import http from 'node:http';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { openLoopbackUrl } from './open-artifact.mjs';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const cliPath = path.join(here, 'archify.mjs');
+const loopbackHost = '127.0.0.1';
+const defaultDebounceMs = 400;
+const defaultPollMs = 800;
+const defaultStopGraceMs = 3000;
+const defaultStopKillMs = 750;
+const diagramTypes = new Set(['architecture', 'workflow', 'sequence', 'dataflow', 'lifecycle']);
+
+function sha256(value) {
+ return createHash('sha256').update(value).digest('hex');
+}
+
+function sourceDigest(inputPath) {
+ try {
+ const bytes = fs.readFileSync(inputPath);
+ return { hash: sha256(bytes), bytes, missing: false };
+ } catch (error) {
+ return { hash: `unreadable:${error.code || 'unknown'}`, bytes: null, missing: true };
+ }
+}
+
+function canonicalFuturePath(targetPath) {
+ let current = path.resolve(targetPath);
+ const missingSegments = [];
+ while (true) {
+ try {
+ return path.join(fs.realpathSync(current), ...missingSegments.reverse());
+ } catch {
+ const parent = path.dirname(current);
+ if (parent === current) return path.resolve(targetPath);
+ missingSegments.push(path.basename(current));
+ current = parent;
+ }
+ }
+}
+
+function initialOutputPath(type, inputPath, requestedOutput) {
+ if (requestedOutput) return path.resolve(requestedOutput);
+ try {
+ const source = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
+ if (typeof source?.meta?.output === 'string' && source.meta.output) {
+ return path.resolve(source.meta.output);
+ }
+ } catch {
+ // An invalid initial source still gets a status shell. Its output target is
+ // fixed to the same fallback that `deliver` would use after repair.
+ }
+ return path.resolve(`${type}.html`);
+}
+
+function previewPage() {
+ return `<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width,initial-scale=1">
+ <title>Archify Live Preview</title>
+ <style>
+ :root { color-scheme: light dark; font-family: Inter, ui-sans-serif, system-ui, sans-serif; }
+ * { box-sizing: border-box; }
+ html, body { width: 100%; height: 100%; margin: 0; overflow: hidden; background: #0b111b; }
+ body { display: grid; grid-template-rows: auto minmax(0, 1fr); color: #e8edf5; }
+ header { position: relative; z-index: 2; display: flex; align-items: center; gap: 12px; min-height: 44px; padding: 7px 12px; border-bottom: 1px solid #253248; background: rgba(11, 17, 27, .96); box-shadow: 0 8px 22px rgba(0,0,0,.18); }
+ .brand { font-size: 12px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; color: #9cadc6; }
+ #status { margin-left: auto; display: inline-flex; align-items: center; gap: 8px; min-height: 30px; padding: 5px 10px; border: 1px solid #33435d; border-radius: 999px; background: #111b2a; font-size: 12px; white-space: nowrap; }
+ #status::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: #6f819d; }
+ body[data-state="checking"] #status::before { background: #f3b44b; box-shadow: 0 0 0 4px rgba(243,180,75,.12); }
+ body[data-state="verified"] #status::before { background: #45d6a8; box-shadow: 0 0 0 4px rgba(69,214,168,.12); }
+ body[data-state="needs-fix"] #status::before { background: #ff6f78; box-shadow: 0 0 0 4px rgba(255,111,120,.12); }
+ details { max-width: min(62vw, 760px); }
+ summary { cursor: pointer; color: #ffbdc2; font-size: 12px; }
+ .diagnostic { position: absolute; top: 38px; right: 12px; width: min(760px, calc(100vw - 24px)); max-height: min(44vh, 360px); overflow: auto; padding: 14px; border: 1px solid #6a3440; border-radius: 10px; background: #17131b; box-shadow: 0 14px 48px rgba(0,0,0,.42); }
+ pre { margin: 0 0 10px; white-space: pre-wrap; overflow-wrap: anywhere; font: 11px/1.55 ui-monospace, SFMono-Regular, Menlo, monospace; color: #f2dfe2; }
+ button { min-height: 32px; padding: 5px 10px; border: 1px solid #4a5d79; border-radius: 7px; background: #1a273a; color: #eef4ff; cursor: pointer; }
+ main { position: relative; min-height: 0; }
+ iframe { display: none; width: 100%; height: 100%; border: 0; background: #fff; }
+ body[data-has-artifact="true"] iframe { display: block; }
+ #empty { position: absolute; inset: 0; display: grid; place-items: center; padding: 32px; color: #91a2bc; text-align: center; background: radial-gradient(circle at 50% 38%, #15233a 0, #0b111b 55%); }
+ body[data-has-artifact="true"] #empty { display: none; }
+ @media (prefers-reduced-motion: reduce) { * { scroll-behavior: auto !important; } }
+ </style>
+</head>
+<body data-state="checking" data-has-artifact="false">
+ <header>
+ <span class="brand">Archify Preview</span>
+ <details id="failure" hidden>
+ <summary role="button" aria-controls="diagnostic-panel">View diagnostic</summary>
+ <div class="diagnostic" id="diagnostic-panel"><pre id="diagnostic"></pre><button id="copy" type="button">Copy diagnostic</button></div>
+ </details>
+ <span id="status" role="status" aria-live="polite">Checking · generation 1</span>
+ </header>
+ <main>
+ <div id="empty">Waiting for the first verified diagram. Invalid input will stay here with an exact diagnostic.</div>
+ <iframe id="artifact" title="Verified Archify diagram"></iframe>
+ </main>
+ <script>
+ (function () {
+ 'use strict';
+ var body = document.body;
+ var status = document.getElementById('status');
+ var failure = document.getElementById('failure');
+ var diagnostic = document.getElementById('diagnostic');
+ var artifact = document.getElementById('artifact');
+ var lastRevision = 0;
+
+ function render(state) {
+ body.dataset.state = state.status;
+ if (state.status === 'verified') {
+ status.textContent = 'Verified · rev ' + state.revision;
+ failure.hidden = true;
+ failure.open = false;
+ if (state.revision !== lastRevision) {
+ lastRevision = state.revision;
+ artifact.src = '/artifact.html?revision=' + encodeURIComponent(state.revision) + '&sha=' + encodeURIComponent(state.lastVerified.sha256.slice(0, 12));
+ body.dataset.hasArtifact = 'true';
+ }
+ } else if (state.status === 'needs-fix') {
+ status.textContent = 'Needs fix · ' + (state.revision ? 'showing rev ' + state.revision : 'no verified revision');
+ diagnostic.textContent = 'Generation ' + state.generation + ' · ' + state.failure.stage + '\\n\\n' + state.failure.message;
+ failure.hidden = false;
+ } else {
+ status.textContent = 'Checking · generation ' + state.generation;
+ failure.hidden = true;
+ }
+ }
+
+ document.getElementById('copy').addEventListener('click', function () {
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(diagnostic.textContent).catch(function () {});
+ }
+ });
+
+ var events = new EventSource('/events');
+ events.addEventListener('state', function (event) {
+ try { render(JSON.parse(event.data)); } catch (_) {}
+ });
+ }());
+ </script>
+</body>
+</html>`;
+}
+
+function compactMessage(value) {
+ let text = String(value || 'Preview build failed without a diagnostic.').trim();
+ const lines = text.split(/\r?\n/);
+ const errorLine = lines.findIndex((line) => /^Error:\s/.test(line));
+ if (errorLine > 0) text = lines.slice(errorLine).join('\n');
+ const relevant = text.split(/\r?\n/);
+ const stackLine = relevant.findIndex((line, index) => index > 0 && /^\s*at\s/.test(line));
+ if (stackLine > 0) text = relevant.slice(0, stackLine).join('\n');
+ return text.length > 6000 ? `${text.slice(0, 6000)}\n… diagnostic truncated` : text;
+}
+
+function redactDiagnostic(value, paths) {
+ let text = compactMessage(value);
+ for (const [absolutePath, replacement] of paths) {
+ if (!absolutePath) continue;
+ text = text.split(absolutePath).join(replacement);
+ }
+ return text;
+}
+
+function safeJson(value) {
+ return JSON.stringify(value).replace(/</g, '\\u003c');
+}
+
+function responseHeaders(contentType) {
+ return {
+ 'Cache-Control': 'no-store',
+ 'Content-Type': contentType,
+ 'Cross-Origin-Resource-Policy': 'same-origin',
+ 'Referrer-Policy': 'no-referrer',
+ 'X-Content-Type-Options': 'nosniff',
+ 'X-Frame-Options': 'SAMEORIGIN',
+ };
+}
+
+function parseReceipt(stdout) {
+ try {
+ return JSON.parse(stdout);
+ } catch {
+ return null;
+ }
+}
+
+export async function startPreview(options) {
+ const type = options.type;
+ if (!diagramTypes.has(type)) throw new Error(`Unknown diagram type "${type}".`);
+ if (options.quality && !['standard', 'showcase'].includes(options.quality)) {
+ throw new Error(`Unknown quality profile "${options.quality}".`);
+ }
+ const inputPath = path.resolve(options.input);
+ const outputPath = initialOutputPath(type, inputPath, options.output);
+ if (canonicalFuturePath(inputPath) === canonicalFuturePath(outputPath)) {
+ throw new Error('Preview output must not replace its JSON input.');
+ }
+ const outputDirectory = path.dirname(outputPath);
+ const debounceMs = Number.isFinite(options.debounceMs) ? options.debounceMs : defaultDebounceMs;
+ const pollMs = Number.isFinite(options.pollMs) ? options.pollMs : defaultPollMs;
+ const stopGraceMs = Number.isFinite(options.stopGraceMs) ? Math.max(0, options.stopGraceMs) : defaultStopGraceMs;
+ const stopKillMs = Number.isFinite(options.stopKillMs) ? Math.max(0, options.stopKillMs) : defaultStopKillMs;
+ const shouldOpen = options.open !== false;
+
+ fs.mkdirSync(outputDirectory, { recursive: true });
+ const stagingDirectory = fs.mkdtempSync(path.join(outputDirectory, '.archify-preview-'));
+
+ let port = 0;
+ let watcher;
+ let debounceTimer;
+ let pollTimer;
+ let stopGraceTimer;
+ let stopKillTimer;
+ let child;
+ let stopping = false;
+ let stopped = false;
+ let serverClosing = false;
+ let serverClosed = false;
+ let queuedHash = null;
+ let activeHash = null;
+ let lastGoodSourceHash = null;
+ let sourceEpoch = 0;
+ let activeEpoch = 0;
+ let pendingBuild = false;
+ let artifactBuffer = null;
+ const clients = new Set();
+ const state = {
+ schemaVersion: 1,
+ status: 'checking',
+ generation: 0,
+ revision: 0,
+ lastVerified: null,
+ failure: null,
+ };
+
+ let resolveClosed;
+ const closed = new Promise((resolve) => { resolveClosed = resolve; });
+
+ function publicState() {
+ return JSON.parse(JSON.stringify(state));
+ }
+
+ function sendState(res) {
+ res.write(`event: state\ndata: ${safeJson(publicState())}\n\n`);
+ }
+
+ function broadcast() {
+ for (const res of clients) sendState(res);
+ }
+
+ const page = Buffer.from(previewPage());
+ const server = http.createServer((req, res) => {
+ const expectedHost = `${loopbackHost}:${port}`;
+ if (req.headers.host !== expectedHost) {
+ res.writeHead(403, responseHeaders('text/plain; charset=utf-8'));
+ res.end('Forbidden host');
+ return;
+ }
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ res.writeHead(405, { ...responseHeaders('text/plain; charset=utf-8'), Allow: 'GET, HEAD' });
+ res.end('Method not allowed');
+ return;
+ }
+
+ let url;
+ try {
+ url = new URL(req.url, `http://${expectedHost}`);
+ } catch {
+ res.writeHead(400, responseHeaders('text/plain; charset=utf-8'));
+ res.end('Bad request');
+ return;
+ }
+
+ if (url.pathname === '/') {
+ res.writeHead(200, {
+ ...responseHeaders('text/html; charset=utf-8'),
+ 'Content-Security-Policy': "default-src 'none'; frame-src 'self'; connect-src 'self'; script-src 'unsafe-inline'; style-src 'unsafe-inline'",
+ 'Content-Length': page.byteLength,
+ });
+ if (req.method === 'HEAD') res.end();
+ else res.end(page);
+ return;
+ }
+ if (url.pathname === '/state') {
+ const body = Buffer.from(`${safeJson(publicState())}\n`);
+ res.writeHead(200, { ...responseHeaders('application/json; charset=utf-8'), 'Content-Length': body.byteLength });
+ if (req.method === 'HEAD') res.end();
+ else res.end(body);
+ return;
+ }
+ if (url.pathname === '/artifact.html') {
+ if (!artifactBuffer) {
+ res.writeHead(404, responseHeaders('text/plain; charset=utf-8'));
+ res.end('No verified artifact yet');
+ return;
+ }
+ res.writeHead(200, { ...responseHeaders('text/html; charset=utf-8'), 'Content-Length': artifactBuffer.byteLength });
+ if (req.method === 'HEAD') res.end();
+ else res.end(artifactBuffer);
+ return;
+ }
+ if (url.pathname === '/events' && req.method === 'GET') {
+ res.writeHead(200, {
+ ...responseHeaders('text/event-stream; charset=utf-8'),
+ Connection: 'keep-alive',
+ });
+ res.write('retry: 1000\n\n');
+ clients.add(res);
+ sendState(res);
+ req.on('close', () => clients.delete(res));
+ return;
+ }
+
+ res.writeHead(404, responseHeaders('text/plain; charset=utf-8'));
+ res.end('Not found');
+ });
+
+ try {
+ await new Promise((resolve, reject) => {
+ server.once('error', reject);
+ server.listen(0, loopbackHost, () => {
+ server.off('error', reject);
+ port = server.address().port;
+ resolve();
+ });
+ });
+ } catch (error) {
+ try { server.close(); } catch {}
+ fs.rmSync(stagingDirectory, { recursive: true, force: true });
+ throw error;
+ }
+
+ const url = `http://${loopbackHost}:${port}/`;
+
+ function finishStop() {
+ if (stopped || child || !serverClosed) return;
+ stopped = true;
+ clearTimeout(debounceTimer);
+ clearInterval(pollTimer);
+ clearTimeout(stopGraceTimer);
+ clearTimeout(stopKillTimer);
+ try {
+ fs.rmSync(stagingDirectory, { recursive: true, force: true });
+ } finally {
+ resolveClosed();
+ }
+ }
+
+ function signalActiveChild(signal) {
+ if (!child || child.exitCode !== null || child.signalCode !== null) return;
+ try {
+ if (process.platform !== 'win32' && child.pid) process.kill(-child.pid, signal);
+ else child.kill(signal);
+ } catch (error) {
+ if (error.code === 'ESRCH') return;
+ try { child.kill(signal); } catch {}
+ }
+ }
+
+ function closeServer() {
+ if (serverClosing) return;
+ serverClosing = true;
+ for (const res of clients) res.end();
+ clients.clear();
+ server.close(() => {
+ serverClosed = true;
+ finishStop();
+ });
+ server.closeIdleConnections?.();
+ }
+
+ function startBoundedChildDrain() {
+ if (!child || stopGraceTimer || stopKillTimer) return;
+ stopGraceTimer = setTimeout(() => {
+ stopGraceTimer = undefined;
+ if (!child) return finishStop();
+ signalActiveChild('SIGTERM');
+ stopKillTimer = setTimeout(() => {
+ stopKillTimer = undefined;
+ signalActiveChild('SIGKILL');
+ }, stopKillMs);
+ }, stopGraceMs);
+ }
+
+ async function stop({ force = false } = {}) {
+ if (!stopping) {
+ stopping = true;
+ clearTimeout(debounceTimer);
+ clearInterval(pollTimer);
+ watcher?.close();
+ closeServer();
+ }
+ if (child && force) {
+ clearTimeout(stopGraceTimer);
+ clearTimeout(stopKillTimer);
+ stopGraceTimer = undefined;
+ stopKillTimer = undefined;
+ signalActiveChild('SIGKILL');
+ } else if (child) {
+ startBoundedChildDrain();
+ } else {
+ finishStop();
+ }
+ return closed;
+ }
+
+ function publishFailure(receipt, stdout, stderr, candidatePath, snapshotPath) {
+ const checkerDetails = receipt?.checker?.checks
+ ?.filter((check) => !check.ok)
+ .flatMap((check) => check.details || [])
+ .filter(Boolean)
+ .slice(0, 12) || [];
+ const diagnostic = [receipt?.error, ...checkerDetails].filter(Boolean).join('\n') || stderr || stdout;
+ state.status = 'needs-fix';
+ state.failure = {
+ stage: receipt?.stage || 'render',
+ message: redactDiagnostic(
+ diagnostic,
+ [
+ [inputPath, '<input.json>'],
+ [outputPath, '<output.html>'],
+ [snapshotPath, '<input.json>'],
+ [candidatePath, '<candidate.html>'],
+ [stagingDirectory, '<preview-staging>'],
+ [path.resolve(here, '..'), '<archify-skill>'],
+ [path.resolve(options.cwd || process.cwd()), '<working-directory>'],
+ ],
+ ),
+ };
+ broadcast();
+ }
+
+ function commitCandidate(candidatePath, receipt, generationHash) {
+ let candidate;
+ try {
+ candidate = fs.readFileSync(candidatePath);
+ const digest = sha256(candidate);
+ if (digest !== receipt?.artifact?.sha256) {
+ throw new Error('Verified candidate bytes do not match the delivery receipt.');
+ }
+ if (canonicalFuturePath(inputPath) === canonicalFuturePath(outputPath)) {
+ throw new Error('Preview output resolved to its JSON input before commit.');
+ }
+ const sameArtifact = state.lastVerified?.sha256 === digest;
+ let outputMatches = false;
+ if (sameArtifact) {
+ try { outputMatches = sha256(fs.readFileSync(outputPath)) === digest; } catch {}
+ }
+ const currentSource = sourceDigest(inputPath);
+ if (currentSource.hash !== generationHash) {
+ return { committed: false, supersededBy: currentSource };
+ }
+ if (!sameArtifact || !outputMatches) fs.renameSync(candidatePath, outputPath);
+ artifactBuffer = candidate;
+ lastGoodSourceHash = generationHash;
+ state.status = 'verified';
+ if (!sameArtifact) {
+ state.revision += 1;
+ state.lastVerified = {
+ sha256: digest,
+ bytes: candidate.byteLength,
+ checksPassed: receipt.validation.checksPassed,
+ checkCount: receipt.validation.checkCount,
+ compositionProfile: receipt.validation.compositionProfile,
+ compositionStatus: receipt.validation.compositionStatus,
+ };
+ }
+ state.failure = null;
+ broadcast();
+ return { committed: true, supersededBy: null };
+ } catch (error) {
+ publishFailure({ stage: 'commit', error: `Could not publish the verified preview: ${error.message}` }, '', '', candidatePath);
+ return { committed: false, supersededBy: null };
+ }
+ }
+
+ function beginBuild(digest, epoch) {
+ if (stopping || child) return;
+ activeHash = digest.hash;
+ activeEpoch = epoch;
+ state.generation += 1;
+ state.status = 'checking';
+ state.failure = null;
+ broadcast();
+
+ const candidatePath = path.join(stagingDirectory, `generation-${state.generation}.html`);
+ const snapshotPath = path.join(stagingDirectory, `generation-${state.generation}.json`);
+ if (digest.bytes !== null) {
+ try {
+ fs.writeFileSync(snapshotPath, digest.bytes, { flag: 'wx', mode: 0o600 });
+ } catch (error) {
+ publishFailure(
+ { stage: 'prepare', error: `Could not snapshot the observed input: ${error.message}` },
+ '',
+ '',
+ candidatePath,
+ snapshotPath,
+ );
+ return;
+ }
+ }
+ const args = [options.deliveryCli || cliPath, 'deliver', type, snapshotPath, candidatePath, '--json'];
+ if (options.quality) args.push('--quality', options.quality);
+ let stdout = '';
+ let stderr = '';
+ child = spawn(process.execPath, args, {
+ cwd: options.cwd || process.cwd(),
+ env: process.env,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ detached: process.platform !== 'win32',
+ });
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
+ child.on('error', (error) => { stderr += error.message; });
+ child.on('close', (code) => {
+ const receipt = parseReceipt(stdout);
+ const generationEpoch = activeEpoch;
+ const generationHash = activeHash;
+ const stale = generationEpoch !== sourceEpoch;
+ let supersededBy = null;
+ child = null;
+ clearTimeout(stopGraceTimer);
+ clearTimeout(stopKillTimer);
+ stopGraceTimer = undefined;
+ stopKillTimer = undefined;
+ if (!stopping && !stale && code === 0 && receipt?.ok) {
+ ({ supersededBy } = commitCandidate(candidatePath, receipt, generationHash));
+ } else if (!stopping && !stale) {
+ publishFailure(receipt, stdout, stderr, candidatePath, snapshotPath);
+ }
+ try { fs.rmSync(candidatePath, { force: true }); } catch {}
+ try { fs.rmSync(snapshotPath, { force: true }); } catch {}
+
+ if (stopping) {
+ finishStop();
+ } else if (pendingBuild || stale || supersededBy) {
+ pendingBuild = false;
+ if (supersededBy && sourceEpoch === generationEpoch) sourceEpoch += 1;
+ const digest = supersededBy || sourceDigest(inputPath);
+ queueStableBuild(digest.hash, true);
+ }
+ });
+ }
+
+ function queueStableBuild(hash, immediate = false) {
+ queuedHash = hash;
+ clearTimeout(debounceTimer);
+ const launch = () => {
+ if (stopping) return;
+ const digest = sourceDigest(inputPath);
+ if (digest.hash !== queuedHash) {
+ queueStableBuild(digest.hash);
+ return;
+ }
+ if (digest.hash === lastGoodSourceHash) {
+ if (state.status !== 'verified' && state.lastVerified) {
+ state.status = 'verified';
+ state.failure = null;
+ broadcast();
+ }
+ return;
+ }
+ if (child) {
+ pendingBuild = true;
+ return;
+ }
+ beginBuild(digest, sourceEpoch);
+ };
+ debounceTimer = setTimeout(launch, immediate ? 0 : debounceMs);
+ }
+
+ function observeSource({ immediate = false } = {}) {
+ const digest = sourceDigest(inputPath);
+ if (!immediate && digest.hash === queuedHash) return;
+ sourceEpoch += 1;
+ queueStableBuild(digest.hash, immediate);
+ }
+
+ if (options.watch !== false) {
+ try {
+ watcher = fs.watch(path.dirname(inputPath), (event, filename) => {
+ if (!filename || filename.toString() === path.basename(inputPath)) observeSource();
+ });
+ } catch (error) {
+ await stop();
+ throw new Error(`Could not watch the input directory: ${error.message}`);
+ }
+ }
+ pollTimer = setInterval(() => observeSource(), pollMs);
+
+ let opener = null;
+ if (shouldOpen) {
+ try {
+ opener = openLoopbackUrl(url);
+ } catch {
+ opener = { requested: true, status: 'unsupported', target: url, method: null };
+ }
+ }
+
+ observeSource({ immediate: true });
+
+ return {
+ url,
+ input: inputPath,
+ output: outputPath,
+ opener,
+ state: publicState,
+ stop,
+ closed,
+ };
+}
+
+export async function runPreview(options) {
+ const preview = await startPreview(options);
+ console.log(`preview ${preview.url}`);
+ console.log(`watching ${preview.input}`);
+ console.log(`output ${preview.output}`);
+ if (preview.opener && preview.opener.status !== 'opened') {
+ console.error(`Could not open the preview (${preview.opener.status}). Open it manually: ${preview.url}`);
+ }
+
+ let signalCount = 0;
+ const stop = () => {
+ signalCount += 1;
+ if (signalCount === 1) {
+ console.log('\nstopping preview…');
+ preview.stop();
+ } else {
+ console.log('\nforcing preview shutdown…');
+ preview.stop({ force: true });
+ }
+ };
+ process.on('SIGINT', stop);
+ process.on('SIGTERM', stop);
+ await preview.closed;
+ process.off('SIGINT', stop);
+ process.off('SIGTERM', stop);
+}
diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjs
index 8b169eee..7d1e5d72 100644
--- a/archify/test/cli.test.mjs
+++ b/archify/test/cli.test.mjs
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { spawnSync } from 'node:child_process';
+import { spawn, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import os from 'node:os';
@@ -73,6 +73,7 @@ test('cli: help lists commands and diagram types', () => {
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 preview <type>/);
assert.match(result.stdout, /--open/);
assert.match(result.stdout, /archify guide \[scenario or question\]/);
assert.match(result.stdout, /archify doctor/);
@@ -86,6 +87,7 @@ test('cli: doctor reports a complete installation is ready', () => {
assert.match(result.stdout, /\[ok\] Node\.js v\d+/);
assert.match(result.stdout, /\[ok\] Core template/);
assert.match(result.stdout, /\[ok\] Example renderer/);
+ assert.match(result.stdout, /\[ok\] Live preview runtime/);
assert.match(result.stdout, /\[ok\] Scenario recipe guide/);
assert.match(result.stdout, /\[ok\] Standalone schema validators/);
assert.match(result.stdout, /\[ok\] architecture renderer, schema, and example/);
@@ -378,6 +380,50 @@ test('cli: deliver works from an installed skill without node_modules', () => {
}
});
+test('cli: preview runs from an installed skill without node_modules and exits cleanly', { timeout: 30000 }, async () => {
+ const installedRoot = path.join(tmp, 'installed-preview-skill');
+ copyInstalledSkill(installedRoot);
+ const installedCli = path.join(installedRoot, 'bin/archify.mjs');
+ const input = path.join(installedRoot, 'examples/web-app.architecture.json');
+ const output = path.join(tmp, 'installed-preview.html');
+ const child = spawn(process.execPath, [installedCli, 'preview', 'architecture', input, output, '--quality', 'showcase', '--no-open'], {
+ cwd: installedRoot,
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe'],
+ });
+ let stdout = '';
+ let stderr = '';
+ child.stdout.setEncoding('utf8');
+ child.stderr.setEncoding('utf8');
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
+
+ let previewUrl;
+ const started = Date.now();
+ while (!previewUrl && Date.now() - started < 8000) {
+ previewUrl = stdout.match(/preview (http:\/\/127\.0\.0\.1:\d+\/)/)?.[1];
+ if (!previewUrl) await new Promise((resolve) => setTimeout(resolve, 40));
+ }
+ assert.ok(previewUrl, `preview URL missing; stdout=${stdout}; stderr=${stderr}`);
+
+ let state;
+ while (Date.now() - started < 15000) {
+ state = await fetch(new URL('/state', previewUrl)).then((response) => response.json());
+ if (state.status === 'verified') break;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ assert.equal(state?.status, 'verified', `preview did not verify; stdout=${stdout}; stderr=${stderr}`);
+ assert.equal(state.revision, 1);
+ assert.equal(fs.existsSync(output), true);
+
+ child.kill('SIGTERM');
+ const exit = await new Promise((resolve) => child.once('close', (code, signal) => resolve({ code, signal })));
+ assert.deepEqual(exit, { code: 0, signal: null });
+ assert.match(stdout, /stopping preview/);
+ await assert.rejects(fetch(previewUrl));
+ assert.deepEqual(fs.readdirSync(path.dirname(output)).filter((name) => name.startsWith('.archify-preview-')), []);
+});
+
test('cli: deliver preserves the previous artifact when the final check fails', () => {
const installedRoot = path.join(tmp, 'broken-deliver-skill');
copyInstalledSkill(installedRoot);
diff --git a/archify/test/open-artifact.test.mjs b/archify/test/open-artifact.test.mjs
index c2c4e4ff..22be2813 100644
--- a/archify/test/open-artifact.test.mjs
+++ b/archify/test/open-artifact.test.mjs
@@ -2,7 +2,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import path from 'node:path';
-import { openArtifact } from '../bin/open-artifact.mjs';
+import { openArtifact, openLoopbackUrl } from '../bin/open-artifact.mjs';
const target = path.resolve("/tmp/-复杂 path 'quoted'/diagram.html");
@@ -84,3 +84,35 @@ test('open artifact: distinguishes missing support from opener execution failure
method: null,
});
});
+
+test('open artifact: live preview opens only an exact loopback HTTP root', () => {
+ const url = 'http://127.0.0.1:43127/';
+ let invocation;
+ const result = openLoopbackUrl(url, {
+ platform: 'darwin',
+ spawn(command, args, options) {
+ invocation = { command, args, options };
+ return { status: 0 };
+ },
+ });
+
+ assert.deepEqual(result, {
+ requested: true,
+ status: 'opened',
+ target: url,
+ method: 'open',
+ });
+ assert.deepEqual(invocation.args, [url]);
+ assert.equal(invocation.options.shell, false);
+
+ for (const rejected of [
+ 'https://127.0.0.1:43127/',
+ 'http://localhost:43127/',
+ 'http://0.0.0.0:43127/',
+ 'http://127.0.0.1:43127/path',
+ 'http://127.0.0.1:43127/?source=secret',
+ 'not a url',
+ ]) {
+ assert.throws(() => openLoopbackUrl(rejected), /loopback|valid/i, rejected);
+ }
+});
diff --git a/archify/test/preview-contract.test.mjs b/archify/test/preview-contract.test.mjs
new file mode 100644
index 00000000..f17fa290
--- /dev/null
+++ b/archify/test/preview-contract.test.mjs
@@ -0,0 +1,40 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const skillRoot = path.resolve(here, '..');
+const repoRoot = path.resolve(skillRoot, '..');
+const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+const readme = fs.readFileSync(path.join(repoRoot, 'README.md'), 'utf8');
+const english = fs.readFileSync(path.join(repoRoot, 'README_EN.md'), 'utf8');
+const chinese = fs.readFileSync(path.join(repoRoot, 'README_ZH.md'), 'utf8');
+const roadmap = fs.readFileSync(path.join(repoRoot, 'ROADMAP.md'), 'utf8');
+
+test('preview contract: the skill keeps live preview explicit, desktop-only, and last-good', () => {
+ assert.match(skill, /archify\.mjs preview <type> <input>\.json <output>\.html/);
+ assert.match(skill, /active desktop authoring loop/i);
+ assert.match(skill, /previous verified revision remains on screen and on disk/i);
+ assert.match(skill, /never start it by default/i);
+ assert.match(skill, /CI, unattended agents, remote sharing, or mobile use/i);
+ assert.match(skill, /must never enter the generated artifact or any export/i);
+});
+
+test('preview contract: all README languages document the same optional command without changing the hero', () => {
+ assert.equal(readme, english);
+ for (const text of [readme, chinese]) {
+ assert.match(text, /bin\/archify\.mjs preview workflow/);
+ assert.match(text, /--no-open/);
+ assert.match(text, /127\.0\.0\.1/);
+ assert.match(text, /Ctrl-C/);
+ assert.match(text, /docs\/assets\/archify-readme-hero\.png/);
+ }
+});
+
+test('preview contract: roadmap records the no-leak and zero-dependency boundary', () => {
+ assert.match(roadmap, /Last-Good Live Preview/);
+ assert.match(roadmap, /installed ZIP skills keep the zero-dependency contract/i);
+ assert.match(roadmap, /no server state, port, path, error, or reload token enters HTML/i);
+});
diff --git a/archify/test/preview.test.mjs b/archify/test/preview.test.mjs
new file mode 100644
index 00000000..fc381fbe
--- /dev/null
+++ b/archify/test/preview.test.mjs
@@ -0,0 +1,499 @@
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import http from 'node:http';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import vm from 'node:vm';
+
+import { startPreview } from '../bin/preview.mjs';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const skillRoot = path.resolve(here, '..');
+
+function sha256(file) {
+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
+}
+
+async function stateAt(url) {
+ const response = await fetch(new URL('/state', url));
+ assert.equal(response.status, 200);
+ return response.json();
+}
+
+async function waitForState(url, predicate, message, timeoutMs = 12000) {
+ const started = Date.now();
+ let latest;
+ while (Date.now() - started < timeoutMs) {
+ latest = await stateAt(url);
+ if (predicate(latest)) return latest;
+ await new Promise((resolve) => setTimeout(resolve, 40));
+ }
+ assert.fail(`${message}; latest state: ${JSON.stringify(latest)}`);
+}
+
+function rawRequest(url, { method = 'GET', pathname = '/', hostHeader } = {}) {
+ const target = new URL(url);
+ return new Promise((resolve, reject) => {
+ const request = http.request({
+ hostname: target.hostname,
+ port: target.port,
+ method,
+ path: pathname,
+ headers: hostHeader ? { Host: hostHeader } : undefined,
+ }, (response) => {
+ let body = '';
+ response.setEncoding('utf8');
+ response.on('data', (chunk) => { body += chunk; });
+ response.on('end', () => resolve({ status: response.statusCode, body, headers: response.headers }));
+ });
+ request.on('error', reject);
+ request.end();
+ });
+}
+
+test('preview: rejects destructive or unsupported startup targets before watching', async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-startup-'));
+ const input = path.join(tmp, 'diagram.json');
+ fs.writeFileSync(input, '{}');
+ await assert.rejects(
+ startPreview({ type: 'architecture', input, output: input, open: false }),
+ /must not replace its JSON input/i,
+ );
+ await assert.rejects(
+ startPreview({ type: 'mindmap', input, output: path.join(tmp, 'out.html'), open: false }),
+ /Unknown diagram type/i,
+ );
+ await assert.rejects(
+ startPreview({ type: 'architecture', input, output: path.join(tmp, 'out.html'), quality: 'pretty', open: false }),
+ /Unknown quality profile/i,
+ );
+
+ const realDirectory = path.join(tmp, 'real');
+ const linkedDirectory = path.join(tmp, 'linked');
+ fs.mkdirSync(realDirectory);
+ fs.symlinkSync(realDirectory, linkedDirectory, 'dir');
+ await assert.rejects(
+ startPreview({
+ type: 'architecture',
+ input: path.join(realDirectory, 'future.json'),
+ output: path.join(linkedDirectory, 'future.json'),
+ open: false,
+ }),
+ /must not replace its JSON input/i,
+ );
+ assert.deepEqual(fs.readdirSync(tmp).filter((name) => name.startsWith('.archify-preview-')), []);
+});
+
+test('preview: invalid candidates preserve the last verified artifact and repair automatically', { timeout: 30000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-last-good-'));
+ const input = path.join(tmp, 'diagram.architecture.json');
+ const output = path.join(tmp, 'diagram.html');
+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));
+ source.meta.title = 'Last Good One';
+ fs.writeFileSync(input, JSON.stringify(source));
+
+ const preview = await startPreview({
+ type: 'architecture',
+ input,
+ output,
+ quality: 'showcase',
+ open: false,
+ debounceMs: 60,
+ pollMs: 80,
+ });
+
+ try {
+ const first = await waitForState(preview.url, (state) => state.status === 'verified' && state.revision === 1, 'first revision did not verify');
+ assert.equal(first.generation, 1);
+ assert.equal(first.lastVerified.sha256, sha256(output));
+ const firstSha = sha256(output);
+ const firstArtifact = await (await fetch(new URL('/artifact.html', preview.url))).text();
+ assert.match(firstArtifact, /Last Good One/);
+
+ fs.rmSync(input);
+ const missing = await waitForState(preview.url, (state) => state.status === 'needs-fix' && state.generation === 2, 'deleted source did not report failure');
+ assert.equal(missing.failure.stage, 'input');
+ assert.equal(missing.revision, 1);
+ assert.equal(sha256(output), firstSha, 'deleted input replaced the last verified output');
+
+ fs.writeFileSync(input, '{"meta":');
+ const failed = await waitForState(preview.url, (state) => state.status === 'needs-fix' && state.generation === 3, 'invalid source did not report failure');
+ assert.equal(failed.revision, 1);
+ assert.equal(failed.failure.stage, 'input');
+ assert.match(failed.failure.message, /Could not read delivery input/);
+ assert.doesNotMatch(JSON.stringify(failed), new RegExp(input.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')));
+ assert.equal(sha256(output), firstSha, 'invalid input replaced the last verified output');
+ assert.equal(await (await fetch(new URL('/artifact.html', preview.url))).text(), firstArtifact);
+
+ source.components[0].unexpected = true;
+ fs.writeFileSync(input, JSON.stringify(source));
+ const schemaFailed = await waitForState(preview.url, (state) => state.status === 'needs-fix' && state.generation === 4, 'schema failure did not report render stage');
+ assert.equal(schemaFailed.failure.stage, 'render');
+ assert.match(schemaFailed.failure.message, /\/components\/0.*additional properties/i);
+ assert.doesNotMatch(schemaFailed.failure.message, /file:\/\/|\/Users\/|node:internal/);
+ assert.equal(sha256(output), firstSha, 'schema failure replaced the last verified output');
+
+ delete source.components[0].unexpected;
+ source.meta.title = 'Verified Repair';
+ source.components[0].label = 'Repaired Browser';
+ fs.writeFileSync(input, JSON.stringify(source));
+ const repaired = await waitForState(preview.url, (state) => state.status === 'verified' && state.revision === 2, 'repaired source did not publish');
+ assert.equal(repaired.generation, 5);
+ assert.notEqual(repaired.lastVerified.sha256, firstSha);
+ const repairedArtifact = await (await fetch(new URL('/artifact.html', preview.url))).text();
+ assert.match(repairedArtifact, /Verified Repair/);
+ assert.match(repairedArtifact, /Repaired Browser/);
+ assert.equal(repaired.lastVerified.sha256, sha256(output));
+
+ const page = await rawRequest(preview.url);
+ assert.equal(page.status, 200);
+ assert.match(page.body, /Archify Live Preview/);
+ assert.match(page.body, /<summary role="button" aria-controls="diagnostic-panel">View diagnostic<\/summary>/);
+ assert.match(page.headers['content-security-policy'], /default-src 'none'/);
+ const script = page.body.match(/<script>\n([\s\S]*?)\n <\/script>/)?.[1];
+ assert.ok(script, 'preview shell script missing');
+ assert.doesNotThrow(() => new vm.Script(script));
+ assert.equal((await rawRequest(preview.url, { method: 'POST' })).status, 405);
+ assert.equal((await rawRequest(preview.url, { pathname: '/../../etc/passwd' })).status, 404);
+ assert.equal((await rawRequest(preview.url, { hostHeader: 'example.com' })).status, 403);
+ } finally {
+ await preview.stop();
+ }
+
+ await assert.rejects(fetch(preview.url));
+ assert.deepEqual(fs.readdirSync(tmp).filter((name) => name.startsWith('.archify-preview-')), []);
+});
+
+test('preview: content digests suppress identical writes and a burst publishes only its stable tail', { timeout: 30000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-burst-'));
+ const input = path.join(tmp, 'diagram.workflow.json');
+ const output = path.join(tmp, 'diagram.html');
+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/agent-tool-call.workflow.json'), 'utf8'));
+ const original = JSON.stringify(source);
+ fs.writeFileSync(input, original);
+ const preview = await startPreview({
+ type: 'workflow',
+ input,
+ output,
+ open: false,
+ debounceMs: 90,
+ pollMs: 70,
+ });
+
+ try {
+ await waitForState(preview.url, (state) => state.status === 'verified' && state.revision === 1, 'initial workflow did not verify');
+ fs.writeFileSync(input, original);
+ await new Promise((resolve) => setTimeout(resolve, 350));
+ let state = await stateAt(preview.url);
+ assert.equal(state.generation, 1);
+ assert.equal(state.revision, 1);
+
+ fs.writeFileSync(input, JSON.stringify(source, null, 2));
+ state = await waitForState(preview.url, (candidate) => candidate.status === 'verified' && candidate.generation === 2, 'semantically identical source did not settle');
+ assert.equal(state.revision, 1, 'identical artifact bytes triggered a browser revision');
+
+ for (let index = 0; index < 8; index += 1) {
+ source.meta.title = `Burst ${index}`;
+ fs.writeFileSync(input, JSON.stringify(source));
+ await new Promise((resolve) => setTimeout(resolve, 12));
+ }
+ source.meta.title = 'Stable Tail';
+ fs.writeFileSync(input, JSON.stringify(source));
+
+ state = await waitForState(preview.url, (candidate) => candidate.status === 'verified' && candidate.revision === 2, 'stable burst tail did not verify');
+ assert.equal(state.generation, 3);
+ const artifact = await (await fetch(new URL('/artifact.html', preview.url))).text();
+ assert.match(artifact, /Stable Tail/);
+ assert.doesNotMatch(artifact, /Burst 7/);
+ } finally {
+ await preview.stop();
+ }
+});
+
+test('preview: a superseded slow candidate can never become a published revision', { timeout: 30000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-latest-wins-'));
+ const input = path.join(tmp, 'diagram.json');
+ const output = path.join(tmp, 'diagram.html');
+ const deliveryCli = path.join(tmp, 'fake-delivery.mjs');
+ fs.writeFileSync(deliveryCli, `
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+const [, , input, output] = process.argv.slice(2);
+const source = JSON.parse(fs.readFileSync(input, 'utf8'));
+await new Promise((resolve) => setTimeout(resolve, source.title === 'Slow Old' ? 550 : 40));
+const artifact = Buffer.from('<!doctype html><title>' + source.title + '</title><svg></svg>');
+fs.writeFileSync(output, artifact);
+console.log(JSON.stringify({
+ ok: true,
+ artifact: { sha256: createHash('sha256').update(artifact).digest('hex'), bytes: artifact.byteLength },
+ validation: { checksPassed: 1, checkCount: 1, compositionProfile: 'showcase', compositionStatus: 'pass' }
+}));
+`);
+ fs.writeFileSync(input, JSON.stringify({ title: 'Slow Old' }));
+
+ const preview = await startPreview({
+ type: 'architecture',
+ input,
+ output,
+ open: false,
+ debounceMs: 25,
+ pollMs: 40,
+ deliveryCli,
+ });
+ try {
+ await waitForState(preview.url, (state) => state.status === 'checking' && state.generation === 1, 'slow generation did not start');
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ fs.writeFileSync(input, JSON.stringify({ title: 'Fast New' }));
+ const state = await waitForState(preview.url, (candidate) => candidate.status === 'verified' && candidate.generation === 2, 'latest generation did not publish');
+ assert.equal(state.revision, 1, 'superseded generation was published before the latest one');
+ const artifact = await (await fetch(new URL('/artifact.html', preview.url))).text();
+ assert.match(artifact, /Fast New/);
+ assert.doesNotMatch(artifact, /Slow Old/);
+ assert.equal(fs.readFileSync(output, 'utf8'), artifact);
+ } finally {
+ await preview.stop();
+ }
+});
+
+test('preview: each delivery reads the immutable bytes bound to its observed digest', { timeout: 30000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-snapshot-'));
+ const input = path.join(tmp, 'diagram.json');
+ const output = path.join(tmp, 'diagram.html');
+ const deliveryCli = path.join(tmp, 'snapshot-delivery.mjs');
+ const readMarker = path.join(tmp, 'delivery-read.txt');
+ fs.writeFileSync(deliveryCli, `
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+const [, , input, output] = process.argv.slice(2);
+await new Promise((resolve) => setTimeout(resolve, 120));
+const source = JSON.parse(fs.readFileSync(input, 'utf8'));
+fs.writeFileSync(${JSON.stringify(readMarker)}, source.title);
+await new Promise((resolve) => setTimeout(resolve, 180));
+const artifact = Buffer.from('<!doctype html><title>' + source.title + '</title><svg></svg>');
+fs.writeFileSync(output, artifact);
+console.log(JSON.stringify({
+ ok: true,
+ artifact: { sha256: createHash('sha256').update(artifact).digest('hex'), bytes: artifact.byteLength },
+ validation: { checksPassed: 1, checkCount: 1, compositionProfile: 'showcase', compositionStatus: 'pass' }
+}));
+`);
+ fs.writeFileSync(input, JSON.stringify({ title: 'Source A' }));
+
+ const preview = await startPreview({
+ type: 'architecture',
+ input,
+ output,
+ open: false,
+ debounceMs: 10,
+ pollMs: 5000,
+ watch: false,
+ deliveryCli,
+ });
+ try {
+ await waitForState(preview.url, (state) => state.status === 'checking' && state.generation === 1, 'snapshot generation did not start');
+ fs.writeFileSync(input, JSON.stringify({ title: 'Source B' }));
+ const markerStarted = Date.now();
+ while (!fs.existsSync(readMarker) && Date.now() - markerStarted < 3000) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ assert.ok(fs.existsSync(readMarker), 'fake delivery never read its generation input');
+ fs.writeFileSync(input, JSON.stringify({ title: 'Source A' }));
+
+ const state = await waitForState(preview.url, (candidate) => candidate.status === 'verified' && candidate.revision === 1, 'snapshot generation did not verify');
+ assert.equal(state.generation, 1, 'an unobserved A → B → A edit started a second generation');
+ assert.equal(fs.readFileSync(readMarker, 'utf8'), 'Source A');
+ assert.match(fs.readFileSync(output, 'utf8'), /Source A/);
+ assert.doesNotMatch(fs.readFileSync(output, 'utf8'), /Source B/);
+ } finally {
+ await preview.stop();
+ }
+});
+
+test('preview: commit rechecks the live digest when watcher and poll have not seen a newer save', { timeout: 10000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-commit-race-'));
+ const input = path.join(tmp, 'diagram.json');
+ const output = path.join(tmp, 'diagram.html');
+ const deliveryCli = path.join(tmp, 'commit-race-delivery.mjs');
+ fs.writeFileSync(deliveryCli, `
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+const [, , input, output] = process.argv.slice(2);
+const source = JSON.parse(fs.readFileSync(input, 'utf8'));
+await new Promise((resolve) => setTimeout(resolve, source.title === 'Prior Good' ? 30 : 260));
+const artifact = Buffer.from('<!doctype html><title>' + source.title + '</title><svg></svg>');
+fs.writeFileSync(output, artifact);
+console.log(JSON.stringify({
+ ok: true,
+ artifact: { sha256: createHash('sha256').update(artifact).digest('hex'), bytes: artifact.byteLength },
+ validation: { checksPassed: 1, checkCount: 1, compositionProfile: 'showcase', compositionStatus: 'pass' }
+}));
+`);
+ fs.writeFileSync(input, JSON.stringify({ title: 'Prior Good' }));
+
+ const preview = await startPreview({
+ type: 'architecture',
+ input,
+ output,
+ open: false,
+ debounceMs: 10,
+ pollMs: 800,
+ watch: false,
+ deliveryCli,
+ });
+ try {
+ await waitForState(preview.url, (state) => state.status === 'verified' && state.revision === 1, 'prior good revision did not verify');
+ const priorArtifact = fs.readFileSync(output, 'utf8');
+ fs.writeFileSync(input, JSON.stringify({ title: 'Intermediate A' }));
+ await waitForState(preview.url, (state) => state.status === 'checking' && state.generation === 2, 'intermediate generation did not start');
+ fs.writeFileSync(input, JSON.stringify({ title: 'Current B' }));
+
+ await new Promise((resolve) => setTimeout(resolve, 340));
+ assert.equal(fs.readFileSync(output, 'utf8'), priorArtifact, 'superseded intermediate bytes replaced the prior last-good output');
+ const pending = await stateAt(preview.url);
+ assert.equal(pending.revision, 1, 'superseded intermediate bytes advanced the browser revision');
+
+ const current = await waitForState(preview.url, (state) => state.status === 'verified' && state.generation === 3, 'current generation did not verify');
+ assert.equal(current.revision, 2);
+ assert.match(fs.readFileSync(output, 'utf8'), /Current B/);
+ assert.doesNotMatch(fs.readFileSync(output, 'utf8'), /Intermediate A/);
+ } finally {
+ await preview.stop();
+ }
+});
+
+test('preview: stopping drains an active delivery without publishing it', { timeout: 30000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-stop-'));
+ const input = path.join(tmp, 'diagram.json');
+ const output = path.join(tmp, 'diagram.html');
+ const deliveryCli = path.join(tmp, 'slow-delivery.mjs');
+ const prior = '<!doctype html><title>Prior verified artifact</title>';
+ fs.writeFileSync(output, prior);
+ fs.writeFileSync(input, JSON.stringify({ title: 'Do not publish after stop' }));
+ fs.writeFileSync(deliveryCli, `
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+const [, , , output] = process.argv.slice(2);
+await new Promise((resolve) => setTimeout(resolve, 450));
+const artifact = Buffer.from('<!doctype html><title>Late candidate</title><svg></svg>');
+fs.writeFileSync(output, artifact);
+console.log(JSON.stringify({
+ ok: true,
+ artifact: { sha256: createHash('sha256').update(artifact).digest('hex'), bytes: artifact.byteLength },
+ validation: { checksPassed: 1, checkCount: 1, compositionProfile: 'showcase', compositionStatus: 'pass' }
+}));
+`);
+
+ const preview = await startPreview({
+ type: 'architecture',
+ input,
+ output,
+ open: false,
+ debounceMs: 10,
+ pollMs: 100,
+ deliveryCli,
+ });
+ await waitForState(preview.url, (state) => state.status === 'checking' && state.generation === 1, 'slow stop candidate did not start');
+ await new Promise((resolve) => setTimeout(resolve, 90));
+ const stoppedAt = Date.now();
+ await preview.stop();
+ assert.ok(Date.now() - stoppedAt >= 250, 'preview did not drain the active delivery');
+ assert.equal(fs.readFileSync(output, 'utf8'), prior);
+ assert.deepEqual(fs.readdirSync(tmp).filter((name) => name.startsWith('.archify-preview-')), []);
+});
+
+test('preview: stopping has a bounded kill path for a delivery that never exits', { timeout: 5000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-hung-stop-'));
+ const input = path.join(tmp, 'diagram.json');
+ const output = path.join(tmp, 'diagram.html');
+ const deliveryCli = path.join(tmp, 'hung-delivery.mjs');
+ const prior = '<!doctype html><title>Keep me</title>';
+ fs.writeFileSync(input, JSON.stringify({ title: 'Never completes' }));
+ fs.writeFileSync(output, prior);
+ fs.writeFileSync(deliveryCli, `
+process.on('SIGTERM', () => {});
+setInterval(() => {}, 1000);
+`);
+
+ const preview = await startPreview({
+ type: 'architecture',
+ input,
+ output,
+ open: false,
+ debounceMs: 10,
+ pollMs: 5000,
+ deliveryCli,
+ stopGraceMs: 80,
+ stopKillMs: 80,
+ });
+ await waitForState(preview.url, (state) => state.status === 'checking' && state.generation === 1, 'hung generation did not start');
+ await new Promise((resolve) => setTimeout(resolve, 80));
+ const stoppedAt = Date.now();
+ await preview.stop();
+ assert.ok(Date.now() - stoppedAt < 1000, 'hung delivery kept preview shutdown open');
+ assert.equal(fs.readFileSync(output, 'utf8'), prior);
+ await assert.rejects(fetch(preview.url));
+ assert.deepEqual(fs.readdirSync(tmp).filter((name) => name.startsWith('.archify-preview-')), []);
+});
+
+test('preview: checker failures keep their actionable detail instead of a generic stage only', { timeout: 30000 }, async () => {
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-preview-checker-'));
+ const input = path.join(tmp, 'diagram.json');
+ const output = path.join(tmp, 'diagram.html');
+ const deliveryCli = path.join(tmp, 'checker-failure.mjs');
+ fs.writeFileSync(input, '{}');
+ fs.writeFileSync(deliveryCli, `
+console.log(JSON.stringify({
+ ok: false,
+ stage: 'check',
+ error: 'Final artifact check failed; the previous artifact was preserved.',
+ checker: { checks: [{ name: 'single_svg', ok: false, details: ['found 2 <svg> blocks; expected exactly one'] }] }
+}));
+process.exitCode = 1;
+`);
+ const preview = await startPreview({
+ type: 'architecture',
+ input,
+ output,
+ open: false,
+ debounceMs: 10,
+ pollMs: 100,
+ deliveryCli,
+ });
+ try {
+ const state = await waitForState(preview.url, (candidate) => candidate.status === 'needs-fix', 'checker failure did not surface');
+ assert.equal(state.failure.stage, 'check');
+ assert.match(state.failure.message, /Final artifact check failed/);
+ assert.match(state.failure.message, /found 2 <svg> blocks; expected exactly one/);
+ } finally {
+ await preview.stop();
+ }
+});
+
+test('preview: all five typed renderers reach a verified first revision', { timeout: 60000 }, async () => {
+ 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 tmp = fs.mkdtempSync(path.join(os.tmpdir(), `archify-preview-${type}-`));
+ const input = path.join(tmp, example);
+ const output = path.join(tmp, `${type}.html`);
+ fs.copyFileSync(path.join(skillRoot, 'examples', example), input);
+ const preview = await startPreview({ type, input, output, open: false, debounceMs: 10, pollMs: 500 });
+ try {
+ const state = await waitForState(preview.url, (candidate) => candidate.status === 'verified', `${type} did not verify`);
+ assert.equal(state.revision, 1, type);
+ assert.equal(state.lastVerified.checksPassed, state.lastVerified.checkCount, type);
+ assert.equal(state.lastVerified.sha256, sha256(output), type);
+ } finally {
+ await preview.stop();
+ }
+ }
+});
diff --git a/docs/research-next-delight-slice-2026-07-22.md b/docs/research-next-delight-slice-2026-07-22.md
new file mode 100644
index 00000000..1a5c1d77
--- /dev/null
+++ b/docs/research-next-delight-slice-2026-07-22.md
@@ -0,0 +1,139 @@
+# Archify 下一增长切片研究:Last-Good Live Preview
+
+日期:2026-07-22(Asia/Shanghai)
+Archify 基线:`main@440e16d`;开放中的 [PR #44](https://github.com/tt-a1i/archify/pull/44) `@212639b` 已加入 opt-in Editable Source Capsule,五项远端检查全绿。**本建议只依赖 `main` 已有的 Atomic Delivery 与 Verified Open,可从 `main@440e16d` 独立落地,不以 PR #44 合并为前置。**
+上游快照:Fireworks `50c819d`、draw.io MCP `c3fcfa5`、GitDiagram `20eea55`、D2 `2446e24`、Markmap `99fc93e`、Mermaid Live Editor `f8836bb`。
+
+## 结论
+
+下一刀推荐 **Last-Good Live Preview(保留最后有效成品的本地实时预览)**:
+
+```bash
+archify preview <type> <input.json> \
+ [--quality standard|showcase] [--no-open]
+```
+
+它在仅监听 `127.0.0.1` 的随机端口打开一个桌面预览页;输入 JSON 变化后,先走 Archify 现有 renderer、composition gate 与 artifact checker,**只有完整通过才刷新浏览器**。非法或半写入输入只显示精确诊断,上一份已验证图继续留在画布上。修复后自动恢复。
+
+这是当前最合适的“好用 + 稳定 + 可展示”切片:D2 和 Mermaid Live Editor 已证明实时反馈是文本制图的核心体验;而 Archify 此前推迟 preview 所缺的 Atomic Delivery 与 Verified Open 前置条件现在已经在 `main` 具备。它改善的是作者从“改 JSON”到“看见可信结果”的循环,不再给已经很丰富的成品 Viewer 增加一个控件,也不读取或依赖 PR #44 的 Source Capsule。
+
+## 一手事实,不按 Star 数抄功能
+
+截至本次核验,GitHub API 显示 Fireworks 约 9.2k Star、draw.io MCP 约 4.9k、GitDiagram 约 15.8k、D2 约 24.7k、Markmap 约 13.0k、Mermaid Live Editor 约 6.7k。Star 只说明分发规模,不是采用整套架构的理由。
+
+### Fireworks:视觉宽度必须被共同质量合同约束
+
+- 当前 README 展示 12 种风格、四个工程语义 profile、14 类 UML 映射、offline HTML 和 GIF motion;真正可迁移的不是“12”这个数字,而是所有风格共用 geometry、text-fit、routing 与 motion gate。[README](https://github.com/yizhiyanhua-ai/fireworks-tech-graph/blob/50c819d68fd4fee330b3010988cd13e98b678d44/README.md#L43-L150) · [composition contract](https://github.com/yizhiyanhua-ai/fireworks-tech-graph/blob/50c819d68fd4fee330b3010988cd13e98b678d44/references/composition-quality-contract.md#L1-L75)
+- v1.2.0 保留静态 1920px PNG regression baselines,并在发布门中运行 12 风格、852 项 Chromium compatibility comparisons;可选 GIF 才引入 Chromium/FFmpeg,静态路径不被拖重。[v1.2.0 release](https://github.com/yizhiyanhua-ai/fireworks-tech-graph/releases/tag/v1.2.0)
+- Archify 已吸收这条纪律:三 preset 同拓扑、Semantic Sigils、有限 motion、确定性/感知式交付门。因此下一步不应再扩 style catalogue。
+
+### D2 与 Mermaid Live Editor:即时反馈是作者体验,但监听和重渲并不简单
+
+- D2 Quickstart 的 `d2 --watch in.d2 out.svg` 会打开浏览器,并随源文件变化 live reload。[D2 README](https://github.com/terrastruct/d2/blob/2446e247b6d7d5b9395a1ae8ad1e9c2641231035/README.md#L111-L124)
+- D2 的 watcher 并非一次简单 `fs.watch`:源码明确警告文件通知 API 容易丢事件,另做修改时间补查、写入 burst 合并、重试与 WebSocket 广播。[watch.go](https://github.com/terrastruct/d2/blob/2446e247b6d7d5b9395a1ae8ad1e9c2641231035/d2cli/watch.go#L211-L329) 浏览器端在收到新 SVG 时才替换画布,错误另行显示。[watch.js](https://github.com/terrastruct/d2/blob/2446e247b6d7d5b9395a1ae8ad1e9c2641231035/d2cli/static/watch.js#L1-L55)
+- Mermaid Live Editor把实时 edit/preview、SVG 保存和 viewer/edit links 列为核心功能。[README](https://github.com/mermaid-js/mermaid-live-editor/blob/f8836bb1540cf00090f529d776a958c557f24522/README.md#L4-L17) 其 E2E 明确测试复杂图延迟更新、非法输入不进入图而进入错误面。[diagramUpdate.spec.ts](https://github.com/mermaid-js/mermaid-live-editor/blob/f8836bb1540cf00090f529d776a958c557f24522/tests/diagramUpdate.spec.ts#L3-L43) 当前 open issue #1892 也记录了逐键重渲造成卡顿的用户信号,说明 debounce 是稳定要求而非锦上添花。[issue #1892](https://github.com/mermaid-js/mermaid-live-editor/issues/1892)
+
+### GitDiagram:代码图的高价值后续是可核验来源,不是 Mermaid 本身
+
+- GitDiagram 的第一阶段要求 architecture brief 中的核心组件绑定 1–3 个真实 repo-relative paths;第二阶段才产出有上限的 graph schema。[prompts.ts](https://github.com/ahmedkhaleel2004/gitdiagram/blob/20eea559377fe3f110ac630856351382c4b5fcab/src/server/generate/prompts.ts#L1-L50)
+- Graph node 的 `path` 会先对真实 file tree 校验;失败会把精确 feedback 送入有界重试。[graph validation](https://github.com/ahmedkhaleel2004/gitdiagram/blob/20eea559377fe3f110ac630856351382c4b5fcab/src/server/generate/graph.ts#L90-L175) 通过后,compiler 才生成指向 GitHub blob/tree 的 click link。[deterministic compiler](https://github.com/ahmedkhaleel2004/gitdiagram/blob/20eea559377fe3f110ac630856351382c4b5fcab/src/server/generate/graph.ts#L323-L409)
+- 这使“Node → source evidence”值得进入候选,但 Archify 若没有 revision、private repo 与 opt-in privacy 合同,不能只复制可点击外观。
+
+### draw.io MCP:编辑回路很顺,但其编辑器/格式矩阵不是 Archify 的边界
+
+- 官方仓库提供 inline MCP App、打开 draw.io 的 MCP Tool、原生 `.drawio` Skill + CLI、零安装项目指令四条路径;导出 SVG/PNG/PDF 时可以嵌入 XML,让产物继续在 draw.io 编辑。[README](https://github.com/jgraph/drawio-mcp/blob/c3fcfa5a7227e873e9ee51451b54c291d81b0099/README.md#L7-L71)
+- MCP App 的价值是把预览放到创作入口附近并保留 `Open in draw.io` 的后路。[MCP App README](https://github.com/jgraph/drawio-mcp/blob/c3fcfa5a7227e873e9ee51451b54c291d81b0099/mcp-app-server/README.md#L1-L43)
+- PR #44 已为 Archify 提供更符合自身 IR 的 Source JSON 交接;再做 draw.io XML round-trip 会形成第二套真相和编辑器依赖。
+
+### Markmap:小而可组合的 Viewer 值得学,mindmap/插件扩张不值得现在学
+
+- Markmap 把 view package 与 transform package 分开以降低不需要浏览器侧能力时的安装体积;toolbar 只保留 zoom、fit、recursive toggle 和 dark mode 等少量动作。[markmap-view README](https://github.com/markmap/markmap/blob/99fc93e6efd4a1df01260232d818fb57955d71df/packages/markmap-view/README.md) · [toolbar source](https://github.com/markmap/markmap/blob/99fc93e6efd4a1df01260232d818fb57955d71df/packages/markmap-toolbar/src/toolbar.tsx#L55-L117)
+- 它的 README 同时列出 VS Code、Vim/Neovim、Emacs 与 MCP 集成。[README](https://github.com/markmap/markmap/blob/99fc93e6efd4a1df01260232d818fb57955d71df/README.md#L1-L27) 对 Archify 的当前启发是保持 preview 与生成 artifact 解耦,不是立刻做 mindmap 或插件矩阵。
+
+## Archify 已有 / 缺口映射
+
+| 竞品中的有效模式 | Archify 当前状态 | 真正缺口 |
+|---|---|---|
+| Offline artifact、pan/zoom/theme/export | 已有,并且 Viewer 交互远多于竞品 | 无需继续叠普通 Viewer 控件 |
+| 多视觉语言 + 统一 gate | 已有 Classic / Signal Flow / Blueprint、Semantic Sigils、同拓扑回归 | 不缺第四 preset;缺的是让作者更快看到每次改动 |
+| Candidate → validate → verified output | 已有 schema/layout/composition/artifact checks、perceptual gate、Atomic Delivery | 无需另造成功语义;preview 应复用它 |
+| 交付后立即看见 | 已有 `deliver --open` | 只打开一次;源改变后仍要重复命令 |
+| 继续编辑 | PR #44 提供 opt-in Source JSON | 已解决 portable handoff;没有必要造全编辑器 |
+| 实时 edit/preview | 没有 | **本轮最清晰缺口** |
+| Node → verified repo evidence | 没有 | 高价值,但需要独立 provenance/privacy 合同 |
+| 平台/IDE 插件 | Skill + CLI + 静态 HTML 已足够分发 | 暂不扩平台矩阵 |
+
+## 候选切片
+
+| 候选 | 用户价值 | 稳定风险 | 必须限制的实现边界 | 可验证证据 | 决策 |
+|---|---|---|---|---|---|
+| **A. Last-Good Live Preview** | 改 JSON 后自动看到新图;坏输入时不丢上一张好图;明显缩短创作循环,也适合录制一个强 README 演示 | 中:常驻进程、端口、文件替换、重渲抖动、退出清理 | 新建 `preview` 命令;仅 `127.0.0.1` + 随机端口;内容摘要轮询/有界 debounce;复用既有 gate;成功才换 artifact;零依赖、无持久化、无 artifact 注入 | 五类型初始预览;有效→有效、有效→无效→修复;原子替换与快速 burst;旧 artifact SHA 保持;端口/进程/临时目录清理;真实浏览器无 console error | **现在做** |
+| **B. Repo Evidence Passport** | 聚焦一个节点即可打开或复制对应源码证据,让代码库图从“看起来对”升级到“可追证” | 中高:路径真实性、commit 漂移、私仓泄露、URL scheme、五 schema 迁移和交互冲突 | 必须 revision-pinned;repo-relative path 经真实 tree 校验;默认关闭;只进 Passport,不把 node click 改成导航;private/offline fail closed | 临时 repo 验证存在/不存在路径;commit 固定;恶意 URL/路径拒绝;默认 HTML/exports 不泄漏 | **下一阶段设计,不塞进 preview** |
+| **C. 一个工程语义合同:deployment ownership** | 云部署图能明确 Region/VPC/ownership 与跨边界机制,提升评审可信度 | 中低:规则过度拟合或让弱模型更难通过 | 只做 architecture 的一个 opt-in profile;验证现有字段能证明的事实;不添 renderer/type/style | 正反 fixture;每条错误指向确切实体和修复字段;legacy 图不变;Proof Lab 单场景证明 | **稳定型后续** |
+| **D. Machine Visual Evidence Bundle** | 将最终 PNG/关键 WebM 帧与 receipt 绑定,回归更可审计 | 中高:Chrome/字体/OS 像素差异、包体与运行时间 | 可选 CI/maintainer gate,不进 zero-install core;只存可复现实证,不发明审美分数 | 固定环境尺寸/像素非空/布局 bounds/有限 perceptual threshold;静态路径无浏览器仍可交付 | **先不做用户特性** |
+
+## 推荐切片的严格合同
+
+### 命令和状态
+
+1. `preview` 是独立的交互命令,不给 `deliver` 增加 `--watch`,避免把一次性交付变成长生命周期进程。
+2. 默认只监听 IPv4 loopback `127.0.0.1`,让操作系统分配空闲端口;不接受 `0.0.0.0`、LAN host、上传或公网 URL。
+3. `--no-open` 只用于无 GUI、自动化测试或用户已自行打开 URL;否则复用 Verified Open 的安全参数数组和失败回退。
+4. Preview shell 与被预览 artifact 分离。artifact 仍是普通自包含 Archify HTML;preview runtime、reload token、错误 banner、source path 和端口都不能写进 canonical HTML/SVG/图片/WebM。
+5. 首次输入合法时,只有 renderer + composition + checker 全部通过后才发布 revision 1。首次输入非法时仍打开 status shell,但不伪造空图或成功 receipt。
+6. 后续修改以**文件内容摘要**去重,不只信 mtime,也不依赖单次 `fs.watch` 事件;使用约 300–500ms 的有界稳定窗口吸收编辑器的 truncate/write/rename burst。
+7. 每一代只允许一个候选。新一代到达时让旧的未发布候选失效;迟到的旧结果永远不能覆盖更新结果。
+8. 候选在临时目录完成现有 render/check,成功后原子替换 preview 的 last-good artifact,再递增 revision。失败只更新诊断,不替换 iframe,不覆盖用户指定输出。
+9. 错误面必须报告 generation、stage 与当前 validator/checker 原文摘要,并明确 `Showing last verified revision N`;修复后自动清除。不要只显示红点或“render failed”。
+10. 页面刷新只发生于 verified revision 变化;相同 bytes、chmod、无关目录变化和失败重试不得让浏览器闪烁。
+11. `SIGINT` / `SIGTERM`、浏览器未打开、端口错误和输入删除都要有明确退出/等待语义;退出后 server、timer、child process 与临时目录必须归零。
+12. Preview 默认保持 Source Capsule 关闭;源码本来就在本机。不要把 PR #44 的 portable handoff 与本地创作循环混成一个默认隐私面。
+
+### 建议最小 UI
+
+- 画布占主位,直接 iframe/呈现最后一份 verified HTML。
+- 右上角只保留一个小状态:`Verified · rev 3`、`Checking…` 或 `Needs fix · showing rev 3`。
+- 失败展开一个可复制诊断区;不弹 modal,不遮住整张上一份好图。
+- 不做源代码编辑器、文件树、terminal、drag/drop、history timeline 或多文件 workspace。
+- 不开展移动端专项;桌面 1280×720 是主要验收面。
+
+## 验收证据
+
+### 自动化
+
+1. 五种 diagram type 均能启动 preview 并拿到 revision 1;artifact 通过现有 checker。
+2. 一份合法输入修改为另一份合法输入:只有新候选完整通过后 revision 才增加,浏览器读取的新 title/node 与输入一致。
+3. 合法 → JSON 半写入 → schema 错误 → showcase composition 错误:每次都保持上一份 artifact 的精确 SHA-256,status 指向真实 stage。
+4. 修复失败输入后自动恢复,错误清空且只增加一次 revision。
+5. 10 次快速写入、truncate/write、同名临时文件 rename、mtime 相同但 bytes 不同,都只发布最终稳定内容;相同 bytes 不重复刷新。
+6. 并发慢候选被更新候选取代时,迟到结果无法 commit。
+7. Server 仅接受固定 GET/HEAD endpoints;拒绝 traversal、任意文件读取、写请求和外部 Host;响应不回显绝对 source path。
+8. `--no-open`、opener 失败、随机端口冲突、输入删除/恢复、SIGINT/SIGTERM 和异常退出均无悬挂进程或 temp residue。
+9. 从不含 `node_modules`/tests 的 ZIP Skill 副本运行,零依赖合同保持。
+10. 全量 `npm test`、WebM/Share Card/Route Share Card smoke、ZIP freshness、package smoke 与 `git diff --check` 全绿。
+
+### 内置浏览器
+
+1. 用一个真实 architecture 或 workflow fixture 启动 preview,确认第一次出现的是 verified artifact,不是闪烁的空壳。
+2. 改 title、一个 node label 与一条 route,观察一次有界刷新;确认主题、Style、Finder、Focus、Route、Presentation 与 Export 仍可用。
+3. 写入非法 JSON 和会触发 showcase gate 的合法 JSON,确认旧图不消失、错误可读且没有 console error。
+4. 修复后确认自动恢复,状态回到 `Verified`,新图与输入吻合。
+5. 验证 preview shell、错误状态和 reload revision 不进入 SVG/PNG/WebM/Share Card/Source JSON。
+6. 关闭进程后 URL 立即不可用,临时目录清空;不做移动端专项。
+
+## 明确拒绝或推迟
+
+- **第四/第五 preset、12-style 追数、vendor icon catalogue**:Archify 已有三种同拓扑视觉语言和 sigils;新增目录会成倍扩大主题、导出、动效与截图矩阵,却不缩短创作循环。
+- **全量 UML / mindmap 类型扩张**:当前五种 typed renderer 的价值是清晰语义和强 gate;不要把竞品“类型数量”当增长 KPI。
+- **WYSIWYG、拖拽、draw.io XML round-trip、Open in editor**:会把 generator + viewer 变成第二个通用编辑器,并产生双格式真相。PR #44 的 opt-in Source JSON 已是更小、更真实的可编辑交接。
+- **Mermaid 式压缩源码 share URL / 托管保存**:需要 hosted decoder、URL/XSS/长度、隐私与持久化合同;Archify 的一个 HTML 文件已经是更强的离线分享边界。
+- **公网 repo ingestion / GitDiagram 克隆**:会引入 provider 成本、token、quota、缓存、私仓凭据和滥用面。Repo Evidence Passport 可在本地、revision-pinned 的小合同中另做。
+- **Obsidian、VS Code、浏览器扩展、MCP 平台矩阵**:Markmap/draw.io 已证明分发宽度有价值,但现在会把维护预算从核心首次成功路径分散出去。
+- **依赖原生 file watcher 或 WebSocket 作为唯一真相**:D2 源码已经展示其复杂度。Archify 应用内容摘要轮询 + debounce + generation token,server 只做本地预览,不引入新 npm 依赖。
+- **独立移动端产品**:保持现有 contained fallback;preview 是桌面创作工具,不把手机布局加入验收门。
+
+## 为什么现在做
+
+此前不做 watch 是对的:当时没有统一 commit point、last-known-good 语义和安全 opener。现在 `main@440e16d` 的 [Atomic Delivery、Verified Open 与当前 Viewer 合同](../ROADMAP.md) 已经建立。Live Preview 可以只做 orchestration:监听输入、调用既有可信管线、成功才刷新,坏候选永不污染成品。PR #44 的 portable editing handoff 与本切片正交;无论它先合并、后合并或暂缓,preview 合同都不变。
+
+这比新增另一个 Viewer “亮点”更能让用户喜欢:第一次成功更快,弱模型或人工微调的每轮反馈更短,演示也更直观;同时它不改变 JSON IR、五 renderer、布局、美术、导出或分享边界。下一阶段再评估 Repo Evidence Passport,前提是先写清 revision、真实路径、private repo 与 opt-in privacy 合同。