Skip to content

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

fix: preserve authored layouts and make tuning evidence reliable

tt-a1i0eaa2f513c8f
diff --git a/.agents/skills/archify-tuning/SKILL.md b/.agents/skills/archify-tuning/SKILL.md
index 9cbef7ee..94b2d2ab 100644
--- a/.agents/skills/archify-tuning/SKILL.md
+++ b/.agents/skills/archify-tuning/SKILL.md
@@ -19,7 +19,7 @@ A change that makes gates pass while the diagram reads worse, or that makes agen
- **The first draft is the unit of measure.** Bundled examples carry hand-tuned widths and routes, so they hide defects that every fresh draft hits.
- **Deleted content is the accuracy signal.** A pass reached by removing an error state or merging lanes is a failure that looks like a success.
-- **Automatic layout must pass its own gates.** When a fully automatic draft (no `via`, sides, channels or label coordinates) fails composition checks, the renderer is at fault, not the agent.
+- **Separate route controls from placement.** A draft without route controls can still have authored positions, dimensions or a fixed canvas. Reproduce a failure with valid placement and constraints before attributing it to automatic layout.
- **Early diagnostics must match the browser gate.** A compile-time check stricter than `browser-check` is a false failure; a looser one defers the failure to the most expensive stage.
- **Traces explain more than outcomes.** Read where a diagnostic or document misled the agent, not only whether it passed.
@@ -27,34 +27,34 @@ A change that makes gates pass while the diagram reads worse, or that makes agen
| Level | Measure | Source |
|---|---|---|
-| Primary | Benchmark first-draft pass rate, per type | `replay.mjs` |
-| Primary | Content kept from first draft to final | `collect.mjs`, "lost" column |
+| Primary | Benchmark first-draft render pass rate, per type | `replay.mjs`; excludes finalize and browser gates |
+| Primary | Content changes from first draft to final | `collect.mjs`, "lost" column, then semantic comparison |
| Secondary | Finalize failures and tool calls per diagram | `collect.mjs` on a new round |
| Visual | Crossings, bends, shared corridors and text size, then screenshots | Receipts, `shots.mjs` |
| Guard | No benchmark draft that passed on base fails on head; every changed output inspected | `replay.mjs`, golden, Gallery |
-A new round on a new project finds problems and shows a change broke nothing. It does not prove improvement, because projects differ too much: prove improvement on the benchmark, or by repeating one project two or three times.
+A round on a new project discovers problems; it does not establish improvement or absence of regressions. Compare fixed inputs for renderer changes. Evaluate authoring-instruction changes with comparable new generations on the same project, preserving first attempts, repairs and failures.
## Setup
- **Tuning home**: `$ARCHIFY_TUNING_HOME`, default `~/.local/share/archify-tuning`. It holds `journal.md`, `bench/`, `rounds/` and `replays/`. It stays outside the repository because drafts carry content from source projects, which may be private: never commit it.
- **Journal**: read `<tuning-home>/journal.md` before starting. It records the branch under tuning, the latest benchmark result, the open problems with evidence and the decisions already taken. Update it at the end of every iteration.
-- **Head**: the worktree you change, in a durable directory. Run `npm ci` there so the full test suite can run.
+- **Head**: the worktree you change, in a durable directory. Follow [Local setup and verification](../../../CONTRIBUTING.md#local-setup-and-verification) for dependencies and test selection.
- **Base**: a separate worktree of the comparison point, usually `dev`: `git worktree add <dir> origin/dev`. Pass its `archify` directory as `--base`.
-- **Tools**: Node 22.13 or later (`collect.mjs` uses `node:sqlite` on Devin CLI session history; other agents need their own trace export) and Chrome or Chromium for `shots.mjs` (`ARCHIFY_CHROME` overrides discovery).
+- **Tools**: Node 22.13 or later and Chrome or Chromium for `shots.mjs` (`ARCHIFY_CHROME` overrides discovery). The collector accepts Devin CLI history or a [normalized trace export](references/trace-export.md) from another agent. It does not read other agents' private history databases.
-Scripts live in `.agents/skills/archify-tuning/scripts/`. `round`, `collect` and `replay` print their usage when run without arguments; `shots` uses the latest replay.
+Run the commands below from the repository root. `round`, `collect` and `replay` print their usage when run without arguments; pass an explicit replay directory to `shots` when retaining an acceptance receipt.
## Loop
-1. **Baseline.** `node scripts/replay.mjs --base <base>/archify` and record the per-type pass rate in the journal.
-2. **Generate.** Pick a project not used before (see the journal). `node scripts/round.mjs <project-path> [--types ...]` creates `<tuning-home>/rounds/<round>/` and `prompts.json`. Start each prompt as its own background subagent, unchanged. The Archify tree they use must stay untouched until every subagent finishes: experiment in a separate worktree meanwhile.
-3. **Collect.** `node scripts/collect.mjs <round> --dump` prints, per type, tool calls, finalize runs and failures, whether the first draft was fully automatic (`draft`), what the final candidate dropped (`lost`) and the diagnostic codes. It writes `<type>.trace.txt` and `<type>/first-draft.json`, and adds each first draft to the benchmark. Cross-check its counts with the subagents' reports.
+1. **Baseline.** `node .agents/skills/archify-tuning/scripts/replay.mjs --base <base>/archify` and record the per-type render pass rate and revision receipt in the journal.
+2. **Generate.** Pick a project not used before (see the journal). `node .agents/skills/archify-tuning/scripts/round.mjs <project-path> [--types ...]` creates `<tuning-home>/rounds/<round>/` and `prompts.json`. Start each prompt as its own background subagent, unchanged. The Archify tree they use must stay untouched until every subagent finishes: experiment in a separate worktree meanwhile.
+3. **Collect.** `node .agents/skills/archify-tuning/scripts/collect.mjs <round> --dump` reads Devin history; add `--trace-export <file.json>` for another agent's normalized export. It records tool calls, finalize outcomes, authored route controls, content-change signals and diagnostic codes; it also retains traces and first drafts. Cross-check counts with the subagents' reports. Compare labels, conditions, sources and meaning manually: a zero loss count is not proof of semantic preservation.
4. **Attribute** every failure to exactly one cause, using [Trace signals](references/trace-signals.md):
| Cause | Test | Response |
|---|---|---|
- | Renderer defect | A fully automatic draft fails its own composition checks | Fix the renderer |
+ | Renderer defect | Valid placement and authored constraints reproduce an automatic layout failure | Fix the renderer |
| Misleading diagnostic | Following the message fails or edits the wrong element | Fix its fix text or evidence |
| Documentation gap | The agent needs a fact found only outside the required reads | Move the fact into a required read, with numbers |
| Authoring error | The required reads already say it | Nothing, or one sentence |
@@ -63,8 +63,8 @@ Scripts live in `.agents/skills/archify-tuning/scripts/`. `round`, `collect` and
6. **Fix** the root cause once, in the shared path. Preserve authored geometry and pins; when the renderer cannot repair a draft itself, return a verified, actionable fix. Reject a change that only moves a metric, such as trading crossings for shared corridors.
7. **Verify.**
- Add a minimal test that fails before the fix.
- - Replay: `node scripts/replay.mjs --base <base>/archify`. Any REGRESSED entry blocks the change; investigate every FIXED and changed entry.
- - `node scripts/shots.mjs` and look at every pair it captures.
+ - Replay: `node .agents/skills/archify-tuning/scripts/replay.mjs --base <base>/archify`. Any REGRESSED entry blocks the change; investigate every FIXED and changed entry. A render pass does not replace finalization or browser acceptance.
+ - Run `node .agents/skills/archify-tuning/scripts/shots.mjs <replay-dir>` and inspect every changed output. Treat capture failures as missing evidence; compare identical inputs, viewport, theme and page state. Use `--all` for a broader visual pass.
- Find affected tests by searching for the changed functions and message text, not by file name, and run them. Regenerate examples and Gallery when output changes, then run golden.
8. **Record.** Commit code, regenerated outputs and documentation separately. Update the journal: benchmark result, problems closed and opened, approaches rejected. Integrate regularly through [CONTRIBUTING.md](../../../CONTRIBUTING.md) so the full suite and CI run. This skill does not authorise pushing, opening pull requests or installing Archify.
diff --git a/.agents/skills/archify-tuning/references/trace-export.md b/.agents/skills/archify-tuning/references/trace-export.md
new file mode 100644
index 00000000..7d00627f
--- /dev/null
+++ b/.agents/skills/archify-tuning/references/trace-export.md
@@ -0,0 +1,38 @@
+# Trace export
+
+Use this input when generation ran outside Devin CLI. Export the relevant sessions with the host's supported tools, then normalize tool names and arguments to the format below. Keep the export in the external tuning home; it can contain source-project content. The collector does not discover or parse another agent's private database.
+
+```sh
+node .agents/skills/archify-tuning/scripts/collect.mjs <round> --trace-export <trace.json> --dump
+```
+
+The JSON object has `schemaVersion: 1` and a `sessions` array. Each session has an `id` and chronological `messages`. Its user task must name the absolute `<round>/<diagram-type>` directory created by `round.mjs`, so collection can associate the session with one diagram.
+
+```json
+{
+ "schemaVersion": 1,
+ "sessions": [{
+ "id": "workflow-run-1",
+ "messages": [
+ { "role": "user", "content": "Create the diagram in /absolute/round/workflow" },
+ {
+ "role": "assistant",
+ "content": "Write the first candidate.",
+ "tool_calls": [{
+ "id": "write-1",
+ "name": "write",
+ "arguments": {
+ "file_path": "/absolute/round/workflow/.archify/example/candidate.json",
+ "content": "{\"diagram_type\":\"workflow\"}"
+ }
+ }]
+ },
+ { "role": "tool", "tool_call_id": "write-1", "content": "Written" }
+ ]
+ }]
+}
+```
+
+The shortened candidate above illustrates encoding only; retain the full actual candidate in an export. Normalize `read` to `{ "file_path": "..." }`, `write` to `{ "file_path": "...", "content": "..." }`, and `exec` to `{ "command": "..." }`. Tool results are strings linked by `tool_call_id`. Preserve command output, including nonzero failures and unknown outcomes. A first draft created through a patch or shell command needs a corresponding normalized `write` event containing its actual first JSON, not the final repaired version.
+
+Keep final candidates in the round directories specified by the prompts. Missing drafts, results or final files are missing evidence; never fabricate events or replace them with successful summaries. Content-change counts flag items to inspect and do not establish factual or semantic equivalence.
diff --git a/.agents/skills/archify-tuning/references/trace-signals.md b/.agents/skills/archify-tuning/references/trace-signals.md
index 00c58f0a..7a90dd03 100644
--- a/.agents/skills/archify-tuning/references/trace-signals.md
+++ b/.agents/skills/archify-tuning/references/trace-signals.md
@@ -5,7 +5,7 @@ Read `<round>/<type>.trace.txt` with the subagent's own report. Each signal belo
| Signal in the trace | Likely cause | Check |
|---|---|---|
| The final candidate dropped nodes, edges or lanes the first draft had | The agent bought a pass with content | `collect.mjs` "lost" column, then compare the drafts. Highest priority |
-| A fully automatic draft (`draft: auto`) fails crossing, corridor, through-node or label checks | Renderer defect | Render the first draft at `--quality standard` and look at the routes |
+| A draft without route controls fails crossing, corridor, through-node or label checks | Possible layout defect or authored placement constraint | Inspect node placement, dimensions and canvas first; render a scratch copy at `standard` to inspect routes, keeping the original failure |
| A crossing or corridor failure, then side pins, then `explicit-pin-conflict`, then a restructure | The router has no legal route the agent can request | Same as above; the hint that suggested pins is also wrong |
| The same code survives a focused repair | The fix text names a change that cannot help | Apply the advertised fix to the draft and rerun |
| Width or gap values oscillate across runs, such as `gapX` 64, 108, 72 | The diagnostic omits the target value | Make it state the required width, gap or character budget |
@@ -20,7 +20,7 @@ Read `<round>/<type>.trace.txt` with the subagent's own report. Each signal belo
Use these as patterns; each was confirmed by replaying the first draft.
-- Workflow same-lane neighbours were placed 8px apart, so no route could pass between columns. Fully automatic drafts failed on crossings and shared corridors, and agents removed lanes and nodes. Neighbours now keep a 32px corridor and routes may take offset tracks.
+- Workflow same-lane neighbours were placed 8px apart, leaving little route space. Automatic drafts failed on crossings and shared corridors, and agents removed lanes and nodes. Unpinned drafts now use a 32px corridor and may take offset tracks; absolute route pins retain their existing geometry contract.
- Dataflow flows across several stages turned at their midpoint, inside a middle stage's node. Agents deleted nodes. They now turn in the nearest clear gap.
- Dataflow ignored perpendicular pinned sides, so agents hand-wrote `via` points.
- Sequence canvases stayed 920px wide whatever the participant labels needed, and the message suggested widening `viewBox`, which the readability budget forbids.
diff --git a/.agents/skills/archify-tuning/scripts/collect.mjs b/.agents/skills/archify-tuning/scripts/collect.mjs
index 6b36b0ff..a717a478 100644
--- a/.agents/skills/archify-tuning/scripts/collect.mjs
+++ b/.agents/skills/archify-tuning/scripts/collect.mjs
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-// Usage: node collect.mjs <round-name-or-path> [--round <name>] [--no-bench] [--dump]
+// Usage: node collect.mjs <round-name-or-path> [--round <name>] [--no-bench] [--dump] [--trace-export <file>]
//
// Reads Devin CLI session history for subagents whose task pointed at
// <round>/<type>, then reports per type: tool calls, finalize runs and
@@ -7,7 +7,6 @@
// the elements and relationships the final candidate dropped from it. Each
// first draft is kept as <round>/<type>/first-draft.json and added to the
// benchmark (repository evidence stripped) unless --no-bench.
-import { DatabaseSync } from 'node:sqlite';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -21,25 +20,37 @@ const option = (name, fallback) => {
const target = args.find((arg, index) => !arg.startsWith('--') && !args[index - 1]?.startsWith('--')) || '';
const root = fs.existsSync(path.resolve(target)) ? path.resolve(target) : path.join(tuningHome(), 'rounds', target);
if (!target || !fs.existsSync(root)) {
- console.error('Usage: node collect.mjs <round-name-or-path> [--round <name>] [--no-bench] [--dump]');
+ console.error('Usage: node collect.mjs <round-name-or-path> [--round <name>] [--no-bench] [--dump] [--trace-export <file>]');
process.exit(2);
}
const recorded = fs.existsSync(path.join(root, 'round.json')) ? JSON.parse(fs.readFileSync(path.join(root, 'round.json'), 'utf8')) : {};
const round = option('--round', recorded.name || path.basename(root));
const bench = path.join(tuningHome(), 'bench');
const database = path.join(os.homedir(), '.local/share/devin/cli/sessions.db');
-const db = new DatabaseSync(database, { readOnly: true });
+let db;
+const traceExport = option('--trace-export');
+if (!traceExport) {
+ const { DatabaseSync } = await import('node:sqlite');
+ db = new DatabaseSync(database, { readOnly: true });
+}
const text = (value) => (typeof value === 'string' ? value : JSON.stringify(value ?? ''));
const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// Task text may name the macOS /private alias or the plain /tmp path.
-const roots = [...new Set([root, root.replace(/^\/private\//, '/'), root.replace(/^\/tmp\//, '/private/tmp/')])];
+const logicalPath = (value) => value.replace(/\\/g, '/');
+const roots = [...new Set([root, root.replace(/^\/private\//, '/'), root.replace(/^\/tmp\//, '/private/tmp/')].map(logicalPath))];
+const taskMatches = (type, content) => new RegExp(`(?:${roots.map(escape).join('|')})/${type}(?![\\w-])`).test(logicalPath(content));
const CODE = /\b((?:layout|composition|clean-flow|workflow|sequence|dataflow|lifecycle|erd|class|tree|timeline|waterfall|architecture|repository-evidence|schema|viewer|delivery)\/[a-z0-9]+(?:-[a-z0-9]+)*)\b/g;
-function chainsByType() {
- const like = roots.map(() => 'chat_message like ?').join(' or ');
+function devinChainsByType() {
+ // Serialized JSON doubles native backslashes; cover native and POSIX spellings.
+ const serializedRoots = [...new Set(roots.flatMap((candidate) => [
+ JSON.stringify(`${candidate}/`).slice(1, -1),
+ JSON.stringify(`${candidate.replace(/\//g, '\\')}\\`).slice(1, -1),
+ ]))];
+ const like = serializedRoots.map(() => 'chat_message like ?').join(' or ');
const hits = db.prepare(`select session_id, min(node_id) as first from message_nodes where ${like} group by session_id`)
- .all(...roots.map((candidate) => `%${candidate}/%`));
+ .all(...serializedRoots.map((candidate) => `%${candidate}%`));
const best = new Map();
for (const { session_id: session, first } of hits) {
const rows = db.prepare('select node_id, parent_node_id, chat_message from message_nodes where session_id = ? and node_id >= ?').all(session, first);
@@ -50,8 +61,7 @@ function chainsByType() {
const chain = [];
for (let current = node; current; current = nodes.get(current.parent_node_id)) chain.unshift(current);
for (const type of DIAGRAM_TYPES) {
- const pattern = new RegExp(`(?:${roots.map(escape).join('|')})/${type}(?![\\w-])`);
- const start = chain.findIndex(({ message }) => message.role === 'user' && typeof message.content === 'string' && pattern.test(message.content));
+ const start = chain.findIndex(({ message }) => message.role === 'user' && typeof message.content === 'string' && taskMatches(type, message.content));
if (start === -1) continue;
const own = chain.slice(start);
if (!best.has(type) || best.get(type).length < own.length) best.set(type, own);
@@ -61,6 +71,53 @@ function chainsByType() {
return best;
}
+// Agent-neutral chronological messages. Host exporters normalize tool names and
+// arguments to read(file_path), write(file_path, content), exec(command).
+function exportedChainsByType(file) {
+ const exported = JSON.parse(fs.readFileSync(file, 'utf8'));
+ if (exported.schemaVersion !== 1 || !Array.isArray(exported.sessions)) throw new Error('Trace export requires schemaVersion: 1 and sessions[]');
+ const best = new Map();
+ for (const session of exported.sessions) {
+ if (typeof session.id !== 'string' || !Array.isArray(session.messages)) throw new Error('Trace session requires id and messages[]');
+ const callIds = new Set();
+ const resultIds = new Set();
+ for (const message of session.messages) {
+ if (!['user', 'assistant', 'tool'].includes(message.role) || typeof message.content !== 'string') throw new Error('Trace messages require a supported role and string content');
+ if (message.role === 'tool') {
+ if (typeof message.tool_call_id !== 'string' || !callIds.has(message.tool_call_id) || resultIds.has(message.tool_call_id)) throw new Error('Trace tool result must reference one earlier tool call');
+ resultIds.add(message.tool_call_id);
+ }
+ if (message.tool_calls !== undefined && (message.role !== 'assistant' || !Array.isArray(message.tool_calls))) throw new Error('Trace tool_calls must be an assistant array');
+ for (const call of message.tool_calls || []) {
+ if (typeof call.id !== 'string' || !call.id || callIds.has(call.id) || typeof call.name !== 'string' || !call.arguments || typeof call.arguments !== 'object' || Array.isArray(call.arguments)) throw new Error('Invalid trace tool call');
+ if (['read', 'write'].includes(call.name) && typeof call.arguments.file_path !== 'string') throw new Error('Trace read/write requires file_path');
+ if (call.name === 'write' && typeof call.arguments.content !== 'string') throw new Error('Trace write requires content');
+ if (call.name === 'exec' && typeof call.arguments.command !== 'string') throw new Error('Trace exec requires command');
+ callIds.add(call.id);
+ }
+ }
+ for (const type of DIAGRAM_TYPES) {
+ const start = session.messages.findIndex((message) => message.role === 'user' && taskMatches(type, message.content));
+ if (start === -1) continue;
+ const own = session.messages.slice(start).map((message) => ({ message }));
+ if (!best.has(type) || best.get(type).length < own.length) best.set(type, own);
+ }
+ }
+ return best;
+}
+
+// Recognize the positional finalize invocation, with ordinary single/double
+// quoted paths. This is trace classification, not shell parsing or execution.
+function isFinalizeCommand(type, command) {
+ const tokens = (command.match(/"[^"]*"|'[^']*'|[^\s]+/g) || []).map((token) => {
+ const quote = token[0];
+ return (quote === '"' || quote === "'") && token.at(-1) === quote ? token.slice(1, -1) : token;
+ });
+ return tokens.some((token, index) => /(?:^|\/)archify\.mjs$/.test(logicalPath(token))
+ && tokens[index + 1] === 'finalize' && tokens[index + 2] === type
+ && /\.json$/.test(tokens[index + 3] || ''));
+}
+
function latestCandidate(type) {
const folder = path.join(root, type, '.archify');
if (!fs.existsSync(folder)) return null;
@@ -73,7 +130,11 @@ function latestCandidate(type) {
const summary = {};
const index = fs.existsSync(path.join(bench, 'index.json')) ? JSON.parse(fs.readFileSync(path.join(bench, 'index.json'), 'utf8')) : {};
-for (const [type, chain] of [...chainsByType()].sort(([a], [b]) => DIAGRAM_TYPES.indexOf(a) - DIAGRAM_TYPES.indexOf(b))) {
+let chains;
+try { chains = traceExport ? exportedChainsByType(traceExport) : devinChainsByType(); }
+catch (error) { console.error(`Cannot collect traces: ${error.message}`); process.exit(2); }
+if (!chains.size) { console.error('No trace sessions matched the round/type paths; no evidence was collected.'); process.exit(2); }
+for (const [type, chain] of [...chains].sort(([a], [b]) => DIAGRAM_TYPES.indexOf(a) - DIAGRAM_TYPES.indexOf(b))) {
const results = new Map();
for (const { message } of chain) if (message.role === 'tool') results.set(message.tool_call_id, text(message.content));
const stats = { tools: 0, reads: 0, docReads: [], finalize: [], firstDraft: null, dump: [] };
@@ -86,12 +147,13 @@ for (const [type, chain] of [...chainsByType()].sort(([a], [b]) => DIAGRAM_TYPES
stats.dump.push(`CALL ${call.name}: ${text(input).slice(0, 3000)}\nRESULT: ${result.slice(0, 4000)}`);
if (call.name === 'read') {
stats.reads += 1;
- if (/\/archify\/.*\.md$/.test(input.file_path || '')) stats.docReads.push(input.file_path.replace(/^.*\/archify\//, ''));
+ const file = logicalPath(input.file_path || '');
+ if (/\/archify\/.*\.md$/.test(file)) stats.docReads.push(file.replace(/^.*\/archify\//, ''));
}
- if (call.name === 'write' && !stats.firstDraft && /candidate[^/]*\.json$/.test(input.file_path || '')) {
+ if (call.name === 'write' && !stats.firstDraft && /candidate[^/]*\.json$/.test(logicalPath(input.file_path || ''))) {
try { stats.firstDraft = JSON.parse(input.content); } catch { /* not JSON yet */ }
}
- if (call.name === 'exec' && new RegExp(`archify\\.mjs\\s+finalize\\s+${type}\\s+\\S+\\.json`).test(input.command || '')) {
+ if (call.name === 'exec' && isFinalizeCommand(type, input.command || '')) {
stats.finalize.push({ status: finalizeStatus(result), codes: [...new Set([...result.matchAll(CODE)].map((match) => match[1]))] });
}
}
@@ -107,6 +169,7 @@ for (const [type, chain] of [...chainsByType()].sort(([a], [b]) => DIAGRAM_TYPES
firstFinalize: stats.finalize[0]?.status ?? 'not-run',
codes: [...new Set(stats.finalize.flatMap(({ codes }) => codes))],
controls: stats.firstDraft ? authoredControls(type, stats.firstDraft) : null,
+ routingMode: !stats.firstDraft ? 'unknown' : Object.keys(authoredControls(type, stats.firstDraft)).length ? 'authored-routes' : 'automatic-routes',
lost,
docReads: stats.docReads,
};
@@ -127,15 +190,16 @@ if (!args.includes('--no-bench') && Object.keys(index).length) {
fs.mkdirSync(bench, { recursive: true });
fs.writeFileSync(path.join(bench, 'index.json'), `${JSON.stringify(index, null, 2)}\n`);
}
+db?.close();
fs.writeFileSync(path.join(root, 'tuning-summary.json'), `${JSON.stringify(summary, null, 2)}\n`);
const pad = (value, width) => String(value).padEnd(width);
-console.log(`${pad('type', 13)}${pad('tools', 7)}${pad('finalize', 10)}${pad('failed', 8)}${pad('first', 9)}${pad('draft', 8)}lost (elements/relations) codes`);
+console.log(`${pad('type', 13)}${pad('tools', 7)}${pad('finalize', 10)}${pad('failed', 8)}${pad('first', 9)}${pad('routes', 18)}lost (elements/relations/containers/membership) codes`);
for (const [type, entry] of Object.entries(summary)) {
- const lost = entry.lost ? `${entry.lost.elements.length}/${entry.lost.relations.length}${entry.lost.elements.length ? ` ${entry.lost.elements.join(',')}` : ''}` : 'n/a';
+ const lost = entry.lost ? `${entry.lost.elements.length}/${entry.lost.relations.length}/${entry.lost.containers.length}/${entry.lost.membershipChanges.length}` : 'n/a';
const failed = `${entry.finalizeFailures}${entry.finalizeUnknown ? `+${entry.finalizeUnknown}?` : ''}`;
- const draft = !entry.controls ? 'n/a' : Object.keys(entry.controls).length ? 'pinned' : 'auto';
- console.log(`${pad(type, 13)}${pad(entry.tools, 7)}${pad(entry.finalizeRuns, 10)}${pad(failed, 8)}${pad(entry.firstFinalize, 9)}${pad(draft, 8)}${pad(lost, 27)}${entry.codes.join(',')}`);
+ const draft = entry.routingMode;
+ console.log(`${pad(type, 13)}${pad(entry.tools, 7)}${pad(entry.finalizeRuns, 10)}${pad(failed, 8)}${pad(entry.firstFinalize, 9)}${pad(draft, 18)}${pad(lost, 46)}${entry.codes.join(',')}`);
}
const entries = Object.values(summary);
console.log(`TOTAL tools ${entries.reduce((sum, entry) => sum + entry.tools, 0)}, finalize ${entries.reduce((sum, entry) => sum + entry.finalizeRuns, 0)}, failed ${entries.reduce((sum, entry) => sum + entry.finalizeFailures, 0)}, first-run passes ${entries.filter((entry) => entry.firstFinalize === 'pass').length}/${entries.length}`);
diff --git a/.agents/skills/archify-tuning/scripts/lib.mjs b/.agents/skills/archify-tuning/scripts/lib.mjs
index 8315388f..4a29fda1 100644
--- a/.agents/skills/archify-tuning/scripts/lib.mjs
+++ b/.agents/skills/archify-tuning/scripts/lib.mjs
@@ -2,6 +2,7 @@
// tuning home that keeps rounds and the benchmark outside the repository.
import os from 'node:os';
import path from 'node:path';
+import crypto from 'node:crypto';
export const DIAGRAM_TYPES = ['architecture', 'workflow', 'sequence', 'dataflow', 'lifecycle', 'erd', 'class', 'tree', 'timeline', 'waterfall'];
@@ -34,23 +35,74 @@ const ROUTE_CONTROLS = ['via', 'route', 'fromSide', 'toSide', 'channelX', 'chann
const list = (value) => (Array.isArray(value) ? value : []);
const relationKey = (relation) => relation.id || `${relation.from}>${relation.to}>${relation.label || ''}`;
-// Elements and relationships of `first` missing from `final`, by id. A renamed
-// id also counts, so treat the result as a prompt to compare, not a verdict.
+// Compare semantic identities, endpoints and container membership, not layout.
+// Renaming is reported too: this is a review signal, not an accuracy verdict.
+function relations(type, document, shape) {
+ if (type === 'tree' || type === 'waterfall') {
+ return list(document[shape.elements]).filter((element) => element.parent !== undefined)
+ .map((element) => ({ from: element.parent, to: element.id }));
+ }
+ return list(document[shape.relations]);
+}
+const relationIdentity = (relation) => JSON.stringify([relationKey(relation), relation.from, relation.to, relation.label || '']);
+
+function containers(type, document) {
+ const result = new Map();
+ const add = (key, members) => result.set(key, new Set(members));
+ if (type === 'architecture') {
+ for (const boundary of list(document.boundaries)) add(`boundary:${boundary.kind}:${boundary.label}`, list(boundary.wraps));
+ }
+ if (type === 'workflow' || type === 'timeline') {
+ const elements = list(document[SHAPE[type].elements]);
+ for (const lane of list(document.lanes)) add(`lane:${lane.id}`, elements.filter((element) => element.lane === lane.id).map((element) => element.id));
+ if (type === 'workflow') {
+ for (const group of list(document.groups)) add(`group:${group.id}`, elements.filter((element) => element.lane === group.lane && element.col >= group.fromCol && element.col <= group.toCol).map((element) => element.id));
+ for (const phase of list(document.phases)) add(`phase:${phase.id}`, elements.filter((element) => element.col >= phase.fromCol && element.col <= phase.toCol).map((element) => element.id));
+ }
+ }
+ if (type === 'dataflow') list(document.stages).forEach((stage, index) => add(`stage:${stage.label}`, list(document.nodes).filter((node) => node.stage === index).map((node) => node.id)));
+ if (type === 'erd') {
+ const entities = list(document.entities);
+ for (const tag of new Set(entities.map((entity) => entity.tag).filter(Boolean))) add(`domain:${tag}`, entities.filter((entity) => entity.tag === tag).map((entity) => entity.id));
+ }
+ return result;
+}
+
export function contentLost(type, first, final) {
const shape = SHAPE[type];
if (!shape || !first || !final) return null;
const finalElements = new Set(list(final[shape.elements]).map((element) => element.id));
- const finalRelations = new Set(list(final[shape.relations]).map(relationKey));
+ const firstRelations = relations(type, first, shape);
+ const finalRelations = relations(type, final, shape);
+ const remaining = new Map();
+ for (const relation of finalRelations) {
+ const key = relationIdentity(relation);
+ remaining.set(key, (remaining.get(key) || 0) + 1);
+ }
+ const missing = [];
+ for (const relation of firstRelations) {
+ const key = relationIdentity(relation);
+ if (remaining.get(key)) remaining.set(key, remaining.get(key) - 1);
+ else missing.push(relationKey(relation));
+ }
+ const before = containers(type, first);
+ const after = containers(type, final);
+ const membershipChanges = [];
+ for (const [container, members] of before) {
+ if (!after.has(container)) continue;
+ for (const element of members) if (finalElements.has(element) && !after.get(container).has(element)) membershipChanges.push({ container, element });
+ }
return {
elements: list(first[shape.elements]).map((element) => element.id).filter((id) => !finalElements.has(id)),
- relations: shape.relations ? list(first[shape.relations]).map(relationKey).filter((key) => !finalRelations.has(key)) : [],
- firstCounts: [list(first[shape.elements]).length, list(first[shape.relations]).length],
- finalCounts: [list(final[shape.elements]).length, list(final[shape.relations]).length],
+ relations: missing,
+ containers: [...before.keys()].filter((key) => !after.has(key)),
+ membershipChanges,
+ firstCounts: [list(first[shape.elements]).length, firstRelations.length],
+ finalCounts: [list(final[shape.elements]).length, finalRelations.length],
};
}
-// Count of authored routing controls, per field. Zero means the draft is
-// fully automatic, so a composition failure on it is the renderer's.
+// Zero means automatic routes; node positions, sizing and grouping remain authored.
export function authoredControls(type, document) {
const relations = SHAPE[type]?.relations;
const counts = {};
@@ -89,3 +141,24 @@ export function finalizeStatus(result) {
const exit = result.match(/Exit code: (\d+)/);
return exit ? (exit[1] === '0' ? 'unknown' : 'fail') : 'unknown';
}
+
+// Include every rendered SVG attribute/text node and the styles that affect it.
+// Normalize line endings, comments and newline indentation only; label spaces stay meaningful.
+export function renderedSvgFingerprint(html) {
+ const start = /<svg\b[^>]*\brole=["']img["'][^>]*>/i.exec(html);
+ if (!start) throw new Error('Rendered diagram SVG (role="img") is missing');
+ const tags = /<\/?svg\b[^>]*>/gi;
+ tags.lastIndex = start.index;
+ let depth = 0;
+ let end;
+ for (let tag; (tag = tags.exec(html));) {
+ depth += tag[0].startsWith('</') ? -1 : tag[0].endsWith('/>') ? 0 : 1;
+ if (depth === 0) { end = tags.lastIndex; break; }
+ }
+ if (end === undefined) throw new Error('Rendered diagram SVG is incomplete');
+ const styles = html.match(/<style\b[^>]*>[\s\S]*?<\/style>/gi) || [];
+ const normalized = [html.slice(start.index, end), ...styles].join('\n')
+ .replace(/\r\n?/g, '\n').replace(/<!--[\s\S]*?-->/g, '')
+ .replace(/>\s*\n\s*</g, '><');
+ return crypto.createHash('sha256').update(normalized).digest('hex');
+}
diff --git a/.agents/skills/archify-tuning/scripts/replay.mjs b/.agents/skills/archify-tuning/scripts/replay.mjs
index 2afa5346..902758b3 100644
--- a/.agents/skills/archify-tuning/scripts/replay.mjs
+++ b/.agents/skills/archify-tuning/scripts/replay.mjs
@@ -4,15 +4,15 @@
// Renders every benchmark first draft with two Archify trees (each the
// directory holding bin/archify.mjs; head defaults to this repository) and
// reports, per type, how many drafts pass on each side, which flipped and
-// which passing drafts changed geometry. Renders and replay.json go to
+// which passing drafts changed their rendered SVG or styles. Renders and replay.json go to
// <tuning-home>/replays/<timestamp> unless --out. Exits 1 when a draft that
// passes on base fails on head. Rendering skips finalize's browser gate.
-import { spawn } from 'node:child_process';
+import { spawn, execFileSync } from 'node:child_process';
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
-import { DIAGRAM_TYPES, tuningHome } from './lib.mjs';
+import { DIAGRAM_TYPES, tuningHome, renderedSvgFingerprint } from './lib.mjs';
const args = process.argv.slice(2);
const option = (name, fallback) => {
@@ -20,7 +20,8 @@ const option = (name, fallback) => {
return index === -1 ? fallback : args[index + 1];
};
const here = path.dirname(fileURLToPath(import.meta.url));
-const base = option('--base');
+const baseOption = option('--base');
+const base = baseOption ? path.resolve(baseOption) : null;
const head = path.resolve(option('--head', path.join(here, '../../../../archify')));
const bench = path.resolve(option('--bench', path.join(tuningHome(), 'bench')));
const out = path.resolve(option('--out', path.join(tuningHome(), 'replays', new Date().toISOString().replace(/[:.]/g, '-'))));
@@ -37,11 +38,21 @@ const entries = DIAGRAM_TYPES.filter((type) => !onlyType || type === onlyType).f
: [];
});
-// Geometry a renderer change can move: routed points and the canvas.
-function geometry(html) {
- const points = html.match(/data-composition-points="[^"]*"|viewBox="[^"]*"/g) || [];
- return crypto.createHash('sha256').update(points.join('\n')).digest('hex').slice(0, 12);
+if (!entries.length) {
+ console.error('No benchmark drafts selected; collect drafts first or choose a populated --bench/--type.');
+ process.exit(2);
+}
+function treeIdentity(tree) {
+ try {
+ const git = (...args) => execFileSync('git', ['-C', tree, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+ return { path: tree, revision: git('rev-parse', 'HEAD'), dirty: git('status', '--porcelain').split('\n').filter(Boolean) };
+ } catch { return { path: tree, revision: null, dirty: null }; }
}
+const inventory = entries.map(({ type, name, file }) => ({ type, name, sha256: crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex') }));
+const provenance = {
+ base: treeIdentity(base), head: treeIdentity(head),
+ benchmark: { inventory, sha256: crypto.createHash('sha256').update(JSON.stringify(inventory)).digest('hex') },
+};
function render(tree, side, entry) {
const document = JSON.parse(fs.readFileSync(entry.file, 'utf8'));
@@ -62,7 +73,7 @@ function render(tree, side, entry) {
problems: problems.length,
codes: [...new Set(problems.map((line) => (line.match(/^- \[([^\]]+)\]/) || [])[1] || 'other'))],
first: ok ? '' : (problems[0] || log.trim().split('\n')[0] || '').slice(0, 160),
- geometry: ok ? geometry(fs.readFileSync(output, 'utf8')) : null,
+ geometry: ok ? renderedSvgFingerprint(fs.readFileSync(output, 'utf8')) : null,
});
});
});
@@ -86,7 +97,7 @@ for (const result of results) {
result.note = note;
console.log(`${`${result.type}/${result.name}`.padEnd(32)} base ${tag(result.base).padEnd(10)} head ${tag(result.head).padEnd(10)} ${note.padEnd(9)} ${result.head.ok ? '' : result.head.codes.join(',')}`);
}
-console.log('\nfirst-draft pass rate by type (base -> head)');
+console.log('\nfirst-draft render pass rate by type (base -> head; browser gate not run)');
for (const type of DIAGRAM_TYPES) {
const own = results.filter((result) => result.type === type);
if (!own.length) continue;
@@ -95,5 +106,5 @@ for (const type of DIAGRAM_TYPES) {
}
const regressed = results.filter((result) => result.base.ok && !result.head.ok);
console.log(`total ${results.filter((result) => result.base.ok).length}/${results.length} -> ${results.filter((result) => result.head.ok).length}/${results.length}; regressed ${regressed.length}; renders in ${out}`);
-fs.writeFileSync(path.join(out, 'replay.json'), `${JSON.stringify({ base: path.resolve(base), head, bench, results }, null, 2)}\n`);
+fs.writeFileSync(path.join(out, 'replay.json'), `${JSON.stringify({ schemaVersion: 1, base, head, bench, provenance, results }, null, 2)}\n`);
process.exit(regressed.length ? 1 : 0);
diff --git a/.agents/skills/archify-tuning/scripts/shots.mjs b/.agents/skills/archify-tuning/scripts/shots.mjs
index 9003209e..83b30683 100644
--- a/.agents/skills/archify-tuning/scripts/shots.mjs
+++ b/.agents/skills/archify-tuning/scripts/shots.mjs
@@ -27,28 +27,62 @@ if (!target || !fs.existsSync(path.join(target, 'replay.json')) || !chrome) {
process.exit(2);
}
const height = Number(option('--height', 1100));
+if (!Number.isInteger(height) || height < 1) { console.error('--height must be a positive integer'); process.exit(2); }
const { results } = JSON.parse(fs.readFileSync(path.join(target, 'replay.json'), 'utf8'));
const picked = results.filter((result) => (args.includes('--all') || result.note) && (!option('--type') || result.type === option('--type')));
const shots = path.join(target, 'shots');
fs.mkdirSync(shots, { recursive: true });
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-shots-'));
+const staging = fs.mkdtempSync(path.join(shots, '.pending-'));
+const captures = [];
+const escape = (value) => String(value).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
function capture(side, result) {
const html = path.join(target, side, result.type, `${result.name}.html`);
- if (!fs.existsSync(html)) return null;
const png = path.join(shots, `${result.type}-${result.name}-${side}.png`);
- spawnSync(chrome, ['--headless=new', '--disable-gpu', '--hide-scrollbars', `--user-data-dir=${profile}`,
- `--window-size=1440,${height}`, `--screenshot=${png}`, pathToFileURL(html).href], { stdio: 'ignore', timeout: 60_000 });
- return fs.existsSync(png) ? path.basename(png) : null;
+ // A failed retry must never display evidence left by an earlier invocation.
+ fs.rmSync(png, { force: true });
+ if (!fs.existsSync(html)) {
+ const expected = result[side]?.ok === false;
+ const entry = { type: result.type, name: result.name, side, status: expected ? 'not-rendered' : 'fail', reason: 'render-missing' };
+ captures.push(entry);
+ return entry;
+ }
+ const pending = path.join(staging, `${result.type}-${result.name}-${side}.png`);
+ const run = spawnSync(chrome, ['--headless=new', '--disable-gpu', '--hide-scrollbars', `--user-data-dir=${profile}`,
+ `--window-size=1440,${height}`, `--screenshot=${pending}`, pathToFileURL(html).href], { encoding: 'utf8', timeout: 60_000 });
+ let reason = run.error?.message || (run.status !== 0 ? `Chrome exited ${run.status ?? run.signal}` : '');
+ if (!reason) {
+ const bytes = fs.existsSync(pending) ? fs.readFileSync(pending) : Buffer.alloc(0);
+ const valid = bytes.length >= 45 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))
+ && bytes.toString('ascii', 12, 16) === 'IHDR' && bytes.readUInt32BE(16) > 0 && bytes.readUInt32BE(20) > 0
+ && bytes.toString('ascii', bytes.length - 8, bytes.length - 4) === 'IEND';
+ if (!valid) reason = 'Chrome did not produce a PNG screenshot';
+ }
+ const entry = { type: result.type, name: result.name, side, status: reason ? 'fail' : 'pass',
+ ...(reason ? { reason, exitCode: run.status, stderr: (run.stderr || '').slice(-2000) } : { file: path.basename(png) }) };
+ if (!reason) fs.renameSync(pending, png);
+ captures.push(entry);
+ return entry;
}
-const rows = picked.map((result) => {
- const [base, head] = [capture('base', result), capture('head', result)];
- const cell = (file, side) => (file ? `<img src="${file}" alt="${side}">` : `<p>${side}: no render (${result[side].first || 'failed'})</p>`);
- return `<h2>${result.type}/${result.name} ${result.note || ''}</h2><div class="pair">${cell(base, 'base')}${cell(head, 'head')}</div>`;
-});
-fs.rmSync(profile, { recursive: true, force: true });
+let rows;
+try {
+ rows = picked.map((result) => {
+ const [base, head] = [capture('base', result), capture('head', result)];
+ const cell = (entry) => entry.status === 'pass' ? `<img src="${escape(entry.file)}" alt="${entry.side}">`
+ : `<p>${entry.side}: ${escape(entry.status)} (${escape(entry.reason)})</p>`;
+ return `<h2>${escape(result.type)}/${escape(result.name)} ${escape(result.note || '')}</h2><div class="pair">${cell(base)}${cell(head)}</div>`;
+ });
+} finally {
+ fs.rmSync(profile, { recursive: true, force: true });
+ fs.rmSync(staging, { recursive: true, force: true });
+}
+const failed = captures.filter((entry) => entry.status === 'fail');
+const passed = captures.filter((entry) => entry.status === 'pass');
+fs.writeFileSync(path.join(shots, 'capture.json'), `${JSON.stringify({ schemaVersion: 1, replay: path.join(target, 'replay.json'), viewport: { width: 1440, height }, captures }, null, 2)}\n`);
fs.writeFileSync(path.join(shots, 'index.html'), `<!doctype html><meta charset="utf-8"><title>Replay shots</title>
<style>body{font:14px system-ui;margin:16px;background:#111;color:#ddd}.pair{display:grid;grid-template-columns:1fr 1fr;gap:8px}img{width:100%;border:1px solid #333}</style>
-<p>Left: base. Right: head. ${picked.length} entries from ${target}</p>${rows.join('\n')}\n`);
-console.log(`${picked.length} pairs: ${path.join(shots, 'index.html')}`);
+<p>Left: base. Right: head. ${picked.length} entries, ${passed.length} screenshots captured, ${failed.length} capture failures, from ${escape(target)}</p>${rows.join('\n')}\n`);
+console.log(`${picked.length} entries; ${passed.length} screenshots captured; ${failed.length} capture failures: ${path.join(shots, 'index.html')}`);
+process.exitCode = failed.length ? 1 : 0;
diff --git a/archify/bin/finalize.mjs b/archify/bin/finalize.mjs
index eb2eb622..d3b39f0f 100644
--- a/archify/bin/finalize.mjs
+++ b/archify/bin/finalize.mjs
@@ -565,7 +565,7 @@ function placementHints({ crossings = [], detours = [], crowdedSides = [] }) {
}
// Route failures call for a connected-scene repair; size and text failures do not.
-const ROUTE_DIAGNOSTIC = /^(clean-flow\/|composition\/(proper-crossing|ambiguous-corridor|border-run|container-border-run|excessive-route-detour|route-rhythm|arrowhead-collision|pinned-reply-detour))/;
+const ROUTE_DIAGNOSTIC = /^(clean-flow\/|composition\/(proper-crossing|ambiguous-corridor|border-run|container-border-run|excessive-route-detour|route-rhythm|arrowhead-collision))/;
export function compactFinalizeReceipt(receipt) {
const gates = {};
diff --git a/archify/references/authoring-contract.md b/archify/references/authoring-contract.md
index 49dcc1ff..ad4e98ee 100644
--- a/archify/references/authoring-contract.md
+++ b/archify/references/authoring-contract.md
@@ -158,7 +158,6 @@ Generate one responsive artifact for laptops and external displays, preserving t
- Automatic Port Spread is a default renderer behavior for architecture, workflow, and data-flow diagrams. Shared automatic endpoints spread deterministically and symmetrically with a 16px corner gutter. It does not apply to sequence messages, single relationships, or explicit `via`, `channelX`, `channelY`, `labelAt`, or non-`auto` routes.
- Showcase route rhythm: every nonzero segment must be at least 8px; every interior segment must be at least 16px. When spread ports are nearly parallel, the router uses a 24px endpoint stub and a 16px outside bridge instead of manufacturing a tiny dogleg.
- Showcase route compactness: an explicit Architecture route fails with `composition/excessive-route-detour` when its orthogonal length is at least 2.5 times an obstacle-aware legal route, adds at least 200px, and sends a control point at least 96px beyond the content envelope. The evidence records both lengths, ratio, excess, bounds, and excursion. Remove an unnecessary `via` or move the diagnosed corridor inward instead of enlarging the canvas. Related relationships that overlap on the same outer corridor by at least 32px are treated as an intentional bus and remain valid.
-- Showcase reply pins: a relationship pinned to leave and enter the same side fails with `composition/pinned-reply-detour` when it has a reply in the opposite direction and both would render as straight parallel lines without `fromSide`/`toSide`. Remove both relationships' side pins.
- Shared endpoint corridors are allowed only when they remain semantically unambiguous. Unrelated collinear overlap of 8px or more fails showcase.
- Container borders are intentional pass-through geometry, but a long edge running along a structural border is not.
- An edge crossing an unrelated opaque node is always a hard failure, independent of quality profile.
diff --git a/archify/references/authoring-defaults.md b/archify/references/authoring-defaults.md
index 882bac08..f96456d1 100644
--- a/archify/references/authoring-defaults.md
+++ b/archify/references/authoring-defaults.md
@@ -22,7 +22,7 @@ Place Architecture nodes by their actual connections before assigning coordinate
Before writing positions, trace each non-main relationship: its straight or one-bend corridor must not pass another node or cross another relationship. If it does, move the endpoint that is off the main path. Start the main actor and its first connected step together near the canvas origin; use content rows for vertical rhythm. Omit `meta.viewBox` for a fresh Architecture so the Reader measures intrinsic height. Keep supplied fixed geometry authoritative.
-Start with automatic routes and endpoint sides. Pin a side only for a necessary branch, return, or supplied geometry. In Architecture, a reply between adjacent nodes in one row or column is not a return: leave both directions automatic so they render as two parallel straight lines. Reserve `via`, `channelX`, `channelY`, and label coordinates for measured defects. Before writing positions, budget each labeled main-path edge at `6.5px × ASCII units + 21px` of clear gap, counting CJK as two units; use its own label length, not a row-wide fixed gap. Keep an Architecture canvas within 1240px wide, or 1790px when it is at least 1.55 times as wide as tall; past that its 8px relationship labels drop below the desktop floor. Size Architecture sublabels for their preferred 9px text at `5.4px × text units + 8px`, with CJK counting twice; keep supporting copy concise without dropping required facts. Do not trade readability or meaning for fewer crossings. The [Geometry reference](authoring-contract.md#executable-geometry-rules) has measured spacing, port, canvas, and route rules for a diagnosed layout problem.
+Start with automatic routes and endpoint sides. Pin a side only for a necessary branch, return, or supplied geometry. For a fresh Architecture, leave adjacent request/reply directions automatic when no required side constraint prevents parallel straight lines; preserve supplied side pins. Reserve `via`, `channelX`, `channelY`, and label coordinates for measured defects. Before writing positions, budget each labeled main-path edge at `6.5px × ASCII units + 21px` of clear gap, counting CJK as two units; use its own label length, not a row-wide fixed gap. Keep an Architecture canvas within 1240px wide, or 1790px when it is at least 1.55 times as wide as tall; past that its 8px relationship labels drop below the desktop floor. Size Architecture sublabels for their preferred 9px text at `5.4px × text units + 8px`, with CJK counting twice; keep supporting copy concise without dropping required facts. Do not trade readability or meaning for fewer crossings. The [Geometry reference](authoring-contract.md#executable-geometry-rules) has measured spacing, port, canvas, and route rules for a diagnosed layout problem.
## Evidence and schema
@@ -36,7 +36,7 @@ Use one primary authored language from the user's choice or the request/conversa
Omit `meta.visual_preset` for classic, `meta.subtitle` for a title-only header, `meta.legend` for truthful auto, and `meta.engineering_profile` for an ordinary system overview. Explicit styles and a subtitle require a user request. Use legend or deployment ownership under the [legend](authoring-contract.md#legend-contract) or [engineering profile](authoring-contract.md#engineering-profile-default) contracts. Branding is optional and explicit when a node names a real product; [Brand marks](brand-marks.md) gives lookup and capture rules for that branch. Never let a badge replace semantic type, label, or relationship facts. Set required `meta.output` to a portable POSIX-relative `.html` path within the working directory; see [Output path contracts](delivery-contract.md#output-path-contracts) for native path exceptions.
-For a fresh Workflow use schema v2 and omit `meta.viewBox` so the compiler measures the real footprint; do not add empty canvas just to satisfy a viewport ratio. Preserve supplied fixed geometry and v1 sources. Omit node `width`: a node starts at 92px and grows to fit its label, sublabel and tag up to 200px. Use its [layout contracts](../renderers/workflow/README.md#layout-contracts) when lane or group geometry needs detail.
+For a fresh Workflow use schema v2 and omit `meta.viewBox` so the compiler measures the real footprint; do not add empty canvas just to satisfy a viewport ratio. Preserve supplied fixed geometry and v1 sources. In an unpinned draft, omit node `width`: a node starts at 92px and grows to fit its label, sublabel and tag up to 200px. Absolute route or label pins retain the previous geometry contract. Use its [layout contracts](../renderers/workflow/README.md#layout-contracts) when lane or group geometry needs detail.
For a fresh Sequence omit `meta.viewBox` and `meta.column_fit`: the canvas widens for participant labels up to its readable width; preserve an authored `meta.viewBox`. Set `meta.column_fit: "fixed"` explicitly when historical fixed coordinates are required; use `spread` when a wide viewBox leaves unused horizontal space or meaningful labels need width. Describe a participant's internal action in a note on its surrounding real cross-participant message, preserving its meaning and order; Sequence self-message loops are not supported.
diff --git a/archify/renderers/architecture/render-architecture.mjs b/archify/renderers/architecture/render-architecture.mjs
index 7f704b18..6eb8437c 100644
--- a/archify/renderers/architecture/render-architecture.mjs
+++ b/archify/renderers/architecture/render-architecture.mjs
@@ -268,7 +268,7 @@ function slideTitleOffRoutes(boundary, title, placedTitles) {
const clear = (x) => {
const rect = { ...title, x };
return !titleRouteSegments.some((segment) => segmentIntersectsRect(segment, rect, 2))
- && ![...placedTitles, ...components.values()].some((other) => rectsOverlap(rect, other));
+ && ![...placedTitles, ...components.values(), ...connectionLabels].some((other) => rectsOverlap(rect, other));
};
if (clear(title.x)) return;
const left = boundary.x + layout.boundaryLabelFrameInset;
@@ -276,8 +276,13 @@ function slideTitleOffRoutes(boundary, title, placedTitles) {
const band = titleRouteSegments.filter(({ start, end }) => (
Math.max(start[1], end[1]) >= title.y - 2 && Math.min(start[1], end[1]) <= title.y + title.height + 2
));
+ const labelBlockers = connectionLabels.filter((label) => (
+ label.y < title.y + title.height && label.y + label.height > title.y
+ ));
const x = [right, ...band.flatMap(({ start, end }) => [
Math.max(start[0], end[0]) + 8, Math.min(start[0], end[0]) - 8 - title.width,
+ ]), ...labelBlockers.flatMap((label) => [
+ label.x + label.width + 8, label.x - 8 - title.width,
])].filter((value) => value >= left && value <= right)
.sort((a, b) => a - b)
.find(clear);
@@ -811,31 +816,6 @@ function validateArchitecture() {
relationCollection: 'connections',
profile: arch.meta?.quality_profile,
}));
- // A reply pinned to leave and enter one side detours around both nodes,
- // although an unpinned reciprocal pair renders as two straight lanes.
- if ((process.env.ARCHIFY_QUALITY_PROFILE || arch.meta?.quality_profile) === 'showcase') {
- const relations = asArray(arch.connections);
- const reported = new Set();
- for (const [index, conn] of relations.entries()) {
- if (reported.has(conn) || !components.has(conn.from) || !components.has(conn.to)
- || !hasAutomaticRouteGeometry(conn) || !conn.fromSide || conn.fromSide === 'auto' || conn.fromSide !== conn.toSide) continue;
- const reply = relations.find((other) => other.from === conn.to && other.to === conn.from && hasAutomaticRouteGeometry(other));
- if (!reply) continue;
- const unpinned = new Map([conn, reply].map((relation) => [relation, { ...relation, fromSide: undefined, toSide: undefined }]));
- const trial = createRouter(components, relations.map((relation) => unpinned.get(relation) || relation), routerOptions);
- if (![...unpinned.values()].every((relation) => trial.pathFor(relation).points.length === 2)) continue;
- reported.add(conn).add(reply);
- const message = `[composition/pinned-reply-detour] architecture connections[${index}]${conn.id ? ` id "${conn.id}"` : ''} "${conn.from}" -> "${conn.to}" is pinned to leave and enter the ${conn.fromSide} side, so it detours around both nodes; without fromSide/toSide it and its reply "${reply.id || `${reply.from}->${reply.to}`}" render as two parallel straight lines — remove fromSide and toSide from both.`;
- problems.push(message);
- diagnostics.push({
- code: 'composition/pinned-reply-detour', severity: 'error', message,
- subject: { diagramType: 'architecture', collection: 'connections', id: conn.id, from: conn.from, to: conn.to },
- evidence: { side: conn.fromSide, replyId: reply.id, points: pathFor(conn).points, unpinnedPoints: [...unpinned.values()].map((relation) => trial.pathFor(relation).points) },
- supportedFixes: [`remove fromSide and toSide from "${conn.id || `${conn.from}->${conn.to}`}" and its reply`],
- });
- }
- }
-
// Connection labels must not land on top of components.
const labelRects = connectionLabels;
for (const rect of labelRects) {
diff --git a/archify/renderers/sequence/render-sequence.mjs b/archify/renderers/sequence/render-sequence.mjs
index 3ac24aec..7feb167b 100644
--- a/archify/renderers/sequence/render-sequence.mjs
+++ b/archify/renderers/sequence/render-sequence.mjs
@@ -124,10 +124,13 @@ const layout = {
labelH: readableMessages ? 18 : 16
};
-// Shrink-to-fit must stop where the text still reads on the desktop at this
-// canvas width; a smaller fit only defers the failure to the browser gate.
-const readableSublabelMinimum = Math.max(participantTextFit.sublabelMinimum,
- Math.ceil(minimumReadableSourceTextPx(viewBox[0]) * 10) / 10);
+// Automatic showcase spread can guarantee a readable fit within its bounded
+// canvas. Standard, fixed columns and authored canvases retain historical text
+// sizing; composition reports their projected readability under its own policy.
+const readableAutomaticSublabel = readableMessages && automaticWidth !== null && columnFit === 'spread';
+const readableSublabelMinimum = readableAutomaticSublabel
+ ? Math.max(participantTextFit.sublabelMinimum, Math.ceil(minimumReadableSourceTextPx(viewBox[0]) * 10) / 10)
+ : participantTextFit.sublabelMinimum;
const readableSublabelPreferred = Math.max(participantTextFit.sublabelPreferred, readableSublabelMinimum);
const participantBoxWidthNote = automaticWidth
@@ -237,11 +240,23 @@ function validateSequence() {
}
for (const participant of participants.values()) {
+ const participantIndex = asArray(sequence.participants).findIndex((entry) => entry.id === participant.id);
+ const participantProblem = (field, message, evidence, supportedFixes) => {
+ problems.push(message);
+ diagnostics.push({
+ code: `sequence/participant-${field}-overflow`, severity: 'error', message,
+ subject: { diagramType: 'sequence', nodeId: participant.id, path: `/participants/${participantIndex}/${field}` },
+ evidence: { viewBoxWidth: viewBox[0], participantWidth: layout.participantW, ...evidence },
+ supportedFixes,
+ });
+ };
const estLabelW = textUnits(participant.label) * 6.8;
if (estLabelW > layout.participantW + 6) {
- problems.push(automaticWidth
+ const message = automaticWidth
? `Label "${participant.label}" (~${Math.round(estLabelW)}px) is wider than component "${participant.id}" — shorten it to at most ${Math.floor((layout.participantW + 6) / 6.8)} text units (CJK counts 2; ${participantBoxWidthNote}).`
- : `Label "${participant.label}" (~${Math.round(estLabelW)}px) is wider than component "${participant.id}" (${layout.participantW}px) — shorten the label or widen the participant box.`);
+ : `Label "${participant.label}" (~${Math.round(estLabelW)}px) is wider than component "${participant.id}" (${layout.participantW}px) — shorten the label or widen the participant box.`;
+ participantProblem('label', message, { text: participant.label, requiredWidth: estLabelW, availableWidth: layout.participantW + 6 },
+ ['shorten the participant label while preserving its role', ...(columnFit === 'fixed' ? ['set meta.column_fit to "spread" if fixed coordinates are not required'] : [])]);
}
const brandRailProblem = brandTopRailProblem(participant, layout.participantW, 8, 'Participant');
if (brandRailProblem) problems.push(brandRailProblem);
@@ -251,7 +266,12 @@ function validateSequence() {
const availableTextW = availableNodeTextWidth(layout.participantW);
const minimumW = minimumNodeTextWidth(participant.sublabel, readableSublabelMinimum);
if (minimumW > availableTextW) {
- problems.push(`Sublabel "${participant.sublabel}" needs ~${Math.ceil(minimumW)}px at the ${readableSublabelMinimum}px minimum that stays readable on this ${viewBox[0]}px canvas, but participant "${participant.id}" provides ${availableTextW}px — shorten the sublabel (${participantBoxWidthNote}).`);
+ const minimumDescription = readableAutomaticSublabel
+ ? `${readableSublabelMinimum}px minimum that stays readable on this ${viewBox[0]}px canvas`
+ : `${readableSublabelMinimum}px legible minimum`;
+ const message = `Sublabel "${participant.sublabel}" needs ~${Math.ceil(minimumW)}px at the ${minimumDescription}, but participant "${participant.id}" provides ${availableTextW}px — shorten the sublabel (${participantBoxWidthNote}).`;
+ participantProblem('sublabel', message, { text: participant.sublabel, requiredWidth: minimumW, availableWidth: availableTextW, minimumFontPx: readableSublabelMinimum },
+ ['shorten the participant sublabel while preserving its role or protocol; move supplementary detail into a card', ...(columnFit === 'fixed' ? ['set meta.column_fit to "spread" if fixed coordinates are not required'] : [])]);
}
}
}
diff --git a/archify/renderers/workflow/README.md b/archify/renderers/workflow/README.md
index 2c4303a1..c5786ffa 100644
--- a/archify/renderers/workflow/README.md
+++ b/archify/renderers/workflow/README.md
@@ -147,6 +147,18 @@ a verified migration-to-v2 repair; v1 never falls through to adaptive layout.
| Explicit viewBox | containment capacity; too-small input reports exact `requiredViewBox` and contributors |
| Lane measurement | A same-column vertical stack (two or more distinct `yOffset` values) opts an implicit, unpinned workflow into per-lane measurement. Explicit `meta.viewBox`, `via`, `labelAt`, `channelX`, or `channelY`, and workflows without a stack retain shared-height v2 geometry for compatibility. |
+Unpinned v2 drafts reserve 32px between overlapping same-lane nodes for routes,
+and omitted node widths may grow from 92px to 200px to fit their text. Documents
+with absolute `via`, `labelAt`, `channelX`, or `channelY` pins retain the existing
+width defaults and 8px rank-clearance constraint, in both compilation and
+migration planning. Authored widths remain authoritative.
+
+Automatic showcase canvases check sublabels against the desktop reading floor
+without enlarging text beyond its existing 8px slot. If the canvas cannot keep
+that slot readable, `workflow/sublabel-readability` reports the required font
+and canvas width. Standard quality and explicit canvases retain their previous
+text-fitting behavior and the existing composition/browser quality checks.
+
The compiler applies constraints only to actual related or overlapping
same-lane nodes, so a wide node in an unrelated lane does not expand every
rank. Legacy centers are a soft preference after correctness constraints, not
diff --git a/archify/renderers/workflow/workflow-compiler.mjs b/archify/renderers/workflow/workflow-compiler.mjs
index 598a16c5..42587f5a 100644
--- a/archify/renderers/workflow/workflow-compiler.mjs
+++ b/archify/renderers/workflow/workflow-compiler.mjs
@@ -25,11 +25,12 @@ import {
import { availableNodeTextWidth, fittedNodeFontSize, minimumNodeTextWidth, nodeLabelLayout } from '../shared/text-fit.mjs';
import { brandLabelFitWidth, brandMarkFor, brandMetadataFor, brandTopRailProblem, renderBrandMark } from '../shared/brand-marks.mjs';
import { translateMessage as i18nText } from '../shared/i18n.mjs';
-import { minimumReadableSourceTextPx, predictedFixedWidthOverflow } from '../shared/desktop-readability.mjs';
+import { DESKTOP_READER_DIAGRAM_WIDTH, MIN_PROJECTED_NODE_TEXT_PX, minimumReadableSourceTextPx, predictedFixedWidthOverflow } from '../shared/desktop-readability.mjs';
import {
createMappedWorkflowCandidate,
intrinsicWorkflow,
planningWorkflow,
+ preservesWorkflowAbsoluteGeometry,
} from './workflow-migration-geometry.mjs';
import {
joinRoutePoints,
@@ -232,6 +233,7 @@ function createReadableLayout(workflow, layoutFeedback = {}) {
const widthContributors = new Set();
const heightContributors = new Set();
const nodes = asArray(workflow.nodes);
+ const nodeClearance = preservesWorkflowAbsoluteGeometry(workflow) ? 8 : 32;
const nodesById = new Map(nodes.map((node) => [node.id, node]));
for (let col = 0; col < columnCount - 1; col += 1) {
@@ -256,11 +258,12 @@ function createReadableLayout(workflow, layoutFeedback = {}) {
if (!verticalIntervalsOverlap(leftNode, rightNode, 8)) continue;
const fromNode = leftNode.col < rightNode.col ? leftNode : rightNode;
const toNode = fromNode === leftNode ? rightNode : leftNode;
- // Leave room for a vertical route corridor between neighbouring nodes.
+ // Unpinned drafts reserve a route corridor; absolute assertions keep
+ // their existing rank plan, including migration planning projections.
constraints.push({
from: fromNode.col,
to: toNode.col,
- minimum: authoredNodeWidth(fromNode) / 2 + 32 + authoredNodeWidth(toNode) / 2,
+ minimum: authoredNodeWidth(fromNode) / 2 + nodeClearance + authoredNodeWidth(toNode) / 2,
contributors: [
`rank ${fromNode.col}→${toNode.col} node width clearance`,
nodeWidthContributor(fromNode),
@@ -686,8 +689,10 @@ function cloneWorkflow(value) {
function canonicalReadableWorkflow(workflow) {
if (workflow.schema_version !== 2) return workflow;
for (const node of asArray(workflow.nodes)) {
- const width = !Number.isFinite(node.width) && automaticNodeWidth(node);
+ const width = !preservesWorkflowAbsoluteGeometry(workflow)
+ && !Number.isFinite(node.width) && automaticNodeWidth(node);
if (width) automaticNodeWidths.set(node, width);
+ else automaticNodeWidths.delete(node);
}
const laneOrder = new Map(asArray(workflow.lanes).map((lane, index) => [lane.id, index]));
const nodes = [...asArray(workflow.nodes)].sort((left, right) => (
@@ -967,7 +972,7 @@ function createWorkflowLaneGeometry(workflow, layout, legendExtraHeight, minimum
function measureWorkflowNodes(workflow, layout, laneGeometry) {
const { laneHeight, laneGroupHeaderH, laneGroupFooterH, laneTop } = laneGeometry;
function measureNode(node) {
- const width = node.width || automaticNodeWidths.get(node) || layout.nodeW;
+ const width = node.width || (workflow.schema_version === 2 && automaticNodeWidths.get(node)) || layout.nodeW;
const height = node.height || (node.tag ? 68 : layout.nodeH);
const cx = layout.colXs[node.col];
const groupHeaderH = laneGroupHeaderH(node.lane);
@@ -4854,25 +4859,52 @@ function renderGroup(group, index) {
<text x="${span.x + 10}" y="${labelY}" class="${textClass}" font-size="7" font-weight="600">${esc(group.label)}</text>`;
}
-// Sublabel shrink-to-fit stops where it still reads on the desktop at the final
-// canvas width, so an overflow is reported here rather than by the browser gate.
-// The gate exempts fine tags, which keep their fixed legible minimum.
+// Automatic showcase canvases stop sublabel shrinking at the desktop floor.
+// Standard and authored canvases retain the established text-fitting contract;
+// the preferred font remains the maximum supported by the fixed text rows.
function readableSublabelMinimum() {
const minimum = nodeTextFit.sublabelMinimum;
- if (workflow.schema_version !== 2) return minimum;
+ if (workflow.schema_version !== 2 || resolvedQualityProfile !== 'showcase'
+ || workflow.meta?.viewBox) return minimum;
return Math.max(minimum, Math.ceil(minimumReadableSourceTextPx(viewBox[0]) * 10) / 10);
}
function validateReadableNodeText() {
- const problems = [];
+ const diagnostics = [];
const minimum = readableSublabelMinimum();
for (const node of nodes.values()) {
- const minimumW = node.sublabel ? minimumNodeTextWidth(node.sublabel, minimum) : 0;
- if (minimumW > availableNodeTextWidth(node.width)) {
- problems.push(`Sublabel "${node.sublabel}" needs ~${Math.ceil(minimumW)}px at the ${minimum}px minimum that stays readable on this ${viewBox[0]}px canvas, but node "${node.id}" provides ${availableNodeTextWidth(node.width)}px — shorten the sublabel; a wider node or canvas lowers every projected font.`);
- }
+ if (!node.sublabel) continue;
+ const maximumCanvasWidth = Math.floor(DESKTOP_READER_DIAGRAM_WIDTH
+ * nodeTextFit.sublabelPreferred / MIN_PROJECTED_NODE_TEXT_PX);
+ const fontBudgetExceeded = minimum > nodeTextFit.sublabelPreferred;
+ const minimumW = minimumNodeTextWidth(node.sublabel, minimum);
+ if (!fontBudgetExceeded && minimumW <= availableNodeTextWidth(node.width)) continue;
+ const message = fontBudgetExceeded
+ ? `Sublabel "${node.sublabel}" needs a ${minimum}px minimum that stays readable on this ${viewBox[0]}px canvas, above the supported ${nodeTextFit.sublabelPreferred}px text row — compact the column spacing or node widths so the canvas is at most ${maximumCanvasWidth}px wide; preserve the sublabel's role or protocol.`
+ : `Sublabel "${node.sublabel}" needs ~${Math.ceil(minimumW)}px at the ${minimum}px minimum that stays readable on this ${viewBox[0]}px canvas, but node "${node.id}" provides ${availableNodeTextWidth(node.width)}px — shorten the sublabel while preserving its role or protocol.`;
+ const authoredNode = workflow.nodes.find((authored) => authored.id === node.id);
+ diagnostics.push({
+ code: 'workflow/sublabel-readability',
+ severity: 'error',
+ message,
+ subject: {
+ diagramType: 'workflow', node: node.id,
+ path: `/nodes/${sourceIndexes.nodes.get(authoredNode)}/sublabel`,
+ },
+ evidence: {
+ requiredFontPx: minimum,
+ maximumSlotFontPx: nodeTextFit.sublabelPreferred,
+ canvasWidthPx: viewBox[0],
+ maximumCanvasWidthPx: maximumCanvasWidth,
+ requiredTextWidthPx: minimumW,
+ availableTextWidthPx: availableNodeTextWidth(node.width),
+ },
+ supportedFixes: fontBudgetExceeded
+ ? [`compact column spacing or node widths until the implicit canvas is at most ${maximumCanvasWidth}px wide, preserving every node and relationship`]
+ : [`shorten node "${node.id}" sublabel while preserving its role or protocol; move supplementary facts into a card`],
+ });
}
- if (problems.length) throwDiagnosticProblems('Workflow layout validation failed', problems, { subject: { diagramType: 'workflow' } });
+ if (diagnostics.length) throwDiagnosticError('Workflow layout validation failed', diagnostics);
}
function renderNode(node) {
@@ -4880,8 +4912,8 @@ function renderNode(node) {
const accent = componentText[node.type] || 't-muted';
const hasSub = node.sublabel != null && node.sublabel !== '';
const labelFontSize = fittedNodeFontSize(node.label, brandLabelFitWidth(node, node.width), nodeTextFit.labelPreferred, nodeTextFit.labelMinimum);
- const sublabelMinimum = readableSublabelMinimum();
- const sublabelFontSize = fittedNodeFontSize(node.sublabel, node.width, Math.max(nodeTextFit.sublabelPreferred, sublabelMinimum), sublabelMinimum);
+ const sublabelMinimum = Math.min(nodeTextFit.sublabelPreferred, readableSublabelMinimum());
+ const sublabelFontSize = fittedNodeFontSize(node.sublabel, node.width, nodeTextFit.sublabelPreferred, sublabelMinimum);
const tagFontSize = fittedNodeFontSize(node.tag, node.width, nodeTextFit.tagPreferred, nodeTextFit.tagMinimum);
const textRows = [{ text: node.label, font: labelFontSize, y: 21 }];
if (hasSub) textRows.push({ text: node.sublabel, font: sublabelFontSize, y: 38 });
diff --git a/archify/renderers/workflow/workflow-migration-geometry.mjs b/archify/renderers/workflow/workflow-migration-geometry.mjs
index 00533871..86aa84fa 100644
--- a/archify/renderers/workflow/workflow-migration-geometry.mjs
+++ b/archify/renderers/workflow/workflow-migration-geometry.mjs
@@ -1,5 +1,15 @@
const TARGET_SCHEMA_VERSION = 2;
+// Planning removes absolute route assertions, but must keep the same rank
+// policy as the document whose coordinates will be mapped into that plan.
+const absoluteGeometryPolicy = Symbol('workflow absolute geometry policy');
+export function preservesWorkflowAbsoluteGeometry(workflow) {
+ return workflow[absoluteGeometryPolicy] ?? (workflow.edges || []).some((edge) => (
+ Array.isArray(edge.via) || Array.isArray(edge.labelAt)
+ || edge.channelX !== undefined || edge.channelY !== undefined
+ ));
+}
+
function clone(value) {
return JSON.parse(JSON.stringify(value));
}
@@ -12,6 +22,7 @@ function clone(value) {
export function intrinsicWorkflow(workflow) {
const intrinsic = clone(workflow);
intrinsic.schema_version = TARGET_SCHEMA_VERSION;
+ intrinsic[absoluteGeometryPolicy] = preservesWorkflowAbsoluteGeometry(workflow);
intrinsic.meta = { ...intrinsic.meta };
delete intrinsic.meta.viewBox;
return intrinsic;
diff --git a/test/archify-tuning.test.mjs b/test/archify-tuning.test.mjs
index 90466b3c..8be212af 100644
--- a/test/archify-tuning.test.mjs
+++ b/test/archify-tuning.test.mjs
@@ -1,11 +1,17 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { spawnSync, execFileSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
import {
authoredControls,
benchmarkDocument,
contentLost,
finalizeStatus,
+ renderedSvgFingerprint,
} from '../.agents/skills/archify-tuning/scripts/lib.mjs';
test('tuning: content lost names the elements and relationships a final candidate dropped', () => {
@@ -17,6 +23,8 @@ test('tuning: content lost names the elements and relationships a final candidat
assert.deepEqual(contentLost('workflow', first, final), {
elements: ['invalid'],
relations: ['b>invalid>rejects'],
+ containers: [],
+ membershipChanges: [],
firstCounts: [3, 2],
finalCounts: [2, 1],
});
@@ -50,3 +58,191 @@ test('tuning: finalize status reads gate results rather than the exit code of a
assert.equal(finalizeStatus('Usage: archify finalize ... Exit code: 2'), 'fail');
assert.equal(finalizeStatus('done Exit code: 0'), 'unknown');
});
+
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const scripts = path.join(repoRoot, '.agents/skills/archify-tuning/scripts');
+const temporary = (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-tuning-test-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ return root;
+};
+const run = (script, args, env = {}) => spawnSync(process.execPath, [path.join(scripts, script), ...args], { encoding: 'utf8', env: { ...process.env, ...env } });
+
+test('tuning: lane merges, group membership loss and parent deletion cannot report complete retention', () => {
+ const first = { lanes: [{ id: 'client' }, { id: 'server' }], groups: [{ id: 'auth', lane: 'server', fromCol: 0, toCol: 1 }], nodes: [{ id: 'a', lane: 'client', col: 0 }, { id: 'b', lane: 'server', col: 1 }], edges: [] };
+ const merged = { ...first, lanes: [{ id: 'client' }], groups: [], nodes: first.nodes.map((node) => ({ ...node, lane: 'client' })) };
+ const lost = contentLost('workflow', first, merged);
+ assert.deepEqual(lost.elements, []);
+ assert.deepEqual(lost.containers, ['lane:server', 'group:auth']);
+ const regrouped = { ...first, nodes: first.nodes.map((node) => node.id === 'b' ? { ...node, col: 2 } : node) };
+ assert.deepEqual(contentLost('workflow', first, regrouped).membershipChanges, [{ container: 'group:auth', element: 'b' }]);
+ for (const type of ['tree', 'waterfall']) {
+ const key = type === 'tree' ? 'nodes' : 'spans';
+ assert.deepEqual(contentLost(type, { [key]: [{ id: 'a' }, { id: 'b', parent: 'a' }] }, { [key]: [{ id: 'a' }, { id: 'b' }] }).relations, ['a>b>']);
+ }
+});
+
+test('tuning: a stable relationship ID cannot conceal endpoint or label loss', () => {
+ const first = { nodes: [{ id: 'a' }, { id: 'b' }, { id: 'c' }], edges: [{ id: 'call', from: 'a', to: 'b', label: 'rejects invalid' }] };
+ for (const edit of [{ to: 'c' }, { label: 'accepts' }]) assert.deepEqual(contentLost('workflow', first, { ...first, edges: [{ ...first.edges[0], ...edit }] }).relations, ['call']);
+});
+
+test('tuning: boundary, stage and domain membership losses remain visible', () => {
+ assert.deepEqual(contentLost('architecture', { components: [{ id: 'a' }], boundaries: [{ kind: 'region', label: 'Private', wraps: ['a'] }] }, { components: [{ id: 'a' }], boundaries: [{ kind: 'region', label: 'Private', wraps: [] }] }).membershipChanges, [{ container: 'boundary:region:Private', element: 'a' }]);
+ assert.deepEqual(contentLost('dataflow', { stages: [{ label: 'In' }, { label: 'Out' }], nodes: [{ id: 'a', stage: 0 }] }, { stages: [{ label: 'In' }, { label: 'Out' }], nodes: [{ id: 'a', stage: 1 }] }).membershipChanges, [{ container: 'stage:In', element: 'a' }]);
+ assert.deepEqual(contentLost('erd', { entities: [{ id: 'orders', tag: 'Sales' }] }, { entities: [{ id: 'orders', tag: 'Accounts' }] }).containers, ['domain:Sales']);
+});
+
+test('tuning: label, frame, node, legend and stylesheet changes request visual comparison', () => {
+ const original = fs.readFileSync(path.join(repoRoot, 'archify/examples/web-app-rendered.html'), 'utf8');
+ const replacements = [
+ ['AWS Region: us-west-2', 'AWS Region: ap-east-1'],
+ ['data-legend-width="87"', 'data-legend-width="187"'],
+ ['font-size="10"', 'font-size="11"'],
+ ['class="c-backend"', 'class="c-database"'],
+ ];
+ for (const [before, after] of replacements) {
+ assert.ok(original.includes(before), before);
+ assert.notEqual(renderedSvgFingerprint(original.replaceAll(before, after)), renderedSvgFingerprint(original), before);
+ }
+ const svg = '<svg role="img" viewBox="0 0 20 20"><rect x="1" y="2" width="3" height="4"/><text x="3">Test</text></svg>';
+ assert.notEqual(renderedSvgFingerprint(svg), renderedSvgFingerprint(svg.replace('width="3"', 'width="5"')));
+ assert.notEqual(renderedSvgFingerprint(svg), renderedSvgFingerprint(svg.replace('x="1"', 'x="9"')));
+ assert.equal(renderedSvgFingerprint(svg), renderedSvgFingerprint(svg.replace('><', '>\n <')));
+ assert.notEqual(renderedSvgFingerprint(`<style>.c-backend{fill:red}</style>${svg}`), renderedSvgFingerprint(`<style>.c-backend{fill:blue}</style>${svg}`));
+});
+
+test('tuning: failed Chrome reruns discard stale screenshots and report failure', (t) => {
+ const root = temporary(t);
+ fs.mkdirSync(path.join(root, 'shots'));
+ for (const side of ['base', 'head']) {
+ fs.mkdirSync(path.join(root, side, 'tree'), { recursive: true });
+ fs.writeFileSync(path.join(root, side, 'tree/demo.html'), '<html>new content</html>');
+ fs.writeFileSync(path.join(root, 'shots', `tree-demo-${side}.png`), 'stale image');
+ }
+ fs.writeFileSync(path.join(root, 'replay.json'), JSON.stringify({ results: [{ type: 'tree', name: 'demo', note: 'changed', base: { ok: true }, head: { ok: true } }] }));
+ // Node is an executable, but rejects Chrome flags: deterministic browser startup failure.
+ const result = run('shots.mjs', [root], { ARCHIFY_CHROME: process.execPath });
+ assert.equal(result.status, 1, result.stderr);
+ assert.match(result.stdout, /0 screenshots captured; 2 capture failures/);
+ assert.ok(!fs.existsSync(path.join(root, 'shots/tree-demo-head.png')));
+ assert.doesNotMatch(fs.readFileSync(path.join(root, 'shots/index.html'), 'utf8'), /<img/);
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(root, 'shots/capture.json'), 'utf8')).captures.map(({ status }) => status), ['fail', 'fail']);
+});
+
+test('tuning: neutral trace exports collect first drafts and repairs without a host database', (t) => {
+ const root = temporary(t);
+ const round = path.join(root, 'round');
+ const candidate = path.join(round, 'workflow/.archify/demo/candidate.json');
+ fs.mkdirSync(path.dirname(candidate), { recursive: true });
+ const first = { nodes: [{ id: 'a' }, { id: 'b' }], edges: [{ id: 'ab', from: 'a', to: 'b' }] };
+ const final = { nodes: [{ id: 'a' }], edges: [] };
+ fs.writeFileSync(candidate, JSON.stringify(final));
+ const trace = path.join(root, 'trace.json');
+ const messages = [
+ { role: 'user', content: `Generate in ${round}/workflow` },
+ { role: 'assistant', content: '', tool_calls: [{ id: 'write-1', name: 'write', arguments: { file_path: candidate, content: JSON.stringify(first) } }] },
+ { role: 'tool', content: 'written', tool_call_id: 'write-1' },
+ { role: 'assistant', content: '', tool_calls: [{ id: 'exec-1', name: 'exec', arguments: { command: `node /archify/bin/archify.mjs finalize workflow ${candidate} output.html --json` } }] },
+ { role: 'tool', content: '{"ok":false,"status":"fail","diagnostics":[{"code":"composition/proper-crossing"}]}', tool_call_id: 'exec-1' },
+ { role: 'assistant', content: '', tool_calls: [{ id: 'exec-2', name: 'exec', arguments: { command: `node /archify/bin/archify.mjs finalize workflow ${candidate} output.html --json` } }] },
+ { role: 'tool', content: '{"ok":true,"status":"pass"}', tool_call_id: 'exec-2' },
+ ];
+ fs.writeFileSync(trace, JSON.stringify({ schemaVersion: 1, sessions: [{ id: 'portable-1', messages }] }));
+ const result = run('collect.mjs', [round, '--trace-export', trace, '--no-bench', '--dump'], { ARCHIFY_TUNING_HOME: root });
+ assert.equal(result.status, 0, result.stderr);
+ const summary = JSON.parse(fs.readFileSync(path.join(round, 'tuning-summary.json'), 'utf8')).workflow;
+ assert.equal(summary.tools, 3);
+ assert.equal(summary.finalizeRuns, 2);
+ assert.equal(summary.finalizeFailures, 1);
+ assert.equal(summary.firstFinalize, 'fail');
+ assert.equal(summary.routingMode, 'automatic-routes');
+ assert.deepEqual(summary.lost.elements, ['b']);
+ assert.deepEqual(summary.lost.relations, ['ab']);
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(round, 'workflow/first-draft.json'), 'utf8')), first);
+ assert.match(fs.readFileSync(path.join(round, 'workflow.trace.txt'), 'utf8'), /composition\/proper-crossing/);
+ messages[2].tool_call_id = 'missing-call';
+ fs.writeFileSync(trace, JSON.stringify({ schemaVersion: 1, sessions: [{ id: 'broken', messages }] }));
+ const bad = run('collect.mjs', [round, '--trace-export', trace, '--no-bench'], { ARCHIFY_TUNING_HOME: root });
+ assert.equal(bad.status, 2);
+ assert.match(bad.stderr, /reference one earlier tool call/);
+});
+
+test('tuning: replay pins revisions and benchmark bytes and flags node-only visual changes', (t) => {
+ const root = temporary(t);
+ const bench = path.join(root, 'bench');
+ fs.mkdirSync(path.join(bench, 'tree'), { recursive: true });
+ fs.writeFileSync(path.join(bench, 'tree/demo.json'), JSON.stringify({ meta: {} }));
+ for (const [side, x] of [['base', 1], ['head', 5]]) {
+ const tree = path.join(root, side);
+ fs.mkdirSync(path.join(tree, 'bin'), { recursive: true });
+ const html = `<svg role="img" viewBox="0 0 20 20"><rect x="${x}" y="1" width="4" height="4"/></svg>`;
+ fs.writeFileSync(path.join(tree, 'bin/archify.mjs'), `import fs from 'node:fs'; fs.writeFileSync(process.argv[5], ${JSON.stringify(html)});`);
+ execFileSync('git', ['init', '-q', tree]);
+ execFileSync('git', ['-C', tree, 'add', '.']);
+ execFileSync('git', ['-C', tree, '-c', 'user.name=Test', '-c', '[email protected]', 'commit', '-qm', 'fixture']);
+ }
+ const out = path.join(root, 'out');
+ const result = run('replay.mjs', ['--base', path.join(root, 'base'), '--head', path.join(root, 'head'), '--bench', bench, '--out', out]);
+ assert.equal(result.status, 0, result.stderr);
+ const receipt = JSON.parse(fs.readFileSync(path.join(out, 'replay.json'), 'utf8'));
+ assert.equal(receipt.results[0].note, 'changed');
+ assert.match(receipt.provenance.base.revision, /^[a-f0-9]{40}$/);
+ assert.deepEqual(receipt.provenance.head.dirty, []);
+ assert.match(receipt.provenance.benchmark.sha256, /^[a-f0-9]{64}$/);
+ assert.match(receipt.provenance.benchmark.inventory[0].sha256, /^[a-f0-9]{64}$/);
+ assert.match(result.stdout, /render pass rate.*browser gate not run/);
+});
+
+test('tuning: fresh PNG captures are published while a failed render stays explicitly absent', { skip: process.platform === 'win32' ? 'Executable fixture uses a POSIX shebang' : false }, (t) => {
+ const root = temporary(t);
+ fs.mkdirSync(path.join(root, 'head/tree'), { recursive: true });
+ fs.writeFileSync(path.join(root, 'head/tree/demo.html'), '<html>fresh content</html>');
+ fs.writeFileSync(path.join(root, 'replay.json'), JSON.stringify({ results: [{ type: 'tree', name: 'demo', note: 'FIXED', base: { ok: false }, head: { ok: true } }] }));
+ const png = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aS1sAAAAASUVORK5CYII=';
+ const chrome = path.join(root, 'chrome-fixture');
+ fs.writeFileSync(chrome, `#!${process.execPath}\nimport fs from 'node:fs';\nconst file=process.argv.find(arg=>arg.startsWith('--screenshot=')).slice(13);\nfs.writeFileSync(file,Buffer.from('${png}','base64'));\n`, { mode: 0o755 });
+ // Use .mjs so the executable fixture is independent of temporary-directory package settings.
+ fs.renameSync(chrome, `${chrome}.mjs`);
+ const result = run('shots.mjs', [root], { ARCHIFY_CHROME: `${chrome}.mjs` });
+ assert.equal(result.status, 0, result.stderr);
+ assert.match(result.stdout, /1 screenshots captured; 0 capture failures/);
+ const captures = JSON.parse(fs.readFileSync(path.join(root, 'shots/capture.json'), 'utf8')).captures;
+ assert.deepEqual(captures.map(({ status }) => status), ['not-rendered', 'pass']);
+ assert.deepEqual(fs.readFileSync(path.join(root, 'shots/tree-demo-head.png')), Buffer.from(png, 'base64'));
+ assert.ok(!fs.readdirSync(path.join(root, 'shots')).some(name => name.startsWith('.pending-')));
+});
+
+test('tuning: portable exports match native separators and quoted finalize paths with spaces', (t) => {
+ const root = temporary(t);
+ for (const nativeSeparators of [false, true]) {
+ const round = path.join(root, nativeSeparators ? 'Windows round' : 'POSIX round');
+ const candidate = path.join(round, 'workflow/.archify/diagram with spaces/candidate.json');
+ fs.mkdirSync(path.dirname(candidate), { recursive: true });
+ const draft = { nodes: [{ id: 'a' }], edges: [] };
+ fs.writeFileSync(candidate, JSON.stringify(draft));
+ const spelling = (file) => nativeSeparators ? file.replaceAll('/', '\\') : file.replaceAll('\\', '/');
+ const cli = nativeSeparators ? 'C:\\Program Files\\Archify\\bin\\archify.mjs' : '/Applications/Archify Skill/bin/archify.mjs';
+ const command = (quote) => `node ${quote}${cli}${quote} finalize workflow ${quote}${spelling(candidate)}${quote} output.html --json`;
+ const messages = [
+ { role: 'user', content: `Create a diagram in ${spelling(path.join(round, 'workflow'))}` },
+ { role: 'assistant', content: '', tool_calls: [{ id: 'read', name: 'read', arguments: { file_path: spelling('/skills/archify/references/authoring-defaults.md') } }, { id: 'write', name: 'write', arguments: { file_path: spelling(candidate), content: JSON.stringify(draft) } }] },
+ { role: 'tool', tool_call_id: 'read', content: 'reference' },
+ { role: 'tool', tool_call_id: 'write', content: 'written' },
+ { role: 'assistant', content: '', tool_calls: [{ id: 'finalize-1', name: 'exec', arguments: { command: command('"') } }] },
+ { role: 'tool', tool_call_id: 'finalize-1', content: '{"ok":false,"status":"fail"}' },
+ { role: 'assistant', content: '', tool_calls: [{ id: 'finalize-2', name: 'exec', arguments: { command: command("'") } }] },
+ { role: 'tool', tool_call_id: 'finalize-2', content: '{"ok":true,"status":"pass"}' },
+ ];
+ const trace = path.join(round, 'trace.json');
+ fs.writeFileSync(trace, JSON.stringify({ schemaVersion: 1, sessions: [{ id: 'portable-paths', messages }] }));
+ const result = run('collect.mjs', [round, '--trace-export', trace, '--no-bench'], { ARCHIFY_TUNING_HOME: root });
+ assert.equal(result.status, 0, result.stderr);
+ const summary = JSON.parse(fs.readFileSync(path.join(round, 'tuning-summary.json'), 'utf8')).workflow;
+ assert.equal(summary.finalizeRuns, 2, `${nativeSeparators ? 'native' : 'POSIX'} quoted command counting`);
+ assert.equal(summary.finalizeFailures, 1);
+ assert.equal(summary.firstFinalize, 'fail');
+ assert.deepEqual(summary.docReads, ['references/authoring-defaults.md']);
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(round, 'workflow/first-draft.json'), 'utf8')), draft);
+ }
+});
diff --git a/test/architecture-route-bends.test.mjs b/test/architecture-route-bends.test.mjs
index a8c49905..58bbeadc 100644
--- a/test/architecture-route-bends.test.mjs
+++ b/test/architecture-route-bends.test.mjs
@@ -61,15 +61,13 @@ function validate(t, profile, replySides) {
return { status: result.status, receipt: JSON.parse(result.stdout) };
}
-test('showcase rejects a reply pinned around both nodes when the pair fits two straight lanes', t => {
+test('showcase preserves a valid authored reply side even when automatic lanes are straighter', t => {
const { status, receipt } = validate(t, 'showcase', { fromSide: 'top', toSide: 'top' });
- assert.equal(status, 1);
- const diagnosis = receipt.diagnostics.find(({ code }) => code === 'composition/pinned-reply-detour');
- assert.ok(diagnosis, JSON.stringify(receipt.diagnostics));
- assert.equal(diagnosis.subject.id, 'report');
- assert.equal(diagnosis.evidence.replyId, 'spawn');
- assert.ok(diagnosis.evidence.unpinnedPoints.every((points) => points.length === 2));
- assert.equal(validate(t, 'showcase', {}).status, 0);
+ assert.equal(status, 0, JSON.stringify(receipt));
+ assert.ok(receipt.composition.metrics.maxBends > 0);
+ const automatic = validate(t, 'showcase', {});
+ assert.equal(automatic.status, 0, JSON.stringify(automatic.receipt));
+ assert.equal(automatic.receipt.composition.metrics.maxBends, 0);
assert.equal(validate(t, 'standard', { fromSide: 'top', toSide: 'top' }).status, 0);
});
@@ -109,3 +107,35 @@ test('showcase slides a boundary title off a route that crosses its rail', t =>
const routeX = Number(html.match(/data-edge-id="read"[^>]*data-composition-points="([\d.]+),/)[1]);
assert.ok(routeX < x - 2 || routeX > x + width + 2, JSON.stringify({ x, width, routeX }));
});
+
+
+test('showcase moves a boundary title around an authored connection label', t => {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-title-authored-label-'));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const input = path.join(directory, 'diagram.json');
+ const output = path.join(directory, 'diagram.html');
+ fs.writeFileSync(input, JSON.stringify({
+ schema_version: 1,
+ diagram_type: 'architecture',
+ meta: { title: 'Title', output: 'diagram.html', quality_profile: 'showcase' },
+ components: [
+ { id: 'cache', type: 'database', label: 'Cache', pos: [40, 40], size: [100, 64] },
+ { id: 'api', type: 'backend', label: 'API', pos: [60, 220], size: [260, 80] },
+ { id: 'a', type: 'backend', label: 'A', pos: [400, 300], size: [200, 80] },
+ { id: 'b', type: 'backend', label: 'B', pos: [800, 300], size: [200, 80] },
+ ],
+ connections: [
+ { id: 'read', from: 'api', to: 'cache' },
+ { id: 'other', from: 'a', to: 'b', label: 'read', labelAt: [165, 208] },
+ ],
+ boundaries: [{ kind: 'region', label: 'Backend services', wraps: ['api'] }],
+ }));
+ const result = spawnSync(process.execPath, [cli, 'render', 'architecture', input, output, '--quality', 'showcase'], { cwd: directory, encoding: 'utf8' });
+ assert.equal(result.status, 0, result.stderr);
+ const html = fs.readFileSync(output, 'utf8');
+ const [, x, width] = html.match(/structural-frame-label-mask" x="([\d.]+)" y="[\d.]+" width="([\d.]+)"/).map(Number);
+ // The authored label occupies x=150..180; the title must move past it,
+ // rather than asking the author to repair an overlap introduced by layout.
+ assert.ok(x > 180 || x + width < 150, JSON.stringify({ x, width }));
+ assert.match(html, /x="165" y="208"/);
+});
diff --git a/test/layout-rules.test.mjs b/test/layout-rules.test.mjs
index c3ad486d..bc763198 100644
--- a/test/layout-rules.test.mjs
+++ b/test/layout-rules.test.mjs
@@ -251,7 +251,7 @@ const CASES = [
['exceeds the segment frame\'s available width', 'increase meta.viewBox[0]']],
['sequence: participant sublabel wider than its legible minimum', 'sequence',
(d) => { d.participants[0].sublabel = 'This supporting sentence is far too long for one sequence participant'; },
- ['Sublabel', 'readable', 'shorten the sublabel']],
+ ['sequence/participant-sublabel-overflow', 'Sublabel', 'legible', 'shorten the sublabel']],
// ---- dataflow layout rules ----
['dataflow: flow missing label', 'dataflow',
@@ -357,6 +357,31 @@ for (const [name, mode, mutate, expected] of CASES) {
});
}
+test('workflow: exact 8px clearance retains the floating-point tolerance (#583)', () => {
+ // A label pin retains the compatibility rank policy. The historical pair
+ // is therefore still checked at the validator's 8px boundary.
+ const doc = {
+ schema_version: 2, diagram_type: 'workflow',
+ meta: { title: 'Pinned clearance rounding', quality_profile: 'showcase' },
+ lanes: [{ id: 'upper', label: 'Upper: the first lane' }, { id: 'lower', label: 'Lower lane: second lane' }],
+ nodes: [
+ { id: 's0', lane: 'lower', col: 0, type: 'backend', label: 'Start', width: 160 },
+ ...[1, 2, 3, 4, 5].map(col => ({ id: `a${col}`, lane: 'upper', col, type: 'backend', label: `Step ${col}`, width: 160 })),
+ ],
+ edges: [
+ { id: 's0-a1', from: 's0', to: 'a1', fromSide: 'top', toSide: 'left' },
+ { id: 'a3-a4', from: 'a3', to: 'a4', label: 'next', labelAt: [870, 82] },
+ ],
+ };
+ const rendered = render('workflow', doc);
+ assert.equal(rendered.code, 0, rendered.stderr);
+ const html = fs.readFileSync(rendered.outPath, 'utf8');
+ const left = workflowNodeRect(html, 'a4');
+ const right = workflowNodeRect(html, 'a5');
+ assert.ok(Math.abs(right.x - (left.x + left.width) - 8) < 1e-6);
+ assert.ok(left.x + left.width + 8 > right.x, 'the pair must need the floating-point tolerance');
+});
+
test('workflow: same-lane nodes the solver separated by its exact minimum keep passing (#583)', () => {
// Redacted reproduction from #583: the neighbour constraint produced a column
// distance the check re-derived from the nodes' left edges as 1.14e-13px past
@@ -621,9 +646,27 @@ test('architecture: boundary title masks cannot obscure connection labels', () =
}],
};
+ const repaired = render('architecture', d);
+ assert.equal(repaired.code, 0, repaired.stderr);
+ const html = fs.readFileSync(repaired.outPath, 'utf8');
+ const match = html.match(/<g data-detail="context" data-edge-from="source" data-edge-to="target"[^>]*>[\s\S]*?<rect x="([^"]+)" y="([^"]+)" width="([^"]+)" height="([^"]+)"/);
+ assert.ok(match, 'expected the authored connection label mask');
+ const [, x, y, width, height] = match.map(Number);
+ const connectionMask = { x, y, width, height };
+ const titleMasks = boundaryTitleMasks(html);
+ assert.equal(titleMasks.length, 1);
+ for (const titleMask of titleMasks) {
+ assert.equal(rectanglesOverlap(titleMask, connectionMask), false);
+ }
+ assert.match(html, /<text x="270" y="88"[^>]*>Route label<\/text>/);
+
+ // A mask covering the complete rail cannot be repaired by sliding the title.
+ // Retain rejection and executable author guidance for that real collision.
+ d.connections[0].label = 'Route label across complete frame';
+ d.connections[0].labelAt = [310, 88];
const { code, stderr } = render('architecture', d);
assert.notEqual(code, 0);
- assert.match(stderr, /Boundary label "Runtime scope" overlaps connection label "Route label"/);
+ assert.match(stderr, /Boundary label "Runtime scope" overlaps connection label "Route label across complete frame"/);
assert.match(stderr, /labelAt\/labelDx\/labelDy\/labelSegment/);
});
diff --git a/test/sequence-column-fit.test.mjs b/test/sequence-column-fit.test.mjs
index 3fe6f97d..468a0240 100644
--- a/test/sequence-column-fit.test.mjs
+++ b/test/sequence-column-fit.test.mjs
@@ -1,6 +1,6 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
-import { execFileSync } from 'node:child_process';
+import { execFileSync, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
@@ -299,4 +299,52 @@ test('a widened automatic canvas reports sublabels at the size that stays readab
const outcome = renderOutcome(doc);
assert.notEqual(outcome.code, 0);
assert.match(outcome.stderr, /Sublabel "tmp 或 reports\/review" needs ~\d+px at the [\d.]+px minimum that stays readable on this \d+px canvas/);
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-sequence-diagnostic-'));
+ try {
+ const input = path.join(tmp, 'input.json');
+ fs.writeFileSync(input, JSON.stringify({ ...doc, meta: { ...doc.meta, output: 'sequence.html' } }));
+ const result = spawnSync(process.execPath, [path.join(skillRoot, 'bin/archify.mjs'), 'validate', 'sequence', input, '--json'], { encoding: 'utf8' });
+ assert.notEqual(result.status, 0);
+ const diagnostic = JSON.parse(result.stdout).diagnostics.find(entry => entry.code === 'sequence/participant-sublabel-overflow');
+ assert.equal(diagnostic.subject.nodeId, 'g');
+ assert.equal(diagnostic.subject.path, '/participants/6/sublabel');
+ assert.ok(diagnostic.evidence.requiredWidth > diagnostic.evidence.availableWidth);
+ assert.ok(diagnostic.evidence.minimumFontPx > 6);
+ assert.match(diagnostic.supportedFixes[0], /preserving its role or protocol/);
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+});
+
+test('standard fixed authored canvases retain accepted sublabel fitting', () => {
+ const doc = wideSequence('fixed');
+ doc.meta.quality_profile = 'standard';
+ doc.participants[0].sublabel = 'ABCDEFGHIJKLMNOPQRST';
+ const html = render(doc, true);
+ assert.match(html, /font-size="6\.5"[^>]*>ABCDEFGHIJKLMNOPQRST<\/text>/);
+ assert.deepEqual(participantBoxes(html), [19, 127, 235, 343, 451].map(x => ({ x, width: 86 })));
+});
+
+test('wide authored canvases never enlarge sublabels beyond the historical card rows', () => {
+ for (const columnFit of ['fixed', 'spread']) {
+ const doc = wideSequence(columnFit);
+ doc.meta.quality_profile = 'standard';
+ doc.meta.viewBox = [3000, 760];
+ doc.participants[0].sublabel = 'DB';
+ assert.match(render(doc, true), /y="122" class="t-muted" font-size="7"[^>]*>DB<\/text>/);
+ }
+});
+
+test('automatic showcase spread retains a readable sublabel font after widening', () => {
+ const doc = {
+ schema_version: 1, diagram_type: 'sequence', meta: { title: 'Readable automatic width', quality_profile: 'showcase' },
+ participants: Array.from({ length: 8 }, (_, index) => ({ id: `p${index}`, type: 'backend', label: 'Team operations', sublabel: 'context' })),
+ messages: [{ from: 'p0', to: 'p7', label: 'send', y: 180 }],
+ };
+ const html = render(doc, true);
+ const width = Number(html.match(/<svg viewBox="0 0 (\d+) /)[1]);
+ assert.ok(width > 920 && width <= 1085, String(width));
+ const fonts = [...html.matchAll(/font-size="([\d.]+)"[^>]*>context<\/text>/g)].map(match => Number(match[1]));
+ assert.ok(fonts.length >= 8);
+ for (const font of fonts) assert.ok(font * Math.min(1, 930 / width) >= 6, `${font}px on ${width}px canvas`);
});
diff --git a/test/workflow-compiler.test.mjs b/test/workflow-compiler.test.mjs
index fbe12929..58b3c1de 100644
--- a/test/workflow-compiler.test.mjs
+++ b/test/workflow-compiler.test.mjs
@@ -500,6 +500,46 @@ test('a readable-v2 node without an authored width grows to fit its label', () =
assert.equal(width, 104);
});
+test('automatic widths are recomputed after editing the same workflow object', () => {
+ const document = adjacentWorkflow({ widths: [undefined, undefined], nodeLabels: ['Start', 'a'.repeat(29)] });
+ document.nodes[1].col = 5;
+ const expanded = compileSuccessfully(document);
+ assert.equal(expanded.receipt.nodes.find(({ id }) => id === 'b').width, 192);
+ document.nodes[1].label = 'A';
+ document.meta.viewBox = [768, 420];
+ const reused = compileSuccessfully(document);
+ const fresh = compileSuccessfully(clone(document));
+ assert.equal(reused.receipt.nodes.find(({ id }) => id === 'b').width, 92);
+ assert.equal(reused.svg, fresh.svg);
+ assert.deepEqual(reused.receipt, fresh.receipt);
+});
+
+test('switching an edited document to fixed-v1 does not reuse automatic widths', () => {
+ const document = adjacentWorkflow({ widths: [undefined, undefined], nodeLabels: ['Start', 'a'.repeat(29)] });
+ document.nodes[1].col = 5;
+ compileSuccessfully(document);
+ document.nodes[1].label = 'A';
+ document.schema_version = 1;
+ const reused = compileSuccessfully(document);
+ const fresh = compileSuccessfully(clone(document));
+ assert.equal(reused.receipt.nodes.find(({ id }) => id === 'b').width, 92);
+ assert.equal(reused.svg, fresh.svg);
+});
+
+test('authored canvases and standard workflows preserve bounded sublabel fonts', () => {
+ for (const qualityProfile of ['standard', 'showcase']) {
+ const document = adjacentWorkflow({ widths: [92, 92], viewBox: [10000, 420] });
+ document.nodes[0].sublabel = 'x';
+ const result = compileSuccessfully(document, qualityProfile);
+ assert.match(result.svg, /data-detail="context"[^>]*font-size="8"[^>]*>x<\/text>/);
+ }
+ const document = adjacentWorkflow({ widths: [132, 200] });
+ document.nodes[1].col = 5;
+ document.nodes[0].sublabel = 'chain / debate / synthesis 调度';
+ for (const col of [0, 2, 3, 4]) document.nodes.push({ id: `wide-${col}`, lane: 'main', col, type: 'backend', label: `Step ${col}`, width: 200 });
+ compileSuccessfully(document, 'standard');
+});
+
test('readable-v2 sublabels must fit at the size that stays readable on the final canvas', () => {
const workflow = adjacentWorkflow({ widths: [132, 200] });
workflow.nodes[1].col = 5;
@@ -507,11 +547,27 @@ test('readable-v2 sublabels must fit at the size that stays readable on the fina
for (const col of [0, 2, 3, 4]) {
workflow.nodes.push({ id: `wide-${col}`, lane: 'main', col, type: 'backend', label: `Step ${col}`, width: 200 });
}
- const result = compileWorkflow({ workflow });
+ const result = compileWorkflow({ workflow, qualityProfile: 'showcase' });
assert.equal(result.ok, false, 'expected a readable-size failure on a canvas wider than the reader');
assert.match(JSON.stringify(result.diagnostics), /minimum that stays readable on this \d+px canvas/);
});
+test('automatic showcase rejects a sublabel floor above the fixed row font budget', () => {
+ const workflow = adjacentWorkflow({ fromCol: 0, widths: [400, 400] });
+ workflow.nodes[0].sublabel = 'x';
+ workflow.nodes[1].col = 5;
+ for (const col of [2, 3, 4]) workflow.nodes.push({ id: `wide-${col}`, lane: 'main', col, type: 'backend', label: `Step ${col}`, width: 400 });
+ const result = compileWorkflow({ workflow, qualityProfile: 'showcase' });
+ assert.equal(result.ok, false);
+ assert.match(JSON.stringify(result.diagnostics), /above the supported 8px text row/);
+ const diagnostic = result.diagnostics.find(({ code }) => code === 'workflow/sublabel-readability');
+ assert.equal(diagnostic.subject.path, '/nodes/0/sublabel');
+ assert.ok(diagnostic.evidence.requiredFontPx > diagnostic.evidence.maximumSlotFontPx);
+ assert.equal(diagnostic.evidence.maximumSlotFontPx, 8);
+ assert.ok(diagnostic.supportedFixes.some(fix => /compact column spacing/.test(fix)));
+ compileSuccessfully(workflow, 'standard');
+});
+
test('an automatic readable-v2 canvas too tall for the desktop page reads at page width', () => {
const workflow = adjacentWorkflow();
workflow.lanes = Array.from({ length: 6 }, (_, index) => ({ id: `lane-${index}`, label: `Lane ${index}` }));
diff --git a/test/workflow-migration.test.mjs b/test/workflow-migration.test.mjs
index 085a8caf..3ceb956e 100644
--- a/test/workflow-migration.test.mjs
+++ b/test/workflow-migration.test.mjs
@@ -436,10 +436,10 @@ test('workflow migration remaps absolute x coordinates, expands only the constra
const migratedBytes = fs.readFileSync(destination);
const migrated = JSON.parse(migratedBytes);
assert.equal(migrated.schema_version, 2);
- assert.deepEqual(migrated.meta.viewBox, [772, 700], 'width grows to fit v2 while sufficient height is preserved');
+ assert.deepEqual(migrated.meta.viewBox, [768, 700], 'width grows to fit v2 while sufficient height is preserved');
assert.deepEqual(migrated.edges[0].via, [[214, 119]]);
- assert.deepEqual(migrated.edges[1].labelAt, [396, 203]);
- assert.equal(migrated.edges[2].channelX, 578);
+ assert.deepEqual(migrated.edges[1].labelAt, [394, 203]);
+ assert.equal(migrated.edges[2].channelX, 574);
const report = parseJsonOutput(result);
assert.equal(report.ok, true);
@@ -462,11 +462,11 @@ test('workflow migration remaps absolute x coordinates, expands only the constra
assert.deepEqual(report.newSchemaDiagnostics, []);
assert.deepEqual(report.changedCoordinates, [
{ path: '/edges/0/via/0/0', from: 220, to: 214 },
- { path: '/edges/1/labelAt/0', from: 365, to: 396 },
- { path: '/edges/2/channelX', from: 500, to: 578 },
+ { path: '/edges/1/labelAt/0', from: 365, to: 394 },
+ { path: '/edges/2/channelX', from: 500, to: 574 },
]);
assert.deepEqual(report.oldRequiredViewBox, [720, 652]);
- assert.deepEqual(report.newRequiredViewBox, [772, 652]);
+ assert.deepEqual(report.newRequiredViewBox, [768, 652]);
});
test('workflow migration never shrinks an already spacious explicit viewBox', () => {
diff --git a/test/workflow-routing-clarity.test.mjs b/test/workflow-routing-clarity.test.mjs
index 8b07cf93..f8a9eb7a 100644
--- a/test/workflow-routing-clarity.test.mjs
+++ b/test/workflow-routing-clarity.test.mjs
@@ -120,7 +120,7 @@ test('readable-v2 preserves authored sides, routes, channels, vias, and label po
{ route: 'straight' },
{ route: 'bottom-channel' },
{ channelY: 425 },
- { via: [[716.8, 425], [840.8, 425]], fromSide: 'bottom', toSide: 'bottom' },
+ { via: [[716.8, 425], [836.8, 425]], fromSide: 'bottom', toSide: 'bottom' },
{ labelAt: [776.8, 415] },
];
for (const authored of cases) {