Skip to content

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

feat(cli): finalize verified delivery with capture-free browser evidence

tt-a1i3707ef2321d2
diff --git a/archify.zip b/archify.zip
index 186db91e..56d5bdbf 100644
Binary files a/archify.zip and b/archify.zip differ
diff --git a/archify/SKILL.md b/archify/SKILL.md
index 9a20e016..7e6dc800 100644
--- a/archify/SKILL.md
+++ b/archify/SKILL.md
@@ -10,61 +10,53 @@ metadata:
# Archify
-Create a self-contained, interactive HTML diagram from a small typed JSON specification. Static output is the default; enable motion only when the user asks for a demo or presentation.
+Create an interactive HTML diagram from typed JSON. Static output is the default; enable motion only when requested.
+
+For a real codebase, read [Repository authoring](references/repository-authoring.md) for exploration and example selection. A system description uses the steps below; an existing JSON uses the handoff path.
+
+## Existing candidate handoff
+
+When the user supplies a frozen candidate, run `finalize` first as one CLI invocation. Its passing receipt completes the handoff; screenshots and an image-capable model are optional. For repair, follow step 5.
+
+The update check is outside the delivery critical path. A harness may start it concurrently with `finalize`; if it cannot, omit it for this task. Never add a foreground tool turn or delay a required gate for update information.
## Fast authoring path
Use this bounded path for ordinary generation. Do not read the optional Viewer Runtime reference unless the user asks about those features.
1. Choose `architecture`, `workflow`, `sequence`, `dataflow`, or `lifecycle` from the question.
-2. Read one matching schema in `schemas/`, `schemas/common.schema.json`, and one matching JSON example in `examples/`. Read only those files. Fresh authorship means new stable IDs, domain wording, and layout; use the example for field shape, not facts. New workflow sources use `schema_version: 2` and its readable layout contract; keep `schema_version: 1` only when preserving an existing workflow's fixed geometry. When real product identity matters, query `node bin/archify.mjs brands "<name>" --json`; read `references/brand-marks.md` only for an unknown brand with a user-provided URL.
-3. Artifact first: the next tool action must write the candidate. Write the candidate before inspecting renderer internals. Do not plan exact coordinates in prose. Start with one clear main path, short side branches, and sparse labels. Use roughly 12 primary nodes as an initial readability budget. Preserve every node and relationship required by the user's question; for larger diagrams, group related content where the selected schema supports it. Set `meta.quality_profile` to `"showcase"` unless the user explicitly requests a dense `standard` map. Start with automatic routes and labels. Do not add `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, or `labelAt` before a diagnostic calls for one; test one repair hypothesis per round. When geometry fails or repeats, read the repair order in `references/authoring-contract.md` and inspect measured layout before manual routing: use `validate <type> <candidate.json> --layout-json` for architecture/workflow; for other types, use validation diagnostics and the rendered SVG geometry. Check whether unnecessary agent-added controls disable automatic port spread; preserve user-required route intent. If several edges share a constrained channel, compare a small node-layout change with adding route controls; validate the coupled change together while preserving required nodes, relationships, labels, and boundary membership.
-4. Validate after every candidate edit and immediately before handoff:
+2. Use the exact paths in the Type router; do not list `schemas/` or `examples/` first. For Architecture, select the matching showcase example in the Type router before loading it with `references/authoring-defaults.md` in one parallel batch; it includes boundaries, guided views, and conclusion cards. For Workflow, read defaults and its starter together. Read the relevant schema definition for any new field, enum choice, or constrained text; an example shows shape, not every allowed value or length. Boundary kinds and guided-view notes need their schema constraints before writing. For Sequence, Dataflow, and Lifecycle, read defaults, schema, common schema, and example together. Fresh authorship means new IDs, domain wording, and layout; examples provide shape, not facts. Do not run help, doctor, validate a starter, create a temporary diagram, pre-create/list output paths, or query brands. Only for explicitly requested branded marks may you query `node bin/archify.mjs brands "<name>" --json`; read `references/brand-marks.md` only for an unknown brand with a user-provided URL.
+3. Artifact first: once requested scope and source evidence are covered, write the candidate directly; do not plan coordinates in prose. Let the real system determine the number of nodes and relationships: keep separate nodes when merging would hide a responsibility, boundary, trust boundary, protocol, lifecycle, ownership, or persistence seam; group only unified concerns. Never use node, relationship, source-reference, view, card, or boundary counts as an authoring target, ceiling, or performance lever. Audit responsibility ownership rather than counts: keep an evidence-backed controller, broker, runtime, or supervisor separate when it manages multiple participants and merging would hide control-plane ownership or lifecycle. Keep an external caller or client separate from the gateway, relay, or service when source distinguishes runtimes or trust; a transport is not its user. Never use shared source citations as a substitute for an omitted role; omit only roles absent in code. For a repository showcase, add curated `meta.views` for distinct reader questions and evidence-backed conclusion cards for material takeaways; every aid must improve comprehension, with no quota. Set `meta.quality_profile` to `"showcase"` unless the user requests dense `standard`. Keep forward flow monotonic where practical, branches beside their owner, shared stores outside the main lane, and feedback paths on the perimeter; wrap broad systems into meaningful rows. Leave clear gaps for actual relationship labels and add whitespace rather than route controls. On the first draft, let the renderer route every connection: omit `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, `labelAt`, `labelDx`, `labelDy`, and `labelSegment` unless the user supplied that exact route intent. Add the smallest control only after a measured diagnostic.
+4. 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:
```bash
- node bin/archify.mjs validate <type> <candidate.json> --quality showcase --json
+ node bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json
```
- A receipt with only 4 artifact checks is basic validation, never showcase acceptance. A showcase pass must report all 9 artifact checks with 0 composition errors and 0 warnings. If the candidate omits or misspells the exact `meta.quality_profile` field, fix it before geometry. For a workflow v2 geometry diagnosis, run `node bin/archify.mjs validate workflow <candidate.json> --layout-json` and use the stable compiler receipt; solver internals are not authoring controls. A passing final validation freezes the candidate: never edit it afterward.
-5. For a delivered HTML, `deliver` is the final acceptance command:
+ 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`.
- ```bash
- node bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality showcase --json
- ```
+ A passing receipt proves that the included `validate`, `deliver`, strict `check`, and deterministic real-browser `browser-check` gates passed. Do not read its full sidecar or rerun individual commands afterward; use a standalone command only for an explicitly separate execution or focused failure diagnosis.
- A non-zero exit can never be described as success. Continue to the strict delivery gate below only after `deliver` exits zero. If validation fails, use the diagnosed subjects and measured evidence to choose one repair hypothesis, then rerun. Missing evidence is a reason to inspect layout, not guess a constraint from the message. Compare remaining diagnostic codes and subjects within the same validation stage; a later stage can reveal new issues. If the same issue survives two focused repairs, inspect its measured geometry or the relevant implementation before changing that hypothesis. If it remains unresolved after that investigation and one evidence-based repair, stop and report it truthfully. A lower error count does not justify changing the diagram’s meaning.
+5. A non-zero exit is never success. Use its compact stdout or `evidence.summaryReceipt`; read the full receipt only if the summary is truncated and lacks enough evidence for a coherent repair. After a validation failure, the next action is the smallest coherent local edit named by that evidence, not prose coordinate exploration or whole-candidate replacement. Do not run validate, layout, render, or finalize first; edit the existing JSON in place. Geometry never authorizes deleting or merging a source-backed component, relationship, reference, view, card, boundary, or semantic label; reroute, reposition, or add readable canvas space instead. After the edit, rerun the complete `finalize` command from step 4 once, retaining `--quality showcase` and `--repo-root <repo-root>` for repository-backed candidates. After editing, omit any earlier `--candidate-sha256`: it binds the previous candidate. Use `--layout-json` before the edit only when compact evidence lacks needed geometry. A receipt with only 4 artifact checks is basic validation: require all 9 checks with 0 composition errors and 0 warnings. Fix `meta.quality_profile` before geometry. For workflow v2, use the stable compiler receipt; solver internals are not authoring controls. Use standalone `validate` only for focused diagnosis, with `--repo-root <repo-root>` for a repository. A passing validation returns `candidateFrozen: true`; do not edit, revalidate, or reread it. Run its `nextAction.arguments`, replacing only `<output.html>`. Repair a later gate without changing the frozen candidate, then rerun `finalize`. If one issue survives two focused repairs, inspect measured geometry or the relevant contract; after one evidence-based retry, stop truthfully. A lower error count never justifies changing meaning.
## Update awareness
-After the first candidate exists, run the packaged checker `scripts/check-update.mjs` once with Node and continue the requested workflow. If the command cannot run, continue without mentioning the check.
+After the first candidate exists, a harness with true parallel tool calls may run the packaged checker `scripts/check-update.mjs` once alongside validation or `finalize`. Otherwise skip it; do not serialize it into the user's delivery path. If the checker cannot run, continue without mentioning it.
- For `silent`, continue without mentioning the update check.
-- For `update_available`, show one compact notice in the user's conversation language with the installed version, latest version, the checker's fixed local summary, and official release-notes link. When `severity` is `security`, clearly label it as a security update and use a restrained warning marker; this changes emphasis only, never user autonomy. Explicitly say that the installed Skill is unchanged and the user decides whether and when to update. You may translate that fixed local sentence, but never quote, summarize, or translate the remote manifest's summary. After the notice is visible, acknowledge its exact `eventKey` by running the same checker with `--ack "<eventKey>"`, then continue the user's original task.
-
-The notice is information, not permission. Keep the installed version unchanged; this v0.1 workflow never downloads, installs, or executes an update, and silence is never consent.
-
-Do not read `renderers/shared/geometry.mjs`, renderer source, validator source, tests, or benchmarks before the first candidate. Inspect implementation only for a diagnostic without actionable evidence or after two focused repairs fail.
+- For `update_available`, read `references/update-awareness.md`, follow it, then continue the requested task.
-Workflow note: use schema v2 for new workflows; preserve schema v1 when an
-existing source needs fixed legacy geometry. For sequential stages stacked in
-one container, use one v2 lane and one group, omit `meta.viewBox`, and place the
-nodes around the lane content center with symmetric `yOffset` values such as
-`-90 / 0 / 90`; readable-v2 measures that lane independently when no absolute
-route pins are present. Keep semantic edge labels and act on the compiler
-diagnostic. The canonical layout, pin, migration, and receipt contract is in
-[`renderers/workflow/README.md`](renderers/workflow/README.md#layout-contracts).
-
-Lifecycle note: phase columns `0..4` occupy the main rail; event/terminal column `N` in `0..2` aligns exactly beneath main column `N + 2`. Every lane other than `main` and `terminal` shares the one middle band, so two such states in the same column need distinct `yOffset` values. A recoverable state uses `type: "failure"` plus a real transition back to the active state.
+Do not read `bin/` implementation, renderer or validator source, tests, or benchmarks before the first candidate; the commands above are sufficient. Inspect implementation only for a diagnostic without actionable evidence or after two focused repairs fail.
## Type router
-| Type | Use for |
-|---|---|
-| `architecture` | Components, services, cloud/security boundaries, infrastructure |
-| `workflow` | Processes, approval gates, tool calls, runbooks, CI/CD |
-| `sequence` | API call chains, request lifecycles, async traces, returns |
-| `dataflow` | Pipelines, ETL/ELT, lineage, governance, consumers |
-| `lifecycle` | State/status transitions, retries, waiting and terminal states |
+| Type | Use for | Schema | Example |
+|---|---|---|---|
+| `architecture` | Components, services, cloud/security boundaries, infrastructure | `schemas/architecture.schema.json` | System descriptions, services, libraries, and CLI repos: `examples/web-app.architecture.json`; deployment repos: `examples/production-deployment.architecture.json` |
+| `workflow` | Processes, approval gates, tool calls, runbooks, CI/CD | `schemas/workflow.schema.json` | `examples/agent-tool-call.workflow.json` |
+| `sequence` | API call chains, request lifecycles, async traces, returns | `schemas/sequence.schema.json` | `examples/cache-miss-request.sequence.json` |
+| `dataflow` | Pipelines, ETL/ELT, lineage, governance, consumers | `schemas/dataflow.schema.json` | `examples/product-analytics.dataflow.json` |
+| `lifecycle` | State/status transitions, retries, waiting and terminal states | `schemas/lifecycle.schema.json` | `examples/deployment-release.lifecycle.json` |
When ambiguous, run `node bin/archify.mjs guide "<scenario>" --json`. Scenario proof examples are structural references, not facts to copy.
@@ -76,51 +68,21 @@ Read Mermaid for topology and meaning, then author fresh Archify JSON; do not me
- `sequenceDiagram` → `sequence`; participants become semantic participants and arrows become messages.
- `stateDiagram` → `lifecycle`; states and transitions retain meaning, not Mermaid style.
-## Authoring invariants
-
-- One obvious main path; side branches leave the nearest main-path node. Remove low-value edges before adding routing controls.
-- Omit `meta.visual_preset` by default so every diagram opens in `classic`, regardless of whether its resolved color mode is light or dark. Color mode and visual preset are independent: switching Light / Dark must preserve the current preset. Set `signal-flow`, `blueprint`, or `editorial` only when the user explicitly requests that visual style.
-- Omit `meta.subtitle` by default. Never invent a subtitle that restates the title, nodes, or cards; include one short supporting line only when the user explicitly asks for it.
-- Treat the standalone desktop viewer as a first-screen artifact by default, not a shallow strip. Generate one responsive artifact for laptops and external displays—never device-specific HTML or alternate topology. The viewer may adapt only the outer reading width from the live viewport height; it must preserve the authored SVG/viewBox, proportions, semantic geometry, and normal document flow. On a wide or tall desktop, use enough authored vertical rhythm that the diagram panel and its necessary conclusion cards occupy the screen as a balanced whole; runtime scaling cannot repair an over-compressed Y layout or an undersized explicit `meta.viewBox`. Before handoff, run the real browser check at 1440×900, 1600×1000, 1920×1080, and 2048×1320, then inspect both endpoint themes. Require zero horizontal overflow. Prefer full first-screen containment, but when an intrinsic-height diagram cannot fit without crossing the Viewer readability floor, preserve readable sizing and allow only the Reader-declared vertical page scroll recorded by `visual-check`; do not rewrite valid semantic geometry merely to remove that scroll. Repair every other overflow by removing only genuinely redundant content or compacting spacing before shrinking nodes, labels, or the main panel. If the largest viewport still has a conspicuous empty lower band at the viewer's width cap, redistribute authored Y positions and increase the viewBox height proportionally; do not add filler copy or decorative cards. Never counterfeit a pass with `overflow: hidden`, clipped content, an internal diagram scroller, stretched SVG height, or smaller typography. See [Automated browser evidence](references/delivery-contract.md#automated-browser-evidence) for the authoritative acceptance rule.
-- Omit `meta.legend` for the truthful `auto` default. When needed, use only `mode: auto|all|hidden` and renderer-supported `entries.<kind>.label|visible`; labels never change semantics.
-- Choose one primary authored language from an explicit user choice; otherwise follow the request or conversation's dominant language. `meta.locale` controls only renderer-owned Viewer UI: use `"en"`, `"zh-CN"`, or `"es"` for the corresponding supported primary language. For every other language, omit `meta.locale` and explicitly disclose that the fixed Viewer UI and `<html lang>` fall back to English. The renderer never translates authored content. See `references/authoring-contract.md` for details.
-- Preserve exact product names, code identifiers, commands, protocols, API paths, and environment names. They may remain English inside localized copy, but never justify leaving the surrounding explanatory prose in another language.
-- Brand identity is optional and explicit. Put a canonical built-in ID in `brand` when the node names that real product. If no preset matches and the user supplied the official HTTP(S) URL, first run `node bin/archify.mjs brands capture "<url>" --json`, then author the returned digest-pinned `brand` object. Render and validate never perform an unpinned capture. Otherwise omit `brand`. Never infer a brand from a vague role such as "database", and never let a badge replace the semantic `type`, label, or relationship facts.
-- For sequence diagrams, omit `meta.column_fit` for the stable `fixed` layout. Set it to `"spread"` when a wide viewBox would otherwise leave unused horizontal space or when meaningful participant labels do not fit the fixed boxes; do not shorten semantic labels before trying `spread`.
-- Component types are `frontend`, `backend`, `database`, `cloud`, `security`, `messagebus`, and `external`; variants are `default`, `emphasis`, `security`, and `dashed`.
-- Relationship labels are semantic data. When one collides, move the label, adjust the route or spacing, then shorten the wording while preserving meaning. Omit only wording that is already fully implied by both endpoints and contains no protocol, action, direction, synchronous/asynchronous behavior, or cross-boundary mechanism. Preserve every meaningful label; deleting it is not a geometry repair. If a relationship starts unlabeled because its endpoints fully imply it, explain why the wording is redundant; this is a semantic authoring choice, not a geometry repair.
-- Omit `meta.engineering_profile` by default. Region, cluster, and security boundary wording do not by themselves enable it. Enable `deployment-ownership` only when the user explicitly asks for a production deployment topology, ownership handoff, or fail-closed deployment review and the source facts are known. Once enabled, must not remove the engineering profile merely to pass validation; repair the facts or report the diagnostics truthfully.
-- Spacing means clear gap, not center distance. For a relationship label, clear gap must exceed its measured mask width; follow the label-preserving repair order.
-- Automatic routes own their endpoint sides. A side is a direction contract: the first and final segment must leave/enter perpendicular to that side.
-- Automatic Port Spread is a default renderer behavior for architecture, workflow, data-flow, and lifecycle. It skips single relationships and explicit `via`, `channelX`, `channelY`, `labelAt`, or non-`auto` routes. Near parallel ports use an outside bridge so automatic routing cannot create a sub-8px segment or sub-16px interior turn. Architecture separately keeps unobstructed facing automatic ports (`left`/`right` or `top`/`bottom`) on one shared axis when their offset is under 16px and both ports retain corner clearance. If exactly one endpoint was spread, only the unshared endpoint may move onto that axis; if both endpoints were spread, keep the outside bridge so competing ports remain distinct.
-- Never accept an edge crossing an unrelated opaque node, an ambiguous shared corridor, or a relationship label masking another route.
-
-Read `references/authoring-contract.md` only when you need field enums, spacing math, geometry repair rules, repository evidence, or mode-specific placement.
-
## Delivery
-Use `validate` during repair and `deliver` once for final acceptance. This is deterministic artifact evidence; it does not exercise the Viewer in a browser. After `deliver` exits zero, require current delivery evidence before handoff:
+Use the `finalize` command above for the first candidate and after a repair.
-```bash
-node bin/archify.mjs check <output.html> --require-provenance
-```
+`finalize` stops at the first non-passing gate. Its compact stdout and `<output-stem>.finalize-summary.json` are the normal evidence; `<output-stem>.finalize.json` is full audit detail, not ordinary repair context. A passing handoff reports `visualReview: "not-requested"` and creates no screenshots.
-Read `references/delivery-contract.md` whenever `deliver`, strict `check`, or
-`visual-check` fails; provenance is not current; recovery metadata remains; or
-the same output path needs another delivery. That file is the canonical source
-for provenance, serialization, recovery, receipt, and browser-evidence rules.
+Escalate to perceptual review only when the user requests an aesthetic review, a template/renderer/viewer change needs visual regression evidence, a novel layout or browser diagnostic leaves low confidence, or the run is a sampled audit. Run `visual-check` on the finalized artifact, open its HTML contact sheet in a browser or inspect the viewport PNGs with a capable image reader, and record that judgment separately. Model image capability is optional because this path is not part of ordinary acceptance.
-After the strict `check` above exits zero, collect bounded desktop evidence without modifying or rerendering the trusted HTML:
-
-```bash
-node bin/archify.mjs visual-check <output.html> --json --require-provenance
-```
+For recovery, the required order stays `deliver` → strict provenance `check` → `browser-check`. Run optional `visual-check` only against a strict-provenance artifact. Read `references/delivery-contract.md` for standalone syntax, any failed gate, stale provenance, recovery metadata, repeated delivery to one path, export evidence, or post-delivery opening.
For workflow viewport overflow, read [Workflow viewport repair](references/authoring-contract.md#workflow-viewport-repair) before the next layout edit.
-`visual-check` collects automated browser evidence from the exact delivered HTML without modifying or rerendering it. Its machine-readable measurements and screenshots do not approve perceptual polish. Follow `references/delivery-contract.md` for the canonical receipt fields, coverage, sidecars, exit behavior, and supplementary manual-record requirements.
+`browser-check` collects machine-readable browser evidence from the exact delivered HTML without modifying, rerendering, or capturing it. `visual-check` is the capture-producing command for an escalated perceptual review.
-Keep the three claims separate: `deliver` proves deterministic artifact checks, `visual-check` proves bounded behavior in a real browser, and perceptual visual review requires an actual human or image-capable reviewer. Report browser evidence and perceptual review independently. An unconstrained glance can support only perceptual review; use the canonical delivery contract when recording supplementary manual browser work or handling an environmental failure.
+Keep the claims separate: `deliver` proves deterministic artifact checks, `browser-check` proves bounded behavior in a real browser, `visual-check` adds artifact-bound captures, and perceptual review requires an actual human or image-capable reviewer. Report optional perceptual review only when it was requested or triggered by the escalation rules above.
Add `--open` only when the user wants an immediate local preview. For an active desktop authoring loop, the optional command is:
@@ -128,11 +90,11 @@ Add `--open` only when the user wants an immediate local preview. For an active
node bin/archify.mjs preview <type> <input>.json <output>.html --quality showcase
```
-Never start preview by default. Read `references/delivery-contract.md` when using preview, repository evidence, export receipts, visual review, or post-delivery opening.
+Never start preview by default.
## Optional viewer capabilities
-Generated HTML already contains theme switching, pan/zoom, search, focus, relationship tracing, semantic views, presentation, and truthful exports. These are reader capabilities, not extra authoring work. `meta.animation: "trace"` is opt-in; `meta.views` is optional and should contain at most five curated chapters.
+`meta.animation: "trace"` is opt-in. Use optional `meta.views` for distinct reader questions, with no numeric target.
Read `references/viewer-runtime.md` only when the user explicitly asks for Share Cards, Route/Reach cards, motion, guided stories, deep links, presentation, search/focus, or another Viewer Runtime feature.
diff --git a/archify/bin/archify.mjs b/archify/bin/archify.mjs
index 0f1ea325..6e15ce19 100755
--- a/archify/bin/archify.mjs
+++ b/archify/bin/archify.mjs
@@ -2178,11 +2178,13 @@ function usage() {
archify render <type> <input.json> [output.html] [--quality standard|showcase] [--repo-root path]
archify compare architecture <base.json> <head.json> [output.html] [--receipt path] [--json] [--quality standard|showcase] [--repo-root path]
archify deliver <type> <input.json> [output.html] [--json] [--open] [--quality standard|showcase] [--repo-root path]
+ archify finalize <type> <input.json> <output.html> [--json] [--receipt path] [--out-dir <dir>] [--quality standard|showcase] [--repo-root path] [--candidate-sha256 hex]
archify preview <type> <input.json> [output.html] [--no-open] [--quality standard|showcase] [--repo-root path]
archify validate <type> <input.json> [--json] [--layout-json] [--quality standard|showcase] [--repo-root path]
archify migrate workflow <old.json> <new.json> --to-schema 2 [--output portable.html] [--json] [--repo-root path]
archify inspect <type> <input.json>
archify check <output.html> [--require-provenance]
+ archify browser-check <output.html> [--json] [--require-provenance] [--out-dir <dir>]
archify visual-check <output.html> [--json] [--require-provenance] [--out-dir <dir>]
archify guide [scenario or question] [--json] [--lang en|zh]
archify brands [name, alias, domain, or category] [--json]
@@ -5332,10 +5334,10 @@ function provenanceFailureReceipt({ command, artifactPath, provenance }) {
schemaVersion: 1,
ok: false,
command,
- ...(command === 'visual-check' ? {
+ ...(['visual-check', 'browser-check'].includes(command) ? {
evidenceKind: 'automated-browser',
status: 'fail',
- visualReview: 'pending',
+ visualReview: command === 'visual-check' ? 'pending' : 'not-requested',
} : {}),
provenance: provenance.status,
...(provenance.receiptId ? { deliveryReceiptId: provenance.receiptId } : {}),
@@ -5402,80 +5404,34 @@ async function commandCheck(args) {
if (result.status !== 0) process.exitCode = result.status ?? 1;
}
-async function commandVisualCheck(rawArgs) {
- const { rest: args, outDir: rawOutDir } = extractOutDirArgs(rawArgs);
- const json = args.includes('--json');
- const requireProvenance = args.includes('--require-provenance');
- const knownOptions = new Set(['--json', '--require-provenance']);
- const unknown = args.filter((arg) => arg.startsWith('--') && !knownOptions.has(arg));
- if (unknown.length) fail(`Unknown visual-check option "${unknown[0]}".`, 1);
- const positional = args.filter((arg) => !knownOptions.has(arg));
- if (positional.length !== 1) fail(usage(), 1);
-
- const artifactPath = path.resolve(positional[0]);
- let outDir;
- if (rawOutDir !== undefined) {
- const { resolveNativeOutputDirectory } = await import('../renderers/shared/output-path.mjs');
- try {
- outDir = resolveNativeOutputDirectory(rawOutDir);
- } catch (error) {
- const outputDiagnostic = error.archifyDiagnostics?.[0] || diagnostic({
- code: 'output/native-path-syntax',
- message: error.message,
- subject: { output: rawOutDir },
- evidence: { ...(error?.code ? { systemCode: error.code } : {}) },
- supportedFixes: ['choose an ordinary native filesystem directory and retry'],
- });
- const failure = {
- schemaVersion: 1,
- ok: false,
- command: 'visual-check',
- evidenceKind: 'automated-browser',
- status: 'fail',
- visualReview: 'pending',
- artifact: { path: artifactPath },
- error: error.message,
- diagnostics: [outputDiagnostic],
- };
- if (json) console.log(JSON.stringify(failure, null, 2));
- else {
- console.error(formatDiagnostics(`automated browser evidence failed: ${failure.error}`, failure.diagnostics));
- console.error('perceptual visual review pending');
- }
- process.exitCode = 1;
- return;
- }
- }
+async function executeBrowserEvidence({
+ artifactPath, outDir, requireProvenance, command, capture, ...browserOptions
+}) {
const pathIdentityRuntime = await loadPathIdentityRuntime();
- const provenance = inspectArtifactDeliveryProvenance(
- artifactPath,
- requireProvenance,
- pathIdentityRuntime,
- );
- let runVisualCheck;
- let persistVisualCheckFailure;
+ const provenance = inspectArtifactDeliveryProvenance(artifactPath, requireProvenance, pathIdentityRuntime);
+ let runEvidence;
+ let persistFailure;
try {
- ({ runVisualCheck, persistVisualCheckFailure } = await import('./visual-check.mjs'));
+ const evidence = await import('./visual-check.mjs');
+ runEvidence = command === 'browser-check' ? evidence.runBrowserCheck : evidence.runVisualCheck;
+ persistFailure = command === 'browser-check'
+ ? evidence.persistBrowserCheckFailure
+ : evidence.persistVisualCheckFailure;
} catch (error) {
- fail(`Could not load visual-check: ${error.message}`, 1);
+ fail(`Could not load ${command}: ${error.message}`, 1);
}
if (provenance && !provenance.ok) {
- const receipt = persistVisualCheckFailure(artifactPath,
- provenanceFailureReceipt({ command: 'visual-check', artifactPath, provenance }),
+ const receipt = persistFailure(artifactPath,
+ provenanceFailureReceipt({ command, artifactPath, provenance }),
{ outDir });
- if (json) console.log(JSON.stringify(receipt, null, 2));
- else {
- console.error(formatDiagnostics(`automated browser evidence failed: ${receipt.error}`, receipt.diagnostics));
- console.error('perceptual visual review pending');
- }
- process.exitCode = 1;
- return;
+ return { exitCode: 1, receipt, inputFailure: true };
}
let result;
try {
- result = await runVisualCheck({
- artifactPath: positional[0],
+ result = await runEvidence({
+ ...browserOptions,
+ artifactPath,
outDir,
...(provenance ? { deliveryProvenance: provenance } : {}),
verifyArtifact: (bytes) => {
@@ -5494,34 +5450,86 @@ async function commandVisualCheck(rawArgs) {
},
});
} catch (error) {
- const failure = persistVisualCheckFailure(artifactPath, {
+ const failure = persistFailure(artifactPath, {
schemaVersion: 1,
ok: false,
- command: 'visual-check',
+ command,
evidenceKind: 'automated-browser',
status: 'fail',
- visualReview: 'pending',
+ visualReview: capture ? 'pending' : 'not-requested',
...(provenance ? {
provenance: provenance.status,
...(provenance.receiptId ? { deliveryReceiptId: provenance.receiptId } : {}),
} : {}),
- artifact: { path: path.resolve(positional[0]) },
+ artifact: { path: artifactPath },
error: error.message,
diagnostics: [diagnostic({
- code: 'viewer/visual-check-input',
- message: 'visual-check could not read a valid HTML input or prepare its evidence files.',
- subject: { artifact: path.resolve(positional[0]) },
+ code: `viewer/${command}-input`,
+ message: `${command} could not read a valid HTML input or prepare its evidence files.`,
+ subject: { artifact: artifactPath },
evidence: { reason: error.message, ...(error.code ? { systemCode: error.code } : {}) },
supportedFixes: ['provide an existing readable .html artifact and a writable directory for evidence files'],
})],
}, { outDir });
- if (json) {
- console.log(JSON.stringify(failure, null, 2));
- } else {
- console.error(formatDiagnostics(`automated browser evidence failed: ${failure.error}`, failure.diagnostics));
- console.error('perceptual visual review pending');
+ return { exitCode: 1, receipt: failure, inputFailure: true };
+ }
+
+ return result;
+}
+
+async function commandBrowserEvidence(rawArgs, { command, capture }) {
+ const { rest: args, outDir: rawOutDir } = extractOutDirArgs(rawArgs);
+ const json = args.includes('--json');
+ const requireProvenance = args.includes('--require-provenance');
+ const knownOptions = new Set(['--json', '--require-provenance']);
+ const unknown = args.filter((arg) => arg.startsWith('--') && !knownOptions.has(arg));
+ if (unknown.length) fail(`Unknown ${command} option "${unknown[0]}".`, 1);
+ const positional = args.filter((arg) => !knownOptions.has(arg));
+ if (positional.length !== 1) fail(usage(), 1);
+
+ const artifactPath = path.resolve(positional[0]);
+ let outDir;
+ if (rawOutDir !== undefined) {
+ const { resolveNativeOutputDirectory } = await import('../renderers/shared/output-path.mjs');
+ try {
+ outDir = resolveNativeOutputDirectory(rawOutDir);
+ } catch (error) {
+ const outputDiagnostic = error.archifyDiagnostics?.[0] || diagnostic({
+ code: 'output/native-path-syntax',
+ message: error.message,
+ subject: { output: rawOutDir },
+ evidence: { ...(error?.code ? { systemCode: error.code } : {}) },
+ supportedFixes: ['choose an ordinary native filesystem directory and retry'],
+ });
+ const failure = {
+ schemaVersion: 1,
+ ok: false,
+ command,
+ evidenceKind: 'automated-browser',
+ status: 'fail',
+ visualReview: capture ? 'pending' : 'not-requested',
+ artifact: { path: artifactPath },
+ error: error.message,
+ diagnostics: [outputDiagnostic],
+ };
+ if (json) console.log(JSON.stringify(failure, null, 2));
+ else {
+ console.error(formatDiagnostics(`automated browser evidence failed: ${failure.error}`, failure.diagnostics));
+ console.error('perceptual visual review pending');
+ }
+ process.exitCode = 1;
+ return;
}
- process.exitCode = 1;
+ }
+ const result = await executeBrowserEvidence({ artifactPath, outDir, requireProvenance, command, capture });
+
+ if (result.inputFailure) {
+ if (json) console.log(JSON.stringify(result.receipt, null, 2));
+ else {
+ console.error(formatDiagnostics(`automated browser evidence failed: ${result.receipt.error}`, result.receipt.diagnostics));
+ console.error(capture ? 'perceptual visual review pending' : 'perceptual visual review not requested');
+ }
+ process.exitCode = result.exitCode;
return;
}
@@ -5530,7 +5538,7 @@ async function commandVisualCheck(rawArgs) {
} else {
const sidecarDirectory = outDir || path.dirname(result.receipt.artifact.path);
console.log(`automated browser evidence ${result.receipt.status}: ${result.receipt.artifact.path}`);
- console.log(`visual-check containment ${result.receipt.containment.status}; captures ${result.receipt.captures.status}; perceptual visual review pending`);
+ console.log(`${command} containment ${result.receipt.containment.status}; captures ${result.receipt.captures.status}; perceptual visual review ${result.receipt.visualReview}`);
console.log(`receipt ${path.join(sidecarDirectory, result.receipt.sidecars.receipt)}`);
if (result.receipt.captures.contactSheet) {
console.log(`contact sheet ${path.join(sidecarDirectory, result.receipt.captures.contactSheet)}`);
@@ -5540,6 +5548,169 @@ async function commandVisualCheck(rawArgs) {
process.exitCode = result.exitCode;
}
+async function commandVisualCheck(rawArgs) {
+ return commandBrowserEvidence(rawArgs, { command: 'visual-check', capture: true });
+}
+
+async function commandBrowserCheck(rawArgs) {
+ return commandBrowserEvidence(rawArgs, { command: 'browser-check', capture: false });
+}
+
+function extractFinalizeReceiptArgs(args) {
+ const rest = [];
+ let receiptPath;
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (arg === '--receipt') {
+ receiptPath = args[index + 1];
+ if (!receiptPath || receiptPath.startsWith('--')) rejectCliArgument('--receipt requires a JSON output path.', {
+ code: 'cli/missing-option-value',
+ subject: { option: '--receipt' },
+ supportedFixes: ['provide one .json path after --receipt'],
+ });
+ index += 1;
+ continue;
+ }
+ if (arg.startsWith('--receipt=')) {
+ receiptPath = arg.slice('--receipt='.length);
+ if (!receiptPath) rejectCliArgument('--receipt requires a JSON output path.', {
+ code: 'cli/missing-option-value',
+ subject: { option: '--receipt' },
+ supportedFixes: ['provide one .json path after --receipt'],
+ });
+ continue;
+ }
+ rest.push(arg);
+ }
+ return { rest, receiptPath };
+}
+
+function extractCandidateSha256Args(args) {
+ const rest = [];
+ let candidateSha256;
+ for (let index = 0; index < args.length; index += 1) {
+ const arg = args[index];
+ if (arg === '--candidate-sha256') {
+ candidateSha256 = args[index + 1];
+ if (!candidateSha256 || candidateSha256.startsWith('--')) rejectCliArgument('--candidate-sha256 requires a SHA-256 digest.', {
+ code: 'cli/missing-option-value',
+ subject: { option: '--candidate-sha256' },
+ supportedFixes: ['provide the candidate sha256 from the passing validate receipt'],
+ });
+ index += 1;
+ continue;
+ }
+ if (arg.startsWith('--candidate-sha256=')) {
+ candidateSha256 = arg.slice('--candidate-sha256='.length);
+ if (!candidateSha256) rejectCliArgument('--candidate-sha256 requires a SHA-256 digest.', {
+ code: 'cli/missing-option-value',
+ subject: { option: '--candidate-sha256' },
+ supportedFixes: ['provide the candidate sha256 from the passing validate receipt'],
+ });
+ continue;
+ }
+ rest.push(arg);
+ }
+ if (candidateSha256 !== undefined && !/^[0-9a-f]{64}$/.test(candidateSha256)) {
+ rejectCliArgument('--candidate-sha256 must be 64 lowercase hexadecimal characters.', {
+ code: 'cli/invalid-option-value',
+ subject: { option: '--candidate-sha256' },
+ evidence: { value: candidateSha256 },
+ supportedFixes: ['copy candidate.sha256 from the passing validate receipt without modification'],
+ });
+ }
+ return { rest, candidateSha256 };
+}
+
+async function commandFinalize(rawArgs) {
+ const qualityArgs = extractQualityArgs(rawArgs);
+ const repoArgs = extractRepoRootArgs(qualityArgs.rest);
+ const outDirArgs = extractOutDirArgs(repoArgs.rest);
+ const receiptArgs = extractFinalizeReceiptArgs(outDirArgs.rest);
+ const candidateArgs = extractCandidateSha256Args(receiptArgs.rest);
+ const json = candidateArgs.rest.includes('--json');
+ const knownOptions = new Set(['--json']);
+ const unknown = candidateArgs.rest.filter((arg) => arg.startsWith('--') && !knownOptions.has(arg));
+ if (unknown.length) rejectCliArgument(`Unknown finalize option "${unknown[0]}".`, {
+ code: 'cli/unknown-option',
+ subject: { option: unknown[0] },
+ supportedFixes: ['remove the unknown option and retry'],
+ });
+ const positional = candidateArgs.rest.filter((arg) => !knownOptions.has(arg));
+ const [type, input, output] = positional;
+ if (!type || !input || !output || positional.length !== 3) rejectCliArgument(usage(), {
+ code: 'cli/usage',
+ supportedFixes: ['use: archify finalize <type> <input.json> <output.html> [options]'],
+ });
+ rendererPath(type);
+
+ let runFinalize;
+ try {
+ ({ runFinalize } = await import('./finalize.mjs'));
+ } catch (error) {
+ fail(`Could not load finalize: ${error.message}`, 1);
+ }
+
+ let result;
+ try {
+ const pathIdentityRuntime = await loadPathIdentityRuntime();
+ result = await runFinalize({
+ cliPath: fileURLToPath(import.meta.url),
+ type,
+ input,
+ output,
+ quality: qualityArgs.quality || 'showcase',
+ repoRoot: repoArgs.repoRoot,
+ candidateSha256: candidateArgs.candidateSha256,
+ outDir: outDirArgs.outDir,
+ receiptPath: receiptArgs.receiptPath,
+ inspectDelivery: artifact => inspectArtifactDeliveryProvenance(artifact, true, pathIdentityRuntime),
+ deliveryPaths: artifact => ({
+ provenance: deliveryProvenancePath(artifact),
+ pending: deliveryPendingPath(artifact),
+ lock: deliverySidecarPath(artifact, '.delivery-lock.json'),
+ directoryLock: path.join(path.dirname(deliveryProvenancePath(artifact)), DELIVERY_DIRECTORY_LOCK),
+ }),
+ runBrowserCheck: options => executeBrowserEvidence({
+ ...options, command: 'browser-check', capture: false, requireProvenance: true,
+ }),
+ });
+ } catch (error) {
+ const failure = {
+ schemaVersion: 1,
+ ok: false,
+ command: 'finalize',
+ status: 'fail',
+ type,
+ quality: qualityArgs.quality || 'showcase',
+ specification: { path: path.resolve(input) },
+ artifact: { path: path.resolve(output) },
+ gates: Object.fromEntries(['validate', 'deliver', 'check', 'browser-check'].map((stage) => [stage, 'not-run'])),
+ diagnostics: error.archifyDiagnostics || [{
+ code: error.finalizeCode || 'finalize/runtime',
+ severity: 'error',
+ message: error.message,
+ ...(error.finalizeEvidence ? { evidence: error.finalizeEvidence } : {}),
+ }],
+ visualReview: 'not-requested',
+ };
+ if (json) console.log(JSON.stringify(failure));
+ else console.error(formatDiagnostics('finalize could not start', failure.diagnostics));
+ process.exitCode = 1;
+ return;
+ }
+
+ if (json) {
+ console.log(JSON.stringify(result.summary));
+ } else {
+ console.log(`finalize ${result.summary.status}: ${result.summary.artifact.path}`);
+ console.log(`gates ${Object.entries(result.summary.gates).map(([stage, status]) => `${stage}:${status}`).join(' ')}`);
+ console.log(`receipt ${result.summary.evidence.receipt}`);
+ console.log(`perceptual visual review ${result.summary.visualReview}`);
+ }
+ process.exitCode = result.exitCode;
+}
+
function commandExamples(args) {
const unknown = args.find((arg) => arg.startsWith('--'));
if (unknown) fail(`Unknown examples option "${unknown}".`);
@@ -5589,6 +5760,13 @@ async function commandDoctor(args) {
missing: fs.existsSync(visualCheckRuntime) ? 0 : 1,
});
+ const finalizeRuntime = path.join(skillRoot, 'bin/finalize.mjs');
+ checks.push({
+ label: 'Finalize runtime',
+ ok: fs.existsSync(finalizeRuntime),
+ missing: fs.existsSync(finalizeRuntime) ? 0 : 1,
+ });
+
const outputPathRuntime = path.join(skillRoot, 'renderers/shared/output-path.mjs');
checks.push({
label: 'Output path safety runtime',
@@ -6503,8 +6681,10 @@ async function commandValidate(args) {
}
const inputPath = path.resolve(input);
+ let specification;
try {
- const document = JSON.parse(fs.readFileSync(inputPath, 'utf8'));
+ specification = fs.readFileSync(inputPath);
+ const document = JSON.parse(specification.toString('utf8'));
const [{ validateAuthoredOutputPath }, { validateSchema }] = await Promise.all([
import('../renderers/shared/output-path.mjs'),
import('../renderers/shared/validator.mjs'),
@@ -6565,7 +6745,9 @@ async function commandValidate(args) {
let exitCode = 0;
try {
- const render = runNode([renderer, input, out], {
+ const snapshot = path.join(tmp, 'specification.snapshot.json');
+ fs.writeFileSync(snapshot, specification, { flag: 'wx' });
+ const render = runNode([renderer, snapshot, out], {
stdio: 'pipe',
env: rendererEnv(quality, repoRoot, true),
});
@@ -6606,12 +6788,33 @@ async function commandValidate(args) {
const result = JSON.parse(check.stdout);
const engineeringProfile = engineeringProfileFromArtifact(fs.readFileSync(out));
if (json) {
+ const candidate = {
+ path: path.resolve(input),
+ ...artifactIdentity(specification),
+ };
+ const resolvedQuality = quality || result.composition.profile || 'standard';
console.log(JSON.stringify({
schemaVersion: 1,
ok: true,
command: 'validate',
type,
- input: path.resolve(input),
+ input: candidate.path,
+ candidate,
+ candidateFrozen: true,
+ nextAction: {
+ command: 'finalize',
+ arguments: [
+ type,
+ candidate.path,
+ '<output.html>',
+ '--quality',
+ resolvedQuality,
+ ...(repoRoot ? ['--repo-root', repoRoot] : []),
+ '--candidate-sha256',
+ candidate.sha256,
+ '--json',
+ ],
+ },
checks: result.checks,
composition: result.composition,
...(engineeringProfile ? { engineeringProfile } : {}),
@@ -6650,6 +6853,9 @@ try {
case 'deliver':
await commandDeliver(args);
break;
+ case 'finalize':
+ await commandFinalize(args);
+ break;
case 'preview':
await commandPreview(args);
break;
@@ -6671,6 +6877,9 @@ try {
case 'visual-check':
await commandVisualCheck(args);
break;
+ case 'browser-check':
+ await commandBrowserCheck(args);
+ break;
case 'guide':
await commandGuide(args);
break;
@@ -6691,7 +6900,7 @@ try {
}
} catch (error) {
if (!error.archifyArgument) throw error;
- if (['validate', 'deliver'].includes(command) && args.includes('--json')) {
+ if (['validate', 'deliver', 'finalize'].includes(command) && args.includes('--json')) {
reportArtifactArgumentFailure(command, error);
} else {
fail(error.message);
diff --git a/archify/bin/finalize.mjs b/archify/bin/finalize.mjs
new file mode 100644
index 00000000..582c11da
--- /dev/null
+++ b/archify/bin/finalize.mjs
@@ -0,0 +1,783 @@
+import { execFile } from 'node:child_process';
+import { createHash, randomUUID } from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { canonicalFuturePath, pathsAlias, resolveNativeOutputDirectory, resolveOutputPath } from '../renderers/shared/output-path.mjs';
+import { boundedSidecarStem } from '../renderers/shared/sidecar-path.mjs';
+import {
+ captureAtomicOutput, captureRegularFileBinding, publishRegularFileBinding,
+ releaseRegularFileBinding, removeOwnedRegularFile, verifyAtomicOutput,
+} from '../renderers/shared/atomic-output.mjs';
+import {
+ browserCheckSidecarPaths,
+ CAPTURE_VIEWPORTS,
+ ChromeVisualBrowser,
+ findChrome,
+ THEMES,
+ VISUAL_CHECK_VIEWPORTS,
+} from './visual-check.mjs';
+
+export const FINALIZE_STAGES = Object.freeze(['validate', 'deliver', 'check', 'browser-check']);
+
+function sha256(buffer) {
+ return createHash('sha256').update(buffer).digest('hex');
+}
+
+function identity(file) {
+ try {
+ const bytes = fs.readFileSync(file);
+ return { path: path.resolve(file), sha256: sha256(bytes), bytes: bytes.byteLength };
+ } catch {
+ return { path: path.resolve(file) };
+ }
+}
+
+function durationMs(start) {
+ return Number((process.hrtime.bigint() - start) / 1000000n);
+}
+
+function receiptWriteError(file, state) {
+ const error = new Error(`Could not publish finalize evidence "${file}" safely (${state.reason?.code || state.status}).`);
+ error.finalizeCode = 'finalize/receipt-publication';
+ error.finalizeEvidence = { file, state };
+ return error;
+}
+
+function captureReceipt(file) {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ const capture = captureAtomicOutput(file, { requestedEntryPolicy: 'regular-or-absent' });
+ if (capture.status !== 'captured') throw receiptWriteError(file, capture);
+ return capture;
+}
+
+function writeJsonAtomic(file, value, capture, beforeCommit) {
+ const serialized = Buffer.from(`${JSON.stringify(value, null, 2)}\n`);
+ const temporary = path.join(path.dirname(capture.commitPath), `.archify-finalize-${randomUUID()}.json`);
+ let binding;
+ let stagedIdentity;
+ try {
+ fs.writeFileSync(temporary, serialized, { flag: 'wx' });
+ const metadata = fs.lstatSync(temporary, { bigint: true });
+ stagedIdentity = { device: metadata.dev, inode: metadata.ino };
+ if (capture.mode !== null) fs.chmodSync(temporary, capture.mode);
+ const staged = captureRegularFileBinding(temporary, {
+ subject: 'finalize-receipt', expectedIdentity: stagedIdentity,
+ expectedSha256: sha256(serialized), expectedBytes: serialized.byteLength,
+ ...(capture.mode === null ? {} : { expectedMode: capture.mode }),
+ });
+ if (staged.status !== 'captured') throw receiptWriteError(file, staged);
+ binding = staged.binding;
+ beforeCommit();
+ const publication = publishRegularFileBinding(binding, temporary, capture.snapshot, { subject: 'finalize-receipt' });
+ if (!['committed', 'committed-with-warning'].includes(publication.status)) throw receiptWriteError(file, publication);
+ // Preserve recovery evidence instead of reporting a clean completion when cleanup failed.
+ if (publication.status === 'committed-with-warning') throw receiptWriteError(file, publication);
+ const next = captureReceipt(file);
+ if (!pathsAlias(next.commitPath, capture.commitPath)) {
+ throw receiptWriteError(file, { status: 'different', reason: { code: 'receipt-slot-changed' } });
+ }
+ return next;
+ } finally {
+ if (binding) releaseRegularFileBinding(binding);
+ if (stagedIdentity) removeOwnedRegularFile(temporary, stagedIdentity, { subject: 'finalize-receipt' });
+ }
+}
+
+function parsedReceipt(stdout) {
+ const source = String(stdout || '').trim();
+ if (!source) return null;
+ try { return JSON.parse(source); } catch { return null; }
+}
+
+function isReceiptObject(receipt) {
+ return Boolean(receipt && typeof receipt === 'object' && !Array.isArray(receipt));
+}
+
+function validIdentity(value) {
+ return isReceiptObject(value)
+ && typeof value.sha256 === 'string'
+ && /^[0-9a-f]{64}$/.test(value.sha256)
+ && Number.isSafeInteger(value.bytes)
+ && value.bytes >= 0;
+}
+
+function identitiesMatch(left, right) {
+ return validIdentity(left)
+ && validIdentity(right)
+ && left.sha256 === right.sha256
+ && left.bytes === right.bytes;
+}
+
+function validReceiptId(value) {
+ return typeof value === 'string'
+ && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
+}
+
+function allChecksPassed(checks) {
+ return Array.isArray(checks) && checks.length > 0
+ && checks.every((check) => isReceiptObject(check) && check.ok === true);
+}
+
+function validCheckComposition(receipt, quality) {
+ const composition = receipt?.composition;
+ return isReceiptObject(composition)
+ && composition.schemaVersion === 1
+ && composition.profile === quality
+ && composition.status === 'pass'
+ && composition.summary?.errors === 0
+ && (quality !== 'showcase' || composition.summary?.warnings === 0);
+}
+
+function exactViewportCoverage(entries, viewports, predicate) {
+ if (!Array.isArray(entries) || entries.length !== viewports.length) return false;
+ return viewports.every((expected) => {
+ const matching = entries.filter((entry) => (
+ isReceiptObject(entry)
+ && entry.width === expected.width
+ && entry.height === expected.height
+ && (expected.theme === undefined || entry.requestedTheme === expected.theme)
+ ));
+ return matching.length === 1 && predicate(matching[0], expected);
+ });
+}
+
+function validBrowserEvidence(receipt) {
+ return exactViewportCoverage(receipt.containment?.viewports, VISUAL_CHECK_VIEWPORTS, (entry) => (
+ entry.theme === 'light' && entry.ok === true
+ ))
+ && exactViewportCoverage(receipt.readability?.viewports, VISUAL_CHECK_VIEWPORTS, (entry) => (
+ entry.theme === 'light' && entry.ok === true && entry.readabilityOk === true
+ ))
+ && exactViewportCoverage(receipt.viewerChrome?.viewports, VISUAL_CHECK_VIEWPORTS, (entry) => (
+ entry.theme === 'light' && entry.ok === true && entry.viewerChromeOk === true
+ ))
+ && exactViewportCoverage(receipt.themeStates?.viewports,
+ CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map((theme) => ({ width, height, theme }))),
+ (entry, expected) => entry.ok === true
+ && entry.requestedTheme === expected.theme
+ && entry.resolvedTheme === expected.theme);
+}
+
+function validDeliveryValidation(receipt, quality) {
+ const validation = receipt?.validation;
+ return isReceiptObject(validation)
+ && Number.isInteger(validation.checkCount)
+ && validation.checkCount > 0
+ && validation.checksPassed === validation.checkCount
+ && validation.compositionStatus === 'pass'
+ && validation.errors === 0
+ && validation.compositionProfile === quality
+ && (quality !== 'showcase' || validation.warnings === 0);
+}
+
+function validStageReceipt(stage, receipt, quality) {
+ if (!isReceiptObject(receipt) || receipt.ok !== true) return false;
+ if (receipt.status && receipt.status !== 'pass') return false;
+ if (stage === 'validate') return receipt.command === 'validate' && Array.isArray(receipt.checks);
+ if (stage === 'deliver') {
+ return receipt.command === 'deliver'
+ && receipt.schemaVersion === 1
+ && validReceiptId(receipt.receiptId)
+ && isReceiptObject(receipt.specification)
+ && validIdentity(receipt.specification)
+ && validIdentity(receipt.artifact)
+ && validDeliveryValidation(receipt, quality);
+ }
+ if (stage === 'check') {
+ return validIdentity(receipt.artifact)
+ && allChecksPassed(receipt.checks)
+ && receipt.provenance === 'current'
+ && validReceiptId(receipt.deliveryReceiptId)
+ && validCheckComposition(receipt, quality);
+ }
+ return receipt.command === 'browser-check'
+ && receipt.schemaVersion === 1
+ && receipt.status === 'pass'
+ && receipt.evidenceKind === 'automated-browser'
+ && validIdentity(receipt.artifact)
+ && receipt.provenance === 'current'
+ && validReceiptId(receipt.deliveryReceiptId)
+ && receipt.containment?.status === 'pass'
+ && receipt.themeStates?.status === 'pass'
+ && receipt.readability?.status === 'pass'
+ && receipt.viewerChrome?.status === 'pass'
+ && validBrowserEvidence(receipt);
+}
+
+function identityMismatchDiagnostic({ stage, expected, actual, expectedReceiptId, actualReceiptId, output }) {
+ return {
+ code: 'finalize/artifact-binding-mismatch',
+ severity: 'error',
+ message: `The ${stage} receipt does not prove the artifact delivered by this finalize run.`,
+ subject: { stage, artifact: output },
+ evidence: {
+ expectedArtifact: expected,
+ actualArtifact: actual,
+ ...(expectedReceiptId ? { expectedDeliveryReceiptId: expectedReceiptId } : {}),
+ ...(actualReceiptId ? { actualDeliveryReceiptId: actualReceiptId } : {}),
+ },
+ supportedFixes: ['finish other delivery attempts for this output, then rerun finalize from the frozen candidate'],
+ };
+}
+
+function stageBindingDiagnostic({ stage, receipt, expectedArtifact, expectedReceiptId, output, specification, type, deliveryValidation }) {
+ if (stage === 'deliver') {
+ if (receipt.type !== type) {
+ return {
+ code: 'finalize/delivery-type-mismatch',
+ severity: 'error',
+ message: 'The delivery command reported a different diagram type than finalize requested.',
+ subject: { stage: 'deliver', artifact: output },
+ evidence: { expectedType: type, actualType: receipt.type },
+ supportedFixes: ['rerun finalize with a delivery command for the requested diagram type'],
+ };
+ }
+ if (!identitiesMatch(receipt.specification, specification)) {
+ return {
+ code: 'finalize/candidate-changed-during-delivery',
+ severity: 'error',
+ message: 'The delivery command froze a different candidate than finalize started with.',
+ subject: { stage: 'validate', candidate: specification.path },
+ evidence: {
+ expectedSha256: specification.sha256,
+ actualSha256: receipt.specification?.sha256,
+ expectedBytes: specification.bytes,
+ actualBytes: receipt.specification?.bytes,
+ },
+ supportedFixes: ['restore the frozen candidate and rerun finalize'],
+ };
+ }
+ if ((!receipt.output || !pathsAlias(receipt.output, output)) || !identitiesMatch(receipt.artifact, identity(output))) {
+ return identityMismatchDiagnostic({
+ stage,
+ expected: receipt.artifact,
+ actual: identity(output),
+ expectedReceiptId: receipt.receiptId,
+ output,
+ });
+ }
+ return null;
+ }
+ if (stage === 'check' && deliveryValidation?.checkCount !== receipt.checks.length) {
+ return {
+ code: 'finalize/delivery-validation-mismatch',
+ severity: 'error',
+ message: 'The delivery validation count does not match the complete checker receipt for the delivered artifact.',
+ subject: { stage: 'check', artifact: output },
+ evidence: {
+ deliveryCheckCount: deliveryValidation?.checkCount,
+ checkerCheckCount: receipt.checks.length,
+ },
+ supportedFixes: ['restore the complete delivery validation receipt and rerun finalize from the frozen candidate'],
+ };
+ }
+ const receiptArtifactPath = receipt.artifact?.path;
+ const receiptFile = receipt.file;
+ const pathMatchesOutput = stage === 'check'
+ ? typeof receiptFile === 'string' && pathsAlias(receiptFile, output)
+ : typeof receiptArtifactPath === 'string' && pathsAlias(receiptArtifactPath, output);
+ if (!pathMatchesOutput
+ || !identitiesMatch(receipt.artifact, expectedArtifact)
+ || receipt.deliveryReceiptId !== expectedReceiptId) {
+ return identityMismatchDiagnostic({
+ stage,
+ expected: expectedArtifact,
+ actual: receipt.artifact,
+ expectedReceiptId,
+ actualReceiptId: receipt.deliveryReceiptId,
+ output,
+ });
+ }
+ return null;
+}
+
+function finalArtifactDiagnostic({ output, expectedArtifact, expectedReceiptId, type, deliveryPath, inspectDelivery }) {
+ // Recheck dev's pending/lock, physical identity, and regular-file provenance barriers at handoff.
+ const provenance = inspectDelivery?.(output);
+ if (provenance && (!provenance.ok || provenance.receiptId !== expectedReceiptId)) {
+ return provenance.diagnostics?.[0] || identityMismatchDiagnostic({
+ stage: 'finalize', output, expected: expectedArtifact,
+ expectedReceiptId, actualReceiptId: provenance.receiptId,
+ });
+ }
+ const currentArtifact = identity(output);
+ let delivery;
+ try {
+ delivery = JSON.parse(fs.readFileSync(deliveryPath, 'utf8'));
+ } catch {
+ delivery = null;
+ }
+ if (identitiesMatch(currentArtifact, expectedArtifact)
+ && delivery?.schemaVersion === 1
+ && delivery.command === 'deliver'
+ && delivery.status === 'current'
+ && delivery.receiptId === expectedReceiptId
+ && delivery.type === type
+ && typeof delivery.output === 'string' && pathsAlias(delivery.output, output)
+ && identitiesMatch(delivery.artifact, expectedArtifact)) return null;
+ return {
+ code: 'finalize/final-artifact-mismatch',
+ severity: 'error',
+ message: 'The artifact or delivery receipt changed after the final gate completed.',
+ subject: { stage: 'finalize', artifact: output },
+ evidence: {
+ expectedArtifact,
+ currentArtifact,
+ expectedDeliveryReceiptId: expectedReceiptId,
+ expectedType: type,
+ ...(delivery?.receiptId ? { currentDeliveryReceiptId: delivery.receiptId } : {}),
+ ...(delivery?.type ? { currentType: delivery.type } : {}),
+ ...(delivery?.artifact ? { currentDeliveryArtifact: delivery.artifact } : {}),
+ },
+ supportedFixes: ['finish other delivery attempts for this output, then rerun finalize from the frozen candidate'],
+ };
+}
+
+function stageStatus(stage, exitCode, receipt, quality) {
+ if (exitCode === 2 || receipt?.status === 'skipped') return 'skipped';
+ return exitCode === 0 && validStageReceipt(stage, receipt, quality) ? 'pass' : 'fail';
+}
+
+function failureDiagnostics(stage, result, receipt, quality) {
+ if (Array.isArray(receipt?.diagnostics) && receipt.diagnostics.length) return receipt.diagnostics;
+ const invalidReceipt = (result.status ?? 1) === 0 && !validStageReceipt(stage, receipt, quality);
+ return [{
+ code: invalidReceipt ? 'finalize/invalid-stage-receipt' : 'finalize/stage-failure',
+ severity: 'error',
+ message: invalidReceipt
+ ? `The ${stage} stage exited successfully without a valid passing receipt.`
+ : `The ${stage} stage did not complete successfully.`,
+ subject: { stage },
+ evidence: {
+ exitCode: result.status ?? 1,
+ ...(result.signal ? { signal: result.signal } : {}),
+ ...(result.error?.message ? { reason: result.error.message } : {}),
+ ...(String(result.stdout || '').trim() ? { stdout: String(result.stdout).trim().slice(0, 2000) } : {}),
+ ...(String(result.stderr || '').trim() ? { stderr: String(result.stderr).trim().slice(0, 2000) } : {}),
+ },
+ supportedFixes: [invalidReceipt
+ ? `restore the ${stage} JSON receipt contract before retrying finalize`
+ : 'use the compact finalize summary to repair the named subject in place, then rerun finalize once'],
+ }];
+}
+
+function sidecarFile(directory, value) {
+ if (!value) return null;
+ return path.resolve(directory, value);
+}
+
+function browserEvidence(receipt, artifactPath) {
+ if (!receipt) return {};
+ const directory = receipt.sidecars?.directory
+ ? path.resolve(receipt.sidecars.directory)
+ : path.dirname(path.resolve(artifactPath));
+ return {
+ ...(receipt.sidecars?.receipt ? { browserCheckReceipt: sidecarFile(directory, receipt.sidecars.receipt) } : {}),
+ };
+}
+
+function defaultRunner({ cliPath, args, cwd, env }) {
+ return new Promise((resolve) => {
+ execFile(process.execPath, [cliPath, ...args], { cwd, env, encoding: 'utf8' }, (error, stdout, stderr) => {
+ resolve({
+ status: error ? (Number.isInteger(error.code) ? error.code : 1) : 0,
+ stdout,
+ stderr,
+ ...(error ? { error, signal: error.signal } : {}),
+ });
+ });
+ });
+}
+
+function stageArguments({ stage, type, input, output, quality, repoRoot, outDir }) {
+ const qualityArgs = ['--quality', quality];
+ const repoArgs = repoRoot ? ['--repo-root', repoRoot] : [];
+ if (stage === 'validate') return ['validate', type, input, ...qualityArgs, ...repoArgs, '--json'];
+ if (stage === 'deliver') return ['deliver', type, input, output, ...qualityArgs, ...repoArgs, '--json'];
+ if (stage === 'check') return ['check', output, '--require-provenance'];
+ return [
+ 'browser-check', output, '--json', '--require-provenance',
+ ...(outDir ? ['--out-dir', outDir] : []),
+ ];
+}
+
+export function defaultFinalizeReceiptPath(output, { outDir } = {}) {
+ // Reuse the physical artifact and cross-directory namespace used by browser evidence.
+ const browserReceipt = browserCheckSidecarPaths(output, { outDir }).receipt;
+ const stem = path.basename(browserReceipt).slice(0, -'.browser-check.json'.length);
+ return path.join(path.dirname(browserReceipt), `${boundedSidecarStem(stem, ['.finalize.json', '.finalize-summary.json'])}.finalize.json`);
+}
+
+export function defaultFinalizeSummaryPath(receiptPath) {
+ const receipt = path.resolve(receiptPath);
+ const component = path.basename(receipt);
+ const isDefault = /\.finalize\.json$/i.test(component);
+ const stem = component.replace(isDefault ? /\.finalize\.json$/i : /\.json$/i, '');
+ const suffix = isDefault ? '.finalize-summary.json' : '-summary.json';
+ // Already bounded default stems share the receipt namespace; avoid hashing twice.
+ const summaryStem = Buffer.byteLength(`${stem}${suffix}`) <= 255 && `${stem}${suffix}`.length <= 255
+ ? stem : boundedSidecarStem(stem, [suffix]);
+ return path.join(path.dirname(receipt), `${summaryStem}${suffix}`);
+}
+
+function defaultDeliveryPaths(output) {
+ const artifact = canonicalFuturePath(output);
+ const delivery = artifact.replace(/\.html?$/i, '.delivery.json');
+ return {
+ provenance: delivery,
+ pending: delivery.replace(/\.json$/i, '-pending.json'),
+ lock: delivery.replace(/\.json$/i, '-lock.json'),
+ directoryLock: path.join(path.dirname(artifact), '.archify-delivery-lock.json'),
+ };
+}
+
+function reservedFinalizePaths({ input, output, outDir, deliveryPaths }) {
+ const browser = browserCheckSidecarPaths(output, { outDir });
+ return [path.resolve(input), path.resolve(output), ...Object.values(deliveryPaths(output)), browser.receipt];
+}
+
+export function compactFinalizeReceipt(receipt) {
+ const gates = {};
+ for (const stage of FINALIZE_STAGES) gates[stage] = receipt.stages?.[stage]?.status || 'not-run';
+ const allDiagnostics = receipt.diagnostics || [];
+ const diagnosticLimit = 8;
+ const selectedDiagnostics = [];
+ const selectedIndexes = new Set();
+ const seenCodes = new Set();
+ const seenSubjects = new Set();
+ const subjectKey = (entry) => {
+ const subject = entry?.subject;
+ if (!subject) return null;
+ if (typeof subject === 'string') return subject;
+ if (typeof subject !== 'object' || Array.isArray(subject)) return JSON.stringify(subject);
+ for (const key of ['id', 'edge', 'connection', 'relationship', 'component', 'node', 'path', 'stage']) {
+ if (subject[key] !== undefined) return `${key}:${JSON.stringify(subject[key])}`;
+ }
+ return JSON.stringify(subject);
+ };
+ const addDiagnostic = (entry, index) => {
+ if (selectedDiagnostics.length >= diagnosticLimit || selectedIndexes.has(index)) return;
+ selectedIndexes.add(index);
+ selectedDiagnostics.push({
+ code: entry.code,
+ severity: entry.severity || 'error',
+ message: entry.message,
+ ...(entry.subject ? { subject: entry.subject } : {}),
+ ...(entry.evidence && Object.keys(entry.evidence).length ? { evidence: entry.evidence } : {}),
+ ...(Array.isArray(entry.supportedFixes) && entry.supportedFixes.length
+ ? { supportedFixes: entry.supportedFixes.slice(0, 2) } : {}),
+ });
+ };
+ for (const [index, entry] of allDiagnostics.entries()) {
+ if (seenCodes.has(entry.code)) continue;
+ seenCodes.add(entry.code);
+ addDiagnostic(entry, index);
+ }
+ for (const [index, entry] of allDiagnostics.entries()) {
+ const key = subjectKey(entry);
+ if (!key || seenSubjects.has(key)) continue;
+ seenSubjects.add(key);
+ addDiagnostic(entry, index);
+ }
+ for (const [index, entry] of allDiagnostics.entries()) addDiagnostic(entry, index);
+ const compact = {
+ schemaVersion: 1,
+ ok: receipt.ok,
+ command: 'finalize',
+ status: receipt.status,
+ type: receipt.type,
+ quality: receipt.quality,
+ specification: receipt.specification,
+ artifact: receipt.artifact,
+ gates,
+ ...(receipt.failedStage ? { failedStage: receipt.failedStage } : {}),
+ diagnostics: selectedDiagnostics,
+ diagnosticSummary: {
+ total: allDiagnostics.length,
+ shown: selectedDiagnostics.length,
+ truncated: allDiagnostics.length > selectedDiagnostics.length,
+ },
+ evidence: receipt.evidence,
+ visualReview: receipt.visualReview || 'not-requested',
+ durationMs: receipt.durationMs,
+ };
+ if (!receipt.ok && receipt.status === 'fail' && receipt.failedStage === 'validate') {
+ compact.nextAction = {
+ action: 'edit-in-place',
+ candidate: receipt.specification?.path,
+ constraint: 'Preserve unaffected semantics and geometry; do not replace the whole candidate.',
+ then: 'finalize-once',
+ };
+ }
+ return compact;
+}
+
+export async function runFinalize({
+ cliPath,
+ type,
+ input,
+ output,
+ quality = 'showcase',
+ repoRoot,
+ candidateSha256,
+ outDir,
+ receiptPath,
+ deliveryPaths = defaultDeliveryPaths,
+ inspectDelivery,
+ cwd = process.cwd(),
+ env = process.env,
+ runCommand = defaultRunner,
+ runBrowserCheck,
+ resolveChrome = findChrome,
+ createBrowser = (chromePath, options) => new ChromeVisualBrowser(chromePath, options),
+} = {}) {
+ if (!cliPath || !type || !input || !output) throw new Error('finalize requires cliPath, type, input, and output.');
+ const started = process.hrtime.bigint();
+ const startedAt = new Date().toISOString();
+ const resolvedInput = path.resolve(input);
+ const resolvedOutput = resolveOutputPath({ requestedOutput: output, inputPaths: [resolvedInput] }).outputPath;
+ const resolvedOutDir = outDir === undefined ? undefined : resolveNativeOutputDirectory(outDir);
+ const specification = identity(resolvedInput);
+ if (candidateSha256 && specification.sha256 !== candidateSha256) {
+ const error = new Error(`The candidate changed after validation: expected sha256 ${candidateSha256}, found ${specification.sha256 || 'unreadable'}.`);
+ error.finalizeCode = 'finalize/candidate-changed';
+ error.finalizeEvidence = {
+ candidate: resolvedInput,
+ expectedSha256: candidateSha256,
+ ...(specification.sha256 ? { actualSha256: specification.sha256 } : {}),
+ };
+ throw error;
+ }
+ // Validate raw native CLI paths before creating directories or normalizing them.
+ if (receiptPath !== undefined) resolveOutputPath({ requestedOutput: receiptPath, inputPaths: [resolvedInput], requiredExtension: '.json' });
+ fs.mkdirSync(path.dirname(canonicalFuturePath(resolvedOutput)), { recursive: true });
+ const resolvedReceipt = resolveOutputPath({
+ requestedOutput: receiptPath ?? defaultFinalizeReceiptPath(resolvedOutput, { outDir: resolvedOutDir }),
+ inputPaths: [resolvedInput], requiredExtension: '.json',
+ }).outputPath;
+ const resolvedSummary = resolveOutputPath({
+ requestedOutput: defaultFinalizeSummaryPath(resolvedReceipt), inputPaths: [resolvedInput], requiredExtension: '.json',
+ }).outputPath;
+ const assertReceiptPaths = () => {
+ const reserved = reservedFinalizePaths({ input: resolvedInput, output: resolvedOutput, outDir: resolvedOutDir, deliveryPaths });
+ const receiptCollision = reserved.find((file) => pathsAlias(resolvedReceipt, file));
+ if (receiptCollision) throw new Error(`The finalize receipt must be distinct from the specification, artifact, and gate sidecars: "${receiptCollision}".`);
+ const summaryCollision = [resolvedReceipt, ...reserved].find((file) => pathsAlias(resolvedSummary, file));
+ if (summaryCollision) throw new Error(`The finalize summary must be distinct from the full receipt, specification, artifact, and gate sidecars: "${summaryCollision}".`);
+ };
+ assertReceiptPaths();
+ // Capture both paths before changing either: an unsafe summary cannot leave a new full receipt behind.
+ let receiptCapture = captureReceipt(resolvedReceipt);
+ let summaryCapture = captureReceipt(resolvedSummary);
+
+ const receipt = {
+ schemaVersion: 1,
+ ok: false,
+ command: 'finalize',
+ status: 'running',
+ type,
+ quality,
+ startedAt,
+ specification,
+ artifact: { path: resolvedOutput },
+ stages: {},
+ diagnostics: [],
+ evidence: { receipt: resolvedReceipt, summaryReceipt: resolvedSummary },
+ visualReview: 'not-requested',
+ };
+ const persistReceipts = () => {
+ assertReceiptPaths();
+ for (const [file, capture] of [[resolvedReceipt, receiptCapture], [resolvedSummary, summaryCapture]]) {
+ const current = verifyAtomicOutput(capture.snapshot);
+ if (current.status !== 'match') throw receiptWriteError(file, current);
+ }
+ receiptCapture = writeJsonAtomic(resolvedReceipt, receipt, receiptCapture, assertReceiptPaths);
+ summaryCapture = writeJsonAtomic(resolvedSummary, compactFinalizeReceipt(receipt), summaryCapture, assertReceiptPaths);
+ };
+ persistReceipts();
+
+ // Only launch/attach the blank browser here. The normal browser gate still
+ // verifies current delivery provenance before it consumes this one-shot factory.
+ const chromePath = runBrowserCheck ? resolveChrome({ env }) : null;
+ let browser;
+ let browserStartupError;
+ let browserTransferred = false;
+ if (chromePath) {
+ try {
+ browser = createBrowser(chromePath, { env });
+ // Deliver/check may fail before inspect() awaits startup. Handle the
+ // rejection now while retaining the same promise for the browser gate.
+ browser.sessionPromise.catch(() => {});
+ } catch (error) {
+ browserStartupError = error;
+ }
+ }
+ const browserFactory = () => {
+ if (browserStartupError) throw browserStartupError;
+ if (browserTransferred || !browser) throw new Error('The finalize browser is unavailable or already consumed.');
+ browserTransferred = true;
+ return browser;
+ };
+
+ try {
+ let exitCode = 0;
+ for (const stage of ['deliver', 'check', 'browser-check']) {
+ const stageStarted = process.hrtime.bigint();
+ const args = stageArguments({
+ stage,
+ type,
+ input: resolvedInput,
+ output: resolvedOutput,
+ quality,
+ repoRoot,
+ outDir: resolvedOutDir,
+ });
+ const inProcess = stage === 'browser-check' && runBrowserCheck;
+ let result;
+ if (inProcess) {
+ const checked = await runBrowserCheck({
+ artifactPath: resolvedOutput,
+ outDir: resolvedOutDir,
+ chromePath,
+ resolveChrome: () => chromePath,
+ browserFactory,
+ });
+ result = { status: checked.exitCode, stdout: JSON.stringify(checked.receipt) };
+ } else {
+ result = await runCommand({ stage, cliPath, args, cwd, env });
+ }
+ const stageReceipt = parsedReceipt(result.stdout);
+ const code = result.status ?? 1;
+ let status = stageStatus(stage, code, stageReceipt, quality);
+ let stageDiagnostics;
+ const command = [process.execPath, cliPath, ...args];
+ const elapsed = durationMs(stageStarted);
+ if (status === 'pass') {
+ const deliveryReceipt = stage === 'deliver' ? stageReceipt : receipt.stages.deliver?.receipt;
+ const bindingDiagnostic = stageBindingDiagnostic({
+ stage,
+ receipt: stageReceipt,
+ expectedArtifact: deliveryReceipt?.artifact,
+ expectedReceiptId: deliveryReceipt?.receiptId,
+ output: resolvedOutput,
+ specification,
+ type,
+ deliveryValidation: deliveryReceipt?.validation,
+ });
+ if (bindingDiagnostic) stageDiagnostics = [bindingDiagnostic];
+ }
+ if (stageDiagnostics) {
+ status = 'fail';
+ }
+ const stageEntry = {
+ status,
+ exitCode: code,
+ durationMs: elapsed,
+ command,
+ ...(inProcess ? { execution: 'in-process' } : {}),
+ ...(stageReceipt ? { receipt: stageReceipt } : {}),
+ ...(!stageReceipt && String(result.stdout || '').trim() ? { stdout: String(result.stdout).trim() } : {}),
+ ...(String(result.stderr || '').trim() ? { stderr: String(result.stderr).trim() } : {}),
+ ...(result.signal ? { signal: result.signal } : {}),
+ };
+
+ if (stage === 'deliver' && status === 'pass') {
+ receipt.stages.validate = {
+ status: 'pass',
+ exitCode: 0,
+ durationMs: null,
+ execution: 'embedded-in-deliver',
+ command,
+ receipt: {
+ schemaVersion: 1,
+ ok: true,
+ command: 'validate',
+ specification: stageReceipt.specification,
+ validation: stageReceipt.validation,
+ },
+ };
+ receipt.stages.deliver = stageEntry;
+ } else if (stage === 'deliver') {
+ const validationFailed = stageDiagnostics?.some((diagnostic) => diagnostic.code === 'finalize/candidate-changed-during-delivery')
+ || ['input', 'render', 'check'].includes(stageReceipt?.stage);
+ receipt.stages.validate = validationFailed ? {
+ ...stageEntry,
+ status: 'fail',
+ durationMs: null,
+ execution: 'embedded-in-deliver',
+ } : { status: 'not-run', execution: 'embedded-in-deliver' };
+ receipt.stages.deliver = validationFailed
+ ? { status: 'not-run', execution: 'blocked-by-validate' }
+ : stageEntry;
+ } else {
+ receipt.stages[stage] = stageEntry;
+ }
+
+ if (stage === 'deliver' && stageReceipt?.artifact) receipt.artifact = {
+ path: resolvedOutput,
+ ...stageReceipt.artifact,
+ };
+ if (stage === 'browser-check') {
+ receipt.evidence = {
+ receipt: resolvedReceipt,
+ summaryReceipt: resolvedSummary,
+ ...browserEvidence(stageReceipt, resolvedOutput),
+ };
+ }
+
+ if (status !== 'pass') {
+ exitCode = status === 'skipped' ? 2 : (code || 1);
+ receipt.status = status;
+ receipt.diagnostics = stageDiagnostics || failureDiagnostics(stage, result, stageReceipt, quality);
+ receipt.failedStage = stage === 'deliver'
+ && receipt.stages.validate.status === 'fail' ? 'validate' : stage;
+ break;
+ }
+ persistReceipts();
+ }
+
+ receipt.ok = exitCode === 0;
+ receipt.status = receipt.ok ? 'pass' : receipt.status === 'running' ? 'fail' : receipt.status;
+ if (receipt.ok) {
+ const deliveryReceipt = receipt.stages.deliver?.receipt;
+ const diagnostic = finalArtifactDiagnostic({
+ output: resolvedOutput,
+ expectedArtifact: deliveryReceipt?.artifact,
+ expectedReceiptId: deliveryReceipt?.receiptId,
+ type,
+ deliveryPath: deliveryPaths(resolvedOutput).provenance,
+ inspectDelivery,
+ });
+ if (diagnostic) {
+ exitCode = 1;
+ receipt.ok = false;
+ receipt.status = 'fail';
+ receipt.failedStage = 'finalize';
+ receipt.diagnostics = [diagnostic];
+ }
+ }
+ if (receipt.ok && !identitiesMatch(specification, identity(resolvedInput))) {
+ exitCode = 1;
+ receipt.ok = false;
+ receipt.status = 'fail';
+ receipt.failedStage = 'finalize';
+ receipt.diagnostics = [{
+ code: 'finalize/candidate-changed', severity: 'error',
+ message: 'The frozen candidate changed before the final handoff.',
+ subject: { candidate: resolvedInput },
+ evidence: { expected: specification, actual: identity(resolvedInput) },
+ supportedFixes: ['restore the frozen candidate, or finalize the edited candidate as a new attempt'],
+ }];
+ }
+ receipt.artifact = receipt.ok
+ ? { path: resolvedOutput, ...receipt.stages.deliver.receipt.artifact }
+ : identity(resolvedOutput);
+ receipt.finishedAt = new Date().toISOString();
+ receipt.durationMs = durationMs(started);
+ persistReceipts();
+ return { exitCode, receipt, summary: compactFinalizeReceipt(receipt) };
+ } finally {
+ if (browser && !browserTransferred) await browser.close();
+ }
+}
diff --git a/archify/bin/visual-check.mjs b/archify/bin/visual-check.mjs
index f2bb6645..c5666652 100644
--- a/archify/bin/visual-check.mjs
+++ b/archify/bin/visual-check.mjs
@@ -74,7 +74,7 @@ function pathEntry(file) {
}
function visualEvidencePaths(outputs) {
- return [outputs.contactSheet, ...outputs.screenshots.map((entry) => entry.path)];
+ return outputs.capture === false ? [] : [outputs.contactSheet, ...outputs.screenshots.map((entry) => entry.path)];
}
function regularFileEvidence(file, { expectedLinks = 1 } = {}) {
@@ -186,7 +186,7 @@ function targetSidecarNamespace(directory, component) {
throw error;
}
-export function sidecarPaths(artifactPath, { outDir } = {}) {
+function evidenceSidecarPaths(artifactPath, { outDir, command = 'visual-check', capture = true } = {}) {
let artifact = path.resolve(artifactPath);
try {
// Existing aliases, including Windows 8.3 spellings, must share the
@@ -210,30 +210,38 @@ export function sidecarPaths(artifactPath, { outDir } = {}) {
|| portableTargetKey !== namespace.componentKey;
const stem = boundedSidecarStem(
namespaceStem.stem,
- VISUAL_SIDECAR_SUFFIXES,
+ capture ? VISUAL_SIDECAR_SUFFIXES : ['.browser-check.json'],
targetAliasesSourceSpelling ? {
force: true,
- hashDomain: `visual-check-artifact\0${artifact}\0target-component\0${portableTargetKey}`,
+ hashDomain: `${command}-artifact\0${artifact}\0target-component\0${portableTargetKey}`,
} : namespaceStem.options,
);
- const base = path.join(directory, `${stem}.visual-check`);
- const screenshots = CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map((theme) => ({
+ const base = path.join(directory, `${stem}.${command}`);
+ const screenshots = (capture ? CAPTURE_VIEWPORTS : []).flatMap(({ width, height }) => THEMES.map((theme) => ({
width,
height,
theme,
path: `${base}.${width}x${height}.${theme}.png`,
})));
return {
- base,
+ base, command, capture,
receipt: `${base}.json`,
contactSheet: `${base}.html`,
screenshots,
};
}
+export function sidecarPaths(artifactPath, options = {}) {
+ return evidenceSidecarPaths(artifactPath, options);
+}
+
+export function browserCheckSidecarPaths(artifactPath, options = {}) {
+ return evidenceSidecarPaths(artifactPath, { ...options, command: 'browser-check', capture: false });
+}
+
function evidencePathConflict(artifactPath, outputs, file, reason) {
const target = file || outputs.receipt;
- const error = `visual-check will not replace the existing unowned evidence path "${target}".`;
+ const error = `${outputs.command} will not replace the existing unowned evidence path "${target}".`;
return {
ok: false,
error,
@@ -243,7 +251,7 @@ function evidencePathConflict(artifactPath, outputs, file, reason) {
subject: { artifact: path.resolve(artifactPath), evidencePath: target },
evidence: { reason },
supportedFixes: [
- 'move the conflicting file aside, or choose a separate --out-dir, then rerun visual-check',
+ `move the conflicting file aside, or choose a separate --out-dir, then rerun ${outputs.command}`,
],
}),
};
@@ -259,7 +267,7 @@ function visualEvidenceOwnershipMatches(ownership, artifactPath, outputs) {
function visualEvidenceTargets(outputs) {
return [
{ kind: 'receipt', path: outputs.receipt },
- { kind: 'contact-sheet', path: outputs.contactSheet },
+ ...(outputs.capture === false ? [] : [{ kind: 'contact-sheet', path: outputs.contactSheet }]),
...outputs.screenshots.map((entry, index) => ({
kind: 'screenshot',
index,
@@ -675,7 +683,7 @@ function beginVisualEvidenceWrite(artifactPath, artifactBytes, outputs) {
...previousReceipt.evidence,
});
- if (previous?.schemaVersion !== 1 || previous?.command !== 'visual-check') {
+ if (previous?.schemaVersion !== 1 || previous?.command !== outputs.command) {
return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
code: 'ownership-receipt-schema-mismatch',
});
@@ -686,12 +694,12 @@ function beginVisualEvidenceWrite(artifactPath, artifactBytes, outputs) {
const receiptNameSafe = typeof recordedReceiptName === 'string'
// path-contract-allow: portable-logical-path -- receipt filenames are serialized logical basenames.
&& path.basename(recordedReceiptName) === recordedReceiptName;
- const contactNameSafe = typeof recordedContactName === 'string'
+ const contactNameSafe = outputs.capture === false || typeof recordedContactName === 'string'
// path-contract-allow: portable-logical-path -- contact-sheet filenames are serialized logical basenames.
&& path.basename(recordedContactName) === recordedContactName;
if (!path.isAbsolute(recordedDirectory) || !receiptNameSafe || !contactNameSafe
|| sameLocation(path.join(recordedDirectory, recordedReceiptName), outputs.receipt).status !== 'match'
- || sameLocation(path.join(recordedDirectory, recordedContactName), outputs.contactSheet).status !== 'match') {
+ || (outputs.capture !== false && sameLocation(path.join(recordedDirectory, recordedContactName), outputs.contactSheet).status !== 'match')) {
return evidencePathConflict(artifactPath, outputs, outputs.receipt, {
code: 'ownership-sidecar-path-mismatch',
});
@@ -1960,7 +1968,7 @@ function resolveSidecarDirectory(artifactPath, outputs, compareParents) {
const sidecars = {
...(comparison?.status === 'different' ? { directory: sidecarDirectory } : {}),
receipt: path.basename(outputs.receipt),
- contactSheet: path.basename(outputs.contactSheet),
+ ...(outputs.capture === false ? {} : { contactSheet: path.basename(outputs.contactSheet) }),
};
if (comparison?.status === 'match' || comparison?.status === 'different') {
return { ok: true, sidecars };
@@ -2009,9 +2017,23 @@ export function verticalBudgetFixes(entry) {
return fixes;
}
-function observationDiagnostics({ artifact, allObservations, readabilityObservations }) {
+function observationDiagnostics({ artifact, allObservations, readabilityObservations, command }) {
const diagnostics = [];
for (const entry of allObservations) {
+ if (entry.resolvedTheme !== entry.theme) {
+ diagnostics.push(failureDiagnostic({
+ code: 'viewer/theme-state',
+ message: `The rendered artifact resolved ${entry.resolvedTheme || 'no theme'} instead of the requested ${entry.theme} theme at ${entry.width}x${entry.height}.`,
+ subject: viewportSubject(artifact, entry),
+ evidence: {
+ requestedTheme: entry.theme,
+ resolvedTheme: entry.resolvedTheme,
+ },
+ supportedFixes: [
+ `restore deterministic ${entry.theme} theme resolution, then rerun ${command}`,
+ ],
+ }));
+ }
if (!entry.ok) {
const budgetFixes = verticalBudgetFixes(entry);
diagnostics.push(failureDiagnostic({
@@ -2043,8 +2065,8 @@ function observationDiagnostics({ artifact, allObservations, readabilityObservat
...(entry.overflowY && entry.workflowLanes?.length ? [
'run validate workflow <source.json> --layout-json and compare the tallest rendered lane frames with source lanes, col and yOffset; frame IDs are rendered indices, not source lane IDs',
'where ownership and explicit geometry permit, distribute stacked steps across logical columns and meaningful lanes before increasing yOffset; preserve nodes, branches, labels and hard pins',
- 'read references/authoring-contract.md#workflow-viewport-repair, then validate and deliver the changed source before rerunning visual-check on the new artifact; this is inspection guidance, not a verified coordinate fix',
- ] : budgetFixes.length ? [] : [`contain the rendered layout within ${entry.width}x${entry.height}, then rerun visual-check`]),
+ `read references/authoring-contract.md#workflow-viewport-repair, then validate and deliver the changed source before rerunning ${command} on the new artifact; this is inspection guidance, not a verified coordinate fix`,
+ ] : budgetFixes.length ? [] : [`contain the rendered layout within ${entry.width}x${entry.height}, then rerun ${command}`]),
],
}));
}
@@ -2055,7 +2077,7 @@ function observationDiagnostics({ artifact, allObservations, readabilityObservat
subject: viewportSubject(artifact, entry),
evidence: { legendDockIntersectionArea: entry.legendDockIntersectionArea },
supportedFixes: [
- 'move the SVG Legend or Viewer Dock until legendDockIntersectionArea is 0, then rerun visual-check',
+ `move the SVG Legend or Viewer Dock until legendDockIntersectionArea is 0, then rerun ${command}`,
],
}));
}
@@ -2073,7 +2095,7 @@ function observationDiagnostics({ artifact, allObservations, readabilityObservat
requiredDockStageGap: entry.requiredDockStageGap,
},
supportedFixes: [
- `adjust Viewer stage reservation or clipping until dockStageGap is at least ${entry.requiredDockStageGap} and dockStageIntersectionArea is 0, then rerun visual-check`,
+ `adjust Viewer stage reservation or clipping until dockStageGap is at least ${entry.requiredDockStageGap} and dockStageIntersectionArea is 0, then rerun ${command}`,
],
}));
}
@@ -2092,21 +2114,21 @@ function observationDiagnostics({ artifact, allObservations, readabilityObservat
minimumRequiredNodeTextPx: entry.minimumRequiredNodeTextPx,
},
supportedFixes: [
- `increase projected ${entry.minimumProjectedNodeTextOwner?.kind === 'edge' ? 'relationship label' : entry.minimumProjectedNodeTextOwner?.kind === 'boundary' ? 'boundary label' : 'node text'} to at least ${entry.minimumRequiredNodeTextPx}px at ${entry.width}x${entry.height}, then rerun visual-check`,
+ `increase projected ${entry.minimumProjectedNodeTextOwner?.kind === 'edge' ? 'relationship label' : entry.minimumProjectedNodeTextOwner?.kind === 'boundary' ? 'boundary label' : 'node text'} to at least ${entry.minimumRequiredNodeTextPx}px at ${entry.width}x${entry.height}, then rerun ${command}`,
],
}));
}
return diagnostics;
}
-function baseReceipt({ artifactPath, artifact, sidecars, chrome, deliveryProvenance }) {
+function baseReceipt({ artifactPath, artifact, sidecars, chrome, deliveryProvenance, command, capture }) {
return {
schemaVersion: 1,
ok: false,
- command: 'visual-check',
+ command,
evidenceKind: 'automated-browser',
status: 'fail',
- visualReview: 'pending',
+ visualReview: capture ? 'pending' : 'not-requested',
...(deliveryProvenance ? {
provenance: deliveryProvenance.status,
...(deliveryProvenance.receiptId ? { deliveryReceiptId: deliveryProvenance.receiptId } : {}),
@@ -2124,9 +2146,10 @@ function baseReceipt({ artifactPath, artifact, sidecars, chrome, deliveryProvena
policy: 'fit-or-reader-declared-readable-vertical-scroll',
viewports: [],
},
+ themeStates: { status: 'fail', viewports: [] },
readability: { status: 'fail', minimumProjectedNodeTextPx: MIN_PROJECTED_NODE_TEXT_PX, viewports: [] },
viewerChrome: { status: 'fail', viewports: [] },
- captures: { status: 'fail', screenshots: [], contactSheet: null },
+ captures: { status: capture ? 'fail' : 'not-requested', screenshots: [], contactSheet: null },
sidecars: { ...sidecars, files: [] },
};
}
@@ -2204,12 +2227,12 @@ function publishReceiptOnly(artifactPath, outputs, receipt, ownership) {
return commitVisualEvidence(artifactPath, outputs, ownership, [outputs.receipt]);
}
-export function persistVisualCheckFailure(
+function persistBrowserEvidenceFailure(
artifactPath,
failure,
- { outDir, compareSidecarParents = sameParent, ownership } = {},
+ { outDir, compareSidecarParents = sameParent, ownership, command = 'visual-check', capture = true } = {},
) {
- const outputs = sidecarPaths(artifactPath, { outDir });
+ const outputs = evidenceSidecarPaths(artifactPath, { outDir, command, capture });
const directory = resolveSidecarDirectory(artifactPath, outputs, compareSidecarParents);
const capturedArtifact = readRegularFileContents(artifactPath, {
subject: 'failure-artifact',
@@ -2230,7 +2253,7 @@ export function persistVisualCheckFailure(
policy: 'fit-or-reader-declared-readable-vertical-scroll',
viewports: [],
},
- captures: { status: 'fail', screenshots: [], contactSheet: null },
+ captures: { status: capture ? 'fail' : 'not-requested', screenshots: [], contactSheet: null },
sidecars: { ...directory.sidecars, files: [] },
};
if (!directory.ok) {
@@ -2262,7 +2285,7 @@ export function persistVisualCheckFailure(
return receipt;
}
-export async function runVisualCheck({
+async function runBrowserEvidence({
artifactPath,
outDir,
chromePath,
@@ -2271,10 +2294,11 @@ export async function runVisualCheck({
deliveryProvenance,
verifyArtifact,
compareSidecarParents = sameParent,
+ command, capture,
} = {}) {
- if (!artifactPath) throw new Error('visual-check requires one delivered HTML artifact.');
+ if (!artifactPath) throw new Error(`${command} requires one delivered HTML artifact.`);
const artifact = path.resolve(artifactPath);
- if (!/\.html?$/i.test(artifact)) throw new Error('visual-check requires an .html artifact.');
+ if (!/\.html?$/i.test(artifact)) throw new Error(`${command} requires an .html artifact.`);
const capturedArtifact = captureRegularFileBinding(artifact, {
subject: 'visual-check-artifact',
expectedLinks: 1,
@@ -2285,14 +2309,14 @@ export async function runVisualCheck({
}
const artifactBytes = capturedArtifact.content.buffer;
try {
- const outputs = sidecarPaths(artifact, { outDir });
+ const outputs = evidenceSidecarPaths(artifact, { outDir, command, capture });
const directory = resolveSidecarDirectory(artifact, outputs, compareSidecarParents);
const receipt = baseReceipt({
artifactPath: artifact,
artifact: artifactBytes,
sidecars: directory.sidecars,
chrome: { status: 'not-checked', executable: null },
- deliveryProvenance,
+ deliveryProvenance, command, capture,
});
if (!directory.ok) {
receipt.error = directory.error;
@@ -2322,7 +2346,7 @@ export async function runVisualCheck({
ownership.stagingPaths.set(artifact, inspectionArtifact);
writeStagedEvidence(ownership, artifact, artifactBytes);
} catch (error) {
- return { exitCode: EXIT.fail, receipt: persistVisualCheckFailure(artifact, {
+ return { exitCode: EXIT.fail, receipt: persistBrowserEvidenceFailure(artifact, {
...receipt,
status: 'fail',
ok: false,
@@ -2334,7 +2358,7 @@ export async function runVisualCheck({
evidence: { reason: error.message },
supportedFixes: ['retry after resolving the reported staging filesystem error'],
})],
- }, { outDir, compareSidecarParents, ownership }) };
+ }, { outDir, compareSidecarParents, ownership, command, capture }) };
}
const verifyInspectionArtifact = () => {
const entry = ownership.stagedEntries.get(artifact);
@@ -2345,12 +2369,12 @@ export async function runVisualCheck({
try {
verifyArtifact?.(artifactBytes);
} catch (error) {
- return { exitCode: EXIT.fail, receipt: persistVisualCheckFailure(artifact, {
- schemaVersion: 1, command: 'visual-check', evidenceKind: 'automated-browser', visualReview: 'pending',
+ return { exitCode: EXIT.fail, receipt: persistBrowserEvidenceFailure(artifact, {
+ schemaVersion: 1, command, evidenceKind: 'automated-browser', visualReview: capture ? 'pending' : 'not-requested',
artifact: { path: artifact, sha256: sha256(artifactBytes), bytes: artifactBytes.byteLength },
provenance: error.deliveryProvenance?.status, error: error.message,
diagnostics: error.archifyDiagnostics || [],
- }, { outDir, compareSidecarParents, ownership }) };
+ }, { outDir, compareSidecarParents, ownership, command, capture }) };
}
const resolvedChrome = chromePath || resolveChrome();
@@ -2363,7 +2387,8 @@ export async function runVisualCheck({
receipt.containment.status = 'skipped';
receipt.readability.status = 'skipped';
receipt.viewerChrome.status = 'skipped';
- receipt.captures.status = 'skipped';
+ receipt.themeStates.status = 'skipped';
+ if (capture) receipt.captures.status = 'skipped';
receipt.error = 'Chrome or Chromium is unavailable. Set ARCHIFY_CHROME to its executable path.';
receipt.diagnostics = [failureDiagnostic({
code: 'viewer/chrome-unavailable',
@@ -2371,7 +2396,7 @@ export async function runVisualCheck({
message: receipt.error,
subject: { artifact },
evidence: { executable: null },
- supportedFixes: ['set ARCHIFY_CHROME to a Chrome or Chromium executable and rerun visual-check'],
+ supportedFixes: [`set ARCHIFY_CHROME to a Chrome or Chromium executable and rerun ${command}`],
})];
const publication = publishReceiptOnly(artifact, outputs, receipt, ownership);
if (!publication.ok) {
@@ -2407,7 +2432,7 @@ export async function runVisualCheck({
});
verifyInspectionArtifact();
if (screenshot) {
- if (!ownership.stagedEntries.has(screenshot.path)) {
+ if (screenshot && !ownership.stagedEntries.has(screenshot.path)) {
registerStagedEvidence(ownership, screenshot.path);
} else {
const staged = ownership.stagedEntries.get(screenshot.path);
@@ -2425,13 +2450,15 @@ export async function runVisualCheck({
artifactPath: inspectionArtifact,
...viewport,
theme: 'dark',
- screenshotPath: screenshot.stagedPath,
- writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),
+ ...(screenshot ? {
+ screenshotPath: screenshot.stagedPath,
+ writeScreenshot: (bytes) => writeStagedEvidence(ownership, screenshot.path, bytes),
+ } : {}),
});
verifyInspectionArtifact();
- if (!ownership.stagedEntries.has(screenshot.path)) {
+ if (screenshot && !ownership.stagedEntries.has(screenshot.path)) {
registerStagedEvidence(ownership, screenshot.path);
- } else {
+ } else if (screenshot) {
const staged = ownership.stagedEntries.get(screenshot.path);
if (!currentEvidenceMatches(staged.path, staged.identity, staged.evidence)) {
throw new Error('The staged visual-check screenshot changed after capture.');
@@ -2442,12 +2469,12 @@ export async function runVisualCheck({
let artifactVerification = verifyRegularFileBinding(capturedArtifact.binding);
if (artifactVerification.status !== 'match') {
- throw regularFileCaptureError('The delivered artifact changed while visual-check was running', artifactVerification);
+ throw regularFileCaptureError(`The delivered artifact changed while ${command} was running`, artifactVerification);
}
verifyArtifact?.(artifactBytes);
artifactVerification = verifyRegularFileBinding(capturedArtifact.binding);
if (artifactVerification.status !== 'match') {
- throw regularFileCaptureError('The delivered artifact changed while visual-check was running', artifactVerification);
+ throw regularFileCaptureError(`The delivered artifact changed while ${command} was running`, artifactVerification);
}
receipt.containment.viewports = VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => (
@@ -2460,22 +2487,30 @@ export async function runVisualCheck({
file: path.basename(entry.path),
}));
const allObservations = [...observations.values()];
+ receipt.themeStates.viewports = CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map(theme => {
+ const entry = observations.get(screenshotKey(width, height, theme));
+ return { width, height, requestedTheme: theme, resolvedTheme: entry.resolvedTheme, ok: entry.resolvedTheme === theme };
+ }));
+ const themeStatePass = receipt.themeStates.viewports.every(entry => entry.ok);
const containmentPass = allObservations.every((entry) => entry.ok);
const readabilityPass = receipt.readability.viewports.every((entry) => entry.readabilityOk);
const viewerChromePass = allObservations.every((entry) => entry.viewerChromeOk);
receipt.diagnostics = observationDiagnostics({
artifact,
allObservations,
- readabilityObservations: receipt.readability.viewports,
+ readabilityObservations: receipt.readability.viewports, command,
});
+ receipt.themeStates.status = themeStatePass ? 'pass' : 'fail';
receipt.containment.status = containmentPass ? 'pass' : 'fail';
receipt.readability.status = readabilityPass ? 'pass' : 'fail';
receipt.viewerChrome.status = viewerChromePass ? 'pass' : 'fail';
- receipt.captures.status = 'pass';
- receipt.captures.contactSheet = path.basename(outputs.contactSheet);
- receipt.status = containmentPass && readabilityPass && viewerChromePass ? 'pass' : 'fail';
- receipt.ok = containmentPass && readabilityPass && viewerChromePass;
- writeStagedEvidence(ownership, outputs.contactSheet, contactSheetHtml({
+ if (capture) {
+ receipt.captures.status = 'pass';
+ receipt.captures.contactSheet = path.basename(outputs.contactSheet);
+ }
+ receipt.status = containmentPass && themeStatePass && readabilityPass && viewerChromePass ? 'pass' : 'fail';
+ receipt.ok = containmentPass && themeStatePass && readabilityPass && viewerChromePass;
+ if (capture) writeStagedEvidence(ownership, outputs.contactSheet, contactSheetHtml({
artifactPath: artifact,
receipt,
screenshots: receipt.captures.screenshots,
@@ -2507,30 +2542,31 @@ export async function runVisualCheck({
receipt.containment.status = 'fail';
receipt.readability.status = 'fail';
receipt.viewerChrome.status = 'fail';
- receipt.captures.status = 'fail';
+ receipt.themeStates.status = 'fail';
+ receipt.captures.status = capture ? 'fail' : 'not-requested';
receipt.captures.screenshots = [];
receipt.captures.contactSheet = null;
if (error.deliveryProvenance) receipt.provenance = error.deliveryProvenance.status;
receipt.diagnostics = error.archifyDiagnostics || [failureDiagnostic({
- code: startupTimeout ? 'viewer/chrome-startup-timeout' : 'viewer/visual-check-runtime',
+ code: startupTimeout ? 'viewer/chrome-startup-timeout' : `viewer/${command}-runtime`,
message: startupTimeout
? 'Chrome did not finish its initial DevTools handshake within the startup window.'
- : 'visual-check could not complete its Chrome inspection.',
+ : `${command} could not complete its Chrome inspection.`,
subject: { artifact },
evidence: { reason: error.message },
supportedFixes: startupTimeout
? [
'do not edit or simplify the artifact because this is a browser-startup failure',
- `retry visual-check once after host load subsides; if it repeats, stop and report the environment failure`,
+ `retry ${command} once after host load subsides; if it repeats, stop and report the environment failure`,
]
- : ['resolve the reported Chrome inspection error, then rerun visual-check'],
+ : [`resolve the reported Chrome inspection error, then rerun ${command}`],
})];
return {
exitCode: EXIT.fail,
- receipt: persistVisualCheckFailure(artifact, receipt, {
+ receipt: persistBrowserEvidenceFailure(artifact, receipt, {
outDir,
compareSidecarParents,
- ownership,
+ ownership, command, capture,
}),
};
} finally {
@@ -2540,3 +2576,16 @@ export async function runVisualCheck({
releaseRegularFileBinding(capturedArtifact.binding);
}
}
+
+export function persistVisualCheckFailure(artifactPath, failure, options = {}) {
+ return persistBrowserEvidenceFailure(artifactPath, failure, { ...options, command: 'visual-check', capture: true });
+}
+export function persistBrowserCheckFailure(artifactPath, failure, options = {}) {
+ return persistBrowserEvidenceFailure(artifactPath, failure, { ...options, command: 'browser-check', capture: false });
+}
+export function runVisualCheck(options = {}) {
+ return runBrowserEvidence({ ...options, command: 'visual-check', capture: true });
+}
+export function runBrowserCheck(options = {}) {
+ return runBrowserEvidence({ ...options, command: 'browser-check', capture: false });
+}
diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.md
index 3a318e9c..7e688a80 100644
--- a/archify/references/authoring-contract.md
+++ b/archify/references/authoring-contract.md
@@ -10,7 +10,7 @@ Read both the mode schema and `schemas/common.schema.json`. The mode schemas use
- `variant`: `default`, `emphasis`, `security`, `dashed`
- Relationship IDs use the shared identifier pattern and must be unique in their collection.
-Do not invent fields. Use the nearest matching example for structure, then author fresh IDs, wording, facts, and layout.
+Do not invent fields. Before writing any new field, enum, or constrained text, read its schema definition, including common `$ref` targets. In particular, check boundary kinds, guided-view note lengths, repository identity, and source-reference shapes. An example demonstrates structure; it does not enumerate every valid value. Author fresh IDs, wording, facts, and layout.
## Workflow layout contracts
diff --git a/archify/references/authoring-defaults.md b/archify/references/authoring-defaults.md
new file mode 100644
index 00000000..5d353a12
--- /dev/null
+++ b/archify/references/authoring-defaults.md
@@ -0,0 +1,70 @@
+# Authoring defaults
+
+Read this file once before writing a fresh candidate. A frozen existing candidate that is going straight to `finalize` does not need it unless a failed gate requires repair.
+
+## Repository-backed first draft
+
+When the diagram reflects a real repository, finish the evidence shape while inspecting source, not after validation fails. Record the canonical remote URL and full 40-character commit, add `meta.repository`, and attach at least one inspected `sources` entry to every key semantic node. Use only real repository-relative files and line numbers; source references are evidence, never decoration. The minimum shape is:
+
+```json
+"meta": { "repository": { "url": "<canonical-url>", "revision": "<40-char-commit>" } },
+"components": [{ "id": "runtime", "sources": [{ "path": "src/runtime.ts", "line": 1, "label": "runtime entry" }] }]
+```
+
+For local-only source links or an unsupported forge, set `meta.repository.link_mode` to `"local-only"` and retain `url` and `revision`. This disables web hyperlinks while preserving local identity and source verification.
+
+Keep `<repo-root>` from source inspection and pass it to the first `finalize` call. Do not omit a required role or merge distinct responsibilities merely to reduce layout work.
+
+A source reference proves only the implementation visible at that location. When separate files or locations establish materially different relationships, protocols, lifecycle transitions, persistence behavior, or conclusion-card claims, attach those inspected locations to the relevant semantic node. Let the real claims determine the references; never target a total reference count or reuse one citation as a proxy for evidence it does not contain.
+
+## Field constraints before writing
+
+Examples demonstrate valid field shape. Before choosing a different boundary kind or writing a guided-view note, inspect `properties.boundaries.items` in `schemas/architecture.schema.json` and `$defs.guidedViews` in `schemas/common.schema.json`. Use their actual enums and length limits. Keep longer evidence in a conclusion card; do not remove the underlying fact to fit a note. Finished showcase examples may contain measured route repairs; transfer their semantic shape, then follow the automatic-routing first-draft rule below.
+
+## Composition and meaning
+
+- Keep one obvious main path. Side branches leave the nearest main-path node. Omit a relationship only during semantic authoring when repository evidence shows it is genuinely irrelevant or already expresses no distinct fact; never delete it to simplify geometry.
+- Treat semantic coverage and reader explanation as quality, never as performance overhead. Let the real system determine node and relationship counts; never target a number or merge facts merely to simplify drawing. Do not reduce distinct components, relationships, source evidence, guided views, or evidence-backed conclusion cards merely to finish sooner. For a repository showcase that introduces several functional concerns to a new reader, add focused `meta.views` for the actual reading questions and concise cards for material conclusions. Every reader aid must earn its place; there is no quota.
+- Audit ownership before freezing topology. When one controller, broker, runtime, or supervisor creates, routes to, resumes, or observes multiple participants, keep that shared control plane distinct from the managed participants if merging would hide ownership or lifecycle. A source file cited on multiple participant nodes is a signal to check for this seam, not a reason to invent one: follow the actual code and omit absent roles.
+- Audit entry and trust boundaries too. When the repository distinguishes an external caller or client from a gateway, relay, tunnel, or local service, show the caller and transport as separate responsibilities. Do not merge an actor into infrastructure merely because both sit on one side branch.
+- A boundary is evidence, not decoration. Use it when it communicates a real trust, runtime, process, ownership, or persistence boundary; a boundary around one node needs an explicit isolation fact. Do not box every concern or duplicate the node label as a boundary title.
+- Omit `meta.visual_preset` by default so every diagram opens in `classic`, regardless of whether its resolved color mode is light or dark. Switching Light / Dark preserves the current preset. Set `signal-flow`, `blueprint`, or `editorial` only when the user explicitly requests that visual style.
+- Omit `meta.subtitle` by default. Never invent a subtitle that restates the title, nodes, or cards; include one short supporting line only when the user explicitly asks for it.
+- Omit `meta.legend` for the truthful `auto` default. When needed, use only `mode: auto|all|hidden` and renderer-supported `entries.<kind>.label|visible`; labels never change semantics.
+- Component types are `frontend`, `backend`, `database`, `cloud`, `security`, `messagebus`, and `external`. Components do not accept a `variant` field. Relationship variants are `default`, `emphasis`, `security`, and `dashed`; when an optional component must be visible, mark it in the component label and use a dashed relationship instead.
+- Relationship labels are semantic data. When one collides, move the label, adjust the route or spacing, then shorten the wording while preserving meaning. Omit only wording that is already fully implied by both endpoints and contains no protocol, action, direction, synchronous/asynchronous behavior, or cross-boundary mechanism. Preserve every meaningful label; deleting it is not a geometry repair. If a relationship starts unlabeled because its endpoints fully imply it, explain why the wording is redundant; this is a semantic authoring choice, not a geometry repair.
+- Omit `meta.engineering_profile` by default. Region, cluster, and security boundary wording do not by themselves enable it. Enable `deployment-ownership` only when the user explicitly asks for a production deployment topology, ownership handoff, or fail-closed deployment review and the source facts are known. Once enabled, must not remove the engineering profile merely to pass validation; repair the facts or report the diagnostics truthfully.
+
+## Language and identity
+
+- Choose one primary authored language from an explicit user choice; otherwise follow the request or conversation's dominant language. `meta.locale` controls only renderer-owned Viewer UI: use `"en"`, `"zh-CN"`, or `"es"` for the corresponding supported primary language. For every other language, omit `meta.locale` and explicitly disclose that the fixed Viewer UI and `<html lang>` fall back to English. The renderer never translates authored content. See `authoring-contract.md` for details.
+- Preserve exact product names, code identifiers, commands, protocols, API paths, and environment names. They may remain English inside localized copy, but never justify leaving the surrounding explanatory prose in another language.
+- Keep node and boundary headings concise in that primary language. Do not append a parenthesized translation that merely repeats the same meaning; keep only exact product or protocol identifiers in their original form and move useful explanation into the sublabel, guided-view note, or card.
+- Brand identity is optional and explicit. Put a canonical built-in ID in `brand` when the node names that real product. If no preset matches and the user supplied the official HTTP(S) URL, first run `node bin/archify.mjs brands capture "<url>" --json`, then author the returned digest-pinned `brand` object. Render and validate never perform an unpinned capture. Otherwise omit `brand`. Never infer a brand from a vague role such as "database", and never let a badge replace the semantic `type`, label, or relationship facts.
+
+## Output path
+
+Set required `meta.output` to a portable POSIX-relative `.html` path, such as `reports/diagram.html`. It resolves from the working directory and must remain inside it. An explicit native CLI output may be elsewhere but does not replace this authored contract. See [Output path contracts](delivery-contract.md#output-path-contracts) for native Windows paths, aliases, and long filenames.
+
+## Layout and routing
+
+- Treat the standalone desktop viewer as a first-screen artifact by default, not a shallow strip. Generate one responsive artifact for laptops and external displays, preserving the authored SVG/viewBox, proportions, semantic geometry, and normal document flow. Use enough authored vertical rhythm for the diagram panel and necessary conclusion cards to occupy a wide or tall desktop as a balanced whole. For a fresh Architecture, omit `meta.viewBox` by default so the renderer measures the real content and declares intrinsic-height Reader behavior. Author a fixed viewBox only when the user supplied fixed geometry or measured evidence shows it is necessary and the resulting text remains comfortably readable.
+- Let `finalize` run the real browser check at 1440×900, 1600×1000, 1920×1080, and 2048×1320. Require zero horizontal overflow. Prefer full first-screen containment only when the complete diagram stays comfortably readable. The 6px projected-text check is a hard failure floor, not a layout target; at 1440px, aim for ordinary context text around 7.5px or larger. If semantic completeness needs more room, add meaningful vertical rows and use Reader-declared vertical page scroll with an intrinsic-height diagram instead of merging responsibilities, dropping evidence, or squeezing typography. Repair every other overflow by removing genuinely redundant content or compacting spacing before shrinking nodes, labels, or the main panel. Never counterfeit a pass with `overflow: hidden`, clipped content, an internal diagram scroller, stretched SVG height, or smaller typography. See [Automated browser evidence](delivery-contract.md#automated-browser-evidence) for the authoritative rule.
+- Architecture sublabels render at a preferred 9px before responsive projection. Size each component for that preferred size (`5.4px × text units + 8px`, counting each CJK character as two units) instead of relying on shrink-to-fit. If a supporting phrase would make the node disproportionately wide, keep the node's exact role or protocol concise and preserve the supplementary fact in a guided-view note or conclusion card. Never remove a responsibility, protocol, or boundary fact just to shorten text.
+- If the largest viewport still has a conspicuous empty lower band at the viewer's width cap, redistribute authored Y positions and increase the viewBox height proportionally; do not add filler copy or decorative cards.
+- Spacing means clear gap, not center distance. For a relationship label, clear gap must exceed its measured mask width; follow the label-preserving repair order.
+- For a medium Architecture, encode one obvious main path, but let it step across multiple rows when one horizontal rail would create a shallow strip, long empty corridors, or force semantic compression. Put short branches above or below their nearest hub. The first draft leaves every connection on automatic routing and omits `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, and label-position controls unless the user supplied that exact route intent. After a measured diagnostic, add only the smallest named control: at a crowded hub reserve facing sides for the main path and other sides for branches, or give a real return edge one compact outer side pair or perimeter corridor. Never make unrelated orthogonal segments share the same axis for 8px or more; keep nonzero segments at least 8px and interior turns at least 16px.
+- Before writing, apply `6.5px × ASCII units + 21px`, counting each CJK character as two units, to every labeled connection on the main path. Treat the result as that edge's minimum clear gap, never as one fixed gap shared across the row. Increase the gap or choose a clear segment when the budget does not fit; do not wait for a predictable label-route collision.
+- Automatic routes own their endpoint sides. A relationship does not accept a `side` field; only after a diagnostic proves endpoint routing is required, use `fromSide` or `toSide` on the diagnosed endpoint. Each endpoint side is a direction contract: the first and final segment must leave/enter perpendicular to that side.
+- Estimate the resolved Architecture content width before the first write. At 1440px, legacy, unknown, and authored-viewBox artifacts use the conservative 930px diagram budget. A fresh automatic wide Architecture with the recognized Reader contract instead reports its declared budget and cap in `composition.desktopReadability`; use that evidence before changing a semantic node or relationship label. Keep ordinary context text comfortably above the 6px hard floor by adding meaningful rows or using intrinsic-height layout, not by dropping meaning or designing to a fixed viewBox width.
+- Automatic Port Spread is a default renderer behavior for architecture, workflow, data-flow, and lifecycle. It skips single relationships and explicit `via`, `channelX`, `channelY`, `labelAt`, or non-`auto` routes. Near parallel ports use an outside bridge so automatic routing cannot create a sub-8px segment or sub-16px interior turn. Architecture separately keeps unobstructed facing automatic ports (`left`/`right` or `top`/`bottom`) on one shared axis when their offset is under 16px and both ports retain corner clearance. If exactly one endpoint was spread, only the unshared endpoint may move onto that axis; if both endpoints were spread, keep the outside bridge so competing ports remain distinct.
+- In showcase Architecture, an explicit route must stay proportionate to the shortest legal orthogonal route. `composition/excessive-route-detour` reports the actual length, obstacle-aware shortest length, ratio, and empty-space excursion. Remove an unnecessary `via` or move the diagnosed corridor inward; do not enlarge the canvas to legitimize the detour. Related edges may share one deliberate outer bus.
+- Never accept an edge crossing an unrelated opaque node, an ambiguous shared corridor, or a relationship label masking another route.
+
+## Type-specific defaults
+
+- Workflow: use schema v2 for new workflows and preserve schema v1 for an existing source with fixed legacy geometry. For sequential stages stacked in one container, use one v2 lane and one group, omit `meta.viewBox`, and place nodes around the lane content center with symmetric `yOffset` values such as `-90 / 0 / 90`. Keep semantic edge labels and act on compiler diagnostics. The canonical contract is in [`../renderers/workflow/README.md`](../renderers/workflow/README.md#layout-contracts).
+- Sequence: omit `meta.column_fit` for the stable `fixed` layout. Set it to `"spread"` when a wide viewBox leaves unused horizontal space or meaningful participant labels do not fit fixed boxes; do not shorten semantic labels before trying `spread`.
+- Lifecycle: phase columns `0..4` occupy the main rail. Event or terminal column `N` in `0..2` aligns beneath main column `N + 2`. Every lane other than `main` and `terminal` shares the one middle band, so two such states in the same column need distinct `yOffset` values. A recoverable state uses `type: "failure"` plus a real transition back to the active state.
+
+Read `authoring-contract.md` only when field enums, spacing math, geometry repair rules, repository evidence, or more mode-specific placement is needed.
diff --git a/archify/references/delivery-contract.md b/archify/references/delivery-contract.md
index 4483c64c..322181f9 100644
--- a/archify/references/delivery-contract.md
+++ b/archify/references/delivery-contract.md
@@ -142,7 +142,7 @@ After ownership is established, `deliver` creates the journal before rendering
and keeps it through the recoverable HTML/sidecar pair commit. It removes the
journal only after that commit completes. A validation, render, or pair-commit
failure, or a process interruption, may therefore leave a journal. The journal
-is a safety barrier: `check` and `visual-check` fail closed when any directory
+is a safety barrier: `check`, `browser-check`, and `visual-check` fail closed when any directory
entry exists at the journal or lock path, including an unreadable file,
symlink, or dangling symlink. Run deliveries targeting the same physical output
directory serially; one attempt must finish or be recovered before another
@@ -182,7 +182,7 @@ artifact:
```bash
node bin/archify.mjs check <output.html> --require-provenance
-node bin/archify.mjs visual-check <output.html> --json --require-provenance
+node bin/archify.mjs browser-check <output.html> --json --require-provenance
```
## Output path contracts
@@ -227,7 +227,7 @@ bypass any non-output schema or compiler error. For every other repair, add a
portable POSIX-relative `.html` path to `meta.output`; no schema-version change
is otherwise required.
-Use `validate` after every candidate edit. CLI HTML output paths must end in
+Run `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
`.html`, including after symbolic-link resolution. Compare receipt paths must
end in `.json`. A type mismatch fails before writing with
`output/cli-extension` or `output/cli-resolved-extension`. These checks prevent
@@ -242,6 +242,45 @@ node bin/archify.mjs deliver <type> <candidate.json> <output.html> --quality sho
Deliver reads the specification once, writes those exact bytes to a private same-directory candidate snapshot, renders that snapshot, runs the complete artifact checker, and only replaces the target after all artifact checks pass. The JSON receipt includes SHA-256 and byte counts for both `specification` and `artifact`.
+For the ordinary agent handoff path, prefer the finalizer:
+
+```bash
+node bin/archify.mjs finalize <type> <candidate.json> <output.html> --quality showcase --json
+```
+
+`finalize` invokes verified `deliver` once, reuses its embedded showcase
+validation result, then runs strict `check --require-provenance` and
+`browser-check --require-provenance`. It stops at the first failed or skipped stage
+and preserves that stage's full receipt. Its stdout is one compact JSON
+object with gate statuses, bounded actionable diagnostics, artifact identity,
+and evidence paths. The same compact object is written atomically to
+`<output-stem>.finalize-summary.json`; use that file for normal failure repair.
+Complete stage receipts and timings remain available for auditing in
+`<output-stem>.finalize.json`. With `--out-dir`, both files are written there;
+`--receipt <path.json>` overrides the full receipt path and derives a distinct
+`<path>-summary.json`. Read the full receipt only when the compact summary is
+truncated and its shown subjects and evidence cannot identify a coherent local
+repair, or when complete audit evidence was explicitly requested. The compact
+receipt reports `visualReview: "not-requested"`; ordinary acceptance does not create images or require a perceptual reviewer.
+
+A passing finalizer receipt is sufficient evidence for all four gates. Merely
+naming the gates or requiring each one to pass does not require replaying their
+standalone commands. Replay an individual command only when the request
+explicitly requires separate executions or focused failure diagnosis needs it.
+
+The individual commands remain authoritative and backward compatible. Use
+them directly for focused diagnosis, recovery, or when only one gate is
+required. A finalize failure does not relax any gate and does not turn a
+preserved older artifact into a current successful delivery.
+
+`finalize` overlaps private Chrome startup with delivery and strict checking.
+It loads the artifact only after those gates pass and current provenance is
+verified. The browser gate retains every viewport, theme, and stability check;
+the browser closes at completion or an earlier failure. Its full stage receipt
+records `execution: "in-process"` and the equivalent standalone `command` for
+replay. Use total finalize duration to compare performance because Chrome
+startup overlaps the earlier stages.
+
The pair commit is recoverable, not a claim that two filesystem paths change
atomically or are durable across power loss. Journal finalization is part of
that commit: a caught failure while verifying or removing the journal rolls
@@ -273,19 +312,20 @@ lock keeps strict checkers fail-closed. Only after pair commit, journal
finalization, and lock release all succeed may `deliver` exit zero, print its
success receipt, or run `--open`.
-Run strict `check` after `deliver` exits zero. Run `visual-check` only after that
-strict check exits zero. A failed marker, recovery journal, or delivery lock
-makes both commands fail before accepting the preserved HTML; report the
-diagnostics and complete a successful recovery delivery before collecting new
-visual evidence.
+Run strict `check` after `deliver` exits zero. Run `browser-check` or optional
+`visual-check` only after that strict check exits zero. A failed marker,
+recovery journal, or delivery lock makes every checker fail before accepting
+the preserved HTML; report the diagnostics and complete a successful recovery
+delivery before collecting new browser evidence.
-The delivery interface exposes three separate claims:
+The delivery interface exposes four separate claims:
1. `deliver` proves deterministic artifact checks and byte identity.
-2. `visual-check` collects automated browser evidence from the exact artifact.
-3. Perceptual visual review records a human or image-capable reviewer's judgment.
+2. `browser-check` collects required automated browser evidence from the exact artifact without capturing images.
+3. `visual-check` optionally adds artifact-bound screenshots and a contact sheet.
+4. Perceptual visual review records a human or image-capable reviewer's judgment.
-Passing one claim never implies either of the others. Never claim that the deterministic receipt includes visual review. It does not include browser evidence either.
+Passing one claim never implies the others. Never claim that the deterministic receipt includes browser or perceptual review evidence.
## Recovering a failed comparison
@@ -307,27 +347,24 @@ Successful comparisons and failures before commit retain their normal cleanup.
## Automated browser evidence
-After delivery, inspect the exact trusted HTML without rerendering or modifying
-it:
+`finalize` runs the required browser gate against the exact trusted HTML without
+rerendering or modifying it. For focused diagnosis, the equivalent standalone
+command is:
```bash
-node bin/archify.mjs visual-check <output.html> --json --require-provenance
+node bin/archify.mjs browser-check <output.html> --json --require-provenance
```
The zero-dependency command uses Chrome/Chromium through the DevTools pipe. It
measures light-theme containment at 1440×900, 1600×1000, 1920×1080, and
-2048×1320, then captures light/dark screenshots at 1440×900 and 2048×1320. It
-writes four PNG sidecars, one relative-path HTML contact sheet, and one JSON
-receipt beside the artifact by default — pass `--out-dir <dir>` to write all of
-them into a separate directory instead (created if missing) when a project
-keeps its testing/evidence artifacts apart from the delivered `.json`/`.html`
-result pair. When that directory differs from the artifact directory, the
-receipt records its absolute path as `sidecars.directory`; sidecar filenames
-resolve there, otherwise beside `artifact.path`. The contact sheet keeps its
-image links relative for portability. The receipt binds the source artifact SHA-256 and
-byte count, identifies `evidenceKind: "automated-browser"`, records READ plus
-Still runtime state, and always reports `visualReview: "pending"`; automated
-browser evidence cannot claim perceptual review.
+2048×1320, and verifies the endpoint light/dark theme plus READ/Still runtime
+states. A requested theme that resolves to a different theme fails with measured
+evidence. It creates one
+`<output-stem>.browser-check.json` receipt and no screenshots or contact sheet.
+Pass `--out-dir <dir>` to place the receipt in a separate evidence directory.
+The receipt binds the artifact SHA-256 and byte count, identifies
+`evidenceKind: "automated-browser"`, and reports
+`visualReview: "not-requested"`.
Horizontal overflow always fails. Vertical overflow normally fails as well. One
bounded exception preserves readability for compiler-measured intrinsic-height
@@ -341,13 +378,40 @@ explicit authored viewBoxes, horizontal overflow, unreadable text, clipping, and
Viewer chrome collisions remain failures. Do not add an internal diagram
scroller or hide overflow.
-`browser_evidence` in the handoff records only the outcome of this automated command:
+`browser_evidence` in the handoff records only the outcome of this automated
+command:
-- `passed` maps from exit 0 and receipt `status: "pass"` only after every required measurement and capture completes and passes.
-- `failed` maps from exit 1 and receipt `status: "fail"` when the inspection finds a defect, the command fails, or a runtime/capture error leaves the evidence incomplete.
+- `passed` maps from exit 0 and receipt `status: "pass"` after every required measurement completes and passes.
+- `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.
- `skipped` maps only from exit 2 and receipt `status: "skipped"` when Chrome/Chromium is unavailable and the inspection does not run.
-Runtime or capture failures leave incomplete evidence and must not be normalized to `skipped`.
+Runtime failures leave incomplete evidence and must not be normalized to
+`skipped`. They do not invalidate an already successful deterministic delivery.
+Retry an environmental failure in a browser-capable execution context when
+practical. Keep the packaged transport unchanged unless the failure reproduces
+through that seam in a capable environment.
+
+A provenance failure exits before browser inspection and persists a failed
+browser-check receipt bound to the attempted artifact. If the failure receipt
+cannot be written, the diagnostic names that incomplete evidence.
+
+Both browser commands inspect the exact delivered HTML without modifying or rerendering it.
+
+## Optional capture evidence
+
+`visual-check` remains backward compatible for a requested or escalated
+perceptual review:
+
+```bash
+node bin/archify.mjs visual-check <output.html> --json --require-provenance
+```
+
+It performs the same automated browser measurements, captures light/dark
+screenshots at 1440×900 and 2048×1320, and writes four viewport PNG sidecars,
+one relative-path HTML contact sheet, and one JSON receipt. `--out-dir <dir>` moves all of these sidecars together.
+Open 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
+make a perceptual judgment. Capture and provenance failures follow the ownership rules below.
+
The receipt, contact sheet, and four PNGs form one owned evidence set. Before
capture, `visual-check` freezes every requested directory entry, its
canonical write slot and physical parent, and the target's absent/file state,
@@ -393,6 +457,8 @@ command in a browser-capable execution context when practical. Keep the
packaged transport unchanged unless the failure reproduces through that seam in
a capable environment.
+`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.
+
## Optional opening
Add `--open` only when the user wants an immediate local preview. It runs after
@@ -419,23 +485,39 @@ The preview runtime ships inside the zero-dependency Skill ZIP and must work wit
Never 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.
-## Perceptual delivery gate
+## Optional perceptual review
+
+The ordinary path ends with the deterministic browser gate and reports
+`visual_review: not_requested`. Escalate to perceptual review when any of these
+conditions applies:
-Automated validation and browser evidence cannot prove visual polish. After deterministic delivery, inspect the actual HTML in a capable browser or render the evidence screenshots with an image reader. Check both themes when changed, the default READ view, line crossings/corridors, label masks, node/card fit, focus/search/passport closure, and export cleanliness.
+- the user explicitly requests an aesthetic or visual review;
+- a template, renderer, or Viewer change needs visual regression evidence;
+- a novel layout or browser diagnostic leaves low confidence;
+- the run is selected for sampled audit or dogfood.
For the default standalone desktop viewer, measure 1440×900, 1600×1000, 1920×1080, and 2048×1320. Require `document.documentElement.scrollWidth <= window.innerWidth` at every checked size. Prefer `scrollHeight <= window.innerHeight`; accept page-level vertical scrolling only through the Reader-declared readable exception defined above. At the largest checked viewport, inspect the rendered composition for a conspicuous empty lower band: the main panel and necessary conclusion cards should use the available height as a balanced whole, not collapse into a shallow strip. For unexpected overflow, repair the authored composition by removing only genuinely redundant content or compacting spacing before shrinking nodes, labels, or the main panel. Do not hide overflow, clip content, introduce an internal diagram scroller, or reduce node/label typography to make the measurement pass. Narrow/mobile containment may retain vertical page scrolling.
-A manual browser record is supplementary to the automated status. Reproducing the same coverage requires all four exact viewport measurements, both endpoint themes, and an artifact-bound record of the inspected SHA-256 and byte count. It never changes `browser_evidence`: when Chrome/Chromium is unavailable, that status remains `skipped` even when the manual browser record is complete and `visual_review: passed`; an automated `failed` result likewise remains `failed`. An unconstrained browser glance can support perceptual review only.
+For an escalation, run `visual-check` on the current finalized artifact, inspect
+its contact sheet with a capable image reader or human, and check both endpoint
+themes, the default READ view, line crossings/corridors, label masks, node/card
+fit, focus/search/passport closure, and export cleanliness. This review is
+supplementary and never changes `browser_evidence`. An unconstrained browser
+glance can support perceptual review only.
-Report exactly one truthful status:
+Report one truthful optional-review status:
+- `visual_review: not_requested` — the default successful handoff.
- `visual_review: passed` — only after inspecting the rendered artifact.
-- `visual_review: skipped (image reader unavailable)` — when no capable visual surface exists.
+- `visual_review: skipped (image reader unavailable)` — a requested or triggered review could not run.
- `visual_review: failed` — with the concrete visible defect.
-Use `correction_rounds: 0`, `correction_rounds: 1`, or `correction_rounds: 2`; never exceed a maximum of two focused correction rounds. Never report `visual_review: passed` without inspecting the artifact.
-
-If visual review changes the candidate, validation and delivery must run again because the prior frozen specification receipt is no longer current.
+For an escalated review, use `correction_rounds: 0`, `correction_rounds: 1`, or
+`correction_rounds: 2`; never exceed two focused correction rounds. When review
+is not requested, use `correction_rounds: 0`. Never report
+`visual_review: passed` without inspecting the artifact. If perceptual review
+changes the candidate, rerun `finalize` because the previous specification and
+artifact receipts are no longer current.
## Handoff receipt
@@ -448,10 +530,16 @@ specification_sha256: <receipt value>
artifact_sha256: <receipt value>
validation: 9/9 showcase, 0 errors, 0 warnings
browser_evidence: passed|failed|skipped
-visual_review: passed|skipped (image reader unavailable)|failed
+visual_review: not_requested|passed|skipped (image reader unavailable)|failed
correction_rounds: 0|1|2
```
-Derive `browser_evidence` only from the latest artifact-bound `visual-check` receipt. Record any manual browser work separately with its artifact binding, viewport/theme scope, and observations; never use it or `visual_review` to overwrite the automated status.
+Derive `browser_evidence` only from the latest artifact-bound `browser-check`
+receipt, normally the stage embedded by `finalize`. Record optional capture or
+manual browser work separately with its artifact binding, viewport/theme scope,
+and observations; never use it or `visual_review` to overwrite the automated
+status.
Opening, preview status, Share Cards, and other viewer exports are not validation claims.
+
+Finalize receipt publication uses the same identity-bound, no-clobber publisher and explicit recovery records described above. The full and summary receipts must be distinct from the candidate, artifact, delivery metadata, and browser receipt. Their targets must be absent or single-link regular files; symlink receipt entries and hardlinked targets fail closed. A later claimant or changed parent stops publication and remains untouched. Default receipt names share the physical artifact namespace and are bounded for the host filename limit. The two receipts are published individually, not as a crash-atomic pair; only a completed passing command is a successful handoff.
diff --git a/archify/references/repository-authoring.md b/archify/references/repository-authoring.md
new file mode 100644
index 00000000..79ccd10b
--- /dev/null
+++ b/archify/references/repository-authoring.md
@@ -0,0 +1,88 @@
+# Repository-backed architecture authoring
+
+Use this reference when a diagram must explain a real repository. The source is
+the authority for responsibilities, calls, boundaries, and persistence. The
+diagram is complete when the requested meaning is covered and every asserted
+fact has supporting source evidence.
+
+## Explore on demand
+
+1. **Freeze identity.** From the target repository, record `git rev-parse
+ HEAD`, `git remote get-url origin`, and `git status --short`. Pin the URL and
+ forty-character revision in `meta.repository`; use `link_mode: "local-only"`
+ for a local fixture whose HTTPS URL is only a credential-free identity. If
+ the worktree is dirty, record the changed paths and treat them as part of
+ the inspected source only when the task explicitly includes them.
+
+2. **Map the slice.** Use project instructions, manifests, entry points,
+ registrations, and deployment configuration to locate candidate runtime
+ units. Read the entry, configuration, and modules relevant to the request.
+ Follow imports and call sites
+ until the requested responsibility reaches its actual input, output, or
+ side effect. Read a small connected slice instead of scanning the repository
+ for a convenient label.
+
+3. **Trace ownership.** For each step, name the controller that owns the
+ decision, the runtime that performs it, and the filesystem or durable store
+ that supplies or receives bytes. Keep control ownership separate from file
+ I/O. A configured provider, an injected adapter, a local stub, and a durable
+ service are different claims; label the one the source supports.
+
+4. **Record evidence while reading.** Keep exact repository-relative paths and
+ inclusive line ranges for each component and meaningful relationship. Follow
+ actual branches, retries, fallbacks, and error handling. A function that is
+ exported or configured but never called by the normal path is an optional
+ capability, not a required runtime edge.
+
+5. **Name uncertainty.** Write unresolved questions beside the claim they
+ affect: for example, “`writeFile` is called here; durability is unknown.”
+ Resolve a question by reading the next relevant source range or preserve it
+ as an explicit unknown. Never turn a label, package description, or config
+ value into an unobserved service or behavior.
+
+Stop exploring when every requested responsibility, relationship, and boundary
+has supporting source entailment and the remaining unknowns cannot change that
+coverage. There is no node, edge, citation, view, card, or boundary count to
+hit. Do not add a summary step merely to signal completion.
+
+Batch independent relevant files when known. Each additional read should answer
+an unresolved question that can change the diagram. Reuse concise facts and
+their source ranges already verified in this task; across revisions, recheck
+the affected entry points, configuration, dependencies, and evidence.
+
+## Choose an example by structure
+
+Select the main example in the [Type router](../SKILL.md#type-router) before
+loading its content, using the request and repository metadata already needed
+for source inspection. Selection fits the existing read batch and needs no extra
+message, command, or repository-wide scan. For mixed or unclear tasks, use the
+requested responsibilities and entry points as they become known in normal
+inspection; keep their actual roles. Read another example when a necessary
+capability remains unexplained. Examples teach shape, not facts: a library need
+not acquire filesystem nodes, and finished showcases still follow the
+first-draft automatic-routing rule.
+
+## Author from evidence
+
+Use the mode's complete JSON shape, including repository identity,
+components, and connections; every repository-backed component needs supporting source
+references, while boundaries, cards, or guided views are added only when they
+answer a real reader question. Let automatic routes and automatic
+viewBox sizing work first. Keep the primary path readable, put exception paths
+beside their owner, and leave filesystem stores outside a control boundary when
+the source shows a separate responsibility.
+
+An existing example teaches field shape, not facts or arbitrary values. It does
+not authorize a new boundary kind, a long note, a viewBox size, or a route
+control. Consult the specific mode schema and `schemas/common.schema.json`
+whether or not the selected example already contains the field; use the
+schema's enum, length, identifier, and repository rules. Architecture
+boundaries currently use `kind: "region"` or `kind: "security-group"`; source
+references use `path`, `line`, and optional `end_line`; guided-view notes have
+their own limit.
+
+Repository-backed components need concise, truthful `sources` references. Keep
+control ownership separate from filesystem I/O: the code that reads or writes
+a file owns that action, while a pure in-memory transform receives and returns
+values. Use the existing examples for valid field shape, then replace all
+identifiers, wording, source paths, and claims with inspected repository facts.
diff --git a/archify/references/update-awareness.md b/archify/references/update-awareness.md
new file mode 100644
index 00000000..45d84587
--- /dev/null
+++ b/archify/references/update-awareness.md
@@ -0,0 +1,9 @@
+# Update awareness
+
+Read this file only when `scripts/check-update.mjs` returns `update_available`.
+
+Show one compact notice in the user's conversation language with the installed version, latest version, the checker's fixed local summary, and official release-notes link. When `severity` is `security`, label it as a security update with restrained emphasis; this changes emphasis only, never user autonomy. Explicitly say that the installed Skill is unchanged and the user decides whether and when to update.
+
+You may translate the fixed local sentence. Never quote, summarize, or translate the remote manifest's summary. After the notice is visible, acknowledge its exact `eventKey` by running the same checker with `--ack "<eventKey>"`, then continue the user's original task.
+
+The notice is information, not permission. Keep the installed version unchanged. This workflow never downloads, installs, or executes an update, and silence is never consent.
diff --git a/archify/test/adaptive-reader-layout.test.mjs b/archify/test/adaptive-reader-layout.test.mjs
index a4178427..ef740415 100644
--- a/archify/test/adaptive-reader-layout.test.mjs
+++ b/archify/test/adaptive-reader-layout.test.mjs
@@ -19,7 +19,7 @@ import {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..');
const template = fs.readFileSync(path.join(skillRoot, 'assets', 'template.html'), 'utf8');
-const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+const skill = fs.readFileSync(path.join(skillRoot, 'references/authoring-defaults.md'), 'utf8');
const architectureRenderer = fs.readFileSync(path.join(skillRoot, 'renderers', 'architecture', 'render-architecture.mjs'), 'utf8');
const reader = template.slice(
template.indexOf('Adaptive Reader Shell'),
@@ -130,7 +130,7 @@ test('reader remeasures real content and reduces width before allowing desktop p
assert.match(skill, /1440×900, 1600×1000, 1920×1080, and 2048×1320/);
assert.match(skill, /Reader-declared vertical page scroll/);
assert.match(skill, /Generate one responsive artifact for laptops and external displays/);
- assert.match(skill, /preserve the authored SVG\/viewBox, proportions, semantic geometry/);
+ assert.match(skill, /preserv(?:e|ing) the authored SVG\/viewBox, proportions, semantic geometry/);
});
test('reader exposes an explicit stable-dimensions contract for browser evidence', () => {
diff --git a/archify/test/authoring-safety-contract.test.mjs b/archify/test/authoring-safety-contract.test.mjs
index 6c1d8430..ffa0f9cf 100644
--- a/archify/test/authoring-safety-contract.test.mjs
+++ b/archify/test/authoring-safety-contract.test.mjs
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..');
const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+const authoringDefaults = fs.readFileSync(path.join(skillRoot, 'references', 'authoring-defaults.md'), 'utf8');
const authoringContract = fs.readFileSync(
path.join(skillRoot, 'references', 'authoring-contract.md'),
'utf8',
@@ -14,7 +15,7 @@ const authoringContract = fs.readFileSync(
const schemaReadme = fs.readFileSync(path.join(skillRoot, 'schemas', 'README.md'), 'utf8');
test('semantic relationship labels are preserved and deletion is not a geometry repair', () => {
- for (const [name, source] of [['SKILL.md', skill], ['authoring contract', authoringContract]]) {
+ for (const [name, source] of [['authoring defaults', authoringDefaults], ['authoring contract', authoringContract]]) {
assert.match(source, /Relationship labels are semantic data/i, name);
assert.match(source, /move the label[\s\S]*adjust the route or spacing[\s\S]*shorten/i, name);
assert.match(source, /protocol[\s\S]*action[\s\S]*direction[\s\S]*synchronous[\s\S]*asynchronous[\s\S]*cross-boundary mechanism/i, name);
@@ -31,10 +32,10 @@ test('schema policy documents the workflow v1/v2 compatibility boundary', () =>
});
test('deployment ownership stays explicit, fact-backed, and cannot be removed to pass', () => {
- assert.match(skill, /Omit `meta\.engineering_profile` by default/);
- assert.match(skill, /Region.*cluster.*security boundar.*do not.*enable/i);
- assert.match(skill, /production deployment topology.*ownership.*fail-closed deployment review/i);
- assert.match(skill, /must not remove.*engineering profile.*pass validation/i);
+ assert.match(authoringDefaults, /Omit `meta\.engineering_profile` by default/);
+ assert.match(authoringDefaults, /Region.*cluster.*security boundar.*do not.*enable/i);
+ assert.match(authoringDefaults, /production deployment topology.*ownership.*fail-closed deployment review/i);
+ assert.match(authoringDefaults, /must not remove.*engineering profile.*pass validation/i);
});
test('visual-check stays a pending sidecar receipt instead of a polish claim', () => {
@@ -42,8 +43,8 @@ test('visual-check stays a pending sidecar receipt instead of a polish claim', (
path.join(skillRoot, 'references', 'delivery-contract.md'),
'utf8',
);
- assert.match(skill, /visual-check <output\.html> --json/);
- assert.match(skill, /automated browser evidence[\s\S]*perceptual visual review/i);
+ assert.match(skill, /Run `visual-check` on the finalized artifact/);
+ assert.match(skill, /machine-readable browser evidence[\s\S]*perceptual review/i);
assert.match(skill, /references\/delivery-contract\.md/);
assert.match(skill, /without (?:rerendering or )?modifying/i);
diff --git a/archify/test/automatic-port-spread.test.mjs b/archify/test/automatic-port-spread.test.mjs
index a73bbf72..187dc096 100644
--- a/archify/test/automatic-port-spread.test.mjs
+++ b/archify/test/automatic-port-spread.test.mjs
@@ -361,7 +361,7 @@ test('lifecycle: same-band port spread remains orthogonal', () => {
});
test('skill and READMEs describe automatic port spread as bounded default behavior', () => {
- const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+ const skill = fs.readFileSync(path.join(skillRoot, 'references/authoring-defaults.md'), 'utf8');
assert.match(skill, /Automatic Port Spread is a default renderer behavior/);
assert.match(skill, /single relationship|single relationships/);
assert.match(skill, /explicit `via`.*`channelX`.*`channelY`.*`labelAt`/);
diff --git a/archify/test/cli.test.mjs b/archify/test/cli.test.mjs
index c4be17a1..cad1f912 100644
--- a/archify/test/cli.test.mjs
+++ b/archify/test/cli.test.mjs
@@ -176,7 +176,9 @@ test('cli: help lists commands and diagram types', () => {
assert.match(result.stdout, /archify render <type>/);
assert.match(result.stdout, /archify compare architecture <base\.json> <head\.json>/);
assert.match(result.stdout, /archify deliver <type>/);
+ assert.match(result.stdout, /archify finalize <type>/);
assert.match(result.stdout, /archify preview <type>/);
+ assert.match(result.stdout, /archify browser-check <output\.html>/);
assert.match(result.stdout, /archify visual-check <output\.html>/);
assert.match(result.stdout, /--open/);
assert.match(result.stdout, /archify validate <type> <input\.json> .*\[--repo-root path\]/);
@@ -196,6 +198,7 @@ test('cli: doctor reports a complete installation is ready', () => {
assert.match(result.stdout, /\[ok\] Live preview runtime/);
assert.match(result.stdout, /\[ok\] Atomic output safety runtime/);
assert.match(result.stdout, /\[ok\] Sidecar path naming runtime/);
+ assert.match(result.stdout, /\[ok\] Finalize runtime/);
assert.match(result.stdout, /\[ok\] Scenario recipe guide/);
assert.match(result.stdout, /\[ok\] Progressive authoring references/);
assert.match(result.stdout, /\[ok\] Architecture compare runtime and proof fixtures/);
@@ -399,7 +402,7 @@ test('cli: visual-check returns a skipped receipt with exit 2 when Chrome is una
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
- assert.equal(result.status, 2, result.stderr);
+ assert.equal(result.status, 2, result.stderr || result.stdout);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.status, 'skipped');
assert.equal(receipt.evidenceKind, 'automated-browser');
@@ -408,6 +411,57 @@ test('cli: visual-check returns a skipped receipt with exit 2 when Chrome is una
assert.equal(fs.existsSync(out.replace(/\.html$/, '.visual-check.json')), true);
});
+test('cli: browser-check returns deterministic evidence without requesting perceptual review', () => {
+ const out = path.join(tmp, 'browser-check-skipped.html');
+ fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
+ const missingChrome = path.join(tmp, 'missing-browser-check-chrome');
+ const result = run(['browser-check', out, '--json'], {
+ env: { ...process.env, ARCHIFY_CHROME: missingChrome },
+ });
+
+ assert.equal(result.status, 2, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(receipt.command, 'browser-check');
+ assert.equal(receipt.status, 'skipped');
+ assert.equal(receipt.evidenceKind, 'automated-browser');
+ assert.equal(receipt.visualReview, 'not-requested');
+ assert.equal(receipt.captures.status, 'not-requested');
+ assert.equal(receipt.chrome.status, 'unavailable');
+ assert.equal(fs.existsSync(out.replace(/\.html$/, '.browser-check.json')), true);
+ assert.equal(fs.existsSync(out.replace(/\.html$/, '.browser-check.contact.png')), false);
+});
+
+test('cli: finalize emits one compact receipt and keeps complete stage evidence in its sidecar', () => {
+ const input = path.join(skillRoot, 'examples/web-app.architecture.json');
+ const out = path.join(tmp, 'finalize-skipped.html');
+ const outDir = path.join(tmp, 'finalize-skipped-evidence');
+ const missingChrome = path.join(tmp, 'missing-finalize-chrome');
+ const result = run([
+ 'finalize', 'architecture', input, out,
+ '--quality', 'showcase', '--json', '--out-dir', outDir,
+ ], { env: { ...process.env, ARCHIFY_CHROME: missingChrome } });
+
+ assert.equal(result.status, 2, result.stderr || result.stdout);
+ assert.equal(result.stdout.trim().split('\n').length, 1, 'agent stdout stays compact');
+ const summary = JSON.parse(result.stdout);
+ assert.equal(summary.status, 'skipped');
+ assert.equal(summary.failedStage, 'browser-check');
+ assert.deepEqual(summary.gates, {
+ validate: 'pass', deliver: 'pass', check: 'pass', 'browser-check': 'skipped',
+ });
+ assert.equal(summary.visualReview, 'not-requested');
+ assert.equal(summary.evidence.receipt, path.join(outDir, 'finalize-skipped.finalize.json'));
+ assert.equal(summary.evidence.summaryReceipt, path.join(outDir, 'finalize-skipped.finalize-summary.json'));
+ assert.equal(summary.evidence.browserCheckReceipt, path.join(outDir, 'finalize-skipped.browser-check.json'));
+ const full = JSON.parse(fs.readFileSync(summary.evidence.receipt, 'utf8'));
+ assert.equal(full.stages.validate.receipt.validation.checkCount, 9);
+ assert.equal(full.stages['browser-check'].receipt.status, 'skipped');
+ const persistedSummary = JSON.parse(fs.readFileSync(summary.evidence.summaryReceipt, 'utf8'));
+ assert.deepEqual(persistedSummary, summary);
+ assert.equal('stages' in persistedSummary, false);
+ assert.equal(fs.existsSync(out), true, 'verified delivery remains available when browser evidence is skipped');
+});
+
test('cli: visual-check --out-dir writes the receipt into that directory, not beside the artifact', () => {
const out = path.join(tmp, 'visual-check-outdir.html');
fs.writeFileSync(out, '<!doctype html><html><body>delivered</body></html>');
@@ -417,7 +471,7 @@ test('cli: visual-check --out-dir writes the receipt into that directory, not be
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
- assert.equal(result.status, 2, result.stderr);
+ assert.equal(result.status, 2, result.stderr || result.stdout);
const receipt = JSON.parse(result.stdout);
assert.equal(receipt.status, 'skipped');
assert.equal(fs.existsSync(path.join(outDir, 'visual-check-outdir.visual-check.json')), true);
@@ -492,7 +546,7 @@ test('cli: visual-check describes human output as automated browser evidence, no
env: { ...process.env, ARCHIFY_CHROME: missingChrome },
});
- assert.equal(result.status, 2, result.stderr);
+ assert.equal(result.status, 2, result.stderr || result.stdout);
assert.match(result.stdout, /automated browser evidence skipped:/i);
assert.match(result.stdout, /perceptual visual review pending/i);
assert.doesNotMatch(result.stdout, /^visual-check skipped:/m);
diff --git a/archify/test/delivery-contract.test.mjs b/archify/test/delivery-contract.test.mjs
index b53d0bfb..a0354743 100644
--- a/archify/test/delivery-contract.test.mjs
+++ b/archify/test/delivery-contract.test.mjs
@@ -29,62 +29,74 @@ test('delivery contract describes the directory-wide physical delivery lock', ()
assert.match(delivery, /pre-namespace raw pending journal[\s\S]*independent\s+fail-closed barrier[\s\S]*encoded pending\s+journal also exists/i);
});
-test('skill requires a bounded and truthful perceptual delivery receipt', () => {
- assert.match(delivery, /browser_evidence: passed\|failed\|skipped/);
- assert.match(delivery, /visual_review: passed/);
- assert.match(delivery, /visual_review: skipped \(image reader unavailable\)/);
- assert.match(delivery, /correction_rounds: [0-2]/);
- assert.match(delivery, /maximum of two focused correction rounds/i);
- assert.match(delivery, /never report `visual_review: passed` without inspecting/i);
+const finalizeSection = delivery.match(/For the ordinary agent handoff path[\s\S]*?The individual commands remain authoritative/)?.[0] ?? '';
+const browserSection = delivery.match(/## Automated browser evidence[\s\S]*?## Optional capture evidence/)?.[0] ?? '';
+const optionalReviewSection = delivery.match(/## Optional perceptual review[\s\S]*?## Handoff receipt/)?.[0] ?? '';
+
+test('ordinary handoff uses one deterministic finalizer without image capability', () => {
+ assert.ok(skill.indexOf('## Existing candidate handoff') < skill.indexOf('## Fast authoring path'));
+ assert.match(skill, /run `finalize` first as one CLI invocation/);
+ assert.match(skill, /passing receipt completes the handoff; screenshots and an image-capable model are optional/i);
+ assert.match(skill, /archify\.mjs finalize <type> <candidate\.json> <output\.html> --quality showcase --json/);
+ assert.match(skill, /When the user supplies a frozen candidate[\s\S]*?run `finalize` first as one CLI invocation/);
+ assert.match(skill, /Once the complete first candidate is written, run `finalize` directly\. Its first gate is showcase validation/);
+ assert.doesNotMatch(skill, /node bin\/archify\.mjs deliver <type> <candidate\.json> <output\.html>/);
+
+ assert.match(finalizeSection, /`browser-check --require-provenance`/);
+ assert.match(finalizeSection, /stops at the first failed or skipped stage/i);
+ assert.match(finalizeSection, /Complete stage\s+receipts and timings[\s\S]*<output-stem>\.finalize\.json/i);
+ assert.match(finalizeSection, /visualReview: "not-requested"/);
+ assert.match(finalizeSection, /does not create images or require a perceptual reviewer/i);
+ assert.match(finalizeSection, /Merely\s+naming the gates or requiring each one to pass does not require replaying their\s+standalone commands/);
+});
+
+test('required browser evidence stays deterministic and capture-free', () => {
+ assert.match(browserSection, /browser-check <output\.html> --json --require-provenance/);
+ assert.match(browserSection, /1440×900, 1600×1000, 1920×1080, and\s+2048×1320/);
+ assert.match(browserSection, /creates one\s+`<output-stem>\.browser-check\.json` receipt and no screenshots or contact sheet/i);
+ assert.match(browserSection, /visualReview: "not-requested"/);
+ assert.match(browserSection, /Reader reaches its projected text floor/i);
});
-test('skill keeps deterministic delivery, automated browser evidence, and perceptual review distinct', () => {
+test('delivery, browser evidence, capture evidence, and perceptual review remain distinct', () => {
for (const [name, source] of [['SKILL.md', skill], ['delivery contract', delivery]]) {
assert.match(source, /deliver[\s\S]*deterministic/i, name);
- assert.match(source, /visual-check[\s\S]*automated browser evidence/i, name);
- assert.match(source, /human|perceptual visual review/i, name);
+ assert.match(source, /browser-check[\s\S]*browser evidence/i, name);
+ assert.match(source, /visual-check[\s\S]*capture|screenshots/i, name);
+ assert.match(source, /human|perceptual review/i, name);
}
- assert.match(delivery, /manual browser record[\s\S]*all four exact viewport measurements, both endpoint themes, and an artifact-bound record/i);
+ assert.match(delivery, /Passing one claim never implies the others/i);
+ assert.match(delivery, /Never claim that the deterministic receipt includes browser or perceptual review evidence/i);
});
-test('strict provenance check must succeed before visual-check', () => {
- const workflows = [
- {
- name: 'SKILL.md',
- section: skill.match(/After `deliver` exits zero, require current delivery evidence before handoff:[\s\S]*?node bin\/archify\.mjs visual-check <output\.html> --json --require-provenance/)?.[0] ?? '',
- check: 'node bin/archify.mjs check <output.html> --require-provenance',
- visualCheck: 'node bin/archify.mjs visual-check <output.html> --json --require-provenance',
- },
- {
- name: 'delivery contract',
- section: delivery.match(/Run strict `check` after `deliver` exits zero\.[\s\S]*?before collecting new\s+visual evidence\./)?.[0] ?? '',
- check: 'strict `check`',
- visualCheck: '`visual-check`',
- },
- ];
-
- for (const { name, section, check, visualCheck } of workflows) {
- const checkIndex = section.indexOf(check);
- const visualCheckIndex = section.indexOf(visualCheck);
-
- assert.notEqual(checkIndex, -1, `${name}: strict check command is documented`);
- assert.ok(checkIndex < visualCheckIndex, `${name}: strict check command precedes visual-check`);
- assert.match(
- section,
- /(?:after the strict `check` above exits zero[\s\S]{0,300}visual-check|visual-check`? only after that\s+strict check exits zero)/i,
- `${name}: visual-check requires a successful strict check`,
- );
- }
+test('strict provenance succeeds before either browser command', () => {
+ const ordering = delivery.match(/Run strict `check` after `deliver` exits zero\.[\s\S]*?collecting new browser evidence\./)?.[0] ?? '';
+ assert.match(ordering, /Run `browser-check` or optional\s+`visual-check` only after that strict check exits zero/i);
+ assert.match(skill, /required order stays `deliver` → strict provenance `check` → `browser-check`/);
+ assert.match(skill, /Run optional `visual-check` only against a strict-provenance artifact/);
+});
+
+test('perceptual review is an explicit risk escalation with a bounded correction loop', () => {
+ assert.match(optionalReviewSection, /visual_review: not_requested/);
+ assert.match(optionalReviewSection, /user explicitly requests an aesthetic or visual review/i);
+ assert.match(optionalReviewSection, /template, renderer, or Viewer change/i);
+ assert.match(optionalReviewSection, /novel layout or browser diagnostic leaves low confidence/i);
+ assert.match(optionalReviewSection, /sampled audit or dogfood/i);
+ assert.match(optionalReviewSection, /run `visual-check`[\s\S]*contact sheet/i);
+ assert.match(optionalReviewSection, /never exceed two focused correction rounds/i);
+ assert.match(optionalReviewSection, /Never report\s+`visual_review: passed` without inspecting/i);
+ assert.match(skill, /Model image capability is optional/i);
+ assert.match(delivery, /Open the HTML contact sheet in a browser or inspect the viewport PNGs/i);
});
-test('handoff browser evidence mirrors only the automated visual-check outcome', () => {
- assert.match(delivery, /`browser_evidence`[\s\S]*records only the outcome of this automated command/i);
- assert.match(delivery, /`passed`[\s\S]*exit 0[\s\S]*receipt `status: "pass"`/i);
- assert.match(delivery, /`failed`[\s\S]*exit 1[\s\S]*receipt `status: "fail"`/i);
- assert.match(delivery, /`skipped`[\s\S]*exit 2[\s\S]*receipt `status: "skipped"`/i);
- assert.match(delivery, /runtime or capture failures[\s\S]*must not be normalized to `skipped`/i);
- assert.match(delivery, /remains `skipped` even when[\s\S]*`visual_review: passed`/i);
- assert.match(delivery, /manual browser record[\s\S]*never changes `browser_evidence`/i);
+test('handoff browser evidence mirrors only browser-check outcomes', () => {
+ assert.match(browserSection, /`browser_evidence`[\s\S]*records only the outcome of this automated\s+command/i);
+ assert.match(browserSection, /`passed`[\s\S]*exit 0[\s\S]*receipt `status: "pass"`/i);
+ assert.match(browserSection, /`failed`[\s\S]*exit 1[\s\S]*receipt `status: "fail"`/i);
+ assert.match(browserSection, /`skipped`[\s\S]*exit 2[\s\S]*receipt `status: "skipped"`/i);
+ assert.match(browserSection, /Runtime failures[\s\S]*must not be normalized to\s+`skipped`/i);
+ assert.match(delivery, /Derive `browser_evidence` only from the latest artifact-bound `browser-check`\s+receipt/i);
+ assert.match(delivery, /visual_review: not_requested\|passed\|skipped \(image reader unavailable\)\|failed/);
});
test('visual evidence replacement is ownership-bound and fails closed on slot changes', () => {
@@ -107,7 +119,7 @@ test('skill uses recoverable verified delivery for the final artifact', () => {
assert.match(delivery, /same-directory candidate/i);
assert.match(delivery, /only replaces the target after.*artifact checks pass/i);
assert.match(delivery, /journal[\s\S]*checkers then fail closed/i);
- assert.match(delivery, /never claim that the deterministic receipt includes visual review/i);
+ assert.match(delivery, /never claim that the deterministic receipt includes browser or perceptual review evidence/i);
});
test('no-clobber publishers freeze the write slot and reject hardlinked write targets', () => {
@@ -130,9 +142,8 @@ test('publication contract distinguishes no-clobber recovery from crash-atomic r
test('skill keeps optional opening behind the verified commit and outside automation', () => {
assert.match(delivery, /Add `--open` only when the user wants an immediate local preview/);
- assert.match(delivery, /runs after[\s\S]*verified pair commit[\s\S]*journal has been\s+removed/);
- assert.match(delivery, /journal has been removed[\s\S]*delivery lock has been released successfully/);
- assert.match(delivery, /Keep it off for CI, unattended agents, and non-interactive\s+environments/);
+ assert.match(delivery, /runs after[\s\S]*verified pair commit[\s\S]*journal has been removed/i);
+ assert.match(delivery, /journal has been removed[\s\S]*delivery lock has been released successfully/i);
+ assert.match(delivery, /Keep it off for CI, unattended agents, and non-interactive\s+environments/i);
assert.match(delivery, /never invokes an opener/);
- assert.match(delivery, /status proves only whether the local opener invocation succeeded/);
});
diff --git a/archify/test/finalize-browser-lifecycle.test.mjs b/archify/test/finalize-browser-lifecycle.test.mjs
new file mode 100644
index 00000000..9e0fbd1c
--- /dev/null
+++ b/archify/test/finalize-browser-lifecycle.test.mjs
@@ -0,0 +1,311 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { runFinalize } from '../bin/finalize.mjs';
+import { CAPTURE_VIEWPORTS, THEMES, VISUAL_CHECK_VIEWPORTS } from '../bin/visual-check.mjs';
+
+function workspace(t) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-finalize-browser-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ return directory;
+}
+
+function identity(contents) {
+ const bytes = Buffer.isBuffer(contents) ? contents : Buffer.from(contents);
+ return {
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ bytes: bytes.byteLength,
+ };
+}
+
+function stageResult(receipt, status = 0) {
+ return { status, stdout: JSON.stringify(receipt), stderr: '' };
+}
+
+function delivery({ input, output, source }) {
+ const artifact = '<!doctype html><title>browser lifecycle</title>';
+ fs.writeFileSync(output, artifact);
+ const receipt = {
+ schemaVersion: 1,
+ receiptId: '11111111-1111-4111-8111-111111111111',
+ ok: true,
+ command: 'deliver',
+ type: 'architecture',
+ input,
+ output,
+ specification: identity(source),
+ artifact: identity(artifact),
+ validation: {
+ checksPassed: 9,
+ checkCount: 9,
+ compositionProfile: 'showcase',
+ compositionStatus: 'pass',
+ errors: 0,
+ warnings: 0,
+ },
+ };
+ fs.writeFileSync(output.replace(/\.html?$/i, '.delivery.json'), `${JSON.stringify({
+ schemaVersion: 1,
+ receiptId: receipt.receiptId,
+ status: 'current',
+ command: 'deliver',
+ type: receipt.type,
+ input: receipt.input,
+ output: receipt.output,
+ specification: receipt.specification,
+ artifact: receipt.artifact,
+ })}\n`);
+ return receipt;
+}
+
+function check(output, delivered) {
+ return {
+ schemaVersion: 1,
+ ok: true,
+ file: output,
+ artifact: delivered.artifact,
+ checks: Array.from({ length: 9 }, (_, index) => ({ name: `check-${index}`, ok: true })),
+ provenance: 'current',
+ deliveryReceiptId: delivered.receiptId,
+ composition: {
+ schemaVersion: 1,
+ profile: 'showcase',
+ status: 'pass',
+ summary: { errors: 0, warnings: 0 },
+ },
+ };
+}
+
+function browserReceipt(output, delivered, outDir) {
+ return {
+ schemaVersion: 1,
+ ok: true,
+ command: 'browser-check',
+ evidenceKind: 'automated-browser',
+ status: 'pass',
+ provenance: 'current',
+ deliveryReceiptId: delivered.receiptId,
+ artifact: { path: output, ...delivered.artifact },
+ containment: {
+ status: 'pass',
+ viewports: VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => ({ width, height, theme: 'light', ok: true })),
+ },
+ themeStates: {
+ status: 'pass',
+ viewports: CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map((theme) => ({
+ width, height, requestedTheme: theme, resolvedTheme: theme, ok: true,
+ }))),
+ },
+ readability: {
+ status: 'pass',
+ viewports: VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => ({
+ width, height, theme: 'light', ok: true, readabilityOk: true,
+ })),
+ },
+ viewerChrome: {
+ status: 'pass',
+ viewports: VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => ({
+ width, height, theme: 'light', ok: true, viewerChromeOk: true,
+ })),
+ },
+ sidecars: { directory: outDir, receipt: 'diagram.browser-check.json' },
+ };
+}
+
+function browser(events, sessionPromise = Promise.resolve()) {
+ return {
+ sessionPromise,
+ async inspect() { events.push('inspect'); },
+ async close() { events.push('close'); },
+ };
+}
+
+function inputs(t) {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const outDir = path.join(directory, 'evidence');
+ const source = '{"meta":{"quality_profile":"showcase"}}';
+ fs.writeFileSync(input, source);
+ return { directory, input, output, outDir, source };
+}
+
+function options({ input, output, outDir, runCommand, runBrowserCheck, resolveChrome, createBrowser }) {
+ return {
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ outDir,
+ runCommand,
+ runBrowserCheck,
+ resolveChrome,
+ createBrowser,
+ };
+}
+
+test('finalize prestarts Chrome during deliver without inspecting it before the browser gate consumes it', async t => {
+ const { input, output, outDir, source } = inputs(t);
+ const events = [];
+ let delivered;
+ const finalized = await runFinalize(options({
+ input, output, outDir,
+ resolveChrome: () => '/fake/chrome',
+ createBrowser: (chromePath, { env }) => {
+ assert.equal(chromePath, '/fake/chrome');
+ assert.ok(env);
+ events.push('create');
+ return browser(events);
+ },
+ runCommand: async ({ stage }) => {
+ events.push(`run:${stage}`);
+ assert.deepEqual(events.filter((event) => event === 'inspect'), []);
+ if (stage === 'deliver') {
+ assert.deepEqual(events, ['create', 'run:deliver']);
+ await Promise.resolve();
+ delivered = delivery({ input, output, source });
+ return stageResult(delivered);
+ }
+ assert.deepEqual(events, ['create', 'run:deliver', 'run:check']);
+ return stageResult(check(output, delivered));
+ },
+ runBrowserCheck: async ({ artifactPath, outDir: receivedOutDir, chromePath, resolveChrome, browserFactory }) => {
+ assert.equal(artifactPath, output);
+ assert.equal(receivedOutDir, outDir);
+ assert.equal(chromePath, '/fake/chrome');
+ assert.equal(resolveChrome(), '/fake/chrome');
+ const reusable = browserFactory();
+ await reusable.sessionPromise;
+ await reusable.inspect();
+ await reusable.close();
+ return { exitCode: 0, receipt: browserReceipt(output, delivered, outDir) };
+ },
+ }));
+
+ assert.equal(finalized.exitCode, 0);
+ assert.equal(finalized.receipt.stages['browser-check'].execution, 'in-process');
+ assert.deepEqual(events, ['create', 'run:deliver', 'run:check', 'inspect', 'close']);
+});
+
+test('finalize closes a prestarted browser without navigation when deliver or check fails', async t => {
+ for (const failedStage of ['deliver', 'check']) {
+ const { input, output, outDir, source } = inputs(t);
+ const events = [];
+ let delivered;
+ const finalized = await runFinalize(options({
+ input, output, outDir,
+ resolveChrome: () => '/fake/chrome',
+ createBrowser: () => { events.push('create'); return browser(events); },
+ runBrowserCheck: () => { throw new Error('browser gate must not run'); },
+ runCommand: ({ stage }) => {
+ events.push(`run:${stage}`);
+ if (stage === failedStage) return stageResult({ ok: false, command: stage, diagnostics: [] }, 1);
+ delivered = delivery({ input, output, source });
+ return stageResult(delivered);
+ },
+ }));
+ assert.equal(finalized.exitCode, 1, failedStage);
+ assert.equal(finalized.receipt.failedStage, failedStage === 'deliver' ? 'deliver' : 'check', failedStage);
+ assert.equal(events.includes('inspect'), false, failedStage);
+ assert.equal(events.filter((event) => event === 'close').length, 1, failedStage);
+ }
+});
+
+test('a rejected Chrome attach does not replace a delivery failure or emit an unhandled rejection', async t => {
+ const { input, output, outDir } = inputs(t);
+ const events = [];
+ const unhandled = [];
+ const onUnhandled = (reason) => unhandled.push(reason);
+ process.on('unhandledRejection', onUnhandled);
+ try {
+ const finalized = await runFinalize(options({
+ input, output, outDir,
+ resolveChrome: () => '/fake/chrome',
+ createBrowser: () => browser(events, Promise.reject(new Error('attach failed'))),
+ runBrowserCheck: () => { throw new Error('browser gate must not run'); },
+ runCommand: () => stageResult({ ok: false, command: 'deliver', diagnostics: [] }, 1),
+ }));
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(finalized.exitCode, 1);
+ assert.equal(finalized.receipt.failedStage, 'deliver');
+ assert.deepEqual(unhandled, []);
+ assert.deepEqual(events, ['close']);
+ } finally {
+ process.off('unhandledRejection', onUnhandled);
+ }
+});
+
+test('Chrome startup and discovery failures are reported by the browser gate', async t => {
+ const scenarios = [
+ {
+ name: 'startup failure',
+ resolveChrome: () => '/fake/chrome',
+ createBrowser: () => { throw new Error('Chrome attach failed'); },
+ exitCode: 1,
+ expectedStatus: 'fail',
+ },
+ {
+ name: 'Chrome unavailable',
+ resolveChrome: () => null,
+ createBrowser: () => { throw new Error('must not construct'); },
+ exitCode: 2,
+ expectedStatus: 'skipped',
+ },
+ ];
+ for (const scenario of scenarios) {
+ const { input, output, outDir, source } = inputs(t);
+ let delivered;
+ let created = false;
+ const finalized = await runFinalize(options({
+ input, output, outDir,
+ resolveChrome: scenario.resolveChrome,
+ createBrowser: (...args) => {
+ created = true;
+ return scenario.createBrowser(...args);
+ },
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivered = delivery({ input, output, source });
+ return stageResult(delivered);
+ }
+ return stageResult(check(output, delivered));
+ },
+ runBrowserCheck: ({ browserFactory }) => {
+ if (scenario.exitCode === 1) {
+ assert.throws(browserFactory, /Chrome attach failed/);
+ return { exitCode: 1, receipt: { ok: false, command: 'browser-check', diagnostics: [] } };
+ }
+ assert.throws(browserFactory, /unavailable/);
+ return { exitCode: 2, receipt: { ok: false, command: 'browser-check', status: 'skipped' } };
+ },
+ }));
+ assert.equal(finalized.exitCode, scenario.exitCode, scenario.name);
+ assert.equal(finalized.receipt.stages['browser-check'].status, scenario.expectedStatus, scenario.name);
+ assert.equal(finalized.receipt.failedStage, 'browser-check', scenario.name);
+ assert.equal(created, scenario.exitCode === 1, scenario.name);
+ }
+});
+
+test('finalize closes an unconsumed browser when the in-process browser callback throws', async t => {
+ const { input, output, outDir, source } = inputs(t);
+ const events = [];
+ let delivered;
+ await assert.rejects(() => runFinalize(options({
+ input, output, outDir,
+ resolveChrome: () => '/fake/chrome',
+ createBrowser: () => browser(events),
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivered = delivery({ input, output, source });
+ return stageResult(delivered);
+ }
+ return stageResult(check(output, delivered));
+ },
+ runBrowserCheck: () => { throw new Error('browser callback failed before consume'); },
+ })), /browser callback failed before consume/);
+ assert.deepEqual(events, ['close']);
+});
diff --git a/archify/test/finalize-browser.test.mjs b/archify/test/finalize-browser.test.mjs
new file mode 100644
index 00000000..0feef198
--- /dev/null
+++ b/archify/test/finalize-browser.test.mjs
@@ -0,0 +1,42 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const cli = path.join(skillRoot, 'bin/archify.mjs');
+
+test('finalize proves all four gates in real Chrome with bounded mixed-case sidecars and repeat delivery', {
+ skip: !process.env.ARCHIFY_CHROME,
+}, t => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-finalize-browser-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const output = path.join(dir, `${'long-'.repeat(46)}.HTML`);
+ const captureSentinel = path.join(dir, 'unrelated.visual-check.light.png');
+ fs.writeFileSync(captureSentinel, 'existing capture evidence');
+ let evidence;
+ for (let attempt = 0; attempt < 2; attempt++) {
+ const result = spawnSync(process.execPath, [
+ cli, 'finalize', 'architecture', path.join(skillRoot, 'examples/web-app.architecture.json'), output,
+ '--quality', 'showcase', '--json',
+ ], { cwd: skillRoot, encoding: 'utf8', env: process.env, timeout: 180000 });
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ assert.deepEqual(receipt.gates, { validate: 'pass', deliver: 'pass', check: 'pass', 'browser-check': 'pass' });
+ assert.equal(receipt.visualReview, 'not-requested');
+ if (evidence) assert.deepEqual(receipt.evidence, evidence);
+ evidence = receipt.evidence;
+ const browser = JSON.parse(fs.readFileSync(receipt.evidence.browserCheckReceipt));
+ assert.equal(browser.command, 'browser-check');
+ assert.equal(browser.containment.viewports.length, 4);
+ assert.equal(browser.themeStates.viewports.length, 4);
+ assert.equal(browser.captures.status, 'not-requested');
+ assert.deepEqual(browser.captures.screenshots, []);
+ assert.equal(browser.deliveryReceiptId, JSON.parse(fs.readFileSync(evidence.receipt)).stages.deliver.receipt.receiptId);
+ assert.equal(fs.readFileSync(captureSentinel, 'utf8'), 'existing capture evidence');
+ assert.deepEqual(fs.readdirSync(dir).filter(name => name.endsWith('.png')), ['unrelated.visual-check.light.png']);
+ }
+});
diff --git a/archify/test/finalize-paths.test.mjs b/archify/test/finalize-paths.test.mjs
new file mode 100644
index 00000000..3524509e
--- /dev/null
+++ b/archify/test/finalize-paths.test.mjs
@@ -0,0 +1,101 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { defaultFinalizeReceiptPath, defaultFinalizeSummaryPath, runFinalize } from '../bin/finalize.mjs';
+
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const cli = path.join(skillRoot, 'bin/archify.mjs');
+const example = path.join(skillRoot, 'examples/web-app.architecture.json');
+function workspace(t) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-finalize-paths-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ return dir;
+}
+function finalize(output, options = []) {
+ const result = spawnSync(process.execPath, [cli, 'finalize', 'architecture', example, output, '--quality', 'showcase', '--json', ...options], {
+ cwd: skillRoot, encoding: 'utf8', env: { ...process.env, ARCHIFY_CHROME: path.join(os.tmpdir(), 'archify-definitely-missing-chrome') },
+ });
+ return { ...result, receipt: JSON.parse(result.stdout) };
+}
+
+test('finalize uses bounded canonical delivery and evidence names for long output components', t => {
+ const dir = workspace(t);
+ const output = path.join(dir, `${'审'.repeat(78)}.html`);
+ const result = finalize(output);
+ assert.equal(result.status, 2, result.stdout || result.stderr);
+ assert.deepEqual(result.receipt.gates, { validate: 'pass', deliver: 'pass', check: 'pass', 'browser-check': 'skipped' });
+ assert.equal(result.receipt.visualReview, 'not-requested');
+ for (const entry of fs.readdirSync(dir)) assert.ok(Buffer.byteLength(entry) <= 255, entry);
+ assert.ok(fs.existsSync(result.receipt.evidence.receipt));
+ assert.ok(fs.existsSync(result.receipt.evidence.summaryReceipt));
+ assert.ok(fs.existsSync(result.receipt.evidence.browserCheckReceipt));
+ assert.equal(fs.readdirSync(dir).some(name => name.endsWith('.png')), false);
+ const retry = finalize(output);
+ assert.equal(retry.status, 2, retry.stdout || retry.stderr);
+ assert.equal(retry.receipt.evidence.receipt, result.receipt.evidence.receipt);
+});
+
+test('finalize receipt paths cannot replace a delivery journal or directory lock', t => {
+ const dir = workspace(t);
+ const output = path.join(dir, 'diagram.html');
+ for (const name of ['diagram.delivery.json', 'diagram.delivery-pending.json', 'diagram.delivery-lock.json', '.archify-delivery-lock.json']) {
+ const receiptPath = path.join(dir, name);
+ const result = finalize(output, ['--receipt', receiptPath]);
+ assert.equal(result.status, 1, name);
+ assert.match(result.receipt.diagnostics[0].message, /distinct/);
+ assert.equal(fs.existsSync(receiptPath), false);
+ assert.equal(fs.existsSync(output), false);
+ }
+});
+
+test('finalize checks both receipt targets before writing and preserves hardlinked files', async t => {
+ const dir = workspace(t);
+ const output = path.join(dir, 'diagram.html');
+ const receiptPath = defaultFinalizeReceiptPath(output);
+ const summaryPath = defaultFinalizeSummaryPath(receiptPath);
+ const source = path.join(dir, 'source.json');
+ fs.writeFileSync(source, 'sentinel');
+ fs.linkSync(source, summaryPath);
+ await assert.rejects(runFinalize({ cliPath: cli, type: 'architecture', input: example, output }), /hardlinked/);
+ assert.equal(fs.existsSync(receiptPath), false);
+ assert.equal(fs.existsSync(output), false);
+ assert.equal(fs.readFileSync(source, 'utf8'), 'sentinel');
+ assert.equal(fs.readFileSync(summaryPath, 'utf8'), 'sentinel');
+});
+
+test('finalize preserves a receipt claimant that replaces a captured target during a gate', async t => {
+ const dir = workspace(t);
+ const output = path.join(dir, 'diagram.html');
+ const receiptPath = defaultFinalizeReceiptPath(output);
+ const summaryPath = defaultFinalizeSummaryPath(receiptPath);
+ const claimant = path.join(dir, 'claimant.json');
+ fs.writeFileSync(claimant, 'external claimant');
+ await assert.rejects(runFinalize({
+ cliPath: cli, type: 'architecture', input: example, output,
+ runCommand: () => {
+ fs.renameSync(claimant, summaryPath);
+ return { status: 1, stdout: JSON.stringify({ ok: false, command: 'deliver', stage: 'render', diagnostics: [] }) };
+ },
+ }), /requested-entry-changed/);
+ assert.equal(fs.readFileSync(summaryPath, 'utf8'), 'external claimant');
+ assert.equal(fs.existsSync(output), false);
+ assert.equal(JSON.parse(fs.readFileSync(receiptPath)).status, 'running');
+});
+
+test('finalize preserves its existing receipt permissions on repeat publication', async t => {
+ const dir = workspace(t);
+ const output = path.join(dir, 'diagram.html');
+ const receiptPath = defaultFinalizeReceiptPath(output);
+ fs.writeFileSync(receiptPath, '{}', { mode: 0o600 });
+ const beforeMode = fs.statSync(receiptPath).mode & 0o777;
+ const result = await runFinalize({
+ cliPath: cli, type: 'architecture', input: example, output,
+ runCommand: () => ({ status: 1, stdout: JSON.stringify({ ok: false, command: 'deliver', stage: 'render', diagnostics: [] }) }),
+ });
+ assert.equal(result.exitCode, 1);
+ assert.equal(fs.statSync(receiptPath).mode & 0o777, beforeMode);
+});
diff --git a/archify/test/finalize.test.mjs b/archify/test/finalize.test.mjs
new file mode 100644
index 00000000..98fb451b
--- /dev/null
+++ b/archify/test/finalize.test.mjs
@@ -0,0 +1,878 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import { createHash } from 'node:crypto';
+import os from 'node:os';
+import path from 'node:path';
+
+import {
+ FINALIZE_STAGES,
+ compactFinalizeReceipt,
+ defaultFinalizeReceiptPath,
+ defaultFinalizeSummaryPath,
+ runFinalize,
+} from '../bin/finalize.mjs';
+import { CAPTURE_VIEWPORTS, THEMES, VISUAL_CHECK_VIEWPORTS } from '../bin/visual-check.mjs';
+
+function workspace(t) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-finalize-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ return directory;
+}
+
+function result(receipt, status = 0, stderr = '') {
+ return { status, signal: null, stdout: `${JSON.stringify(receipt)}\n`, stderr };
+}
+
+function artifactIdentity(contents) {
+ const bytes = Buffer.isBuffer(contents) ? contents : Buffer.from(contents);
+ return {
+ sha256: createHash('sha256').update(bytes).digest('hex'),
+ bytes: bytes.byteLength,
+ };
+}
+
+function writeCurrentDelivery(output, receipt) {
+ fs.writeFileSync(output.replace(/\.html?$/i, '.delivery.json'), `${JSON.stringify({
+ schemaVersion: 1,
+ receiptId: receipt.receiptId,
+ status: 'current',
+ command: 'deliver',
+ type: receipt.type,
+ input: receipt.input,
+ output: receipt.output,
+ specification: receipt.specification,
+ artifact: receipt.artifact,
+ })}\n`);
+}
+
+function passingDelivery({ input, output, source, artifact = '<!doctype html><title>verified</title>', receiptId = '11111111-1111-4111-8111-111111111111', quality = 'showcase', type = 'architecture' }) {
+ fs.writeFileSync(output, artifact);
+ const receipt = {
+ schemaVersion: 1,
+ receiptId,
+ ok: true,
+ command: 'deliver',
+ type,
+ input,
+ output,
+ specification: artifactIdentity(source),
+ artifact: artifactIdentity(artifact),
+ validation: {
+ checksPassed: 9,
+ checkCount: 9,
+ compositionProfile: quality,
+ compositionStatus: 'pass',
+ errors: 0,
+ warnings: 0,
+ },
+ };
+ writeCurrentDelivery(output, receipt);
+ return receipt;
+}
+
+function passingCheck({ output, artifact, deliveryReceiptId, quality = 'showcase', checkCount = 9 }) {
+ return {
+ schemaVersion: 1,
+ ok: true,
+ file: output,
+ artifact,
+ checks: Array.from({ length: checkCount }, (_, index) => ({ name: `artifact-${index}`, ok: true })),
+ provenance: 'current',
+ deliveryReceiptId,
+ composition: {
+ schemaVersion: 1,
+ profile: quality,
+ status: 'pass',
+ summary: { errors: 0, warnings: 0 },
+ },
+ };
+}
+
+function passingBrowserCheck({ output, artifact, deliveryReceiptId, outDir }) {
+ return {
+ schemaVersion: 1,
+ ok: true,
+ command: 'browser-check',
+ evidenceKind: 'automated-browser',
+ status: 'pass',
+ visualReview: 'not-requested',
+ provenance: 'current',
+ deliveryReceiptId,
+ artifact: { path: output, ...artifact },
+ diagnostics: [],
+ containment: {
+ status: 'pass',
+ viewports: VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => ({ width, height, theme: 'light', ok: true })),
+ },
+ themeStates: {
+ status: 'pass',
+ viewports: CAPTURE_VIEWPORTS.flatMap(({ width, height }) => THEMES.map((theme) => ({
+ width, height, requestedTheme: theme, resolvedTheme: theme, ok: true,
+ }))),
+ },
+ readability: {
+ status: 'pass',
+ viewports: VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => ({ width, height, theme: 'light', ok: true, readabilityOk: true })),
+ },
+ viewerChrome: {
+ status: 'pass',
+ viewports: VISUAL_CHECK_VIEWPORTS.map(({ width, height }) => ({ width, height, theme: 'light', ok: true, viewerChromeOk: true })),
+ },
+ captures: { status: 'not-requested', screenshots: [], contactSheet: null, contactSheetImage: null },
+ sidecars: { directory: outDir, receipt: 'diagram.browser-check.json' },
+ };
+}
+
+test('finalize reuses delivery validation, runs one build, and keeps full stage receipts out of its compact summary', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const outDir = path.join(directory, 'evidence');
+ const source = '{"meta":{"quality_profile":"showcase"}}';
+ fs.writeFileSync(input, source);
+ const calls = [];
+ const runCommand = ({ stage, args }) => {
+ calls.push({ stage, args });
+ if (stage === 'deliver') {
+ return result(passingDelivery({ input, output, source }));
+ }
+ if (stage === 'check') {
+ const delivery = passingDelivery({ input, output, source });
+ return result(passingCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId }));
+ }
+ fs.mkdirSync(outDir, { recursive: true });
+ fs.writeFileSync(path.join(outDir, 'diagram.browser-check.json'), 'browser evidence');
+ const delivery = passingDelivery({ input, output, source });
+ const browser = passingBrowserCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir });
+ browser.containment.viewports[0].large = 'large-stage-array-is-kept-only-in-full-receipt';
+ return result(browser);
+ };
+
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ outDir,
+ runCommand,
+ });
+
+ assert.equal(finalized.exitCode, 0);
+ assert.equal(finalized.receipt.ok, true);
+ assert.deepEqual(calls.map(({ stage }) => stage), ['deliver', 'check', 'browser-check']);
+ assert.deepEqual(finalized.summary.gates, {
+ validate: 'pass', deliver: 'pass', check: 'pass', 'browser-check': 'pass',
+ });
+ assert.equal(finalized.summary.evidence.browserCheckReceipt, path.join(outDir, 'diagram.browser-check.json'));
+ assert.equal(finalized.summary.visualReview, 'not-requested');
+ assert.equal('stages' in finalized.summary, false);
+ assert.equal(JSON.stringify(finalized.summary).includes('large-stage-array'), false);
+ assert.equal(finalized.receipt.stages['browser-check'].receipt.containment.viewports.length, VISUAL_CHECK_VIEWPORTS.length);
+
+ const receiptPath = defaultFinalizeReceiptPath(output, { outDir });
+ assert.equal(finalized.summary.evidence.receipt, receiptPath);
+ const summaryPath = defaultFinalizeSummaryPath(receiptPath);
+ assert.equal(finalized.summary.evidence.summaryReceipt, summaryPath);
+ const persisted = JSON.parse(fs.readFileSync(receiptPath, 'utf8'));
+ assert.equal(persisted.ok, true);
+ assert.equal(persisted.stages.validate.execution, 'embedded-in-deliver');
+ assert.equal(persisted.stages.validate.receipt.validation.checkCount, 9);
+ const persistedSummary = JSON.parse(fs.readFileSync(summaryPath, 'utf8'));
+ assert.equal(persistedSummary.ok, true);
+ assert.equal('stages' in persistedSummary, false);
+});
+
+test('finalize stops at the failed gate and persists actionable failure evidence', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ fs.writeFileSync(input, '{}');
+ const calls = [];
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'workflow',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ calls.push(stage);
+ return result({
+ ok: false,
+ command: 'deliver',
+ stage: 'render',
+ diagnostics: [{
+ code: 'composition/route-crossing',
+ severity: 'error',
+ message: 'A route crosses an unrelated node.',
+ subject: { edge: 'a-b' },
+ evidence: { intersection: [12, 40] },
+ supportedFixes: ['move the diagnosed route'],
+ }],
+ }, 1);
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1);
+ assert.deepEqual(calls, ['deliver']);
+ assert.equal(finalized.receipt.failedStage, 'validate');
+ assert.equal(finalized.summary.gates.deliver, 'not-run');
+ assert.equal(finalized.summary.gates.check, 'not-run');
+ assert.equal(finalized.summary.gates['browser-check'], 'not-run');
+ assert.deepEqual(finalized.summary.diagnostics, [{
+ code: 'composition/route-crossing',
+ severity: 'error',
+ message: 'A route crosses an unrelated node.',
+ subject: { edge: 'a-b' },
+ evidence: { intersection: [12, 40] },
+ supportedFixes: ['move the diagnosed route'],
+ }]);
+ assert.deepEqual(finalized.summary.diagnosticSummary, { total: 1, shown: 1, truncated: false });
+ assert.deepEqual(finalized.summary.nextAction, {
+ action: 'edit-in-place',
+ candidate: input,
+ constraint: 'Preserve unaffected semantics and geometry; do not replace the whole candidate.',
+ then: 'finalize-once',
+ });
+ assert.equal(finalized.receipt.diagnostics[0].evidence.intersection[1], 40);
+ assert.equal(JSON.parse(fs.readFileSync(finalized.summary.evidence.receipt)).status, 'fail');
+ const persistedSummary = JSON.parse(fs.readFileSync(finalized.summary.evidence.summaryReceipt));
+ assert.deepEqual(persistedSummary, finalized.summary);
+});
+
+test('compact finalize receipts preserve the acceptance boundary', () => {
+ const compact = compactFinalizeReceipt({
+ ok: true,
+ status: 'pass',
+ type: 'sequence',
+ quality: 'showcase',
+ specification: { path: '/tmp/spec.json', sha256: 'spec' },
+ artifact: { path: '/tmp/artifact.html', sha256: 'artifact' },
+ stages: Object.fromEntries(['validate', 'deliver', 'check', 'browser-check'].map((stage) => [stage, { status: 'pass' }])),
+ diagnostics: [],
+ evidence: { receipt: '/tmp/artifact.finalize.json', browserCheckReceipt: '/tmp/artifact.browser-check.json' },
+ visualReview: 'not-requested',
+ durationMs: 4200,
+ });
+ assert.equal(compact.ok, true);
+ assert.equal(compact.visualReview, 'not-requested');
+ assert.equal(compact.gates['browser-check'], 'pass');
+ assert.equal(compact.evidence.browserCheckReceipt.endsWith('.json'), true);
+ assert.deepEqual(compact.diagnosticSummary, { total: 0, shown: 0, truncated: false });
+ assert.equal('nextAction' in compact, false);
+});
+
+test('compact failure receipts retain diverse actionable subjects without embedding full stage evidence', () => {
+ const diagnostics = Array.from({ length: 20 }, (_, index) => ({
+ code: 'composition/proper-crossing',
+ severity: 'error',
+ message: `Connection edge-${index} crosses another route.`,
+ subject: { id: `edge-${index}`, collection: 'connections', index },
+ evidence: { crossing: { x: index * 10, y: index * 20 } },
+ supportedFixes: [`move edge-${index} without changing its endpoints`],
+ }));
+ const receipt = {
+ ok: false,
+ status: 'fail',
+ failedStage: 'validate',
+ type: 'architecture',
+ quality: 'showcase',
+ specification: { path: '/tmp/spec.json', sha256: 'spec' },
+ artifact: { path: '/tmp/artifact.html' },
+ stages: { validate: { status: 'fail', receipt: { diagnostics, renderedHtml: 'x'.repeat(100000) } } },
+ diagnostics,
+ evidence: {
+ receipt: '/tmp/artifact.finalize.json',
+ summaryReceipt: '/tmp/artifact.finalize-summary.json',
+ },
+ };
+
+ const compact = compactFinalizeReceipt(receipt);
+ assert.equal(compact.diagnostics.length, 8);
+ assert.equal(new Set(compact.diagnostics.map(({ subject }) => subject.id)).size, 8);
+ assert.deepEqual(compact.diagnosticSummary, { total: 20, shown: 8, truncated: true });
+ assert.equal(compact.nextAction.action, 'edit-in-place');
+ assert.equal('stages' in compact, false);
+ assert.ok(JSON.stringify(compact).length < JSON.stringify(receipt).length / 4);
+});
+
+test('finalize refuses a receipt path that aliases a gate sidecar', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const visualReceipt = path.join(directory, 'diagram.browser-check.json');
+ fs.writeFileSync(input, '{}');
+ fs.writeFileSync(visualReceipt, 'preserve me');
+ let invoked = false;
+
+ await assert.rejects(() => runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ receiptPath: visualReceipt,
+ runCommand: () => { invoked = true; return result({ ok: true }); },
+ }), /gate sidecars/);
+ assert.equal(invoked, false);
+ assert.equal(fs.readFileSync(visualReceipt, 'utf8'), 'preserve me');
+});
+
+test('finalize binds a passing validate receipt to the unchanged candidate', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"quality_profile":"showcase"}}';
+ fs.writeFileSync(input, source);
+ const candidateSha256 = createHash('sha256').update(source).digest('hex');
+ const calls = [];
+ const pass = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ candidateSha256,
+ runCommand: ({ stage }) => {
+ calls.push(stage);
+ const delivery = passingDelivery({ input, output, source, artifact: '<!doctype html>' });
+ if (stage === 'deliver') return result(delivery);
+ if (stage === 'check') return result(passingCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId,
+ }));
+ return result(passingBrowserCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory,
+ }));
+ },
+ });
+ assert.equal(pass.exitCode, 0);
+ assert.deepEqual(calls, ['deliver', 'check', 'browser-check']);
+
+ fs.writeFileSync(input, `${source}\n`);
+ await assert.rejects(() => runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output: path.join(directory, 'changed.html'),
+ candidateSha256,
+ runCommand: () => { throw new Error('must not run'); },
+ }), error => {
+ assert.equal(error.finalizeCode, 'finalize/candidate-changed');
+ assert.equal(error.finalizeEvidence.expectedSha256, candidateSha256);
+ return true;
+ });
+});
+
+test('finalize fails closed when a stage exits zero without a valid passing receipt', async t => {
+ const invalidOutputs = [
+ '',
+ 'not json',
+ '{}',
+ '"success"',
+ '{"ok":true,"status":"fail","command":"validate","checks":[]}',
+ ];
+
+ for (const [index, stdout] of invalidOutputs.entries()) {
+ const directory = workspace(t);
+ const input = path.join(directory, `diagram-${index}.json`);
+ const output = path.join(directory, `diagram-${index}.html`);
+ fs.writeFileSync(input, '{}');
+ const calls = [];
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ calls.push(stage);
+ return { status: 0, signal: null, stdout, stderr: '' };
+ },
+ });
+ assert.equal(finalized.exitCode, 1, `invalid receipt ${index} must fail`);
+ assert.deepEqual(calls, ['deliver']);
+ assert.equal(finalized.receipt.failedStage, 'deliver');
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/invalid-stage-receipt');
+ }
+});
+
+test('finalize rejects an interleaved delivery whose check proves another artifact and receipt', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'a.json');
+ const replacement = path.join(directory, 'b.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"A"}}';
+ const replacementSource = '{"meta":{"title":"B"}}';
+ fs.writeFileSync(input, source);
+ fs.writeFileSync(replacement, replacementSource);
+ const calls = [];
+
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ calls.push(stage);
+ if (stage === 'deliver') return result(passingDelivery({
+ input, output, source, artifact: '<!doctype html><title>A</title>', receiptId: '11111111-1111-4111-8111-111111111111',
+ }));
+ const deliveredB = passingDelivery({
+ input: replacement,
+ output,
+ source: replacementSource,
+ artifact: '<!doctype html><title>B</title>',
+ receiptId: '22222222-2222-4222-8222-222222222222',
+ });
+ return result(passingCheck({
+ output,
+ artifact: deliveredB.artifact,
+ deliveryReceiptId: deliveredB.receiptId,
+ }));
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1);
+ assert.deepEqual(calls, ['deliver', 'check']);
+ assert.equal(finalized.receipt.failedStage, 'check');
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/artifact-binding-mismatch');
+ assert.equal(finalized.summary.diagnostics[0].evidence.expectedDeliveryReceiptId, '11111111-1111-4111-8111-111111111111');
+ assert.equal(finalized.summary.diagnostics[0].evidence.actualDeliveryReceiptId, '22222222-2222-4222-8222-222222222222');
+});
+
+test('finalize verifies the artifact and delivery sidecar after browser evidence completes', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"stable"}}';
+ fs.writeFileSync(input, source);
+ let delivery;
+
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ return result(delivery);
+ }
+ if (stage === 'check') return result(passingCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId,
+ }));
+ const browser = passingBrowserCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory,
+ });
+ fs.unlinkSync(output);
+ return result(browser);
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1);
+ assert.equal(finalized.receipt.failedStage, 'finalize');
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/final-artifact-mismatch');
+ assert.deepEqual(finalized.receipt.artifact, { path: output });
+});
+
+test('a successful finalize receipt keeps the delivery identity after its final verification snapshot', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"stable"}}';
+ fs.writeFileSync(input, source);
+ let delivery;
+ let originalRead;
+ let mutated = false;
+
+ try {
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source, artifact: '<!doctype html><title>A</title>' });
+ return result(delivery);
+ }
+ if (stage === 'check') return result(passingCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId,
+ }));
+ const browser = passingBrowserCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory,
+ });
+ originalRead = fs.readFileSync;
+ fs.readFileSync = function interceptedRead(file, ...args) {
+ const contents = originalRead.call(this, file, ...args);
+ if (!mutated && path.resolve(file) === output) {
+ mutated = true;
+ fs.writeFileSync(output, '<!doctype html><title>B</title>');
+ }
+ return contents;
+ };
+ return result(browser);
+ },
+ });
+
+ assert.equal(mutated, true);
+ assert.equal(finalized.exitCode, 0);
+ assert.equal(finalized.receipt.ok, true);
+ assert.deepEqual(finalized.receipt.artifact, { path: output, ...delivery.artifact });
+ assert.notDeepEqual(artifactIdentity(fs.readFileSync(output)), delivery.artifact);
+ } finally {
+ if (originalRead) fs.readFileSync = originalRead;
+ }
+});
+
+test('finalize rejects a delivery sidecar replaced after the browser receipt', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const replacement = path.join(directory, 'replacement.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"stable"}}';
+ const replacementSource = '{"meta":{"title":"replacement"}}';
+ fs.writeFileSync(input, source);
+ fs.writeFileSync(replacement, replacementSource);
+ let delivery;
+
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ return result(delivery);
+ }
+ if (stage === 'check') return result(passingCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId,
+ }));
+ const browser = passingBrowserCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory,
+ });
+ const replacementDelivery = {
+ ...delivery,
+ receiptId: '22222222-2222-4222-8222-222222222222',
+ input: replacement,
+ specification: artifactIdentity(replacementSource),
+ };
+ writeCurrentDelivery(output, replacementDelivery);
+ return result(browser);
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1);
+ assert.equal(finalized.receipt.failedStage, 'finalize');
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/final-artifact-mismatch');
+ assert.equal(finalized.summary.diagnostics[0].evidence.currentDeliveryReceiptId, '22222222-2222-4222-8222-222222222222');
+});
+
+test('finalize rejects a delivery type mismatch before checking a different diagram contract', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"type"}}';
+ fs.writeFileSync(input, source);
+ const calls = [];
+
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ calls.push(stage);
+ return result(passingDelivery({ input, output, source, type: 'workflow' }));
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1);
+ assert.deepEqual(calls, ['deliver']);
+ assert.equal(finalized.receipt.failedStage, 'deliver');
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/delivery-type-mismatch');
+ assert.deepEqual(finalized.summary.diagnostics[0].evidence, {
+ expectedType: 'architecture', actualType: 'workflow',
+ });
+});
+
+test('finalize rejects a final delivery sidecar whose type no longer matches the requested diagram', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"type-sidecar"}}';
+ fs.writeFileSync(input, source);
+ let delivery;
+
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ return result(delivery);
+ }
+ if (stage === 'check') return result(passingCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId,
+ }));
+ writeCurrentDelivery(output, { ...delivery, type: 'workflow' });
+ return result(passingBrowserCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory,
+ }));
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1);
+ assert.equal(finalized.receipt.failedStage, 'finalize');
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/final-artifact-mismatch');
+ assert.equal(finalized.summary.diagnostics[0].evidence.currentType, 'workflow');
+});
+
+test('finalize rejects a showcase delivery whose count does not match the complete artifact checker', async t => {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"incomplete"}}';
+ fs.writeFileSync(input, source);
+ let delivery;
+
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ delivery.validation.checksPassed = 4;
+ delivery.validation.checkCount = 4;
+ return result(delivery);
+ }
+ return result(passingCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, checkCount: 9,
+ }));
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1);
+ assert.equal(finalized.receipt.failedStage, 'check');
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/delivery-validation-mismatch');
+ assert.deepEqual(finalized.summary.diagnostics[0].evidence, {
+ deliveryCheckCount: 4, checkerCheckCount: 9,
+ });
+});
+
+test('finalize requires the canonical check and browser artifact paths without inventing fallbacks', async t => {
+ const cases = [
+ {
+ stage: 'check',
+ receipt: ({ output, delivery }) => {
+ const receipt = passingCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId });
+ delete receipt.file;
+ return receipt;
+ },
+ },
+ {
+ stage: 'browser-check',
+ receipt: ({ output, delivery, directory }) => {
+ const receipt = passingBrowserCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory,
+ });
+ delete receipt.artifact.path;
+ return receipt;
+ },
+ },
+ ];
+
+ for (const scenario of cases) {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"path"}}';
+ fs.writeFileSync(input, source);
+ let delivery;
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ return result(delivery);
+ }
+ if (stage === 'check') {
+ return result(scenario.stage === stage
+ ? scenario.receipt({ output, delivery, directory })
+ : passingCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId }));
+ }
+ return result(scenario.receipt({ output, delivery, directory }));
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1, scenario.stage);
+ assert.equal(finalized.receipt.failedStage, scenario.stage);
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/artifact-binding-mismatch');
+ }
+});
+
+test('finalize requires complete passing browser evidence coverage', async t => {
+ const cases = [
+ {
+ name: 'missing containment viewport',
+ mutate: (receipt) => { receipt.containment.viewports.pop(); },
+ },
+ {
+ name: 'null containment viewport before a valid matching entry',
+ mutate: (receipt) => { receipt.containment.viewports = [null, ...receipt.containment.viewports.slice(0, -1)]; },
+ },
+ {
+ name: 'failed readability child',
+ mutate: (receipt) => { receipt.readability.viewports[0].readabilityOk = false; },
+ },
+ {
+ name: 'non-light containment viewport',
+ mutate: (receipt) => { receipt.containment.viewports[1].theme = 'dark'; },
+ },
+ {
+ name: 'missing viewer chrome viewport',
+ mutate: (receipt) => { receipt.viewerChrome.viewports = []; },
+ },
+ {
+ name: 'incomplete theme coverage',
+ mutate: (receipt) => { receipt.themeStates.viewports.pop(); },
+ },
+ ];
+
+ for (const scenario of cases) {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"browser"}}';
+ fs.writeFileSync(input, source);
+ let delivery;
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ return result(delivery);
+ }
+ if (stage === 'check') return result(passingCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId,
+ }));
+ const browser = passingBrowserCheck({
+ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory,
+ });
+ scenario.mutate(browser);
+ return result(browser);
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1, scenario.name);
+ assert.equal(finalized.receipt.failedStage, 'browser-check', scenario.name);
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/invalid-stage-receipt', scenario.name);
+ }
+});
+
+test('finalize rejects incomplete or mismatched successful protocol receipts', async t => {
+ const cases = [
+ {
+ name: 'standard validation reported for a showcase delivery',
+ stage: 'deliver',
+ receipt: ({ input, output, source }) => {
+ const receipt = passingDelivery({ input, output, source, quality: 'standard' });
+ receipt.validation.checksPassed = 4;
+ receipt.validation.checkCount = 4;
+ return receipt;
+ },
+ },
+ {
+ name: 'empty artifact checker receipt',
+ stage: 'check',
+ receipt: () => ({ ok: true, artifact: {}, checks: [], provenance: 'current' }),
+ },
+ {
+ name: 'artifact checker child failure',
+ stage: 'check',
+ receipt: ({ output, delivery }) => ({
+ ...passingCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId }),
+ checks: [{ name: 'artifact', ok: false }],
+ }),
+ },
+ {
+ name: 'minimal browser receipt',
+ stage: 'browser-check',
+ receipt: () => ({ ok: true, command: 'browser-check', status: 'pass' }),
+ },
+ ];
+
+ for (const scenario of cases) {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{"meta":{"title":"protocol"}}';
+ fs.writeFileSync(input, source);
+ let delivery;
+ const calls = [];
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs',
+ type: 'architecture',
+ input,
+ output,
+ runCommand: ({ stage }) => {
+ calls.push(stage);
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ return result(scenario.stage === stage ? scenario.receipt({ input, output, source, delivery }) : delivery);
+ }
+ if (stage === 'check') {
+ const receipt = scenario.stage === stage
+ ? scenario.receipt({ input, output, source, delivery })
+ : passingCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId });
+ return result(receipt);
+ }
+ return result(scenario.receipt({ input, output, source, delivery }));
+ },
+ });
+
+ assert.equal(finalized.exitCode, 1, scenario.name);
+ assert.equal(finalized.receipt.failedStage, scenario.stage, scenario.name);
+ assert.deepEqual(calls, FINALIZE_STAGES.slice(1, FINALIZE_STAGES.indexOf(scenario.stage) + 1), scenario.name);
+ assert.equal(finalized.summary.diagnostics[0].code, 'finalize/invalid-stage-receipt', scenario.name);
+ }
+});
+
+test('finalize rechecks delivery barriers and the frozen candidate after the browser gate', async t => {
+ for (const scenario of ['pending-delivery', 'changed-candidate']) {
+ const directory = workspace(t);
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ const source = '{}';
+ fs.writeFileSync(input, source);
+ let delivery;
+ const finalized = await runFinalize({
+ cliPath: '/fake/archify.mjs', type: 'architecture', input, output,
+ ...(scenario === 'pending-delivery' ? { inspectDelivery: () => ({
+ ok: false, status: 'pending', diagnostics: [{
+ code: 'delivery/provenance-pending', severity: 'error', message: 'A new delivery is pending.',
+ }],
+ }) } : {}),
+ runCommand: ({ stage }) => {
+ if (stage === 'deliver') {
+ delivery = passingDelivery({ input, output, source });
+ return result(delivery);
+ }
+ if (stage === 'check') return result(passingCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId }));
+ if (scenario === 'changed-candidate') fs.writeFileSync(input, '{"changed":true}');
+ return result(passingBrowserCheck({ output, artifact: delivery.artifact, deliveryReceiptId: delivery.receiptId, outDir: directory }));
+ },
+ });
+ assert.equal(finalized.exitCode, 1, scenario);
+ assert.equal(finalized.summary.failedStage, 'finalize');
+ assert.equal(finalized.summary.ok, false);
+ assert.equal(finalized.summary.diagnostics[0].code, scenario === 'pending-delivery' ? 'delivery/provenance-pending' : 'finalize/candidate-changed');
+ }
+});
diff --git a/archify/test/ordinary-model-floor.test.mjs b/archify/test/ordinary-model-floor.test.mjs
index 162e7c5b..a0788d29 100644
--- a/archify/test/ordinary-model-floor.test.mjs
+++ b/archify/test/ordinary-model-floor.test.mjs
@@ -896,8 +896,11 @@ test('benchmark documentation locks the fair-run and truthful-evidence contract'
test('packaged skill puts a bounded ordinary-model path before progressive feature references', () => {
const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+ const authoringDefaults = fs.readFileSync(path.join(skillRoot, 'references', 'authoring-defaults.md'), 'utf8');
const authoring = fs.readFileSync(path.join(skillRoot, 'references', 'authoring-contract.md'), 'utf8');
const viewer = fs.readFileSync(path.join(skillRoot, 'references', 'viewer-runtime.md'), 'utf8');
+ assert.match(skill, /## Existing candidate handoff[\s\S]*run `finalize` first as one CLI invocation/);
+ assert.match(skill, /After editing, omit any earlier `--candidate-sha256`/);
const fastPath = skill.indexOf('## Fast authoring path');
// A diagnosed repair may link to a reference inside the fast path. Bound
// the contract by its next section, not by the first inline link.
@@ -907,32 +910,48 @@ test('packaged skill puts a bounded ordinary-model path before progressive featu
assert.ok(fastPathEnd > fastPath, 'fast authoring path must precede the type router');
assert.ok(skill.trimEnd().split('\n').length <= 160, 'ordinary authors must not ingest the viewer catalogue');
for (const required of [
- 'one matching schema',
- 'one matching JSON example',
- 'the next tool action must write the candidate',
- 'Do not plan exact coordinates in prose',
- 'Fresh authorship means new stable IDs, domain wording, and layout',
- 'Write the candidate before inspecting renderer internals',
- 'Start with automatic routes and labels',
- 'Do not add `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, or `labelAt` before a diagnostic',
+ 'exact paths in the Type router',
+ 'do not list `schemas/` or `examples/` first',
+ 'once requested scope and source evidence are covered, write the candidate directly',
+ 'do not plan coordinates in prose',
+ 'Fresh authorship means new IDs, domain wording, and layout',
+ 'let the renderer route every connection',
+ 'omit `via`, `route`, `fromSide`, `toSide`, `channelX`, `channelY`, `labelAt`, `labelDx`, `labelDy`, and `labelSegment`',
+ 'Add the smallest control only after a measured diagnostic',
'Set `meta.quality_profile` to `"showcase"`',
- 'A recoverable state uses `type: "failure"` plus a real transition back to the active state',
- 'after every candidate edit',
- 'A passing final validation freezes the candidate: never edit it afterward',
- 'A receipt with only 4 artifact checks is basic validation, never showcase acceptance',
- 'a showcase pass must report all 9 artifact checks with 0 composition errors and 0 warnings',
- 'If the candidate omits or misspells the exact `meta.quality_profile` field',
- '`deliver` is the final acceptance command',
- 'deliver <type> <candidate.json> <output.html> --quality showcase --json',
- 'A non-zero exit can never be described as success',
- 'Do not read `renderers/shared/geometry.mjs`',
- 'validate <type>',
+ 'Once the complete first candidate is written, run `finalize` directly',
+ 'Keep the candidate unchanged while the command runs',
+ 'A passing validation returns `candidateFrozen: true`',
+ 'A receipt with only 4 artifact checks is basic validation',
+ 'require all 9 checks with 0 composition errors and 0 warnings',
+ 'Fix `meta.quality_profile` before geometry',
+ 'finalize <type> <candidate.json> <output.html> --quality showcase --json',
+ 'successful first drafts need no separate pre-validation',
+ 'Do not read its full sidecar or rerun individual commands afterward',
+ 'A non-zero exit is never success',
+ 'Do not read `bin/` implementation',
+ 'not prose coordinate exploration or whole-candidate replacement',
+ 'After the edit, rerun the complete `finalize` command from step 4 once',
]) {
assert.match(
skill.slice(fastPath, fastPathEnd),
new RegExp(required.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i'),
);
}
+ assert.doesNotMatch(skill.slice(fastPath, fastPathEnd), /Then run exactly one `validate/);
+ assert.match(skill.slice(fastPath, fastPathEnd), /references\/authoring-defaults\.md/);
+ assert.match(skill, /real system determine the number of nodes and relationships/i);
+ assert.match(skill, /Never use node, relationship, source-reference, view, card, or boundary counts as an authoring target/i);
+ assert.match(authoringDefaults, /Let the real system determine node and relationship counts/i);
+ assert.match(authoringDefaults, /never target a total reference count/i);
+ for (const instructions of [skill, authoringDefaults]) {
+ assert.doesNotMatch(
+ instructions,
+ /(?:at most|no more than|maximum of|cap(?:ped)? at|limit(?:ed)? to)\s+\d+\s+(?:nodes?|components?|relationships?)/i,
+ 'authoring instructions must not impose a fixed topology quota',
+ );
+ }
+ assert.match(authoringDefaults, /A recoverable state uses `type: "failure"` plus a real transition back to the active state/);
assert.match(authoring, /componentType/);
assert.match(authoring, /clear gap between boxes, not center distance/i);
assert.match(viewer, /Direct Relationship Pin/);
diff --git a/archify/test/sequence-column-fit.test.mjs b/archify/test/sequence-column-fit.test.mjs
index e2eb3388..5a9bbc94 100644
--- a/archify/test/sequence-column-fit.test.mjs
+++ b/archify/test/sequence-column-fit.test.mjs
@@ -128,7 +128,7 @@ test('the sublabel diagnostic reports the width in force, not the historical con
test('the fast authoring path explains when to opt into spread', () => {
const schema = JSON.parse(fs.readFileSync(path.join(skillRoot, 'schemas/sequence.schema.json'), 'utf8'));
const description = schema.properties.meta.properties.column_fit.description;
- const skill = fs.readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+ const skill = fs.readFileSync(path.join(skillRoot, 'references/authoring-defaults.md'), 'utf8');
const rendererReadme = fs.readFileSync(path.join(skillRoot, 'renderers/sequence/README.md'), 'utf8');
assert.match(description, /wide viewBox/);
diff --git a/archify/test/skill-metadata.test.mjs b/archify/test/skill-metadata.test.mjs
index 8b5ab26f..b4b8ada0 100644
--- a/archify/test/skill-metadata.test.mjs
+++ b/archify/test/skill-metadata.test.mjs
@@ -7,6 +7,8 @@ import assert from 'node:assert/strict';
const here = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.join(here, '..');
const skill = readFileSync(path.join(skillRoot, 'SKILL.md'), 'utf8');
+const defaults = readFileSync(path.join(skillRoot, 'references', 'authoring-defaults.md'), 'utf8');
+const updateAwareness = readFileSync(path.join(skillRoot, 'references', 'update-awareness.md'), 'utf8');
const authoringContract = readFileSync(path.join(skillRoot, 'references', 'authoring-contract.md'), 'utf8');
const frontmatter = skill.match(/^---\n([\s\S]*?)\n---/);
@@ -49,25 +51,25 @@ test('main skill stays a bounded authoring router with progressive references',
});
test('update awareness is notification-only and never replaces the requested workflow', () => {
- assert.match(skill, /`scripts\/check-update\.mjs`/);
- assert.match(skill, /`silent`[\s\S]*without mentioning/i);
- assert.match(skill, /`update_available`[\s\S]*compact notice/i);
- assert.match(skill, /information, not permission/i);
- assert.match(skill, /`severity` is `security`[\s\S]*security update[\s\S]*emphasis only, never user autonomy/i);
- assert.match(skill, /continue the user's original task/i);
- assert.match(skill, /installed version unchanged/i);
+ assert.match(skill + updateAwareness, /`scripts\/check-update\.mjs`/);
+ assert.match(skill + updateAwareness, /`silent`[\s\S]*without mentioning/i);
+ assert.match(skill + updateAwareness, /`update_available`[\s\S]*compact notice/i);
+ assert.match(skill + updateAwareness, /information, not permission/i);
+ assert.match(skill + updateAwareness, /`severity` is `security`[\s\S]*security update[\s\S]*emphasis only, never user autonomy/i);
+ assert.match(skill + updateAwareness, /continue the user's original task/i);
+ assert.match(skill + updateAwareness, /installed version unchanged/i);
assert.doesNotMatch(skill, /npx skills update|gh skill update/i);
});
test('language behavior stays within the bounded locale contract', () => {
- assert.match(skill, /one primary authored language/);
- assert.match(skill, /explicit user choice; otherwise follow the request or conversation's dominant language/);
- assert.match(skill, /`meta\.locale` controls only renderer-owned Viewer UI/);
- assert.match(skill, /use `"en"`, `"zh-CN"`, or `"es"`/);
- assert.match(skill, /For every other language, omit `meta\.locale`/);
- assert.match(skill, /fixed Viewer UI and `<html lang>` fall back to English/);
- assert.match(skill, /renderer never translates authored content/i);
- assert.match(skill, /product names.*code identifiers.*protocols.*API paths.*environment names/);
+ assert.match(defaults, /one primary authored language/);
+ assert.match(defaults, /explicit user choice; otherwise follow the request or conversation's dominant language/);
+ assert.match(defaults, /`meta\.locale` controls only renderer-owned Viewer UI/);
+ assert.match(defaults, /use `"en"`, `"zh-CN"`, or `"es"`/);
+ assert.match(defaults, /For every other language, omit `meta\.locale`/);
+ assert.match(defaults, /fixed Viewer UI and `<html lang>` fall back to English/);
+ assert.match(defaults, /renderer never translates authored content/i);
+ assert.match(defaults, /product names.*code identifiers.*protocols.*API paths.*environment names/);
assert.match(authoringContract, /`meta\.locale` controls only renderer-owned reader surfaces/);
assert.match(authoringContract, /outside `en`, `zh-CN`, and `es`/);
assert.match(authoringContract, /artifact is\s+not fully localized/);
@@ -78,7 +80,7 @@ test('language behavior stays within the bounded locale contract', () => {
});
test('skill keeps the title hierarchy compact by default', () => {
- assert.match(skill, /Omit `meta\.subtitle` by default/);
- assert.match(skill, /Never invent a subtitle that restates the title, nodes, or cards/);
+ assert.match(defaults, /Omit `meta\.subtitle` by default/);
+ assert.match(defaults, /Never invent a subtitle that restates the title, nodes, or cards/);
assert.match(authoringContract, /omitted or blank subtitle must not leave an empty visual row/);
});
diff --git a/archify/test/validate-next-action.test.mjs b/archify/test/validate-next-action.test.mjs
new file mode 100644
index 00000000..79040e58
--- /dev/null
+++ b/archify/test/validate-next-action.test.mjs
@@ -0,0 +1,62 @@
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import { createHash } from 'node:crypto';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import test from 'node:test';
+import { fileURLToPath } from 'node:url';
+
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const cli = path.join(skillRoot, 'bin', 'archify.mjs');
+
+test('passing validate emits a frozen candidate and one hash-bound finalize action', t => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-next-action-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const input = path.join(directory, 'diagram.json');
+ const source = fs.readFileSync(path.join(skillRoot, 'examples', 'web-app.architecture.json'));
+ fs.writeFileSync(input, source);
+ const sha256 = createHash('sha256').update(source).digest('hex');
+
+ const result = spawnSync(process.execPath, [
+ cli, 'validate', 'architecture', input,
+ '--repo-root', directory,
+ '--quality', 'showcase',
+ '--json',
+ ], { encoding: 'utf8' });
+
+ assert.equal(result.status, 0, result.stderr || result.stdout);
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(receipt.candidateFrozen, true);
+ assert.deepEqual(receipt.candidate, { path: input, sha256, bytes: source.byteLength });
+ assert.equal(receipt.nextAction.command, 'finalize');
+ assert.deepEqual(receipt.nextAction.arguments, [
+ 'architecture', input, '<output.html>',
+ '--quality', 'showcase',
+ '--repo-root', directory,
+ '--candidate-sha256', sha256,
+ '--json',
+ ]);
+});
+
+test('finalize fails closed before gates when the validated candidate hash changed', t => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-next-action-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ fs.copyFileSync(path.join(skillRoot, 'examples', 'web-app.architecture.json'), input);
+
+ const result = spawnSync(process.execPath, [
+ cli, 'finalize', 'architecture', input, output,
+ '--candidate-sha256', '0'.repeat(64),
+ '--quality', 'showcase',
+ '--json',
+ ], { encoding: 'utf8' });
+
+ assert.equal(result.status, 1, result.stderr || result.stdout);
+ assert.equal(fs.existsSync(output), false);
+ const receipt = JSON.parse(result.stdout);
+ assert.equal(receipt.gates.validate, 'not-run');
+ assert.equal(receipt.diagnostics[0].code, 'finalize/candidate-changed');
+ assert.equal(receipt.diagnostics[0].evidence.expectedSha256, '0'.repeat(64));
+});
diff --git a/archify/test/visual-check.test.mjs b/archify/test/visual-check.test.mjs
index 4802ba4c..c30d9926 100644
--- a/archify/test/visual-check.test.mjs
+++ b/archify/test/visual-check.test.mjs
@@ -18,6 +18,8 @@ import {
findChrome,
persistVisualCheckFailure,
runVisualCheck,
+ runBrowserCheck,
+ browserCheckSidecarPaths,
sidecarPaths,
} from '../bin/visual-check.mjs';
import { sameLocation } from '../renderers/shared/path-semantics.mjs';
@@ -55,6 +57,7 @@ function fakeBrowser({
stageCollisionAt,
stageGapAt,
screenshotFailure,
+ resolvedThemeAt,
} = {}) {
const calls = [];
return {
@@ -81,7 +84,7 @@ function fakeBrowser({
innerHeight: height,
scrollWidth: width + (overflow ? 1 : 0),
scrollHeight: height + (readableScroll ? 240 : 0) + (tall ? 300 : 0),
- resolvedTheme: theme,
+ resolvedTheme: resolvedThemeAt?.({ theme }) ?? theme,
...(tall ? {
pageComposition: {
bodyPaddingPx: 12, headerPx: 40, guidedViewsPx: 60, diagramChromePx: 76,
@@ -3052,3 +3055,49 @@ test('visual-check reports local inspection cleanup failure alongside an evidenc
&& /synthetic inspection cleanup denied/.test(entry.reason)
)), 'the conflict must report the retained local inspection directory');
});
+
+test('browser-check proves rendered behavior without creating screenshots or requiring perceptual review', async () => {
+ const input = artifact('browser-check-passing.html');
+ const browser = fakeBrowser();
+ const result = await runBrowserCheck({
+ artifactPath: input,
+ chromePath: '/fake/chrome',
+ browserFactory: async () => browser,
+ });
+
+ assert.equal(result.exitCode, 0);
+ assert.equal(result.receipt.command, 'browser-check');
+ assert.equal(result.receipt.status, 'pass');
+ assert.equal(result.receipt.visualReview, 'not-requested');
+ assert.equal(result.receipt.themeStates.status, 'pass');
+ assert.equal(result.receipt.themeStates.viewports.length, 4);
+ assert.equal(result.receipt.captures.status, 'not-requested');
+ assert.deepEqual(result.receipt.captures.screenshots, []);
+ assert.equal(result.receipt.captures.contactSheet, null);
+ assert.equal(browser.calls.length, VISUAL_CHECK_VIEWPORTS.length + 2);
+ assert.equal(browser.calls.every(({ screenshotPath }) => screenshotPath === undefined), true);
+
+ const outputs = browserCheckSidecarPaths(input);
+ assert.equal(fs.existsSync(outputs.receipt), true);
+ assert.equal(fs.existsSync(outputs.contactSheet), false);
+ assert.equal(outputs.screenshots.every(({ path: screenshot }) => !fs.existsSync(screenshot)), true);
+});
+
+test('browser-check fails when an endpoint theme does not resolve without needing image inspection', async () => {
+ const input = artifact('browser-check-theme-mismatch.html');
+ const browser = fakeBrowser({
+ resolvedThemeAt: ({ theme }) => theme === 'dark' ? 'light' : theme,
+ });
+ const result = await runBrowserCheck({
+ artifactPath: input,
+ chromePath: '/fake/chrome',
+ browserFactory: async () => browser,
+ });
+
+ assert.equal(result.exitCode, 1);
+ assert.equal(result.receipt.status, 'fail');
+ assert.equal(result.receipt.themeStates.status, 'fail');
+ assert.equal(result.receipt.themeStates.viewports.filter(({ ok }) => !ok).length, 2);
+ assert.equal(result.receipt.diagnostics.filter(({ code }) => code === 'viewer/theme-state').length, 2);
+ assert.equal(result.receipt.captures.status, 'not-requested');
+});
diff --git a/scripts/run-browser-tests.mjs b/scripts/run-browser-tests.mjs
index 6277f498..96f1f4ef 100644
--- a/scripts/run-browser-tests.mjs
+++ b/scripts/run-browser-tests.mjs
@@ -8,6 +8,7 @@ import { findChrome } from '../archify/bin/visual-check.mjs';
const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');
// Shared by PR CI and tag releases. WebM decoding stays in test:webm.
const testFiles = [
+ 'finalize-browser.test.mjs',
'desktop-reader-browser.test.mjs',
'reader-readability-maintained-browser.test.mjs',
'reader-layout-browser.test.mjs',