{"owner":"tt-a1i","repo":"archify","hasSkills":true,"totalSkillsCount":4,"totalTokensCount":20005,"categories":["project-spec","anthropic-skill"],"hasMcp":false,"mcpConfig":null,"found":["DESIGN.md","archify/references/viewer-runtime.md","archify/SKILL.md","archify/references/delivery-contract.md"],"skills":{"DESIGN.md":"---\nname: Archify\ndescription: A precise, vivid technical instrument for trustworthy interactive architecture maps.\ncolors:\n  canvas: \"#020617\"\n  mask: \"#0F172A\"\n  ink: \"#FFFFFF\"\n  muted: \"#94A3B8\"\n  dim: \"#475569\"\n  border: \"#1E293B\"\n  frontend: \"#22D3EE\"\n  backend: \"#34D399\"\n  database: \"#A78BFA\"\n  cloud: \"#FBBF24\"\n  security: \"#FB7185\"\n  messagebus: \"#FB923C\"\n  external: \"#94A3B8\"\ntypography:\n  headline:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"1.5rem\"\n    fontWeight: 700\n    lineHeight: 1.2\n    letterSpacing: \"-0.025em\"\n  title:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.875rem\"\n    fontWeight: 600\n    lineHeight: 1.4\n    letterSpacing: \"normal\"\n  body:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.75rem\"\n    fontWeight: 400\n    lineHeight: 1.55\n    letterSpacing: \"normal\"\n  label:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.625rem\"\n    fontWeight: 700\n    lineHeight: 1.35\n    letterSpacing: \"0.12em\"\nrounded:\n  precise: \"0.2rem\"\n  control: \"0.5rem\"\n  panel: \"1rem\"\n  pill: \"999px\"\nspacing:\n  xs: \"0.25rem\"\n  sm: \"0.5rem\"\n  md: \"0.75rem\"\n  lg: \"1rem\"\n  xl: \"1.5rem\"\n  page: \"2rem\"\ncomponents:\n  toolbar-button:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.5rem 0.875rem\"\n    height: \"2.75rem\"\n  diagram-panel:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    rounded: \"{rounded.panel}\"\n    padding: \"1.5rem\"\n  search-field:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.58rem 0.65rem\"\n  evidence-beacon:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.backend}\"\n    typography: \"{typography.label}\"\n    rounded: \"{rounded.pill}\"\n    size: \"30px × 12px\"\n---\n\n# Design System: Archify\n\n## Overview\n\n**Creative North Star: \"The Evidence Console\"**\n\nArchify is a composed technical instrument, not a drawing suite. The canvas carries one spatial narrative; restrained controls and progressive disclosure let a reader move from the primary path to exact authored relationships, metadata, and verified code evidence without losing orientation.\n\nThe visual system is precise, dark-first, and vivid only where semantics earn it. Light mode and Blueprint preserve the same vocabulary rather than becoming separate products. Motion has one bounded owner, finishes, and never carries meaning that disappears in a still frame. Desktop is the primary surface; narrow screens receive containment, not a second interface.\n\n**Key Characteristics:**\n\n- One dominant technical canvas with compact, low-interference chrome.\n- A fixed semantic color vocabulary shared by nodes, edges, legends, focus, and evidence.\n- Mono-forward typography, small labels, and deliberate density for engineering review.\n- Viewer state stays outside canonical exports; proof remains portable and deterministic.\n- State transitions are 140–200ms; authored story motion may be longer but finite and reader-controlled.\n\n## Colors\n\nThe palette is a midnight console with seven semantic signals; color identifies meaning, never decoration.\n\n### Primary\n\n- **Verified Cyan** (`frontend`): the main focus, navigation, and frontend signal. Its scarcity establishes hierarchy.\n\n### Secondary\n\n- **Proof Green** (`backend`): backend semantics, verified evidence, and successful state.\n- **Repository Violet** (`database`): persisted state, stores, and inward relationships.\n\n### Tertiary\n\n- **Boundary Rose** (`security`): policy, security, and guarded paths.\n- **Cloud Amber** (`cloud`), **Transit Orange** (`messagebus`), and **External Slate** (`external`): stable semantic categories, never interchangeable accents.\n\n### Neutral\n\n- **Midnight Canvas** (`canvas`) and **Ink Mask** (`mask`): the dark workspace and opaque geometry mask.\n- **Instrument Ink** (`ink`), **Quiet Copy** (`muted`), **Dim Annotation** (`dim`), and **Structural Border** (`border`): the text and containment ladder.\n\n### Named Rules\n\n**The Semantic Color Rule.** Every saturated color maps to a node or relationship meaning; never add an accent merely to make a surface lively.\n\n**The Theme Parity Rule.** Light, dark, Signal Flow, and Blueprint may change material and contrast, but must preserve category identity and information priority.\n\n## Typography\n\n**Display Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Body Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Label/Mono Font:** JetBrains Mono\n\n**Character:** A single mono family makes the artifact feel authored by an engineering instrument. Hierarchy comes from weight, scale, spacing, and case rather than a decorative display face.\n\n### Hierarchy\n\n- **Headline** (700, `1.5rem`, 1.2): artifact title only.\n- **Title** (600, `0.875rem`, 1.4): panels, cards, and selected semantic objects.\n- **Body** (400, `0.75rem`, 1.55): explanatory copy and relationship details.\n- **Label** (700, `0.625rem`, `0.12em`, uppercase): state, modes, metadata, and compact proof markers.\n\n### Named Rules\n\n**The One Voice Rule.** UI and diagram chrome remain mono-forward; never introduce a display font inside the generated artifact.\n\n**The Legibility Floor Rule.** Tiny labels are metadata, not prose. If a reader must parse a sentence, promote it to body size or disclose it on focus.\n\n## Elevation\n\nArchify is flat and tonal by default. Borders and surface contrast establish structure; shadows appear only on floating controls, temporary panels, active focus, or the Signal Flow atmosphere. Blueprint removes glow and squares materials to keep the review surface exact.\n\n### Shadow Vocabulary\n\n- **Canvas Lift** (`0 28px 80px rgba(0,0,0,0.34)`): Signal Flow diagram surface only.\n- **Floating Panel** (`0 18px 48px rgba(0,0,0,0.30)`): temporary discovery panels and the Semantic Passport.\n- **Action Feedback** (`0 0 7px var(--frontend-stroke)`): active SVG focus only, never an idle decoration.\n\n### Named Rules\n\n**The Flat-at-Rest Rule.** A static card or control uses border and tone; a shadow must explain layering or state.\n\n**The Canonical Clean Rule.** Viewer glow, overlays, focus, and temporary marks are removed from visual exports unless the export explicitly owns that narrative.\n\n## Components\n\n### Buttons\n\n- **Shape:** compact rounded rectangle (`0.5rem`), or precise corners (`0.2rem`) in Blueprint.\n- **Primary:** translucent toolbar material, one-pixel structural border, and mono body label. Desktop viewer chrome may use compact 32px controls; touch and narrow-screen targets stay at least `2.75rem` high.\n- **Hover / Focus:** 150ms border/background response; `2px` cyan focus ring with `2px` offset.\n- **Secondary / Ghost:** transparent within menus; never add a second saturated fill hierarchy.\n\n### Chips\n\n- **Style:** quiet bordered capsules for semantic metadata; selected state uses the owning semantic color.\n- **State:** a chip may summarize focus, mode, count, or evidence, but must not become an unlabeled icon-only control.\n\n### Cards / Containers\n\n- **Corner Style:** composed panel corners (`1rem`), reduced to `0.35rem` in Blueprint.\n- **Background:** tonal panel over the canvas, with a one-pixel border.\n- **Shadow Strategy:** flat by default; floating or Signal Flow surfaces use the elevation vocabulary.\n- **Internal Padding:** `1.25rem`–`1.5rem` for panels; compact proof blocks may use `0.5rem`–`0.75rem`.\n\n### Inputs / Fields\n\n- **Style:** one continuous bordered field, `0.5rem` corners, muted placeholder, and compact mono body text.\n- **Focus:** no browser outline; shift the border to Verified Cyan and add a restrained two-pixel halo.\n- **Error / Disabled:** preserve readable text and add a non-color cue; never rely on opacity alone for failure.\n\n### Navigation\n\n- **Style:** the diagram remains dominant. Toolbar, guided views, map, search, and passport appear only when relevant and reuse familiar labels.\n- **Default / Hover / Active:** 140–200ms state response; active state combines text, border, shape, or marker—not color alone.\n- **Narrow screens:** contain and stack existing controls safely; do not create a dedicated mobile product surface.\n\n### Semantic Passport\n\nOne focused node opens one compact proof surface containing stable ID, authored metadata, relationships, and optional revision-pinned sources. It is the single destination for details; new capabilities should route here before proposing another panel.\n\n### Verified Source Beacon\n\nAn evidence-backed node receives one viewer-only `SRC n` capsule in its upper-right corner. It inherits node state, adds no tab stop, and is stripped from every canonical visual export.\n\n### Brand Mark\n\nAn authored `brand` adds one compact identity badge to the upper-right of the\nnode. Built-in vectors and explicitly captured, digest-pinned site icons sit on a neutral plate;\ntheir color stays inside that plate and never recolors the semantic node, edge,\nlegend, focus, or evidence vocabulary. The semantic sigil remains visible. A\nVerified Source Beacon shifts left when both facts are present. Brand marks are\ncanonical authored SVG content and therefore survive visual export.\n\n### Authored Reachability\n\nSemantic Passport offers two native, count-bearing actions: `Upstream` follows authored incoming relationships and `Downstream` follows authored outgoing relationships. The canvas keeps the focused origin plus the complete reachable subgraph strong while unrelated topology recedes. Upstream uses Repository Violet, downstream uses Proof Green, and Blueprint removes glow. The receipt says nodes, links, and maximum hops; it never says blast radius or breakage.\n\n### Reach Share Card\n\nAn active reach query may expose one contextual **Export → Reach Share Card** item. The 1200×630 card keeps the full diagram as quiet context, preserves the selected origin and every matched authored node and link, and writes direction, origin, node count, link count, and maximum hops into the card header. Upstream retains Repository Violet; downstream retains Proof Green; Blueprint stays filter-free. The card is an explicit non-canonical reading variant, not runtime impact, causality, or breakage evidence. No animated state, live focus glow, camera transform, or unrelated viewer chrome enters the clone.\n\n## Do's and Don'ts\n\n### Do:\n\n- **Do** make the primary path legible before adding secondary relationships or detail.\n- **Do** derive every focus, reachability query, route, story, source link, receipt, and count from authored or locally verified evidence.\n- **Do** keep ordinary artifacts source-free and make repository evidence explicitly opt-in.\n- **Do** use 140–200ms transitions for control state and honor `prefers-reduced-motion`.\n- **Do** preserve keyboard access, visible focus, semantic labels, dark/light parity, and non-color state cues.\n- **Do** keep runtime exploration outside canonical SVG, raster, Share Card, and WebM backgrounds.\n- **Do** name an intentionally scoped Route or Reach Share Card in its header and machine-readable receipt.\n\n### Don't:\n\n- **Don't** build generic Mermaid beautifiers that change themes without improving information architecture.\n- **Don't** turn Archify into WYSIWYG drawing suites whose editing chrome becomes the product.\n- **Don't** ship motion-first graph demos that imply relationships or activity not present in the authored source.\n- **Don't** use dense dashboard shells, endless identical card grids, decorative glass, gradient text, and other AI-generated interface clichés.\n- **Don't** infer identity from arbitrary label text, add an unbounded icon marketplace, or let a brand badge replace the portable semantic vocabulary.\n- **Don't** create another permanent panel when the Semantic Passport, Node Finder, or existing canvas can carry the capability.\n- **Don't** call graph reachability runtime impact, blast radius, or breakage without independent code-analysis evidence.\n- **Don't** change the README Hero as a side effect of artifact or viewer iteration.\n","archify/references/viewer-runtime.md":"# Viewer Runtime reference\n\nRead this only when the user asks for a reader-facing capability. Ordinary generation does not require implementing or re-documenting these features; they are already in the generated HTML.\n\n## Exploration\n\n- Diagram Guide lists current actions and shortcuts. Open it with the guide button or `?`; it never opens automatically.\n- Reading Depth starts at READ at the default 100% scale, reveals FULL detail at 175%, and falls back to MAP only below 100%. Focus, route, and semantic interactions reveal their exact facts at any scale.\n- Semantic Lens summarizes selected node/relationship kinds without changing authored geometry.\n- Intent Trace previews a fine-pointer or keyboard target before committed focus.\n- Node Finder searches labels and stable IDs.\n- Semantic Passport opens on focus, shows authored upstream/downstream facts, supports a copyable deep link, has an explicit close action, closes on true outside activation and Escape, and never enters canonical export.\n- Semantic Radar mirrors the visible viewport and authored graph without becoming a second source of truth.\n- Direct Relationship Pin makes a unique compiled relationship operable while preserving the authored line and stable relationship identity. It must fail closed on conflicting source/target/label/ID metadata.\n- Route Probe resolves exactly two endpoints over authored directed relationships. It never infers a route from geometry.\n\n## Embedded reading addresses\n\nA host displaying the native reader in an opaque `srcdoc` frame may set\n`data-reading-link-template` on that reader's `html` element. Supply an absolute\nHTTP, HTTPS or file URL containing exactly one `{state}` marker, for example\n`https://example.test/architecture#page=mechanism&reader={state}`. Native Focus,\nRelationship, Reach, Route and Lens copy actions replace the marker with their\npercent-encoded opaque query state. The host keeps its page identity and restores\nthat value as the native frame's hash; it never parses or reconstructs queries.\n\nAbsent configuration preserves standalone links. Invalid, credential-bearing or\nunsupported URL templates make copying fail without accessing the clipboard.\nThis seam changes copied addresses only, not query parsing, history, permissions,\nembedding isolation or authored geometry. It adds no network or storage surface.\n\n## Motion and presentation\n\nFor a narrated walkthrough with camera framing, explanations, captions and\nsynchronized audio, use [Story authoring](story-authoring.md). The `story attach`\ncommand adds Story to the native motion control and Story video to Export.\nThe player loads on first use and follows the existing preset and theme controls.\nPlayback schedules two short audio buffers ahead instead of synthesizing the whole timeline.\nVery large video exports are rejected before rendering. Use\n`Archify.story.exportVideo({start, seconds})` for a shorter range when needed.\n\nEvery rendered diagram enables reader-controlled Live/Still motion by default. In Live, every edge runs a small light show on one shared cycle: a comet (glow, halo, tail, head, plus a dimmer echo on every edge) cascades downstream, leaves a soft wake, and lands as a ripple on the target node, while nodes enter once and then glow on the same cycle with authored-step staggering. Phases follow the authored step order (source-node rank, chronological in sequence diagrams); the flow rides a separate Viewer overlay and the original line styles and arrowheads remain intact. Compact edges receive a larger, brighter comet; echoes stay dimmer. With no saved preference, new pages start Still. Choosing Live starts continuous flow and saves that preference; choosing Still stops it and clears the saved Live preference. Existing saved Still preferences remain Still. Semantic exploration temporarily owns the motion budget, and continuous flow resumes when that action releases it. Diagrams without connections retain their bounded node entrance rather than inventing a flow. Omit `meta.animation`; historical `\"trace\"` and `\"none\"` values remain accepted for input compatibility and do not change this default. Reduced motion, page hiding, print, and canonical export preserve complete static meaning. Presentation Stage changes viewer chrome and framing, never authored geometry. This is not a mobile product feature; narrow layouts get containment only.\n\n## Canonical exports\n\nThe export menu can copy/download full-diagram PNG, download JPEG/WebP, download a dual-theme SVG, and record a trace-enabled WebM. Viewer state—Guide, Lens, finder, focus, route, camera, radar, presentation, motion ownership, and temporary overlays—must be removed from canonical export.\n\nOpening, closing, or completing an export preserves the live Focus/Reach selection for continued exploration. Export-owned download activation is not outside dismissal; genuine outside activation and Escape retain their existing behavior. Full-diagram PNG/SVG exports still contain the complete canonical diagram, while the Reach Share Card communicates the active authored closure.\n\n### Route Share Card\n\nAfter a real directed Route Probe resolves, the reader may use **Export → Route Share Card**. It reuses the exact ordered route snapshot and the shared Share Card seam: `format=share-card`, `variant=route`. The isolated clone may use only static `data-share-route-*` decoration. It is download-only, fails closed for stale/unreachable/conflicting routes, and never becomes the canonical artifact.\n\n### Reach Share Card\n\nAfter a non-empty authored reachability query, the reader may use **Export → Reach Share Card**. It consumes the already resolved upstream/downstream node and edge set without rerunning traversal: `format=share-card`, `variant=reach`. The isolated clone may use only static `data-share-reach-*` decoration. It is download-only. Call it authored reachability—not impact, blast radius, breakage, or runtime causality.\n\n## Truth boundary\n\nViewer exports are communication assets. They do not replace the checked HTML, the deterministic delivery receipt, or a real visual review. Do not add a hosted service, storage surface, dependency, schema branch, or mobile product surface for these viewer-only capabilities.\n","archify/SKILL.md":"---\nname: archify\ndescription: \"Create validated architecture, workflow, sequence, data-flow, lifecycle/state, ERD, class, tree, timeline, and waterfall diagrams as explorable standalone HTML with dark/light themes, motion and image/SVG/WebM export. Accept requirements or Mermaid; inspect repository evidence for code-backed diagrams. Also investigate local repository architecture health, coupling and refactoring scope with source-backed Code Analysis. Use when visualizing systems, API calls, pipelines, schemas, histories, timings, or everyday steps, parts, relationships and states. Also turn an answer into a one-page explainer, with the conclusion first, structured panels, native diagrams and charts, when the user asks for a page, an explainer or an answer to share (做成一页, 用页面讲), and by default unasked for a complex flow, diagnosis, comparison or test report; an [archify explainer: on-demand] rules line limits pages to requests. Optionally add a guided story and video export to an existing native diagram. Not for dashboards.\"\nlicense: Apache-2.0\nmetadata:\n  version: \"3.3\"\n  author: tt-a1i\n---\n\n# Archify\n\nCreate checked HTML as a native diagram, explainer, story, or standalone Code Analysis workbench.\n\nRun commands from your working directory. Unless the user names another location, give each new artifact request its own folder `.archify/<type>-<slug>-<YYYYMMDD-HHMMSS>/` there (local time, chosen once): keep the candidate and `<slug>.html` in it and reuse it for repairs. Native diagrams use `candidate.json` with `meta.output` relative to the working directory; explainers may use `candidate.archify.md` and a portable output filename. A later request gets a new folder. Replace `bin/archify.mjs` in every command with the installed package's absolute path, or its path relative to your working directory; CLI input and output paths resolve from that directory.\n\nFor a native diagram of a real codebase, read [Repository authoring](references/repository-authoring.md) while tracing the requested behavior. A system description uses the native steps below; a frozen candidate uses the handoff path.\n\n## Choose the artifact\n\n- For drawing a system, flow, schema or history, use a native diagram and the Type router. Deliver the requested diagram through `finalize`; code analysis is a separate mode.\n- For local repository architecture health, module coupling, cycles, layer violations, large files, complexity hotspots or refactoring orientation, use Code Analysis below; the agent handles commands and no architecture JSON is required.\n- For a guided walkthrough, animated/static dual-theme SVG, interactive stage player, or 1080p MP4/WebM video over one or more native diagrams, read [Story authoring](references/story-authoring.md). Use `story draft`/`attach` to add playback to a native Viewer, or `story validate`/`svg`/`stage`/`video` for declarative component choreography.\n- Only when the user explicitly asks to explain or visualize a pull request, a branch change or a `git diff`, or to attach change diagrams to a PR, or names the companion skill `archify-pr` when installed, read [PR review authoring](references/pr-review.md) first: it covers the three-dot diff, change-marked merged-superset views and the `pr validate` / `pr build` / `pr attach` loop.\n- Use `explainer` when the user asks for the answer as a page: a page, one page, an explainer, something to share (“做成一页”, “用页面讲”, “answer with a page”).\n- Explainer mode is `proactive` by default. A rules line `[archify explainer: <mode>]` in context selects another; an instruction in the conversation overrides it for that conversation.\n  - `proactive` (default, no line needed): also make a page, unasked, when the answer is a complex flow or process, a diagnosis or troubleshooting result, an option comparison, trade-off or decision, a test or review report, or a plan, and needs a table, steps or several sections to be read well.\n  - `on-demand`: make a page only when asked; otherwise answer in text or draw the requested diagram.\n  - `always-on` (opt-in only): every reply that reaches a conclusion also gets a compact page of at most four panels.\n- In every mode a page needs a conclusion with some structure behind it. Chat, short or one-line answers, routine status updates (“done, tests pass”), raw command output, a requested native diagram and any reply where the user asks for text only or no page (“只要文字”, “不用做页面”) get none. Make at most one page per reply, and none when the user names another page tool or another skill already made a page for that reply.\n- To change the mode, only when the user asks (“只在我要求时做页面”, “always make a page”), write or replace one `[archify explainer: <mode>]` line in the current agent's global rules file (such as `~/.codex/AGENTS.md`, `~/.claude/CLAUDE.md` or `~/.config/devin/AGENTS.md`) and name the file, for example `[archify explainer: on-demand] Make Archify explainer pages only when I ask for one.`; deleting the line restores `proactive`. Never switch to `always-on` unasked.\n- For `explainer`, read [Explainer authoring](references/explainer-authoring.md) for its conclusion, reasons, scope, board layout and optional native diagrams. Write the complete draft, then run `finalize explainer` for validation, atomic delivery and artifact checks. Use panel patch for local content revisions.\n\n## Existing candidate handoff\n\nWhen the user supplies a frozen candidate, run `finalize` first as one CLI invocation. Its passing receipt completes the automated gates; follow any visual review recommendation under Delivery before claiming visual quality. For repair, follow step 5.\n\n`finalize` includes a bounded update check in its delivery receipt; see Update awareness.\n\n## Native diagram authoring\n\nUse this path for ordinary generation. Read branch references only when their stated trigger applies.\n\n1. Choose `architecture`, `workflow`, `sequence`, `dataflow`, `lifecycle`, `erd`, `class`, `tree`, `timeline`, or `waterfall` from the question.\n2. Use the exact schema and example paths in the Type router without listing their directories. Read [Authoring defaults](references/authoring-defaults.md) and the mode's example in a bounded batch separate from project documents and complete schemas so neither is truncated; recover any missing section before writing. For a new Architecture, use `\"layout\": {\"mode\": \"auto\"}` and leave component positions to the renderer. Take component and relationship fields from the matching showcase example. Preserve any layout the user supplied. For every mode except Architecture, also read the mode and common schemas. Read the relevant schema definition before choosing any new field, enum, or constrained text, especially boundary kinds. Examples teach shape, not facts. Use fresh IDs, wording, and layout. Go directly to the candidate without preliminary help, doctor, starter validation, temporary diagrams, or output-path listing. Query brands only for an explicitly requested mark; read [Brand marks](references/brand-marks.md) for an unknown mark with a user-provided URL.\n3. Once the requested scope and, for a real codebase, [source evidence](references/repository-authoring.md) are covered, write the complete candidate directly without planning coordinates in prose. Choose Architecture abstraction and connected placement using Authoring defaults before coordinates: show the main user journey and necessary branches, preserve control roles and behavior-changing conditions, and leave enough room for actual relationship labels. No node, relationship, source, view, card, or boundary count is a target or ceiling. Use automatic routes first; add explicit routing only for necessary branch, return, supplied geometry, or measured repair. Set `meta.quality_profile` to `\"showcase\"` unless the user requests dense `standard`. For a grid ERD with automatic canvas, placement and routing, omit `layout.entityW` and entity `width` to fit fields. With a fixed view box, pinned table or manual route, size wide tables explicitly. For ERD, use a table-first layout: show every physical column in `entities[].attributes`, keep its SQL type and source comment, state every key role a column carries (`key` takes a role or a list, so a junction column is `[\"pk\", \"fk\"]`, and every `fk` column also needs `references` like `\"orders.id\"`), and never move columns into cards as a substitute for the table. Classify tables into functional domains before placement, give each domain a concise `tag`, and place its members in one solid rectangle of grid cells — a single row, a single column, or a filled rectangular block, not an L or diagonal. A tagged table always needs `row`/`col`, because absolute coordinates have no grid cells and a domain whose tables do not fill one rectangle cannot be drawn as a band: the renderer reports `erd/domain-not-drawn` instead of publishing a diagram that cannot name the domain. A multi-domain schema reads best as one domain per column — each `tag` a vertical run — because the reader scales a wide canvas up to the reader width and shrinks a tall one until the page fits, so the wide arrangement is the one that stays complete and legible inside a laptop viewport. A schema-first ERD over roughly 8 tables or 50 fields is itself a dense map: author its first complete-field pass at `standard` and upgrade only once the layout still reads.\n4. Once the complete first candidate is written, run `finalize` directly. Its first gate is showcase validation; successful first drafts need no separate pre-validation. Keep the candidate unchanged while the command runs:\n\n   ```bash\n   node bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n   ```\n\n   For a repository-backed candidate, include evidence on the first draft and use the complete first command: `node bin/archify.mjs finalize <type> <candidate.json> <output.html> --repo-root <repo-root> --quality showcase --json`. Pass the `--quality` that matches `meta.quality_profile`, such as `standard` for a dense first ERD pass.\n\n   A passing receipt proves the included `validate`, `deliver`, strict `check`, and real-browser `browser-check` gates passed. Use its compact summary; run standalone commands only for a separate request or focused failure diagnosis. After a passing Architecture finalize with `codeAnalysisOffer`, end the delivery summary with the [Architecture Diagnosis section](references/delivery-contract.md#architecture-diagnosis-offer) in the user's language, once per repository in the task. Skip it if the user already asked for or declined analysis. Wait for yes before running the offered command.\n\n5. A non-zero exit is never success. Read compact stdout or `evidence.summaryReceipt`, then [repair the failed gate](references/delivery-contract.md#failed-finalize-and-candidate-repair), including its repair limit. Preserve requested meaning and source evidence. For several tangled Architecture routes, read [Architecture layout repair](references/architecture-layout-repair.md); for measured field or geometry failures, read [Authoring contract](references/authoring-contract.md). Edit the connected neighborhood and rerun the complete `finalize` command from step 4. Once a run has reached `browser-check`, the output path owns that evidence: give every later run its own `--out-dir <folder>/review-<n>`.\n\n## Update awareness\n\n`finalize` and standalone `deliver` include `update` in their receipts. Do not run a separate check for the same delivery. If `update.noticeRequired` is true, read `references/update-awareness.md` and keep one compact update notice in your final response to the user, even after a quality gate fails. For a task with several diagrams, mention the update once in the final response. Snooze or ignore a reminder only when the user explicitly asks; never install or update on your own initiative.\n\nBefore the first candidate, use the authoring references and relevant repository source, not Archify implementation or tests. Inspect Archify implementation if diagnostics remain unactionable after focused repairs.\n\n## Type router\n\n| Type | Use for | Schema | Example |\n|---|---|---|---|\n| `architecture` | Components, services, cloud/security boundaries, infrastructure; what something everyday is made of | `schemas/architecture.schema.json` | System descriptions, services, libraries, and CLI repos: `examples/web-app.architecture.json`; deployment repos: `examples/production-deployment.architecture.json` |\n| `workflow` | Processes, approval gates, tool calls, runbooks, CI/CD; plans and step-by-step life processes | `schemas/workflow.schema.json` | `examples/agent-tool-call.workflow.json` |\n| `sequence` | API call chains, request lifecycles, async traces, returns; back-and-forth between people | `schemas/sequence.schema.json` | `examples/cache-miss-request.sequence.json` |\n| `dataflow` | Pipelines, ETL/ELT, lineage, governance, consumers; where money or documents go | `schemas/dataflow.schema.json` | `examples/product-analytics.dataflow.json` |\n| `lifecycle` | State/status transitions, retries, waiting and terminal states; where an application or order stands | `schemas/lifecycle.schema.json` | `examples/deployment-release.lifecycle.json` |\n| `erd` | Tables/entities, attributes, primary/foreign/unique keys, cardinality between them | `schemas/erd.schema.json` | `examples/orders.erd.json` |\n| `tree` | Single-parent containment: repository/module trees, capability or feature breakdowns, org-style decomposition | `schemas/tree.schema.json` | `examples/payment-platform.tree.json` |\n| `class` | Classes, interfaces, selected members, and dependency/association/inheritance/realization/composition between types | `schemas/class.schema.json` | `examples/payments.class.json` |\n| `timeline` | When things happened: incident reviews, release histories, timestamped events on a proportional clock with source lanes | `schemas/timeline.schema.json` | `examples/payment-incident.timeline.json` |\n| `waterfall` | Where the time went: span durations, overlap, and nesting of one request or agent run on a common time axis | `schemas/waterfall.schema.json` | `examples/checkout-request.waterfall.json` |\n\nWhen choosing among native diagram types is ambiguous, run `node bin/archify.mjs guide \"<scenario>\" --json`. Scenario proof examples are structural references, not facts to copy.\n\nFor an everyday subject, keep the same diagram modes and semantic types, then name them for the reader: use everyday `icon` values and `meta.legend` labels as in [Node icons](references/authoring-contract.md#node-icons). Ask for missing personal facts instead of inventing dates, amounts, or rules.\n\n## Mermaid input\n\nRead Mermaid for topology and meaning, then author fresh Archify JSON; do not mechanically render Mermaid styling.\n\n- `flowchart` / `graph` → `workflow`, or `architecture` for a component map.\n- `sequenceDiagram` → `sequence`; participants become semantic participants and arrows become messages.\n- `stateDiagram` → `lifecycle`; states and transitions retain meaning, not Mermaid style.\n- `erDiagram` → `erd`; entity and relationship names, keys, and cardinality retain meaning, not Mermaid style.\n- `classDiagram` → `class`; type kinds, selected members, and relationship kinds retain meaning, not Mermaid style.\n\n## Delivery\n\nUse the `finalize` command above for the first candidate and after a repair.\n\n`finalize` stops at the first non-passing gate. Its compact stdout and `<output-stem>.finalize-summary.json` are ordinary evidence. A passing run creates no screenshots and reports `visualReview: \"not-requested\"`.\n\nWhen a passing Architecture receipt reports `visualReviewRecommendation.signals.resolvedCrossovers`, save the candidate and follow [Architecture layout repair](references/architecture-layout-repair.md). Where several lines cross the reader’s main path, place the connected main steps in order and put each branch beside the component that owns it. Use the hints to locate the affected relationships. Make one edit to node positions and sizes only: every node, relationship (including its `from` and `to`), label, and source stays as it was. Rerun the complete `finalize` once with `--out-dir <folder>/review-2`, because the previous HTML already owns its browser evidence. `--out-dir` relocates the new browser-check and default finalize receipts, not the HTML or its delivery receipt. Successful delivery rewrites that pair at the requested output path; earlier review evidence remains bound to its original artifact bytes. See [review evidence paths](references/delivery-contract.md#a-new-candidate-at-an-existing-output-path). If that run fails, reports more crossings, or reports the same crossings with more `signals.routesOverSuggestedBends`, restore the copy and finalize it with `--out-dir <folder>/review-3`. Do not start a second placement round. Hints about extra bends alone are optional.\n\nWhen `layoutReviewRecommendation.action` is `inspect-sequence-width`, follow [Sequence width review](references/delivery-contract.md#sequence-width-review) before handing off a newly authored Sequence.\n\nFor a project README, deliver a static SVG by default. Follow an explicit request for a link or interactive HTML. Use Chrome or Chromium to export the finished HTML to a new file with `node <skill-dir>/bin/export-svg.mjs <diagram.html> <image.svg> [auto|light|dark]`. If the answer depends on small labels or Viewer cards, deliver a paste-ready Markdown image and a short caption that answers the question at normal text size.\n\nFor a README or project document, inspect the delivered diagram at its intended reading size. Follow the arrows from the starting point through each return or branch needed to answer the request. Verify conditional steps, fields and checks against the source, and name the condition where the reader sees the claim. Repair a broken reading path and inspect the result. For multiple runtimes or conditional handoffs, use the [reader check](references/repository-authoring.md#check-the-readers-answer).\n\nPerceptual review is optional for ordinary generation. Use [Optional capture evidence](references/delivery-contract.md#optional-capture-evidence), with `--out-dir <folder>/visual-check`, for a reproducible review or a concrete route/browser concern. `visualReviewRecommendation` is advisory. Inspect captures before claiming visual quality; qualify any check claim as automated when perceptual review has not occurred.\n\nRead [Delivery contract](references/delivery-contract.md) for failed gates, standalone commands, provenance/recovery, repeated delivery, exports, or opening. Native diagram recovery follows `deliver` → strict provenance `check` → `browser-check`; captures require strict provenance. Explainer delivery uses validate, deliver and check as described in its authoring guide.\n\nFor workflow viewport overflow, read [Workflow viewport repair](references/authoring-contract.md#workflow-viewport-repair) before the next layout edit.\n\nWhen reporting verification details, distinguish artifact checks, browser evidence, captures, and actual perceptual review. For an explicitly requested immediate preview or active desktop loop, see [Optional opening](references/delivery-contract.md#optional-opening).\n\n## Code Analysis (local repository architecture)\n\nFor a repository investigation, run `node bin/archify.mjs code-analysis prepare <repo-root> --out <analysis-dir> [--locale zh-CN|en] [--language ts|py|java|go|rust]`. Use `--locale zh-CN` for Chinese conversations. It creates `analysis/repo.analysis.html` with a source-backed workbench, interactive Atlas and captured AI tasks, then exits. No architecture JSON or diagram authoring is needed. Normal diagram requests end with their `finalize` delivery; analysis runs when the user requests investigation. Add `--ir <architecture.json>` only when a relevant diagram already exists or the user also wants authored architecture boundaries aligned with code evidence. This keeps the existing architecture/Atlas views and checked source mapping. Read [Code Analysis entry and investigation](modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation) for adapter prerequisites, headless checks, interactive re-analysis and coverage limits. Deliver the analysis HTML with one or two scoped observations and its task-copy controls, or continue investigating in this conversation. Users need no maintenance objective or CLI knowledge. Analysis describes the working tree, including uncommitted source; keep authored commit evidence separate. Verify source before editing, make a scoped improvement or explain why to retain the structure, then rerun analysis and project tests. Report measured preparation time and tool gaps, preserve any separately delivered diagram on failure, and avoid claims that static or missing findings prove runtime failure or a fix.\n\n## Optional viewer capabilities\n\nArchitecture, Workflow, Sequence, Dataflow and Lifecycle nodes may carry optional plain-text `explanation` (1–1200 characters). The focused Semantic Passport offers Explain; prose stays outside canonical SVG and visual exports. Omit the field when the existing label, sublabel and sources are sufficient.\n\nLive motion is enabled by default for every rendered diagram; omit `meta.animation`. The Viewer’s Live/Still button controls playback.\n\n### Cross-diagram navigation (overview → module → detail across HTML artifacts)\n\n- Targets are same-directory `filename.html` only (optional `?` / `#`). No `../`, `/`, or schemes.\n- Node `href` is sugar for a one-entry list (label defaults to the node label). `drilldowns` wins if both are present.\n- One child: native SVG `<a>` + corner mark; click follows the link; Alt-click focuses Passport.\n- Several children: Passport lists every target; click focuses; Ctrl+click / double-click opens the first entry.\n- Child diagrams may set `meta.parentHref`. The header Back control appears when `parentHref` or URL `?from=` is present.\n- Examples: sibling pair `examples/drilldown-platform.architecture.json` ↔ `examples/drilldown-integrations.architecture.json`; multi-child `examples/drilldown-overview.architecture.json`.\n\nRead `references/viewer-runtime.md` only when the user explicitly asks for Share Cards, Route/Reach cards, motion, deep links, presentation, search/focus, or another Viewer Runtime feature.\n\n## Setup and fallback\n\nNo install is required inside the skill package. For setup diagnosis, verify with:\n\n```bash\nnode bin/archify.mjs doctor\nnode bin/archify.mjs demo <output-directory>\n```\n\nFor native diagrams, when shell access is unavailable, hand-place architecture SVG into `assets/template.html`, use CSS semantic classes rather than inline colors, and follow the visual review contract in `references/delivery-contract.md`. Explainers require their renderer and real delivery gates; if those are unavailable, report the limitation and give a text answer when useful, without claiming HTML delivery.\n\n## Output\n\nReply in the user's language, as briefly as the result allows; the diagram carries the content, so a single diagram usually needs one line.\n\n- For a README diagram, lead with a link to the requested artifact (the exported SVG by default). Link the README when edited. For other native diagrams, lead with the HTML. Use descriptive Markdown links with absolute paths, wrapping paths with spaces in `<...>`.\n- When the user wants to understand a system or codebase rather than draw a described subject, add one or two sentences with the key takeaway. Skip sentences that only restate what the diagram obviously shows.\n- State anything that changes how the diagram should be read: the abstraction level or deliberately omitted parts when a reader might expect them, illustrative rather than measured values, missing source evidence, or requested content dropped or merged during repair.\n- For several diagrams, report completion once with a link to an existing overview or compact per-diagram links, not a directory path.\n\nDo not recap commands, repair rounds, hashes, quality profiles, or check lists; they stay in the receipts. If asked whether the diagram was verified, answer in one line, such as “Automated checks passed; not visually reviewed.” Give receipt links and details only for reproducibility or troubleshooting. Disclose requested visual review that could not run, and claim visual inspection only when performed. Keep the required update notice under Update awareness.\n\nExample: `Created [Checkout request timing](/abs/path/checkout-timing.html). Durations are illustrative, not measured.`\n\nFor an explainer, the reply must read well without opening the page: the conclusion in one to three lines with the key cause, numbers or recommendation, then, as the very last line, a Markdown link with a descriptive title in the user's language, such as `[查看测试报告](/abs/path/test-report.html)` or `[Open the test report](...)`. Use the absolute path, wrapped in `<...>` when it contains spaces, not `file://`; put any update notice before it. Never offer a directory, terminal log or auto-open (`--open`) instead of the link. When `finalize explainer` fails or the renderer is unavailable, answer in text, say in one line that the page was not produced, and give no page link. Mention gates only when one failed or writing warnings remain; do not paste the draft.\n","archify/references/delivery-contract.md":"# Delivery contract\n\n## Failed finalize and candidate repair\n\n`finalize` stops at the first non-passing gate. Use compact stdout or `evidence.summaryReceipt`; read its full sidecar only when the summary lacks evidence needed for a coherent repair. A receipt with four artifact checks is basic validation, not showcase acceptance: require all nine checks, zero composition errors, and zero warnings. Fix `meta.quality_profile` and schema errors before geometry. A dense full-schema ERD may keep `standard` for its first complete-field pass: require zero structural errors, no edge-through-node failures, complete field rows, and a readable grouped grid, and record composition warnings instead of spending unbounded time on them.\n\nWhen every diagnostic from the first embedded validation is\n`repository-evidence/line-out-of-range`, `finalize` may narrow an existing\ncitation's `end_line` to the last line of its pinned file and retry the complete\ngates once. The start line must already exist in that nonempty file; the source\npath, revision, start, and all other authored content stay unchanged. Automatic\nrepair requires the original bytes to match `JSON.stringify(parsed, null, 2)`\nplus one LF exactly. Other formatting, a BOM, CRLF, or number spellings that\nwould change on parsing and serialization require author repair, so reserialization\ncannot change unrelated bytes or numeric precision. Missing files, invalid starts,\nand mixed failures also require author repair. This only bounds\nthe cited range; it does not establish or correct the cited fact. `autoRepair`\nrecords the changed ranges and original/repaired hashes in both receipts. A\npassing retry keeps the repaired candidate. Any later failure or exception\nattempts a byte-for-byte restore, guarded by the repaired candidate's identity\nand bytes, and invalidates only that retry's current-delivery sidecar. External\nedits are preserved and a returned receipt reports `restore-failed` if recovery\ncannot safely complete. Failure diagnostics and `specification` describe the\nchecked retry; `autoRepair.outcome` states whether the original was restored.\nThrown exceptions remain command failures and may leave the last persisted\nreceipt at an earlier stage; only a completed passing command is a handoff.\n\nFor a validation failure, edit the existing JSON in the connected neighborhood named by diagnostics before rerunning a command. Preserve requested semantics, meaningful labels, source evidence, and fixed or agreed topology. Several routes sharing nodes call for one placement repair; read [Architecture layout repair](architecture-layout-repair.md) for that case. Reflow a blocked main path rather than nudging unrelated labels. Keep unrelated geometry when its composition already reads clearly. Use `--layout-json` before editing only when compact evidence lacks needed measurements. Workflow v2 uses its stable compiler receipt, not solver internals, as authoring evidence.\n\nKeep the best candidate that cleared route checks before a viewport repair. If that repair introduces new route collisions, restore the measured layout and address its remaining canvas or text constraint.\n\nAfter the edit, rerun the complete `finalize` command with `--quality showcase` and, for repository-backed work, `--repo-root <repo-root>`. If the output path already has browser evidence from another candidate, use a fresh `--out-dir <output-stem>.review-<revision>` for both the new `finalize` and any `visual-check`. Omit an earlier `--candidate-sha256` after editing because it binds the previous candidate. Compare diagnostics by code, subject, stage, and evidence, never by declining error count alone. Track the repair limit per persistent issue, using that code, subject, stage, and evidence: a newly exposed issue starts its own repair sequence. If an issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, report the concrete gap.\n\nUse standalone `validate` only for focused diagnosis, passing `--repo-root` for repository-backed work. Its passing receipt marks `candidateFrozen: true`; run `nextAction.arguments`, replacing only `<output.html>`, without editing, revalidating, or rereading the candidate. Retry later environmental or evidence failures against those frozen bytes. A measured reason to edit creates a new candidate and calls for the complete `finalize` without the old hash.\n\n## Validate and deliver\n\n`render` and direct renderer entry points print classified authoring failures\nto stderr as readable diagnostics and exit 1. Input read/JSON parse failures\nuse `input/read` or `input/json-parse`; output filesystem failures use\n`output/write` and identify the output path. Schema and layout failures keep\ntheir existing rule codes. Use the advertised `validate --json` or\n`deliver --json` interface for a machine receipt; `render` has no `--json` flag.\nUnexpected implementation failures retain debugging information in human\nmode and remain `internal/unclassified` in machine receipts.\n\nDeclared local Explainer chart data and native-diagram specification files are protected inputs, including physical aliases. Delivery and finalize refuse sidecars that would overwrite those inputs, including when resource preparation fails; an uninspectable draft cannot publish failure evidence.\n\nEach delivered output has two artifact-specific metadata paths. When an output\nstem is too long for those derived filenames, Archify shortens it and appends a\nstable hash:\n\n- `<output-stem>.delivery.json` records the latest completed attempt.\n- `<output-stem>.delivery-pending.json` is the recovery journal for an attempt\n  in progress.\n\nFor a literal artifact stem that already matches Archify's reserved bounded-name\nmarker, a pre-namespace raw provenance sidecar remains a read fallback when the\nencoded sidecar is absent. A pre-namespace raw pending journal is an independent\nfail-closed barrier: it blocks checks and redelivery even when an encoded pending\njournal also exists, and neither journal is silently replaced.\n\nOne directory-wide `.archify-delivery-lock.json` serializes every delivery that\nresolves into the same physical output directory. This deliberately prevents\ncase, Unicode-normalization, Windows short-name, and symbolic-link aliases from\ncreating independent owners for one filesystem location. The tradeoff is that\ndeliveries to different artifact names in one directory also run serially;\nprovenance and pending journals remain artifact-specific.\n\nFor migration safety, Archify also detects and preserves a legacy\n`<output-stem>.delivery-lock.json` beside the requested artifact. An existing\nlegacy entry is a fail-closed recovery barrier. While a new delivery owns the\ndirectory mutex, it also holds temporary legacy-format fences for the requested\nspelling and an existing artifact's physical target spelling. It acquires the\ndirectory lock first, then all required compatibility fences before writing a\njournal or artifact, and removes the directory lock before those fences during\nrelease. This blocks an older Archify binary using\neither known spelling from entering the delivery. A legacy fence whose raw\nHEAD-era filename exceeds the host component limit is omitted because the old\nbinary could not create that lock or deliver that artifact on the host either.\n\n`deliver` acquires the lock by exclusive `open(..., \"wx\")` before creating or\nreplacing the recovery journal. A successful exclusive create yields an\ninternal opaque ownership capability bound to that attempt. Journal creation,\nfailed-provenance recording, pair commit, rollback, journal finalization, and\nlock release each verify the current capability inside the operation that\nwould mutate shared state. A rejected contender does not create a journal or\nwrite failed provenance.\n\nAn existing directory or legacy lock is handled without automatic recovery:\n\n| Observed lock state | Required `deliver` result |\n| --- | --- |\n| No directory entry | Attempt exclusive creation; only its success grants ownership. |\n| Valid schema-v1 lock whose PID is running, or whose death cannot be established | Exit 1 with `delivery/concurrent-attempt`; preserve every shared path. |\n| Valid schema-v1 lock whose PID is known to have exited | Exit 1 with `delivery/lock-stale`; preserve the lock, artifact, journal, and current provenance exactly. |\n| Unreadable, malformed, symlink, dangling symlink, directory, or other non-regular lock entry | Exit 1 with `delivery/lock-invalid`; preserve the entry and every other shared path. |\n| An acquired capability no longer matches the current lock or journal | Exit 1 with `delivery/ownership-lost`; stop all shared-path mutation. |\n| The matching owner cannot remove its lock | Exit 1 with `delivery/lock-release`; preserve the lock. |\n\nA `delivery/lock-stale` diagnostic identifies the absolute output and lock\npaths plus the original PID and receipt ID. Recovery is deliberately explicit\nand serial: stop all delivery attempts for that physical output directory,\nconfirm that no active delivery owns it and that the reported stale entry has\nnot been replaced, remove only the reported lock, then rerun `deliver`. Do not\nremove an artifact, current provenance, or pending journal as part of\nstale-lock recovery.\n\nThe lock protocol targets Node.js 18 or later on a local filesystem with\ncooperating Archify processes. PID, receipt, and file-identity comparisons are\ndefensive checks, not an atomic compare-and-swap. Compatibility fences cover\nthe requested spelling and an existing physical-target spelling; they cannot\nenumerate arbitrary hard-link names or previously unknown filesystem aliases,\nso mixed-version delivery through such aliases remains out of scope. This\ncontract does not claim distributed-lock correctness on NFS, SMB, or other\nnetwork filesystems, and it cannot prevent an external process that ignores\nthe protocol from replacing shared paths.\n\nEvery no-clobber HTML publisher (`render`, `deliver`, `compare`, and `preview`)\ncaptures the requested directory entry, canonical write slot, physical parent,\nand existing target type, device/inode identity, and mode before staging, then\nrevalidates that snapshot immediately before replacement. An existing write\ntarget must be a regular file with exactly one hard-link name. A target with\nmultiple hard-link names fails closed with `output/target-hardlinked`: replacing\nthe requested name cannot update unknown sibling names as one publication.\nHard links remain supported for read identity and input/alias collision checks;\nthey are unsupported only as write targets. A symbolic link to a single-link regular\nfile remains supported: publication preserves the symbolic-link entry and\napplies the same protocol to its resolved target. Directory, FIFO, socket,\ndevice, changing mode, new claimant, and indeterminate identity cases fail\nbefore replacement.\n\nPublication is no-clobber and recoverable, not crash-atomic replacement of an\nexisting target. To avoid overwriting a claimant that appears after the last\nidentity check, Archify first retains the bound old file in a private recovery\nbackup, removes the public name through identity-bound quarantine, and then\ncreates the new public name with an exclusive hard link. A caught failure rolls\nback when the public slot and recovery binding still permit it. A process\ninterruption between those namespace operations can instead leave the public\npath absent while the verified previous bytes remain in an adjacent private\nrecovery backup. Single-artifact publication records the original slot/alias\nidentity and backup inode, mode, SHA-256, and byte count in private\n`.archify-remove-*/publication-recovery-v1.json`, beside `previous`. To make a\nspecific interrupted publication visible again, stop concurrent writers and run:\n\n```bash\nnode bin/recover-output.mjs /absolute/path/to/.archify-remove-<id> --json\n```\n\nThis is explicit recovery, not a directory scanner. Before linking, the helper\nchecks for a changed parent or alias, an altered/hardlinked record or backup,\ndigest or inode mismatch, and any existing public target. It restores only by\nno-clobber hard link, so a new claimant is preserved rather than overwritten;\nit never recursively removes unknown entries. A completed recovery is\nidempotent. The record is evidence to be independently verified, not an\nauthority to restore arbitrary private bytes: the helper accepts it only from\nthe recorded generated child of the original physical target parent, with the\nsame directory identity. Name the exact directory reported by the interrupted\nprocess and inspect an uncertain record manually. A non-cooperating process can\nstill swap pathnames after those checks and before Node.js `linkSync`; Node does\nnot expose a descriptor-bound link operation. Post-link identity verification\nthen fails closed and retains recovery evidence, rather than claiming recovery\nor deleting an uncertain name. If recovery itself is interrupted after the\nlink, the old public bytes and private backup can both remain; a later recovery\nrun preserves the public target and needs explicit operator resolution. The\nrecord is fsynced before the old public name is retired on platforms supporting\ndirectory sync, and the tested guarantee is recovery after a killed process;\nthis is not a claim of power-loss, storage-controller, NFS, or SMB durability.\nPaired flows retain their backup in private transaction staging. For `deliver`,\nthe pending journal and lock keep strict checkers fail-closed. The portable\nNode.js filesystem API has no pathname\ncompare-and-swap that both replaces an existing name atomically and refuses to\noverwrite a late claimant: `rename` would close the visibility gap only by\noverwriting that claimant.\n\nAfter ownership is established, `deliver` creates the journal before rendering\nand keeps it through the recoverable HTML/sidecar pair commit. It removes the\njournal only after that commit completes. A validation, render, or pair-commit\nfailure, or a process interruption, may therefore leave a journal. The journal\nis a safety barrier: `check`, `browser-check`, and `visual-check` fail closed when any directory\nentry exists at the journal or lock path, including an unreadable file,\nsymlink, or dangling symlink. Run deliveries targeting the same physical output\ndirectory serially; one attempt must finish or be recovered before another\nbegins.\n\nA successful sidecar has `schemaVersion: 1`, `status: \"current\"`,\n`command: \"deliver\"`, a unique `receiptId`, the diagram `type`, an absolute\n`input` path, an absolute `output` path matching the inspected\nartifact, and specification/artifact SHA-256 and byte counts. Checkers treat a\nmissing, malformed, unsupported, or inconsistent field as invalid. They also\nreject a sidecar symlink, including a dangling one. A checker binds provenance\nto the artifact bytes it actually checks and verifies that binding again before\nreporting success; a concurrent byte change fails. The provenance directory\nentry itself must be a single-link regular file: `deliver` and strict check fail\nclosed with `delivery/provenance-hardlink-unsupported` when it has another hard\nlink, without scanning for or guessing the sibling name.\n\nIf a currently verified owner fails after an older HTML exists, Archify writes\na new `status: \"failed\"` sidecar and leaves the journal until recovery is\ncomplete. An unreadable old HTML does not prevent that marker; its artifact hash\nand byte count may be absent. If the sidecar is locked or otherwise unwritable,\nArchify keeps the prior sidecar rather than deleting evidence, and the journal\nprevents checkers from trusting it. A rejected concurrent, stale, or invalid\nlock attempt does not write failed provenance. If ownership is lost, Archify\nreports `delivery/ownership-lost`, does not overwrite or remove the successor's\nartifact, provenance, journal, or lock, and does not claim recorded failed\nprovenance; a failure receipt may report `provenance: \"unrecorded\"`. If every\nmetadata path is unavailable, the same unrecorded status applies; no tool can\npreserve that fact across processes. Restore metadata-path access and complete\na successful `deliver` before trusting the output.\n\nArtifacts with no sidecar, journal, or lock remain supported for backward\ncompatibility and for the lower-level `render` command. Their checker receipts\nreport `provenance: \"unknown\"`; use `--require-provenance` to turn that state\ninto a non-zero failure when the workflow requires a successfully delivered\nartifact:\n\n```bash\nnode bin/archify.mjs check <output.html> --require-provenance\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\n## Output path contracts\n\nArchify intentionally separates durable authored paths from command-line paths:\n\n- Required authored `meta.output` is a portable POSIX-relative path such as\n  `reports/diagram.html`. It uses `/`, ends in a non-empty `.html` basename,\n  and cannot contain an absolute or drive-relative prefix, URI, backslash,\n  empty or dot segment, control character, unpaired UTF-16 surrogate, Windows\n  alternate-data-stream separator or invalid filename character, trailing dot\n  or space, DOS device name, or a component over either the 255-byte UTF-8 or\n  255-code-unit UTF-16 limit. It resolves from the current working directory\n  and must remain physically inside that directory, with an `.html` target,\n  after symbolic links are followed. The durable output/archive profile also\n  conservatively rejects a Windows 8.3 short-name shape such as `PROGRA~1`;\n  descriptive repo/Git POSIX paths use a separate profile and are exempt.\n- Explicit CLI output arguments use the active host's native syntax. They may\n  be relative or absolute, use native separators, and resolve outside the\n  current working directory. On Windows, ordinary drive-absolute, UNC, and\n  relative paths (including ordinary `.` and `..` navigation) are supported.\n  A system-resolved 8.3 spelling of an existing file or directory is accepted\n  when Archify can prove its physical identity; this native alias support does\n  not relax the durable output/archive profile's 8.3-shaped-name rejection.\n  Extended-length paths are limited to raw backslash-only `\\\\?\\C:\\...` and\n  `\\\\?\\UNC\\server\\share\\...` forms without dot segments; device namespaces,\n  malformed roots, drive-relative paths such as `C:file.html`, current-drive\n  roots such as `\\file.html`, alternate data streams, reserved device names,\n  invalid or trailing filename characters, and overlong components fail\n  closed. POSIX CLI paths retain POSIX filename rules rather than inheriting\n  Windows spelling restrictions. Every host rejects NUL, unpaired surrogates,\n  and components that exceed its supported bound.\n\nThese contracts are not interchangeable: an explicit CLI output does not hide\nan invalid durable `meta.output` (including a missing value), and `validate`\nchecks the authored output even when it does not publish to that path. A\nworkflow v1-to-v2 migration may explicitly receive a portable durable\nreplacement through `migrate workflow old.json new.json --to-schema 2 --output\nreports/diagram.html`; that value is written only to its separate verified v2\ndestination. This migration-candidate exception does not repair the source or\nbypass any non-output schema or compiler error. For every other repair, add a\nportable POSIX-relative `.html` path to `meta.output`; no schema-version change\nis otherwise required.\n\nRun `finalize` directly on a complete first candidate and after every repair edit. Its embedded validation checks the candidate before delivery; use standalone `validate` only for focused diagnosis. After an edit, omit any earlier `--candidate-sha256`, which binds the previous candidate. CLI HTML output paths must end in\n`.html`, including after symbolic-link resolution. Compare receipt paths must\nend in `.json`. A type mismatch fails before writing with\n`output/cli-extension` or `output/cli-resolved-extension`. These checks prevent\naccidental file-type overwrites; they do not sandbox explicit CLI directories\nor prevent replacement of an existing artifact of the expected type.\n\nUse final verified delivery only after the candidate is frozen:\n\n```bash\nnode bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality showcase --json\n```\n\nDeliver reads the specification once, writes those exact bytes to a private same-directory candidate snapshot, renders that snapshot, runs the complete artifact checker, and only replaces the target after all artifact checks pass. The JSON receipt includes SHA-256 and byte counts for both `specification` and `artifact`. Deliver adds a required [update notice](update-awareness.md) before running the checker. The hash binds the delivered bytes, and the receipt records `updateNotice`. The dismissible notice uses the top bar on wide Viewer diagrams when the title and toolbar leave space, and the footer otherwise. It includes a one-click copy button for a localized Agent update prompt and the official release notes link. Opening the page and copying the prompt work offline and make zero network requests.\n\nFor the ordinary agent handoff path, prefer the finalizer:\n\n```bash\nnode bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n```\n\n`finalize` invokes verified `deliver` once, reuses its embedded showcase\nvalidation result, then runs strict `check --require-provenance` and\n`browser-check --require-provenance`. It stops at the first failed or skipped stage\nand preserves that stage's full receipt. Its stdout is one compact JSON\nobject with gate statuses, bounded actionable diagnostics, artifact identity,\nand evidence paths. The same compact object is written atomically to\n`<output-stem>.finalize-summary.json`; use that file for normal failure repair. When diagnostics are truncated, `diagnosticSummary.omittedByCode` counts the unshown entries by diagnostic code without replacing their full subject and repair evidence in the full receipt.\nComplete stage receipts and timings remain available for auditing in\n`<output-stem>.finalize.json`. With `--out-dir`, both files are written there (unless an explicit `--receipt` overrides the finalize receipt path; the artifact HTML stays at the requested output path);\n`--receipt <path.json>` overrides the full receipt path and derives a distinct\n`<path>-summary.json`. Read the full receipt only when the compact summary is\ntruncated and its shown subjects and evidence cannot identify a coherent local\nrepair, or when complete audit evidence was explicitly requested. The compact\nreceipt reports `visualReview: \"not-requested\"`; the automated gate does not create images or require a perceptual reviewer. A compact `visualReviewRecommendation` retains positive crossover and route-detour metrics from the strict check so the author can apply the review escalation below without reading the full receipt. A recommendation does not change the machine exit code or claim that review happened. Its `affectedRoutes` identifies crossing pairs and detours (up to eight of each, with a truncation flag); the full strict-check `composition.routeReview` retains all affected relationships. Use these IDs to trace the routes in the captured default viewport. Detours may include `directCorridorBlockers`, identifying nodes between aligned endpoints. These are geometric review clues, not new validation failures or inferred main-path semantics. For a blocked main path or several tangled routes, follow [Architecture layout repair](architecture-layout-repair.md) and reflow the connected scene before tuning individual sides or labels. Preserve every semantic fact; retain unrelated positions only when their surrounding composition is already accepted.\n\nFor a measured automatic Architecture with a large unused leading area, the\ncompact receipt may include `layoutReviewRecommendation`. Its\n`composition.leadingSpace` evidence accounts for nodes, boundary titles,\nroutes and labels. Check whether that space is intentional; if not, reposition\nthe connected scene while preserving meaning and user-fixed geometry, then\nfinalize again. This suggestion changes no gate or exit status and requires\nno screenshot. A fixed canvas or uncertain measurement receives no suggestion.\n\nA passing finalizer receipt is sufficient evidence for all four gates. Merely\nnaming the gates or requiring each one to pass does not require replaying their\nstandalone commands. Replay an individual command only when the request\nexplicitly requires separate executions or focused failure diagnosis needs it.\n\nThe individual commands remain authoritative and backward compatible. Use\nthem directly for focused diagnosis, recovery, or when only one gate is\nrequired. A finalize failure does not relax any gate and does not turn a\npreserved older artifact into a current successful delivery.\n\n`finalize` discovers and starts private Chrome only after delivery and strict\nchecking pass. Failed input, repository-evidence, delivery, or artifact checks\ntherefore do not launch a browser. It loads the artifact only after current\nprovenance is verified. The browser gate retains every viewport, theme, and\nstability check; the browser closes at completion or a browser-stage failure.\nIts full stage receipt records `execution: \"in-process\"` and the equivalent\nstandalone `command` for replay. Chrome startup no longer overlaps the earlier\nstages, so successful runs may take slightly longer. This avoids unnecessary\nstartup on invalid candidates; it does not fix host sandbox restrictions on\nChrome startup or relax a browser gate.\n\nThe pair commit is recoverable, not a claim that two filesystem paths change\natomically or are durable across power loss. Journal finalization is part of\nthat commit: a caught failure while verifying or removing the journal rolls\nback the replaced files when possible and while ownership remains current. If\nownership is lost, the old attempt immediately stops renaming, rolling back,\nfinalizing the journal, recording failure provenance, or cleaning up shared\npaths. Any private staging or recoverable backups remain available and are\nidentified by the failure diagnostic. If restoration fails for another reason,\nthe failure receipt likewise identifies retained backups for recovery. A\nprocess interruption can leave the journal, backups, or private staging behind;\ncheckers then fail closed. Follow the reported recovery evidence before rerunning\n`deliver` serially on the same output. A failed attempt exits non-zero and never invokes an opener; it never\nauthorizes visual evidence collection.\n\nIf exclusive creation succeeds but lock initialization fails, Archify may\nrecord failed provenance and remove the incomplete lock only while its\ncapability still identifies that exact entry. A replacement is preserved.\nFilesystem and cleanup errors are reported separately from an active concurrent\ndelivery. An active, stale, unrecognized, or otherwise preserved lock\nindependently prevents checkers from accepting the prior artifact. Fix the\nreported filesystem error before retrying, and use another physical output\ndirectory if the lock path contains unrelated data.\n\nLock release is part of delivery completion. If the artifact/provenance pair\nhas committed and the journal has finalized but the matching lock cannot be\nremoved, `deliver` exits 1 with `delivery/lock-release`, preserves the lock,\ndoes not print a success receipt, and does not invoke an opener. The preserved\nlock keeps strict checkers fail-closed. Only after pair commit, journal\nfinalization, and lock release all succeed may `deliver` exit zero, print its\nsuccess receipt, or run `--open`.\n\nRun strict `check` after `deliver` exits zero. Run `browser-check` or optional\n`visual-check` only after that strict check exits zero. A failed marker,\nrecovery journal, or delivery lock makes every checker fail before accepting\nthe preserved HTML; report the diagnostics and complete a successful recovery\ndelivery before collecting new browser evidence.\n\nStatic `check` uses the same SVG path analysis for inspected relationships and\nstructural frames. It supports `M/L/H/V/Q/Z`, their lowercase relative forms,\nrepeated parameters, and finite numbers. Each `M` starts an independent subpath;\n`Z` closes only the current subpath. Separate subpaths never create connecting\nsegments that are absent from the drawing. Straight segments separated by a\nnon-collinear `Q` also remain separate in route analysis; curve sample points\ndo not become micro-segments in straight-route budgets or rhythm checks.\nSegment lengths and stretch are measured per continuous piece, while actual\nbends are summed per relationship. A relationship exceeding a budget is counted\nonce, and internal piece boundaries do not receive the short shared-trunk\nexception reserved for semantic endpoints.\n\nThis is not a promise of full SVG command support: `A/C/S/T` produce\n`artifact/svg-path-unsupported`; missing parameters, invalid numbers, and other\nsyntax errors produce `artifact/svg-path-malformed`. The checker exits non-zero\ninstead of skipping a bad path or waiting indefinitely. Path failures append a\n`svg_path_data` check; normal valid artifacts retain the existing nine checks.\nDiagnostics carry the inspected `pathIndex`, `role`, available relationship/frame\n`id`, parsing `tokenOffset`, available `command`, and `reason` so the generating\nsource can be located and repaired. `pathIndex` is one-based; `tokenOffset` is a\nzero-based UTF-16 offset in `d` after numeric character references are decoded.\nApparent tags in comments, CDATA, and attribute text are ignored. Passing static\npath checks does not establish browser or perceptual visual acceptance.\n\n<details>\n<summary>中文说明</summary>\n\n静态 `check` 对受检关系线和结构边界的 SVG 路径使用同一解析结果，支持\n`M/L/H/V/Q/Z` 及其小写相对形式、重复参数和有限数值。每个 `M` 开始独立\n子路径，`Z` 只闭合当前子路径；子路径之间不会被拼接成图中不存在的线段。\n非共线 `Q` 前后的直线也保持分离，不会把曲线采样点计为直线路由预算或\n节奏检查中的微线段。线段长度和伸长率按连续片段测量，真实转弯数汇总到原关系；超预算关系\n只计一次，内部子路径断点不享有语义起终点的短共享线例外。\n这不是完整 SVG 命令集的支持承诺：`A/C/S/T` 返回\n`artifact/svg-path-unsupported`；缺少参数、非法数值等格式错误返回\n`artifact/svg-path-malformed`，检查以非零状态结束，不跳过坏路径或无限等待。\n路径失败时追加 `svg_path_data` 检查；普通有效产物仍保留原来的 9 项检查。\n诊断携带受检路径的 `pathIndex`、`role`、可用的关系/边界 `id`，以及解析位置\n`tokenOffset`、可用的 `command` 和 `reason`，用于定位并修复生成路径的来源。\n`pathIndex` 从 1 开始；`tokenOffset` 是数字字符引用解码后的 `d` 字符串中\n从 0 开始的 UTF-16 位置。注释、CDATA 和属性文本中的伪标签不参与检查。\n静态路径检查通过仍不代表浏览器或感知视觉验收通过。\n\n</details>\n\nThe delivery interface exposes four separate claims:\n\n1. `deliver` proves deterministic artifact checks and byte identity.\n2. `browser-check` collects required automated browser evidence from the exact artifact without capturing images.\n3. `visual-check` optionally adds artifact-bound screenshots and a contact sheet.\n4. Perceptual visual review records a human or image-capable reviewer's judgment.\n\nPassing one claim never implies the others. Never claim that the deterministic receipt includes browser or perceptual review evidence.\n\n## Architecture Diagnosis offer\n\nAfter a passing `finalize architecture` with `--repo-root`, the full receipt\nand compact summary include `codeAnalysisOffer` if a bounded scan finds\nsources eligible for the default analysis. The offer includes the effective\nfinalize `quality`, passes it in `start.argv`, and records a `dependencies`\nstatus of `installed` or `missing`. Finalize performs these checks without\nstarting analysis or installing anything.\n\nEnd the delivery summary with the capability section below, in the user's\nlanguage, once per repository in the task. It is part of the summary, not a\nseparate question, so users learn what Diagnosis does even if they never\nreply. Skip it if the user already asked for or declined analysis in this\ntask. Keep the bullets; adapt only wording, not the claims. If `dependencies`\nis `missing`, the installed Skill copy is incomplete: replace the closing line\nwith the reinstall line, because analysis cannot start. If the offer includes\n`linkedDiagrams: true`, add that sibling-diagram links work from the original\ndelivered diagram, not from the Diagnosis server. Mention the diagram button\nonly when `codeAnalysisOffer.diagramButton` is `true`; otherwise drop that\nsentence. Start only after the user agrees.\n\n**中文**\n\n**还可以：架构诊断**（Archify 自带，在本机运行）\n- **环形星图**：几千个文件、几万个函数之间的依赖一眼看全\n- **可旋转的 3D 模型**：换个角度看模块怎么连在一起\n- **组件问题数**：直接标在这张架构图上，哪里最拥挤、哪里有循环依赖、哪些依赖图里没画\n- 每条发现都能点开看源码，也能一键交给 AI 修\n\n回复「好」我就启动。图右上角的「架构诊断」按钮也随时能看到这个功能。\n（依赖缺失时，最后一句改为：分析组件缺失，需要先重新安装 Archify 才能使用。）\n\n**English**\n\n**Also available: Architecture Diagnosis** (built into Archify, runs locally)\n- **Radial star map**: dependencies across thousands of files and functions at a glance\n- **Rotatable 3D model**: see how modules connect from any angle\n- **Issue counts per component**, right on this diagram: where things are most crowded, where dependencies cycle, and which dependencies the diagram doesn't show\n- Every finding opens its source and can be handed to an AI as a fix task\n\nReply \"yes\" and I'll start it. The **Code Analysis** button at the top right of the diagram shows this anytime.\n(If dependencies are missing, the closing line becomes: The analysis components are missing; reinstall Archify to use it.)\n\nAfter consent, run `start.argv`. Add `--locale zh-CN` for Chinese or\n`--locale en` for English if needed. For a repository with several supported\nlanguages, select the adapter with `--language` as described in the\n[Code Analysis guide](../modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation).\nShare the printed local URL. The original architecture diagram appears first.\nClick **Code Analysis** (**架构诊断** in Chinese) to run analysis and open the\ncomponent findings, radial star map, and Atlas 3D views.\n\n## Comparison presentation changes\n\nArchitecture comparisons include authored `meta.translations` in presentation changes. Adding, removing or editing translations changes `summary.presentationChanged`; reordering translation keys does not. An empty translation object is equivalent to an omitted catalog for presentation classification; the canonical source digest still records the authored representation. Component, relationship, boundary and repository-provenance classifications remain independent.\n\n## Recovering a failed comparison\n\n`compare` commits an HTML artifact and its JSON receipt as a pair. If that commit\nfails, it attempts to restore the previous files. A complete rollback removes\nthe temporary directory as usual.\n\nIf a previous file cannot be restored, compare exits non-zero with\n`delta/commit-rollback-failed` and retains the recovery directory. In the JSON\nfailure receipt, `diagnostics[].evidence.recoveryDirectory` identifies that\ndirectory and `recoveryFiles` lists `{ backup, target }` paths for the files whose\nrestoration failed. Human-readable diagnostics also print the recovery paths.\n\nResolve the filesystem error, inspect the current targets, and restore each\nlisted backup to its corresponding target before retrying. Keep the recovery\ndirectory until both previous files have been recovered and verified; it can\nalso contain rejected candidate files, which must not be mistaken for backups.\nSuccessful comparisons and failures before commit retain their normal cleanup.\n\n## Automated browser evidence\n\n`finalize` runs the required browser gate against the exact trusted HTML without\nrerendering or modifying it. For focused diagnosis, the equivalent standalone\ncommand is:\n\n```bash\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\nThe zero-dependency command uses Chrome/Chromium (or Microsoft Edge)\nthrough the DevTools pipe. `ARCHIFY_CHROME` is authoritative when set, including\nan invalid path: Archify does not silently fall back to another browser. Automatic\nWindows discovery checks every Chrome/Chromium install location and PATH command\nfirst, then Edge under `%ProgramFiles(x86)%`, `%ProgramFiles%`, and `%LocalAppData%`,\nfollowed by `msedge` on PATH. On macOS and Linux, discovery also checks\nChrome/Chromium first, then the Edge application bundle (macOS) and\n`microsoft-edge`/`microsoft-edge-stable` on PATH. It\nmeasures light-theme containment at 1440×900, 1600×1000, 1920×1080, and\n2048×1320, and verifies the requested light theme at all four viewports, the dark\ntheme at both endpoints, and READ/Still runtime states. A requested theme that\nresolves to a different theme fails with measured evidence. It creates one\n`<output-stem>.browser-check.json` receipt and no screenshots or contact sheet.\nPass `--out-dir <dir>` to place the receipt in a separate evidence directory.\nThe receipt binds the artifact SHA-256 and byte count, identifies\n`evidenceKind: \"automated-browser\"`, and reports\n`visualReview: \"not-requested\"`.\n\nHorizontal overflow always fails. Normal document-level vertical scrolling is\naccepted only with a renderer-declared contract and measured readable text.\nAutomatic canvases declare `data-reader-fit=\"intrinsic-height\"` (height fitting)\nor `data-reader-fit=\"width-first\"` (Sequence and Waterfall reading width); their adaptive\nReader must reach its readable width and expose `data-reader-overflow=\"authored\"`.\nArchitecture with an explicit `meta.viewBox` instead declares\n`data-diagram-type=\"architecture\"` and `data-reader-fit=\"authored-height\"`:\nits SVG coordinates, aspect ratio and existing Reader width behavior stay\nunchanged. Its full SVG must remain inside the diagram panel without internal\nscrolling or clipping, and the document must permit vertical scrolling.\nThe receipt records `verticalScrollAccepted: true` and\n`overflowDisposition: \"readable-vertical-scroll\"`. Missing or unknown declarations,\nexplicit viewBoxes in other modes, unreadable text, horizontal overflow,\nclipping and Viewer chrome collisions remain failures. Do not add an internal\ndiagram scroller or hide overflow.\n\n`browser_evidence` in the handoff records only the outcome of this automated\ncommand:\n\n- `passed` maps from exit 0 and receipt `status: \"pass\"` after every required measurement completes and passes.\n- `failed` maps from exit 1 and receipt `status: \"fail\"` when the inspection finds a defect, the command fails, or a runtime error leaves the evidence incomplete.\n- `skipped` maps only from exit 2 and receipt `status: \"skipped\"` when no supported browser is available and the inspection does not run.\n\nRuntime failures leave incomplete evidence and must not be normalized to\n`skipped`. They do not invalidate an already successful deterministic delivery.\nRetry an environmental failure in a browser-capable execution context when\npractical. Keep the packaged transport unchanged unless the failure reproduces\nthrough that seam in a capable environment.\n\nOn Windows, Chrome/Edge startup relaunches can lose the inherited DevTools\npipe before any response arrives. Archify removes a standalone\n`__COMPAT_LAYER=DetectorsAppHealth` from the browser child's environment only\n(case-insensitive name and value); the parent environment, unknown layers,\ncombined layers, and privilege-related compatibility settings are unchanged.\nThis targets the reported non-elevated Git Bash app-health case, not every\nAppCompat mode. Elevated-shell relaunches remain unsupported: rerun from a\nnon-elevated PowerShell opened normally, outside an elevated or compatibility-mode\nparent. Archify does not suppress browser de-elevation or disable the sandbox\nas a relaunch workaround. A zero-response startup diagnostic suggests this\nremedy without claiming that elevation or AppCompat caused every pipe failure.\n\nA provenance failure exits before browser inspection and persists a failed\nbrowser-check receipt bound to the attempted artifact. If the failure receipt\ncannot be written, the diagnostic names that incomplete evidence.\n\nBoth browser commands inspect the exact delivered HTML without modifying or rerendering it.\n\n## Sequence width review\n\nA passing `finalize` may report `layoutReviewRecommendation.action: \"inspect-sequence-width\"`. Its `evidence` measures the fixed participant columns' unused right-hand space after accounting for message labels, notes and segment titles. This advice adds no warning, failure, screenshot requirement or automatic geometry change.\n\nA passing `validate --json`, `deliver`, or `finalize` receipt may carry `diagnostics[]` entries with `severity: \"warning\"` for Viewer locale fallbacks (`i18n/*`). They fail no gate. When the artifact should be fully localized, repair the listed keys from their `evidence` and rerun `finalize`.\n\nSequence canvases with omitted `meta.column_fit` use `spread`, whether or not `meta.viewBox` is supplied. An authored viewBox remains authoritative; infeasible participant capacity fails without silently enlarging it. Explicit `meta.column_fit: \"fixed\"` preserves historical fixed columns. For a candidate whose fixed-column width suggestion remains, first check whether the fixed geometry is intentional. Only when a change to that geometry is authorized, save the candidate, set only `meta.column_fit` to `\"spread\"`, and rerun the complete `finalize` once with `--out-dir <folder>/width-review`. Keep participant order, messages and their y positions, labels, notes, sources and canvas dimensions. If that attempt fails, restore the candidate and finalize it with `--out-dir <folder>/width-restore`; report the remaining layout suggestion rather than iterating. Preserve intentional fixed geometry and disclose the suggestion when a change is not authorized. To retain historical fixed coordinates for an older omitted-fit input, set `meta.column_fit: \"fixed\"` explicitly. This review is about horizontal composition; a passing receipt still does not claim perceptual approval.\n\n## Optional capture evidence\n\n`visual-check` remains backward compatible for a requested or escalated\nperceptual review:\n\n```bash\nnode bin/archify.mjs visual-check <output.html> --summary --require-provenance\n```\n\n`--summary` returns compact JSON with all diagnostics and absolute paths to the complete receipt, contact sheet, and every screenshot. For a chosen visual review, inspect the relevant captures; capture success is not perceptual approval. `--json` retains the full receipt output for existing consumers. Both modes run the same checks and keep the same exit status. If cleanup fails after publication, the summary retains the final failure diagnostics and `publication` recovery details; the linked receipt records the earlier committed evidence.\n\nIt performs the same automated browser measurements, captures light/dark\nscreenshots at 1440×900 and 2048×1320, and writes four viewport PNG sidecars,\none relative-path HTML contact sheet, and one JSON receipt. `--out-dir <dir>` moves all of these sidecars together.\nOpen the HTML contact sheet in a browser or inspect the viewport PNGs with an image reader. Its receipt reports `visualReview: \"pending\"` because captures do not themselves\nmake a perceptual judgment. Capture and provenance failures follow the ownership rules below.\n\nThe receipt, contact sheet, and four PNGs form one owned evidence set. Before\ncapture, `visual-check` freezes every requested directory entry, its\ncanonical write slot and physical parent, and the target's absent/file state,\ntype, device/inode identity, and mode. Hard-linked evidence targets are not safe\nwrite targets. All candidate files are created exclusively inside one random,\nprivate staging directory beneath the physical evidence directory; the receipt\nis published last. Each staged candidate must have exactly one hard-link name\nbefore publication. The no-clobber publish link temporarily gives the staged\nand final names a link count of two; unlinking the verified staged name must\nleave the final entry with a link count of one. An unexpected external hard\nlink fails closed and its alias is never removed.\n\nChrome inspects one identity- and content-checked copy of the captured artifact\nin a private local temporary directory, so browser file loading does not depend\non UNC or long-path support. The six publication candidates remain on the\nevidence volume. Both temporary directories are cleaned without recursively\ndeleting unknown contents; retained entries include their recovery locations.\n\nImmediately before committing anything, `visual-check` re-resolves and verifies\nthe complete six-path set. An absent-path claimant, existing-path replacement,\nsymbolic-link or dangling-link retarget, parent-topology change, hard link, or\nindeterminate identity fails closed with `viewer/evidence-path-conflict`. The\nclaimant and every other final evidence path remain untouched. Cleanup removes\nonly this run's staged or published entries after rechecking their captured\nidentities; a changed or unknown entry is preserved.\n\nAn existing visual evidence set is replaceable only when a regular\n`visual-check` receipt proves ownership of the same artifact and evidence\ndirectory, and its exact sidecar manifest matches every existing contact-sheet\nor PNG byte count and SHA-256 digest. A missing, malformed, unknown, mismatched,\nor incomplete ownership record never authorizes deletion. Failed and skipped\nruns retire prior screenshots/contact sheets only as part of the same verified\ntransaction when that ownership proof succeeds; otherwise they preserve all\nunknown evidence and report `viewer/evidence-path-conflict`.\n\nThis rule also applies when Chrome is unavailable or provenance fails before\nbrowser inspection: neither path may blindly delete stale-looking evidence. A\nverified owned set may be recoverably retired before publishing a skipped or\nfailed receipt; unowned evidence remains intact. These outcomes do not invalidate an already\nsuccessful deterministic delivery and do not turn a perceptual visual review\ninto passed or failed. Retry an environmental failure through the supported\ncommand in a browser-capable execution context when practical. Keep the\npackaged transport unchanged unless the failure reproduces through that seam in\na capable environment.\n\n`browser-check` applies the same private-snapshot, identity, ownership, and no-clobber rules to its single JSON receipt. Its namespace is separate from `visual-check`, so a browser-only rerun cannot remove capture evidence.\n\n## A new candidate at an existing output path\n\nBrowser evidence belongs to exact artifact bytes. After editing a candidate whose previous HTML already has browser evidence, choose a fresh evidence directory before running the next `finalize`; this preserves the old receipts and captures without an avoidable ownership-conflict retry. `--out-dir` relocates the new browser-check receipt and, by default, the finalize receipt and summary. An explicit `--receipt` overrides the finalize receipt path; its summary follows that path. Successful delivery still rewrites the requested HTML and its sibling `*.delivery.json`. Earlier browser or visual evidence remains bound to its original artifact bytes and must not be treated as evidence for changed HTML:\n\n```bash\nnode bin/archify.mjs finalize architecture candidate.json diagram.html --quality showcase --repo-root <root> --out-dir diagram.review-2 --json\nnode bin/archify.mjs visual-check diagram.html --out-dir diagram.review-2 --summary --require-provenance\n```\n\nThe evidence directory is not an archive of the HTML. Copying the HTML there alone does not rebind receipt paths or provenance. If a historical snapshot is needed, preserve the candidate and artifact separately before overwriting them; do not assume copied receipts validate a relocated artifact.\n\nKeep the requested HTML path stable. Use a new revision directory for each changed candidate, and retain the same directory for retries of unchanged bytes. For a diagram without repository evidence, omit `--repo-root`. Let the commands create their output directory. A prior validation failure that produced no HTML or browser evidence needs no new directory. Never remove unknown evidence to make a retry pass.\n\n## Optional opening\n\nAdd `--open` only when the user wants an immediate local preview. It runs after\nthe verified pair commit has completed, its recovery journal has been removed,\nand the delivery lock has been released successfully. It uses one argument-array\nOS opener with a five-second bound on macOS and Linux, and a fifteen-second bound\nfor PowerShell startup on Windows. The receipt records `open.status`; failed or\nunavailable launch attempts also include normalized `open.failure` details.\nKeep it off for CI, unattended agents, and non-interactive environments.\nFailure or unsupported opening does not invalidate delivery; its\nstatus proves only whether the local opener invocation succeeded.\n\n## Last-Good Live Preview\n\nFor an active desktop authoring loop only:\n\n```bash\nnode bin/archify.mjs preview <type> <input>.json <output>.html --quality showcase\n```\n\nPreview watches one explicit input on loopback, binds each stable digest to a private snapshot, and advances only after the existing verified delivery pipeline passes. Invalid, half-written, deleted, or superseded input leaves the previous verified revision on screen and on disk. Identical bytes do not rebuild or reload.\n\nThe preview runtime ships inside the zero-dependency Skill ZIP and must work without `node_modules`.\n\nNever start it by default. Do not use it for CI, unattended agents, remote sharing, or mobile use. `--no-open` is only for a user who will open the printed local URL or for loop testing. Stop it with Ctrl-C before handoff. The first Ctrl-C drains the active delivery without publishing it; a second Ctrl-C forces shutdown of both delivery processes and HTTP connections, including incomplete requests. Shutdown preserves the last verified artifact and removes only staging files whose ownership can be verified. If delivery is interrupted before its receipt reaches Preview, unconfirmed files and recovery material may remain in the private staging directory; shutdown does not recursively delete unknown contents. Server state, port, source path, diagnostics, error text, and reload tokens must never enter the generated artifact or any export.\n\n## Per"},"files":{"DESIGN.md":"---\nname: Archify\ndescription: A precise, vivid technical instrument for trustworthy interactive architecture maps.\ncolors:\n  canvas: \"#020617\"\n  mask: \"#0F172A\"\n  ink: \"#FFFFFF\"\n  muted: \"#94A3B8\"\n  dim: \"#475569\"\n  border: \"#1E293B\"\n  frontend: \"#22D3EE\"\n  backend: \"#34D399\"\n  database: \"#A78BFA\"\n  cloud: \"#FBBF24\"\n  security: \"#FB7185\"\n  messagebus: \"#FB923C\"\n  external: \"#94A3B8\"\ntypography:\n  headline:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"1.5rem\"\n    fontWeight: 700\n    lineHeight: 1.2\n    letterSpacing: \"-0.025em\"\n  title:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.875rem\"\n    fontWeight: 600\n    lineHeight: 1.4\n    letterSpacing: \"normal\"\n  body:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.75rem\"\n    fontWeight: 400\n    lineHeight: 1.55\n    letterSpacing: \"normal\"\n  label:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.625rem\"\n    fontWeight: 700\n    lineHeight: 1.35\n    letterSpacing: \"0.12em\"\nrounded:\n  precise: \"0.2rem\"\n  control: \"0.5rem\"\n  panel: \"1rem\"\n  pill: \"999px\"\nspacing:\n  xs: \"0.25rem\"\n  sm: \"0.5rem\"\n  md: \"0.75rem\"\n  lg: \"1rem\"\n  xl: \"1.5rem\"\n  page: \"2rem\"\ncomponents:\n  toolbar-button:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.5rem 0.875rem\"\n    height: \"2.75rem\"\n  diagram-panel:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    rounded: \"{rounded.panel}\"\n    padding: \"1.5rem\"\n  search-field:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.58rem 0.65rem\"\n  evidence-beacon:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.backend}\"\n    typography: \"{typography.label}\"\n    rounded: \"{rounded.pill}\"\n    size: \"30px × 12px\"\n---\n\n# Design System: Archify\n\n## Overview\n\n**Creative North Star: \"The Evidence Console\"**\n\nArchify is a composed technical instrument, not a drawing suite. The canvas carries one spatial narrative; restrained controls and progressive disclosure let a reader move from the primary path to exact authored relationships, metadata, and verified code evidence without losing orientation.\n\nThe visual system is precise, dark-first, and vivid only where semantics earn it. Light mode and Blueprint preserve the same vocabulary rather than becoming separate products. Motion has one bounded owner, finishes, and never carries meaning that disappears in a still frame. Desktop is the primary surface; narrow screens receive containment, not a second interface.\n\n**Key Characteristics:**\n\n- One dominant technical canvas with compact, low-interference chrome.\n- A fixed semantic color vocabulary shared by nodes, edges, legends, focus, and evidence.\n- Mono-forward typography, small labels, and deliberate density for engineering review.\n- Viewer state stays outside canonical exports; proof remains portable and deterministic.\n- State transitions are 140–200ms; authored story motion may be longer but finite and reader-controlled.\n\n## Colors\n\nThe palette is a midnight console with seven semantic signals; color identifies meaning, never decoration.\n\n### Primary\n\n- **Verified Cyan** (`frontend`): the main focus, navigation, and frontend signal. Its scarcity establishes hierarchy.\n\n### Secondary\n\n- **Proof Green** (`backend`): backend semantics, verified evidence, and successful state.\n- **Repository Violet** (`database`): persisted state, stores, and inward relationships.\n\n### Tertiary\n\n- **Boundary Rose** (`security`): policy, security, and guarded paths.\n- **Cloud Amber** (`cloud`), **Transit Orange** (`messagebus`), and **External Slate** (`external`): stable semantic categories, never interchangeable accents.\n\n### Neutral\n\n- **Midnight Canvas** (`canvas`) and **Ink Mask** (`mask`): the dark workspace and opaque geometry mask.\n- **Instrument Ink** (`ink`), **Quiet Copy** (`muted`), **Dim Annotation** (`dim`), and **Structural Border** (`border`): the text and containment ladder.\n\n### Named Rules\n\n**The Semantic Color Rule.** Every saturated color maps to a node or relationship meaning; never add an accent merely to make a surface lively.\n\n**The Theme Parity Rule.** Light, dark, Signal Flow, and Blueprint may change material and contrast, but must preserve category identity and information priority.\n\n## Typography\n\n**Display Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Body Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Label/Mono Font:** JetBrains Mono\n\n**Character:** A single mono family makes the artifact feel authored by an engineering instrument. Hierarchy comes from weight, scale, spacing, and case rather than a decorative display face.\n\n### Hierarchy\n\n- **Headline** (700, `1.5rem`, 1.2): artifact title only.\n- **Title** (600, `0.875rem`, 1.4): panels, cards, and selected semantic objects.\n- **Body** (400, `0.75rem`, 1.55): explanatory copy and relationship details.\n- **Label** (700, `0.625rem`, `0.12em`, uppercase): state, modes, metadata, and compact proof markers.\n\n### Named Rules\n\n**The One Voice Rule.** UI and diagram chrome remain mono-forward; never introduce a display font inside the generated artifact.\n\n**The Legibility Floor Rule.** Tiny labels are metadata, not prose. If a reader must parse a sentence, promote it to body size or disclose it on focus.\n\n## Elevation\n\nArchify is flat and tonal by default. Borders and surface contrast establish structure; shadows appear only on floating controls, temporary panels, active focus, or the Signal Flow atmosphere. Blueprint removes glow and squares materials to keep the review surface exact.\n\n### Shadow Vocabulary\n\n- **Canvas Lift** (`0 28px 80px rgba(0,0,0,0.34)`): Signal Flow diagram surface only.\n- **Floating Panel** (`0 18px 48px rgba(0,0,0,0.30)`): temporary discovery panels and the Semantic Passport.\n- **Action Feedback** (`0 0 7px var(--frontend-stroke)`): active SVG focus only, never an idle decoration.\n\n### Named Rules\n\n**The Flat-at-Rest Rule.** A static card or control uses border and tone; a shadow must explain layering or state.\n\n**The Canonical Clean Rule.** Viewer glow, overlays, focus, and temporary marks are removed from visual exports unless the export explicitly owns that narrative.\n\n## Components\n\n### Buttons\n\n- **Shape:** compact rounded rectangle (`0.5rem`), or precise corners (`0.2rem`) in Blueprint.\n- **Primary:** translucent toolbar material, one-pixel structural border, and mono body label. Desktop viewer chrome may use compact 32px controls; touch and narrow-screen targets stay at least `2.75rem` high.\n- **Hover / Focus:** 150ms border/background response; `2px` cyan focus ring with `2px` offset.\n- **Secondary / Ghost:** transparent within menus; never add a second saturated fill hierarchy.\n\n### Chips\n\n- **Style:** quiet bordered capsules for semantic metadata; selected state uses the owning semantic color.\n- **State:** a chip may summarize focus, mode, count, or evidence, but must not become an unlabeled icon-only control.\n\n### Cards / Containers\n\n- **Corner Style:** composed panel corners (`1rem`), reduced to `0.35rem` in Blueprint.\n- **Background:** tonal panel over the canvas, with a one-pixel border.\n- **Shadow Strategy:** flat by default; floating or Signal Flow surfaces use the elevation vocabulary.\n- **Internal Padding:** `1.25rem`–`1.5rem` for panels; compact proof blocks may use `0.5rem`–`0.75rem`.\n\n### Inputs / Fields\n\n- **Style:** one continuous bordered field, `0.5rem` corners, muted placeholder, and compact mono body text.\n- **Focus:** no browser outline; shift the border to Verified Cyan and add a restrained two-pixel halo.\n- **Error / Disabled:** preserve readable text and add a non-color cue; never rely on opacity alone for failure.\n\n### Navigation\n\n- **Style:** the diagram remains dominant. Toolbar, guided views, map, search, and passport appear only when relevant and reuse familiar labels.\n- **Default / Hover / Active:** 140–200ms state response; active state combines text, border, shape, or marker—not color alone.\n- **Narrow screens:** contain and stack existing controls safely; do not create a dedicated mobile product surface.\n\n### Semantic Passport\n\nOne focused node opens one compact proof surface containing stable ID, authored metadata, relationships, and optional revision-pinned sources. It is the single destination for details; new capabilities should route here before proposing another panel.\n\n### Verified Source Beacon\n\nAn evidence-backed node receives one viewer-only `SRC n` capsule in its upper-right corner. It inherits node state, adds no tab stop, and is stripped from every canonical visual export.\n\n### Brand Mark\n\nAn authored `brand` adds one compact identity badge to the upper-right of the\nnode. Built-in vectors and explicitly captured, digest-pinned site icons sit on a neutral plate;\ntheir color stays inside that plate and never recolors the semantic node, edge,\nlegend, focus, or evidence vocabulary. The semantic sigil remains visible. A\nVerified Source Beacon shifts left when both facts are present. Brand marks are\ncanonical authored SVG content and therefore survive visual export.\n\n### Authored Reachability\n\nSemantic Passport offers two native, count-bearing actions: `Upstream` follows authored incoming relationships and `Downstream` follows authored outgoing relationships. The canvas keeps the focused origin plus the complete reachable subgraph strong while unrelated topology recedes. Upstream uses Repository Violet, downstream uses Proof Green, and Blueprint removes glow. The receipt says nodes, links, and maximum hops; it never says blast radius or breakage.\n\n### Reach Share Card\n\nAn active reach query may expose one contextual **Export → Reach Share Card** item. The 1200×630 card keeps the full diagram as quiet context, preserves the selected origin and every matched authored node and link, and writes direction, origin, node count, link count, and maximum hops into the card header. Upstream retains Repository Violet; downstream retains Proof Green; Blueprint stays filter-free. The card is an explicit non-canonical reading variant, not runtime impact, causality, or breakage evidence. No animated state, live focus glow, camera transform, or unrelated viewer chrome enters the clone.\n\n## Do's and Don'ts\n\n### Do:\n\n- **Do** make the primary path legible before adding secondary relationships or detail.\n- **Do** derive every focus, reachability query, route, story, source link, receipt, and count from authored or locally verified evidence.\n- **Do** keep ordinary artifacts source-free and make repository evidence explicitly opt-in.\n- **Do** use 140–200ms transitions for control state and honor `prefers-reduced-motion`.\n- **Do** preserve keyboard access, visible focus, semantic labels, dark/light parity, and non-color state cues.\n- **Do** keep runtime exploration outside canonical SVG, raster, Share Card, and WebM backgrounds.\n- **Do** name an intentionally scoped Route or Reach Share Card in its header and machine-readable receipt.\n\n### Don't:\n\n- **Don't** build generic Mermaid beautifiers that change themes without improving information architecture.\n- **Don't** turn Archify into WYSIWYG drawing suites whose editing chrome becomes the product.\n- **Don't** ship motion-first graph demos that imply relationships or activity not present in the authored source.\n- **Don't** use dense dashboard shells, endless identical card grids, decorative glass, gradient text, and other AI-generated interface clichés.\n- **Don't** infer identity from arbitrary label text, add an unbounded icon marketplace, or let a brand badge replace the portable semantic vocabulary.\n- **Don't** create another permanent panel when the Semantic Passport, Node Finder, or existing canvas can carry the capability.\n- **Don't** call graph reachability runtime impact, blast radius, or breakage without independent code-analysis evidence.\n- **Don't** change the README Hero as a side effect of artifact or viewer iteration.\n","archify/references/viewer-runtime.md":"# Viewer Runtime reference\n\nRead this only when the user asks for a reader-facing capability. Ordinary generation does not require implementing or re-documenting these features; they are already in the generated HTML.\n\n## Exploration\n\n- Diagram Guide lists current actions and shortcuts. Open it with the guide button or `?`; it never opens automatically.\n- Reading Depth starts at READ at the default 100% scale, reveals FULL detail at 175%, and falls back to MAP only below 100%. Focus, route, and semantic interactions reveal their exact facts at any scale.\n- Semantic Lens summarizes selected node/relationship kinds without changing authored geometry.\n- Intent Trace previews a fine-pointer or keyboard target before committed focus.\n- Node Finder searches labels and stable IDs.\n- Semantic Passport opens on focus, shows authored upstream/downstream facts, supports a copyable deep link, has an explicit close action, closes on true outside activation and Escape, and never enters canonical export.\n- Semantic Radar mirrors the visible viewport and authored graph without becoming a second source of truth.\n- Direct Relationship Pin makes a unique compiled relationship operable while preserving the authored line and stable relationship identity. It must fail closed on conflicting source/target/label/ID metadata.\n- Route Probe resolves exactly two endpoints over authored directed relationships. It never infers a route from geometry.\n\n## Embedded reading addresses\n\nA host displaying the native reader in an opaque `srcdoc` frame may set\n`data-reading-link-template` on that reader's `html` element. Supply an absolute\nHTTP, HTTPS or file URL containing exactly one `{state}` marker, for example\n`https://example.test/architecture#page=mechanism&reader={state}`. Native Focus,\nRelationship, Reach, Route and Lens copy actions replace the marker with their\npercent-encoded opaque query state. The host keeps its page identity and restores\nthat value as the native frame's hash; it never parses or reconstructs queries.\n\nAbsent configuration preserves standalone links. Invalid, credential-bearing or\nunsupported URL templates make copying fail without accessing the clipboard.\nThis seam changes copied addresses only, not query parsing, history, permissions,\nembedding isolation or authored geometry. It adds no network or storage surface.\n\n## Motion and presentation\n\nFor a narrated walkthrough with camera framing, explanations, captions and\nsynchronized audio, use [Story authoring](story-authoring.md). The `story attach`\ncommand adds Story to the native motion control and Story video to Export.\nThe player loads on first use and follows the existing preset and theme controls.\nPlayback schedules two short audio buffers ahead instead of synthesizing the whole timeline.\nVery large video exports are rejected before rendering. Use\n`Archify.story.exportVideo({start, seconds})` for a shorter range when needed.\n\nEvery rendered diagram enables reader-controlled Live/Still motion by default. In Live, every edge runs a small light show on one shared cycle: a comet (glow, halo, tail, head, plus a dimmer echo on every edge) cascades downstream, leaves a soft wake, and lands as a ripple on the target node, while nodes enter once and then glow on the same cycle with authored-step staggering. Phases follow the authored step order (source-node rank, chronological in sequence diagrams); the flow rides a separate Viewer overlay and the original line styles and arrowheads remain intact. Compact edges receive a larger, brighter comet; echoes stay dimmer. With no saved preference, new pages start Still. Choosing Live starts continuous flow and saves that preference; choosing Still stops it and clears the saved Live preference. Existing saved Still preferences remain Still. Semantic exploration temporarily owns the motion budget, and continuous flow resumes when that action releases it. Diagrams without connections retain their bounded node entrance rather than inventing a flow. Omit `meta.animation`; historical `\"trace\"` and `\"none\"` values remain accepted for input compatibility and do not change this default. Reduced motion, page hiding, print, and canonical export preserve complete static meaning. Presentation Stage changes viewer chrome and framing, never authored geometry. This is not a mobile product feature; narrow layouts get containment only.\n\n## Canonical exports\n\nThe export menu can copy/download full-diagram PNG, download JPEG/WebP, download a dual-theme SVG, and record a trace-enabled WebM. Viewer state—Guide, Lens, finder, focus, route, camera, radar, presentation, motion ownership, and temporary overlays—must be removed from canonical export.\n\nOpening, closing, or completing an export preserves the live Focus/Reach selection for continued exploration. Export-owned download activation is not outside dismissal; genuine outside activation and Escape retain their existing behavior. Full-diagram PNG/SVG exports still contain the complete canonical diagram, while the Reach Share Card communicates the active authored closure.\n\n### Route Share Card\n\nAfter a real directed Route Probe resolves, the reader may use **Export → Route Share Card**. It reuses the exact ordered route snapshot and the shared Share Card seam: `format=share-card`, `variant=route`. The isolated clone may use only static `data-share-route-*` decoration. It is download-only, fails closed for stale/unreachable/conflicting routes, and never becomes the canonical artifact.\n\n### Reach Share Card\n\nAfter a non-empty authored reachability query, the reader may use **Export → Reach Share Card**. It consumes the already resolved upstream/downstream node and edge set without rerunning traversal: `format=share-card`, `variant=reach`. The isolated clone may use only static `data-share-reach-*` decoration. It is download-only. Call it authored reachability—not impact, blast radius, breakage, or runtime causality.\n\n## Truth boundary\n\nViewer exports are communication assets. They do not replace the checked HTML, the deterministic delivery receipt, or a real visual review. Do not add a hosted service, storage surface, dependency, schema branch, or mobile product surface for these viewer-only capabilities.\n","archify/SKILL.md":"---\nname: archify\ndescription: \"Create validated architecture, workflow, sequence, data-flow, lifecycle/state, ERD, class, tree, timeline, and waterfall diagrams as explorable standalone HTML with dark/light themes, motion and image/SVG/WebM export. Accept requirements or Mermaid; inspect repository evidence for code-backed diagrams. Also investigate local repository architecture health, coupling and refactoring scope with source-backed Code Analysis. Use when visualizing systems, API calls, pipelines, schemas, histories, timings, or everyday steps, parts, relationships and states. Also turn an answer into a one-page explainer, with the conclusion first, structured panels, native diagrams and charts, when the user asks for a page, an explainer or an answer to share (做成一页, 用页面讲), and by default unasked for a complex flow, diagnosis, comparison or test report; an [archify explainer: on-demand] rules line limits pages to requests. Optionally add a guided story and video export to an existing native diagram. Not for dashboards.\"\nlicense: Apache-2.0\nmetadata:\n  version: \"3.3\"\n  author: tt-a1i\n---\n\n# Archify\n\nCreate checked HTML as a native diagram, explainer, story, or standalone Code Analysis workbench.\n\nRun commands from your working directory. Unless the user names another location, give each new artifact request its own folder `.archify/<type>-<slug>-<YYYYMMDD-HHMMSS>/` there (local time, chosen once): keep the candidate and `<slug>.html` in it and reuse it for repairs. Native diagrams use `candidate.json` with `meta.output` relative to the working directory; explainers may use `candidate.archify.md` and a portable output filename. A later request gets a new folder. Replace `bin/archify.mjs` in every command with the installed package's absolute path, or its path relative to your working directory; CLI input and output paths resolve from that directory.\n\nFor a native diagram of a real codebase, read [Repository authoring](references/repository-authoring.md) while tracing the requested behavior. A system description uses the native steps below; a frozen candidate uses the handoff path.\n\n## Choose the artifact\n\n- For drawing a system, flow, schema or history, use a native diagram and the Type router. Deliver the requested diagram through `finalize`; code analysis is a separate mode.\n- For local repository architecture health, module coupling, cycles, layer violations, large files, complexity hotspots or refactoring orientation, use Code Analysis below; the agent handles commands and no architecture JSON is required.\n- For a guided walkthrough, animated/static dual-theme SVG, interactive stage player, or 1080p MP4/WebM video over one or more native diagrams, read [Story authoring](references/story-authoring.md). Use `story draft`/`attach` to add playback to a native Viewer, or `story validate`/`svg`/`stage`/`video` for declarative component choreography.\n- Only when the user explicitly asks to explain or visualize a pull request, a branch change or a `git diff`, or to attach change diagrams to a PR, or names the companion skill `archify-pr` when installed, read [PR review authoring](references/pr-review.md) first: it covers the three-dot diff, change-marked merged-superset views and the `pr validate` / `pr build` / `pr attach` loop.\n- Use `explainer` when the user asks for the answer as a page: a page, one page, an explainer, something to share (“做成一页”, “用页面讲”, “answer with a page”).\n- Explainer mode is `proactive` by default. A rules line `[archify explainer: <mode>]` in context selects another; an instruction in the conversation overrides it for that conversation.\n  - `proactive` (default, no line needed): also make a page, unasked, when the answer is a complex flow or process, a diagnosis or troubleshooting result, an option comparison, trade-off or decision, a test or review report, or a plan, and needs a table, steps or several sections to be read well.\n  - `on-demand`: make a page only when asked; otherwise answer in text or draw the requested diagram.\n  - `always-on` (opt-in only): every reply that reaches a conclusion also gets a compact page of at most four panels.\n- In every mode a page needs a conclusion with some structure behind it. Chat, short or one-line answers, routine status updates (“done, tests pass”), raw command output, a requested native diagram and any reply where the user asks for text only or no page (“只要文字”, “不用做页面”) get none. Make at most one page per reply, and none when the user names another page tool or another skill already made a page for that reply.\n- To change the mode, only when the user asks (“只在我要求时做页面”, “always make a page”), write or replace one `[archify explainer: <mode>]` line in the current agent's global rules file (such as `~/.codex/AGENTS.md`, `~/.claude/CLAUDE.md` or `~/.config/devin/AGENTS.md`) and name the file, for example `[archify explainer: on-demand] Make Archify explainer pages only when I ask for one.`; deleting the line restores `proactive`. Never switch to `always-on` unasked.\n- For `explainer`, read [Explainer authoring](references/explainer-authoring.md) for its conclusion, reasons, scope, board layout and optional native diagrams. Write the complete draft, then run `finalize explainer` for validation, atomic delivery and artifact checks. Use panel patch for local content revisions.\n\n## Existing candidate handoff\n\nWhen the user supplies a frozen candidate, run `finalize` first as one CLI invocation. Its passing receipt completes the automated gates; follow any visual review recommendation under Delivery before claiming visual quality. For repair, follow step 5.\n\n`finalize` includes a bounded update check in its delivery receipt; see Update awareness.\n\n## Native diagram authoring\n\nUse this path for ordinary generation. Read branch references only when their stated trigger applies.\n\n1. Choose `architecture`, `workflow`, `sequence`, `dataflow`, `lifecycle`, `erd`, `class`, `tree`, `timeline`, or `waterfall` from the question.\n2. Use the exact schema and example paths in the Type router without listing their directories. Read [Authoring defaults](references/authoring-defaults.md) and the mode's example in a bounded batch separate from project documents and complete schemas so neither is truncated; recover any missing section before writing. For a new Architecture, use `\"layout\": {\"mode\": \"auto\"}` and leave component positions to the renderer. Take component and relationship fields from the matching showcase example. Preserve any layout the user supplied. For every mode except Architecture, also read the mode and common schemas. Read the relevant schema definition before choosing any new field, enum, or constrained text, especially boundary kinds. Examples teach shape, not facts. Use fresh IDs, wording, and layout. Go directly to the candidate without preliminary help, doctor, starter validation, temporary diagrams, or output-path listing. Query brands only for an explicitly requested mark; read [Brand marks](references/brand-marks.md) for an unknown mark with a user-provided URL.\n3. Once the requested scope and, for a real codebase, [source evidence](references/repository-authoring.md) are covered, write the complete candidate directly without planning coordinates in prose. Choose Architecture abstraction and connected placement using Authoring defaults before coordinates: show the main user journey and necessary branches, preserve control roles and behavior-changing conditions, and leave enough room for actual relationship labels. No node, relationship, source, view, card, or boundary count is a target or ceiling. Use automatic routes first; add explicit routing only for necessary branch, return, supplied geometry, or measured repair. Set `meta.quality_profile` to `\"showcase\"` unless the user requests dense `standard`. For a grid ERD with automatic canvas, placement and routing, omit `layout.entityW` and entity `width` to fit fields. With a fixed view box, pinned table or manual route, size wide tables explicitly. For ERD, use a table-first layout: show every physical column in `entities[].attributes`, keep its SQL type and source comment, state every key role a column carries (`key` takes a role or a list, so a junction column is `[\"pk\", \"fk\"]`, and every `fk` column also needs `references` like `\"orders.id\"`), and never move columns into cards as a substitute for the table. Classify tables into functional domains before placement, give each domain a concise `tag`, and place its members in one solid rectangle of grid cells — a single row, a single column, or a filled rectangular block, not an L or diagonal. A tagged table always needs `row`/`col`, because absolute coordinates have no grid cells and a domain whose tables do not fill one rectangle cannot be drawn as a band: the renderer reports `erd/domain-not-drawn` instead of publishing a diagram that cannot name the domain. A multi-domain schema reads best as one domain per column — each `tag` a vertical run — because the reader scales a wide canvas up to the reader width and shrinks a tall one until the page fits, so the wide arrangement is the one that stays complete and legible inside a laptop viewport. A schema-first ERD over roughly 8 tables or 50 fields is itself a dense map: author its first complete-field pass at `standard` and upgrade only once the layout still reads.\n4. Once the complete first candidate is written, run `finalize` directly. Its first gate is showcase validation; successful first drafts need no separate pre-validation. Keep the candidate unchanged while the command runs:\n\n   ```bash\n   node bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n   ```\n\n   For a repository-backed candidate, include evidence on the first draft and use the complete first command: `node bin/archify.mjs finalize <type> <candidate.json> <output.html> --repo-root <repo-root> --quality showcase --json`. Pass the `--quality` that matches `meta.quality_profile`, such as `standard` for a dense first ERD pass.\n\n   A passing receipt proves the included `validate`, `deliver`, strict `check`, and real-browser `browser-check` gates passed. Use its compact summary; run standalone commands only for a separate request or focused failure diagnosis. After a passing Architecture finalize with `codeAnalysisOffer`, end the delivery summary with the [Architecture Diagnosis section](references/delivery-contract.md#architecture-diagnosis-offer) in the user's language, once per repository in the task. Skip it if the user already asked for or declined analysis. Wait for yes before running the offered command.\n\n5. A non-zero exit is never success. Read compact stdout or `evidence.summaryReceipt`, then [repair the failed gate](references/delivery-contract.md#failed-finalize-and-candidate-repair), including its repair limit. Preserve requested meaning and source evidence. For several tangled Architecture routes, read [Architecture layout repair](references/architecture-layout-repair.md); for measured field or geometry failures, read [Authoring contract](references/authoring-contract.md). Edit the connected neighborhood and rerun the complete `finalize` command from step 4. Once a run has reached `browser-check`, the output path owns that evidence: give every later run its own `--out-dir <folder>/review-<n>`.\n\n## Update awareness\n\n`finalize` and standalone `deliver` include `update` in their receipts. Do not run a separate check for the same delivery. If `update.noticeRequired` is true, read `references/update-awareness.md` and keep one compact update notice in your final response to the user, even after a quality gate fails. For a task with several diagrams, mention the update once in the final response. Snooze or ignore a reminder only when the user explicitly asks; never install or update on your own initiative.\n\nBefore the first candidate, use the authoring references and relevant repository source, not Archify implementation or tests. Inspect Archify implementation if diagnostics remain unactionable after focused repairs.\n\n## Type router\n\n| Type | Use for | Schema | Example |\n|---|---|---|---|\n| `architecture` | Components, services, cloud/security boundaries, infrastructure; what something everyday is made of | `schemas/architecture.schema.json` | System descriptions, services, libraries, and CLI repos: `examples/web-app.architecture.json`; deployment repos: `examples/production-deployment.architecture.json` |\n| `workflow` | Processes, approval gates, tool calls, runbooks, CI/CD; plans and step-by-step life processes | `schemas/workflow.schema.json` | `examples/agent-tool-call.workflow.json` |\n| `sequence` | API call chains, request lifecycles, async traces, returns; back-and-forth between people | `schemas/sequence.schema.json` | `examples/cache-miss-request.sequence.json` |\n| `dataflow` | Pipelines, ETL/ELT, lineage, governance, consumers; where money or documents go | `schemas/dataflow.schema.json` | `examples/product-analytics.dataflow.json` |\n| `lifecycle` | State/status transitions, retries, waiting and terminal states; where an application or order stands | `schemas/lifecycle.schema.json` | `examples/deployment-release.lifecycle.json` |\n| `erd` | Tables/entities, attributes, primary/foreign/unique keys, cardinality between them | `schemas/erd.schema.json` | `examples/orders.erd.json` |\n| `tree` | Single-parent containment: repository/module trees, capability or feature breakdowns, org-style decomposition | `schemas/tree.schema.json` | `examples/payment-platform.tree.json` |\n| `class` | Classes, interfaces, selected members, and dependency/association/inheritance/realization/composition between types | `schemas/class.schema.json` | `examples/payments.class.json` |\n| `timeline` | When things happened: incident reviews, release histories, timestamped events on a proportional clock with source lanes | `schemas/timeline.schema.json` | `examples/payment-incident.timeline.json` |\n| `waterfall` | Where the time went: span durations, overlap, and nesting of one request or agent run on a common time axis | `schemas/waterfall.schema.json` | `examples/checkout-request.waterfall.json` |\n\nWhen choosing among native diagram types is ambiguous, run `node bin/archify.mjs guide \"<scenario>\" --json`. Scenario proof examples are structural references, not facts to copy.\n\nFor an everyday subject, keep the same diagram modes and semantic types, then name them for the reader: use everyday `icon` values and `meta.legend` labels as in [Node icons](references/authoring-contract.md#node-icons). Ask for missing personal facts instead of inventing dates, amounts, or rules.\n\n## Mermaid input\n\nRead Mermaid for topology and meaning, then author fresh Archify JSON; do not mechanically render Mermaid styling.\n\n- `flowchart` / `graph` → `workflow`, or `architecture` for a component map.\n- `sequenceDiagram` → `sequence`; participants become semantic participants and arrows become messages.\n- `stateDiagram` → `lifecycle`; states and transitions retain meaning, not Mermaid style.\n- `erDiagram` → `erd`; entity and relationship names, keys, and cardinality retain meaning, not Mermaid style.\n- `classDiagram` → `class`; type kinds, selected members, and relationship kinds retain meaning, not Mermaid style.\n\n## Delivery\n\nUse the `finalize` command above for the first candidate and after a repair.\n\n`finalize` stops at the first non-passing gate. Its compact stdout and `<output-stem>.finalize-summary.json` are ordinary evidence. A passing run creates no screenshots and reports `visualReview: \"not-requested\"`.\n\nWhen a passing Architecture receipt reports `visualReviewRecommendation.signals.resolvedCrossovers`, save the candidate and follow [Architecture layout repair](references/architecture-layout-repair.md). Where several lines cross the reader’s main path, place the connected main steps in order and put each branch beside the component that owns it. Use the hints to locate the affected relationships. Make one edit to node positions and sizes only: every node, relationship (including its `from` and `to`), label, and source stays as it was. Rerun the complete `finalize` once with `--out-dir <folder>/review-2`, because the previous HTML already owns its browser evidence. `--out-dir` relocates the new browser-check and default finalize receipts, not the HTML or its delivery receipt. Successful delivery rewrites that pair at the requested output path; earlier review evidence remains bound to its original artifact bytes. See [review evidence paths](references/delivery-contract.md#a-new-candidate-at-an-existing-output-path). If that run fails, reports more crossings, or reports the same crossings with more `signals.routesOverSuggestedBends`, restore the copy and finalize it with `--out-dir <folder>/review-3`. Do not start a second placement round. Hints about extra bends alone are optional.\n\nWhen `layoutReviewRecommendation.action` is `inspect-sequence-width`, follow [Sequence width review](references/delivery-contract.md#sequence-width-review) before handing off a newly authored Sequence.\n\nFor a project README, deliver a static SVG by default. Follow an explicit request for a link or interactive HTML. Use Chrome or Chromium to export the finished HTML to a new file with `node <skill-dir>/bin/export-svg.mjs <diagram.html> <image.svg> [auto|light|dark]`. If the answer depends on small labels or Viewer cards, deliver a paste-ready Markdown image and a short caption that answers the question at normal text size.\n\nFor a README or project document, inspect the delivered diagram at its intended reading size. Follow the arrows from the starting point through each return or branch needed to answer the request. Verify conditional steps, fields and checks against the source, and name the condition where the reader sees the claim. Repair a broken reading path and inspect the result. For multiple runtimes or conditional handoffs, use the [reader check](references/repository-authoring.md#check-the-readers-answer).\n\nPerceptual review is optional for ordinary generation. Use [Optional capture evidence](references/delivery-contract.md#optional-capture-evidence), with `--out-dir <folder>/visual-check`, for a reproducible review or a concrete route/browser concern. `visualReviewRecommendation` is advisory. Inspect captures before claiming visual quality; qualify any check claim as automated when perceptual review has not occurred.\n\nRead [Delivery contract](references/delivery-contract.md) for failed gates, standalone commands, provenance/recovery, repeated delivery, exports, or opening. Native diagram recovery follows `deliver` → strict provenance `check` → `browser-check`; captures require strict provenance. Explainer delivery uses validate, deliver and check as described in its authoring guide.\n\nFor workflow viewport overflow, read [Workflow viewport repair](references/authoring-contract.md#workflow-viewport-repair) before the next layout edit.\n\nWhen reporting verification details, distinguish artifact checks, browser evidence, captures, and actual perceptual review. For an explicitly requested immediate preview or active desktop loop, see [Optional opening](references/delivery-contract.md#optional-opening).\n\n## Code Analysis (local repository architecture)\n\nFor a repository investigation, run `node bin/archify.mjs code-analysis prepare <repo-root> --out <analysis-dir> [--locale zh-CN|en] [--language ts|py|java|go|rust]`. Use `--locale zh-CN` for Chinese conversations. It creates `analysis/repo.analysis.html` with a source-backed workbench, interactive Atlas and captured AI tasks, then exits. No architecture JSON or diagram authoring is needed. Normal diagram requests end with their `finalize` delivery; analysis runs when the user requests investigation. Add `--ir <architecture.json>` only when a relevant diagram already exists or the user also wants authored architecture boundaries aligned with code evidence. This keeps the existing architecture/Atlas views and checked source mapping. Read [Code Analysis entry and investigation](modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation) for adapter prerequisites, headless checks, interactive re-analysis and coverage limits. Deliver the analysis HTML with one or two scoped observations and its task-copy controls, or continue investigating in this conversation. Users need no maintenance objective or CLI knowledge. Analysis describes the working tree, including uncommitted source; keep authored commit evidence separate. Verify source before editing, make a scoped improvement or explain why to retain the structure, then rerun analysis and project tests. Report measured preparation time and tool gaps, preserve any separately delivered diagram on failure, and avoid claims that static or missing findings prove runtime failure or a fix.\n\n## Optional viewer capabilities\n\nArchitecture, Workflow, Sequence, Dataflow and Lifecycle nodes may carry optional plain-text `explanation` (1–1200 characters). The focused Semantic Passport offers Explain; prose stays outside canonical SVG and visual exports. Omit the field when the existing label, sublabel and sources are sufficient.\n\nLive motion is enabled by default for every rendered diagram; omit `meta.animation`. The Viewer’s Live/Still button controls playback.\n\n### Cross-diagram navigation (overview → module → detail across HTML artifacts)\n\n- Targets are same-directory `filename.html` only (optional `?` / `#`). No `../`, `/`, or schemes.\n- Node `href` is sugar for a one-entry list (label defaults to the node label). `drilldowns` wins if both are present.\n- One child: native SVG `<a>` + corner mark; click follows the link; Alt-click focuses Passport.\n- Several children: Passport lists every target; click focuses; Ctrl+click / double-click opens the first entry.\n- Child diagrams may set `meta.parentHref`. The header Back control appears when `parentHref` or URL `?from=` is present.\n- Examples: sibling pair `examples/drilldown-platform.architecture.json` ↔ `examples/drilldown-integrations.architecture.json`; multi-child `examples/drilldown-overview.architecture.json`.\n\nRead `references/viewer-runtime.md` only when the user explicitly asks for Share Cards, Route/Reach cards, motion, deep links, presentation, search/focus, or another Viewer Runtime feature.\n\n## Setup and fallback\n\nNo install is required inside the skill package. For setup diagnosis, verify with:\n\n```bash\nnode bin/archify.mjs doctor\nnode bin/archify.mjs demo <output-directory>\n```\n\nFor native diagrams, when shell access is unavailable, hand-place architecture SVG into `assets/template.html`, use CSS semantic classes rather than inline colors, and follow the visual review contract in `references/delivery-contract.md`. Explainers require their renderer and real delivery gates; if those are unavailable, report the limitation and give a text answer when useful, without claiming HTML delivery.\n\n## Output\n\nReply in the user's language, as briefly as the result allows; the diagram carries the content, so a single diagram usually needs one line.\n\n- For a README diagram, lead with a link to the requested artifact (the exported SVG by default). Link the README when edited. For other native diagrams, lead with the HTML. Use descriptive Markdown links with absolute paths, wrapping paths with spaces in `<...>`.\n- When the user wants to understand a system or codebase rather than draw a described subject, add one or two sentences with the key takeaway. Skip sentences that only restate what the diagram obviously shows.\n- State anything that changes how the diagram should be read: the abstraction level or deliberately omitted parts when a reader might expect them, illustrative rather than measured values, missing source evidence, or requested content dropped or merged during repair.\n- For several diagrams, report completion once with a link to an existing overview or compact per-diagram links, not a directory path.\n\nDo not recap commands, repair rounds, hashes, quality profiles, or check lists; they stay in the receipts. If asked whether the diagram was verified, answer in one line, such as “Automated checks passed; not visually reviewed.” Give receipt links and details only for reproducibility or troubleshooting. Disclose requested visual review that could not run, and claim visual inspection only when performed. Keep the required update notice under Update awareness.\n\nExample: `Created [Checkout request timing](/abs/path/checkout-timing.html). Durations are illustrative, not measured.`\n\nFor an explainer, the reply must read well without opening the page: the conclusion in one to three lines with the key cause, numbers or recommendation, then, as the very last line, a Markdown link with a descriptive title in the user's language, such as `[查看测试报告](/abs/path/test-report.html)` or `[Open the test report](...)`. Use the absolute path, wrapped in `<...>` when it contains spaces, not `file://`; put any update notice before it. Never offer a directory, terminal log or auto-open (`--open`) instead of the link. When `finalize explainer` fails or the renderer is unavailable, answer in text, say in one line that the page was not produced, and give no page link. Mention gates only when one failed or writing warnings remain; do not paste the draft.\n","archify/references/delivery-contract.md":"# Delivery contract\n\n## Failed finalize and candidate repair\n\n`finalize` stops at the first non-passing gate. Use compact stdout or `evidence.summaryReceipt`; read its full sidecar only when the summary lacks evidence needed for a coherent repair. A receipt with four artifact checks is basic validation, not showcase acceptance: require all nine checks, zero composition errors, and zero warnings. Fix `meta.quality_profile` and schema errors before geometry. A dense full-schema ERD may keep `standard` for its first complete-field pass: require zero structural errors, no edge-through-node failures, complete field rows, and a readable grouped grid, and record composition warnings instead of spending unbounded time on them.\n\nWhen every diagnostic from the first embedded validation is\n`repository-evidence/line-out-of-range`, `finalize` may narrow an existing\ncitation's `end_line` to the last line of its pinned file and retry the complete\ngates once. The start line must already exist in that nonempty file; the source\npath, revision, start, and all other authored content stay unchanged. Automatic\nrepair requires the original bytes to match `JSON.stringify(parsed, null, 2)`\nplus one LF exactly. Other formatting, a BOM, CRLF, or number spellings that\nwould change on parsing and serialization require author repair, so reserialization\ncannot change unrelated bytes or numeric precision. Missing files, invalid starts,\nand mixed failures also require author repair. This only bounds\nthe cited range; it does not establish or correct the cited fact. `autoRepair`\nrecords the changed ranges and original/repaired hashes in both receipts. A\npassing retry keeps the repaired candidate. Any later failure or exception\nattempts a byte-for-byte restore, guarded by the repaired candidate's identity\nand bytes, and invalidates only that retry's current-delivery sidecar. External\nedits are preserved and a returned receipt reports `restore-failed` if recovery\ncannot safely complete. Failure diagnostics and `specification` describe the\nchecked retry; `autoRepair.outcome` states whether the original was restored.\nThrown exceptions remain command failures and may leave the last persisted\nreceipt at an earlier stage; only a completed passing command is a handoff.\n\nFor a validation failure, edit the existing JSON in the connected neighborhood named by diagnostics before rerunning a command. Preserve requested semantics, meaningful labels, source evidence, and fixed or agreed topology. Several routes sharing nodes call for one placement repair; read [Architecture layout repair](architecture-layout-repair.md) for that case. Reflow a blocked main path rather than nudging unrelated labels. Keep unrelated geometry when its composition already reads clearly. Use `--layout-json` before editing only when compact evidence lacks needed measurements. Workflow v2 uses its stable compiler receipt, not solver internals, as authoring evidence.\n\nKeep the best candidate that cleared route checks before a viewport repair. If that repair introduces new route collisions, restore the measured layout and address its remaining canvas or text constraint.\n\nAfter the edit, rerun the complete `finalize` command with `--quality showcase` and, for repository-backed work, `--repo-root <repo-root>`. If the output path already has browser evidence from another candidate, use a fresh `--out-dir <output-stem>.review-<revision>` for both the new `finalize` and any `visual-check`. Omit an earlier `--candidate-sha256` after editing because it binds the previous candidate. Compare diagnostics by code, subject, stage, and evidence, never by declining error count alone. Track the repair limit per persistent issue, using that code, subject, stage, and evidence: a newly exposed issue starts its own repair sequence. If an issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, report the concrete gap.\n\nUse standalone `validate` only for focused diagnosis, passing `--repo-root` for repository-backed work. Its passing receipt marks `candidateFrozen: true`; run `nextAction.arguments`, replacing only `<output.html>`, without editing, revalidating, or rereading the candidate. Retry later environmental or evidence failures against those frozen bytes. A measured reason to edit creates a new candidate and calls for the complete `finalize` without the old hash.\n\n## Validate and deliver\n\n`render` and direct renderer entry points print classified authoring failures\nto stderr as readable diagnostics and exit 1. Input read/JSON parse failures\nuse `input/read` or `input/json-parse`; output filesystem failures use\n`output/write` and identify the output path. Schema and layout failures keep\ntheir existing rule codes. Use the advertised `validate --json` or\n`deliver --json` interface for a machine receipt; `render` has no `--json` flag.\nUnexpected implementation failures retain debugging information in human\nmode and remain `internal/unclassified` in machine receipts.\n\nDeclared local Explainer chart data and native-diagram specification files are protected inputs, including physical aliases. Delivery and finalize refuse sidecars that would overwrite those inputs, including when resource preparation fails; an uninspectable draft cannot publish failure evidence.\n\nEach delivered output has two artifact-specific metadata paths. When an output\nstem is too long for those derived filenames, Archify shortens it and appends a\nstable hash:\n\n- `<output-stem>.delivery.json` records the latest completed attempt.\n- `<output-stem>.delivery-pending.json` is the recovery journal for an attempt\n  in progress.\n\nFor a literal artifact stem that already matches Archify's reserved bounded-name\nmarker, a pre-namespace raw provenance sidecar remains a read fallback when the\nencoded sidecar is absent. A pre-namespace raw pending journal is an independent\nfail-closed barrier: it blocks checks and redelivery even when an encoded pending\njournal also exists, and neither journal is silently replaced.\n\nOne directory-wide `.archify-delivery-lock.json` serializes every delivery that\nresolves into the same physical output directory. This deliberately prevents\ncase, Unicode-normalization, Windows short-name, and symbolic-link aliases from\ncreating independent owners for one filesystem location. The tradeoff is that\ndeliveries to different artifact names in one directory also run serially;\nprovenance and pending journals remain artifact-specific.\n\nFor migration safety, Archify also detects and preserves a legacy\n`<output-stem>.delivery-lock.json` beside the requested artifact. An existing\nlegacy entry is a fail-closed recovery barrier. While a new delivery owns the\ndirectory mutex, it also holds temporary legacy-format fences for the requested\nspelling and an existing artifact's physical target spelling. It acquires the\ndirectory lock first, then all required compatibility fences before writing a\njournal or artifact, and removes the directory lock before those fences during\nrelease. This blocks an older Archify binary using\neither known spelling from entering the delivery. A legacy fence whose raw\nHEAD-era filename exceeds the host component limit is omitted because the old\nbinary could not create that lock or deliver that artifact on the host either.\n\n`deliver` acquires the lock by exclusive `open(..., \"wx\")` before creating or\nreplacing the recovery journal. A successful exclusive create yields an\ninternal opaque ownership capability bound to that attempt. Journal creation,\nfailed-provenance recording, pair commit, rollback, journal finalization, and\nlock release each verify the current capability inside the operation that\nwould mutate shared state. A rejected contender does not create a journal or\nwrite failed provenance.\n\nAn existing directory or legacy lock is handled without automatic recovery:\n\n| Observed lock state | Required `deliver` result |\n| --- | --- |\n| No directory entry | Attempt exclusive creation; only its success grants ownership. |\n| Valid schema-v1 lock whose PID is running, or whose death cannot be established | Exit 1 with `delivery/concurrent-attempt`; preserve every shared path. |\n| Valid schema-v1 lock whose PID is known to have exited | Exit 1 with `delivery/lock-stale`; preserve the lock, artifact, journal, and current provenance exactly. |\n| Unreadable, malformed, symlink, dangling symlink, directory, or other non-regular lock entry | Exit 1 with `delivery/lock-invalid`; preserve the entry and every other shared path. |\n| An acquired capability no longer matches the current lock or journal | Exit 1 with `delivery/ownership-lost`; stop all shared-path mutation. |\n| The matching owner cannot remove its lock | Exit 1 with `delivery/lock-release`; preserve the lock. |\n\nA `delivery/lock-stale` diagnostic identifies the absolute output and lock\npaths plus the original PID and receipt ID. Recovery is deliberately explicit\nand serial: stop all delivery attempts for that physical output directory,\nconfirm that no active delivery owns it and that the reported stale entry has\nnot been replaced, remove only the reported lock, then rerun `deliver`. Do not\nremove an artifact, current provenance, or pending journal as part of\nstale-lock recovery.\n\nThe lock protocol targets Node.js 18 or later on a local filesystem with\ncooperating Archify processes. PID, receipt, and file-identity comparisons are\ndefensive checks, not an atomic compare-and-swap. Compatibility fences cover\nthe requested spelling and an existing physical-target spelling; they cannot\nenumerate arbitrary hard-link names or previously unknown filesystem aliases,\nso mixed-version delivery through such aliases remains out of scope. This\ncontract does not claim distributed-lock correctness on NFS, SMB, or other\nnetwork filesystems, and it cannot prevent an external process that ignores\nthe protocol from replacing shared paths.\n\nEvery no-clobber HTML publisher (`render`, `deliver`, `compare`, and `preview`)\ncaptures the requested directory entry, canonical write slot, physical parent,\nand existing target type, device/inode identity, and mode before staging, then\nrevalidates that snapshot immediately before replacement. An existing write\ntarget must be a regular file with exactly one hard-link name. A target with\nmultiple hard-link names fails closed with `output/target-hardlinked`: replacing\nthe requested name cannot update unknown sibling names as one publication.\nHard links remain supported for read identity and input/alias collision checks;\nthey are unsupported only as write targets. A symbolic link to a single-link regular\nfile remains supported: publication preserves the symbolic-link entry and\napplies the same protocol to its resolved target. Directory, FIFO, socket,\ndevice, changing mode, new claimant, and indeterminate identity cases fail\nbefore replacement.\n\nPublication is no-clobber and recoverable, not crash-atomic replacement of an\nexisting target. To avoid overwriting a claimant that appears after the last\nidentity check, Archify first retains the bound old file in a private recovery\nbackup, removes the public name through identity-bound quarantine, and then\ncreates the new public name with an exclusive hard link. A caught failure rolls\nback when the public slot and recovery binding still permit it. A process\ninterruption between those namespace operations can instead leave the public\npath absent while the verified previous bytes remain in an adjacent private\nrecovery backup. Single-artifact publication records the original slot/alias\nidentity and backup inode, mode, SHA-256, and byte count in private\n`.archify-remove-*/publication-recovery-v1.json`, beside `previous`. To make a\nspecific interrupted publication visible again, stop concurrent writers and run:\n\n```bash\nnode bin/recover-output.mjs /absolute/path/to/.archify-remove-<id> --json\n```\n\nThis is explicit recovery, not a directory scanner. Before linking, the helper\nchecks for a changed parent or alias, an altered/hardlinked record or backup,\ndigest or inode mismatch, and any existing public target. It restores only by\nno-clobber hard link, so a new claimant is preserved rather than overwritten;\nit never recursively removes unknown entries. A completed recovery is\nidempotent. The record is evidence to be independently verified, not an\nauthority to restore arbitrary private bytes: the helper accepts it only from\nthe recorded generated child of the original physical target parent, with the\nsame directory identity. Name the exact directory reported by the interrupted\nprocess and inspect an uncertain record manually. A non-cooperating process can\nstill swap pathnames after those checks and before Node.js `linkSync`; Node does\nnot expose a descriptor-bound link operation. Post-link identity verification\nthen fails closed and retains recovery evidence, rather than claiming recovery\nor deleting an uncertain name. If recovery itself is interrupted after the\nlink, the old public bytes and private backup can both remain; a later recovery\nrun preserves the public target and needs explicit operator resolution. The\nrecord is fsynced before the old public name is retired on platforms supporting\ndirectory sync, and the tested guarantee is recovery after a killed process;\nthis is not a claim of power-loss, storage-controller, NFS, or SMB durability.\nPaired flows retain their backup in private transaction staging. For `deliver`,\nthe pending journal and lock keep strict checkers fail-closed. The portable\nNode.js filesystem API has no pathname\ncompare-and-swap that both replaces an existing name atomically and refuses to\noverwrite a late claimant: `rename` would close the visibility gap only by\noverwriting that claimant.\n\nAfter ownership is established, `deliver` creates the journal before rendering\nand keeps it through the recoverable HTML/sidecar pair commit. It removes the\njournal only after that commit completes. A validation, render, or pair-commit\nfailure, or a process interruption, may therefore leave a journal. The journal\nis a safety barrier: `check`, `browser-check`, and `visual-check` fail closed when any directory\nentry exists at the journal or lock path, including an unreadable file,\nsymlink, or dangling symlink. Run deliveries targeting the same physical output\ndirectory serially; one attempt must finish or be recovered before another\nbegins.\n\nA successful sidecar has `schemaVersion: 1`, `status: \"current\"`,\n`command: \"deliver\"`, a unique `receiptId`, the diagram `type`, an absolute\n`input` path, an absolute `output` path matching the inspected\nartifact, and specification/artifact SHA-256 and byte counts. Checkers treat a\nmissing, malformed, unsupported, or inconsistent field as invalid. They also\nreject a sidecar symlink, including a dangling one. A checker binds provenance\nto the artifact bytes it actually checks and verifies that binding again before\nreporting success; a concurrent byte change fails. The provenance directory\nentry itself must be a single-link regular file: `deliver` and strict check fail\nclosed with `delivery/provenance-hardlink-unsupported` when it has another hard\nlink, without scanning for or guessing the sibling name.\n\nIf a currently verified owner fails after an older HTML exists, Archify writes\na new `status: \"failed\"` sidecar and leaves the journal until recovery is\ncomplete. An unreadable old HTML does not prevent that marker; its artifact hash\nand byte count may be absent. If the sidecar is locked or otherwise unwritable,\nArchify keeps the prior sidecar rather than deleting evidence, and the journal\nprevents checkers from trusting it. A rejected concurrent, stale, or invalid\nlock attempt does not write failed provenance. If ownership is lost, Archify\nreports `delivery/ownership-lost`, does not overwrite or remove the successor's\nartifact, provenance, journal, or lock, and does not claim recorded failed\nprovenance; a failure receipt may report `provenance: \"unrecorded\"`. If every\nmetadata path is unavailable, the same unrecorded status applies; no tool can\npreserve that fact across processes. Restore metadata-path access and complete\na successful `deliver` before trusting the output.\n\nArtifacts with no sidecar, journal, or lock remain supported for backward\ncompatibility and for the lower-level `render` command. Their checker receipts\nreport `provenance: \"unknown\"`; use `--require-provenance` to turn that state\ninto a non-zero failure when the workflow requires a successfully delivered\nartifact:\n\n```bash\nnode bin/archify.mjs check <output.html> --require-provenance\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\n## Output path contracts\n\nArchify intentionally separates durable authored paths from command-line paths:\n\n- Required authored `meta.output` is a portable POSIX-relative path such as\n  `reports/diagram.html`. It uses `/`, ends in a non-empty `.html` basename,\n  and cannot contain an absolute or drive-relative prefix, URI, backslash,\n  empty or dot segment, control character, unpaired UTF-16 surrogate, Windows\n  alternate-data-stream separator or invalid filename character, trailing dot\n  or space, DOS device name, or a component over either the 255-byte UTF-8 or\n  255-code-unit UTF-16 limit. It resolves from the current working directory\n  and must remain physically inside that directory, with an `.html` target,\n  after symbolic links are followed. The durable output/archive profile also\n  conservatively rejects a Windows 8.3 short-name shape such as `PROGRA~1`;\n  descriptive repo/Git POSIX paths use a separate profile and are exempt.\n- Explicit CLI output arguments use the active host's native syntax. They may\n  be relative or absolute, use native separators, and resolve outside the\n  current working directory. On Windows, ordinary drive-absolute, UNC, and\n  relative paths (including ordinary `.` and `..` navigation) are supported.\n  A system-resolved 8.3 spelling of an existing file or directory is accepted\n  when Archify can prove its physical identity; this native alias support does\n  not relax the durable output/archive profile's 8.3-shaped-name rejection.\n  Extended-length paths are limited to raw backslash-only `\\\\?\\C:\\...` and\n  `\\\\?\\UNC\\server\\share\\...` forms without dot segments; device namespaces,\n  malformed roots, drive-relative paths such as `C:file.html`, current-drive\n  roots such as `\\file.html`, alternate data streams, reserved device names,\n  invalid or trailing filename characters, and overlong components fail\n  closed. POSIX CLI paths retain POSIX filename rules rather than inheriting\n  Windows spelling restrictions. Every host rejects NUL, unpaired surrogates,\n  and components that exceed its supported bound.\n\nThese contracts are not interchangeable: an explicit CLI output does not hide\nan invalid durable `meta.output` (including a missing value), and `validate`\nchecks the authored output even when it does not publish to that path. A\nworkflow v1-to-v2 migration may explicitly receive a portable durable\nreplacement through `migrate workflow old.json new.json --to-schema 2 --output\nreports/diagram.html`; that value is written only to its separate verified v2\ndestination. This migration-candidate exception does not repair the source or\nbypass any non-output schema or compiler error. For every other repair, add a\nportable POSIX-relative `.html` path to `meta.output`; no schema-version change\nis otherwise required.\n\nRun `finalize` directly on a complete first candidate and after every repair edit. Its embedded validation checks the candidate before delivery; use standalone `validate` only for focused diagnosis. After an edit, omit any earlier `--candidate-sha256`, which binds the previous candidate. CLI HTML output paths must end in\n`.html`, including after symbolic-link resolution. Compare receipt paths must\nend in `.json`. A type mismatch fails before writing with\n`output/cli-extension` or `output/cli-resolved-extension`. These checks prevent\naccidental file-type overwrites; they do not sandbox explicit CLI directories\nor prevent replacement of an existing artifact of the expected type.\n\nUse final verified delivery only after the candidate is frozen:\n\n```bash\nnode bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality showcase --json\n```\n\nDeliver reads the specification once, writes those exact bytes to a private same-directory candidate snapshot, renders that snapshot, runs the complete artifact checker, and only replaces the target after all artifact checks pass. The JSON receipt includes SHA-256 and byte counts for both `specification` and `artifact`. Deliver adds a required [update notice](update-awareness.md) before running the checker. The hash binds the delivered bytes, and the receipt records `updateNotice`. The dismissible notice uses the top bar on wide Viewer diagrams when the title and toolbar leave space, and the footer otherwise. It includes a one-click copy button for a localized Agent update prompt and the official release notes link. Opening the page and copying the prompt work offline and make zero network requests.\n\nFor the ordinary agent handoff path, prefer the finalizer:\n\n```bash\nnode bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n```\n\n`finalize` invokes verified `deliver` once, reuses its embedded showcase\nvalidation result, then runs strict `check --require-provenance` and\n`browser-check --require-provenance`. It stops at the first failed or skipped stage\nand preserves that stage's full receipt. Its stdout is one compact JSON\nobject with gate statuses, bounded actionable diagnostics, artifact identity,\nand evidence paths. The same compact object is written atomically to\n`<output-stem>.finalize-summary.json`; use that file for normal failure repair. When diagnostics are truncated, `diagnosticSummary.omittedByCode` counts the unshown entries by diagnostic code without replacing their full subject and repair evidence in the full receipt.\nComplete stage receipts and timings remain available for auditing in\n`<output-stem>.finalize.json`. With `--out-dir`, both files are written there (unless an explicit `--receipt` overrides the finalize receipt path; the artifact HTML stays at the requested output path);\n`--receipt <path.json>` overrides the full receipt path and derives a distinct\n`<path>-summary.json`. Read the full receipt only when the compact summary is\ntruncated and its shown subjects and evidence cannot identify a coherent local\nrepair, or when complete audit evidence was explicitly requested. The compact\nreceipt reports `visualReview: \"not-requested\"`; the automated gate does not create images or require a perceptual reviewer. A compact `visualReviewRecommendation` retains positive crossover and route-detour metrics from the strict check so the author can apply the review escalation below without reading the full receipt. A recommendation does not change the machine exit code or claim that review happened. Its `affectedRoutes` identifies crossing pairs and detours (up to eight of each, with a truncation flag); the full strict-check `composition.routeReview` retains all affected relationships. Use these IDs to trace the routes in the captured default viewport. Detours may include `directCorridorBlockers`, identifying nodes between aligned endpoints. These are geometric review clues, not new validation failures or inferred main-path semantics. For a blocked main path or several tangled routes, follow [Architecture layout repair](architecture-layout-repair.md) and reflow the connected scene before tuning individual sides or labels. Preserve every semantic fact; retain unrelated positions only when their surrounding composition is already accepted.\n\nFor a measured automatic Architecture with a large unused leading area, the\ncompact receipt may include `layoutReviewRecommendation`. Its\n`composition.leadingSpace` evidence accounts for nodes, boundary titles,\nroutes and labels. Check whether that space is intentional; if not, reposition\nthe connected scene while preserving meaning and user-fixed geometry, then\nfinalize again. This suggestion changes no gate or exit status and requires\nno screenshot. A fixed canvas or uncertain measurement receives no suggestion.\n\nA passing finalizer receipt is sufficient evidence for all four gates. Merely\nnaming the gates or requiring each one to pass does not require replaying their\nstandalone commands. Replay an individual command only when the request\nexplicitly requires separate executions or focused failure diagnosis needs it.\n\nThe individual commands remain authoritative and backward compatible. Use\nthem directly for focused diagnosis, recovery, or when only one gate is\nrequired. A finalize failure does not relax any gate and does not turn a\npreserved older artifact into a current successful delivery.\n\n`finalize` discovers and starts private Chrome only after delivery and strict\nchecking pass. Failed input, repository-evidence, delivery, or artifact checks\ntherefore do not launch a browser. It loads the artifact only after current\nprovenance is verified. The browser gate retains every viewport, theme, and\nstability check; the browser closes at completion or a browser-stage failure.\nIts full stage receipt records `execution: \"in-process\"` and the equivalent\nstandalone `command` for replay. Chrome startup no longer overlaps the earlier\nstages, so successful runs may take slightly longer. This avoids unnecessary\nstartup on invalid candidates; it does not fix host sandbox restrictions on\nChrome startup or relax a browser gate.\n\nThe pair commit is recoverable, not a claim that two filesystem paths change\natomically or are durable across power loss. Journal finalization is part of\nthat commit: a caught failure while verifying or removing the journal rolls\nback the replaced files when possible and while ownership remains current. If\nownership is lost, the old attempt immediately stops renaming, rolling back,\nfinalizing the journal, recording failure provenance, or cleaning up shared\npaths. Any private staging or recoverable backups remain available and are\nidentified by the failure diagnostic. If restoration fails for another reason,\nthe failure receipt likewise identifies retained backups for recovery. A\nprocess interruption can leave the journal, backups, or private staging behind;\ncheckers then fail closed. Follow the reported recovery evidence before rerunning\n`deliver` serially on the same output. A failed attempt exits non-zero and never invokes an opener; it never\nauthorizes visual evidence collection.\n\nIf exclusive creation succeeds but lock initialization fails, Archify may\nrecord failed provenance and remove the incomplete lock only while its\ncapability still identifies that exact entry. A replacement is preserved.\nFilesystem and cleanup errors are reported separately from an active concurrent\ndelivery. An active, stale, unrecognized, or otherwise preserved lock\nindependently prevents checkers from accepting the prior artifact. Fix the\nreported filesystem error before retrying, and use another physical output\ndirectory if the lock path contains unrelated data.\n\nLock release is part of delivery completion. If the artifact/provenance pair\nhas committed and the journal has finalized but the matching lock cannot be\nremoved, `deliver` exits 1 with `delivery/lock-release`, preserves the lock,\ndoes not print a success receipt, and does not invoke an opener. The preserved\nlock keeps strict checkers fail-closed. Only after pair commit, journal\nfinalization, and lock release all succeed may `deliver` exit zero, print its\nsuccess receipt, or run `--open`.\n\nRun strict `check` after `deliver` exits zero. Run `browser-check` or optional\n`visual-check` only after that strict check exits zero. A failed marker,\nrecovery journal, or delivery lock makes every checker fail before accepting\nthe preserved HTML; report the diagnostics and complete a successful recovery\ndelivery before collecting new browser evidence.\n\nStatic `check` uses the same SVG path analysis for inspected relationships and\nstructural frames. It supports `M/L/H/V/Q/Z`, their lowercase relative forms,\nrepeated parameters, and finite numbers. Each `M` starts an independent subpath;\n`Z` closes only the current subpath. Separate subpaths never create connecting\nsegments that are absent from the drawing. Straight segments separated by a\nnon-collinear `Q` also remain separate in route analysis; curve sample points\ndo not become micro-segments in straight-route budgets or rhythm checks.\nSegment lengths and stretch are measured per continuous piece, while actual\nbends are summed per relationship. A relationship exceeding a budget is counted\nonce, and internal piece boundaries do not receive the short shared-trunk\nexception reserved for semantic endpoints.\n\nThis is not a promise of full SVG command support: `A/C/S/T` produce\n`artifact/svg-path-unsupported`; missing parameters, invalid numbers, and other\nsyntax errors produce `artifact/svg-path-malformed`. The checker exits non-zero\ninstead of skipping a bad path or waiting indefinitely. Path failures append a\n`svg_path_data` check; normal valid artifacts retain the existing nine checks.\nDiagnostics carry the inspected `pathIndex`, `role`, available relationship/frame\n`id`, parsing `tokenOffset`, available `command`, and `reason` so the generating\nsource can be located and repaired. `pathIndex` is one-based; `tokenOffset` is a\nzero-based UTF-16 offset in `d` after numeric character references are decoded.\nApparent tags in comments, CDATA, and attribute text are ignored. Passing static\npath checks does not establish browser or perceptual visual acceptance.\n\n<details>\n<summary>中文说明</summary>\n\n静态 `check` 对受检关系线和结构边界的 SVG 路径使用同一解析结果，支持\n`M/L/H/V/Q/Z` 及其小写相对形式、重复参数和有限数值。每个 `M` 开始独立\n子路径，`Z` 只闭合当前子路径；子路径之间不会被拼接成图中不存在的线段。\n非共线 `Q` 前后的直线也保持分离，不会把曲线采样点计为直线路由预算或\n节奏检查中的微线段。线段长度和伸长率按连续片段测量，真实转弯数汇总到原关系；超预算关系\n只计一次，内部子路径断点不享有语义起终点的短共享线例外。\n这不是完整 SVG 命令集的支持承诺：`A/C/S/T` 返回\n`artifact/svg-path-unsupported`；缺少参数、非法数值等格式错误返回\n`artifact/svg-path-malformed`，检查以非零状态结束，不跳过坏路径或无限等待。\n路径失败时追加 `svg_path_data` 检查；普通有效产物仍保留原来的 9 项检查。\n诊断携带受检路径的 `pathIndex`、`role`、可用的关系/边界 `id`，以及解析位置\n`tokenOffset`、可用的 `command` 和 `reason`，用于定位并修复生成路径的来源。\n`pathIndex` 从 1 开始；`tokenOffset` 是数字字符引用解码后的 `d` 字符串中\n从 0 开始的 UTF-16 位置。注释、CDATA 和属性文本中的伪标签不参与检查。\n静态路径检查通过仍不代表浏览器或感知视觉验收通过。\n\n</details>\n\nThe delivery interface exposes four separate claims:\n\n1. `deliver` proves deterministic artifact checks and byte identity.\n2. `browser-check` collects required automated browser evidence from the exact artifact without capturing images.\n3. `visual-check` optionally adds artifact-bound screenshots and a contact sheet.\n4. Perceptual visual review records a human or image-capable reviewer's judgment.\n\nPassing one claim never implies the others. Never claim that the deterministic receipt includes browser or perceptual review evidence.\n\n## Architecture Diagnosis offer\n\nAfter a passing `finalize architecture` with `--repo-root`, the full receipt\nand compact summary include `codeAnalysisOffer` if a bounded scan finds\nsources eligible for the default analysis. The offer includes the effective\nfinalize `quality`, passes it in `start.argv`, and records a `dependencies`\nstatus of `installed` or `missing`. Finalize performs these checks without\nstarting analysis or installing anything.\n\nEnd the delivery summary with the capability section below, in the user's\nlanguage, once per repository in the task. It is part of the summary, not a\nseparate question, so users learn what Diagnosis does even if they never\nreply. Skip it if the user already asked for or declined analysis in this\ntask. Keep the bullets; adapt only wording, not the claims. If `dependencies`\nis `missing`, the installed Skill copy is incomplete: replace the closing line\nwith the reinstall line, because analysis cannot start. If the offer includes\n`linkedDiagrams: true`, add that sibling-diagram links work from the original\ndelivered diagram, not from the Diagnosis server. Mention the diagram button\nonly when `codeAnalysisOffer.diagramButton` is `true`; otherwise drop that\nsentence. Start only after the user agrees.\n\n**中文**\n\n**还可以：架构诊断**（Archify 自带，在本机运行）\n- **环形星图**：几千个文件、几万个函数之间的依赖一眼看全\n- **可旋转的 3D 模型**：换个角度看模块怎么连在一起\n- **组件问题数**：直接标在这张架构图上，哪里最拥挤、哪里有循环依赖、哪些依赖图里没画\n- 每条发现都能点开看源码，也能一键交给 AI 修\n\n回复「好」我就启动。图右上角的「架构诊断」按钮也随时能看到这个功能。\n（依赖缺失时，最后一句改为：分析组件缺失，需要先重新安装 Archify 才能使用。）\n\n**English**\n\n**Also available: Architecture Diagnosis** (built into Archify, runs locally)\n- **Radial star map**: dependencies across thousands of files and functions at a glance\n- **Rotatable 3D model**: see how modules connect from any angle\n- **Issue counts per component**, right on this diagram: where things are most crowded, where dependencies cycle, and which dependencies the diagram doesn't show\n- Every finding opens its source and can be handed to an AI as a fix task\n\nReply \"yes\" and I'll start it. The **Code Analysis** button at the top right of the diagram shows this anytime.\n(If dependencies are missing, the closing line becomes: The analysis components are missing; reinstall Archify to use it.)\n\nAfter consent, run `start.argv`. Add `--locale zh-CN` for Chinese or\n`--locale en` for English if needed. For a repository with several supported\nlanguages, select the adapter with `--language` as described in the\n[Code Analysis guide](../modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation).\nShare the printed local URL. The original architecture diagram appears first.\nClick **Code Analysis** (**架构诊断** in Chinese) to run analysis and open the\ncomponent findings, radial star map, and Atlas 3D views.\n\n## Comparison presentation changes\n\nArchitecture comparisons include authored `meta.translations` in presentation changes. Adding, removing or editing translations changes `summary.presentationChanged`; reordering translation keys does not. An empty translation object is equivalent to an omitted catalog for presentation classification; the canonical source digest still records the authored representation. Component, relationship, boundary and repository-provenance classifications remain independent.\n\n## Recovering a failed comparison\n\n`compare` commits an HTML artifact and its JSON receipt as a pair. If that commit\nfails, it attempts to restore the previous files. A complete rollback removes\nthe temporary directory as usual.\n\nIf a previous file cannot be restored, compare exits non-zero with\n`delta/commit-rollback-failed` and retains the recovery directory. In the JSON\nfailure receipt, `diagnostics[].evidence.recoveryDirectory` identifies that\ndirectory and `recoveryFiles` lists `{ backup, target }` paths for the files whose\nrestoration failed. Human-readable diagnostics also print the recovery paths.\n\nResolve the filesystem error, inspect the current targets, and restore each\nlisted backup to its corresponding target before retrying. Keep the recovery\ndirectory until both previous files have been recovered and verified; it can\nalso contain rejected candidate files, which must not be mistaken for backups.\nSuccessful comparisons and failures before commit retain their normal cleanup.\n\n## Automated browser evidence\n\n`finalize` runs the required browser gate against the exact trusted HTML without\nrerendering or modifying it. For focused diagnosis, the equivalent standalone\ncommand is:\n\n```bash\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\nThe zero-dependency command uses Chrome/Chromium (or Microsoft Edge)\nthrough the DevTools pipe. `ARCHIFY_CHROME` is authoritative when set, including\nan invalid path: Archify does not silently fall back to another browser. Automatic\nWindows discovery checks every Chrome/Chromium install location and PATH command\nfirst, then Edge under `%ProgramFiles(x86)%`, `%ProgramFiles%`, and `%LocalAppData%`,\nfollowed by `msedge` on PATH. On macOS and Linux, discovery also checks\nChrome/Chromium first, then the Edge application bundle (macOS) and\n`microsoft-edge`/`microsoft-edge-stable` on PATH. It\nmeasures light-theme containment at 1440×900, 1600×1000, 1920×1080, and\n2048×1320, and verifies the requested light theme at all four viewports, the dark\ntheme at both endpoints, and READ/Still runtime states. A requested theme that\nresolves to a different theme fails with measured evidence. It creates one\n`<output-stem>.browser-check.json` receipt and no screenshots or contact sheet.\nPass `--out-dir <dir>` to place the receipt in a separate evidence directory.\nThe receipt binds the artifact SHA-256 and byte count, identifies\n`evidenceKind: \"automated-browser\"`, and reports\n`visualReview: \"not-requested\"`.\n\nHorizontal overflow always fails. Normal document-level vertical scrolling is\naccepted only with a renderer-declared contract and measured readable text.\nAutomatic canvases declare `data-reader-fit=\"intrinsic-height\"` (height fitting)\nor `data-reader-fit=\"width-first\"` (Sequence and Waterfall reading width); their adaptive\nReader must reach its readable width and expose `data-reader-overflow=\"authored\"`.\nArchitecture with an explicit `meta.viewBox` instead declares\n`data-diagram-type=\"architecture\"` and `data-reader-fit=\"authored-height\"`:\nits SVG coordinates, aspect ratio and existing Reader width behavior stay\nunchanged. Its full SVG must remain inside the diagram panel without internal\nscrolling or clipping, and the document must permit vertical scrolling.\nThe receipt records `verticalScrollAccepted: true` and\n`overflowDisposition: \"readable-vertical-scroll\"`. Missing or unknown declarations,\nexplicit viewBoxes in other modes, unreadable text, horizontal overflow,\nclipping and Viewer chrome collisions remain failures. Do not add an internal\ndiagram scroller or hide overflow.\n\n`browser_evidence` in the handoff records only the outcome of this automated\ncommand:\n\n- `passed` maps from exit 0 and receipt `status: \"pass\"` after every required measurement completes and passes.\n- `failed` maps from exit 1 and receipt `status: \"fail\"` when the inspection finds a defect, the command fails, or a runtime error leaves the evidence incomplete.\n- `skipped` maps only from exit 2 and receipt `status: \"skipped\"` when no supported browser is available and the inspection does not run.\n\nRuntime failures leave incomplete evidence and must not be normalized to\n`skipped`. They do not invalidate an already successful deterministic delivery.\nRetry an environmental failure in a browser-capable execution context when\npractical. Keep the packaged transport unchanged unless the failure reproduces\nthrough that seam in a capable environment.\n\nOn Windows, Chrome/Edge startup relaunches can lose the inherited DevTools\npipe before any response arrives. Archify removes a standalone\n`__COMPAT_LAYER=DetectorsAppHealth` from the browser child's environment only\n(case-insensitive name and value); the parent environment, unknown layers,\ncombined layers, and privilege-related compatibility settings are unchanged.\nThis targets the reported non-elevated Git Bash app-health case, not every\nAppCompat mode. Elevated-shell relaunches remain unsupported: rerun from a\nnon-elevated PowerShell opened normally, outside an elevated or compatibility-mode\nparent. Archify does not suppress browser de-elevation or disable the sandbox\nas a relaunch workaround. A zero-response startup diagnostic suggests this\nremedy without claiming that elevation or AppCompat caused every pipe failure.\n\nA provenance failure exits before browser inspection and persists a failed\nbrowser-check receipt bound to the attempted artifact. If the failure receipt\ncannot be written, the diagnostic names that incomplete evidence.\n\nBoth browser commands inspect the exact delivered HTML without modifying or rerendering it.\n\n## Sequence width review\n\nA passing `finalize` may report `layoutReviewRecommendation.action: \"inspect-sequence-width\"`. Its `evidence` measures the fixed participant columns' unused right-hand space after accounting for message labels, notes and segment titles. This advice adds no warning, failure, screenshot requirement or automatic geometry change.\n\nA passing `validate --json`, `deliver`, or `finalize` receipt may carry `diagnostics[]` entries with `severity: \"warning\"` for Viewer locale fallbacks (`i18n/*`). They fail no gate. When the artifact should be fully localized, repair the listed keys from their `evidence` and rerun `finalize`.\n\nSequence canvases with omitted `meta.column_fit` use `spread`, whether or not `meta.viewBox` is supplied. An authored viewBox remains authoritative; infeasible participant capacity fails without silently enlarging it. Explicit `meta.column_fit: \"fixed\"` preserves historical fixed columns. For a candidate whose fixed-column width suggestion remains, first check whether the fixed geometry is intentional. Only when a change to that geometry is authorized, save the candidate, set only `meta.column_fit` to `\"spread\"`, and rerun the complete `finalize` once with `--out-dir <folder>/width-review`. Keep participant order, messages and their y positions, labels, notes, sources and canvas dimensions. If that attempt fails, restore the candidate and finalize it with `--out-dir <folder>/width-restore`; report the remaining layout suggestion rather than iterating. Preserve intentional fixed geometry and disclose the suggestion when a change is not authorized. To retain historical fixed coordinates for an older omitted-fit input, set `meta.column_fit: \"fixed\"` explicitly. This review is about horizontal composition; a passing receipt still does not claim perceptual approval.\n\n## Optional capture evidence\n\n`visual-check` remains backward compatible for a requested or escalated\nperceptual review:\n\n```bash\nnode bin/archify.mjs visual-check <output.html> --summary --require-provenance\n```\n\n`--summary` returns compact JSON with all diagnostics and absolute paths to the complete receipt, contact sheet, and every screenshot. For a chosen visual review, inspect the relevant captures; capture success is not perceptual approval. `--json` retains the full receipt output for existing consumers. Both modes run the same checks and keep the same exit status. If cleanup fails after publication, the summary retains the final failure diagnostics and `publication` recovery details; the linked receipt records the earlier committed evidence.\n\nIt performs the same automated browser measurements, captures light/dark\nscreenshots at 1440×900 and 2048×1320, and writes four viewport PNG sidecars,\none relative-path HTML contact sheet, and one JSON receipt. `--out-dir <dir>` moves all of these sidecars together.\nOpen the HTML contact sheet in a browser or inspect the viewport PNGs with an image reader. Its receipt reports `visualReview: \"pending\"` because captures do not themselves\nmake a perceptual judgment. Capture and provenance failures follow the ownership rules below.\n\nThe receipt, contact sheet, and four PNGs form one owned evidence set. Before\ncapture, `visual-check` freezes every requested directory entry, its\ncanonical write slot and physical parent, and the target's absent/file state,\ntype, device/inode identity, and mode. Hard-linked evidence targets are not safe\nwrite targets. All candidate files are created exclusively inside one random,\nprivate staging directory beneath the physical evidence directory; the receipt\nis published last. Each staged candidate must have exactly one hard-link name\nbefore publication. The no-clobber publish link temporarily gives the staged\nand final names a link count of two; unlinking the verified staged name must\nleave the final entry with a link count of one. An unexpected external hard\nlink fails closed and its alias is never removed.\n\nChrome inspects one identity- and content-checked copy of the captured artifact\nin a private local temporary directory, so browser file loading does not depend\non UNC or long-path support. The six publication candidates remain on the\nevidence volume. Both temporary directories are cleaned without recursively\ndeleting unknown contents; retained entries include their recovery locations.\n\nImmediately before committing anything, `visual-check` re-resolves and verifies\nthe complete six-path set. An absent-path claimant, existing-path replacement,\nsymbolic-link or dangling-link retarget, parent-topology change, hard link, or\nindeterminate identity fails closed with `viewer/evidence-path-conflict`. The\nclaimant and every other final evidence path remain untouched. Cleanup removes\nonly this run's staged or published entries after rechecking their captured\nidentities; a changed or unknown entry is preserved.\n\nAn existing visual evidence set is replaceable only when a regular\n`visual-check` receipt proves ownership of the same artifact and evidence\ndirectory, and its exact sidecar manifest matches every existing contact-sheet\nor PNG byte count and SHA-256 digest. A missing, malformed, unknown, mismatched,\nor incomplete ownership record never authorizes deletion. Failed and skipped\nruns retire prior screenshots/contact sheets only as part of the same verified\ntransaction when that ownership proof succeeds; otherwise they preserve all\nunknown evidence and report `viewer/evidence-path-conflict`.\n\nThis rule also applies when Chrome is unavailable or provenance fails before\nbrowser inspection: neither path may blindly delete stale-looking evidence. A\nverified owned set may be recoverably retired before publishing a skipped or\nfailed receipt; unowned evidence remains intact. These outcomes do not invalidate an already\nsuccessful deterministic delivery and do not turn a perceptual visual review\ninto passed or failed. Retry an environmental failure through the supported\ncommand in a browser-capable execution context when practical. Keep the\npackaged transport unchanged unless the failure reproduces through that seam in\na capable environment.\n\n`browser-check` applies the same private-snapshot, identity, ownership, and no-clobber rules to its single JSON receipt. Its namespace is separate from `visual-check`, so a browser-only rerun cannot remove capture evidence.\n\n## A new candidate at an existing output path\n\nBrowser evidence belongs to exact artifact bytes. After editing a candidate whose previous HTML already has browser evidence, choose a fresh evidence directory before running the next `finalize`; this preserves the old receipts and captures without an avoidable ownership-conflict retry. `--out-dir` relocates the new browser-check receipt and, by default, the finalize receipt and summary. An explicit `--receipt` overrides the finalize receipt path; its summary follows that path. Successful delivery still rewrites the requested HTML and its sibling `*.delivery.json`. Earlier browser or visual evidence remains bound to its original artifact bytes and must not be treated as evidence for changed HTML:\n\n```bash\nnode bin/archify.mjs finalize architecture candidate.json diagram.html --quality showcase --repo-root <root> --out-dir diagram.review-2 --json\nnode bin/archify.mjs visual-check diagram.html --out-dir diagram.review-2 --summary --require-provenance\n```\n\nThe evidence directory is not an archive of the HTML. Copying the HTML there alone does not rebind receipt paths or provenance. If a historical snapshot is needed, preserve the candidate and artifact separately before overwriting them; do not assume copied receipts validate a relocated artifact.\n\nKeep the requested HTML path stable. Use a new revision directory for each changed candidate, and retain the same directory for retries of unchanged bytes. For a diagram without repository evidence, omit `--repo-root`. Let the commands create their output directory. A prior validation failure that produced no HTML or browser evidence needs no new directory. Never remove unknown evidence to make a retry pass.\n\n## Optional opening\n\nAdd `--open` only when the user wants an immediate local preview. It runs after\nthe verified pair commit has completed, its recovery journal has been removed,\nand the delivery lock has been released successfully. It uses one argument-array\nOS opener with a five-second bound on macOS and Linux, and a fifteen-second bound\nfor PowerShell startup on Windows. The receipt records `open.status`; failed or\nunavailable launch attempts also include normalized `open.failure` details.\nKeep it off for CI, unattended agents, and non-interactive environments.\nFailure or unsupported opening does not invalidate delivery; its\nstatus proves only whether the local opener invocation succeeded.\n\n## Last-Good Live Preview\n\nFor an active desktop authoring loop only:\n\n```bash\nnode bin/archify.mjs preview <type> <input>.json <output>.html --quality showcase\n```\n\nPreview watches one explicit input on loopback, binds each stable digest to a private snapshot, and advances only after the existing verified delivery pipeline passes. Invalid, half-written, deleted, or superseded input leaves the previous verified revision on screen and on disk. Identical bytes do not rebuild or reload.\n\nThe preview runtime ships inside the zero-dependency Skill ZIP and must work without `node_modules`.\n\nNever start it by default. Do not use it for CI, unattended agents, remote sharing, or mobile use. `--no-open` is only for a user who will open the printed local URL or for loop testing. Stop it with Ctrl-C before handoff. The first Ctrl-C drains the active delivery without publishing it; a second Ctrl-C forces shutdown of both delivery processes and HTTP connections, including incomplete requests. Shutdown preserves the last verified artifact and removes only staging files whose ownership can be verified. If delivery is interrupted before its receipt reaches Preview, unconfirmed files and recovery material may remain in the private staging directory; shutdown does not recursively delete unknown contents. Server state, port, source path, diagnostics, error text, and reload tokens must never enter the generated artifact or any export.\n\n## Per"},"items":[{"name":"DESIGN.md","path":"DESIGN.md","rawUrl":"https://raw.githubusercontent.com/tt-a1i/archify/HEAD/DESIGN.md","title":"Archify","category":"project-spec","format":"markdown","content":"---\nname: Archify\ndescription: A precise, vivid technical instrument for trustworthy interactive architecture maps.\ncolors:\n  canvas: \"#020617\"\n  mask: \"#0F172A\"\n  ink: \"#FFFFFF\"\n  muted: \"#94A3B8\"\n  dim: \"#475569\"\n  border: \"#1E293B\"\n  frontend: \"#22D3EE\"\n  backend: \"#34D399\"\n  database: \"#A78BFA\"\n  cloud: \"#FBBF24\"\n  security: \"#FB7185\"\n  messagebus: \"#FB923C\"\n  external: \"#94A3B8\"\ntypography:\n  headline:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"1.5rem\"\n    fontWeight: 700\n    lineHeight: 1.2\n    letterSpacing: \"-0.025em\"\n  title:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.875rem\"\n    fontWeight: 600\n    lineHeight: 1.4\n    letterSpacing: \"normal\"\n  body:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.75rem\"\n    fontWeight: 400\n    lineHeight: 1.55\n    letterSpacing: \"normal\"\n  label:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.625rem\"\n    fontWeight: 700\n    lineHeight: 1.35\n    letterSpacing: \"0.12em\"\nrounded:\n  precise: \"0.2rem\"\n  control: \"0.5rem\"\n  panel: \"1rem\"\n  pill: \"999px\"\nspacing:\n  xs: \"0.25rem\"\n  sm: \"0.5rem\"\n  md: \"0.75rem\"\n  lg: \"1rem\"\n  xl: \"1.5rem\"\n  page: \"2rem\"\ncomponents:\n  toolbar-button:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.5rem 0.875rem\"\n    height: \"2.75rem\"\n  diagram-panel:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    rounded: \"{rounded.panel}\"\n    padding: \"1.5rem\"\n  search-field:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.58rem 0.65rem\"\n  evidence-beacon:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.backend}\"\n    typography: \"{typography.label}\"\n    rounded: \"{rounded.pill}\"\n    size: \"30px × 12px\"\n---\n\n# Design System: Archify\n\n## Overview\n\n**Creative North Star: \"The Evidence Console\"**\n\nArchify is a composed technical instrument, not a drawing suite. The canvas carries one spatial narrative; restrained controls and progressive disclosure let a reader move from the primary path to exact authored relationships, metadata, and verified code evidence without losing orientation.\n\nThe visual system is precise, dark-first, and vivid only where semantics earn it. Light mode and Blueprint preserve the same vocabulary rather than becoming separate products. Motion has one bounded owner, finishes, and never carries meaning that disappears in a still frame. Desktop is the primary surface; narrow screens receive containment, not a second interface.\n\n**Key Characteristics:**\n\n- One dominant technical canvas with compact, low-interference chrome.\n- A fixed semantic color vocabulary shared by nodes, edges, legends, focus, and evidence.\n- Mono-forward typography, small labels, and deliberate density for engineering review.\n- Viewer state stays outside canonical exports; proof remains portable and deterministic.\n- State transitions are 140–200ms; authored story motion may be longer but finite and reader-controlled.\n\n## Colors\n\nThe palette is a midnight console with seven semantic signals; color identifies meaning, never decoration.\n\n### Primary\n\n- **Verified Cyan** (`frontend`): the main focus, navigation, and frontend signal. Its scarcity establishes hierarchy.\n\n### Secondary\n\n- **Proof Green** (`backend`): backend semantics, verified evidence, and successful state.\n- **Repository Violet** (`database`): persisted state, stores, and inward relationships.\n\n### Tertiary\n\n- **Boundary Rose** (`security`): policy, security, and guarded paths.\n- **Cloud Amber** (`cloud`), **Transit Orange** (`messagebus`), and **External Slate** (`external`): stable semantic categories, never interchangeable accents.\n\n### Neutral\n\n- **Midnight Canvas** (`canvas`) and **Ink Mask** (`mask`): the dark workspace and opaque geometry mask.\n- **Instrument Ink** (`ink`), **Quiet Copy** (`muted`), **Dim Annotation** (`dim`), and **Structural Border** (`border`): the text and containment ladder.\n\n### Named Rules\n\n**The Semantic Color Rule.** Every saturated color maps to a node or relationship meaning; never add an accent merely to make a surface lively.\n\n**The Theme Parity Rule.** Light, dark, Signal Flow, and Blueprint may change material and contrast, but must preserve category identity and information priority.\n\n## Typography\n\n**Display Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Body Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Label/Mono Font:** JetBrains Mono\n\n**Character:** A single mono family makes the artifact feel authored by an engineering instrument. Hierarchy comes from weight, scale, spacing, and case rather than a decorative display face.\n\n### Hierarchy\n\n- **Headline** (700, `1.5rem`, 1.2): artifact title only.\n- **Title** (600, `0.875rem`, 1.4): panels, cards, and selected semantic objects.\n- **Body** (400, `0.75rem`, 1.55): explanatory copy and relationship details.\n- **Label** (700, `0.625rem`, `0.12em`, uppercase): state, modes, metadata, and compact proof markers.\n\n### Named Rules\n\n**The One Voice Rule.** UI and diagram chrome remain mono-forward; never introduce a display font inside the generated artifact.\n\n**The Legibility Floor Rule.** Tiny labels are metadata, not prose. If a reader must parse a sentence, promote it to body size or disclose it on focus.\n\n## Elevation\n\nArchify is flat and tonal by default. Borders and surface contrast establish structure; shadows appear only on floating controls, temporary panels, active focus, or the Signal Flow atmosphere. Blueprint removes glow and squares materials to keep the review surface exact.\n\n### Shadow Vocabulary\n\n- **Canvas Lift** (`0 28px 80px rgba(0,0,0,0.34)`): Signal Flow diagram surface only.\n- **Floating Panel** (`0 18px 48px rgba(0,0,0,0.30)`): temporary discovery panels and the Semantic Passport.\n- **Action Feedback** (`0 0 7px var(--frontend-stroke)`): active SVG focus only, never an idle decoration.\n\n### Named Rules\n\n**The Flat-at-Rest Rule.** A static card or control uses border and tone; a shadow must explain layering or state.\n\n**The Canonical Clean Rule.** Viewer glow, overlays, focus, and temporary marks are removed from visual exports unless the export explicitly owns that narrative.\n\n## Components\n\n### Buttons\n\n- **Shape:** compact rounded rectangle (`0.5rem`), or precise corners (`0.2rem`) in Blueprint.\n- **Primary:** translucent toolbar material, one-pixel structural border, and mono body label. Desktop viewer chrome may use compact 32px controls; touch and narrow-screen targets stay at least `2.75rem` high.\n- **Hover / Focus:** 150ms border/background response; `2px` cyan focus ring with `2px` offset.\n- **Secondary / Ghost:** transparent within menus; never add a second saturated fill hierarchy.\n\n### Chips\n\n- **Style:** quiet bordered capsules for semantic metadata; selected state uses the owning semantic color.\n- **State:** a chip may summarize focus, mode, count, or evidence, but must not become an unlabeled icon-only control.\n\n### Cards / Containers\n\n- **Corner Style:** composed panel corners (`1rem`), reduced to `0.35rem` in Blueprint.\n- **Background:** tonal panel over the canvas, with a one-pixel border.\n- **Shadow Strategy:** flat by default; floating or Signal Flow surfaces use the elevation vocabulary.\n- **Internal Padding:** `1.25rem`–`1.5rem` for panels; compact proof blocks may use `0.5rem`–`0.75rem`.\n\n### Inputs / Fields\n\n- **Style:** one continuous bordered field, `0.5rem` corners, muted placeholder, and compact mono body text.\n- **Focus:** no browser outline; shift the border to Verified Cyan and add a restrained two-pixel halo.\n- **Error / Disabled:** preserve readable text and add a non-color cue; never rely on opacity alone for failure.\n\n### Navigation\n\n- **Style:** the diagram remains dominant. Toolbar, guided views, map, search, and passport appear only when relevant and reuse familiar labels.\n- **Default / Hover / Active:** 140–200ms state response; active state combines text, border, shape, or marker—not color alone.\n- **Narrow screens:** contain and stack existing controls safely; do not create a dedicated mobile product surface.\n\n### Semantic Passport\n\nOne focused node opens one compact proof surface containing stable ID, authored metadata, relationships, and optional revision-pinned sources. It is the single destination for details; new capabilities should route here before proposing another panel.\n\n### Verified Source Beacon\n\nAn evidence-backed node receives one viewer-only `SRC n` capsule in its upper-right corner. It inherits node state, adds no tab stop, and is stripped from every canonical visual export.\n\n### Brand Mark\n\nAn authored `brand` adds one compact identity badge to the upper-right of the\nnode. Built-in vectors and explicitly captured, digest-pinned site icons sit on a neutral plate;\ntheir color stays inside that plate and never recolors the semantic node, edge,\nlegend, focus, or evidence vocabulary. The semantic sigil remains visible. A\nVerified Source Beacon shifts left when both facts are present. Brand marks are\ncanonical authored SVG content and therefore survive visual export.\n\n### Authored Reachability\n\nSemantic Passport offers two native, count-bearing actions: `Upstream` follows authored incoming relationships and `Downstream` follows authored outgoing relationships. The canvas keeps the focused origin plus the complete reachable subgraph strong while unrelated topology recedes. Upstream uses Repository Violet, downstream uses Proof Green, and Blueprint removes glow. The receipt says nodes, links, and maximum hops; it never says blast radius or breakage.\n\n### Reach Share Card\n\nAn active reach query may expose one contextual **Export → Reach Share Card** item. The 1200×630 card keeps the full diagram as quiet context, preserves the selected origin and every matched authored node and link, and writes direction, origin, node count, link count, and maximum hops into the card header. Upstream retains Repository Violet; downstream retains Proof Green; Blueprint stays filter-free. The card is an explicit non-canonical reading variant, not runtime impact, causality, or breakage evidence. No animated state, live focus glow, camera transform, or unrelated viewer chrome enters the clone.\n\n## Do's and Don'ts\n\n### Do:\n\n- **Do** make the primary path legible before adding secondary relationships or detail.\n- **Do** derive every focus, reachability query, route, story, source link, receipt, and count from authored or locally verified evidence.\n- **Do** keep ordinary artifacts source-free and make repository evidence explicitly opt-in.\n- **Do** use 140–200ms transitions for control state and honor `prefers-reduced-motion`.\n- **Do** preserve keyboard access, visible focus, semantic labels, dark/light parity, and non-color state cues.\n- **Do** keep runtime exploration outside canonical SVG, raster, Share Card, and WebM backgrounds.\n- **Do** name an intentionally scoped Route or Reach Share Card in its header and machine-readable receipt.\n\n### Don't:\n\n- **Don't** build generic Mermaid beautifiers that change themes without improving information architecture.\n- **Don't** turn Archify into WYSIWYG drawing suites whose editing chrome becomes the product.\n- **Don't** ship motion-first graph demos that imply relationships or activity not present in the authored source.\n- **Don't** use dense dashboard shells, endless identical card grids, decorative glass, gradient text, and other AI-generated interface clichés.\n- **Don't** infer identity from arbitrary label text, add an unbounded icon marketplace, or let a brand badge replace the portable semantic vocabulary.\n- **Don't** create another permanent panel when the Semantic Passport, Node Finder, or existing canvas can carry the capability.\n- **Don't** call graph reachability runtime impact, blast radius, or breakage without independent code-analysis evidence.\n- **Don't** change the README Hero as a side effect of artifact or viewer iteration.\n","frontmatter":{"name":"Archify","description":"A precise, vivid technical instrument for trustworthy interactive architecture maps.","colors":{"canvas":"#020617","mask":"#0F172A","ink":"#FFFFFF","muted":"#94A3B8","dim":"#475569","border":"#1E293B","frontend":"#22D3EE","backend":"#34D399","database":"#A78BFA","cloud":"#FBBF24","security":"#FB7185","messagebus":"#FB923C","external":"#94A3B8"},"typography":{"headline":{"fontFamily":"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace","fontSize":"1.5rem","fontWeight":700,"lineHeight":1.2,"letterSpacing":"-0.025em"},"title":{"fontFamily":"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace","fontSize":"0.875rem","fontWeight":600,"lineHeight":1.4,"letterSpacing":"normal"},"body":{"fontFamily":"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace","fontSize":"0.75rem","fontWeight":400,"lineHeight":1.55,"letterSpacing":"normal"},"label":{"fontFamily":"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace","fontSize":"0.625rem","fontWeight":700,"lineHeight":1.35,"letterSpacing":"0.12em"}},"rounded":{"precise":"0.2rem","control":"0.5rem","panel":"1rem","pill":"999px"},"spacing":{"xs":"0.25rem","sm":"0.5rem","md":"0.75rem","lg":"1rem","xl":"1.5rem","page":"2rem"},"components":{"toolbar-button":{"backgroundColor":"{colors.mask}","textColor":"{colors.ink}","typography":"{typography.body}","rounded":"{rounded.control}","padding":"0.5rem 0.875rem","height":"2.75rem"},"diagram-panel":{"backgroundColor":"{colors.mask}","textColor":"{colors.ink}","rounded":"{rounded.panel}","padding":"1.5rem"},"search-field":{"backgroundColor":"{colors.mask}","textColor":"{colors.ink}","typography":"{typography.body}","rounded":"{rounded.control}","padding":"0.58rem 0.65rem"},"evidence-beacon":{"backgroundColor":"{colors.mask}","textColor":"{colors.backend}","typography":"{typography.label}","rounded":"{rounded.pill}","size":"30px × 12px"}}},"isInternal":false,"tokens":2821,"sizeBytes":12286},{"name":"delivery-contract.md","path":"archify/references/delivery-contract.md","rawUrl":"https://raw.githubusercontent.com/tt-a1i/archify/HEAD/archify/references/delivery-contract.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# Delivery contract\n\n## Failed finalize and candidate repair\n\n`finalize` stops at the first non-passing gate. Use compact stdout or `evidence.summaryReceipt`; read its full sidecar only when the summary lacks evidence needed for a coherent repair. A receipt with four artifact checks is basic validation, not showcase acceptance: require all nine checks, zero composition errors, and zero warnings. Fix `meta.quality_profile` and schema errors before geometry. A dense full-schema ERD may keep `standard` for its first complete-field pass: require zero structural errors, no edge-through-node failures, complete field rows, and a readable grouped grid, and record composition warnings instead of spending unbounded time on them.\n\nWhen every diagnostic from the first embedded validation is\n`repository-evidence/line-out-of-range`, `finalize` may narrow an existing\ncitation's `end_line` to the last line of its pinned file and retry the complete\ngates once. The start line must already exist in that nonempty file; the source\npath, revision, start, and all other authored content stay unchanged. Automatic\nrepair requires the original bytes to match `JSON.stringify(parsed, null, 2)`\nplus one LF exactly. Other formatting, a BOM, CRLF, or number spellings that\nwould change on parsing and serialization require author repair, so reserialization\ncannot change unrelated bytes or numeric precision. Missing files, invalid starts,\nand mixed failures also require author repair. This only bounds\nthe cited range; it does not establish or correct the cited fact. `autoRepair`\nrecords the changed ranges and original/repaired hashes in both receipts. A\npassing retry keeps the repaired candidate. Any later failure or exception\nattempts a byte-for-byte restore, guarded by the repaired candidate's identity\nand bytes, and invalidates only that retry's current-delivery sidecar. External\nedits are preserved and a returned receipt reports `restore-failed` if recovery\ncannot safely complete. Failure diagnostics and `specification` describe the\nchecked retry; `autoRepair.outcome` states whether the original was restored.\nThrown exceptions remain command failures and may leave the last persisted\nreceipt at an earlier stage; only a completed passing command is a handoff.\n\nFor a validation failure, edit the existing JSON in the connected neighborhood named by diagnostics before rerunning a command. Preserve requested semantics, meaningful labels, source evidence, and fixed or agreed topology. Several routes sharing nodes call for one placement repair; read [Architecture layout repair](architecture-layout-repair.md) for that case. Reflow a blocked main path rather than nudging unrelated labels. Keep unrelated geometry when its composition already reads clearly. Use `--layout-json` before editing only when compact evidence lacks needed measurements. Workflow v2 uses its stable compiler receipt, not solver internals, as authoring evidence.\n\nKeep the best candidate that cleared route checks before a viewport repair. If that repair introduces new route collisions, restore the measured layout and address its remaining canvas or text constraint.\n\nAfter the edit, rerun the complete `finalize` command with `--quality showcase` and, for repository-backed work, `--repo-root <repo-root>`. If the output path already has browser evidence from another candidate, use a fresh `--out-dir <output-stem>.review-<revision>` for both the new `finalize` and any `visual-check`. Omit an earlier `--candidate-sha256` after editing because it binds the previous candidate. Compare diagnostics by code, subject, stage, and evidence, never by declining error count alone. Track the repair limit per persistent issue, using that code, subject, stage, and evidence: a newly exposed issue starts its own repair sequence. If an issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, report the concrete gap.\n\nUse standalone `validate` only for focused diagnosis, passing `--repo-root` for repository-backed work. Its passing receipt marks `candidateFrozen: true`; run `nextAction.arguments`, replacing only `<output.html>`, without editing, revalidating, or rereading the candidate. Retry later environmental or evidence failures against those frozen bytes. A measured reason to edit creates a new candidate and calls for the complete `finalize` without the old hash.\n\n## Validate and deliver\n\n`render` and direct renderer entry points print classified authoring failures\nto stderr as readable diagnostics and exit 1. Input read/JSON parse failures\nuse `input/read` or `input/json-parse`; output filesystem failures use\n`output/write` and identify the output path. Schema and layout failures keep\ntheir existing rule codes. Use the advertised `validate --json` or\n`deliver --json` interface for a machine receipt; `render` has no `--json` flag.\nUnexpected implementation failures retain debugging information in human\nmode and remain `internal/unclassified` in machine receipts.\n\nDeclared local Explainer chart data and native-diagram specification files are protected inputs, including physical aliases. Delivery and finalize refuse sidecars that would overwrite those inputs, including when resource preparation fails; an uninspectable draft cannot publish failure evidence.\n\nEach delivered output has two artifact-specific metadata paths. When an output\nstem is too long for those derived filenames, Archify shortens it and appends a\nstable hash:\n\n- `<output-stem>.delivery.json` records the latest completed attempt.\n- `<output-stem>.delivery-pending.json` is the recovery journal for an attempt\n  in progress.\n\nFor a literal artifact stem that already matches Archify's reserved bounded-name\nmarker, a pre-namespace raw provenance sidecar remains a read fallback when the\nencoded sidecar is absent. A pre-namespace raw pending journal is an independent\nfail-closed barrier: it blocks checks and redelivery even when an encoded pending\njournal also exists, and neither journal is silently replaced.\n\nOne directory-wide `.archify-delivery-lock.json` serializes every delivery that\nresolves into the same physical output directory. This deliberately prevents\ncase, Unicode-normalization, Windows short-name, and symbolic-link aliases from\ncreating independent owners for one filesystem location. The tradeoff is that\ndeliveries to different artifact names in one directory also run serially;\nprovenance and pending journals remain artifact-specific.\n\nFor migration safety, Archify also detects and preserves a legacy\n`<output-stem>.delivery-lock.json` beside the requested artifact. An existing\nlegacy entry is a fail-closed recovery barrier. While a new delivery owns the\ndirectory mutex, it also holds temporary legacy-format fences for the requested\nspelling and an existing artifact's physical target spelling. It acquires the\ndirectory lock first, then all required compatibility fences before writing a\njournal or artifact, and removes the directory lock before those fences during\nrelease. This blocks an older Archify binary using\neither known spelling from entering the delivery. A legacy fence whose raw\nHEAD-era filename exceeds the host component limit is omitted because the old\nbinary could not create that lock or deliver that artifact on the host either.\n\n`deliver` acquires the lock by exclusive `open(..., \"wx\")` before creating or\nreplacing the recovery journal. A successful exclusive create yields an\ninternal opaque ownership capability bound to that attempt. Journal creation,\nfailed-provenance recording, pair commit, rollback, journal finalization, and\nlock release each verify the current capability inside the operation that\nwould mutate shared state. A rejected contender does not create a journal or\nwrite failed provenance.\n\nAn existing directory or legacy lock is handled without automatic recovery:\n\n| Observed lock state | Required `deliver` result |\n| --- | --- |\n| No directory entry | Attempt exclusive creation; only its success grants ownership. |\n| Valid schema-v1 lock whose PID is running, or whose death cannot be established | Exit 1 with `delivery/concurrent-attempt`; preserve every shared path. |\n| Valid schema-v1 lock whose PID is known to have exited | Exit 1 with `delivery/lock-stale`; preserve the lock, artifact, journal, and current provenance exactly. |\n| Unreadable, malformed, symlink, dangling symlink, directory, or other non-regular lock entry | Exit 1 with `delivery/lock-invalid`; preserve the entry and every other shared path. |\n| An acquired capability no longer matches the current lock or journal | Exit 1 with `delivery/ownership-lost`; stop all shared-path mutation. |\n| The matching owner cannot remove its lock | Exit 1 with `delivery/lock-release`; preserve the lock. |\n\nA `delivery/lock-stale` diagnostic identifies the absolute output and lock\npaths plus the original PID and receipt ID. Recovery is deliberately explicit\nand serial: stop all delivery attempts for that physical output directory,\nconfirm that no active delivery owns it and that the reported stale entry has\nnot been replaced, remove only the reported lock, then rerun `deliver`. Do not\nremove an artifact, current provenance, or pending journal as part of\nstale-lock recovery.\n\nThe lock protocol targets Node.js 18 or later on a local filesystem with\ncooperating Archify processes. PID, receipt, and file-identity comparisons are\ndefensive checks, not an atomic compare-and-swap. Compatibility fences cover\nthe requested spelling and an existing physical-target spelling; they cannot\nenumerate arbitrary hard-link names or previously unknown filesystem aliases,\nso mixed-version delivery through such aliases remains out of scope. This\ncontract does not claim distributed-lock correctness on NFS, SMB, or other\nnetwork filesystems, and it cannot prevent an external process that ignores\nthe protocol from replacing shared paths.\n\nEvery no-clobber HTML publisher (`render`, `deliver`, `compare`, and `preview`)\ncaptures the requested directory entry, canonical write slot, physical parent,\nand existing target type, device/inode identity, and mode before staging, then\nrevalidates that snapshot immediately before replacement. An existing write\ntarget must be a regular file with exactly one hard-link name. A target with\nmultiple hard-link names fails closed with `output/target-hardlinked`: replacing\nthe requested name cannot update unknown sibling names as one publication.\nHard links remain supported for read identity and input/alias collision checks;\nthey are unsupported only as write targets. A symbolic link to a single-link regular\nfile remains supported: publication preserves the symbolic-link entry and\napplies the same protocol to its resolved target. Directory, FIFO, socket,\ndevice, changing mode, new claimant, and indeterminate identity cases fail\nbefore replacement.\n\nPublication is no-clobber and recoverable, not crash-atomic replacement of an\nexisting target. To avoid overwriting a claimant that appears after the last\nidentity check, Archify first retains the bound old file in a private recovery\nbackup, removes the public name through identity-bound quarantine, and then\ncreates the new public name with an exclusive hard link. A caught failure rolls\nback when the public slot and recovery binding still permit it. A process\ninterruption between those namespace operations can instead leave the public\npath absent while the verified previous bytes remain in an adjacent private\nrecovery backup. Single-artifact publication records the original slot/alias\nidentity and backup inode, mode, SHA-256, and byte count in private\n`.archify-remove-*/publication-recovery-v1.json`, beside `previous`. To make a\nspecific interrupted publication visible again, stop concurrent writers and run:\n\n```bash\nnode bin/recover-output.mjs /absolute/path/to/.archify-remove-<id> --json\n```\n\nThis is explicit recovery, not a directory scanner. Before linking, the helper\nchecks for a changed parent or alias, an altered/hardlinked record or backup,\ndigest or inode mismatch, and any existing public target. It restores only by\nno-clobber hard link, so a new claimant is preserved rather than overwritten;\nit never recursively removes unknown entries. A completed recovery is\nidempotent. The record is evidence to be independently verified, not an\nauthority to restore arbitrary private bytes: the helper accepts it only from\nthe recorded generated child of the original physical target parent, with the\nsame directory identity. Name the exact directory reported by the interrupted\nprocess and inspect an uncertain record manually. A non-cooperating process can\nstill swap pathnames after those checks and before Node.js `linkSync`; Node does\nnot expose a descriptor-bound link operation. Post-link identity verification\nthen fails closed and retains recovery evidence, rather than claiming recovery\nor deleting an uncertain name. If recovery itself is interrupted after the\nlink, the old public bytes and private backup can both remain; a later recovery\nrun preserves the public target and needs explicit operator resolution. The\nrecord is fsynced before the old public name is retired on platforms supporting\ndirectory sync, and the tested guarantee is recovery after a killed process;\nthis is not a claim of power-loss, storage-controller, NFS, or SMB durability.\nPaired flows retain their backup in private transaction staging. For `deliver`,\nthe pending journal and lock keep strict checkers fail-closed. The portable\nNode.js filesystem API has no pathname\ncompare-and-swap that both replaces an existing name atomically and refuses to\noverwrite a late claimant: `rename` would close the visibility gap only by\noverwriting that claimant.\n\nAfter ownership is established, `deliver` creates the journal before rendering\nand keeps it through the recoverable HTML/sidecar pair commit. It removes the\njournal only after that commit completes. A validation, render, or pair-commit\nfailure, or a process interruption, may therefore leave a journal. The journal\nis a safety barrier: `check`, `browser-check`, and `visual-check` fail closed when any directory\nentry exists at the journal or lock path, including an unreadable file,\nsymlink, or dangling symlink. Run deliveries targeting the same physical output\ndirectory serially; one attempt must finish or be recovered before another\nbegins.\n\nA successful sidecar has `schemaVersion: 1`, `status: \"current\"`,\n`command: \"deliver\"`, a unique `receiptId`, the diagram `type`, an absolute\n`input` path, an absolute `output` path matching the inspected\nartifact, and specification/artifact SHA-256 and byte counts. Checkers treat a\nmissing, malformed, unsupported, or inconsistent field as invalid. They also\nreject a sidecar symlink, including a dangling one. A checker binds provenance\nto the artifact bytes it actually checks and verifies that binding again before\nreporting success; a concurrent byte change fails. The provenance directory\nentry itself must be a single-link regular file: `deliver` and strict check fail\nclosed with `delivery/provenance-hardlink-unsupported` when it has another hard\nlink, without scanning for or guessing the sibling name.\n\nIf a currently verified owner fails after an older HTML exists, Archify writes\na new `status: \"failed\"` sidecar and leaves the journal until recovery is\ncomplete. An unreadable old HTML does not prevent that marker; its artifact hash\nand byte count may be absent. If the sidecar is locked or otherwise unwritable,\nArchify keeps the prior sidecar rather than deleting evidence, and the journal\nprevents checkers from trusting it. A rejected concurrent, stale, or invalid\nlock attempt does not write failed provenance. If ownership is lost, Archify\nreports `delivery/ownership-lost`, does not overwrite or remove the successor's\nartifact, provenance, journal, or lock, and does not claim recorded failed\nprovenance; a failure receipt may report `provenance: \"unrecorded\"`. If every\nmetadata path is unavailable, the same unrecorded status applies; no tool can\npreserve that fact across processes. Restore metadata-path access and complete\na successful `deliver` before trusting the output.\n\nArtifacts with no sidecar, journal, or lock remain supported for backward\ncompatibility and for the lower-level `render` command. Their checker receipts\nreport `provenance: \"unknown\"`; use `--require-provenance` to turn that state\ninto a non-zero failure when the workflow requires a successfully delivered\nartifact:\n\n```bash\nnode bin/archify.mjs check <output.html> --require-provenance\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\n## Output path contracts\n\nArchify intentionally separates durable authored paths from command-line paths:\n\n- Required authored `meta.output` is a portable POSIX-relative path such as\n  `reports/diagram.html`. It uses `/`, ends in a non-empty `.html` basename,\n  and cannot contain an absolute or drive-relative prefix, URI, backslash,\n  empty or dot segment, control character, unpaired UTF-16 surrogate, Windows\n  alternate-data-stream separator or invalid filename character, trailing dot\n  or space, DOS device name, or a component over either the 255-byte UTF-8 or\n  255-code-unit UTF-16 limit. It resolves from the current working directory\n  and must remain physically inside that directory, with an `.html` target,\n  after symbolic links are followed. The durable output/archive profile also\n  conservatively rejects a Windows 8.3 short-name shape such as `PROGRA~1`;\n  descriptive repo/Git POSIX paths use a separate profile and are exempt.\n- Explicit CLI output arguments use the active host's native syntax. They may\n  be relative or absolute, use native separators, and resolve outside the\n  current working directory. On Windows, ordinary drive-absolute, UNC, and\n  relative paths (including ordinary `.` and `..` navigation) are supported.\n  A system-resolved 8.3 spelling of an existing file or directory is accepted\n  when Archify can prove its physical identity; this native alias support does\n  not relax the durable output/archive profile's 8.3-shaped-name rejection.\n  Extended-length paths are limited to raw backslash-only `\\\\?\\C:\\...` and\n  `\\\\?\\UNC\\server\\share\\...` forms without dot segments; device namespaces,\n  malformed roots, drive-relative paths such as `C:file.html`, current-drive\n  roots such as `\\file.html`, alternate data streams, reserved device names,\n  invalid or trailing filename characters, and overlong components fail\n  closed. POSIX CLI paths retain POSIX filename rules rather than inheriting\n  Windows spelling restrictions. Every host rejects NUL, unpaired surrogates,\n  and components that exceed its supported bound.\n\nThese contracts are not interchangeable: an explicit CLI output does not hide\nan invalid durable `meta.output` (including a missing value), and `validate`\nchecks the authored output even when it does not publish to that path. A\nworkflow v1-to-v2 migration may explicitly receive a portable durable\nreplacement through `migrate workflow old.json new.json --to-schema 2 --output\nreports/diagram.html`; that value is written only to its separate verified v2\ndestination. This migration-candidate exception does not repair the source or\nbypass any non-output schema or compiler error. For every other repair, add a\nportable POSIX-relative `.html` path to `meta.output`; no schema-version change\nis otherwise required.\n\nRun `finalize` directly on a complete first candidate and after every repair edit. Its embedded validation checks the candidate before delivery; use standalone `validate` only for focused diagnosis. After an edit, omit any earlier `--candidate-sha256`, which binds the previous candidate. CLI HTML output paths must end in\n`.html`, including after symbolic-link resolution. Compare receipt paths must\nend in `.json`. A type mismatch fails before writing with\n`output/cli-extension` or `output/cli-resolved-extension`. These checks prevent\naccidental file-type overwrites; they do not sandbox explicit CLI directories\nor prevent replacement of an existing artifact of the expected type.\n\nUse final verified delivery only after the candidate is frozen:\n\n```bash\nnode bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality showcase --json\n```\n\nDeliver reads the specification once, writes those exact bytes to a private same-directory candidate snapshot, renders that snapshot, runs the complete artifact checker, and only replaces the target after all artifact checks pass. The JSON receipt includes SHA-256 and byte counts for both `specification` and `artifact`. Deliver adds a required [update notice](update-awareness.md) before running the checker. The hash binds the delivered bytes, and the receipt records `updateNotice`. The dismissible notice uses the top bar on wide Viewer diagrams when the title and toolbar leave space, and the footer otherwise. It includes a one-click copy button for a localized Agent update prompt and the official release notes link. Opening the page and copying the prompt work offline and make zero network requests.\n\nFor the ordinary agent handoff path, prefer the finalizer:\n\n```bash\nnode bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n```\n\n`finalize` invokes verified `deliver` once, reuses its embedded showcase\nvalidation result, then runs strict `check --require-provenance` and\n`browser-check --require-provenance`. It stops at the first failed or skipped stage\nand preserves that stage's full receipt. Its stdout is one compact JSON\nobject with gate statuses, bounded actionable diagnostics, artifact identity,\nand evidence paths. The same compact object is written atomically to\n`<output-stem>.finalize-summary.json`; use that file for normal failure repair. When diagnostics are truncated, `diagnosticSummary.omittedByCode` counts the unshown entries by diagnostic code without replacing their full subject and repair evidence in the full receipt.\nComplete stage receipts and timings remain available for auditing in\n`<output-stem>.finalize.json`. With `--out-dir`, both files are written there (unless an explicit `--receipt` overrides the finalize receipt path; the artifact HTML stays at the requested output path);\n`--receipt <path.json>` overrides the full receipt path and derives a distinct\n`<path>-summary.json`. Read the full receipt only when the compact summary is\ntruncated and its shown subjects and evidence cannot identify a coherent local\nrepair, or when complete audit evidence was explicitly requested. The compact\nreceipt reports `visualReview: \"not-requested\"`; the automated gate does not create images or require a perceptual reviewer. A compact `visualReviewRecommendation` retains positive crossover and route-detour metrics from the strict check so the author can apply the review escalation below without reading the full receipt. A recommendation does not change the machine exit code or claim that review happened. Its `affectedRoutes` identifies crossing pairs and detours (up to eight of each, with a truncation flag); the full strict-check `composition.routeReview` retains all affected relationships. Use these IDs to trace the routes in the captured default viewport. Detours may include `directCorridorBlockers`, identifying nodes between aligned endpoints. These are geometric review clues, not new validation failures or inferred main-path semantics. For a blocked main path or several tangled routes, follow [Architecture layout repair](architecture-layout-repair.md) and reflow the connected scene before tuning individual sides or labels. Preserve every semantic fact; retain unrelated positions only when their surrounding composition is already accepted.\n\nFor a measured automatic Architecture with a large unused leading area, the\ncompact receipt may include `layoutReviewRecommendation`. Its\n`composition.leadingSpace` evidence accounts for nodes, boundary titles,\nroutes and labels. Check whether that space is intentional; if not, reposition\nthe connected scene while preserving meaning and user-fixed geometry, then\nfinalize again. This suggestion changes no gate or exit status and requires\nno screenshot. A fixed canvas or uncertain measurement receives no suggestion.\n\nA passing finalizer receipt is sufficient evidence for all four gates. Merely\nnaming the gates or requiring each one to pass does not require replaying their\nstandalone commands. Replay an individual command only when the request\nexplicitly requires separate executions or focused failure diagnosis needs it.\n\nThe individual commands remain authoritative and backward compatible. Use\nthem directly for focused diagnosis, recovery, or when only one gate is\nrequired. A finalize failure does not relax any gate and does not turn a\npreserved older artifact into a current successful delivery.\n\n`finalize` discovers and starts private Chrome only after delivery and strict\nchecking pass. Failed input, repository-evidence, delivery, or artifact checks\ntherefore do not launch a browser. It loads the artifact only after current\nprovenance is verified. The browser gate retains every viewport, theme, and\nstability check; the browser closes at completion or a browser-stage failure.\nIts full stage receipt records `execution: \"in-process\"` and the equivalent\nstandalone `command` for replay. Chrome startup no longer overlaps the earlier\nstages, so successful runs may take slightly longer. This avoids unnecessary\nstartup on invalid candidates; it does not fix host sandbox restrictions on\nChrome startup or relax a browser gate.\n\nThe pair commit is recoverable, not a claim that two filesystem paths change\natomically or are durable across power loss. Journal finalization is part of\nthat commit: a caught failure while verifying or removing the journal rolls\nback the replaced files when possible and while ownership remains current. If\nownership is lost, the old attempt immediately stops renaming, rolling back,\nfinalizing the journal, recording failure provenance, or cleaning up shared\npaths. Any private staging or recoverable backups remain available and are\nidentified by the failure diagnostic. If restoration fails for another reason,\nthe failure receipt likewise identifies retained backups for recovery. A\nprocess interruption can leave the journal, backups, or private staging behind;\ncheckers then fail closed. Follow the reported recovery evidence before rerunning\n`deliver` serially on the same output. A failed attempt exits non-zero and never invokes an opener; it never\nauthorizes visual evidence collection.\n\nIf exclusive creation succeeds but lock initialization fails, Archify may\nrecord failed provenance and remove the incomplete lock only while its\ncapability still identifies that exact entry. A replacement is preserved.\nFilesystem and cleanup errors are reported separately from an active concurrent\ndelivery. An active, stale, unrecognized, or otherwise preserved lock\nindependently prevents checkers from accepting the prior artifact. Fix the\nreported filesystem error before retrying, and use another physical output\ndirectory if the lock path contains unrelated data.\n\nLock release is part of delivery completion. If the artifact/provenance pair\nhas committed and the journal has finalized but the matching lock cannot be\nremoved, `deliver` exits 1 with `delivery/lock-release`, preserves the lock,\ndoes not print a success receipt, and does not invoke an opener. The preserved\nlock keeps strict checkers fail-closed. Only after pair commit, journal\nfinalization, and lock release all succeed may `deliver` exit zero, print its\nsuccess receipt, or run `--open`.\n\nRun strict `check` after `deliver` exits zero. Run `browser-check` or optional\n`visual-check` only after that strict check exits zero. A failed marker,\nrecovery journal, or delivery lock makes every checker fail before accepting\nthe preserved HTML; report the diagnostics and complete a successful recovery\ndelivery before collecting new browser evidence.\n\nStatic `check` uses the same SVG path analysis for inspected relationships and\nstructural frames. It supports `M/L/H/V/Q/Z`, their lowercase relative forms,\nrepeated parameters, and finite numbers. Each `M` starts an independent subpath;\n`Z` closes only the current subpath. Separate subpaths never create connecting\nsegments that are absent from the drawing. Straight segments separated by a\nnon-collinear `Q` also remain separate in route analysis; curve sample points\ndo not become micro-segments in straight-route budgets or rhythm checks.\nSegment lengths and stretch are measured per continuous piece, while actual\nbends are summed per relationship. A relationship exceeding a budget is counted\nonce, and internal piece boundaries do not receive the short shared-trunk\nexception reserved for semantic endpoints.\n\nThis is not a promise of full SVG command support: `A/C/S/T` produce\n`artifact/svg-path-unsupported`; missing parameters, invalid numbers, and other\nsyntax errors produce `artifact/svg-path-malformed`. The checker exits non-zero\ninstead of skipping a bad path or waiting indefinitely. Path failures append a\n`svg_path_data` check; normal valid artifacts retain the existing nine checks.\nDiagnostics carry the inspected `pathIndex`, `role`, available relationship/frame\n`id`, parsing `tokenOffset`, available `command`, and `reason` so the generating\nsource can be located and repaired. `pathIndex` is one-based; `tokenOffset` is a\nzero-based UTF-16 offset in `d` after numeric character references are decoded.\nApparent tags in comments, CDATA, and attribute text are ignored. Passing static\npath checks does not establish browser or perceptual visual acceptance.\n\n<details>\n<summary>中文说明</summary>\n\n静态 `check` 对受检关系线和结构边界的 SVG 路径使用同一解析结果，支持\n`M/L/H/V/Q/Z` 及其小写相对形式、重复参数和有限数值。每个 `M` 开始独立\n子路径，`Z` 只闭合当前子路径；子路径之间不会被拼接成图中不存在的线段。\n非共线 `Q` 前后的直线也保持分离，不会把曲线采样点计为直线路由预算或\n节奏检查中的微线段。线段长度和伸长率按连续片段测量，真实转弯数汇总到原关系；超预算关系\n只计一次，内部子路径断点不享有语义起终点的短共享线例外。\n这不是完整 SVG 命令集的支持承诺：`A/C/S/T` 返回\n`artifact/svg-path-unsupported`；缺少参数、非法数值等格式错误返回\n`artifact/svg-path-malformed`，检查以非零状态结束，不跳过坏路径或无限等待。\n路径失败时追加 `svg_path_data` 检查；普通有效产物仍保留原来的 9 项检查。\n诊断携带受检路径的 `pathIndex`、`role`、可用的关系/边界 `id`，以及解析位置\n`tokenOffset`、可用的 `command` 和 `reason`，用于定位并修复生成路径的来源。\n`pathIndex` 从 1 开始；`tokenOffset` 是数字字符引用解码后的 `d` 字符串中\n从 0 开始的 UTF-16 位置。注释、CDATA 和属性文本中的伪标签不参与检查。\n静态路径检查通过仍不代表浏览器或感知视觉验收通过。\n\n</details>\n\nThe delivery interface exposes four separate claims:\n\n1. `deliver` proves deterministic artifact checks and byte identity.\n2. `browser-check` collects required automated browser evidence from the exact artifact without capturing images.\n3. `visual-check` optionally adds artifact-bound screenshots and a contact sheet.\n4. Perceptual visual review records a human or image-capable reviewer's judgment.\n\nPassing one claim never implies the others. Never claim that the deterministic receipt includes browser or perceptual review evidence.\n\n## Architecture Diagnosis offer\n\nAfter a passing `finalize architecture` with `--repo-root`, the full receipt\nand compact summary include `codeAnalysisOffer` if a bounded scan finds\nsources eligible for the default analysis. The offer includes the effective\nfinalize `quality`, passes it in `start.argv`, and records a `dependencies`\nstatus of `installed` or `missing`. Finalize performs these checks without\nstarting analysis or installing anything.\n\nEnd the delivery summary with the capability section below, in the user's\nlanguage, once per repository in the task. It is part of the summary, not a\nseparate question, so users learn what Diagnosis does even if they never\nreply. Skip it if the user already asked for or declined analysis in this\ntask. Keep the bullets; adapt only wording, not the claims. If `dependencies`\nis `missing`, the installed Skill copy is incomplete: replace the closing line\nwith the reinstall line, because analysis cannot start. If the offer includes\n`linkedDiagrams: true`, add that sibling-diagram links work from the original\ndelivered diagram, not from the Diagnosis server. Mention the diagram button\nonly when `codeAnalysisOffer.diagramButton` is `true`; otherwise drop that\nsentence. Start only after the user agrees.\n\n**中文**\n\n**还可以：架构诊断**（Archify 自带，在本机运行）\n- **环形星图**：几千个文件、几万个函数之间的依赖一眼看全\n- **可旋转的 3D 模型**：换个角度看模块怎么连在一起\n- **组件问题数**：直接标在这张架构图上，哪里最拥挤、哪里有循环依赖、哪些依赖图里没画\n- 每条发现都能点开看源码，也能一键交给 AI 修\n\n回复「好」我就启动。图右上角的「架构诊断」按钮也随时能看到这个功能。\n（依赖缺失时，最后一句改为：分析组件缺失，需要先重新安装 Archify 才能使用。）\n\n**English**\n\n**Also available: Architecture Diagnosis** (built into Archify, runs locally)\n- **Radial star map**: dependencies across thousands of files and functions at a glance\n- **Rotatable 3D model**: see how modules connect from any angle\n- **Issue counts per component**, right on this diagram: where things are most crowded, where dependencies cycle, and which dependencies the diagram doesn't show\n- Every finding opens its source and can be handed to an AI as a fix task\n\nReply \"yes\" and I'll start it. The **Code Analysis** button at the top right of the diagram shows this anytime.\n(If dependencies are missing, the closing line becomes: The analysis components are missing; reinstall Archify to use it.)\n\nAfter consent, run `start.argv`. Add `--locale zh-CN` for Chinese or\n`--locale en` for English if needed. For a repository with several supported\nlanguages, select the adapter with `--language` as described in the\n[Code Analysis guide](../modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation).\nShare the printed local URL. The original architecture diagram appears first.\nClick **Code Analysis** (**架构诊断** in Chinese) to run analysis and open the\ncomponent findings, radial star map, and Atlas 3D views.\n\n## Comparison presentation changes\n\nArchitecture comparisons include authored `meta.translations` in presentation changes. Adding, removing or editing translations changes `summary.presentationChanged`; reordering translation keys does not. An empty translation object is equivalent to an omitted catalog for presentation classification; the canonical source digest still records the authored representation. Component, relationship, boundary and repository-provenance classifications remain independent.\n\n## Recovering a failed comparison\n\n`compare` commits an HTML artifact and its JSON receipt as a pair. If that commit\nfails, it attempts to restore the previous files. A complete rollback removes\nthe temporary directory as usual.\n\nIf a previous file cannot be restored, compare exits non-zero with\n`delta/commit-rollback-failed` and retains the recovery directory. In the JSON\nfailure receipt, `diagnostics[].evidence.recoveryDirectory` identifies that\ndirectory and `recoveryFiles` lists `{ backup, target }` paths for the files whose\nrestoration failed. Human-readable diagnostics also print the recovery paths.\n\nResolve the filesystem error, inspect the current targets, and restore each\nlisted backup to its corresponding target before retrying. Keep the recovery\ndirectory until both previous files have been recovered and verified; it can\nalso contain rejected candidate files, which must not be mistaken for backups.\nSuccessful comparisons and failures before commit retain their normal cleanup.\n\n## Automated browser evidence\n\n`finalize` runs the required browser gate against the exact trusted HTML without\nrerendering or modifying it. For focused diagnosis, the equivalent standalone\ncommand is:\n\n```bash\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\nThe zero-dependency command uses Chrome/Chromium (or Microsoft Edge)\nthrough the DevTools pipe. `ARCHIFY_CHROME` is authoritative when set, including\nan invalid path: Archify does not silently fall back to another browser. Automatic\nWindows discovery checks every Chrome/Chromium install location and PATH command\nfirst, then Edge under `%ProgramFiles(x86)%`, `%ProgramFiles%`, and `%LocalAppData%`,\nfollowed by `msedge` on PATH. On macOS and Linux, discovery also checks\nChrome/Chromium first, then the Edge application bundle (macOS) and\n`microsoft-edge`/`microsoft-edge-stable` on PATH. It\nmeasures light-theme containment at 1440×900, 1600×1000, 1920×1080, and\n2048×1320, and verifies the requested light theme at all four viewports, the dark\ntheme at both endpoints, and READ/Still runtime states. A requested theme that\nresolves to a different theme fails with measured evidence. It creates one\n`<output-stem>.browser-check.json` receipt and no screenshots or contact sheet.\nPass `--out-dir <dir>` to place the receipt in a separate evidence directory.\nThe receipt binds the artifact SHA-256 and byte count, identifies\n`evidenceKind: \"automated-browser\"`, and reports\n`visualReview: \"not-requested\"`.\n\nHorizontal overflow always fails. Normal document-level vertical scrolling is\naccepted only with a renderer-declared contract and measured readable text.\nAutomatic canvases declare `data-reader-fit=\"intrinsic-height\"` (height fitting)\nor `data-reader-fit=\"width-first\"` (Sequence and Waterfall reading width); their adaptive\nReader must reach its readable width and expose `data-reader-overflow=\"authored\"`.\nArchitecture with an explicit `meta.viewBox` instead declares\n`data-diagram-type=\"architecture\"` and `data-reader-fit=\"authored-height\"`:\nits SVG coordinates, aspect ratio and existing Reader width behavior stay\nunchanged. Its full SVG must remain inside the diagram panel without internal\nscrolling or clipping, and the document must permit vertical scrolling.\nThe receipt records `verticalScrollAccepted: true` and\n`overflowDisposition: \"readable-vertical-scroll\"`. Missing or unknown declarations,\nexplicit viewBoxes in other modes, unreadable text, horizontal overflow,\nclipping and Viewer chrome collisions remain failures. Do not add an internal\ndiagram scroller or hide overflow.\n\n`browser_evidence` in the handoff records only the outcome of this automated\ncommand:\n\n- `passed` maps from exit 0 and receipt `status: \"pass\"` after every required measurement completes and passes.\n- `failed` maps from exit 1 and receipt `status: \"fail\"` when the inspection finds a defect, the command fails, or a runtime error leaves the evidence incomplete.\n- `skipped` maps only from exit 2 and receipt `status: \"skipped\"` when no supported browser is available and the inspection does not run.\n\nRuntime failures leave incomplete evidence and must not be normalized to\n`skipped`. They do not invalidate an already successful deterministic delivery.\nRetry an environmental failure in a browser-capable execution context when\npractical. Keep the packaged transport unchanged unless the failure reproduces\nthrough that seam in a capable environment.\n\nOn Windows, Chrome/Edge startup relaunches can lose the inherited DevTools\npipe before any response arrives. Archify removes a standalone\n`__COMPAT_LAYER=DetectorsAppHealth` from the browser child's environment only\n(case-insensitive name and value); the parent environment, unknown layers,\ncombined layers, and privilege-related compatibility settings are unchanged.\nThis targets the reported non-elevated Git Bash app-health case, not every\nAppCompat mode. Elevated-shell relaunches remain unsupported: rerun from a\nnon-elevated PowerShell opened normally, outside an elevated or compatibility-mode\nparent. Archify does not suppress browser de-elevation or disable the sandbox\nas a relaunch workaround. A zero-response startup diagnostic suggests this\nremedy without claiming that elevation or AppCompat caused every pipe failure.\n\nA provenance failure exits before browser inspection and persists a failed\nbrowser-check receipt bound to the attempted artifact. If the failure receipt\ncannot be written, the diagnostic names that incomplete evidence.\n\nBoth browser commands inspect the exact delivered HTML without modifying or rerendering it.\n\n## Sequence width review\n\nA passing `finalize` may report `layoutReviewRecommendation.action: \"inspect-sequence-width\"`. Its `evidence` measures the fixed participant columns' unused right-hand space after accounting for message labels, notes and segment titles. This advice adds no warning, failure, screenshot requirement or automatic geometry change.\n\nA passing `validate --json`, `deliver`, or `finalize` receipt may carry `diagnostics[]` entries with `severity: \"warning\"` for Viewer locale fallbacks (`i18n/*`). They fail no gate. When the artifact should be fully localized, repair the listed keys from their `evidence` and rerun `finalize`.\n\nSequence canvases with omitted `meta.column_fit` use `spread`, whether or not `meta.viewBox` is supplied. An authored viewBox remains authoritative; infeasible participant capacity fails without silently enlarging it. Explicit `meta.column_fit: \"fixed\"` preserves historical fixed columns. For a candidate whose fixed-column width suggestion remains, first check whether the fixed geometry is intentional. Only when a change to that geometry is authorized, save the candidate, set only `meta.column_fit` to `\"spread\"`, and rerun the complete `finalize` once with `--out-dir <folder>/width-review`. Keep participant order, messages and their y positions, labels, notes, sources and canvas dimensions. If that attempt fails, restore the candidate and finalize it with `--out-dir <folder>/width-restore`; report the remaining layout suggestion rather than iterating. Preserve intentional fixed geometry and disclose the suggestion when a change is not authorized. To retain historical fixed coordinates for an older omitted-fit input, set `meta.column_fit: \"fixed\"` explicitly. This review is about horizontal composition; a passing receipt still does not claim perceptual approval.\n\n## Optional capture evidence\n\n`visual-check` remains backward compatible for a requested or escalated\nperceptual review:\n\n```bash\nnode bin/archify.mjs visual-check <output.html> --summary --require-provenance\n```\n\n`--summary` returns compact JSON with all diagnostics and absolute paths to the complete receipt, contact sheet, and every screenshot. For a chosen visual review, inspect the relevant captures; capture success is not perceptual approval. `--json` retains the full receipt output for existing consumers. Both modes run the same checks and keep the same exit status. If cleanup fails after publication, the summary retains the final failure diagnostics and `publication` recovery details; the linked receipt records the earlier committed evidence.\n\nIt performs the same automated browser measurements, captures light/dark\nscreenshots at 1440×900 and 2048×1320, and writes four viewport PNG sidecars,\none relative-path HTML contact sheet, and one JSON receipt. `--out-dir <dir>` moves all of these sidecars together.\nOpen the HTML contact sheet in a browser or inspect the viewport PNGs with an image reader. Its receipt reports `visualReview: \"pending\"` because captures do not themselves\nmake a perceptual judgment. Capture and provenance failures follow the ownership rules below.\n\nThe receipt, contact sheet, and four PNGs form one owned evidence set. Before\ncapture, `visual-check` freezes every requested directory entry, its\ncanonical write slot and physical parent, and the target's absent/file state,\ntype, device/inode identity, and mode. Hard-linked evidence targets are not safe\nwrite targets. All candidate files are created exclusively inside one random,\nprivate staging directory beneath the physical evidence directory; the receipt\nis published last. Each staged candidate must have exactly one hard-link name\nbefore publication. The no-clobber publish link temporarily gives the staged\nand final names a link count of two; unlinking the verified staged name must\nleave the final entry with a link count of one. An unexpected external hard\nlink fails closed and its alias is never removed.\n\nChrome inspects one identity- and content-checked copy of the captured artifact\nin a private local temporary directory, so browser file loading does not depend\non UNC or long-path support. The six publication candidates remain on the\nevidence volume. Both temporary directories are cleaned without recursively\ndeleting unknown contents; retained entries include their recovery locations.\n\nImmediately before committing anything, `visual-check` re-resolves and verifies\nthe complete six-path set. An absent-path claimant, existing-path replacement,\nsymbolic-link or dangling-link retarget, parent-topology change, hard link, or\nindeterminate identity fails closed with `viewer/evidence-path-conflict`. The\nclaimant and every other final evidence path remain untouched. Cleanup removes\nonly this run's staged or published entries after rechecking their captured\nidentities; a changed or unknown entry is preserved.\n\nAn existing visual evidence set is replaceable only when a regular\n`visual-check` receipt proves ownership of the same artifact and evidence\ndirectory, and its exact sidecar manifest matches every existing contact-sheet\nor PNG byte count and SHA-256 digest. A missing, malformed, unknown, mismatched,\nor incomplete ownership record never authorizes deletion. Failed and skipped\nruns retire prior screenshots/contact sheets only as part of the same verified\ntransaction when that ownership proof succeeds; otherwise they preserve all\nunknown evidence and report `viewer/evidence-path-conflict`.\n\nThis rule also applies when Chrome is unavailable or provenance fails before\nbrowser inspection: neither path may blindly delete stale-looking evidence. A\nverified owned set may be recoverably retired before publishing a skipped or\nfailed receipt; unowned evidence remains intact. These outcomes do not invalidate an already\nsuccessful deterministic delivery and do not turn a perceptual visual review\ninto passed or failed. Retry an environmental failure through the supported\ncommand in a browser-capable execution context when practical. Keep the\npackaged transport unchanged unless the failure reproduces through that seam in\na capable environment.\n\n`browser-check` applies the same private-snapshot, identity, ownership, and no-clobber rules to its single JSON receipt. Its namespace is separate from `visual-check`, so a browser-only rerun cannot remove capture evidence.\n\n## A new candidate at an existing output path\n\nBrowser evidence belongs to exact artifact bytes. After editing a candidate whose previous HTML already has browser evidence, choose a fresh evidence directory before running the next `finalize`; this preserves the old receipts and captures without an avoidable ownership-conflict retry. `--out-dir` relocates the new browser-check receipt and, by default, the finalize receipt and summary. An explicit `--receipt` overrides the finalize receipt path; its summary follows that path. Successful delivery still rewrites the requested HTML and its sibling `*.delivery.json`. Earlier browser or visual evidence remains bound to its original artifact bytes and must not be treated as evidence for changed HTML:\n\n```bash\nnode bin/archify.mjs finalize architecture candidate.json diagram.html --quality showcase --repo-root <root> --out-dir diagram.review-2 --json\nnode bin/archify.mjs visual-check diagram.html --out-dir diagram.review-2 --summary --require-provenance\n```\n\nThe evidence directory is not an archive of the HTML. Copying the HTML there alone does not rebind receipt paths or provenance. If a historical snapshot is needed, preserve the candidate and artifact separately before overwriting them; do not assume copied receipts validate a relocated artifact.\n\nKeep the requested HTML path stable. Use a new revision directory for each changed candidate, and retain the same directory for retries of unchanged bytes. For a diagram without repository evidence, omit `--repo-root`. Let the commands create their output directory. A prior validation failure that produced no HTML or browser evidence needs no new directory. Never remove unknown evidence to make a retry pass.\n\n## Optional opening\n\nAdd `--open` only when the user wants an immediate local preview. It runs after\nthe verified pair commit has completed, its recovery journal has been removed,\nand the delivery lock has been released successfully. It uses one argument-array\nOS opener with a five-second bound on macOS and Linux, and a fifteen-second bound\nfor PowerShell startup on Windows. The receipt records `open.status`; failed or\nunavailable launch attempts also include normalized `open.failure` details.\nKeep it off for CI, unattended agents, and non-interactive environments.\nFailure or unsupported opening does not invalidate delivery; its\nstatus proves only whether the local opener invocation succeeded.\n\n## Last-Good Live Preview\n\nFor an active desktop authoring loop only:\n\n```bash\nnode bin/archify.mjs preview <type> <input>.json <output>.html --quality showcase\n```\n\nPreview watches one explicit input on loopback, binds each stable digest to a private snapshot, and advances only after the existing verified delivery pipeline passes. Invalid, half-written, deleted, or superseded input leaves the previous verified revision on screen and on disk. Identical bytes do not rebuild or reload.\n\nThe preview runtime ships inside the zero-dependency Skill ZIP and must work without `node_modules`.\n\nNever start it by default. Do not use it for CI, unattended agents, remote sharing, or mobile use. `--no-open` is only for a user who will open the printed local URL or for loop testing. Stop it with Ctrl-C before handoff. The first Ctrl-C drains the active delivery without publishing it; a second Ctrl-C forces shutdown of both delivery processes and HTTP connections, including incomplete requests. Shutdown preserves the last verified artifact and removes only staging files whose ownership can be verified. If delivery is interrupted before its receipt reaches Preview, unconfirmed files and recovery material may remain in the private staging directory; shutdown does not recursively delete unknown contents. Server state, port, source path, diagnostics, error text, and reload tokens must never enter the generated artifact or any export.\n\n## Per","isInternal":false,"tokens":10634,"sizeBytes":51174},{"name":"viewer-runtime.md","path":"archify/references/viewer-runtime.md","rawUrl":"https://raw.githubusercontent.com/tt-a1i/archify/HEAD/archify/references/viewer-runtime.md","title":"References Skill","category":"anthropic-skill","format":"markdown","content":"# Viewer Runtime reference\n\nRead this only when the user asks for a reader-facing capability. Ordinary generation does not require implementing or re-documenting these features; they are already in the generated HTML.\n\n## Exploration\n\n- Diagram Guide lists current actions and shortcuts. Open it with the guide button or `?`; it never opens automatically.\n- Reading Depth starts at READ at the default 100% scale, reveals FULL detail at 175%, and falls back to MAP only below 100%. Focus, route, and semantic interactions reveal their exact facts at any scale.\n- Semantic Lens summarizes selected node/relationship kinds without changing authored geometry.\n- Intent Trace previews a fine-pointer or keyboard target before committed focus.\n- Node Finder searches labels and stable IDs.\n- Semantic Passport opens on focus, shows authored upstream/downstream facts, supports a copyable deep link, has an explicit close action, closes on true outside activation and Escape, and never enters canonical export.\n- Semantic Radar mirrors the visible viewport and authored graph without becoming a second source of truth.\n- Direct Relationship Pin makes a unique compiled relationship operable while preserving the authored line and stable relationship identity. It must fail closed on conflicting source/target/label/ID metadata.\n- Route Probe resolves exactly two endpoints over authored directed relationships. It never infers a route from geometry.\n\n## Embedded reading addresses\n\nA host displaying the native reader in an opaque `srcdoc` frame may set\n`data-reading-link-template` on that reader's `html` element. Supply an absolute\nHTTP, HTTPS or file URL containing exactly one `{state}` marker, for example\n`https://example.test/architecture#page=mechanism&reader={state}`. Native Focus,\nRelationship, Reach, Route and Lens copy actions replace the marker with their\npercent-encoded opaque query state. The host keeps its page identity and restores\nthat value as the native frame's hash; it never parses or reconstructs queries.\n\nAbsent configuration preserves standalone links. Invalid, credential-bearing or\nunsupported URL templates make copying fail without accessing the clipboard.\nThis seam changes copied addresses only, not query parsing, history, permissions,\nembedding isolation or authored geometry. It adds no network or storage surface.\n\n## Motion and presentation\n\nFor a narrated walkthrough with camera framing, explanations, captions and\nsynchronized audio, use [Story authoring](story-authoring.md). The `story attach`\ncommand adds Story to the native motion control and Story video to Export.\nThe player loads on first use and follows the existing preset and theme controls.\nPlayback schedules two short audio buffers ahead instead of synthesizing the whole timeline.\nVery large video exports are rejected before rendering. Use\n`Archify.story.exportVideo({start, seconds})` for a shorter range when needed.\n\nEvery rendered diagram enables reader-controlled Live/Still motion by default. In Live, every edge runs a small light show on one shared cycle: a comet (glow, halo, tail, head, plus a dimmer echo on every edge) cascades downstream, leaves a soft wake, and lands as a ripple on the target node, while nodes enter once and then glow on the same cycle with authored-step staggering. Phases follow the authored step order (source-node rank, chronological in sequence diagrams); the flow rides a separate Viewer overlay and the original line styles and arrowheads remain intact. Compact edges receive a larger, brighter comet; echoes stay dimmer. With no saved preference, new pages start Still. Choosing Live starts continuous flow and saves that preference; choosing Still stops it and clears the saved Live preference. Existing saved Still preferences remain Still. Semantic exploration temporarily owns the motion budget, and continuous flow resumes when that action releases it. Diagrams without connections retain their bounded node entrance rather than inventing a flow. Omit `meta.animation`; historical `\"trace\"` and `\"none\"` values remain accepted for input compatibility and do not change this default. Reduced motion, page hiding, print, and canonical export preserve complete static meaning. Presentation Stage changes viewer chrome and framing, never authored geometry. This is not a mobile product feature; narrow layouts get containment only.\n\n## Canonical exports\n\nThe export menu can copy/download full-diagram PNG, download JPEG/WebP, download a dual-theme SVG, and record a trace-enabled WebM. Viewer state—Guide, Lens, finder, focus, route, camera, radar, presentation, motion ownership, and temporary overlays—must be removed from canonical export.\n\nOpening, closing, or completing an export preserves the live Focus/Reach selection for continued exploration. Export-owned download activation is not outside dismissal; genuine outside activation and Escape retain their existing behavior. Full-diagram PNG/SVG exports still contain the complete canonical diagram, while the Reach Share Card communicates the active authored closure.\n\n### Route Share Card\n\nAfter a real directed Route Probe resolves, the reader may use **Export → Route Share Card**. It reuses the exact ordered route snapshot and the shared Share Card seam: `format=share-card`, `variant=route`. The isolated clone may use only static `data-share-route-*` decoration. It is download-only, fails closed for stale/unreachable/conflicting routes, and never becomes the canonical artifact.\n\n### Reach Share Card\n\nAfter a non-empty authored reachability query, the reader may use **Export → Reach Share Card**. It consumes the already resolved upstream/downstream node and edge set without rerunning traversal: `format=share-card`, `variant=reach`. The isolated clone may use only static `data-share-reach-*` decoration. It is download-only. Call it authored reachability—not impact, blast radius, breakage, or runtime causality.\n\n## Truth boundary\n\nViewer exports are communication assets. They do not replace the checked HTML, the deterministic delivery receipt, or a real visual review. Do not add a hosted service, storage surface, dependency, schema branch, or mobile product surface for these viewer-only capabilities.\n","isInternal":false,"tokens":1197,"sizeBytes":6239},{"name":"SKILL.md","path":"archify/SKILL.md","rawUrl":"https://raw.githubusercontent.com/tt-a1i/archify/HEAD/archify/SKILL.md","title":"archify","category":"anthropic-skill","format":"markdown","content":"---\nname: archify\ndescription: \"Create validated architecture, workflow, sequence, data-flow, lifecycle/state, ERD, class, tree, timeline, and waterfall diagrams as explorable standalone HTML with dark/light themes, motion and image/SVG/WebM export. Accept requirements or Mermaid; inspect repository evidence for code-backed diagrams. Also investigate local repository architecture health, coupling and refactoring scope with source-backed Code Analysis. Use when visualizing systems, API calls, pipelines, schemas, histories, timings, or everyday steps, parts, relationships and states. Also turn an answer into a one-page explainer, with the conclusion first, structured panels, native diagrams and charts, when the user asks for a page, an explainer or an answer to share (做成一页, 用页面讲), and by default unasked for a complex flow, diagnosis, comparison or test report; an [archify explainer: on-demand] rules line limits pages to requests. Optionally add a guided story and video export to an existing native diagram. Not for dashboards.\"\nlicense: Apache-2.0\nmetadata:\n  version: \"3.3\"\n  author: tt-a1i\n---\n\n# Archify\n\nCreate checked HTML as a native diagram, explainer, story, or standalone Code Analysis workbench.\n\nRun commands from your working directory. Unless the user names another location, give each new artifact request its own folder `.archify/<type>-<slug>-<YYYYMMDD-HHMMSS>/` there (local time, chosen once): keep the candidate and `<slug>.html` in it and reuse it for repairs. Native diagrams use `candidate.json` with `meta.output` relative to the working directory; explainers may use `candidate.archify.md` and a portable output filename. A later request gets a new folder. Replace `bin/archify.mjs` in every command with the installed package's absolute path, or its path relative to your working directory; CLI input and output paths resolve from that directory.\n\nFor a native diagram of a real codebase, read [Repository authoring](references/repository-authoring.md) while tracing the requested behavior. A system description uses the native steps below; a frozen candidate uses the handoff path.\n\n## Choose the artifact\n\n- For drawing a system, flow, schema or history, use a native diagram and the Type router. Deliver the requested diagram through `finalize`; code analysis is a separate mode.\n- For local repository architecture health, module coupling, cycles, layer violations, large files, complexity hotspots or refactoring orientation, use Code Analysis below; the agent handles commands and no architecture JSON is required.\n- For a guided walkthrough, animated/static dual-theme SVG, interactive stage player, or 1080p MP4/WebM video over one or more native diagrams, read [Story authoring](references/story-authoring.md). Use `story draft`/`attach` to add playback to a native Viewer, or `story validate`/`svg`/`stage`/`video` for declarative component choreography.\n- Only when the user explicitly asks to explain or visualize a pull request, a branch change or a `git diff`, or to attach change diagrams to a PR, or names the companion skill `archify-pr` when installed, read [PR review authoring](references/pr-review.md) first: it covers the three-dot diff, change-marked merged-superset views and the `pr validate` / `pr build` / `pr attach` loop.\n- Use `explainer` when the user asks for the answer as a page: a page, one page, an explainer, something to share (“做成一页”, “用页面讲”, “answer with a page”).\n- Explainer mode is `proactive` by default. A rules line `[archify explainer: <mode>]` in context selects another; an instruction in the conversation overrides it for that conversation.\n  - `proactive` (default, no line needed): also make a page, unasked, when the answer is a complex flow or process, a diagnosis or troubleshooting result, an option comparison, trade-off or decision, a test or review report, or a plan, and needs a table, steps or several sections to be read well.\n  - `on-demand`: make a page only when asked; otherwise answer in text or draw the requested diagram.\n  - `always-on` (opt-in only): every reply that reaches a conclusion also gets a compact page of at most four panels.\n- In every mode a page needs a conclusion with some structure behind it. Chat, short or one-line answers, routine status updates (“done, tests pass”), raw command output, a requested native diagram and any reply where the user asks for text only or no page (“只要文字”, “不用做页面”) get none. Make at most one page per reply, and none when the user names another page tool or another skill already made a page for that reply.\n- To change the mode, only when the user asks (“只在我要求时做页面”, “always make a page”), write or replace one `[archify explainer: <mode>]` line in the current agent's global rules file (such as `~/.codex/AGENTS.md`, `~/.claude/CLAUDE.md` or `~/.config/devin/AGENTS.md`) and name the file, for example `[archify explainer: on-demand] Make Archify explainer pages only when I ask for one.`; deleting the line restores `proactive`. Never switch to `always-on` unasked.\n- For `explainer`, read [Explainer authoring](references/explainer-authoring.md) for its conclusion, reasons, scope, board layout and optional native diagrams. Write the complete draft, then run `finalize explainer` for validation, atomic delivery and artifact checks. Use panel patch for local content revisions.\n\n## Existing candidate handoff\n\nWhen the user supplies a frozen candidate, run `finalize` first as one CLI invocation. Its passing receipt completes the automated gates; follow any visual review recommendation under Delivery before claiming visual quality. For repair, follow step 5.\n\n`finalize` includes a bounded update check in its delivery receipt; see Update awareness.\n\n## Native diagram authoring\n\nUse this path for ordinary generation. Read branch references only when their stated trigger applies.\n\n1. Choose `architecture`, `workflow`, `sequence`, `dataflow`, `lifecycle`, `erd`, `class`, `tree`, `timeline`, or `waterfall` from the question.\n2. Use the exact schema and example paths in the Type router without listing their directories. Read [Authoring defaults](references/authoring-defaults.md) and the mode's example in a bounded batch separate from project documents and complete schemas so neither is truncated; recover any missing section before writing. For a new Architecture, use `\"layout\": {\"mode\": \"auto\"}` and leave component positions to the renderer. Take component and relationship fields from the matching showcase example. Preserve any layout the user supplied. For every mode except Architecture, also read the mode and common schemas. Read the relevant schema definition before choosing any new field, enum, or constrained text, especially boundary kinds. Examples teach shape, not facts. Use fresh IDs, wording, and layout. Go directly to the candidate without preliminary help, doctor, starter validation, temporary diagrams, or output-path listing. Query brands only for an explicitly requested mark; read [Brand marks](references/brand-marks.md) for an unknown mark with a user-provided URL.\n3. Once the requested scope and, for a real codebase, [source evidence](references/repository-authoring.md) are covered, write the complete candidate directly without planning coordinates in prose. Choose Architecture abstraction and connected placement using Authoring defaults before coordinates: show the main user journey and necessary branches, preserve control roles and behavior-changing conditions, and leave enough room for actual relationship labels. No node, relationship, source, view, card, or boundary count is a target or ceiling. Use automatic routes first; add explicit routing only for necessary branch, return, supplied geometry, or measured repair. Set `meta.quality_profile` to `\"showcase\"` unless the user requests dense `standard`. For a grid ERD with automatic canvas, placement and routing, omit `layout.entityW` and entity `width` to fit fields. With a fixed view box, pinned table or manual route, size wide tables explicitly. For ERD, use a table-first layout: show every physical column in `entities[].attributes`, keep its SQL type and source comment, state every key role a column carries (`key` takes a role or a list, so a junction column is `[\"pk\", \"fk\"]`, and every `fk` column also needs `references` like `\"orders.id\"`), and never move columns into cards as a substitute for the table. Classify tables into functional domains before placement, give each domain a concise `tag`, and place its members in one solid rectangle of grid cells — a single row, a single column, or a filled rectangular block, not an L or diagonal. A tagged table always needs `row`/`col`, because absolute coordinates have no grid cells and a domain whose tables do not fill one rectangle cannot be drawn as a band: the renderer reports `erd/domain-not-drawn` instead of publishing a diagram that cannot name the domain. A multi-domain schema reads best as one domain per column — each `tag` a vertical run — because the reader scales a wide canvas up to the reader width and shrinks a tall one until the page fits, so the wide arrangement is the one that stays complete and legible inside a laptop viewport. A schema-first ERD over roughly 8 tables or 50 fields is itself a dense map: author its first complete-field pass at `standard` and upgrade only once the layout still reads.\n4. Once the complete first candidate is written, run `finalize` directly. Its first gate is showcase validation; successful first drafts need no separate pre-validation. Keep the candidate unchanged while the command runs:\n\n   ```bash\n   node bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n   ```\n\n   For a repository-backed candidate, include evidence on the first draft and use the complete first command: `node bin/archify.mjs finalize <type> <candidate.json> <output.html> --repo-root <repo-root> --quality showcase --json`. Pass the `--quality` that matches `meta.quality_profile`, such as `standard` for a dense first ERD pass.\n\n   A passing receipt proves the included `validate`, `deliver`, strict `check`, and real-browser `browser-check` gates passed. Use its compact summary; run standalone commands only for a separate request or focused failure diagnosis. After a passing Architecture finalize with `codeAnalysisOffer`, end the delivery summary with the [Architecture Diagnosis section](references/delivery-contract.md#architecture-diagnosis-offer) in the user's language, once per repository in the task. Skip it if the user already asked for or declined analysis. Wait for yes before running the offered command.\n\n5. A non-zero exit is never success. Read compact stdout or `evidence.summaryReceipt`, then [repair the failed gate](references/delivery-contract.md#failed-finalize-and-candidate-repair), including its repair limit. Preserve requested meaning and source evidence. For several tangled Architecture routes, read [Architecture layout repair](references/architecture-layout-repair.md); for measured field or geometry failures, read [Authoring contract](references/authoring-contract.md). Edit the connected neighborhood and rerun the complete `finalize` command from step 4. Once a run has reached `browser-check`, the output path owns that evidence: give every later run its own `--out-dir <folder>/review-<n>`.\n\n## Update awareness\n\n`finalize` and standalone `deliver` include `update` in their receipts. Do not run a separate check for the same delivery. If `update.noticeRequired` is true, read `references/update-awareness.md` and keep one compact update notice in your final response to the user, even after a quality gate fails. For a task with several diagrams, mention the update once in the final response. Snooze or ignore a reminder only when the user explicitly asks; never install or update on your own initiative.\n\nBefore the first candidate, use the authoring references and relevant repository source, not Archify implementation or tests. Inspect Archify implementation if diagnostics remain unactionable after focused repairs.\n\n## Type router\n\n| Type | Use for | Schema | Example |\n|---|---|---|---|\n| `architecture` | Components, services, cloud/security boundaries, infrastructure; what something everyday is made of | `schemas/architecture.schema.json` | System descriptions, services, libraries, and CLI repos: `examples/web-app.architecture.json`; deployment repos: `examples/production-deployment.architecture.json` |\n| `workflow` | Processes, approval gates, tool calls, runbooks, CI/CD; plans and step-by-step life processes | `schemas/workflow.schema.json` | `examples/agent-tool-call.workflow.json` |\n| `sequence` | API call chains, request lifecycles, async traces, returns; back-and-forth between people | `schemas/sequence.schema.json` | `examples/cache-miss-request.sequence.json` |\n| `dataflow` | Pipelines, ETL/ELT, lineage, governance, consumers; where money or documents go | `schemas/dataflow.schema.json` | `examples/product-analytics.dataflow.json` |\n| `lifecycle` | State/status transitions, retries, waiting and terminal states; where an application or order stands | `schemas/lifecycle.schema.json` | `examples/deployment-release.lifecycle.json` |\n| `erd` | Tables/entities, attributes, primary/foreign/unique keys, cardinality between them | `schemas/erd.schema.json` | `examples/orders.erd.json` |\n| `tree` | Single-parent containment: repository/module trees, capability or feature breakdowns, org-style decomposition | `schemas/tree.schema.json` | `examples/payment-platform.tree.json` |\n| `class` | Classes, interfaces, selected members, and dependency/association/inheritance/realization/composition between types | `schemas/class.schema.json` | `examples/payments.class.json` |\n| `timeline` | When things happened: incident reviews, release histories, timestamped events on a proportional clock with source lanes | `schemas/timeline.schema.json` | `examples/payment-incident.timeline.json` |\n| `waterfall` | Where the time went: span durations, overlap, and nesting of one request or agent run on a common time axis | `schemas/waterfall.schema.json` | `examples/checkout-request.waterfall.json` |\n\nWhen choosing among native diagram types is ambiguous, run `node bin/archify.mjs guide \"<scenario>\" --json`. Scenario proof examples are structural references, not facts to copy.\n\nFor an everyday subject, keep the same diagram modes and semantic types, then name them for the reader: use everyday `icon` values and `meta.legend` labels as in [Node icons](references/authoring-contract.md#node-icons). Ask for missing personal facts instead of inventing dates, amounts, or rules.\n\n## Mermaid input\n\nRead Mermaid for topology and meaning, then author fresh Archify JSON; do not mechanically render Mermaid styling.\n\n- `flowchart` / `graph` → `workflow`, or `architecture` for a component map.\n- `sequenceDiagram` → `sequence`; participants become semantic participants and arrows become messages.\n- `stateDiagram` → `lifecycle`; states and transitions retain meaning, not Mermaid style.\n- `erDiagram` → `erd`; entity and relationship names, keys, and cardinality retain meaning, not Mermaid style.\n- `classDiagram` → `class`; type kinds, selected members, and relationship kinds retain meaning, not Mermaid style.\n\n## Delivery\n\nUse the `finalize` command above for the first candidate and after a repair.\n\n`finalize` stops at the first non-passing gate. Its compact stdout and `<output-stem>.finalize-summary.json` are ordinary evidence. A passing run creates no screenshots and reports `visualReview: \"not-requested\"`.\n\nWhen a passing Architecture receipt reports `visualReviewRecommendation.signals.resolvedCrossovers`, save the candidate and follow [Architecture layout repair](references/architecture-layout-repair.md). Where several lines cross the reader’s main path, place the connected main steps in order and put each branch beside the component that owns it. Use the hints to locate the affected relationships. Make one edit to node positions and sizes only: every node, relationship (including its `from` and `to`), label, and source stays as it was. Rerun the complete `finalize` once with `--out-dir <folder>/review-2`, because the previous HTML already owns its browser evidence. `--out-dir` relocates the new browser-check and default finalize receipts, not the HTML or its delivery receipt. Successful delivery rewrites that pair at the requested output path; earlier review evidence remains bound to its original artifact bytes. See [review evidence paths](references/delivery-contract.md#a-new-candidate-at-an-existing-output-path). If that run fails, reports more crossings, or reports the same crossings with more `signals.routesOverSuggestedBends`, restore the copy and finalize it with `--out-dir <folder>/review-3`. Do not start a second placement round. Hints about extra bends alone are optional.\n\nWhen `layoutReviewRecommendation.action` is `inspect-sequence-width`, follow [Sequence width review](references/delivery-contract.md#sequence-width-review) before handing off a newly authored Sequence.\n\nFor a project README, deliver a static SVG by default. Follow an explicit request for a link or interactive HTML. Use Chrome or Chromium to export the finished HTML to a new file with `node <skill-dir>/bin/export-svg.mjs <diagram.html> <image.svg> [auto|light|dark]`. If the answer depends on small labels or Viewer cards, deliver a paste-ready Markdown image and a short caption that answers the question at normal text size.\n\nFor a README or project document, inspect the delivered diagram at its intended reading size. Follow the arrows from the starting point through each return or branch needed to answer the request. Verify conditional steps, fields and checks against the source, and name the condition where the reader sees the claim. Repair a broken reading path and inspect the result. For multiple runtimes or conditional handoffs, use the [reader check](references/repository-authoring.md#check-the-readers-answer).\n\nPerceptual review is optional for ordinary generation. Use [Optional capture evidence](references/delivery-contract.md#optional-capture-evidence), with `--out-dir <folder>/visual-check`, for a reproducible review or a concrete route/browser concern. `visualReviewRecommendation` is advisory. Inspect captures before claiming visual quality; qualify any check claim as automated when perceptual review has not occurred.\n\nRead [Delivery contract](references/delivery-contract.md) for failed gates, standalone commands, provenance/recovery, repeated delivery, exports, or opening. Native diagram recovery follows `deliver` → strict provenance `check` → `browser-check`; captures require strict provenance. Explainer delivery uses validate, deliver and check as described in its authoring guide.\n\nFor workflow viewport overflow, read [Workflow viewport repair](references/authoring-contract.md#workflow-viewport-repair) before the next layout edit.\n\nWhen reporting verification details, distinguish artifact checks, browser evidence, captures, and actual perceptual review. For an explicitly requested immediate preview or active desktop loop, see [Optional opening](references/delivery-contract.md#optional-opening).\n\n## Code Analysis (local repository architecture)\n\nFor a repository investigation, run `node bin/archify.mjs code-analysis prepare <repo-root> --out <analysis-dir> [--locale zh-CN|en] [--language ts|py|java|go|rust]`. Use `--locale zh-CN` for Chinese conversations. It creates `analysis/repo.analysis.html` with a source-backed workbench, interactive Atlas and captured AI tasks, then exits. No architecture JSON or diagram authoring is needed. Normal diagram requests end with their `finalize` delivery; analysis runs when the user requests investigation. Add `--ir <architecture.json>` only when a relevant diagram already exists or the user also wants authored architecture boundaries aligned with code evidence. This keeps the existing architecture/Atlas views and checked source mapping. Read [Code Analysis entry and investigation](modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation) for adapter prerequisites, headless checks, interactive re-analysis and coverage limits. Deliver the analysis HTML with one or two scoped observations and its task-copy controls, or continue investigating in this conversation. Users need no maintenance objective or CLI knowledge. Analysis describes the working tree, including uncommitted source; keep authored commit evidence separate. Verify source before editing, make a scoped improvement or explain why to retain the structure, then rerun analysis and project tests. Report measured preparation time and tool gaps, preserve any separately delivered diagram on failure, and avoid claims that static or missing findings prove runtime failure or a fix.\n\n## Optional viewer capabilities\n\nArchitecture, Workflow, Sequence, Dataflow and Lifecycle nodes may carry optional plain-text `explanation` (1–1200 characters). The focused Semantic Passport offers Explain; prose stays outside canonical SVG and visual exports. Omit the field when the existing label, sublabel and sources are sufficient.\n\nLive motion is enabled by default for every rendered diagram; omit `meta.animation`. The Viewer’s Live/Still button controls playback.\n\n### Cross-diagram navigation (overview → module → detail across HTML artifacts)\n\n- Targets are same-directory `filename.html` only (optional `?` / `#`). No `../`, `/`, or schemes.\n- Node `href` is sugar for a one-entry list (label defaults to the node label). `drilldowns` wins if both are present.\n- One child: native SVG `<a>` + corner mark; click follows the link; Alt-click focuses Passport.\n- Several children: Passport lists every target; click focuses; Ctrl+click / double-click opens the first entry.\n- Child diagrams may set `meta.parentHref`. The header Back control appears when `parentHref` or URL `?from=` is present.\n- Examples: sibling pair `examples/drilldown-platform.architecture.json` ↔ `examples/drilldown-integrations.architecture.json`; multi-child `examples/drilldown-overview.architecture.json`.\n\nRead `references/viewer-runtime.md` only when the user explicitly asks for Share Cards, Route/Reach cards, motion, deep links, presentation, search/focus, or another Viewer Runtime feature.\n\n## Setup and fallback\n\nNo install is required inside the skill package. For setup diagnosis, verify with:\n\n```bash\nnode bin/archify.mjs doctor\nnode bin/archify.mjs demo <output-directory>\n```\n\nFor native diagrams, when shell access is unavailable, hand-place architecture SVG into `assets/template.html`, use CSS semantic classes rather than inline colors, and follow the visual review contract in `references/delivery-contract.md`. Explainers require their renderer and real delivery gates; if those are unavailable, report the limitation and give a text answer when useful, without claiming HTML delivery.\n\n## Output\n\nReply in the user's language, as briefly as the result allows; the diagram carries the content, so a single diagram usually needs one line.\n\n- For a README diagram, lead with a link to the requested artifact (the exported SVG by default). Link the README when edited. For other native diagrams, lead with the HTML. Use descriptive Markdown links with absolute paths, wrapping paths with spaces in `<...>`.\n- When the user wants to understand a system or codebase rather than draw a described subject, add one or two sentences with the key takeaway. Skip sentences that only restate what the diagram obviously shows.\n- State anything that changes how the diagram should be read: the abstraction level or deliberately omitted parts when a reader might expect them, illustrative rather than measured values, missing source evidence, or requested content dropped or merged during repair.\n- For several diagrams, report completion once with a link to an existing overview or compact per-diagram links, not a directory path.\n\nDo not recap commands, repair rounds, hashes, quality profiles, or check lists; they stay in the receipts. If asked whether the diagram was verified, answer in one line, such as “Automated checks passed; not visually reviewed.” Give receipt links and details only for reproducibility or troubleshooting. Disclose requested visual review that could not run, and claim visual inspection only when performed. Keep the required update notice under Update awareness.\n\nExample: `Created [Checkout request timing](/abs/path/checkout-timing.html). Durations are illustrative, not measured.`\n\nFor an explainer, the reply must read well without opening the page: the conclusion in one to three lines with the key cause, numbers or recommendation, then, as the very last line, a Markdown link with a descriptive title in the user's language, such as `[查看测试报告](/abs/path/test-report.html)` or `[Open the test report](...)`. Use the absolute path, wrapped in `<...>` when it contains spaces, not `file://`; put any update notice before it. Never offer a directory, terminal log or auto-open (`--open`) instead of the link. When `finalize explainer` fails or the renderer is unavailable, answer in text, say in one line that the page was not produced, and give no page link. Mention gates only when one failed or writing warnings remain; do not paste the draft.\n","frontmatter":{"name":"archify","description":"Create validated architecture, workflow, sequence, data-flow, lifecycle/state, ERD, class, tree, timeline, and waterfall diagrams as explorable standalone HTML with dark/light themes, motion and image/SVG/WebM export. Accept requirements or Mermaid; inspect repository evidence for code-backed diagrams. Also investigate local repository architecture health, coupling and refactoring scope with source-backed Code Analysis. Use when visualizing systems, API calls, pipelines, schemas, histories, timings, or everyday steps, parts, relationships and states. Also turn an answer into a one-page explainer, with the conclusion first, structured panels, native diagrams and charts, when the user asks for a page, an explainer or an answer to share (做成一页, 用页面讲), and by default unasked for a complex flow, diagnosis, comparison or test report; an [archify explainer: on-demand] rules line limits pages to requests. Optionally add a guided story and video export to an existing native diagram. Not for dashboards.","license":"Apache-2.0","metadata":{"version":"3.3","author":"tt-a1i"}},"isInternal":false,"tokens":5353,"sizeBytes":25479}],"systemPromptSnippet":"<yakaai_skills repo=\"tt-a1i/archify\">\n<!-- File: DESIGN.md (Tokens: ~2821 | Category: project-spec) -->\n---\nname: Archify\ndescription: A precise, vivid technical instrument for trustworthy interactive architecture maps.\ncolors:\n  canvas: \"#020617\"\n  mask: \"#0F172A\"\n  ink: \"#FFFFFF\"\n  muted: \"#94A3B8\"\n  dim: \"#475569\"\n  border: \"#1E293B\"\n  frontend: \"#22D3EE\"\n  backend: \"#34D399\"\n  database: \"#A78BFA\"\n  cloud: \"#FBBF24\"\n  security: \"#FB7185\"\n  messagebus: \"#FB923C\"\n  external: \"#94A3B8\"\ntypography:\n  headline:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"1.5rem\"\n    fontWeight: 700\n    lineHeight: 1.2\n    letterSpacing: \"-0.025em\"\n  title:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.875rem\"\n    fontWeight: 600\n    lineHeight: 1.4\n    letterSpacing: \"normal\"\n  body:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.75rem\"\n    fontWeight: 400\n    lineHeight: 1.55\n    letterSpacing: \"normal\"\n  label:\n    fontFamily: \"JetBrains Mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace\"\n    fontSize: \"0.625rem\"\n    fontWeight: 700\n    lineHeight: 1.35\n    letterSpacing: \"0.12em\"\nrounded:\n  precise: \"0.2rem\"\n  control: \"0.5rem\"\n  panel: \"1rem\"\n  pill: \"999px\"\nspacing:\n  xs: \"0.25rem\"\n  sm: \"0.5rem\"\n  md: \"0.75rem\"\n  lg: \"1rem\"\n  xl: \"1.5rem\"\n  page: \"2rem\"\ncomponents:\n  toolbar-button:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.5rem 0.875rem\"\n    height: \"2.75rem\"\n  diagram-panel:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    rounded: \"{rounded.panel}\"\n    padding: \"1.5rem\"\n  search-field:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.ink}\"\n    typography: \"{typography.body}\"\n    rounded: \"{rounded.control}\"\n    padding: \"0.58rem 0.65rem\"\n  evidence-beacon:\n    backgroundColor: \"{colors.mask}\"\n    textColor: \"{colors.backend}\"\n    typography: \"{typography.label}\"\n    rounded: \"{rounded.pill}\"\n    size: \"30px × 12px\"\n---\n\n# Design System: Archify\n\n## Overview\n\n**Creative North Star: \"The Evidence Console\"**\n\nArchify is a composed technical instrument, not a drawing suite. The canvas carries one spatial narrative; restrained controls and progressive disclosure let a reader move from the primary path to exact authored relationships, metadata, and verified code evidence without losing orientation.\n\nThe visual system is precise, dark-first, and vivid only where semantics earn it. Light mode and Blueprint preserve the same vocabulary rather than becoming separate products. Motion has one bounded owner, finishes, and never carries meaning that disappears in a still frame. Desktop is the primary surface; narrow screens receive containment, not a second interface.\n\n**Key Characteristics:**\n\n- One dominant technical canvas with compact, low-interference chrome.\n- A fixed semantic color vocabulary shared by nodes, edges, legends, focus, and evidence.\n- Mono-forward typography, small labels, and deliberate density for engineering review.\n- Viewer state stays outside canonical exports; proof remains portable and deterministic.\n- State transitions are 140–200ms; authored story motion may be longer but finite and reader-controlled.\n\n## Colors\n\nThe palette is a midnight console with seven semantic signals; color identifies meaning, never decoration.\n\n### Primary\n\n- **Verified Cyan** (`frontend`): the main focus, navigation, and frontend signal. Its scarcity establishes hierarchy.\n\n### Secondary\n\n- **Proof Green** (`backend`): backend semantics, verified evidence, and successful state.\n- **Repository Violet** (`database`): persisted state, stores, and inward relationships.\n\n### Tertiary\n\n- **Boundary Rose** (`security`): policy, security, and guarded paths.\n- **Cloud Amber** (`cloud`), **Transit Orange** (`messagebus`), and **External Slate** (`external`): stable semantic categories, never interchangeable accents.\n\n### Neutral\n\n- **Midnight Canvas** (`canvas`) and **Ink Mask** (`mask`): the dark workspace and opaque geometry mask.\n- **Instrument Ink** (`ink`), **Quiet Copy** (`muted`), **Dim Annotation** (`dim`), and **Structural Border** (`border`): the text and containment ladder.\n\n### Named Rules\n\n**The Semantic Color Rule.** Every saturated color maps to a node or relationship meaning; never add an accent merely to make a surface lively.\n\n**The Theme Parity Rule.** Light, dark, Signal Flow, and Blueprint may change material and contrast, but must preserve category identity and information priority.\n\n## Typography\n\n**Display Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Body Font:** JetBrains Mono (with system monospace fallbacks)<br>\n**Label/Mono Font:** JetBrains Mono\n\n**Character:** A single mono family makes the artifact feel authored by an engineering instrument. Hierarchy comes from weight, scale, spacing, and case rather than a decorative display face.\n\n### Hierarchy\n\n- **Headline** (700, `1.5rem`, 1.2): artifact title only.\n- **Title** (600, `0.875rem`, 1.4): panels, cards, and selected semantic objects.\n- **Body** (400, `0.75rem`, 1.55): explanatory copy and relationship details.\n- **Label** (700, `0.625rem`, `0.12em`, uppercase): state, modes, metadata, and compact proof markers.\n\n### Named Rules\n\n**The One Voice Rule.** UI and diagram chrome remain mono-forward; never introduce a display font inside the generated artifact.\n\n**The Legibility Floor Rule.** Tiny labels are metadata, not prose. If a reader must parse a sentence, promote it to body size or disclose it on focus.\n\n## Elevation\n\nArchify is flat and tonal by default. Borders and surface contrast establish structure; shadows appear only on floating controls, temporary panels, active focus, or the Signal Flow atmosphere. Blueprint removes glow and squares materials to keep the review surface exact.\n\n### Shadow Vocabulary\n\n- **Canvas Lift** (`0 28px 80px rgba(0,0,0,0.34)`): Signal Flow diagram surface only.\n- **Floating Panel** (`0 18px 48px rgba(0,0,0,0.30)`): temporary discovery panels and the Semantic Passport.\n- **Action Feedback** (`0 0 7px var(--frontend-stroke)`): active SVG focus only, never an idle decoration.\n\n### Named Rules\n\n**The Flat-at-Rest Rule.** A static card or control uses border and tone; a shadow must explain layering or state.\n\n**The Canonical Clean Rule.** Viewer glow, overlays, focus, and temporary marks are removed from visual exports unless the export explicitly owns that narrative.\n\n## Components\n\n### Buttons\n\n- **Shape:** compact rounded rectangle (`0.5rem`), or precise corners (`0.2rem`) in Blueprint.\n- **Primary:** translucent toolbar material, one-pixel structural border, and mono body label. Desktop viewer chrome may use compact 32px controls; touch and narrow-screen targets stay at least `2.75rem` high.\n- **Hover / Focus:** 150ms border/background response; `2px` cyan focus ring with `2px` offset.\n- **Secondary / Ghost:** transparent within menus; never add a second saturated fill hierarchy.\n\n### Chips\n\n- **Style:** quiet bordered capsules for semantic metadata; selected state uses the owning semantic color.\n- **State:** a chip may summarize focus, mode, count, or evidence, but must not become an unlabeled icon-only control.\n\n### Cards / Containers\n\n- **Corner Style:** composed panel corners (`1rem`), reduced to `0.35rem` in Blueprint.\n- **Background:** tonal panel over the canvas, with a one-pixel border.\n- **Shadow Strategy:** flat by default; floating or Signal Flow surfaces use the elevation vocabulary.\n- **Internal Padding:** `1.25rem`–`1.5rem` for panels; compact proof blocks may use `0.5rem`–`0.75rem`.\n\n### Inputs / Fields\n\n- **Style:** one continuous bordered field, `0.5rem` corners, muted placeholder, and compact mono body text.\n- **Focus:** no browser outline; shift the border to Verified Cyan and add a restrained two-pixel halo.\n- **Error / Disabled:** preserve readable text and add a non-color cue; never rely on opacity alone for failure.\n\n### Navigation\n\n- **Style:** the diagram remains dominant. Toolbar, guided views, map, search, and passport appear only when relevant and reuse familiar labels.\n- **Default / Hover / Active:** 140–200ms state response; active state combines text, border, shape, or marker—not color alone.\n- **Narrow screens:** contain and stack existing controls safely; do not create a dedicated mobile product surface.\n\n### Semantic Passport\n\nOne focused node opens one compact proof surface containing stable ID, authored metadata, relationships, and optional revision-pinned sources. It is the single destination for details; new capabilities should route here before proposing another panel.\n\n### Verified Source Beacon\n\nAn evidence-backed node receives one viewer-only `SRC n` capsule in its upper-right corner. It inherits node state, adds no tab stop, and is stripped from every canonical visual export.\n\n### Brand Mark\n\nAn authored `brand` adds one compact identity badge to the upper-right of the\nnode. Built-in vectors and explicitly captured, digest-pinned site icons sit on a neutral plate;\ntheir color stays inside that plate and never recolors the semantic node, edge,\nlegend, focus, or evidence vocabulary. The semantic sigil remains visible. A\nVerified Source Beacon shifts left when both facts are present. Brand marks are\ncanonical authored SVG content and therefore survive visual export.\n\n### Authored Reachability\n\nSemantic Passport offers two native, count-bearing actions: `Upstream` follows authored incoming relationships and `Downstream` follows authored outgoing relationships. The canvas keeps the focused origin plus the complete reachable subgraph strong while unrelated topology recedes. Upstream uses Repository Violet, downstream uses Proof Green, and Blueprint removes glow. The receipt says nodes, links, and maximum hops; it never says blast radius or breakage.\n\n### Reach Share Card\n\nAn active reach query may expose one contextual **Export → Reach Share Card** item. The 1200×630 card keeps the full diagram as quiet context, preserves the selected origin and every matched authored node and link, and writes direction, origin, node count, link count, and maximum hops into the card header. Upstream retains Repository Violet; downstream retains Proof Green; Blueprint stays filter-free. The card is an explicit non-canonical reading variant, not runtime impact, causality, or breakage evidence. No animated state, live focus glow, camera transform, or unrelated viewer chrome enters the clone.\n\n## Do's and Don'ts\n\n### Do:\n\n- **Do** make the primary path legible before adding secondary relationships or detail.\n- **Do** derive every focus, reachability query, route, story, source link, receipt, and count from authored or locally verified evidence.\n- **Do** keep ordinary artifacts source-free and make repository evidence explicitly opt-in.\n- **Do** use 140–200ms transitions for control state and honor `prefers-reduced-motion`.\n- **Do** preserve keyboard access, visible focus, semantic labels, dark/light parity, and non-color state cues.\n- **Do** keep runtime exploration outside canonical SVG, raster, Share Card, and WebM backgrounds.\n- **Do** name an intentionally scoped Route or Reach Share Card in its header and machine-readable receipt.\n\n### Don't:\n\n- **Don't** build generic Mermaid beautifiers that change themes without improving information architecture.\n- **Don't** turn Archify into WYSIWYG drawing suites whose editing chrome becomes the product.\n- **Don't** ship motion-first graph demos that imply relationships or activity not present in the authored source.\n- **Don't** use dense dashboard shells, endless identical card grids, decorative glass, gradient text, and other AI-generated interface clichés.\n- **Don't** infer identity from arbitrary label text, add an unbounded icon marketplace, or let a brand badge replace the portable semantic vocabulary.\n- **Don't** create another permanent panel when the Semantic Passport, Node Finder, or existing canvas can carry the capability.\n- **Don't** call graph reachability runtime impact, blast radius, or breakage without independent code-analysis evidence.\n- **Don't** change the README Hero as a side effect of artifact or viewer iteration.\n\n<!-- File: archify/references/delivery-contract.md (Tokens: ~10634 | Category: anthropic-skill) -->\n# Delivery contract\n\n## Failed finalize and candidate repair\n\n`finalize` stops at the first non-passing gate. Use compact stdout or `evidence.summaryReceipt`; read its full sidecar only when the summary lacks evidence needed for a coherent repair. A receipt with four artifact checks is basic validation, not showcase acceptance: require all nine checks, zero composition errors, and zero warnings. Fix `meta.quality_profile` and schema errors before geometry. A dense full-schema ERD may keep `standard` for its first complete-field pass: require zero structural errors, no edge-through-node failures, complete field rows, and a readable grouped grid, and record composition warnings instead of spending unbounded time on them.\n\nWhen every diagnostic from the first embedded validation is\n`repository-evidence/line-out-of-range`, `finalize` may narrow an existing\ncitation's `end_line` to the last line of its pinned file and retry the complete\ngates once. The start line must already exist in that nonempty file; the source\npath, revision, start, and all other authored content stay unchanged. Automatic\nrepair requires the original bytes to match `JSON.stringify(parsed, null, 2)`\nplus one LF exactly. Other formatting, a BOM, CRLF, or number spellings that\nwould change on parsing and serialization require author repair, so reserialization\ncannot change unrelated bytes or numeric precision. Missing files, invalid starts,\nand mixed failures also require author repair. This only bounds\nthe cited range; it does not establish or correct the cited fact. `autoRepair`\nrecords the changed ranges and original/repaired hashes in both receipts. A\npassing retry keeps the repaired candidate. Any later failure or exception\nattempts a byte-for-byte restore, guarded by the repaired candidate's identity\nand bytes, and invalidates only that retry's current-delivery sidecar. External\nedits are preserved and a returned receipt reports `restore-failed` if recovery\ncannot safely complete. Failure diagnostics and `specification` describe the\nchecked retry; `autoRepair.outcome` states whether the original was restored.\nThrown exceptions remain command failures and may leave the last persisted\nreceipt at an earlier stage; only a completed passing command is a handoff.\n\nFor a validation failure, edit the existing JSON in the connected neighborhood named by diagnostics before rerunning a command. Preserve requested semantics, meaningful labels, source evidence, and fixed or agreed topology. Several routes sharing nodes call for one placement repair; read [Architecture layout repair](architecture-layout-repair.md) for that case. Reflow a blocked main path rather than nudging unrelated labels. Keep unrelated geometry when its composition already reads clearly. Use `--layout-json` before editing only when compact evidence lacks needed measurements. Workflow v2 uses its stable compiler receipt, not solver internals, as authoring evidence.\n\nKeep the best candidate that cleared route checks before a viewport repair. If that repair introduces new route collisions, restore the measured layout and address its remaining canvas or text constraint.\n\nAfter the edit, rerun the complete `finalize` command with `--quality showcase` and, for repository-backed work, `--repo-root <repo-root>`. If the output path already has browser evidence from another candidate, use a fresh `--out-dir <output-stem>.review-<revision>` for both the new `finalize` and any `visual-check`. Omit an earlier `--candidate-sha256` after editing because it binds the previous candidate. Compare diagnostics by code, subject, stage, and evidence, never by declining error count alone. Track the repair limit per persistent issue, using that code, subject, stage, and evidence: a newly exposed issue starts its own repair sequence. If an issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, report the concrete gap.\n\nUse standalone `validate` only for focused diagnosis, passing `--repo-root` for repository-backed work. Its passing receipt marks `candidateFrozen: true`; run `nextAction.arguments`, replacing only `<output.html>`, without editing, revalidating, or rereading the candidate. Retry later environmental or evidence failures against those frozen bytes. A measured reason to edit creates a new candidate and calls for the complete `finalize` without the old hash.\n\n## Validate and deliver\n\n`render` and direct renderer entry points print classified authoring failures\nto stderr as readable diagnostics and exit 1. Input read/JSON parse failures\nuse `input/read` or `input/json-parse`; output filesystem failures use\n`output/write` and identify the output path. Schema and layout failures keep\ntheir existing rule codes. Use the advertised `validate --json` or\n`deliver --json` interface for a machine receipt; `render` has no `--json` flag.\nUnexpected implementation failures retain debugging information in human\nmode and remain `internal/unclassified` in machine receipts.\n\nDeclared local Explainer chart data and native-diagram specification files are protected inputs, including physical aliases. Delivery and finalize refuse sidecars that would overwrite those inputs, including when resource preparation fails; an uninspectable draft cannot publish failure evidence.\n\nEach delivered output has two artifact-specific metadata paths. When an output\nstem is too long for those derived filenames, Archify shortens it and appends a\nstable hash:\n\n- `<output-stem>.delivery.json` records the latest completed attempt.\n- `<output-stem>.delivery-pending.json` is the recovery journal for an attempt\n  in progress.\n\nFor a literal artifact stem that already matches Archify's reserved bounded-name\nmarker, a pre-namespace raw provenance sidecar remains a read fallback when the\nencoded sidecar is absent. A pre-namespace raw pending journal is an independent\nfail-closed barrier: it blocks checks and redelivery even when an encoded pending\njournal also exists, and neither journal is silently replaced.\n\nOne directory-wide `.archify-delivery-lock.json` serializes every delivery that\nresolves into the same physical output directory. This deliberately prevents\ncase, Unicode-normalization, Windows short-name, and symbolic-link aliases from\ncreating independent owners for one filesystem location. The tradeoff is that\ndeliveries to different artifact names in one directory also run serially;\nprovenance and pending journals remain artifact-specific.\n\nFor migration safety, Archify also detects and preserves a legacy\n`<output-stem>.delivery-lock.json` beside the requested artifact. An existing\nlegacy entry is a fail-closed recovery barrier. While a new delivery owns the\ndirectory mutex, it also holds temporary legacy-format fences for the requested\nspelling and an existing artifact's physical target spelling. It acquires the\ndirectory lock first, then all required compatibility fences before writing a\njournal or artifact, and removes the directory lock before those fences during\nrelease. This blocks an older Archify binary using\neither known spelling from entering the delivery. A legacy fence whose raw\nHEAD-era filename exceeds the host component limit is omitted because the old\nbinary could not create that lock or deliver that artifact on the host either.\n\n`deliver` acquires the lock by exclusive `open(..., \"wx\")` before creating or\nreplacing the recovery journal. A successful exclusive create yields an\ninternal opaque ownership capability bound to that attempt. Journal creation,\nfailed-provenance recording, pair commit, rollback, journal finalization, and\nlock release each verify the current capability inside the operation that\nwould mutate shared state. A rejected contender does not create a journal or\nwrite failed provenance.\n\nAn existing directory or legacy lock is handled without automatic recovery:\n\n| Observed lock state | Required `deliver` result |\n| --- | --- |\n| No directory entry | Attempt exclusive creation; only its success grants ownership. |\n| Valid schema-v1 lock whose PID is running, or whose death cannot be established | Exit 1 with `delivery/concurrent-attempt`; preserve every shared path. |\n| Valid schema-v1 lock whose PID is known to have exited | Exit 1 with `delivery/lock-stale`; preserve the lock, artifact, journal, and current provenance exactly. |\n| Unreadable, malformed, symlink, dangling symlink, directory, or other non-regular lock entry | Exit 1 with `delivery/lock-invalid`; preserve the entry and every other shared path. |\n| An acquired capability no longer matches the current lock or journal | Exit 1 with `delivery/ownership-lost`; stop all shared-path mutation. |\n| The matching owner cannot remove its lock | Exit 1 with `delivery/lock-release`; preserve the lock. |\n\nA `delivery/lock-stale` diagnostic identifies the absolute output and lock\npaths plus the original PID and receipt ID. Recovery is deliberately explicit\nand serial: stop all delivery attempts for that physical output directory,\nconfirm that no active delivery owns it and that the reported stale entry has\nnot been replaced, remove only the reported lock, then rerun `deliver`. Do not\nremove an artifact, current provenance, or pending journal as part of\nstale-lock recovery.\n\nThe lock protocol targets Node.js 18 or later on a local filesystem with\ncooperating Archify processes. PID, receipt, and file-identity comparisons are\ndefensive checks, not an atomic compare-and-swap. Compatibility fences cover\nthe requested spelling and an existing physical-target spelling; they cannot\nenumerate arbitrary hard-link names or previously unknown filesystem aliases,\nso mixed-version delivery through such aliases remains out of scope. This\ncontract does not claim distributed-lock correctness on NFS, SMB, or other\nnetwork filesystems, and it cannot prevent an external process that ignores\nthe protocol from replacing shared paths.\n\nEvery no-clobber HTML publisher (`render`, `deliver`, `compare`, and `preview`)\ncaptures the requested directory entry, canonical write slot, physical parent,\nand existing target type, device/inode identity, and mode before staging, then\nrevalidates that snapshot immediately before replacement. An existing write\ntarget must be a regular file with exactly one hard-link name. A target with\nmultiple hard-link names fails closed with `output/target-hardlinked`: replacing\nthe requested name cannot update unknown sibling names as one publication.\nHard links remain supported for read identity and input/alias collision checks;\nthey are unsupported only as write targets. A symbolic link to a single-link regular\nfile remains supported: publication preserves the symbolic-link entry and\napplies the same protocol to its resolved target. Directory, FIFO, socket,\ndevice, changing mode, new claimant, and indeterminate identity cases fail\nbefore replacement.\n\nPublication is no-clobber and recoverable, not crash-atomic replacement of an\nexisting target. To avoid overwriting a claimant that appears after the last\nidentity check, Archify first retains the bound old file in a private recovery\nbackup, removes the public name through identity-bound quarantine, and then\ncreates the new public name with an exclusive hard link. A caught failure rolls\nback when the public slot and recovery binding still permit it. A process\ninterruption between those namespace operations can instead leave the public\npath absent while the verified previous bytes remain in an adjacent private\nrecovery backup. Single-artifact publication records the original slot/alias\nidentity and backup inode, mode, SHA-256, and byte count in private\n`.archify-remove-*/publication-recovery-v1.json`, beside `previous`. To make a\nspecific interrupted publication visible again, stop concurrent writers and run:\n\n```bash\nnode bin/recover-output.mjs /absolute/path/to/.archify-remove-<id> --json\n```\n\nThis is explicit recovery, not a directory scanner. Before linking, the helper\nchecks for a changed parent or alias, an altered/hardlinked record or backup,\ndigest or inode mismatch, and any existing public target. It restores only by\nno-clobber hard link, so a new claimant is preserved rather than overwritten;\nit never recursively removes unknown entries. A completed recovery is\nidempotent. The record is evidence to be independently verified, not an\nauthority to restore arbitrary private bytes: the helper accepts it only from\nthe recorded generated child of the original physical target parent, with the\nsame directory identity. Name the exact directory reported by the interrupted\nprocess and inspect an uncertain record manually. A non-cooperating process can\nstill swap pathnames after those checks and before Node.js `linkSync`; Node does\nnot expose a descriptor-bound link operation. Post-link identity verification\nthen fails closed and retains recovery evidence, rather than claiming recovery\nor deleting an uncertain name. If recovery itself is interrupted after the\nlink, the old public bytes and private backup can both remain; a later recovery\nrun preserves the public target and needs explicit operator resolution. The\nrecord is fsynced before the old public name is retired on platforms supporting\ndirectory sync, and the tested guarantee is recovery after a killed process;\nthis is not a claim of power-loss, storage-controller, NFS, or SMB durability.\nPaired flows retain their backup in private transaction staging. For `deliver`,\nthe pending journal and lock keep strict checkers fail-closed. The portable\nNode.js filesystem API has no pathname\ncompare-and-swap that both replaces an existing name atomically and refuses to\noverwrite a late claimant: `rename` would close the visibility gap only by\noverwriting that claimant.\n\nAfter ownership is established, `deliver` creates the journal before rendering\nand keeps it through the recoverable HTML/sidecar pair commit. It removes the\njournal only after that commit completes. A validation, render, or pair-commit\nfailure, or a process interruption, may therefore leave a journal. The journal\nis a safety barrier: `check`, `browser-check`, and `visual-check` fail closed when any directory\nentry exists at the journal or lock path, including an unreadable file,\nsymlink, or dangling symlink. Run deliveries targeting the same physical output\ndirectory serially; one attempt must finish or be recovered before another\nbegins.\n\nA successful sidecar has `schemaVersion: 1`, `status: \"current\"`,\n`command: \"deliver\"`, a unique `receiptId`, the diagram `type`, an absolute\n`input` path, an absolute `output` path matching the inspected\nartifact, and specification/artifact SHA-256 and byte counts. Checkers treat a\nmissing, malformed, unsupported, or inconsistent field as invalid. They also\nreject a sidecar symlink, including a dangling one. A checker binds provenance\nto the artifact bytes it actually checks and verifies that binding again before\nreporting success; a concurrent byte change fails. The provenance directory\nentry itself must be a single-link regular file: `deliver` and strict check fail\nclosed with `delivery/provenance-hardlink-unsupported` when it has another hard\nlink, without scanning for or guessing the sibling name.\n\nIf a currently verified owner fails after an older HTML exists, Archify writes\na new `status: \"failed\"` sidecar and leaves the journal until recovery is\ncomplete. An unreadable old HTML does not prevent that marker; its artifact hash\nand byte count may be absent. If the sidecar is locked or otherwise unwritable,\nArchify keeps the prior sidecar rather than deleting evidence, and the journal\nprevents checkers from trusting it. A rejected concurrent, stale, or invalid\nlock attempt does not write failed provenance. If ownership is lost, Archify\nreports `delivery/ownership-lost`, does not overwrite or remove the successor's\nartifact, provenance, journal, or lock, and does not claim recorded failed\nprovenance; a failure receipt may report `provenance: \"unrecorded\"`. If every\nmetadata path is unavailable, the same unrecorded status applies; no tool can\npreserve that fact across processes. Restore metadata-path access and complete\na successful `deliver` before trusting the output.\n\nArtifacts with no sidecar, journal, or lock remain supported for backward\ncompatibility and for the lower-level `render` command. Their checker receipts\nreport `provenance: \"unknown\"`; use `--require-provenance` to turn that state\ninto a non-zero failure when the workflow requires a successfully delivered\nartifact:\n\n```bash\nnode bin/archify.mjs check <output.html> --require-provenance\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\n## Output path contracts\n\nArchify intentionally separates durable authored paths from command-line paths:\n\n- Required authored `meta.output` is a portable POSIX-relative path such as\n  `reports/diagram.html`. It uses `/`, ends in a non-empty `.html` basename,\n  and cannot contain an absolute or drive-relative prefix, URI, backslash,\n  empty or dot segment, control character, unpaired UTF-16 surrogate, Windows\n  alternate-data-stream separator or invalid filename character, trailing dot\n  or space, DOS device name, or a component over either the 255-byte UTF-8 or\n  255-code-unit UTF-16 limit. It resolves from the current working directory\n  and must remain physically inside that directory, with an `.html` target,\n  after symbolic links are followed. The durable output/archive profile also\n  conservatively rejects a Windows 8.3 short-name shape such as `PROGRA~1`;\n  descriptive repo/Git POSIX paths use a separate profile and are exempt.\n- Explicit CLI output arguments use the active host's native syntax. They may\n  be relative or absolute, use native separators, and resolve outside the\n  current working directory. On Windows, ordinary drive-absolute, UNC, and\n  relative paths (including ordinary `.` and `..` navigation) are supported.\n  A system-resolved 8.3 spelling of an existing file or directory is accepted\n  when Archify can prove its physical identity; this native alias support does\n  not relax the durable output/archive profile's 8.3-shaped-name rejection.\n  Extended-length paths are limited to raw backslash-only `\\\\?\\C:\\...` and\n  `\\\\?\\UNC\\server\\share\\...` forms without dot segments; device namespaces,\n  malformed roots, drive-relative paths such as `C:file.html`, current-drive\n  roots such as `\\file.html`, alternate data streams, reserved device names,\n  invalid or trailing filename characters, and overlong components fail\n  closed. POSIX CLI paths retain POSIX filename rules rather than inheriting\n  Windows spelling restrictions. Every host rejects NUL, unpaired surrogates,\n  and components that exceed its supported bound.\n\nThese contracts are not interchangeable: an explicit CLI output does not hide\nan invalid durable `meta.output` (including a missing value), and `validate`\nchecks the authored output even when it does not publish to that path. A\nworkflow v1-to-v2 migration may explicitly receive a portable durable\nreplacement through `migrate workflow old.json new.json --to-schema 2 --output\nreports/diagram.html`; that value is written only to its separate verified v2\ndestination. This migration-candidate exception does not repair the source or\nbypass any non-output schema or compiler error. For every other repair, add a\nportable POSIX-relative `.html` path to `meta.output`; no schema-version change\nis otherwise required.\n\nRun `finalize` directly on a complete first candidate and after every repair edit. Its embedded validation checks the candidate before delivery; use standalone `validate` only for focused diagnosis. After an edit, omit any earlier `--candidate-sha256`, which binds the previous candidate. CLI HTML output paths must end in\n`.html`, including after symbolic-link resolution. Compare receipt paths must\nend in `.json`. A type mismatch fails before writing with\n`output/cli-extension` or `output/cli-resolved-extension`. These checks prevent\naccidental file-type overwrites; they do not sandbox explicit CLI directories\nor prevent replacement of an existing artifact of the expected type.\n\nUse final verified delivery only after the candidate is frozen:\n\n```bash\nnode bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality showcase --json\n```\n\nDeliver reads the specification once, writes those exact bytes to a private same-directory candidate snapshot, renders that snapshot, runs the complete artifact checker, and only replaces the target after all artifact checks pass. The JSON receipt includes SHA-256 and byte counts for both `specification` and `artifact`. Deliver adds a required [update notice](update-awareness.md) before running the checker. The hash binds the delivered bytes, and the receipt records `updateNotice`. The dismissible notice uses the top bar on wide Viewer diagrams when the title and toolbar leave space, and the footer otherwise. It includes a one-click copy button for a localized Agent update prompt and the official release notes link. Opening the page and copying the prompt work offline and make zero network requests.\n\nFor the ordinary agent handoff path, prefer the finalizer:\n\n```bash\nnode bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n```\n\n`finalize` invokes verified `deliver` once, reuses its embedded showcase\nvalidation result, then runs strict `check --require-provenance` and\n`browser-check --require-provenance`. It stops at the first failed or skipped stage\nand preserves that stage's full receipt. Its stdout is one compact JSON\nobject with gate statuses, bounded actionable diagnostics, artifact identity,\nand evidence paths. The same compact object is written atomically to\n`<output-stem>.finalize-summary.json`; use that file for normal failure repair. When diagnostics are truncated, `diagnosticSummary.omittedByCode` counts the unshown entries by diagnostic code without replacing their full subject and repair evidence in the full receipt.\nComplete stage receipts and timings remain available for auditing in\n`<output-stem>.finalize.json`. With `--out-dir`, both files are written there (unless an explicit `--receipt` overrides the finalize receipt path; the artifact HTML stays at the requested output path);\n`--receipt <path.json>` overrides the full receipt path and derives a distinct\n`<path>-summary.json`. Read the full receipt only when the compact summary is\ntruncated and its shown subjects and evidence cannot identify a coherent local\nrepair, or when complete audit evidence was explicitly requested. The compact\nreceipt reports `visualReview: \"not-requested\"`; the automated gate does not create images or require a perceptual reviewer. A compact `visualReviewRecommendation` retains positive crossover and route-detour metrics from the strict check so the author can apply the review escalation below without reading the full receipt. A recommendation does not change the machine exit code or claim that review happened. Its `affectedRoutes` identifies crossing pairs and detours (up to eight of each, with a truncation flag); the full strict-check `composition.routeReview` retains all affected relationships. Use these IDs to trace the routes in the captured default viewport. Detours may include `directCorridorBlockers`, identifying nodes between aligned endpoints. These are geometric review clues, not new validation failures or inferred main-path semantics. For a blocked main path or several tangled routes, follow [Architecture layout repair](architecture-layout-repair.md) and reflow the connected scene before tuning individual sides or labels. Preserve every semantic fact; retain unrelated positions only when their surrounding composition is already accepted.\n\nFor a measured automatic Architecture with a large unused leading area, the\ncompact receipt may include `layoutReviewRecommendation`. Its\n`composition.leadingSpace` evidence accounts for nodes, boundary titles,\nroutes and labels. Check whether that space is intentional; if not, reposition\nthe connected scene while preserving meaning and user-fixed geometry, then\nfinalize again. This suggestion changes no gate or exit status and requires\nno screenshot. A fixed canvas or uncertain measurement receives no suggestion.\n\nA passing finalizer receipt is sufficient evidence for all four gates. Merely\nnaming the gates or requiring each one to pass does not require replaying their\nstandalone commands. Replay an individual command only when the request\nexplicitly requires separate executions or focused failure diagnosis needs it.\n\nThe individual commands remain authoritative and backward compatible. Use\nthem directly for focused diagnosis, recovery, or when only one gate is\nrequired. A finalize failure does not relax any gate and does not turn a\npreserved older artifact into a current successful delivery.\n\n`finalize` discovers and starts private Chrome only after delivery and strict\nchecking pass. Failed input, repository-evidence, delivery, or artifact checks\ntherefore do not launch a browser. It loads the artifact only after current\nprovenance is verified. The browser gate retains every viewport, theme, and\nstability check; the browser closes at completion or a browser-stage failure.\nIts full stage receipt records `execution: \"in-process\"` and the equivalent\nstandalone `command` for replay. Chrome startup no longer overlaps the earlier\nstages, so successful runs may take slightly longer. This avoids unnecessary\nstartup on invalid candidates; it does not fix host sandbox restrictions on\nChrome startup or relax a browser gate.\n\nThe pair commit is recoverable, not a claim that two filesystem paths change\natomically or are durable across power loss. Journal finalization is part of\nthat commit: a caught failure while verifying or removing the journal rolls\nback the replaced files when possible and while ownership remains current. If\nownership is lost, the old attempt immediately stops renaming, rolling back,\nfinalizing the journal, recording failure provenance, or cleaning up shared\npaths. Any private staging or recoverable backups remain available and are\nidentified by the failure diagnostic. If restoration fails for another reason,\nthe failure receipt likewise identifies retained backups for recovery. A\nprocess interruption can leave the journal, backups, or private staging behind;\ncheckers then fail closed. Follow the reported recovery evidence before rerunning\n`deliver` serially on the same output. A failed attempt exits non-zero and never invokes an opener; it never\nauthorizes visual evidence collection.\n\nIf exclusive creation succeeds but lock initialization fails, Archify may\nrecord failed provenance and remove the incomplete lock only while its\ncapability still identifies that exact entry. A replacement is preserved.\nFilesystem and cleanup errors are reported separately from an active concurrent\ndelivery. An active, stale, unrecognized, or otherwise preserved lock\nindependently prevents checkers from accepting the prior artifact. Fix the\nreported filesystem error before retrying, and use another physical output\ndirectory if the lock path contains unrelated data.\n\nLock release is part of delivery completion. If the artifact/provenance pair\nhas committed and the journal has finalized but the matching lock cannot be\nremoved, `deliver` exits 1 with `delivery/lock-release`, preserves the lock,\ndoes not print a success receipt, and does not invoke an opener. The preserved\nlock keeps strict checkers fail-closed. Only after pair commit, journal\nfinalization, and lock release all succeed may `deliver` exit zero, print its\nsuccess receipt, or run `--open`.\n\nRun strict `check` after `deliver` exits zero. Run `browser-check` or optional\n`visual-check` only after that strict check exits zero. A failed marker,\nrecovery journal, or delivery lock makes every checker fail before accepting\nthe preserved HTML; report the diagnostics and complete a successful recovery\ndelivery before collecting new browser evidence.\n\nStatic `check` uses the same SVG path analysis for inspected relationships and\nstructural frames. It supports `M/L/H/V/Q/Z`, their lowercase relative forms,\nrepeated parameters, and finite numbers. Each `M` starts an independent subpath;\n`Z` closes only the current subpath. Separate subpaths never create connecting\nsegments that are absent from the drawing. Straight segments separated by a\nnon-collinear `Q` also remain separate in route analysis; curve sample points\ndo not become micro-segments in straight-route budgets or rhythm checks.\nSegment lengths and stretch are measured per continuous piece, while actual\nbends are summed per relationship. A relationship exceeding a budget is counted\nonce, and internal piece boundaries do not receive the short shared-trunk\nexception reserved for semantic endpoints.\n\nThis is not a promise of full SVG command support: `A/C/S/T` produce\n`artifact/svg-path-unsupported`; missing parameters, invalid numbers, and other\nsyntax errors produce `artifact/svg-path-malformed`. The checker exits non-zero\ninstead of skipping a bad path or waiting indefinitely. Path failures append a\n`svg_path_data` check; normal valid artifacts retain the existing nine checks.\nDiagnostics carry the inspected `pathIndex`, `role`, available relationship/frame\n`id`, parsing `tokenOffset`, available `command`, and `reason` so the generating\nsource can be located and repaired. `pathIndex` is one-based; `tokenOffset` is a\nzero-based UTF-16 offset in `d` after numeric character references are decoded.\nApparent tags in comments, CDATA, and attribute text are ignored. Passing static\npath checks does not establish browser or perceptual visual acceptance.\n\n<details>\n<summary>中文说明</summary>\n\n静态 `check` 对受检关系线和结构边界的 SVG 路径使用同一解析结果，支持\n`M/L/H/V/Q/Z` 及其小写相对形式、重复参数和有限数值。每个 `M` 开始独立\n子路径，`Z` 只闭合当前子路径；子路径之间不会被拼接成图中不存在的线段。\n非共线 `Q` 前后的直线也保持分离，不会把曲线采样点计为直线路由预算或\n节奏检查中的微线段。线段长度和伸长率按连续片段测量，真实转弯数汇总到原关系；超预算关系\n只计一次，内部子路径断点不享有语义起终点的短共享线例外。\n这不是完整 SVG 命令集的支持承诺：`A/C/S/T` 返回\n`artifact/svg-path-unsupported`；缺少参数、非法数值等格式错误返回\n`artifact/svg-path-malformed`，检查以非零状态结束，不跳过坏路径或无限等待。\n路径失败时追加 `svg_path_data` 检查；普通有效产物仍保留原来的 9 项检查。\n诊断携带受检路径的 `pathIndex`、`role`、可用的关系/边界 `id`，以及解析位置\n`tokenOffset`、可用的 `command` 和 `reason`，用于定位并修复生成路径的来源。\n`pathIndex` 从 1 开始；`tokenOffset` 是数字字符引用解码后的 `d` 字符串中\n从 0 开始的 UTF-16 位置。注释、CDATA 和属性文本中的伪标签不参与检查。\n静态路径检查通过仍不代表浏览器或感知视觉验收通过。\n\n</details>\n\nThe delivery interface exposes four separate claims:\n\n1. `deliver` proves deterministic artifact checks and byte identity.\n2. `browser-check` collects required automated browser evidence from the exact artifact without capturing images.\n3. `visual-check` optionally adds artifact-bound screenshots and a contact sheet.\n4. Perceptual visual review records a human or image-capable reviewer's judgment.\n\nPassing one claim never implies the others. Never claim that the deterministic receipt includes browser or perceptual review evidence.\n\n## Architecture Diagnosis offer\n\nAfter a passing `finalize architecture` with `--repo-root`, the full receipt\nand compact summary include `codeAnalysisOffer` if a bounded scan finds\nsources eligible for the default analysis. The offer includes the effective\nfinalize `quality`, passes it in `start.argv`, and records a `dependencies`\nstatus of `installed` or `missing`. Finalize performs these checks without\nstarting analysis or installing anything.\n\nEnd the delivery summary with the capability section below, in the user's\nlanguage, once per repository in the task. It is part of the summary, not a\nseparate question, so users learn what Diagnosis does even if they never\nreply. Skip it if the user already asked for or declined analysis in this\ntask. Keep the bullets; adapt only wording, not the claims. If `dependencies`\nis `missing`, the installed Skill copy is incomplete: replace the closing line\nwith the reinstall line, because analysis cannot start. If the offer includes\n`linkedDiagrams: true`, add that sibling-diagram links work from the original\ndelivered diagram, not from the Diagnosis server. Mention the diagram button\nonly when `codeAnalysisOffer.diagramButton` is `true`; otherwise drop that\nsentence. Start only after the user agrees.\n\n**中文**\n\n**还可以：架构诊断**（Archify 自带，在本机运行）\n- **环形星图**：几千个文件、几万个函数之间的依赖一眼看全\n- **可旋转的 3D 模型**：换个角度看模块怎么连在一起\n- **组件问题数**：直接标在这张架构图上，哪里最拥挤、哪里有循环依赖、哪些依赖图里没画\n- 每条发现都能点开看源码，也能一键交给 AI 修\n\n回复「好」我就启动。图右上角的「架构诊断」按钮也随时能看到这个功能。\n（依赖缺失时，最后一句改为：分析组件缺失，需要先重新安装 Archify 才能使用。）\n\n**English**\n\n**Also available: Architecture Diagnosis** (built into Archify, runs locally)\n- **Radial star map**: dependencies across thousands of files and functions at a glance\n- **Rotatable 3D model**: see how modules connect from any angle\n- **Issue counts per component**, right on this diagram: where things are most crowded, where dependencies cycle, and which dependencies the diagram doesn't show\n- Every finding opens its source and can be handed to an AI as a fix task\n\nReply \"yes\" and I'll start it. The **Code Analysis** button at the top right of the diagram shows this anytime.\n(If dependencies are missing, the closing line becomes: The analysis components are missing; reinstall Archify to use it.)\n\nAfter consent, run `start.argv`. Add `--locale zh-CN` for Chinese or\n`--locale en` for English if needed. For a repository with several supported\nlanguages, select the adapter with `--language` as described in the\n[Code Analysis guide](../modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation).\nShare the printed local URL. The original architecture diagram appears first.\nClick **Code Analysis** (**架构诊断** in Chinese) to run analysis and open the\ncomponent findings, radial star map, and Atlas 3D views.\n\n## Comparison presentation changes\n\nArchitecture comparisons include authored `meta.translations` in presentation changes. Adding, removing or editing translations changes `summary.presentationChanged`; reordering translation keys does not. An empty translation object is equivalent to an omitted catalog for presentation classification; the canonical source digest still records the authored representation. Component, relationship, boundary and repository-provenance classifications remain independent.\n\n## Recovering a failed comparison\n\n`compare` commits an HTML artifact and its JSON receipt as a pair. If that commit\nfails, it attempts to restore the previous files. A complete rollback removes\nthe temporary directory as usual.\n\nIf a previous file cannot be restored, compare exits non-zero with\n`delta/commit-rollback-failed` and retains the recovery directory. In the JSON\nfailure receipt, `diagnostics[].evidence.recoveryDirectory` identifies that\ndirectory and `recoveryFiles` lists `{ backup, target }` paths for the files whose\nrestoration failed. Human-readable diagnostics also print the recovery paths.\n\nResolve the filesystem error, inspect the current targets, and restore each\nlisted backup to its corresponding target before retrying. Keep the recovery\ndirectory until both previous files have been recovered and verified; it can\nalso contain rejected candidate files, which must not be mistaken for backups.\nSuccessful comparisons and failures before commit retain their normal cleanup.\n\n## Automated browser evidence\n\n`finalize` runs the required browser gate against the exact trusted HTML without\nrerendering or modifying it. For focused diagnosis, the equivalent standalone\ncommand is:\n\n```bash\nnode bin/archify.mjs browser-check <output.html> --json --require-provenance\n```\n\nThe zero-dependency command uses Chrome/Chromium (or Microsoft Edge)\nthrough the DevTools pipe. `ARCHIFY_CHROME` is authoritative when set, including\nan invalid path: Archify does not silently fall back to another browser. Automatic\nWindows discovery checks every Chrome/Chromium install location and PATH command\nfirst, then Edge under `%ProgramFiles(x86)%`, `%ProgramFiles%`, and `%LocalAppData%`,\nfollowed by `msedge` on PATH. On macOS and Linux, discovery also checks\nChrome/Chromium first, then the Edge application bundle (macOS) and\n`microsoft-edge`/`microsoft-edge-stable` on PATH. It\nmeasures light-theme containment at 1440×900, 1600×1000, 1920×1080, and\n2048×1320, and verifies the requested light theme at all four viewports, the dark\ntheme at both endpoints, and READ/Still runtime states. A requested theme that\nresolves to a different theme fails with measured evidence. It creates one\n`<output-stem>.browser-check.json` receipt and no screenshots or contact sheet.\nPass `--out-dir <dir>` to place the receipt in a separate evidence directory.\nThe receipt binds the artifact SHA-256 and byte count, identifies\n`evidenceKind: \"automated-browser\"`, and reports\n`visualReview: \"not-requested\"`.\n\nHorizontal overflow always fails. Normal document-level vertical scrolling is\naccepted only with a renderer-declared contract and measured readable text.\nAutomatic canvases declare `data-reader-fit=\"intrinsic-height\"` (height fitting)\nor `data-reader-fit=\"width-first\"` (Sequence and Waterfall reading width); their adaptive\nReader must reach its readable width and expose `data-reader-overflow=\"authored\"`.\nArchitecture with an explicit `meta.viewBox` instead declares\n`data-diagram-type=\"architecture\"` and `data-reader-fit=\"authored-height\"`:\nits SVG coordinates, aspect ratio and existing Reader width behavior stay\nunchanged. Its full SVG must remain inside the diagram panel without internal\nscrolling or clipping, and the document must permit vertical scrolling.\nThe receipt records `verticalScrollAccepted: true` and\n`overflowDisposition: \"readable-vertical-scroll\"`. Missing or unknown declarations,\nexplicit viewBoxes in other modes, unreadable text, horizontal overflow,\nclipping and Viewer chrome collisions remain failures. Do not add an internal\ndiagram scroller or hide overflow.\n\n`browser_evidence` in the handoff records only the outcome of this automated\ncommand:\n\n- `passed` maps from exit 0 and receipt `status: \"pass\"` after every required measurement completes and passes.\n- `failed` maps from exit 1 and receipt `status: \"fail\"` when the inspection finds a defect, the command fails, or a runtime error leaves the evidence incomplete.\n- `skipped` maps only from exit 2 and receipt `status: \"skipped\"` when no supported browser is available and the inspection does not run.\n\nRuntime failures leave incomplete evidence and must not be normalized to\n`skipped`. They do not invalidate an already successful deterministic delivery.\nRetry an environmental failure in a browser-capable execution context when\npractical. Keep the packaged transport unchanged unless the failure reproduces\nthrough that seam in a capable environment.\n\nOn Windows, Chrome/Edge startup relaunches can lose the inherited DevTools\npipe before any response arrives. Archify removes a standalone\n`__COMPAT_LAYER=DetectorsAppHealth` from the browser child's environment only\n(case-insensitive name and value); the parent environment, unknown layers,\ncombined layers, and privilege-related compatibility settings are unchanged.\nThis targets the reported non-elevated Git Bash app-health case, not every\nAppCompat mode. Elevated-shell relaunches remain unsupported: rerun from a\nnon-elevated PowerShell opened normally, outside an elevated or compatibility-mode\nparent. Archify does not suppress browser de-elevation or disable the sandbox\nas a relaunch workaround. A zero-response startup diagnostic suggests this\nremedy without claiming that elevation or AppCompat caused every pipe failure.\n\nA provenance failure exits before browser inspection and persists a failed\nbrowser-check receipt bound to the attempted artifact. If the failure receipt\ncannot be written, the diagnostic names that incomplete evidence.\n\nBoth browser commands inspect the exact delivered HTML without modifying or rerendering it.\n\n## Sequence width review\n\nA passing `finalize` may report `layoutReviewRecommendation.action: \"inspect-sequence-width\"`. Its `evidence` measures the fixed participant columns' unused right-hand space after accounting for message labels, notes and segment titles. This advice adds no warning, failure, screenshot requirement or automatic geometry change.\n\nA passing `validate --json`, `deliver`, or `finalize` receipt may carry `diagnostics[]` entries with `severity: \"warning\"` for Viewer locale fallbacks (`i18n/*`). They fail no gate. When the artifact should be fully localized, repair the listed keys from their `evidence` and rerun `finalize`.\n\nSequence canvases with omitted `meta.column_fit` use `spread`, whether or not `meta.viewBox` is supplied. An authored viewBox remains authoritative; infeasible participant capacity fails without silently enlarging it. Explicit `meta.column_fit: \"fixed\"` preserves historical fixed columns. For a candidate whose fixed-column width suggestion remains, first check whether the fixed geometry is intentional. Only when a change to that geometry is authorized, save the candidate, set only `meta.column_fit` to `\"spread\"`, and rerun the complete `finalize` once with `--out-dir <folder>/width-review`. Keep participant order, messages and their y positions, labels, notes, sources and canvas dimensions. If that attempt fails, restore the candidate and finalize it with `--out-dir <folder>/width-restore`; report the remaining layout suggestion rather than iterating. Preserve intentional fixed geometry and disclose the suggestion when a change is not authorized. To retain historical fixed coordinates for an older omitted-fit input, set `meta.column_fit: \"fixed\"` explicitly. This review is about horizontal composition; a passing receipt still does not claim perceptual approval.\n\n## Optional capture evidence\n\n`visual-check` remains backward compatible for a requested or escalated\nperceptual review:\n\n```bash\nnode bin/archify.mjs visual-check <output.html> --summary --require-provenance\n```\n\n`--summary` returns compact JSON with all diagnostics and absolute paths to the complete receipt, contact sheet, and every screenshot. For a chosen visual review, inspect the relevant captures; capture success is not perceptual approval. `--json` retains the full receipt output for existing consumers. Both modes run the same checks and keep the same exit status. If cleanup fails after publication, the summary retains the final failure diagnostics and `publication` recovery details; the linked receipt records the earlier committed evidence.\n\nIt performs the same automated browser measurements, captures light/dark\nscreenshots at 1440×900 and 2048×1320, and writes four viewport PNG sidecars,\none relative-path HTML contact sheet, and one JSON receipt. `--out-dir <dir>` moves all of these sidecars together.\nOpen the HTML contact sheet in a browser or inspect the viewport PNGs with an image reader. Its receipt reports `visualReview: \"pending\"` because captures do not themselves\nmake a perceptual judgment. Capture and provenance failures follow the ownership rules below.\n\nThe receipt, contact sheet, and four PNGs form one owned evidence set. Before\ncapture, `visual-check` freezes every requested directory entry, its\ncanonical write slot and physical parent, and the target's absent/file state,\ntype, device/inode identity, and mode. Hard-linked evidence targets are not safe\nwrite targets. All candidate files are created exclusively inside one random,\nprivate staging directory beneath the physical evidence directory; the receipt\nis published last. Each staged candidate must have exactly one hard-link name\nbefore publication. The no-clobber publish link temporarily gives the staged\nand final names a link count of two; unlinking the verified staged name must\nleave the final entry with a link count of one. An unexpected external hard\nlink fails closed and its alias is never removed.\n\nChrome inspects one identity- and content-checked copy of the captured artifact\nin a private local temporary directory, so browser file loading does not depend\non UNC or long-path support. The six publication candidates remain on the\nevidence volume. Both temporary directories are cleaned without recursively\ndeleting unknown contents; retained entries include their recovery locations.\n\nImmediately before committing anything, `visual-check` re-resolves and verifies\nthe complete six-path set. An absent-path claimant, existing-path replacement,\nsymbolic-link or dangling-link retarget, parent-topology change, hard link, or\nindeterminate identity fails closed with `viewer/evidence-path-conflict`. The\nclaimant and every other final evidence path remain untouched. Cleanup removes\nonly this run's staged or published entries after rechecking their captured\nidentities; a changed or unknown entry is preserved.\n\nAn existing visual evidence set is replaceable only when a regular\n`visual-check` receipt proves ownership of the same artifact and evidence\ndirectory, and its exact sidecar manifest matches every existing contact-sheet\nor PNG byte count and SHA-256 digest. A missing, malformed, unknown, mismatched,\nor incomplete ownership record never authorizes deletion. Failed and skipped\nruns retire prior screenshots/contact sheets only as part of the same verified\ntransaction when that ownership proof succeeds; otherwise they preserve all\nunknown evidence and report `viewer/evidence-path-conflict`.\n\nThis rule also applies when Chrome is unavailable or provenance fails before\nbrowser inspection: neither path may blindly delete stale-looking evidence. A\nverified owned set may be recoverably retired before publishing a skipped or\nfailed receipt; unowned evidence remains intact. These outcomes do not invalidate an already\nsuccessful deterministic delivery and do not turn a perceptual visual review\ninto passed or failed. Retry an environmental failure through the supported\ncommand in a browser-capable execution context when practical. Keep the\npackaged transport unchanged unless the failure reproduces through that seam in\na capable environment.\n\n`browser-check` applies the same private-snapshot, identity, ownership, and no-clobber rules to its single JSON receipt. Its namespace is separate from `visual-check`, so a browser-only rerun cannot remove capture evidence.\n\n## A new candidate at an existing output path\n\nBrowser evidence belongs to exact artifact bytes. After editing a candidate whose previous HTML already has browser evidence, choose a fresh evidence directory before running the next `finalize`; this preserves the old receipts and captures without an avoidable ownership-conflict retry. `--out-dir` relocates the new browser-check receipt and, by default, the finalize receipt and summary. An explicit `--receipt` overrides the finalize receipt path; its summary follows that path. Successful delivery still rewrites the requested HTML and its sibling `*.delivery.json`. Earlier browser or visual evidence remains bound to its original artifact bytes and must not be treated as evidence for changed HTML:\n\n```bash\nnode bin/archify.mjs finalize architecture candidate.json diagram.html --quality showcase --repo-root <root> --out-dir diagram.review-2 --json\nnode bin/archify.mjs visual-check diagram.html --out-dir diagram.review-2 --summary --require-provenance\n```\n\nThe evidence directory is not an archive of the HTML. Copying the HTML there alone does not rebind receipt paths or provenance. If a historical snapshot is needed, preserve the candidate and artifact separately before overwriting them; do not assume copied receipts validate a relocated artifact.\n\nKeep the requested HTML path stable. Use a new revision directory for each changed candidate, and retain the same directory for retries of unchanged bytes. For a diagram without repository evidence, omit `--repo-root`. Let the commands create their output directory. A prior validation failure that produced no HTML or browser evidence needs no new directory. Never remove unknown evidence to make a retry pass.\n\n## Optional opening\n\nAdd `--open` only when the user wants an immediate local preview. It runs after\nthe verified pair commit has completed, its recovery journal has been removed,\nand the delivery lock has been released successfully. It uses one argument-array\nOS opener with a five-second bound on macOS and Linux, and a fifteen-second bound\nfor PowerShell startup on Windows. The receipt records `open.status`; failed or\nunavailable launch attempts also include normalized `open.failure` details.\nKeep it off for CI, unattended agents, and non-interactive environments.\nFailure or unsupported opening does not invalidate delivery; its\nstatus proves only whether the local opener invocation succeeded.\n\n## Last-Good Live Preview\n\nFor an active desktop authoring loop only:\n\n```bash\nnode bin/archify.mjs preview <type> <input>.json <output>.html --quality showcase\n```\n\nPreview watches one explicit input on loopback, binds each stable digest to a private snapshot, and advances only after the existing verified delivery pipeline passes. Invalid, half-written, deleted, or superseded input leaves the previous verified revision on screen and on disk. Identical bytes do not rebuild or reload.\n\nThe preview runtime ships inside the zero-dependency Skill ZIP and must work without `node_modules`.\n\nNever start it by default. Do not use it for CI, unattended agents, remote sharing, or mobile use. `--no-open` is only for a user who will open the printed local URL or for loop testing. Stop it with Ctrl-C before handoff. The first Ctrl-C drains the active delivery without publishing it; a second Ctrl-C forces shutdown of both delivery processes and HTTP connections, including incomplete requests. Shutdown preserves the last verified artifact and removes only staging files whose ownership can be verified. If delivery is interrupted before its receipt reaches Preview, unconfirmed files and recovery material may remain in the private staging directory; shutdown does not recursively delete unknown contents. Server state, port, source path, diagnostics, error text, and reload tokens must never enter the generated artifact or any export.\n\n## Per\n\n<!-- File: archify/references/viewer-runtime.md (Tokens: ~1197 | Category: anthropic-skill) -->\n# Viewer Runtime reference\n\nRead this only when the user asks for a reader-facing capability. Ordinary generation does not require implementing or re-documenting these features; they are already in the generated HTML.\n\n## Exploration\n\n- Diagram Guide lists current actions and shortcuts. Open it with the guide button or `?`; it never opens automatically.\n- Reading Depth starts at READ at the default 100% scale, reveals FULL detail at 175%, and falls back to MAP only below 100%. Focus, route, and semantic interactions reveal their exact facts at any scale.\n- Semantic Lens summarizes selected node/relationship kinds without changing authored geometry.\n- Intent Trace previews a fine-pointer or keyboard target before committed focus.\n- Node Finder searches labels and stable IDs.\n- Semantic Passport opens on focus, shows authored upstream/downstream facts, supports a copyable deep link, has an explicit close action, closes on true outside activation and Escape, and never enters canonical export.\n- Semantic Radar mirrors the visible viewport and authored graph without becoming a second source of truth.\n- Direct Relationship Pin makes a unique compiled relationship operable while preserving the authored line and stable relationship identity. It must fail closed on conflicting source/target/label/ID metadata.\n- Route Probe resolves exactly two endpoints over authored directed relationships. It never infers a route from geometry.\n\n## Embedded reading addresses\n\nA host displaying the native reader in an opaque `srcdoc` frame may set\n`data-reading-link-template` on that reader's `html` element. Supply an absolute\nHTTP, HTTPS or file URL containing exactly one `{state}` marker, for example\n`https://example.test/architecture#page=mechanism&reader={state}`. Native Focus,\nRelationship, Reach, Route and Lens copy actions replace the marker with their\npercent-encoded opaque query state. The host keeps its page identity and restores\nthat value as the native frame's hash; it never parses or reconstructs queries.\n\nAbsent configuration preserves standalone links. Invalid, credential-bearing or\nunsupported URL templates make copying fail without accessing the clipboard.\nThis seam changes copied addresses only, not query parsing, history, permissions,\nembedding isolation or authored geometry. It adds no network or storage surface.\n\n## Motion and presentation\n\nFor a narrated walkthrough with camera framing, explanations, captions and\nsynchronized audio, use [Story authoring](story-authoring.md). The `story attach`\ncommand adds Story to the native motion control and Story video to Export.\nThe player loads on first use and follows the existing preset and theme controls.\nPlayback schedules two short audio buffers ahead instead of synthesizing the whole timeline.\nVery large video exports are rejected before rendering. Use\n`Archify.story.exportVideo({start, seconds})` for a shorter range when needed.\n\nEvery rendered diagram enables reader-controlled Live/Still motion by default. In Live, every edge runs a small light show on one shared cycle: a comet (glow, halo, tail, head, plus a dimmer echo on every edge) cascades downstream, leaves a soft wake, and lands as a ripple on the target node, while nodes enter once and then glow on the same cycle with authored-step staggering. Phases follow the authored step order (source-node rank, chronological in sequence diagrams); the flow rides a separate Viewer overlay and the original line styles and arrowheads remain intact. Compact edges receive a larger, brighter comet; echoes stay dimmer. With no saved preference, new pages start Still. Choosing Live starts continuous flow and saves that preference; choosing Still stops it and clears the saved Live preference. Existing saved Still preferences remain Still. Semantic exploration temporarily owns the motion budget, and continuous flow resumes when that action releases it. Diagrams without connections retain their bounded node entrance rather than inventing a flow. Omit `meta.animation`; historical `\"trace\"` and `\"none\"` values remain accepted for input compatibility and do not change this default. Reduced motion, page hiding, print, and canonical export preserve complete static meaning. Presentation Stage changes viewer chrome and framing, never authored geometry. This is not a mobile product feature; narrow layouts get containment only.\n\n## Canonical exports\n\nThe export menu can copy/download full-diagram PNG, download JPEG/WebP, download a dual-theme SVG, and record a trace-enabled WebM. Viewer state—Guide, Lens, finder, focus, route, camera, radar, presentation, motion ownership, and temporary overlays—must be removed from canonical export.\n\nOpening, closing, or completing an export preserves the live Focus/Reach selection for continued exploration. Export-owned download activation is not outside dismissal; genuine outside activation and Escape retain their existing behavior. Full-diagram PNG/SVG exports still contain the complete canonical diagram, while the Reach Share Card communicates the active authored closure.\n\n### Route Share Card\n\nAfter a real directed Route Probe resolves, the reader may use **Export → Route Share Card**. It reuses the exact ordered route snapshot and the shared Share Card seam: `format=share-card`, `variant=route`. The isolated clone may use only static `data-share-route-*` decoration. It is download-only, fails closed for stale/unreachable/conflicting routes, and never becomes the canonical artifact.\n\n### Reach Share Card\n\nAfter a non-empty authored reachability query, the reader may use **Export → Reach Share Card**. It consumes the already resolved upstream/downstream node and edge set without rerunning traversal: `format=share-card`, `variant=reach`. The isolated clone may use only static `data-share-reach-*` decoration. It is download-only. Call it authored reachability—not impact, blast radius, breakage, or runtime causality.\n\n## Truth boundary\n\nViewer exports are communication assets. They do not replace the checked HTML, the deterministic delivery receipt, or a real visual review. Do not add a hosted service, storage surface, dependency, schema branch, or mobile product surface for these viewer-only capabilities.\n\n<!-- File: archify/SKILL.md (Tokens: ~5353 | Category: anthropic-skill) -->\n---\nname: archify\ndescription: \"Create validated architecture, workflow, sequence, data-flow, lifecycle/state, ERD, class, tree, timeline, and waterfall diagrams as explorable standalone HTML with dark/light themes, motion and image/SVG/WebM export. Accept requirements or Mermaid; inspect repository evidence for code-backed diagrams. Also investigate local repository architecture health, coupling and refactoring scope with source-backed Code Analysis. Use when visualizing systems, API calls, pipelines, schemas, histories, timings, or everyday steps, parts, relationships and states. Also turn an answer into a one-page explainer, with the conclusion first, structured panels, native diagrams and charts, when the user asks for a page, an explainer or an answer to share (做成一页, 用页面讲), and by default unasked for a complex flow, diagnosis, comparison or test report; an [archify explainer: on-demand] rules line limits pages to requests. Optionally add a guided story and video export to an existing native diagram. Not for dashboards.\"\nlicense: Apache-2.0\nmetadata:\n  version: \"3.3\"\n  author: tt-a1i\n---\n\n# Archify\n\nCreate checked HTML as a native diagram, explainer, story, or standalone Code Analysis workbench.\n\nRun commands from your working directory. Unless the user names another location, give each new artifact request its own folder `.archify/<type>-<slug>-<YYYYMMDD-HHMMSS>/` there (local time, chosen once): keep the candidate and `<slug>.html` in it and reuse it for repairs. Native diagrams use `candidate.json` with `meta.output` relative to the working directory; explainers may use `candidate.archify.md` and a portable output filename. A later request gets a new folder. Replace `bin/archify.mjs` in every command with the installed package's absolute path, or its path relative to your working directory; CLI input and output paths resolve from that directory.\n\nFor a native diagram of a real codebase, read [Repository authoring](references/repository-authoring.md) while tracing the requested behavior. A system description uses the native steps below; a frozen candidate uses the handoff path.\n\n## Choose the artifact\n\n- For drawing a system, flow, schema or history, use a native diagram and the Type router. Deliver the requested diagram through `finalize`; code analysis is a separate mode.\n- For local repository architecture health, module coupling, cycles, layer violations, large files, complexity hotspots or refactoring orientation, use Code Analysis below; the agent handles commands and no architecture JSON is required.\n- For a guided walkthrough, animated/static dual-theme SVG, interactive stage player, or 1080p MP4/WebM video over one or more native diagrams, read [Story authoring](references/story-authoring.md). Use `story draft`/`attach` to add playback to a native Viewer, or `story validate`/`svg`/`stage`/`video` for declarative component choreography.\n- Only when the user explicitly asks to explain or visualize a pull request, a branch change or a `git diff`, or to attach change diagrams to a PR, or names the companion skill `archify-pr` when installed, read [PR review authoring](references/pr-review.md) first: it covers the three-dot diff, change-marked merged-superset views and the `pr validate` / `pr build` / `pr attach` loop.\n- Use `explainer` when the user asks for the answer as a page: a page, one page, an explainer, something to share (“做成一页”, “用页面讲”, “answer with a page”).\n- Explainer mode is `proactive` by default. A rules line `[archify explainer: <mode>]` in context selects another; an instruction in the conversation overrides it for that conversation.\n  - `proactive` (default, no line needed): also make a page, unasked, when the answer is a complex flow or process, a diagnosis or troubleshooting result, an option comparison, trade-off or decision, a test or review report, or a plan, and needs a table, steps or several sections to be read well.\n  - `on-demand`: make a page only when asked; otherwise answer in text or draw the requested diagram.\n  - `always-on` (opt-in only): every reply that reaches a conclusion also gets a compact page of at most four panels.\n- In every mode a page needs a conclusion with some structure behind it. Chat, short or one-line answers, routine status updates (“done, tests pass”), raw command output, a requested native diagram and any reply where the user asks for text only or no page (“只要文字”, “不用做页面”) get none. Make at most one page per reply, and none when the user names another page tool or another skill already made a page for that reply.\n- To change the mode, only when the user asks (“只在我要求时做页面”, “always make a page”), write or replace one `[archify explainer: <mode>]` line in the current agent's global rules file (such as `~/.codex/AGENTS.md`, `~/.claude/CLAUDE.md` or `~/.config/devin/AGENTS.md`) and name the file, for example `[archify explainer: on-demand] Make Archify explainer pages only when I ask for one.`; deleting the line restores `proactive`. Never switch to `always-on` unasked.\n- For `explainer`, read [Explainer authoring](references/explainer-authoring.md) for its conclusion, reasons, scope, board layout and optional native diagrams. Write the complete draft, then run `finalize explainer` for validation, atomic delivery and artifact checks. Use panel patch for local content revisions.\n\n## Existing candidate handoff\n\nWhen the user supplies a frozen candidate, run `finalize` first as one CLI invocation. Its passing receipt completes the automated gates; follow any visual review recommendation under Delivery before claiming visual quality. For repair, follow step 5.\n\n`finalize` includes a bounded update check in its delivery receipt; see Update awareness.\n\n## Native diagram authoring\n\nUse this path for ordinary generation. Read branch references only when their stated trigger applies.\n\n1. Choose `architecture`, `workflow`, `sequence`, `dataflow`, `lifecycle`, `erd`, `class`, `tree`, `timeline`, or `waterfall` from the question.\n2. Use the exact schema and example paths in the Type router without listing their directories. Read [Authoring defaults](references/authoring-defaults.md) and the mode's example in a bounded batch separate from project documents and complete schemas so neither is truncated; recover any missing section before writing. For a new Architecture, use `\"layout\": {\"mode\": \"auto\"}` and leave component positions to the renderer. Take component and relationship fields from the matching showcase example. Preserve any layout the user supplied. For every mode except Architecture, also read the mode and common schemas. Read the relevant schema definition before choosing any new field, enum, or constrained text, especially boundary kinds. Examples teach shape, not facts. Use fresh IDs, wording, and layout. Go directly to the candidate without preliminary help, doctor, starter validation, temporary diagrams, or output-path listing. Query brands only for an explicitly requested mark; read [Brand marks](references/brand-marks.md) for an unknown mark with a user-provided URL.\n3. Once the requested scope and, for a real codebase, [source evidence](references/repository-authoring.md) are covered, write the complete candidate directly without planning coordinates in prose. Choose Architecture abstraction and connected placement using Authoring defaults before coordinates: show the main user journey and necessary branches, preserve control roles and behavior-changing conditions, and leave enough room for actual relationship labels. No node, relationship, source, view, card, or boundary count is a target or ceiling. Use automatic routes first; add explicit routing only for necessary branch, return, supplied geometry, or measured repair. Set `meta.quality_profile` to `\"showcase\"` unless the user requests dense `standard`. For a grid ERD with automatic canvas, placement and routing, omit `layout.entityW` and entity `width` to fit fields. With a fixed view box, pinned table or manual route, size wide tables explicitly. For ERD, use a table-first layout: show every physical column in `entities[].attributes`, keep its SQL type and source comment, state every key role a column carries (`key` takes a role or a list, so a junction column is `[\"pk\", \"fk\"]`, and every `fk` column also needs `references` like `\"orders.id\"`), and never move columns into cards as a substitute for the table. Classify tables into functional domains before placement, give each domain a concise `tag`, and place its members in one solid rectangle of grid cells — a single row, a single column, or a filled rectangular block, not an L or diagonal. A tagged table always needs `row`/`col`, because absolute coordinates have no grid cells and a domain whose tables do not fill one rectangle cannot be drawn as a band: the renderer reports `erd/domain-not-drawn` instead of publishing a diagram that cannot name the domain. A multi-domain schema reads best as one domain per column — each `tag` a vertical run — because the reader scales a wide canvas up to the reader width and shrinks a tall one until the page fits, so the wide arrangement is the one that stays complete and legible inside a laptop viewport. A schema-first ERD over roughly 8 tables or 50 fields is itself a dense map: author its first complete-field pass at `standard` and upgrade only once the layout still reads.\n4. Once the complete first candidate is written, run `finalize` directly. Its first gate is showcase validation; successful first drafts need no separate pre-validation. Keep the candidate unchanged while the command runs:\n\n   ```bash\n   node bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json\n   ```\n\n   For a repository-backed candidate, include evidence on the first draft and use the complete first command: `node bin/archify.mjs finalize <type> <candidate.json> <output.html> --repo-root <repo-root> --quality showcase --json`. Pass the `--quality` that matches `meta.quality_profile`, such as `standard` for a dense first ERD pass.\n\n   A passing receipt proves the included `validate`, `deliver`, strict `check`, and real-browser `browser-check` gates passed. Use its compact summary; run standalone commands only for a separate request or focused failure diagnosis. After a passing Architecture finalize with `codeAnalysisOffer`, end the delivery summary with the [Architecture Diagnosis section](references/delivery-contract.md#architecture-diagnosis-offer) in the user's language, once per repository in the task. Skip it if the user already asked for or declined analysis. Wait for yes before running the offered command.\n\n5. A non-zero exit is never success. Read compact stdout or `evidence.summaryReceipt`, then [repair the failed gate](references/delivery-contract.md#failed-finalize-and-candidate-repair), including its repair limit. Preserve requested meaning and source evidence. For several tangled Architecture routes, read [Architecture layout repair](references/architecture-layout-repair.md); for measured field or geometry failures, read [Authoring contract](references/authoring-contract.md). Edit the connected neighborhood and rerun the complete `finalize` command from step 4. Once a run has reached `browser-check`, the output path owns that evidence: give every later run its own `--out-dir <folder>/review-<n>`.\n\n## Update awareness\n\n`finalize` and standalone `deliver` include `update` in their receipts. Do not run a separate check for the same delivery. If `update.noticeRequired` is true, read `references/update-awareness.md` and keep one compact update notice in your final response to the user, even after a quality gate fails. For a task with several diagrams, mention the update once in the final response. Snooze or ignore a reminder only when the user explicitly asks; never install or update on your own initiative.\n\nBefore the first candidate, use the authoring references and relevant repository source, not Archify implementation or tests. Inspect Archify implementation if diagnostics remain unactionable after focused repairs.\n\n## Type router\n\n| Type | Use for | Schema | Example |\n|---|---|---|---|\n| `architecture` | Components, services, cloud/security boundaries, infrastructure; what something everyday is made of | `schemas/architecture.schema.json` | System descriptions, services, libraries, and CLI repos: `examples/web-app.architecture.json`; deployment repos: `examples/production-deployment.architecture.json` |\n| `workflow` | Processes, approval gates, tool calls, runbooks, CI/CD; plans and step-by-step life processes | `schemas/workflow.schema.json` | `examples/agent-tool-call.workflow.json` |\n| `sequence` | API call chains, request lifecycles, async traces, returns; back-and-forth between people | `schemas/sequence.schema.json` | `examples/cache-miss-request.sequence.json` |\n| `dataflow` | Pipelines, ETL/ELT, lineage, governance, consumers; where money or documents go | `schemas/dataflow.schema.json` | `examples/product-analytics.dataflow.json` |\n| `lifecycle` | State/status transitions, retries, waiting and terminal states; where an application or order stands | `schemas/lifecycle.schema.json` | `examples/deployment-release.lifecycle.json` |\n| `erd` | Tables/entities, attributes, primary/foreign/unique keys, cardinality between them | `schemas/erd.schema.json` | `examples/orders.erd.json` |\n| `tree` | Single-parent containment: repository/module trees, capability or feature breakdowns, org-style decomposition | `schemas/tree.schema.json` | `examples/payment-platform.tree.json` |\n| `class` | Classes, interfaces, selected members, and dependency/association/inheritance/realization/composition between types | `schemas/class.schema.json` | `examples/payments.class.json` |\n| `timeline` | When things happened: incident reviews, release histories, timestamped events on a proportional clock with source lanes | `schemas/timeline.schema.json` | `examples/payment-incident.timeline.json` |\n| `waterfall` | Where the time went: span durations, overlap, and nesting of one request or agent run on a common time axis | `schemas/waterfall.schema.json` | `examples/checkout-request.waterfall.json` |\n\nWhen choosing among native diagram types is ambiguous, run `node bin/archify.mjs guide \"<scenario>\" --json`. Scenario proof examples are structural references, not facts to copy.\n\nFor an everyday subject, keep the same diagram modes and semantic types, then name them for the reader: use everyday `icon` values and `meta.legend` labels as in [Node icons](references/authoring-contract.md#node-icons). Ask for missing personal facts instead of inventing dates, amounts, or rules.\n\n## Mermaid input\n\nRead Mermaid for topology and meaning, then author fresh Archify JSON; do not mechanically render Mermaid styling.\n\n- `flowchart` / `graph` → `workflow`, or `architecture` for a component map.\n- `sequenceDiagram` → `sequence`; participants become semantic participants and arrows become messages.\n- `stateDiagram` → `lifecycle`; states and transitions retain meaning, not Mermaid style.\n- `erDiagram` → `erd`; entity and relationship names, keys, and cardinality retain meaning, not Mermaid style.\n- `classDiagram` → `class`; type kinds, selected members, and relationship kinds retain meaning, not Mermaid style.\n\n## Delivery\n\nUse the `finalize` command above for the first candidate and after a repair.\n\n`finalize` stops at the first non-passing gate. Its compact stdout and `<output-stem>.finalize-summary.json` are ordinary evidence. A passing run creates no screenshots and reports `visualReview: \"not-requested\"`.\n\nWhen a passing Architecture receipt reports `visualReviewRecommendation.signals.resolvedCrossovers`, save the candidate and follow [Architecture layout repair](references/architecture-layout-repair.md). Where several lines cross the reader’s main path, place the connected main steps in order and put each branch beside the component that owns it. Use the hints to locate the affected relationships. Make one edit to node positions and sizes only: every node, relationship (including its `from` and `to`), label, and source stays as it was. Rerun the complete `finalize` once with `--out-dir <folder>/review-2`, because the previous HTML already owns its browser evidence. `--out-dir` relocates the new browser-check and default finalize receipts, not the HTML or its delivery receipt. Successful delivery rewrites that pair at the requested output path; earlier review evidence remains bound to its original artifact bytes. See [review evidence paths](references/delivery-contract.md#a-new-candidate-at-an-existing-output-path). If that run fails, reports more crossings, or reports the same crossings with more `signals.routesOverSuggestedBends`, restore the copy and finalize it with `--out-dir <folder>/review-3`. Do not start a second placement round. Hints about extra bends alone are optional.\n\nWhen `layoutReviewRecommendation.action` is `inspect-sequence-width`, follow [Sequence width review](references/delivery-contract.md#sequence-width-review) before handing off a newly authored Sequence.\n\nFor a project README, deliver a static SVG by default. Follow an explicit request for a link or interactive HTML. Use Chrome or Chromium to export the finished HTML to a new file with `node <skill-dir>/bin/export-svg.mjs <diagram.html> <image.svg> [auto|light|dark]`. If the answer depends on small labels or Viewer cards, deliver a paste-ready Markdown image and a short caption that answers the question at normal text size.\n\nFor a README or project document, inspect the delivered diagram at its intended reading size. Follow the arrows from the starting point through each return or branch needed to answer the request. Verify conditional steps, fields and checks against the source, and name the condition where the reader sees the claim. Repair a broken reading path and inspect the result. For multiple runtimes or conditional handoffs, use the [reader check](references/repository-authoring.md#check-the-readers-answer).\n\nPerceptual review is optional for ordinary generation. Use [Optional capture evidence](references/delivery-contract.md#optional-capture-evidence), with `--out-dir <folder>/visual-check`, for a reproducible review or a concrete route/browser concern. `visualReviewRecommendation` is advisory. Inspect captures before claiming visual quality; qualify any check claim as automated when perceptual review has not occurred.\n\nRead [Delivery contract](references/delivery-contract.md) for failed gates, standalone commands, provenance/recovery, repeated delivery, exports, or opening. Native diagram recovery follows `deliver` → strict provenance `check` → `browser-check`; captures require strict provenance. Explainer delivery uses validate, deliver and check as described in its authoring guide.\n\nFor workflow viewport overflow, read [Workflow viewport repair](references/authoring-contract.md#workflow-viewport-repair) before the next layout edit.\n\nWhen reporting verification details, distinguish artifact checks, browser evidence, captures, and actual perceptual review. For an explicitly requested immediate preview or active desktop loop, see [Optional opening](references/delivery-contract.md#optional-opening).\n\n## Code Analysis (local repository architecture)\n\nFor a repository investigation, run `node bin/archify.mjs code-analysis prepare <repo-root> --out <analysis-dir> [--locale zh-CN|en] [--language ts|py|java|go|rust]`. Use `--locale zh-CN` for Chinese conversations. It creates `analysis/repo.analysis.html` with a source-backed workbench, interactive Atlas and captured AI tasks, then exits. No architecture JSON or diagram authoring is needed. Normal diagram requests end with their `finalize` delivery; analysis runs when the user requests investigation. Add `--ir <architecture.json>` only when a relevant diagram already exists or the user also wants authored architecture boundaries aligned with code evidence. This keeps the existing architecture/Atlas views and checked source mapping. Read [Code Analysis entry and investigation](modules/code-analysis/docs/USAGE.md#agent-entry-and-investigation) for adapter prerequisites, headless checks, interactive re-analysis and coverage limits. Deliver the analysis HTML with one or two scoped observations and its task-copy controls, or continue investigating in this conversation. Users need no maintenance objective or CLI knowledge. Analysis describes the working tree, including uncommitted source; keep authored commit evidence separate. Verify source before editing, make a scoped improvement or explain why to retain the structure, then rerun analysis and project tests. Report measured preparation time and tool gaps, preserve any separately delivered diagram on failure, and avoid claims that static or missing findings prove runtime failure or a fix.\n\n## Optional viewer capabilities\n\nArchitecture, Workflow, Sequence, Dataflow and Lifecycle nodes may carry optional plain-text `explanation` (1–1200 characters). The focused Semantic Passport offers Explain; prose stays outside canonical SVG and visual exports. Omit the field when the existing label, sublabel and sources are sufficient.\n\nLive motion is enabled by default for every rendered diagram; omit `meta.animation`. The Viewer’s Live/Still button controls playback.\n\n### Cross-diagram navigation (overview → module → detail across HTML artifacts)\n\n- Targets are same-directory `filename.html` only (optional `?` / `#`). No `../`, `/`, or schemes.\n- Node `href` is sugar for a one-entry list (label defaults to the node label). `drilldowns` wins if both are present.\n- One child: native SVG `<a>` + corner mark; click follows the link; Alt-click focuses Passport.\n- Several children: Passport lists every target; click focuses; Ctrl+click / double-click opens the first entry.\n- Child diagrams may set `meta.parentHref`. The header Back control appears when `parentHref` or URL `?from=` is present.\n- Examples: sibling pair `examples/drilldown-platform.architecture.json` ↔ `examples/drilldown-integrations.architecture.json`; multi-child `examples/drilldown-overview.architecture.json`.\n\nRead `references/viewer-runtime.md` only when the user explicitly asks for Share Cards, Route/Reach cards, motion, deep links, presentation, search/focus, or another Viewer Runtime feature.\n\n## Setup and fallback\n\nNo install is required inside the skill package. For setup diagnosis, verify with:\n\n```bash\nnode bin/archify.mjs doctor\nnode bin/archify.mjs demo <output-directory>\n```\n\nFor native diagrams, when shell access is unavailable, hand-place architecture SVG into `assets/template.html`, use CSS semantic classes rather than inline colors, and follow the visual review contract in `references/delivery-contract.md`. Explainers require their renderer and real delivery gates; if those are unavailable, report the limitation and give a text answer when useful, without claiming HTML delivery.\n\n## Output\n\nReply in the user's language, as briefly as the result allows; the diagram carries the content, so a single diagram usually needs one line.\n\n- For a README diagram, lead with a link to the requested artifact (the exported SVG by default). Link the README when edited. For other native diagrams, lead with the HTML. Use descriptive Markdown links with absolute paths, wrapping paths with spaces in `<...>`.\n- When the user wants to understand a system or codebase rather than draw a described subject, add one or two sentences with the key takeaway. Skip sentences that only restate what the diagram obviously shows.\n- State anything that changes how the diagram should be read: the abstraction level or deliberately omitted parts when a reader might expect them, illustrative rather than measured values, missing source evidence, or requested content dropped or merged during repair.\n- For several diagrams, report completion once with a link to an existing overview or compact per-diagram links, not a directory path.\n\nDo not recap commands, repair rounds, hashes, quality profiles, or check lists; they stay in the receipts. If asked whether the diagram was verified, answer in one line, such as “Automated checks passed; not visually reviewed.” Give receipt links and details only for reproducibility or troubleshooting. Disclose requested visual review that could not run, and claim visual inspection only when performed. Keep the required update notice under Update awareness.\n\nExample: `Created [Checkout request timing](/abs/path/checkout-timing.html). Durations are illustrative, not measured.`\n\nFor an explainer, the reply must read well without opening the page: the conclusion in one to three lines with the key cause, numbers or recommendation, then, as the very last line, a Markdown link with a descriptive title in the user's language, such as `[查看测试报告](/abs/path/test-report.html)` or `[Open the test report](...)`. Use the absolute path, wrapped in `<...>` when it contains spaces, not `file://`; put any update notice before it. Never offer a directory, terminal log or auto-open (`--open`) instead of the link. When `finalize explainer` fails or the renderer is unavailable, answer in text, say in one line that the page was not produced, and give no page link. Mention gates only when one failed or writing warnings remain; do not paste the draft.\n</yakaai_skills>"}