Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.
HTML agent-skillsai-agentsarchitecture-diagramclaude-codeclaude-skillscodexcoding-agentsdeepseek-harnessdeveloper-toolsdiagramsdiagrams-as-codedsh-pluginflowchartllmmermaidopencodesequence-diagramsoftware-architecturesystem-designvisualization
feat: add structured repair receipts
tt-a1ie7e22a1e3243
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 86d47a18..550c87f8 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+- **Structured Repair Receipt.** `archify validate --json` and `archify deliver --json` now return exactly one versioned JSON object on both success and failure. Each failure carries additive `diagnostics[]` with a stable rule code, severity, exact subject, measured evidence, and only renderer-supported repairs for input parsing, schema, repository evidence, Clean Flow, composition, artifact checks, and delivery stages; unclassified internal failures are explicit and offer no guessed fix. Human CLI and Last-Good Preview format the same facts without exposing Node stacks, while Atomic Verified Delivery still removes the candidate and preserves the prior artifact byte-for-byte. Five-mode schema fixtures, validate/deliver Clean Flow parity, evidence failure, checker failure, installed-skill smoke, and the existing two-round perceptual boundary are covered. No auto-fix, LLM call, retry expansion, schema/IR change, renderer geometry change, viewer panel, dependency, hosted service, telemetry, or mobile surface was added.- **Reach Share Card.** An active Upstream or Downstream Authored Reachability result now reveals one contextual **Export → Reach Share Card** item. It copies the already resolved origin, direction, stable node/edge identity, minimum depths, and maximum hops without rerunning traversal, then applies only static `data-share-reach-*` decoration to a finite canonical clone before producing a 1200×630 PNG. The full diagram remains as dimmed context; the header names `Authored upstream/downstream`, origin, nodes, links, and hops; upstream uses repository violet, downstream uses proof green, and Blueprint stays filter-free. Missing, empty, stale, duplicate, conflicting, or tampered state fails closed. The truthful receipt uses `format=share-card`, `variant=reach`, `canonical=false`, and a dedicated reach-state-clean proof. Ordinary exports remain canonical. This is download-only and adds no schema, parser, traversal, format, panel, toolbar control, dependency, network, storage, hosted service, geometry change, or mobile product surface.- **Authored Reachability.** A focused node's existing Semantic Passport now offers compact `Upstream` and `Downstream` actions that reveal the deterministic transitive closure of authored relationships, report matched nodes, links, and maximum hops, and round-trip through `#focus=<id>&reach=upstream|downstream` plus Copy link. The viewer deduplicates parallel SVG fragments by stable edge key, terminates cycles, preserves authored DOM order, supports keyboard and browser-history navigation, and remains legible across Classic, Signal Flow, Blueprint, dark, and light. SVG, raster, Share Card, WebM backgrounds, and print strip the temporary state. This is explicitly authored reachability—not blast radius, breakage, repository impact, or runtime causality—and adds no parser, crawler, schema, panel, permanent toolbar action, dependency, hosted runtime, storage, geometry change, or mobile product surface.- **Verified Source Beacons.** Evidence-backed Architecture nodes now show one quiet viewer-only `SRC n` marker derived exclusively from the already verified repository payload. The node remains the single focus target and opens the existing Semantic Passport; screen-reader labels disclose the count, focus/routes/stories/guided views keep one coherent node state, and Classic, Signal Flow, Blueprint, dark, and light reuse the same proof-green vocabulary. Ordinary artifacts remain unchanged, while SVG, raster, Share Card, and WebM backgrounds strip the marker and restore the canonical node label. No parser, crawler, inferred relationship, panel, toolbar control, schema expansion, dependency, hosted runtime, or mobile product surface was added.diff --git a/README.md b/README.mdindex 72a63e04..57754fc4 100644--- a/README.md+++ b/README.md@@ -152,6 +152,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.+- **Failures come with a repair receipt** — `validate --json` and `deliver --json` return stable rule codes, the exact subject, measured evidence, and only supported repair controls instead of a Node stack or an unstructured retry guess.- **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, upstream/downstream reach, exact routes, role comparison, and stories reuse authored nodes and relationships instead of inventing topology or claiming runtime impact.- **Source evidence, only when requested** — Evidence-backed Architecture nodes mark themselves `SRC n` and open Git-verified files and line ranges pinned to one public commit; ordinary artifacts stay source-free.@@ -164,7 +165,7 @@ Archify is not a general-purpose drawing editor or a Mermaid theme. It turns tec| Step | What happens ||---|---|| **Generate** | The agent creates typed JSON IR from your description. |-| **Validate** | Bundled validators and layout rules check the source. |+| **Validate** | Bundled validators and layout rules check the source; failures identify the exact local repair in machine-readable JSON. || **Preview (optional)** | A loopback-only desktop session watches one source and reloads only verified revisions; failures keep the last-good artifact. || **Deliver** | A same-directory candidate is rendered and checked; only a passing artifact atomically replaces the target, then optional `--open` launches that exact file. || **Iterate** | The agent updates the source while unrelated structure stays stable. |@@ -185,6 +186,8 @@ node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmUse `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.+On failure, `validate --json` and `deliver --json` still emit exactly one JSON object. Read `diagnostics[]` and change only the named subject using its `supportedFixes`; do not rewrite the whole diagram or exceed the Skill's two focused correction rounds. Deterministic diagnostics remain separate from visual review.+Optional motion and presentation styling are explicit:```jsondiff --git a/README_EN.md b/README_EN.mdindex 72a63e04..57754fc4 100644--- a/README_EN.md+++ b/README_EN.md@@ -152,6 +152,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.+- **Failures come with a repair receipt** — `validate --json` and `deliver --json` return stable rule codes, the exact subject, measured evidence, and only supported repair controls instead of a Node stack or an unstructured retry guess.- **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, upstream/downstream reach, exact routes, role comparison, and stories reuse authored nodes and relationships instead of inventing topology or claiming runtime impact.- **Source evidence, only when requested** — Evidence-backed Architecture nodes mark themselves `SRC n` and open Git-verified files and line ranges pinned to one public commit; ordinary artifacts stay source-free.@@ -164,7 +165,7 @@ Archify is not a general-purpose drawing editor or a Mermaid theme. It turns tec| Step | What happens ||---|---|| **Generate** | The agent creates typed JSON IR from your description. |-| **Validate** | Bundled validators and layout rules check the source. |+| **Validate** | Bundled validators and layout rules check the source; failures identify the exact local repair in machine-readable JSON. || **Preview (optional)** | A loopback-only desktop session watches one source and reloads only verified revisions; failures keep the last-good artifact. || **Deliver** | A same-directory candidate is rendered and checked; only a passing artifact atomically replaces the target, then optional `--open` launches that exact file. || **Iterate** | The agent updates the source while unrelated structure stays stable. |@@ -185,6 +186,8 @@ node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tmUse `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.+On failure, `validate --json` and `deliver --json` still emit exactly one JSON object. Read `diagnostics[]` and change only the named subject using its `supportedFixes`; do not rewrite the whole diagram or exceed the Skill's two focused correction rounds. Deterministic diagnostics remain separate from visual review.+Optional motion and presentation styling are explicit:```jsondiff --git a/README_ZH.md b/README_ZH.mdindex 0fc77463..5392a998 100644--- a/README_ZH.md+++ b/README_ZH.md@@ -148,6 +148,7 @@ Architecture 示例:[`Web App`](examples/web-app.html) · [`Archify Pipeline`]- **用布局判断代替通用自动布局** —— Agent 根据故事选择层级、留白、线路和强调关系;共享的自动端点会确定性展开,不再让多支箭头堆在同一个中点。- **Typed JSON IR** —— 每种 Renderer 模式都有 Schema 和可复现的源文件。- **原子交付前校验** —— Schema、布局、HTML/SVG、线路和标签到其他路径的净空检查必须全部通过,Showcase 成品才会替换上一份可信结果。+- **失败也有结构化修复回执** —— `validate --json` 和 `deliver --json` 会返回稳定规则码、准确对象、测量证据和真正支持的修复旋钮,不再让 Agent 从 Node 堆栈或自由文本里猜。- **保留最后好图的实时预览** —— 可选桌面循环只监听一个 JSON;只有最新候选通过全部门禁才刷新,半写入或无效保存时继续显示上一份验证成品。- **交互不编造拓扑** —— 聚焦、上下游可达范围、精确路径、角色对比和故事都复用作者定义的节点与关系,也不把图上可达误报成真实运行时影响。- **只在需要时附源码证据** —— 有证据的 Architecture 节点会显示 `SRC n`,并可打开由 Git 校验、固定到公开 commit 的文件与行号;普通成品不携带源码信息。@@ -160,7 +161,7 @@ Archify 不是通用绘图编辑器,也不是 Mermaid 主题;它负责把技| 步骤 | 发生什么 ||---|---|| **生成** | Agent 根据描述创建 Typed JSON IR。 |-| **校验** | 内置 Validator 和布局规则检查源文件。 |+| **校验** | 内置 Validator 和布局规则检查源文件;失败时用机器可读 JSON 指出准确的局部修复。 || **预览(可选)** | 仅 loopback 的桌面会话监听一个源文件,只刷新验证版本;失败时保留最后好图。 || **交付** | 在目标同目录生成并检查候选;只有通过门禁的结果才原子替换目标文件,随后可选用 `--open` 打开这个确切成品。 || **迭代** | Agent 修改源文件,不干扰无关结构。 |@@ -181,6 +182,8 @@ node bin/archify.mjs deliver workflow examples/agent-tool-call.workflow.json /tm`deliver --open` 适合一次性的本地交互交付。它默认关闭,并且只在验证成品原子提交后执行;系统无法打开时,交付仍保持成功,JSON 只写 stdout,stderr 会给出可手动打开的绝对路径。+失败时,`validate --json` 和 `deliver --json` 仍然只输出一个 JSON 对象。读取 `diagnostics[]`,只修改其中 `subject` 指向的对象,并使用 `supportedFixes` 列出的修复方式;不要整图重写,也不要突破 Skill 最多两轮的聚焦修复上限。确定性诊断仍不等于视觉复核。+动态和演示样式需要显式选择:```jsondiff --git a/ROADMAP.md b/ROADMAP.mdindex e399d5f0..a38b9841 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -2,6 +2,8 @@As of v2.12.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, upstream/downstream Authored Reachability, 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, route-focused Route Share Card and authored-reach Reach Share Card variants, 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 stability slice adds Structured Repair Receipt across `validate --json`, `deliver --json`, and Last-Good Preview. A failed input, schema, repository-evidence check, Clean Flow or composition gate, artifact check, or delivery stage now returns one additive `schemaVersion: 1` object with stable `diagnostics[]`: rule code, severity, exact subject, measured evidence, and only supported repair controls. Renderer child processes emit a private structured boundary so the CLI never copies Node stacks into machine output; human mode formats the same facts, and unknown internal failures remain explicitly unclassified with no invented fix. Validate and deliver expose identical Clean Flow evidence, failed delivery still preserves the old artifact byte-for-byte, five modes share schema-subject coverage, and preview shows the bounded repair without leaking its private paths. This is a feedback protocol, not auto-layout or auto-fix: no LLM call, retry expansion, schema/IR change, geometry rewrite, viewer panel, dependency, hosted service, telemetry, or mobile surface was added.+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.zipindex d1f35406..8a5c983a 100644Binary files a/archify.zip and b/archify.zip differdiff --git a/archify/SKILL.md b/archify/SKILL.mdindex 6309528a..2f6be790 100644--- a/archify/SKILL.md+++ b/archify/SKILL.md@@ -80,12 +80,12 @@ 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.+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. Success and failure both produce exactly one JSON object. On failure, consume `diagnostics[]`: use the stable `code`, change only the named `subject`, verify the measured `evidence`, and choose only from `supportedFixes`. Never infer an unsupported field or rewrite the whole graph from the free-text `error`. Use `render` plus `check` separately only when diagnosing a candidate.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.+6. If any step fails, the repair receipt names the JSON path or subject, rule code, measured evidence, and supported fix (thresholds, valid ranges, which knob to change). Apply one local repair and re-run; never edit the renderer, never treat an empty `supportedFixes` list as permission to guess, and never exceed the two focused correction rounds below.-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.+Schema violations exit non-zero with path-prefixed messages like `/nodes/3 (id/label: "router") must NOT have additional properties`. In JSON mode the same fact is a `schema/<keyword>` diagnostic. Input, repository-evidence, shared Clean Flow, composition, artifact-check, and delivery failures use the same additive `schemaVersion: 1` repair contract; an `internal/unclassified` diagnostic has no supported repair and must be reported rather than guessed through. 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.Automatic Port Spread is a default renderer behavior for architecture, workflow, data-flow, and lifecycle diagrams. When two or more eligible automatic relationships share one node-side midpoint, assign deterministic, symmetric edge ports ordered by the opposite endpoint, while preserving a 16px corner gutter. It does not apply to sequence messages, a single relationship, or any relationship with explicit `via`, `channelX`, `channelY`, `labelAt`, or a non-`auto` route; authored geometry always wins. This is bounded endpoint separation, not a graph layout engine, and it must not change topology, schema, labels, presets, viewer state, or export behavior.diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjsindex 6147a665..8e459112 100755--- a/archify/bin/archify.mjs+++ b/archify/bin/archify.mjs@@ -94,13 +94,143 @@ function extractRepoRootArgs(args) {return { rest, repoRoot: repoRoot ? path.resolve(repoRoot) : undefined };}-function rendererEnv(quality, repoRoot) {+function rendererEnv(quality, repoRoot, diagnosticJson = false) {return {...(quality ? { ARCHIFY_QUALITY_PROFILE: quality } : {}),...(repoRoot ? { ARCHIFY_REPO_ROOT: repoRoot } : {}),+ ...(diagnosticJson ? { ARCHIFY_DIAGNOSTIC_FORMAT: 'json' } : {}),};}+function diagnostic({ code, message, subject = {}, evidence = {}, supportedFixes = [], severity = 'error' }) {+ return {+ code,+ severity,+ message,+ subject,+ evidence,+ supportedFixes,+ };+}++function inputDiagnostic(error, inputPath) {+ const isSyntax = error instanceof SyntaxError;+ return diagnostic({+ code: isSyntax ? 'input/json-parse' : 'input/read',+ message: isSyntax+ ? `Input JSON could not be parsed: ${error.message}`+ : `Input could not be read: ${error.message}`,+ subject: { input: inputPath },+ evidence: {+ ...(error?.code ? { systemCode: error.code } : {}),+ reason: error.message,+ },+ supportedFixes: [isSyntax+ ? 'repair the JSON syntax and run validation again'+ : 'provide one readable JSON input file'],+ });+}++function rendererFailure(result) {+ if (result.error) {+ return {+ error: 'Renderer process could not start.',+ diagnostics: [diagnostic({+ code: 'internal/renderer-process',+ message: 'Renderer process could not start.',+ evidence: { reason: result.error.message },+ })],+ };+ }+ try {+ const payload = JSON.parse((result.stderr || '').trim());+ if (payload?.ok === false && Array.isArray(payload.diagnostics) && payload.diagnostics.length) {+ return {+ error: payload.error || payload.diagnostics[0].message,+ diagnostics: payload.diagnostics,+ };+ }+ } catch {+ // The diagnostic boundary is intentionally fail-closed. Never copy a raw+ // Node stack into a machine receipt when a renderer exits unexpectedly.+ }+ return {+ error: 'Renderer failed before emitting a structured diagnostic.',+ diagnostics: [diagnostic({+ code: 'internal/unclassified',+ message: 'Renderer failed before emitting a structured diagnostic.',+ evidence: { exitCode: result.status ?? 1 },+ })],+ };+}++const COMPOSITION_CHECKS = new Set([+ 'label_route_clearance',+ 'relationship_crossings',+ 'relationship_corridors',+ 'container_border_runs',+ 'route_rhythm',+]);++const CHECK_FIXES = {+ single_svg: ['remove additional SVG roots so the artifact contains exactly one diagram SVG'],+ finite_svg: ['replace non-finite coordinates before rendering again'],+ orthogonal_arrows: ['use renderer-supported orthogonal routing controls'],+ legend_clearance: ['move the route or enlarge the viewBox so relationships do not enter the legend'],+};++const COMPOSITION_FIXES = {+ 'composition/proper-crossing': ['adjust route/via or channel coordinates so unrelated relationships use separate corridors'],+ 'composition/ambiguous-corridor': ['adjust route/via or channel coordinates so unrelated relationships do not visually merge'],+ 'composition/container-border-run': ['route across the frame perpendicularly through a clear opening'],+ 'composition/label-route-clearance': ['adjust labelAt, labelDx, labelDy, labelSegment, message y, or the other relationship route'],+ 'composition/micro-segment': ['move the route/channel/via point so every visible segment is at least 8px'],+ 'composition/short-interior-segment': ['move the route/channel/via point so every interior turn has at least 16px'],+};++function checkerDiagnostics(checker) {+ const diagnostics = [];+ for (const issue of checker?.composition?.issues || []) {+ if (issue.severity !== 'error') continue;+ const { severity, code, relationship, ...evidence } = issue;+ diagnostics.push(diagnostic({+ code,+ severity,+ message: `Final artifact failed ${code}.`,+ subject: relationship ? { relationship } : { check: 'composition' },+ evidence,+ supportedFixes: COMPOSITION_FIXES[code] || [],+ }));+ }+ for (const check of checker?.checks || []) {+ if (check.ok || COMPOSITION_CHECKS.has(check.name)) continue;+ diagnostics.push(diagnostic({+ code: `artifact/${check.name.replaceAll('_', '-')}`,+ message: (check.details || []).find(Boolean) || `Final artifact failed ${check.name}.`,+ subject: { check: check.name },+ evidence: { details: check.details || [] },+ supportedFixes: CHECK_FIXES[check.name] || [],+ }));+ }+ return diagnostics.length ? diagnostics : [diagnostic({+ code: 'artifact/check-failed',+ message: 'Final artifact check failed without a classified diagnostic.',+ subject: { check: 'unknown' },+ evidence: {},+ })];+}++function formatDiagnostics(error, diagnostics = []) {+ if (!diagnostics.length) return error;+ return [+ error,+ ...diagnostics.map((entry) => {+ const fix = entry.supportedFixes?.length ? ` Fix: ${entry.supportedFixes.join('; ')}.` : '';+ return `[${entry.code}] ${entry.message}${fix}`;+ }),+ ].join('\n');+}+function assertEvidenceType(type, repoRoot) {if (repoRoot && type !== 'architecture') {fail('--repo-root is currently supported for architecture diagrams only.');@@ -124,7 +254,7 @@ function commandRender(args) {if (result.status !== 0) exitFrom(result);}-function reportDeliveryFailure({ json, stage, type, input, output, error, status = 1, checker }) {+function reportDeliveryFailure({ json, stage, type, input, output, error, diagnostics = [], status = 1, checker }) {const receipt = {schemaVersion: 1,ok: false,@@ -134,10 +264,28 @@ function reportDeliveryFailure({ json, stage, type, input, output, error, statusinput,output,error,+ diagnostics,...(checker ? { checker } : {}),};if (json) console.log(JSON.stringify(receipt, null, 2));- else console.error(error);+ else console.error(formatDiagnostics(error, diagnostics));+ process.exitCode = status;+}++function reportValidateFailure({ json, stage, type, input, error, diagnostics = [], status = 1, checker }) {+ const receipt = {+ schemaVersion: 1,+ ok: false,+ command: 'validate',+ stage,+ type,+ input,+ error,+ diagnostics,+ ...(checker ? { checker } : {}),+ };+ if (json) console.log(JSON.stringify(receipt, null, 2));+ else console.error(formatDiagnostics(error, diagnostics));process.exitCode = status;}@@ -171,6 +319,7 @@ async function commandDeliver(args) {try {diagram = JSON.parse(fs.readFileSync(inputPath, 'utf8'));} catch (error) {+ const repair = inputDiagnostic(error, inputPath);reportDeliveryFailure({json,stage: 'input',@@ -178,6 +327,7 @@ async function commandDeliver(args) {input: inputPath,output: path.resolve(requestedOutput || `${type}.html`),error: `Could not read delivery input "${inputPath}": ${error.message}`,+ diagnostics: [repair],});return;}@@ -190,13 +340,21 @@ async function commandDeliver(args) {try {fs.mkdirSync(outputDirectory, { recursive: true });} catch (error) {+ const message = `Could not create delivery directory "${outputDirectory}": ${error.message}`;reportDeliveryFailure({json,stage: 'prepare',type,input: inputPath,output: outputPath,- error: `Could not create delivery directory "${outputDirectory}": ${error.message}`,+ error: message,+ diagnostics: [diagnostic({+ code: 'delivery/prepare-directory',+ message,+ subject: { outputDirectory },+ evidence: { ...(error?.code ? { systemCode: error.code } : {}), reason: error.message },+ supportedFixes: ['choose a writable output directory'],+ })],});return;}@@ -208,13 +366,21 @@ async function commandDeliver(args) {try {stagingDirectory = fs.mkdtempSync(path.join(outputDirectory, '.archify-delivery-'));} catch (error) {+ const message = `Could not create a delivery candidate beside "${outputPath}": ${error.message}`;reportDeliveryFailure({json,stage: 'prepare',type,input: inputPath,output: outputPath,- error: `Could not create a delivery candidate beside "${outputPath}": ${error.message}`,+ error: message,+ diagnostics: [diagnostic({+ code: 'delivery/prepare-candidate',+ message,+ subject: { output: outputPath },+ evidence: { ...(error?.code ? { systemCode: error.code } : {}), reason: error.message },+ supportedFixes: ['choose a writable output directory on the target filesystem'],+ })],});return;}@@ -223,18 +389,18 @@ async function commandDeliver(args) {try {const render = runNode([renderer, inputPath, candidatePath], {stdio: 'pipe',- env: rendererEnv(qualityArgs.quality, repoArgs.repoRoot),+ env: rendererEnv(qualityArgs.quality, repoArgs.repoRoot, true),});if (render.status !== 0) {- if (render.stderr) process.stderr.write(render.stderr);- if (render.stdout) process.stderr.write(render.stdout);+ const failure = rendererFailure(render);reportDeliveryFailure({json,stage: 'render',type,input: inputPath,output: outputPath,- error: (render.stderr || render.stdout || 'Renderer failed without a diagnostic.').trim(),+ error: failure.error,+ diagnostics: failure.diagnostics,status: render.status ?? 1,});return;@@ -259,6 +425,7 @@ async function commandDeliver(args) {input: inputPath,output: outputPath,error: 'Final artifact check failed; the previous artifact was preserved.',+ diagnostics: checkerDiagnostics(checker),status: check.status ?? 1,checker,});@@ -269,13 +436,20 @@ async function commandDeliver(args) {try {result = JSON.parse(check.stdout);} catch (error) {+ const message = `Could not parse the successful artifact-check receipt: ${error.message}`;reportDeliveryFailure({json,stage: 'receipt',type,input: inputPath,output: outputPath,- error: `Could not parse the successful artifact-check receipt: ${error.message}`,+ error: message,+ diagnostics: [diagnostic({+ code: 'delivery/receipt-invalid',+ message,+ subject: { output: outputPath },+ evidence: { reason: error.message },+ })],});return;}@@ -283,13 +457,20 @@ async function commandDeliver(args) {try {artifact = fs.readFileSync(candidatePath);} catch (error) {+ const message = `Could not read the verified delivery candidate: ${error.message}`;reportDeliveryFailure({json,stage: 'receipt',type,input: inputPath,output: outputPath,- error: `Could not read the verified delivery candidate: ${error.message}`,+ error: message,+ diagnostics: [diagnostic({+ code: 'delivery/candidate-unreadable',+ message,+ subject: { output: outputPath },+ evidence: { ...(error?.code ? { systemCode: error.code } : {}), reason: error.message },+ })],});return;}@@ -297,13 +478,20 @@ async function commandDeliver(args) {try {sourceEvidence = sourceEvidenceFromArtifact(artifact);} catch (error) {+ const message = `Could not read the repository evidence receipt: ${error.message}`;reportDeliveryFailure({json,stage: 'receipt',type,input: inputPath,output: outputPath,- error: `Could not read the repository evidence receipt: ${error.message}`,+ error: message,+ diagnostics: [diagnostic({+ code: 'delivery/evidence-receipt-invalid',+ message,+ subject: { output: outputPath },+ evidence: { reason: error.message },+ })],});return;}@@ -339,13 +527,21 @@ async function commandDeliver(args) {try {fs.renameSync(candidatePath, outputPath);} catch (error) {+ const message = `Could not commit verified delivery "${outputPath}": ${error.message}`;reportDeliveryFailure({json,stage: 'commit',type,input: inputPath,output: outputPath,- error: `Could not commit verified delivery "${outputPath}": ${error.message}`,+ error: message,+ diagnostics: [diagnostic({+ code: 'delivery/commit',+ message,+ subject: { output: outputPath },+ evidence: { ...(error?.code ? { systemCode: error.code } : {}), reason: error.message },+ supportedFixes: ['choose a replaceable file target on the same writable filesystem'],+ })],});return;}@@ -622,12 +818,20 @@ function commandValidate(args) {}const result = runNode([renderer, input, '/dev/null', '--layout-json'], {stdio: 'pipe',- env: rendererEnv(quality, repoRoot),+ env: rendererEnv(quality, repoRoot, true),});if (result.status !== 0) {- if (result.stderr) process.stderr.write(result.stderr);- if (result.stdout) process.stdout.write(result.stdout);- process.exit(result.status ?? 1);+ const failure = rendererFailure(result);+ reportValidateFailure({+ json,+ stage: failure.diagnostics.some((entry) => entry.code.startsWith('input/')) ? 'input' : 'render',+ type,+ input: path.resolve(input),+ error: failure.error,+ diagnostics: failure.diagnostics,+ status: result.status ?? 1,+ });+ return;}process.stdout.write(result.stdout);return;@@ -640,23 +844,48 @@ function commandValidate(args) {try {const render = runNode([renderer, input, out], {stdio: 'pipe',- env: rendererEnv(quality, repoRoot),+ env: rendererEnv(quality, repoRoot, true),});if (render.status !== 0) {- if (render.stderr) process.stderr.write(render.stderr);- if (render.stdout) process.stdout.write(render.stdout);+ const failure = rendererFailure(render);+ reportValidateFailure({+ json,+ stage: failure.diagnostics.some((entry) => entry.code.startsWith('input/')) ? 'input' : 'render',+ type,+ input: path.resolve(input),+ error: failure.error,+ diagnostics: failure.diagnostics,+ status: render.status ?? 1,+ });exitCode = render.status ?? 1;} else {const check = runNode([path.join(skillRoot, 'scripts/check-render-output.mjs'), out], { stdio: 'pipe' });if (check.status !== 0) {- if (check.stdout) process.stdout.write(check.stdout);- if (check.stderr) process.stderr.write(check.stderr);+ let checker;+ try {+ checker = JSON.parse(check.stdout);+ checker.file = path.resolve(input);+ } catch {+ checker = { ok: false, diagnostic: 'Artifact checker failed without a parseable receipt.' };+ }+ reportValidateFailure({+ json,+ stage: 'check',+ type,+ input: path.resolve(input),+ error: 'Final artifact check failed.',+ diagnostics: checkerDiagnostics(checker),+ checker,+ status: check.status ?? 1,+ });exitCode = check.status ?? 1;} else {const result = JSON.parse(check.stdout);if (json) {console.log(JSON.stringify({+ schemaVersion: 1,ok: true,+ command: 'validate',type,input: path.resolve(input),checks: result.checks,@@ -671,7 +900,7 @@ function commandValidate(args) {fs.rmSync(tmp, { recursive: true, force: true });}- if (exitCode !== 0) process.exit(exitCode);+ if (exitCode !== 0) process.exitCode = exitCode;}const [command, ...args] = process.argv.slice(2);diff --git a/archify/bin/preview.mjs b/archify/bin/preview.mjsindex 8d5129e7..0a112018 100644--- a/archify/bin/preview.mjs+++ b/archify/bin/preview.mjs@@ -414,12 +414,21 @@ export async function startPreview(options) {}function publishFailure(receipt, stdout, stderr, candidatePath, snapshotPath) {+ const repairDetails = receipt?.diagnostics+ ?.slice(0, 12)+ .map((entry) => {+ const fix = entry.supportedFixes?.length ? `\nFix: ${entry.supportedFixes.join('; ')}` : '';+ return `[${entry.code}] ${entry.message}${fix}`;+ }) || [];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;+ const diagnostic = [+ receipt?.error,+ ...(repairDetails.length ? repairDetails : checkerDetails),+ ].filter(Boolean).join('\n') || stderr || stdout;state.status = 'needs-fix';state.failure = {stage: receipt?.stage || 'render',diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjsindex bf35daec..94183f4d 100644--- a/archify/renderers/architecture/render-architecture.mjs+++ b/archify/renderers/architecture/render-architecture.mjs@@ -3,6 +3,7 @@ import { fileURLToPath } from 'node:url';import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagram, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';import { componentBox, boundaryBox, connectionPath } from '../shared/layout-report.mjs';+import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';import { gridLayout, resolveComponentPos, validateGridPlacement } from './grid.mjs';import {asArray,@@ -276,7 +277,9 @@ function validateArchitecture() {}));if (problems.length) {- throw new Error(`Architecture layout validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Architecture layout validation failed', problems, {+ subject: { diagramType: 'architecture' },+ });}}diff --git a/archify/renderers/dataflow/render-dataflow.mjs b/archify/renderers/dataflow/render-dataflow.mjsindex e21dc8c1..078977a7 100644--- a/archify/renderers/dataflow/render-dataflow.mjs+++ b/archify/renderers/dataflow/render-dataflow.mjs@@ -2,6 +2,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagram, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';+import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';import {asArray,isFinitePoint,@@ -251,7 +252,9 @@ function validateDataflow() {}if (problems.length) {- throw new Error(`Data-flow layout validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Data-flow layout validation failed', problems, {+ subject: { diagramType: 'dataflow' },+ });}}diff --git a/archify/renderers/lifecycle/render-lifecycle.mjs b/archify/renderers/lifecycle/render-lifecycle.mjsindex 93e45e7a..bf0b3fb7 100644--- a/archify/renderers/lifecycle/render-lifecycle.mjs+++ b/archify/renderers/lifecycle/render-lifecycle.mjs@@ -2,6 +2,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagram, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';+import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';import {asArray,isFinitePoint,@@ -279,7 +280,9 @@ function validateLifecycle() {}));if (problems.length) {- throw new Error(`Lifecycle layout validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Lifecycle layout validation failed', problems, {+ subject: { diagramType: 'lifecycle' },+ });}}diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjsindex 9b2a91cc..48a7875c 100644--- a/archify/renderers/sequence/render-sequence.mjs+++ b/archify/renderers/sequence/render-sequence.mjs@@ -2,6 +2,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagram, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';+import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';import { componentFill, arrowClassMap, rectsOverlap, cleanFlowProblems, cleanCrossingProblems, cleanAmbiguousCorridorProblems, cleanBorderRunProblems, cleanRouteRhythmProblems, cleanLabelRouteClearanceProblems, routePointsValue, asArray, isFinitePoint } from '../shared/geometry.mjs';const __dirname = path.dirname(fileURLToPath(import.meta.url));@@ -230,7 +231,9 @@ function validateSequence() {}if (problems.length) {- throw new Error(`Sequence layout validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Sequence layout validation failed', problems, {+ subject: { diagramType: 'sequence' },+ });}}diff --git a/archify/renderers/shared/cli.mjs b/archify/renderers/shared/cli.mjsindex af27c920..9c71ffa7 100644--- a/archify/renderers/shared/cli.mjs+++ b/archify/renderers/shared/cli.mjs@@ -3,6 +3,9 @@ import path from 'node:path';import { applyTemplate, renderCards, esc } from './utils.mjs';import { validateSchema } from './validator.mjs';import { verifyRepositoryEvidence } from './repository-evidence.mjs';+import { installRendererDiagnosticBoundary, throwDiagnosticProblems } from './diagnostics.mjs';++installRendererDiagnosticBoundary();// Common CLI head: node render-<type>.mjs [input.json] [output.html]export function loadDiagram({ rendererDir, diagramType, defaultExample, argv = process.argv }) {@@ -80,7 +83,10 @@ export function validateRelationshipIds(diagramType, diagram) {});if (problems.length) {- throw new Error(`Relationship identity validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Relationship identity validation failed', problems, {+ code: 'relationship/duplicate-id',+ subject: { diagramType, collection },+ });}}@@ -111,7 +117,10 @@ export function validateGuidedViews(diagramType, diagram) {});if (problems.length) {- throw new Error(`Guided view validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Guided view validation failed', problems, {+ code: 'guided-view/invalid',+ subject: { diagramType, collection: 'meta.views' },+ });}}diff --git a/archify/renderers/shared/diagnostics.mjs b/archify/renderers/shared/diagnostics.mjsnew file mode 100644index 00000000..f392f038--- /dev/null+++ b/archify/renderers/shared/diagnostics.mjs@@ -0,0 +1,116 @@+import fs from 'node:fs';+import path from 'node:path';++const DIAGNOSTIC_MODE = process.env.ARCHIFY_DIAGNOSTIC_FORMAT === 'json';+const recorded = [];+const recordedMessages = new Set();+const boundaryKey = Symbol.for('archify.renderer-diagnostic-boundary');++function plainObject(value) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {};+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));+}++function normalizedDiagnostic(diagnostic) {+ const message = String(diagnostic?.message || 'Archify could not classify this failure.').trim();+ return {+ code: String(diagnostic?.code || 'internal/unclassified'),+ severity: diagnostic?.severity === 'warning' ? 'warning' : 'error',+ message,+ subject: plainObject(diagnostic?.subject),+ evidence: plainObject(diagnostic?.evidence),+ supportedFixes: Array.isArray(diagnostic?.supportedFixes)+ ? [...new Set(diagnostic.supportedFixes.map((fix) => String(fix).trim()).filter(Boolean))]+ : [],+ };+}++export function recordDiagnostic(diagnostic) {+ if (!DIAGNOSTIC_MODE) return;+ const normalized = normalizedDiagnostic(diagnostic);+ if (recordedMessages.has(normalized.message)) return;+ recordedMessages.add(normalized.message);+ recorded.push(normalized);+}++export function throwDiagnosticError(message, diagnostics) {+ for (const diagnostic of diagnostics || []) recordDiagnostic(diagnostic);+ const error = new Error(message);+ error.archifyDiagnostics = (diagnostics || []).map(normalizedDiagnostic);+ throw error;+}++export function throwDiagnosticProblems(prefix, problems, { code = 'layout/constraint', subject = {} } = {}) {+ const messages = (problems || []).map((problem) => String(problem));+ for (const message of messages) {+ recordDiagnostic({+ code,+ severity: 'error',+ message,+ subject,+ evidence: {},+ supportedFixes: [],+ });+ }+ throw new Error(`${prefix}:\n- ${messages.join('\n- ')}`);+}++function fallbackDiagnostic(error) {+ const input = process.argv[2] ? path.resolve(process.argv[2]) : undefined;+ if (error instanceof SyntaxError) {+ return normalizedDiagnostic({+ code: 'input/json-parse',+ severity: 'error',+ message: `Input JSON could not be parsed: ${error.message}`,+ subject: { input },+ evidence: { reason: error.message },+ supportedFixes: ['repair the JSON syntax and run validation again'],+ });+ }+ if (error?.code === 'ENOENT' || error?.code === 'EACCES' || error?.code === 'EISDIR') {+ return normalizedDiagnostic({+ code: 'input/read',+ severity: 'error',+ message: `Input could not be read: ${error.message}`,+ subject: { input },+ evidence: { systemCode: error.code, reason: error.message },+ supportedFixes: ['provide one readable JSON input file'],+ });+ }+ return normalizedDiagnostic({+ code: 'internal/unclassified',+ severity: 'error',+ message: error?.message || 'Renderer failed without a diagnostic.',+ subject: { input },+ evidence: { errorName: error?.name || 'Error' },+ supportedFixes: [],+ });+}+function rendererFailure(error) {+ const attached = Array.isArray(error?.archifyDiagnostics)+ ? error.archifyDiagnostics.map(normalizedDiagnostic)+ : [];+ const diagnostics = recorded.length ? recorded : (attached.length ? attached : [fallbackDiagnostic(error)]);+ return {+ schemaVersion: 1,+ ok: false,+ source: 'renderer',+ error: error?.message || 'Renderer failed without a diagnostic.',+ diagnostics,+ };+}++export function installRendererDiagnosticBoundary() {+ if (!DIAGNOSTIC_MODE || globalThis[boundaryKey]) return;+ globalThis[boundaryKey] = true;+ process.on('uncaughtException', (error) => {+ const payload = `${JSON.stringify(rendererFailure(error))}\n`;+ try {+ fs.writeSync(process.stderr.fd, payload);+ } catch {+ // The renderer is already failing. Avoid replacing its real error with a+ // secondary stream failure; the parent CLI still has the exit status.+ }+ process.exit(1);+ });+}diff --git a/archify/renderers/shared/geometry.mjs b/archify/renderers/shared/geometry.mjsindex ea42b0a1..ea2a2263 100644--- a/archify/renderers/shared/geometry.mjs+++ b/archify/renderers/shared/geometry.mjs@@ -2,6 +2,8 @@// pure; renderers own their layout tables and pass measured rects// ({x, y, width, height, cx, cy}) in.+import { recordDiagnostic } from './diagnostics.mjs';+// In degraded mode (no ajv) a type-wrong top-level field reaches the renderer.// Coerce non-arrays to [] so the module-level Maps build without throwing and// the friendly validator checks (which run later) report the real problem.@@ -170,6 +172,17 @@ function sameRelationship(left, right) {return Boolean(left.id && right.id && left.id === right.id && left.from === right.from && left.to === right.to);}+function relationshipSubject(diagramType, relationCollection, relationIndex, relation) {+ return {+ diagramType,+ collection: relationCollection,+ index: relationIndex,+ ...(relation?.id ? { id: relation.id } : {}),+ ...(relation?.from ? { from: relation.from } : {}),+ ...(relation?.to ? { to: relation.to } : {}),+ };+}+// One mechanical quality gate for every renderer-owned relationship path.// A renderer supplies its semantic obstacle set; source/target boxes are// always exempt because paths are expected to terminate on their boundaries.@@ -215,9 +228,23 @@ export function cleanFlowProblems({const from = points[hitSegment].map(Math.round).join(', ');const to = points[hitSegment + 1].map(Math.round).join(', ');const relationId = relation.id ? ` id "${relation.id}"` : '';- problems.push(- `[clean-flow/edge-through-node] ${diagramType} ${relationCollection}[${relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" crosses ${obstacleKind} "${obstacle.id}" (unrelated to this relationship) on segment ${hitSegment} [${from}] -> [${to}] (${clearance}px clearance) — ${routeHint}.`- );+ const message = `[clean-flow/edge-through-node] ${diagramType} ${relationCollection}[${relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" crosses ${obstacleKind} "${obstacle.id}" (unrelated to this relationship) on segment ${hitSegment} [${from}] -> [${to}] (${clearance}px clearance) — ${routeHint}.`;+ recordDiagnostic({+ code: 'clean-flow/edge-through-node',+ severity: 'error',+ message,+ subject: relationshipSubject(diagramType, relationCollection, relationIndex, relation),+ evidence: {+ obstacleKind,+ obstacleId: obstacle.id,+ segmentIndex: hitSegment,+ from: points[hitSegment],+ to: points[hitSegment + 1],+ clearancePx: clearance,+ },+ supportedFixes: [routeHint],+ });+ problems.push(message);}}return problems;@@ -276,9 +303,21 @@ export function cleanCrossingProblems({return `${relationCollection}[${index}]${id} "${relation.from}" -> "${relation.to}"`;};const point = hit.point.map((value) => Math.round(value * 10) / 10).join(', ');- problems.push(- `[composition/proper-crossing] showcase ${diagramType} ${describe(left)} crosses ${describe(right)} at [${point}] (segments ${hit.leftSegment} and ${hit.rightSegment}) — ${routeHint}.`- );+ const message = `[composition/proper-crossing] showcase ${diagramType} ${describe(left)} crosses ${describe(right)} at [${point}] (segments ${hit.leftSegment} and ${hit.rightSegment}) — ${routeHint}.`;+ recordDiagnostic({+ code: 'composition/proper-crossing',+ severity: 'error',+ message,+ subject: relationshipSubject(diagramType, relationCollection, left.index, left.relation),+ evidence: {+ otherRelationship: relationshipSubject(diagramType, relationCollection, right.index, right.relation),+ point: hit.point,+ segmentIndex: hit.leftSegment,+ otherSegmentIndex: hit.rightSegment,+ },+ supportedFixes: [routeHint],+ });+ problems.push(message);}}return problems;@@ -367,7 +406,24 @@ export function cleanAmbiguousCorridorProblems({const length = Math.round(hit.overlapLength * 10) / 10;const from = hit.overlapStart.map((value) => Math.round(value * 10) / 10).join(', ');const to = hit.overlapEnd.map((value) => Math.round(value * 10) / 10).join(', ');- return `[composition/ambiguous-corridor] showcase ${diagramType} ${describe(hit.left)} shares a ${length}px corridor with ${describe(hit.right)} at [${from}] -> [${to}] (segments ${hit.leftSegment} and ${hit.rightSegment}; minimum ${minOverlapPx}px) — ${routeHint}.`;+ const message = `[composition/ambiguous-corridor] showcase ${diagramType} ${describe(hit.left)} shares a ${length}px corridor with ${describe(hit.right)} at [${from}] -> [${to}] (segments ${hit.leftSegment} and ${hit.rightSegment}; minimum ${minOverlapPx}px) — ${routeHint}.`;+ recordDiagnostic({+ code: 'composition/ambiguous-corridor',+ severity: 'error',+ message,+ subject: relationshipSubject(diagramType, relationCollection, hit.left.relationIndex, hit.left.relation),+ evidence: {+ otherRelationship: relationshipSubject(diagramType, relationCollection, hit.right.relationIndex, hit.right.relation),+ overlapLengthPx: length,+ minimumPx: minOverlapPx,+ from: hit.overlapStart,+ to: hit.overlapEnd,+ segmentIndex: hit.leftSegment,+ otherSegmentIndex: hit.rightSegment,+ },+ supportedFixes: [routeHint],+ });+ return message;});}@@ -445,7 +501,25 @@ export function cleanBorderRunProblems({const length = Math.round(hit.overlapLength * 10) / 10;const from = hit.overlapStart.map((value) => Math.round(value * 10) / 10).join(', ');const to = hit.overlapEnd.map((value) => Math.round(value * 10) / 10).join(', ');- return `[composition/container-border-run] ${diagramType} ${relationCollection}[${hit.relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" follows ${frameKind} "${frameIdentity}" ${hit.side} border for ${length}px on segment ${hit.segmentIndex} [${from}] -> [${to}] — ${routeHint}.`;+ const message = `[composition/container-border-run] ${diagramType} ${relationCollection}[${hit.relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" follows ${frameKind} "${frameIdentity}" ${hit.side} border for ${length}px on segment ${hit.segmentIndex} [${from}] -> [${to}] — ${routeHint}.`;+ recordDiagnostic({+ code: 'composition/container-border-run',+ severity: 'error',+ message,+ subject: relationshipSubject(diagramType, relationCollection, hit.relationIndex, relation),+ evidence: {+ frameKind,+ frameId: hit.frame?.id,+ frameLabel: hit.frame?.label,+ side: hit.side,+ segmentIndex: hit.segmentIndex,+ overlapLengthPx: length,+ from: hit.overlapStart,+ to: hit.overlapEnd,+ },+ supportedFixes: [routeHint],+ });+ return message;});}@@ -576,7 +650,23 @@ export function cleanRouteRhythmProblems({const rule = hit.code === 'composition/micro-segment'? `is below the ${microSegmentPx}px micro-segment floor`: `is below the ${interiorSegmentPx}px interior-segment floor`;- return `[${hit.code}] showcase ${diagramType} ${relationCollection}[${hit.relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" has a ${length}px ${hit.position} segment ${hit.segmentIndex} [${from}] -> [${to}] that ${rule} — ${routeHint}.`;+ const message = `[${hit.code}] showcase ${diagramType} ${relationCollection}[${hit.relationIndex}]${relationId} "${relation.from}" -> "${relation.to}" has a ${length}px ${hit.position} segment ${hit.segmentIndex} [${from}] -> [${to}] that ${rule} — ${routeHint}.`;+ recordDiagnostic({+ code: hit.code,+ severity: 'error',+ message,+ subject: relationshipSubject(diagramType, relationCollection, hit.relationIndex, relation),+ evidence: {+ segmentIndex: hit.segmentIndex,+ position: hit.position,+ lengthPx: length,+ minimumPx: hit.code === 'composition/micro-segment' ? microSegmentPx : interiorSegmentPx,+ from: hit.start,+ to: hit.end,+ },+ supportedFixes: [routeHint],+ });+ return message;});}@@ -607,7 +697,25 @@ export function cleanLabelRouteClearanceProblems({const clearance = Math.round(hit.clearance * 10) / 10;const from = hit.start.map((value) => Math.round(value * 10) / 10).join(', ');const to = hit.end.map((value) => Math.round(value * 10) / 10).join(', ');- return `[composition/label-route-clearance] showcase ${diagramType} label "${hit.label?.label || hit.labelRelation?.label || ''}" on ${describe(hit.labelRelation, hit.labelRelationIndex)} is ${clearance}px from ${describe(hit.otherRelation, hit.otherRelationIndex)} segment ${hit.segmentIndex} [${from}] -> [${to}] (label rect ${formatRect(hit.rect)}; minimum ${threshold}px) — ${routeHint}.`;+ const message = `[composition/label-route-clearance] showcase ${diagramType} label "${hit.label?.label || hit.labelRelation?.label || ''}" on ${describe(hit.labelRelation, hit.labelRelationIndex)} is ${clearance}px from ${describe(hit.otherRelation, hit.otherRelationIndex)} segment ${hit.segmentIndex} [${from}] -> [${to}] (label rect ${formatRect(hit.rect)}; minimum ${threshold}px) — ${routeHint}.`;+ recordDiagnostic({+ code: 'composition/label-route-clearance',+ severity: 'error',+ message,+ subject: relationshipSubject(diagramType, relationCollection, hit.labelRelationIndex, hit.labelRelation),+ evidence: {+ label: hit.label?.label || hit.labelRelation?.label || '',+ otherRelationship: relationshipSubject(diagramType, relationCollection, hit.otherRelationIndex, hit.otherRelation),+ segmentIndex: hit.segmentIndex,+ clearancePx: clearance,+ minimumPx: threshold,+ labelRect: hit.rect,+ from: hit.start,+ to: hit.end,+ },+ supportedFixes: [routeHint],+ });+ return message;});}diff --git a/archify/renderers/shared/repository-evidence.mjs b/archify/renderers/shared/repository-evidence.mjsindex fa739721..23cb6383 100644--- a/archify/renderers/shared/repository-evidence.mjs+++ b/archify/renderers/shared/repository-evidence.mjs@@ -1,22 +1,40 @@import { spawnSync } from 'node:child_process';import fs from 'node:fs';import path from 'node:path';+import { throwDiagnosticError } from './diagnostics.mjs';const FULL_SHA_RE = /^[a-f0-9]{40}$/i;const CONTROL_CHARACTER_RE = /[\u0000-\u001f\u007f]/;+function evidenceFailure(code, message, { subject = {}, evidence = {}, supportedFixes = [] } = {}) {+ throwDiagnosticError(message, [{+ code,+ severity: 'error',+ message,+ subject: { surface: 'repository-evidence', ...subject },+ evidence,+ supportedFixes,+ }]);+}+function runGit(repoRoot, args) {const result = spawnSync('git', ['-C', repoRoot, ...args], {encoding: 'utf8',maxBuffer: 16 * 1024 * 1024,});- if (result.error) throw new Error(`Could not run Git: ${result.error.message}`);+ if (result.error) evidenceFailure('repository-evidence/git-unavailable', `Could not run Git: ${result.error.message}`, {+ evidence: { reason: result.error.message },+ supportedFixes: ['install Git and ensure it is available on PATH'],+ });return result;}function gitValue(repoRoot, args, failure) {const result = runGit(repoRoot, args);- if (result.status !== 0) throw new Error(failure);+ if (result.status !== 0) evidenceFailure('repository-evidence/git-command', failure, {+ evidence: { gitArgs: args, exitCode: result.status },+ supportedFixes: ['use the intended local Git repository and verify its origin and revision'],+ });return result.stdout.trim();}@@ -29,11 +47,19 @@ function githubSlug(value) {function verifiedSourcePath(value, where) {const sourcePath = String(value || '');if (!sourcePath || sourcePath.startsWith('/') || sourcePath.includes('\\') || CONTROL_CHARACTER_RE.test(sourcePath)) {- throw new Error(`${where} must be a repo-relative POSIX path.`);+ evidenceFailure('repository-evidence/path-invalid', `${where} must be a repo-relative POSIX path.`, {+ subject: { path: where },+ evidence: { authoredPath: sourcePath },+ supportedFixes: ['use a repository-relative path with forward slashes'],+ });}const segments = sourcePath.split('/');if (segments.some((segment) => !segment || segment === '.' || segment === '..') || segments[0] === '.git') {- throw new Error(`${where} must stay inside the repository and may not address .git.`);+ evidenceFailure('repository-evidence/path-escape', `${where} must stay inside the repository and may not address .git.`, {+ subject: { path: where },+ evidence: { authoredPath: sourcePath },+ supportedFixes: ['remove empty, dot, parent, or .git path segments'],+ });}return segments.join('/');}@@ -60,19 +86,36 @@ export function hasRepositoryEvidence(diagramType, diagram) {export function verifyRepositoryEvidence(diagramType, diagram, repoRootInput) {if (!hasRepositoryEvidence(diagramType, diagram)) return null;- if (diagramType !== 'architecture') throw new Error('Repository evidence is currently supported for architecture diagrams only.');+ if (diagramType !== 'architecture') evidenceFailure('repository-evidence/type-unsupported', 'Repository evidence is currently supported for architecture diagrams only.', {+ subject: { diagramType },+ supportedFixes: ['use architecture mode or remove repository evidence'],+ });const repository = diagram.meta?.repository;- if (!repository) throw new Error('Repository evidence requires /meta/repository.');+ if (!repository) evidenceFailure('repository-evidence/repository-required', 'Repository evidence requires /meta/repository.', {+ subject: { path: '/meta/repository' },+ supportedFixes: ['add the pinned public repository metadata or remove component sources'],+ });if (!FULL_SHA_RE.test(repository.revision || '')) {- throw new Error('/meta/repository/revision must be a full 40-character commit SHA.');+ evidenceFailure('repository-evidence/revision-invalid', '/meta/repository/revision must be a full 40-character commit SHA.', {+ subject: { path: '/meta/repository/revision' },+ evidence: { revision: repository.revision },+ supportedFixes: ['pin one full 40-character commit SHA'],+ });}const authoredSlug = githubSlug(repository.url);if (!authoredSlug || !String(repository.url).startsWith('https://github.com/')) {- throw new Error('/meta/repository/url must be a public https://github.com owner/repository URL.');+ evidenceFailure('repository-evidence/url-invalid', '/meta/repository/url must be a public https://github.com owner/repository URL.', {+ subject: { path: '/meta/repository/url' },+ evidence: { repositoryUrl: repository.url },+ supportedFixes: ['use the canonical public GitHub HTTPS repository URL'],+ });}if (!repoRootInput) {- throw new Error('This diagram declares source evidence. Pass --repo-root <repository> so Archify can verify it before rendering.');+ evidenceFailure('repository-evidence/root-required', 'This diagram declares source evidence. Pass --repo-root <repository> so Archify can verify it before rendering.', {+ subject: { path: '/meta/repository' },+ supportedFixes: ['pass --repo-root with the matching local Git checkout'],+ });}const requestedRoot = path.resolve(repoRootInput);@@ -80,21 +123,37 @@ export function verifyRepositoryEvidence(diagramType, diagram, repoRootInput) {try {realRoot = fs.realpathSync(requestedRoot);} catch (error) {- throw new Error(`Could not resolve evidence repository root "${requestedRoot}": ${error.message}`);+ evidenceFailure('repository-evidence/root-unreadable', `Could not resolve evidence repository root "${requestedRoot}": ${error.message}`, {+ subject: { repoRoot: requestedRoot },+ evidence: { reason: error.message },+ supportedFixes: ['pass one readable local repository directory'],+ });}const gitRoot = gitValue(realRoot, ['rev-parse', '--show-toplevel'], `Evidence root "${realRoot}" is not a Git repository.`);if (fs.realpathSync(gitRoot) !== realRoot) {- throw new Error(`Evidence root must be the Git top-level directory: ${gitRoot}`);+ evidenceFailure('repository-evidence/root-not-top-level', `Evidence root must be the Git top-level directory: ${gitRoot}`, {+ subject: { repoRoot: realRoot },+ evidence: { gitTopLevel: gitRoot },+ supportedFixes: [`pass --repo-root ${gitRoot}`],+ });}const origin = gitValue(realRoot, ['remote', 'get-url', 'origin'], 'Evidence repository must have an origin remote.');if (githubSlug(origin) !== authoredSlug) {- throw new Error(`Evidence repository origin ${JSON.stringify(origin)} does not match ${JSON.stringify(repository.url)}.`);+ evidenceFailure('repository-evidence/origin-mismatch', `Evidence repository origin ${JSON.stringify(origin)} does not match ${JSON.stringify(repository.url)}.`, {+ subject: { repoRoot: realRoot },+ evidence: { localOrigin: origin, authoredRepository: repository.url },+ supportedFixes: ['use the matching local checkout or correct the authored repository URL'],+ });}const revision = repository.revision.toLowerCase();const commit = runGit(realRoot, ['cat-file', '-e', `${revision}^{commit}`]);if (commit.status !== 0) {- throw new Error(`Evidence revision ${revision} is not available in the local repository.`);+ evidenceFailure('repository-evidence/revision-unavailable', `Evidence revision ${revision} is not available in the local repository.`, {+ subject: { repoRoot: realRoot },+ evidence: { revision },+ supportedFixes: ['fetch the pinned commit or pin an available full commit SHA'],+ });}const nodes = Object.create(null);@@ -112,23 +171,42 @@ export function verifyRepositoryEvidence(diagramType, diagram, repoRootInput) {...(authored.label ? { label: authored.label } : {}),};if (source.endLine && !source.line) {- throw new Error(`/components/${componentIndex}/sources/${sourceIndex}/end_line requires line.`);+ evidenceFailure('repository-evidence/line-required', `/components/${componentIndex}/sources/${sourceIndex}/end_line requires line.`, {+ subject: { path: `/components/${componentIndex}/sources/${sourceIndex}/end_line`, componentId: component.id },+ supportedFixes: ['add line or remove end_line'],+ });}if (source.endLine && source.endLine < source.line) {- throw new Error(`/components/${componentIndex}/sources/${sourceIndex}/end_line must be greater than or equal to line.`);+ evidenceFailure('repository-evidence/line-range-invalid', `/components/${componentIndex}/sources/${sourceIndex}/end_line must be greater than or equal to line.`, {+ subject: { path: `/components/${componentIndex}/sources/${sourceIndex}`, componentId: component.id },+ evidence: { line: source.line, endLine: source.endLine },+ supportedFixes: ['use an end_line greater than or equal to line'],+ });}const object = `${revision}:${source.path}`;const type = runGit(realRoot, ['cat-file', '-t', object]);if (type.status !== 0 || type.stdout.trim() !== 'blob') {- throw new Error(`${where} does not identify a file at revision ${revision}.`);+ evidenceFailure('repository-evidence/file-missing', `${where} does not identify a file at revision ${revision}.`, {+ subject: { path: where, componentId: component.id },+ evidence: { sourcePath: source.path, revision },+ supportedFixes: ['use a file path that exists at the pinned revision'],+ });}if (source.line) {const content = runGit(realRoot, ['show', object]);- if (content.status !== 0) throw new Error(`${where} could not be read at revision ${revision}.`);+ if (content.status !== 0) evidenceFailure('repository-evidence/file-unreadable', `${where} could not be read at revision ${revision}.`, {+ subject: { path: where, componentId: component.id },+ evidence: { sourcePath: source.path, revision },+ supportedFixes: ['verify the pinned blob is readable in the local checkout'],+ });const lineCount = sourceLineCount(content.stdout);const requestedLine = source.endLine || source.line;if (requestedLine > lineCount) {- throw new Error(`/components/${componentIndex}/sources/${sourceIndex} requests line ${requestedLine}, but ${source.path} has ${lineCount} lines at revision ${revision}.`);+ evidenceFailure('repository-evidence/line-out-of-range', `/components/${componentIndex}/sources/${sourceIndex} requests line ${requestedLine}, but ${source.path} has ${lineCount} lines at revision ${revision}.`, {+ subject: { path: `/components/${componentIndex}/sources/${sourceIndex}`, componentId: component.id },+ evidence: { sourcePath: source.path, requestedLine, lineCount, revision },+ supportedFixes: ['use a line range that exists at the pinned revision'],+ });}}verified.push({ ...source, href: sourceHref(repository.url.replace(/\.git\/?$/i, '').replace(/\/$/, ''), revision, source) });@@ -137,7 +215,10 @@ export function verifyRepositoryEvidence(diagramType, diagram, repoRootInput) {nodes[component.id] = verified;}if (referenceCount === 0) {- throw new Error('/meta/repository requires at least one component source reference.');+ evidenceFailure('repository-evidence/source-required', '/meta/repository requires at least one component source reference.', {+ subject: { path: '/meta/repository' },+ supportedFixes: ['add at least one verified component source or remove repository metadata'],+ });}return {diff --git a/archify/renderers/shared/validator.mjs b/archify/renderers/shared/validator.mjsindex d0431599..7664657b 100644--- a/archify/renderers/shared/validator.mjs+++ b/archify/renderers/shared/validator.mjs@@ -1,9 +1,10 @@import * as validators from './generated-validators.mjs';+import { throwDiagnosticError } from './diagnostics.mjs';// "/nodes/3/label" reads much better as "/nodes/3 (id: "router") /label" for the// LLM fixing the JSON; resolve the nearest enclosing element's id or label.-function annotatePath(instancePath, data) {- if (!instancePath) return '/';+function annotatedPath(instancePath, data) {+ if (!instancePath) return { path: '/', identity: null };let node = data;let hint = null;for (const seg of instancePath.split('/').slice(1)) {@@ -14,7 +15,14 @@ function annotatePath(instancePath, data) {if (tag != null) hint = String(tag);}}- return hint != null ? `${instancePath} (id/label: ${JSON.stringify(hint)})` : instancePath;+ return { path: instancePath, identity: hint };+}++function annotatePath(instancePath, data) {+ const annotated = annotatedPath(instancePath, data);+ return annotated.identity != null+ ? `${annotated.path} (id/label: ${JSON.stringify(annotated.identity)})`+ : annotated.path;}function formatErrors(errors, data) {@@ -33,8 +41,46 @@ export function validateSchema(diagramType, data) {throw new Error(`validateSchema: unknown diagram type "${diagramType}"`);}if (!validate(data)) {- throw new Error(- `${diagramType} schema validation failed:\n${formatErrors(validate.errors, data)}`+ const diagnostics = validate.errors.map((error) => {+ const annotated = annotatedPath(error.instancePath, data);+ const subject = {+ diagramType,+ path: annotated.path,+ ...(annotated.identity != null ? { identity: String(annotated.identity) } : {}),+ };+ const evidence = {+ keyword: error.keyword,+ expected: error.schema,+ ...error.params,+ };+ const supportedFixes = {+ additionalProperties: [`remove unsupported property ${JSON.stringify(error.params?.additionalProperty)}`],+ required: [`add required property ${JSON.stringify(error.params?.missingProperty)}`],+ type: [`use ${JSON.stringify(error.params?.type)} at ${annotated.path}`],+ enum: [`choose one of ${JSON.stringify(error.params?.allowedValues || [])}`],+ pattern: [`match the required pattern ${JSON.stringify(error.params?.pattern)}`],+ minimum: [`use a value ${error.params?.comparison || '>='} ${error.params?.limit}`],+ maximum: [`use a value ${error.params?.comparison || '<='} ${error.params?.limit}`],+ minItems: [`provide at least ${error.params?.limit} item(s)`],+ maxItems: [`provide at most ${error.params?.limit} item(s)`],+ minLength: [`provide at least ${error.params?.limit} character(s)`],+ maxLength: [`provide at most ${error.params?.limit} character(s)`],+ }[error.keyword] || [];+ const detail = error.params && Object.keys(error.params).length+ ? ` ${JSON.stringify(error.params)}`+ : '';+ return {+ code: `schema/${error.keyword}`,+ severity: 'error',+ message: `${annotatePath(error.instancePath, data)} ${error.message}${detail}`,+ subject,+ evidence,+ supportedFixes,+ };+ });+ throwDiagnosticError(+ `${diagramType} schema validation failed:\n${formatErrors(validate.errors, data)}`,+ diagnostics,);}}diff --git a/archify/renderers/workflow/render-workflow.mjs b/archify/renderers/workflow/render-workflow.mjsindex 094f0c11..1516fe5a 100644--- a/archify/renderers/workflow/render-workflow.mjs+++ b/archify/renderers/workflow/render-workflow.mjs@@ -2,6 +2,7 @@ import path from 'node:path';import { fileURLToPath } from 'node:url';import { esc, renderDefinitions, renderSemanticSigil, textUnits } from '../shared/utils.mjs';import { animateAttr, focusEdgeAttrs, focusNodeAttrs, focusNodeTitle, loadDiagram, writeDiagram, svgAccessibleText, svgRootAttrs } from '../shared/cli.mjs';+import { throwDiagnosticProblems } from '../shared/diagnostics.mjs';import {asArray,isFinitePoint,@@ -168,7 +169,9 @@ function validateWorkflow() {problems.push('Workflow "cards" must be an array.');}if (problems.length) {- throw new Error(`Workflow layout validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Workflow layout validation failed', problems, {+ subject: { diagramType: 'workflow' },+ });}const laneIds = new Set(workflow.lanes.map((lane) => lane.id));@@ -388,7 +391,9 @@ function validateWorkflow() {}if (problems.length) {- throw new Error(`Workflow layout validation failed:\n- ${problems.join('\n- ')}`);+ throwDiagnosticProblems('Workflow layout validation failed', problems, {+ subject: { diagramType: 'workflow' },+ });}}diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjsindex 7d1e5d72..c852672a 100644--- a/archify/test/cli.test.mjs+++ b/archify/test/cli.test.mjs@@ -446,6 +446,9 @@ test('cli: deliver preserves the previous artifact when the final check fails',const failure = JSON.parse(result.stdout);assert.equal(failure.ok, false);assert.equal(failure.stage, 'check');+ assert.equal(failure.diagnostics[0].code, 'artifact/single-svg');+ assert.equal(failure.diagnostics[0].subject.check, 'single_svg');+ assert.ok(failure.diagnostics[0].supportedFixes.some((fix) => fix.includes('exactly one diagram SVG')));assert.equal(failure.checker.checks.find((entry) => entry.name === 'single_svg').ok, false);assert.equal(fs.readFileSync(out, 'utf8'), trustedPriorArtifact);assert.deepEqual(diff --git a/archify/test/repair-receipt.test.mjs b/archify/test/repair-receipt.test.mjsnew file mode 100644index 00000000..e969d5be--- /dev/null+++ b/archify/test/repair-receipt.test.mjs@@ -0,0 +1,149 @@+import assert from 'node:assert/strict';+import { spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import test from 'node:test';+import { fileURLToPath } from 'node:url';++const here = path.dirname(fileURLToPath(import.meta.url));+const skillRoot = path.resolve(here, '..');+const cli = path.join(skillRoot, 'bin/archify.mjs');+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-repair-receipt-'));++function run(args) {+ return spawnSync(process.execPath, [cli, ...args], {+ cwd: skillRoot,+ encoding: 'utf8',+ });+}++function writeFixture(name, source) {+ const file = path.join(tmp, name);+ fs.writeFileSync(file, JSON.stringify(source, null, 2));+ return file;+}++function receipt(result) {+ assert.doesNotThrow(() => JSON.parse(result.stdout), result.stdout || result.stderr);+ return JSON.parse(result.stdout);+}++test('repair receipt: malformed JSON is one clean machine object without a Node stack', () => {+ const input = path.join(tmp, 'malformed.workflow.json');+ fs.writeFileSync(input, '{broken json');++ const result = run(['validate', 'workflow', input, '--json']);+ assert.equal(result.status, 1);+ assert.equal(result.stderr, '');+ const failure = receipt(result);+ assert.equal(failure.schemaVersion, 1);+ assert.equal(failure.ok, false);+ assert.equal(failure.command, 'validate');+ assert.equal(failure.stage, 'input');+ assert.equal(failure.diagnostics.length, 1);+ assert.deepEqual(failure.diagnostics[0].subject, { input });+ assert.equal(failure.diagnostics[0].code, 'input/json-parse');+ assert.equal(failure.diagnostics[0].severity, 'error');+ assert.match(failure.diagnostics[0].evidence.reason, /JSON/);+ assert.deepEqual(failure.diagnostics[0].supportedFixes, ['repair the JSON syntax and run validation again']);+ assert.doesNotMatch(result.stdout, /\n\s+at\s|file:\/\//);+});++test('repair receipt: all five modes identify schema subjects and supported fixes', () => {+ const cases = {+ architecture: ['web-app.architecture.json', 'components'],+ workflow: ['agent-tool-call.workflow.json', 'nodes'],+ sequence: ['cache-miss-request.sequence.json', 'participants'],+ dataflow: ['product-analytics.dataflow.json', 'nodes'],+ lifecycle: ['agent-run.lifecycle.json', 'states'],+ };++ for (const [type, [example, collection]] of Object.entries(cases)) {+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples', example), 'utf8'));+ source[collection][0].unexpected = true;+ const identity = source[collection][0].id;+ const input = writeFixture(`schema-${type}.json`, source);+ const result = run(['validate', type, input, '--json']);++ assert.equal(result.status, 1, `${type}: ${result.stderr || result.stdout}`);+ assert.equal(result.stderr, '', type);+ const failure = receipt(result);+ const repair = failure.diagnostics.find((entry) => entry.code === 'schema/additionalProperties');+ assert.ok(repair, type);+ assert.deepEqual(repair.subject, {+ diagramType: type,+ path: `/${collection}/0`,+ identity,+ });+ assert.equal(repair.evidence.additionalProperty, 'unexpected');+ assert.deepEqual(repair.supportedFixes, ['remove unsupported property "unexpected"']);+ }+});++test('repair receipt: human validation formats the same rule without a stack', () => {+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/agent-tool-call.workflow.json'), 'utf8'));+ source.nodes[0].unexpected = true;+ const input = writeFixture('human-schema.workflow.json', source);+ const result = run(['validate', 'workflow', input]);++ assert.equal(result.status, 1);+ assert.equal(result.stdout, '');+ assert.match(result.stderr, /\[schema\/additionalProperties\]/);+ assert.match(result.stderr, /Fix: remove unsupported property "unexpected"/);+ assert.doesNotMatch(result.stderr, /\n\s+at\s|file:\/\//);+});++test('repair receipt: validate and deliver share exact Clean Flow evidence while delivery preserves the trusted artifact', () => {+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));+ source.connections[0] = {+ ...source.connections[0],+ fromSide: 'right',+ toSide: 'left',+ via: [[100, 140], [220, 140]],+ };+ const input = writeFixture('blocked-route.architecture.json', source);+ const output = path.join(tmp, 'trusted.html');+ const trusted = '<!doctype html><title>trusted prior artifact</title>\n';+ fs.writeFileSync(output, trusted);++ const validated = run(['validate', 'architecture', input, '--quality', 'showcase', '--json']);+ const delivered = run(['deliver', 'architecture', input, output, '--quality', 'showcase', '--json']);+ assert.equal(validated.status, 1, validated.stderr || validated.stdout);+ assert.equal(delivered.status, 1, delivered.stderr || delivered.stdout);+ assert.equal(validated.stderr, '');+ assert.equal(delivered.stderr, '');++ const validateRepair = receipt(validated).diagnostics.find((entry) => entry.code === 'clean-flow/edge-through-node');+ const deliverRepair = receipt(delivered).diagnostics.find((entry) => entry.code === 'clean-flow/edge-through-node');+ assert.ok(validateRepair);+ assert.ok(deliverRepair);+ assert.deepEqual(deliverRepair, validateRepair);+ assert.equal(validateRepair.subject.id, 'users-to-cdn');+ assert.equal(validateRepair.evidence.obstacleId, 'auth');+ assert.equal(validateRepair.evidence.segmentIndex, 0);+ assert.equal(validateRepair.evidence.clearancePx, 2);+ assert.ok(validateRepair.supportedFixes.some((fix) => fix.includes('route/via')));+ assert.equal(fs.readFileSync(output, 'utf8'), trusted);+ assert.deepEqual(fs.readdirSync(tmp).filter((name) => name.startsWith('.archify-delivery-')), []);+});++test('repair receipt: repository evidence failures retain a stable rule and exact repair', () => {+ const source = JSON.parse(fs.readFileSync(path.join(skillRoot, 'examples/web-app.architecture.json'), 'utf8'));+ source.meta.repository = {+ url: 'https://github.com/example/repository',+ revision: '0123456789abcdef0123456789abcdef01234567',+ };+ source.components[0].sources = [{ path: 'src/index.js', line: 1 }];+ const input = writeFixture('evidence-root-required.architecture.json', source);+ const result = run(['validate', 'architecture', input, '--json']);++ assert.equal(result.status, 1);+ assert.equal(result.stderr, '');+ const repair = receipt(result).diagnostics[0];+ assert.equal(repair.code, 'repository-evidence/root-required');+ assert.deepEqual(repair.subject, { surface: 'repository-evidence', path: '/meta/repository' });+ assert.deepEqual(repair.supportedFixes, ['pass --repo-root with the matching local Git checkout']);+});++process.on('exit', () => fs.rmSync(tmp, { recursive: true, force: true }));diff --git a/docs/research-next-stability-growth-slice-2026-07.md b/docs/research-next-stability-growth-slice-2026-07.mdnew file mode 100644index 00000000..583f81c8--- /dev/null+++ b/docs/research-next-stability-growth-slice-2026-07.md@@ -0,0 +1,186 @@+# Archify 下一轮“稳定优先、用户可见、利于增长”切片研究++> 研究日期:2026-07-23+> 本地基线:`codex/reach-share-card` @ `13d58c406dc4d1449c9761deae039ba78ec403fc`+> 资料边界:Archify 当前代码与公开 issues,以及 Fireworks Tech Graph、GitNexus、GitDiagram、Cursor 和 `skills` CLI 的第一方 README、文档或仓库页面。++## 结论先行++下一轮唯一推荐:**Structured Repair Receipt(结构化修复回执)**。++它不是再加一种图、再加一个动画或再加一个 Viewer 面板,而是让 `validate --json` 和 `deliver --json` 在失败时也输出稳定、可解析、带精确证据与受支持修复旋钮的 JSON。Agent 不必从 Node 堆栈和多行英文错误中猜“应该改哪个对象、哪条线、哪个字段”,因此弱模型和不同客户端也更容易在最多两轮内完成准确修复。++这是当前最符合三项约束的交集:++- **稳定优先**:不降低任何现有质量门槛,不自动改图,只把现有确定性证据变成可靠协议。+- **用户可见**:用户会直接感受到首张图更容易成功、失败解释更清楚、来回调整更少。+- **利于增长**:它改善不同模型/Agent 客户端上的一致性,比继续堆视觉功能更能降低“装了但第一次没画好”的流失。++## 1. 先排除已经完成的能力++本研究按当前本地分支而不是旧版 `main` 判断。以下能力已经存在,不应包装成“下一步新功能”:++- Atomic Verified Delivery:同目录候选文件、完整检查、单次原子替换,失败保留旧成品。+- `deliver --open`:只在验证并提交成功后打开最终 HTML。+- Last-Good Live Preview:候选失败时保留上一份通过验证的成品。+- canonical Share Card、Route Share Card、Reach Share Card。+- Authored Reachability、Semantic Passport、revision-pinned Verified Source Passport。+- 11 个有界场景配方、Start 页面、Proof Lab、五种 typed diagram mode。+- 最多两轮的 Perceptual Delivery Gate,以及 `validation / visual_review / correction_rounds` 的诚实交付说明。++第一方依据:当前 [README](../README.md)、[ROADMAP](../ROADMAP.md)、[SKILL](../archify/SKILL.md),以及已推送的 [`13d58c4` 基线提交](https://github.com/tt-a1i/archify/commit/13d58c406dc4d1449c9761deae039ba78ec403fc)。++因此,Fireworks 的“有界视觉复核”、GitDiagram 的“仓库到图”、GitNexus 的“路径/影响分析”等概念不能不经核对就再次列为 Archify 缺失项。++## 2. 当前公开反馈揭示的真实痛点++### 2.1 弱模型/不同 Agent 的首轮构图质量仍不稳定++公开 [issue #6](https://github.com/tt-a1i/archify/issues/6) 使用 opencode + DeepSeek 生成架构图和 workflow,反馈箭头混乱且观感差。Archify 已合入 `composition/ambiguous-corridor` 这一具体确定性门槛,但维护者在 [进展回复](https://github.com/tt-a1i/archify/issues/6#issuecomment-5041845293) 中明确保留该 issue,因为“弱模型构图”大于单一 corridor 规则。++这说明下一步不该简单继续增加视觉样式;更重要的是让不同能力的 Agent 都能理解失败证据并做小范围、可验证的修复。++### 2.2 多轮调整的成本对用户真实可感++[issue #22](https://github.com/tt-a1i/archify/issues/22) 报告了长时间、多轮细节调整带来的高 token 消耗。维护者最终确认没有证据表明 Archify renderer 自身异常耗 token,主要成本来自客户端、模型、仓库探索和多轮修订,因此该 issue 已关闭。++正确结论不是“Archify 要承诺节省所有 token”,而是:**Archify 能控制的部分,应让每次确定性失败都给 Agent 一份最短、最精确、无需猜测的修复协议**。这样可以减少无效整图重写和重复解释,但不能虚假承诺控制模型或仓库探索成本。++### 2.3 已修复问题不应重复立项++- [issue #14](https://github.com/tt-a1i/archify/issues/14) 的 CJK/全角宽度边界已由 #31 修复并加入回归覆盖。+- [issue #24](https://github.com/tt-a1i/archify/issues/24) 的“连线穿过无关节点、造成拓扑误读”已进入共享 Clean Flow 硬门槛与回归覆盖。++这些案例证明“可复现问题 → 确定性门槛 → 回归测试”的路线有效。下一切片应增强这套路线上失败信息的可消费性,而不是回到泛化的“自动美化”。++### 2.4 Cursor 是明确的增长入口,但不是本轮最高优先级++2026-07-23 新开的 [issue #46](https://github.com/tt-a1i/archify/issues/46) 表示社区成员已经为 Cursor 制作 Archify skill 并希望共同推进。Cursor 官方在 [2.4 changelog](https://cursor.com/changelog/2-4) 中确认 IDE 与 CLI 都支持 `SKILL.md` Agent Skills;`skills` CLI 的官方 [Supported Agents](https://github.com/vercel-labs/skills#supported-agents) 也已经列出 `cursor`,全局路径为 `~/.cursor/skills/`。++所以 Cursor 值得做,但如果不先改善失败回执,只扩大发行面也可能把同一首轮质量波动带给更多用户。++## 3. 同类项目值得吸收的,不是表面功能数量++### 3.1 Fireworks Tech Graph:把“首稿”当候选,并限制修复轮数++Fireworks 的官方 [Loop Engineering](https://github.com/yizhiyanhua-ai/fireworks-tech-graph#loop-engineering) 明确采用:确定性检查 → PNG 视觉回读 → 针对性修复 → 有界收敛;默认最多两轮,无法读取图片时诚实报告 `visual_review: skipped`。其 [README](https://github.com/yizhiyanhua-ai/fireworks-tech-graph) 还用 12 套动图样例在首屏形成强视觉证明。++Archify 已经吸收了正确的“最多两轮 + 不虚报视觉复核”原则,因此不应再次把它当新功能。仍可继续借鉴的是:**让每轮修复输入更结构化、最终状态更可审计**。++### 3.2 GitDiagram:严格 AST、真实路径校验、聚焦反馈重试++GitDiagram 官方 [How generation works](https://github.com/ahmedkhaleel2004/gitdiagram#how-generation-works) 描述了严格、有限大小的 graph AST;服务端校验 identifier、连通性、大小和每条仓库路径,并在模型输出无效时用 focused feedback 重试。成功成品会持久化,重新打开无需再次调用模型。它的另一个增长优势是极短入口:把 GitHub URL 里的 `hub` 换成 `diagram` 即可开始。++Archify 不应复制其托管服务、R2、Redis 或 Mermaid 产品形态;值得吸收的是:**验证失败要成为聚焦、有限、机器可消费的反馈,而不是一段供 Agent 猜测的日志**。++### 3.3 GitNexus:把结构工作前移,让小模型少猜、少查询++GitNexus 官方 [Why a Knowledge Graph](https://github.com/abhigyanpatwari/GitNexus#why-a-knowledge-graph) 把核心价值描述为预计算结构,使 Agent 用一次工具调用获得完整上下文,并明确强调 token efficiency 与 smaller-model reliability。它的 [Quick Start](https://github.com/abhigyanpatwari/GitNexus#quick-start) 只有 `analyze` 和 `setup` 两步;[Editor Setup](https://github.com/abhigyanpatwari/GitNexus#editor-setup) 则把 Cursor、Claude Code、Codex、OpenCode 等多客户端支持放在主路径。++Archify 不需要引入知识图数据库。可吸收的原则是:**把确定性知识放进工具回执,不要把解析错误、归类失败和选择修复手段继续外包给模型**。++## 4. 当前协议层的具体缺口++在本地基线 `13d58c4` 上核对 [CLI 实现](https://github.com/tt-a1i/archify/blob/13d58c406dc4d1449c9761deae039ba78ec403fc/archify/bin/archify.mjs):++1. `validate --json` 只在成功后打印 JSON。输入读取、schema、layout 或 render 失败时,会把 renderer stderr 原样转发;一次不存在文件的实测得到 **stdout 0 bytes、stderr 782 bytes 的 Node 堆栈**,退出码为 1。+2. `deliver --json` 已经在失败时维持一个 JSON envelope(这是正确基础),但 `error` 仍是自由文本;没有稳定的 `diagnostics[]` 来表示规则代码、对象身份、测量证据和受支持修复字段。+3. renderer 已经产生大量稳定规则标识与精确提示,例如 `clean-flow/edge-through-node`、`composition/proper-crossing`、`composition/ambiguous-corridor`、`composition/label-route-clearance`、`composition/micro-segment`。也就是说,Archify 并不缺检测能力,缺的是从内部事实到外部 Agent 的**结构化错误协议**。+4. 当前 [SKILL 的 Perceptual Delivery Gate](https://github.com/tt-a1i/archify/blob/13d58c406dc4d1449c9761deae039ba78ec403fc/archify/SKILL.md#perceptual-delivery-gate) 已要求最多两轮针对性修复,但如果确定性失败只给自由文本,弱模型仍可能整图重写、选错修复旋钮或重复试错。++这是真实、可复现、范围有限的缺口,也能同时解释 #6 的跨模型波动和 #22 中用户对多轮调整的敏感。++## 5. 三个候选切片++| 候选 | 用户/增长收益 | 主要风险 | 可测试性 |+|---|---|---|---|+| **A. Structured Repair Receipt** | 首次失败更容易理解;Agent 能按对象与规则做局部修复;减少日志猜测和无效整图重写;对所有客户端和模型同时生效 | 若仓促用正则解析旧错误文本,协议会脆弱;若一次覆盖所有错误类型,范围会失控;需维护 JSON 向后兼容 | 很高:五种 mode 的 success/failure fixtures、stdout/stderr 契约、exact diagnostic schema、旧成品字节不变、安装 ZIP smoke 都可确定性测试 |+| **B. First-class Cursor Onboarding** | 直接回应 #46;扩大可安装人群;在 README/Start/landing 给出一条 Cursor 命令,缩短增长入口 | 文档写“支持”不等于不同 Cursor 模型都能稳定产出;若做 Cursor 专属 skill 会造成分叉和维护漂移 | 高:临时目录安装到 Cursor 路径、`doctor`、五 mode 包装 smoke、文档生成一致性;真实模型效果只能另做非阻断 benchmark |+| **C. First Diagram Reliability Scorecard** | 用公开样例显示“哪些客户端/模型能在几轮内通过”,建立信任,也为后续门槛提供数据 | 模型、版本、仓库和费用使结果易漂移;若没有先改善协议,benchmark 只会暴露问题而不解决问题 | 中:IR 与 artifact gates 可确定性复跑;模型/Agent 端到端结果必须时间戳化并与 CI 阻断分离 |++## 6. 唯一推荐:Structured Repair Receipt++### 6.1 建议的有界范围++第一期只做“失败协议”,不做自动修图:++1. `archify validate ... --json` 在成功与失败时都只向 stdout 输出一个 JSON 对象;失败时不得泄漏 Node 堆栈到 stdout。+2. `archify deliver ... --json` 保持现有 envelope,并添加与 `validate` 共用的 `diagnostics` 合约。+3. 先覆盖最常见、最有稳定标识的类别:input、schema、repository evidence、通用 layout,以及现有 Clean Flow / composition 规则;未知内部异常可保留一个 `internal/unclassified` fallback,但必须明确不可自动修复。+4. 每条 diagnostic 只包含已知事实与支持的修复旋钮,例如:++```json+{+ "code": "clean-flow/edge-through-node",+ "severity": "error",+ "subject": {+ "collection": "connections",+ "index": 3,+ "id": "api-to-queue"+ },+ "evidence": {+ "obstacleId": "cache",+ "segmentIndex": 2,+ "clearancePx": 2+ },+ "supportedFixes": [+ "fromSide/toSide",+ "via",+ "route/channel",+ "node placement"+ ]+}+```++5. SKILL 只消费这些 diagnostics 来做局部修复,继续遵守最多两轮;不得因为有 JSON 就扩大重试预算。+6. 非 `--json` 模式继续提供简短人类可读错误,但应从同一 diagnostic 对象格式化,避免两套事实漂移。++### 6.2 实现时最重要的约束++- 不要对现有多行错误做长期正则解析;应在规则产生处保留结构化事实,再由边界层格式化文本/JSON。+- `supportedFixes` 只能列出该 mode 真正支持的字段或动作,不给模型“看起来合理但 schema 不接受”的建议。+- 成功 receipt 尽量保持兼容;若新增字段,保持 additive,并用 schema/version 测试锁定。+- `deliver` 的失败仍必须删除候选并保持旧成品逐字节不变。+- deterministic receipt 仍不代表 visual review;两者必须继续分开。++### 6.3 验收门槛++- 五种 diagram mode 各至少一个成功和一个失败 fixture。+- `validate --json` 的 input/schema/layout/check failure 均为有效 JSON,退出码非零,stdout 只有一个对象,无 Node stack。+- `deliver --json` 与 `validate --json` 对同一失败给出相同规则代码和对象身份。+- 每条已知 diagnostic 都有规则代码、severity、subject、evidence、supported fixes;未知错误明确标记,不伪造修复建议。+- 非 JSON 人类输出继续包含具体对象、阈值和修复提示。+- 失败 delivery 保持旧成品 SHA-256/bytes 不变,候选目录清理干净。+- `archify.zip` 零依赖安装 smoke 通过;现有 `npm test`、WebM/浏览器 smoke 全绿。+- 用内置浏览器完成一次“失败回执 → 一处局部修复 → verified artifact”的真实闭环;最终视觉复核仍单独记录。++## 7. 明确非目标++本切片不做:++- 自动移动节点、自动改 route、自动重写整份 JSON。+- 在 CLI 内调用 LLM、自动无限重试或承诺节省模型探索 token。+- 新 diagram type、新 visual preset、新 GIF/WebM 动效或新 Viewer 面板。+- D2/Mermaid engine 替换;当前问题是诊断协议,不是缺少另一个布局引擎。+- hosted upload、repository ingestion、账号系统、遥测或云端持久化。+- 移动端专项设计。+- blast radius、runtime causality 或 repository impact 推断。+- 把 deterministic validation 冒充 perceptual visual review。+- 同一切片顺带做 Cursor 专属 fork;Cursor onboarding 可作为紧随其后的增长切片,共享同一 `SKILL.md`。++## 8. 推荐顺序++1. 先完成 Structured Repair Receipt,并用当前 #6 类构图失败做一条真实闭环。+2. 再做 First-class Cursor Onboarding,借助统一失败协议扩大安装面,而不是扩大不确定性。+3. 最后建立带日期、客户端/模型版本、correction rounds 和视觉复核状态的 Reliability Scorecard;把它当产品证据,不把随机模型结果直接设为 CI 硬门槛。++这个顺序吸收了同类项目最值得学习的共同点:Fireworks 的有界收敛、GitDiagram 的 focused feedback、GitNexus 的结构前移与多客户端入口;同时保留 Archify 自己最强的差异化——离线、自包含、可验证、读图交互丰富,而且不虚构证据。++## 第一方来源++- Archify 当前仓库与 issues:[repository](https://github.com/tt-a1i/archify)、[#6](https://github.com/tt-a1i/archify/issues/6)、[#14](https://github.com/tt-a1i/archify/issues/14)、[#22](https://github.com/tt-a1i/archify/issues/22)、[#24](https://github.com/tt-a1i/archify/issues/24)、[#46](https://github.com/tt-a1i/archify/issues/46)+- Fireworks Tech Graph:[README](https://github.com/yizhiyanhua-ai/fireworks-tech-graph)、[Loop Engineering](https://github.com/yizhiyanhua-ai/fireworks-tech-graph#loop-engineering)+- GitNexus:[README](https://github.com/abhigyanpatwari/GitNexus)、[Quick Start](https://github.com/abhigyanpatwari/GitNexus#quick-start)、[Why a Knowledge Graph](https://github.com/abhigyanpatwari/GitNexus#why-a-knowledge-graph)、[Editor Setup](https://github.com/abhigyanpatwari/GitNexus#editor-setup)+- GitDiagram:[README](https://github.com/ahmedkhaleel2004/gitdiagram)、[How generation works](https://github.com/ahmedkhaleel2004/gitdiagram#how-generation-works)+- Cursor:[Cursor 2.4 Skills announcement](https://cursor.com/changelog/2-4)+- Vercel `skills` CLI:[README](https://github.com/vercel-labs/skills)、[Supported Agents](https://github.com/vercel-labs/skills#supported-agents)