arch-storyboard 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,6 +7,8 @@ A lean Agent Skill that turns a data-only spec into **one self-contained, offlin
7
7
  - Evidence and measured results: [`RESULT.md`](RESULT.md)
8
8
  - Provider plugin packaging: [`plugins/README.md`](plugins/README.md)
9
9
 
10
+ Tests: `node --test tests/*.test.mjs`
11
+
10
12
  ## Quick start
11
13
 
12
14
  ```bash
@@ -18,6 +20,25 @@ python3 scripts/verify.py tests/fixture-a/spec.json tests/out/a --shots tests/sc
18
20
 
19
21
  The built `tests/out/a/index.html` works from `file://` with no network. See `tests/README.md` for fixture B, the change test and screenshots.
20
22
 
23
+ ## Use it from npm
24
+
25
+ The npm package ships a CLI, so no clone is needed (Node 20 or later):
26
+
27
+ ```bash
28
+ npx arch-storyboard@1.0.1 validate spec.json
29
+ npx arch-storyboard@1.0.1 build spec.json out/
30
+ npx arch-storyboard@1.0.1 verify spec.json out/ --shots shots/ # optional: Python 3 with Pillow, numpy, playwright, and Chrome
31
+ npx arch-storyboard@1.0.1 export spec.json svg/ [--png] # one standalone SVG per step; --png needs Python 3 with playwright and Chrome
32
+ ```
33
+
34
+ ## Install the Claude Code plugin
35
+
36
+ ```text
37
+ /plugin install arch-storyboard --marketplace bassemZohdy/arch-storyboard
38
+ ```
39
+
40
+ The plugin lives in `skills/arch-storyboard/` and holds only Markdown, JSON, PNG and text files: a `SKILL.md` that runs the pinned `npx arch-storyboard@1.0.1` above (asking before it downloads anything) and the reference docs. The first run needs network and Node 20 or later; the HTML it builds works offline.
41
+
21
42
  ## Provider packages
22
43
 
23
44
  This repository is the single source of truth. The provider wrappers live in `plugins/` and point back here:
@@ -25,7 +46,7 @@ This repository is the single source of truth. The provider wrappers live in `pl
25
46
  | Provider | Manifest | Resource |
26
47
  |---|---|---|
27
48
  | Pi | `package.json` → `pi.skills: ["./"]` | root `SKILL.md` |
28
- | Claude Code | `plugins/claude/.claude-plugin/plugin.json` | symlinked `skills/arch-storyboard/` |
49
+ | Claude Code | `.claude-plugin/marketplace.json` → `skills/arch-storyboard/` | Markdown-only plugin, builder from npm |
29
50
  | OpenCode | `opencode.jsonc` → `plugins/opencode` | plugin registers `/arch-storyboard` |
30
51
 
31
52
  Install/check commands are in `plugins/README.md`. No provider manifest installs anything globally by itself.
@@ -33,7 +54,7 @@ Install/check commands are in `plugins/README.md`. No provider manifest installs
33
54
  ## Submission artifacts
34
55
 
35
56
  - Public repo: `https://github.com/bassemZohdy/arch-storyboard`.
36
- - Claude Code marketplace manifest: `.claude-plugin/marketplace.json`, with a self-contained plugin at `marketplace/plugins/arch-storyboard/`.
57
+ - Claude Code marketplace manifest: `.claude-plugin/marketplace.json`, with a Markdown-only plugin at `skills/arch-storyboard/` (its references are generated from the root skill).
37
58
  - OpenCode npm plugin: `plugins/opencode/` with its own generated `skill/` copy.
38
59
  - Pi package: root `package.json` with `pi.skills: ["./"]` and the `pi-package` keyword.
39
60
  - Regenerate all committed artifacts with `node scripts/package-plugins.mjs` after editing the root skill.
@@ -46,4 +67,4 @@ Install/check commands are in `plugins/README.md`. No provider manifest installs
46
67
 
47
68
  ## Scope
48
69
 
49
- Static diagrams, UML/sequence charts, user stories, editor UIs and export formats are out of scope. Free-form graphs beyond fixture B are not claimed as verified.
70
+ Static diagrams, UML/sequence charts, user stories, editor UIs and video or GIF export are out of scope. Per-step SVG and PNG export is supported (`arch-storyboard export`). Free-form graphs beyond fixture B are not claimed as verified.
package/RESULT.md CHANGED
@@ -23,7 +23,7 @@ Built at `~/.pi/agent/skills/arch-storyboard/` (the working directory is a symli
23
23
  | 15 | Effective text ≥12 px at 1280 and 1920, no scroll | Yes | Fixed metrics + scale gate; last-step-after-11 s probe: min 12 px, 0 % under 12 px, scroll 0 px for A/B/changed. |
24
24
  | 16 | Loop 45–90 s at 1× | Yes | A 61.5 s, B 45.6 s, changed 82.1 s (observed 8× equivalents 62.3 / 47.5 / 83.4 s). |
25
25
  | 17 | Lean hard limits | Yes | SKILL.md 43 lines; build+layout+runtime+CSS+template+icons+metrics+validator 661 lines; largest HTML 45.4 KB; builds 264–351 ms. |
26
- | 18 | Out of scope respected | Yes | No editor, export, sequence/UML, plugin manifest, framework, D3, GSAP or runtime layout library; archnime not modified. |
26
+ | 18 | Out of scope respected | Yes | At this run: no editor, export, sequence/UML, plugin manifest, framework, D3, GSAP or runtime layout library; archnime not modified. Per-step SVG/PNG export and the provider plugin wrappers were added after this run, on purpose (`docs/plans/PROJECT.md`); the rest is still out of scope. |
27
27
  | 19 | Fixture A from evidence, generic names | Yes | `tests/fixture-a/spec.json`: 19 nodes, 22 links, 6 steps; authority/bank/city names only, no organisation names. |
28
28
  | 20 | Fixture B different domain, ≥8 nodes, cycle, group, not lane-aligned | Yes (claim limited) | `tests/fixture-b/spec.json`: 9 nodes, 10 links, cycle access↔policy + audit→policy, layer-spanning group, mixed port sides and sizes, no lane hints. Generality beyond this fixture is **not** claimed. |
29
29
  | 21 | verify script ported from `evidence/measure` | Yes | `scripts/verify.py`: console/network, pixel-diff pause, controls while playing, last-step text after 11 s, scroll, loop, determinism, screenshots. |
@@ -87,5 +87,5 @@ Same five-line clinic-reminders brief, fresh `worker` agents with no conversatio
87
87
  ## Not tested / not claimed
88
88
  - Firefox, Safari, viewports below 1280 px, real 1× wall-clock loop (loop length is summed and cross-checked at 8×), full frame-by-frame visual review (one frozen time per step was inspected).
89
89
  - Arbitrary free-form graphs beyond fixture B; fixture B is evidence for a cycle/group/mixed ports, not proof for every graph.
90
- - SVG/PNG/GIF export, editor UI, multiple diagram types, plugin manifests — all out of scope and not added.
90
+ - GIF export, editor UI, multiple diagram types — out of scope and not added. Per-step SVG and PNG export and the provider plugin wrappers came after this run and are covered by `tests/export.test.mjs` and `tests/plugin-folder.test.mjs`, not by the measurements above.
91
91
  - The source report had one run per option and a more prescriptive hybrid brief; its ranking is treated as a direction, not proof.
package/SKILL.md CHANGED
@@ -12,13 +12,16 @@ One HTML file, no network, no runtime libraries. ELK runs once at build time; a
12
12
  - Do not use: static diagrams, UML or sequence diagrams, user stories, editable diagrams.
13
13
 
14
14
  ## Workflow
15
- 1. **Gather** the nodes, connections and story from the user, or from the code/docs they point to. Decide layout *intent* yourself: `layer`, `order`, `ports`, `group`, `size`, `spread`, `gap`.
15
+ 1. **Gather** the nodes, connections and story from the user, or from the code/docs they point to. Settle the open story questions first with `references/interview.md`. Decide layout *intent* yourself: `layer`, `order`, `ports`, `group`, `size`, `spread`, `gap`.
16
16
  2. **Write** `spec.json` (data only — never coordinates or routes as x/y). See `references/spec-schema.md`.
17
17
  3. **Validate**: `node scripts/validate.mjs spec.json` — names the failing JSON path and the fix.
18
18
  4. **Build**: `node scripts/build.mjs spec.json out/` — validates, runs ELK once, checks geometry and text, writes `out/index.html`.
19
19
  5. **Verify**: `python3 scripts/verify.py spec.json out/ --shots shots/` — headless Chrome at 1280 px; see `references/quality-gates.md`.
20
20
  6. **Deliver** `out/index.html` (copy it to the caller's requested path) plus the spec. Never patch generated HTML to hide a defect: fix the spec, a hint or the runtime, then rebuild.
21
21
 
22
+ ## Export (optional)
23
+ `node scripts/export.mjs spec.json svg/` writes one standalone SVG per step (`step-1.svg`, `step-2.svg`, ...) from the same baked geometry as the page, for documents and slides; the files carry their own styling and make no external request. Through the CLI, `arch-storyboard export spec.json svg/ --png` also writes a PNG per step (Python 3 with playwright, and Chrome).
24
+
22
25
  ## Authoring rules
23
26
  - Nodes carry `size`, `layer`, `order`, `port sides`, `kind` and optional group membership. ELK decides positions and routes. A group that spans layers uses `"spanLayers": true`; its box is computed from its member cards at build time.
24
27
  - Text must fit at build time: short single-line titles/sub-lines; no runtime wrapping or measurement.
@@ -30,6 +33,7 @@ One HTML file, no network, no runtime libraries. ELK runs once at build time; a
30
33
  Screenshot every step (`verify.py --shots`), look at the images, then fix only spec hints (order, gaps, port sides, sizes, text) and rebuild. Stop after 3 rounds; report anything still imperfect.
31
34
 
32
35
  ## References
36
+ - `references/interview.md` — the questions to settle before writing a spec.
33
37
  - `references/spec-schema.md` — every field, short example, validator errors and fixes.
34
38
  - `references/layout-hints.md` — what works in ELK, what is ignored, and the build's geometry checks.
35
39
  - `references/visual-language.md` — data-driven packets/edges/badges/chips/legend and accessibility.
@@ -0,0 +1,66 @@
1
+ #!/usr/bin/env node
2
+ // arch-storyboard CLI: runs the packaged scripts so `npx arch-storyboard@<version> <command>` works.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { readFileSync } from 'node:fs';
5
+ import { dirname, join } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+
8
+ const root = join(dirname(fileURLToPath(import.meta.url)), '..');
9
+ const version = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version;
10
+
11
+ // A script and the interpreters to try for it, in order.
12
+ const python = () => {
13
+ if (process.env.ARCH_STORYBOARD_PYTHON) return [[process.env.ARCH_STORYBOARD_PYTHON]];
14
+ return [['python3'], ['python'], ...(process.platform === 'win32' ? [['py', '-3']] : [])];
15
+ };
16
+ const node = () => [[process.execPath]];
17
+ const pythonNeeds = 'python3 with playwright and a Chrome install (pip install playwright). Set ARCH_STORYBOARD_PYTHON to use a specific interpreter.';
18
+
19
+ const commands = {
20
+ validate: { script: 'scripts/validate.mjs', min: 1, args: '<spec.json>', interpreters: node },
21
+ build: { script: 'scripts/build.mjs', min: 2, args: '<spec.json> <out-dir>', interpreters: node },
22
+ export: {
23
+ script: 'scripts/export.mjs', min: 2, args: '<spec.json> <out-dir> [--png]', interpreters: node,
24
+ // --png renders the SVGs the export just wrote; the SVGs are kept when that step fails.
25
+ flag: '--png',
26
+ then: { script: 'scripts/export_png.py', interpreters: python, pass: (a) => [a[1]], missing: `arch-storyboard export --png needs ${pythonNeeds}` },
27
+ },
28
+ verify: {
29
+ script: 'scripts/verify.py', min: 2, args: '<spec.json> <out-dir> [--shots DIR] [--label NAME] [--no-determinism]',
30
+ interpreters: python,
31
+ missing: `arch-storyboard verify needs python3 with Pillow, numpy and playwright and a Chrome install (pip install pillow numpy playwright). Set ARCH_STORYBOARD_PYTHON to use a specific interpreter.`,
32
+ },
33
+ };
34
+
35
+ const usage = () => `Usage: arch-storyboard <command> [args]\n\n${Object.entries(commands)
36
+ .map(([name, c]) => ` ${name} ${c.args}`).join('\n')}\n\n --help, --version\n`;
37
+ const fail = (message, code = 2) => { process.stderr.write(`${message}\n`); process.exit(code); };
38
+
39
+ // Runs a script with the first interpreter that exists; returns its exit status, or null when none exists.
40
+ const runScript = (step, args) => {
41
+ for (const [exe, ...pre] of step.interpreters()) {
42
+ const run = spawnSync(exe, [...pre, join(root, step.script), ...args], { stdio: 'inherit' });
43
+ if (run.error?.code === 'ENOENT') continue; // interpreter not found: try the next one
44
+ if (run.error) fail(`arch-storyboard could not run ${step.script}: ${run.error.message}`);
45
+ return run.status ?? 1;
46
+ }
47
+ return null;
48
+ };
49
+
50
+ const [name, ...rawArgs] = process.argv.slice(2);
51
+ if (name === '--version' || name === '-v') { process.stdout.write(`${version}\n`); process.exit(0); }
52
+ if (name === '--help' || name === '-h') { process.stdout.write(usage()); process.exit(0); }
53
+ const command = commands[name];
54
+ if (!command) fail(`${name ? `Unknown command: ${name}\n` : ''}${usage()}`);
55
+ const flagged = command.flag && rawArgs.includes(command.flag);
56
+ const args = command.flag ? rawArgs.filter((a) => a !== command.flag) : rawArgs;
57
+ // `verify --help` goes to the script's own parser; the others need their positional arguments.
58
+ if (args.length < command.min && !(name === 'verify' && args.includes('--help'))) fail(`Missing arguments for ${name}.\n${usage()}`);
59
+
60
+ const status = runScript(command, args);
61
+ if (status === null) fail(command.missing || `arch-storyboard could not find an interpreter for ${command.script}`);
62
+ if (status !== 0 || !flagged) process.exit(status);
63
+
64
+ const after = runScript(command.then, command.then.pass(args));
65
+ if (after === null) fail(command.then.missing);
66
+ process.exit(after);
package/package.json CHANGED
@@ -1,13 +1,16 @@
1
1
  {
2
2
  "name": "arch-storyboard",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "type": "module",
5
5
  "description": "Build-time ELK layout + vanilla WAAPI runtime for offline animated architecture storyboards",
6
6
  "license": "MIT",
7
7
  "repository": { "type": "git", "url": "https://github.com/bassemZohdy/arch-storyboard.git" },
8
8
  "homepage": "https://github.com/bassemZohdy/arch-storyboard#readme",
9
9
  "keywords": ["pi-package", "architecture", "diagram", "storyboard", "skill"],
10
+ "bin": { "arch-storyboard": "bin/arch-storyboard.mjs" },
11
+ "engines": { "node": ">=20" },
10
12
  "files": [
13
+ "bin",
11
14
  "SKILL.md",
12
15
  "README.md",
13
16
  "RESULT.md",
package/plugins/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Provider wrappers
2
2
 
3
- The authored skill stays at the repository root. Development wrappers are thin and reference it; do not copy skill instructions into these files. `node scripts/package-plugins.mjs` materialises self-contained installable copies: `marketplace/plugins/arch-storyboard` (committed, for Claude marketplace), `plugins/opencode/skill/` (committed, for npm), and `dist/` (gitignored, for local validation). Regenerate those after any root skill edit.
3
+ The authored skill stays at the repository root. Development wrappers are thin and reference it; do not copy skill instructions into these files. `node scripts/package-plugins.mjs` materialises self-contained installable copies: `skills/arch-storyboard` (committed, Markdown only, for the Claude marketplace: it runs `npx arch-storyboard@1.0.1` and needs Node 20 or later), `plugins/opencode/skill/` (committed, for npm), and `dist/` (gitignored, for local validation). Regenerate those after any root skill edit.
4
4
 
5
5
  ## Pi
6
6
 
@@ -8,4 +8,4 @@ Invoke it as `/arch-storyboard:arch-storyboard` when installed as a plugin, or `
8
8
  /plugin install arch-storyboard --marketplace bassemZohdy/arch-storyboard
9
9
  ```
10
10
 
11
- Development uses symlinks to the repository root; `node scripts/package-plugins.mjs` materialises the self-contained marketplace artifact at `marketplace/plugins/arch-storyboard` and a local validation copy at `dist/claude-plugin`.
11
+ Development uses symlinks to the repository root; `node scripts/package-plugins.mjs` regenerates the Markdown-only marketplace plugin at `skills/arch-storyboard` (its `SKILL.md` runs `npx arch-storyboard@1.0.1`, Node 20 or later) and a local validation copy at `dist/claude-plugin`.
@@ -12,13 +12,16 @@ One HTML file, no network, no runtime libraries. ELK runs once at build time; a
12
12
  - Do not use: static diagrams, UML or sequence diagrams, user stories, editable diagrams.
13
13
 
14
14
  ## Workflow
15
- 1. **Gather** the nodes, connections and story from the user, or from the code/docs they point to. Decide layout *intent* yourself: `layer`, `order`, `ports`, `group`, `size`, `spread`, `gap`.
15
+ 1. **Gather** the nodes, connections and story from the user, or from the code/docs they point to. Settle the open story questions first with `references/interview.md`. Decide layout *intent* yourself: `layer`, `order`, `ports`, `group`, `size`, `spread`, `gap`.
16
16
  2. **Write** `spec.json` (data only — never coordinates or routes as x/y). See `references/spec-schema.md`.
17
17
  3. **Validate**: `node scripts/validate.mjs spec.json` — names the failing JSON path and the fix.
18
18
  4. **Build**: `node scripts/build.mjs spec.json out/` — validates, runs ELK once, checks geometry and text, writes `out/index.html`.
19
19
  5. **Verify**: `python3 scripts/verify.py spec.json out/ --shots shots/` — headless Chrome at 1280 px; see `references/quality-gates.md`.
20
20
  6. **Deliver** `out/index.html` (copy it to the caller's requested path) plus the spec. Never patch generated HTML to hide a defect: fix the spec, a hint or the runtime, then rebuild.
21
21
 
22
+ ## Export (optional)
23
+ `node scripts/export.mjs spec.json svg/` writes one standalone SVG per step (`step-1.svg`, `step-2.svg`, ...) from the same baked geometry as the page, for documents and slides; the files carry their own styling and make no external request. Through the CLI, `arch-storyboard export spec.json svg/ --png` also writes a PNG per step (Python 3 with playwright, and Chrome).
24
+
22
25
  ## Authoring rules
23
26
  - Nodes carry `size`, `layer`, `order`, `port sides`, `kind` and optional group membership. ELK decides positions and routes. A group that spans layers uses `"spanLayers": true`; its box is computed from its member cards at build time.
24
27
  - Text must fit at build time: short single-line titles/sub-lines; no runtime wrapping or measurement.
@@ -30,6 +33,7 @@ One HTML file, no network, no runtime libraries. ELK runs once at build time; a
30
33
  Screenshot every step (`verify.py --shots`), look at the images, then fix only spec hints (order, gaps, port sides, sizes, text) and rebuild. Stop after 3 rounds; report anything still imperfect.
31
34
 
32
35
  ## References
36
+ - `references/interview.md` — the questions to settle before writing a spec.
33
37
  - `references/spec-schema.md` — every field, short example, validator errors and fixes.
34
38
  - `references/layout-hints.md` — what works in ELK, what is ignored, and the build's geometry checks.
35
39
  - `references/visual-language.md` — data-driven packets/edges/badges/chips/legend and accessibility.
@@ -0,0 +1,57 @@
1
+ # Interview: settle the story before writing a spec
2
+
3
+ Use this at workflow step 1, before any JSON. A brief that says "show how X changes" leaves most of the story open, and every open point becomes a guess in the spec. Ask what the brief and the code do not already answer, in one message of at most five questions; where the user cannot say, propose a default, build with it and list it as a guess in your reply.
4
+
5
+ ## 1. Entities (nodes)
6
+
7
+ - Which parts does the story show? One short title each, and at most two short sub-lines (technology, role).
8
+ - Which kind is each part (user, front end, gateway, service, store, agent...)? Parts of one kind share a colour and an icon.
9
+ - Which belong together in a box (a team, a layer, a trust boundary)? That is a `group`; a group that crosses columns uses `spanLayers`.
10
+ - Which parts are new in the target? They get `from` and `newAt` at the step where they appear.
11
+
12
+ → `nodes[].title`, `sub`, `kind`, `group`, `from`, `newAt`; `kinds`; `groups`.
13
+
14
+ ## 2. Current and target state
15
+
16
+ - What does the first step show: the current state, exactly as it is today?
17
+ - What does the last step show: the target state, once everything has landed?
18
+ - Between the two: what is added, what is changed, what stays as it is? A part the viewer should expect but that does not exist yet can be shown `ghost` one step before it appears.
19
+
20
+ → `from`, `ghost`, `newAt`, `links[].from_step`.
21
+
22
+ ## 3. Steps
23
+
24
+ - How many steps? Four to seven read well; each one should add one idea.
25
+ - For each step: a short `title`, and a `caption` of one or two sentences saying what the viewer should notice.
26
+ - What appears in the step, and which journey (the ordered route a request takes through the nodes) plays?
27
+ - Is the order of reveal the order of the argument (problem, then change, then result)?
28
+
29
+ → `steps[].title`, `caption`, `journeys`, `checklist`.
30
+
31
+ ## 4. Traffic kinds
32
+
33
+ - What moves between the parts: requests, responses, events, agent actions, files?
34
+ - Which of them are round trips, and which are fire-and-forget?
35
+ - Request and response must differ by shape or fill, not colour alone. How else do the kinds differ?
36
+ - Keep the legend to the kinds the viewer needs; the build refuses more than six entries.
37
+
38
+ → `traffic` (colour, shape, filled, icon), `edgeKinds`, `legend`.
39
+
40
+ ## 5. Badges
41
+
42
+ - Which parts carry NEW, CHANGED, UNCHANGED or NOT YET, and from which step?
43
+ - Is a badge a rule ("every gateway is CHANGED from step 3") or a single part? A rule is a `badgeRules` entry; a single part is `badges`.
44
+
45
+ → `badgeRules`, `nodes[].badges`, `steps[].badges`.
46
+
47
+ ## 6. Chip wording
48
+
49
+ - Which moments need a small text label over a part while the animation runs ("consent checked", "tool call")?
50
+ - Chip wording is a few words, one line, no sentences. Pick the tone that matches the meaning: `ok` for success, `warn` for a refusal or a limit, `idle` for waiting, `def` for neutral.
51
+ - When does each chip appear relative to the journey (`at`, `offset`) and for how long (`dur`, 1.2–2.2 s reads well)?
52
+
53
+ → `steps[].chips` (`node`, `text`, `at`, `dur`, `tone`).
54
+
55
+ ## After the answers
56
+
57
+ Write the spec from the answers, validate, build and verify. In the reply, list each default you chose without asking as a guess, so the user can correct the story and not the diagram.
@@ -0,0 +1,144 @@
1
+ // Static export: one standalone SVG per step, drawn from the geometry the build baked into the page.
2
+ // Usage: node scripts/export.mjs spec.json out-dir -> out-dir/step-1.svg ... step-N.svg
3
+ import { spawnSync } from 'node:child_process';
4
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { dirname, join } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const dir = dirname(fileURLToPath(import.meta.url));
10
+ const read = (f) => readFileSync(join(dir, f), 'utf8');
11
+ const rnd = (v) => Math.round(v * 10) / 10;
12
+ const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
13
+
14
+ // The page holds the baked geometry as `const DATA={...};` on one line; read it back from a build.
15
+ export const bakedData = (html) => {
16
+ const start = html.indexOf('const DATA=') + 'const DATA='.length;
17
+ let depth = 0, inString = false;
18
+ for (let i = start; i < html.length; i++) {
19
+ const c = html[i];
20
+ if (inString) { if (c === '\\') i++; else if (c === '"') inString = false; continue; }
21
+ if (c === '"') inString = true;
22
+ else if (c === '{') depth++;
23
+ else if (c === '}' && --depth === 0) return JSON.parse(html.slice(start, i + 1));
24
+ }
25
+ throw new Error('export: no baked DATA found in the built page');
26
+ };
27
+
28
+ // Same state rules as scripts/runtime.js: a step is 1-based here.
29
+ const stateOf = (o, step) => (o.ghost || []).includes(step) ? 'ghost' : step >= (o.from || 1) ? 'on' : 'off';
30
+ const badgeOf = (data, n, step) => n.newAt === step ? 'new' : stateOf(n, step) === 'ghost' ? 'ghost'
31
+ : data.steps[step - 1]?.badges?.[n.id] || n.badges[step]
32
+ || data.badgeRules.find((r) => step >= r.from && r.kinds.includes(n.kind))?.badge || '';
33
+ const rounded = (pts, r = 8) => {
34
+ let d = 'M' + pts[0].join(' ');
35
+ for (let i = 1; i < pts.length - 1; i++) {
36
+ const [p, q, s] = [pts[i - 1], pts[i], pts[i + 1]];
37
+ const l1 = Math.hypot(q[0] - p[0], q[1] - p[1]), l2 = Math.hypot(s[0] - q[0], s[1] - q[1]), k = Math.min(r, l1 / 2, l2 / 2);
38
+ d += ` L${rnd(q[0] - (q[0] - p[0]) / l1 * k)} ${rnd(q[1] - (q[1] - p[1]) / l1 * k)} Q${q[0]} ${q[1]} ${rnd(q[0] + (s[0] - q[0]) / l2 * k)} ${rnd(q[1] + (s[1] - q[1]) / l2 * k)}`;
39
+ }
40
+ return d + ' L' + pts[pts.length - 1].join(' ');
41
+ };
42
+
43
+ const symbols = () => Object.fromEntries([...read('../assets/icons.txt').matchAll(/<symbol id="([^"]+)"[\s\S]*?<\/symbol>/g)].map((m) => [m[1], m[0]]));
44
+ // The page's own rules for what a step shows; motion-only rules (trail, packets, chips) are left out.
45
+ const pageCss = () => read('style.css').split('\n').filter((l) => /^(text\{|\.group|\.node|\.edge)|\.bdg/.test(l)).join('\n');
46
+
47
+ // Text must not depend on the page's CSS (slides and document tools often ignore <style>), so each
48
+ // <text> carries its own presentation attributes. Badge text colours are read from the page's rules.
49
+ const FONT = 'Arial,Helvetica,sans-serif';
50
+ const badgeFill = (badge, fallback) => (pageCss().match(new RegExp(String.raw`\.bdg\.${badge} text\{fill:(#[0-9a-fA-F]{3,8})\}`)) || [])[1] || fallback;
51
+ const text = (a, content) => `<text${Object.entries({ ...a, 'font-family': FONT }).map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}>${esc(content)}</text>`;
52
+
53
+ // A shape's presentation attributes, read from the page's own CSS rules (in file order, later rules win),
54
+ // so the export cannot drift from the page. var(--x) is resolved against the theme and the node colour.
55
+ const cssRules = () => [...pageCss().matchAll(/([^{}]+)\{([^}]*)\}/g)].map(([, sel, body]) => ({
56
+ sels: sel.split(',').map((s) => s.trim()),
57
+ decls: body.split(';').map((d) => d.trim()).filter(Boolean).map((d) => [d.slice(0, d.indexOf(':')).trim(), d.slice(d.indexOf(':') + 1).trim()]),
58
+ }));
59
+ const PRESENTATION = new Set(['fill', 'stroke', 'stroke-width', 'stroke-dasharray', 'opacity', 'color']);
60
+ const cssAttrs = (selectors, vars = {}) => {
61
+ const out = {};
62
+ for (const rule of cssRules()) {
63
+ if (!rule.sels.some((s) => selectors.includes(s))) continue;
64
+ for (const [k, v] of rule.decls) if (PRESENTATION.has(k)) out[k] = v.replace(/var\((--[\w-]+)\)/g, (_, name) => vars[name] ?? '');
65
+ }
66
+ const rgba = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/.exec(out.fill || '');
67
+ if (rgba) { out.fill = '#' + rgba.slice(1, 4).map((c) => Number(c).toString(16).padStart(2, '0')).join(''); out['fill-opacity'] = rgba[4]; }
68
+ return out;
69
+ };
70
+ const asAttrs = (o) => Object.entries(o).map(([k, v]) => ` ${k}="${esc(v)}"`).join('');
71
+
72
+ export function renderStep(data, step, icons = symbols()) {
73
+ const [x, y, w, h] = data.view, t = data.theme;
74
+ const themeVars = { '--bg': t.bg, '--panel': t.panel, '--card': t.card, '--ink': t.ink, '--mute': t.muted };
75
+ const used = new Set();
76
+ const useIcon = (name, attrs) => { if (!name || !icons[`i-${name}`]) return ''; used.add(`i-${name}`); return `<use href="#i-${esc(name)}" ${attrs}/>`; };
77
+ const nodes = new Map(data.nodes.map((n) => [n.id, n]));
78
+ const edgeState = (ed) => {
79
+ const s = [stateOf(ed, step), stateOf(nodes.get(ed.a), step), stateOf(nodes.get(ed.b), step)];
80
+ return s.includes('off') ? 'off' : s.includes('ghost') ? 'ghost' : 'on';
81
+ };
82
+
83
+ const groups = data.groups.filter((g) => step >= (g.from || 1)).map((g) => {
84
+ let tx = g.x + 12, icon = '';
85
+ if (g.icon) { icon = useIcon(g.icon, `x="${tx}" y="${rnd(g.y + 5)}" width="15" height="15"${asAttrs(cssAttrs(['.group use'], themeVars))}`); tx += 20; }
86
+ return `<g class="group" data-group="${esc(g.id)}" data-state="on"><rect x="${g.x}" y="${g.y}" width="${g.w}" height="${g.h}" rx="13"${asAttrs(cssAttrs(['.group rect'], themeVars))}/>${icon}${text({ x: tx, y: rnd(g.spanLayers ? g.y + 18 : g.y + g.h - 6), 'font-size': 12, 'font-weight': 700, 'letter-spacing': 0.72, fill: t.muted }, g.title.toUpperCase())}</g>`;
87
+ });
88
+ const edges = data.edges.map((ed) => [ed, edgeState(ed)]).filter(([, s]) => s !== 'off').map(([ed, s]) => {
89
+ const k = data.edgeKinds[ed.kind], dash = k.dash ? ` stroke-dasharray="${esc(k.dash)}"` : '';
90
+ const ghost = s === 'ghost' ? asAttrs(cssAttrs(['.edge[data-state=ghost]'], themeVars)) : '';
91
+ return `<g class="edge" data-id="${esc(ed.id)}" data-kind="${esc(ed.kind)}" data-state="${s}"${ghost}><path d="${rounded(ed.pts)}" stroke="${k.color}" stroke-width="${k.width || 2}"${dash}${asAttrs({ fill: cssAttrs(['.edge path']).fill || 'none' })} marker-end="url(#m-${esc(ed.kind)})"/></g>`;
92
+ });
93
+ const shown = data.nodes.filter((n) => stateOf(n, step) !== 'off');
94
+ const nodeSvg = shown.map((n) => {
95
+ const badge = badgeOf(data, n, step), state = stateOf(n, step), vars = { ...themeVars, '--c': n.color };
96
+ const ghost = state === 'ghost', changed = badge === 'changed';
97
+ const card = cssAttrs(['.node .card', ...(changed ? ['.node.changed .card'] : []), ...(ghost ? ['.node[data-state=ghost] .card'] : [])], vars);
98
+ const bar = cssAttrs(['.node .bar', ...(changed ? ['.node.changed .bar'] : [])], vars);
99
+ const icon = n.icon ? useIcon(n.icon, `x="11" y="${rnd(n.h / 2 - 9)}" width="18" height="18"${asAttrs(cssAttrs(['.node use'], vars))}`) : '';
100
+ const lines = n.lines.map((l) => text({ class: l.cls, x: l.x, y: l.y, ...(l.cls === 't' ? { 'font-size': 13, 'font-weight': 700, fill: t.ink } : { 'font-size': 12, fill: t.muted }) }, l.text)).join('');
101
+ return `<g class="node${badge === 'changed' ? ' changed' : ''}" data-id="${esc(n.id)}" data-state="${stateOf(n, step)}" transform="translate(${n.x} ${n.y})" style="--c:${n.color}"${ghost ? asAttrs(cssAttrs(['.node[data-state=ghost]'], vars)) : ''}>`
102
+ + `<rect class="card" width="${n.w}" height="${n.h}" rx="8"${asAttrs(card)}/><rect class="bar" x="0" y="8" width="4" height="${rnd(n.h - 16)}" rx="2"${asAttrs(bar)}/>${icon}${lines}</g>`;
103
+ });
104
+ const badges = shown.map((n) => [n, badgeOf(data, n, step)]).filter(([, b]) => b).map(([n, b]) => {
105
+ const bw = data.badgeW[b];
106
+ return `<g class="bdg ${b}" data-node="${esc(n.id)}" transform="translate(${rnd(n.x + n.w - bw - 6)} ${n.y})"><rect width="${bw}" height="16" rx="8" y="-12"${asAttrs(cssAttrs(['.bdg rect', `.bdg.${b} rect`], themeVars))}/>${text({ x: rnd(bw / 2), y: 0, 'font-size': 12, 'font-weight': 700, 'text-anchor': 'middle', fill: badgeFill(b, t.ink) }, data.badgeLabels[b])}</g>`;
107
+ });
108
+ const markers = Object.entries(data.edgeKinds).map(([k, v]) =>
109
+ `<marker id="m-${esc(k)}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 1l9 4-9 4z" fill="${v.color}"/></marker>`).join('');
110
+ const st = data.steps[step - 1] || {};
111
+ const title = [data.title, st.title].filter(Boolean).join(' - ');
112
+ const css = `:root{--bg:${t.bg};--panel:${t.panel};--card:${t.card};--ink:${t.ink};--mute:${t.muted}}\nsvg text{font-family:Arial,Helvetica,sans-serif}\n${pageCss()}`;
113
+
114
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${x} ${y} ${w} ${h}" width="${w}" height="${h}" role="img">`
115
+ + `<title>${esc(title)}</title>${st.caption ? `<desc>${esc(st.caption)}</desc>` : ''}`
116
+ + `<defs>${markers}${[...used].map((id) => icons[id]).join('')}<style>${css}</style></defs>`
117
+ + `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${t.bg}"/>`
118
+ + `<g id="L-groups">${groups.join('')}</g><g id="L-edges">${edges.join('')}</g><g id="L-nodes">${nodeSvg.join('')}</g><g id="L-badges">${badges.join('')}</g></svg>\n`;
119
+ }
120
+
121
+ export function exportSteps(specPath, outDir) {
122
+ const tmp = mkdtempSync(join(tmpdir(), 'arch-storyboard-export-'));
123
+ try {
124
+ const built = spawnSync(process.execPath, [join(dir, 'build.mjs'), specPath, tmp], { encoding: 'utf8' });
125
+ if (built.status !== 0) { process.stderr.write(built.stderr); process.exit(built.status || 1); }
126
+ const data = bakedData(readFileSync(join(tmp, 'index.html'), 'utf8'));
127
+ const icons = symbols();
128
+ mkdirSync(outDir, { recursive: true });
129
+ const files = data.steps.map((_, i) => {
130
+ const file = join(outDir, `step-${i + 1}.svg`);
131
+ writeFileSync(file, renderStep(data, i + 1, icons));
132
+ return file;
133
+ });
134
+ return files;
135
+ } finally { rmSync(tmp, { recursive: true, force: true }); }
136
+ }
137
+
138
+ import { pathToFileURL } from 'node:url';
139
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
140
+ const [spec, out] = process.argv.slice(2);
141
+ if (!spec || !out) { process.stderr.write('Usage: node scripts/export.mjs <spec.json> <out-dir>\n'); process.exit(2); }
142
+ const files = exportSteps(spec, out);
143
+ console.log(`${spec} -> ${files.length} SVGs in ${out}`);
144
+ }
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env python3
2
+ """Render every step-N.svg in a folder to step-N.png with headless Chrome (Playwright).
3
+ Usage: python3 scripts/export_png.py OUT_DIR
4
+ Exit codes: 0 done, 2 bad input, 3 no Chrome could be started. CHROME_PATH overrides the browser."""
5
+ import os, re, sys
6
+ from pathlib import Path
7
+ from playwright.sync_api import sync_playwright
8
+
9
+
10
+ def launch(p):
11
+ attempts = []
12
+ if os.environ.get('CHROME_PATH'):
13
+ attempts.append({'executable_path': os.environ['CHROME_PATH']})
14
+ attempts += [{'channel': 'chrome'}, {}]
15
+ for kwargs in attempts:
16
+ try:
17
+ return p.chromium.launch(**kwargs)
18
+ except Exception:
19
+ continue
20
+ return None
21
+
22
+
23
+ def main(out):
24
+ folder = Path(out)
25
+ files = sorted(folder.glob('step-*.svg'), key=lambda f: int(re.search(r'(\d+)', f.stem).group(1)))
26
+ if not files:
27
+ print(f'export_png: no step-N.svg files in {out}', file=sys.stderr)
28
+ return 2
29
+ with sync_playwright() as p:
30
+ browser = launch(p)
31
+ if browser is None:
32
+ print('export_png: could not start Chrome; install Chrome or set CHROME_PATH', file=sys.stderr)
33
+ return 3
34
+ for svg in files:
35
+ head = svg.read_text(encoding='utf8')[:400]
36
+ w = int(float(re.search(r'width="([\d.]+)"', head).group(1)))
37
+ h = int(float(re.search(r'height="([\d.]+)"', head).group(1)))
38
+ page = browser.new_page(viewport={'width': w, 'height': h}, device_scale_factor=2)
39
+ page.goto(svg.resolve().as_uri())
40
+ page.screenshot(path=str(svg.with_suffix('.png')))
41
+ page.close()
42
+ browser.close()
43
+ print(f'{len(files)} PNGs in {out}')
44
+ return 0
45
+
46
+
47
+ if __name__ == '__main__':
48
+ if len(sys.argv) != 2:
49
+ print('Usage: python3 scripts/export_png.py OUT_DIR', file=sys.stderr)
50
+ sys.exit(2)
51
+ sys.exit(main(sys.argv[1]))
@@ -1,7 +1,8 @@
1
1
  // Materialise provider artifacts from the canonical root skill. dist/ and marketplace/ are generated, not authored.
2
- import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { toPluginDoc } from './plugin-docs.mjs';
5
6
 
6
7
  const root = join(dirname(fileURLToPath(import.meta.url)), '..');
7
8
  const skillFiles = ['SKILL.md', 'references', 'scripts', 'assets'];
@@ -9,15 +10,20 @@ const copySkill = (to) => skillFiles.forEach((f) => cpSync(join(root, f), join(t
9
10
  const clean = (p) => rmSync(p, { recursive: true, force: true });
10
11
  const icon = join(root, 'assets/icon.png');
11
12
 
12
- // Committed Claude marketplace artifact: self-contained, no out-of-folder symlinks.
13
- const market = join(root, 'marketplace/plugins/arch-storyboard');
14
- clean(market);
15
- mkdirSync(join(market, '.claude-plugin'), { recursive: true });
16
- cpSync(join(root, 'plugins/claude/.claude-plugin/plugin.json'), join(market, '.claude-plugin/plugin.json'));
17
- cpSync(join(root, 'plugins/claude/README.md'), join(market, 'README.md'));
18
- cpSync(icon, join(market, '.claude-plugin/icon.png'));
19
- copySkill(market);
20
- if (existsSync(join(root, 'LICENSE'))) cpSync(join(root, 'LICENSE'), join(market, 'LICENSE'));
13
+ // Committed Claude plugin: Markdown only, so the directory accepts it from any organization. The builder
14
+ // ships on npm (bin/arch-storyboard.mjs); the plugin's SKILL.md is authored, its references are generated.
15
+ const version = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version;
16
+ const plugin = join(root, 'skills/arch-storyboard');
17
+ const pluginSkill = join(plugin, 'skills/arch-storyboard');
18
+ clean(join(root, 'marketplace/plugins')); // retired: the marketplace now points at skills/arch-storyboard
19
+ clean(join(pluginSkill, 'references'));
20
+ clean(join(pluginSkill, 'assets'));
21
+ mkdirSync(join(pluginSkill, 'references'), { recursive: true });
22
+ mkdirSync(join(pluginSkill, 'assets'), { recursive: true });
23
+ for (const f of readdirSync(join(root, 'references')).filter((n) => n.endsWith('.md'))) {
24
+ writeFileSync(join(pluginSkill, 'references', f), toPluginDoc(readFileSync(join(root, 'references', f), 'utf8'), version));
25
+ }
26
+ cpSync(join(root, 'assets/icons.txt'), join(pluginSkill, 'assets/icons.txt'));
21
27
 
22
28
  // Published npm plugin needs its own skill copy.
23
29
  const ocSkill = join(root, 'plugins/opencode/skill');
@@ -28,12 +34,7 @@ copySkill(ocSkill);
28
34
  const dist = join(root, 'dist');
29
35
  for (const name of ['claude-plugin', 'opencode-plugin']) clean(join(dist, name));
30
36
  const claude = join(dist, 'claude-plugin');
31
- mkdirSync(join(claude, '.claude-plugin'), { recursive: true });
32
- cpSync(join(market, '.claude-plugin/plugin.json'), join(claude, '.claude-plugin/plugin.json'));
33
- cpSync(join(market, '.claude-plugin/icon.png'), join(claude, '.claude-plugin/icon.png'));
34
- cpSync(join(market, 'README.md'), join(claude, 'README.md'));
35
- mkdirSync(join(claude, 'skills/arch-storyboard'), { recursive: true });
36
- copySkill(join(claude, 'skills/arch-storyboard'));
37
+ cpSync(plugin, claude, { recursive: true });
37
38
 
38
39
  const oc = join(dist, 'opencode-plugin');
39
40
  mkdirSync(oc, { recursive: true });
@@ -41,4 +42,4 @@ cpSync(join(root, 'plugins/opencode/package.json'), join(oc, 'package.json'));
41
42
  cpSync(join(root, 'plugins/opencode/index.js'), join(oc, 'index.js'));
42
43
  copySkill(oc);
43
44
 
44
- console.log(`packaged: ${market}\npackaged: ${ocSkill}\npackaged: ${claude}\npackaged: ${oc}`);
45
+ console.log(`packaged: ${plugin}\npackaged: ${ocSkill}\npackaged: ${claude}\npackaged: ${oc}`);
@@ -0,0 +1,16 @@
1
+ // The Claude plugin ships Markdown only; its copy of the reference docs calls the npm package, not repo scripts.
2
+ const rules = (version) => {
3
+ const npx = `npx arch-storyboard@${version}`;
4
+ return [
5
+ [/^npm install[^\n]*\n/gm, ''],
6
+ [/node scripts\/validate\.mjs\s+tests\/fixture-a\/spec\.json/g, `${npx} validate spec.json`],
7
+ [/node scripts\/build\.mjs\s+tests\/fixture-a\/spec\.json tests\/out\/a/g, `${npx} build spec.json out/`],
8
+ [/python3 scripts\/verify\.py tests\/fixture-a\/spec\.json tests\/out\/a --shots tests\/screenshots\/a/g, `${npx} verify spec.json out/ --shots shots/`],
9
+ [/`node scripts\/build\.mjs`/g, '`arch-storyboard build`'],
10
+ [/`verify\.py` needs/g, '`verify` needs'],
11
+ [/`scripts\/metrics\.mjs`/g, 'its text-metrics module'],
12
+ [/`scripts\/validate\.mjs`/g, 'the packaged validator'],
13
+ ];
14
+ };
15
+
16
+ export const toPluginDoc = (text, version) => rules(version).reduce((t, [from, to]) => t.replace(from, to), text);
@@ -7,6 +7,8 @@ const obj = (v) => v && typeof v === 'object' && !Array.isArray(v);
7
7
  const hex = (v) => typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v);
8
8
  const SHAPES = ['circle', 'square', 'diamond', 'triangle'];
9
9
  export const BADGES = { new: 'NEW', changed: 'CHANGED', unchanged: 'UNCHANGED', ghost: 'NOT YET' };
10
+ // Icon names the page can draw: the symbols in assets/icons.txt.
11
+ const ICONS = new Set([...readFileSync(new URL('../assets/icons.txt', import.meta.url), 'utf8').matchAll(/<symbol id="i-([^"]+)"/g)].map((m) => m[1]));
10
12
 
11
13
  export function validate(s) {
12
14
  const fail = (p, m, f) => { throw new Error(`Invalid spec at ${p}: ${m}. Fix: ${f}`); };
@@ -17,13 +19,15 @@ export function validate(s) {
17
19
  for (const key of ['nodes', 'links', 'steps']) ok(Array.isArray(s[key]) && s[key].length, `$.${key}`, 'must be a non-empty array', `add at least one ${key.slice(0, -1)}`);
18
20
 
19
21
  const kinds = s.kinds || {}, edgeKinds = s.edgeKinds || {}, traffic = s.traffic || {};
20
- for (const [k, v] of Object.entries(kinds)) ok(hex(v.color), `$.kinds.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour');
22
+ const checkIcon = (path, name) => ok(name === undefined || ICONS.has(name), path, `unknown icon "${name}"`, `use one of ${[...ICONS].join(', ')}`);
23
+ for (const [k, v] of Object.entries(kinds)) { ok(hex(v.color), `$.kinds.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour'); checkIcon(`$.kinds.${k}.icon`, v.icon); }
21
24
  for (const [k, v] of Object.entries(edgeKinds)) {
22
25
  ok(hex(v.color), `$.edgeKinds.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour');
23
26
  ok(v.dash === undefined || typeof v.dash === 'string', `$.edgeKinds.${k}.dash`, 'must be a string', 'use a CSS dash array like "7 4" or omit it');
24
27
  ok(v.width === undefined || typeof v.width === 'number', `$.edgeKinds.${k}.width`, 'must be a number', 'use a stroke width number or omit it');
25
28
  }
26
29
  for (const [k, v] of Object.entries(traffic)) {
30
+ checkIcon(`$.traffic.${k}.icon`, v.icon);
27
31
  ok(hex(v.color), `$.traffic.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour');
28
32
  ok(SHAPES.includes(v.shape), `$.traffic.${k}.shape`, `must be one of ${SHAPES.join(', ')}`, 'choose a listed shape');
29
33
  ok(typeof v.filled === 'boolean', `$.traffic.${k}.filled`, 'must be a boolean', 'set filled true or false');
@@ -40,12 +44,17 @@ export function validate(s) {
40
44
  });
41
45
 
42
46
  const ids = new Set();
47
+ const groupIds = new Set((s.groups || []).map((g) => g.id));
43
48
  s.nodes.forEach((n, i) => {
44
49
  const p = `$.nodes[${i}]`;
50
+ ok(n.group === undefined || groupIds.has(n.group), `${p}.group`, `unknown group "${n.group}"`, 'declare it in groups or remove group from the node');
45
51
  ok(typeof n.id === 'string' && !ids.has(n.id), `${p}.id`, 'missing or duplicate node id', 'use a unique string id');
46
52
  ids.add(n.id);
47
53
  for (const bad of ['x', 'y', 'cx', 'cy', 'pos', 'position']) ok(!(bad in n), `${p}.${bad}`, 'specs contain no coordinates', 'delete it; ELK decides geometry from layer/order/ports');
48
54
  ok(typeof n.kind === 'string' && (kinds[n.kind] || n.kind), `${p}.kind`, 'must be a string', 'name a key from kinds or add one');
55
+ // Kinds are optional, but once a spec declares some, a node's kind must be one of them.
56
+ ok(!Object.keys(kinds).length || kinds[n.kind], `${p}.kind`, `unknown node kind "${n.kind}"`, `use one of ${Object.keys(kinds).join(', ')} or add it to kinds`);
57
+ checkIcon(`${p}.icon`, n.icon);
49
58
  ok(typeof n.title === 'string' && n.title.length, `${p}.title`, 'must be a non-empty string', 'add a short title');
50
59
  ok(Array.isArray(n.sub) && n.sub.every((x) => typeof x === 'string'), `${p}.sub`, 'must be an array of strings', 'use [] or short single-line strings');
51
60
  ok(Array.isArray(n.size) && n.size.length === 2 && n.size.every((v) => typeof v === 'number' && v > 0), `${p}.size`, 'must be [width, height]', 'give a positive [w,h] size hint');
@@ -61,6 +70,7 @@ export function validate(s) {
61
70
  const portOf = (ref) => { const [id, pn] = String(ref).split('.'); const n = s.nodes.find((x) => x.id === id); return n && n.ports.some((p) => p === pn || p.endsWith(':' + pn)) ? id : null; };
62
71
  const pairs = new Set();
63
72
  const linkIds = new Set();
73
+ const linkKeys = new Set();
64
74
  s.links.forEach((l, i) => {
65
75
  const p = `$.links[${i}]`;
66
76
  ok(typeof l.id === 'string' && !linkIds.has(l.id), `${p}.id`, 'missing or duplicate link id', 'use a unique string id');
@@ -68,11 +78,18 @@ export function validate(s) {
68
78
  ok(portOf(l.from), `${p}.from`, `unknown port "${l.from}"`, 'use an existing node.port from nodes[].ports');
69
79
  ok(portOf(l.to), `${p}.to`, `unknown port "${l.to}"`, 'use an existing node.port from nodes[].ports');
70
80
  ok(edgeKinds[l.kind], `${p}.kind`, 'unknown edge kind', `add it to edgeKinds or use ${Object.keys(edgeKinds).join(', ')}`);
81
+ const declared = `${l.from}>${l.to}>${l.kind}`;
82
+ ok(!linkKeys.has(declared), p, `link ${l.from} -> ${l.to} (${l.kind}) is declared more than once`, 'delete the repeat, or give it another kind if it means something else');
83
+ linkKeys.add(declared);
71
84
  pairs.add([portOf(l.from), portOf(l.to)].sort().join('~'));
72
85
  });
86
+ const seenGroups = new Set();
73
87
  (s.groups || []).forEach((g, i) => {
74
88
  const p = `$.groups[${i}]`;
75
89
  ok(typeof g.id === 'string', `${p}.id`, 'must be a string', 'add a unique group id');
90
+ checkIcon(`${p}.icon`, g.icon);
91
+ ok(!seenGroups.has(g.id), `${p}.id`, `duplicate group id "${g.id}"`, 'give each group its own id');
92
+ seenGroups.add(g.id);
76
93
  ok(!g.spanLayers || g.layer === undefined, `${p}.layer`, 'a layer-spanning group needs no layer', 'remove layer or set spanLayers false');
77
94
  ok(g.gapNode === undefined || (typeof g.gapNode === 'number' && g.gapNode > 0), `${p}.gapNode`, 'must be a positive number', 'use a positive row gap or omit it');
78
95
  ok(g.padBottom === undefined || (typeof g.padBottom === 'number' && g.padBottom >= 0), `${p}.padBottom`, 'must be a non-negative number', 'use a padding number or omit it');
@@ -80,8 +97,12 @@ export function validate(s) {
80
97
  const members = s.nodes.filter((n) => n.group === g.id);
81
98
  ok(members.length, `${p}.id`, 'no nodes belong to this group', 'set group on at least one node or delete the group');
82
99
  });
100
+ const nodeById = new Map(s.nodes.map((n) => [n.id, n]));
83
101
  s.steps.forEach((st, i) => {
84
102
  const p = `$.steps[${i}]`;
103
+ // A node exists at a step from its first step on, or while it is ghosted (shown as "not yet").
104
+ const present = (id) => { const n = nodeById.get(id); return !n || (n.from || 1) <= i + 1 || (n.ghost || []).includes(i + 1); };
105
+ const absent = (id) => [`node "${id}" does not exist at step ${i + 1}`, `set its from to ${i + 1} or earlier, or add ${i + 1} to its ghost list`];
85
106
  ok(typeof st.title === 'string' && typeof st.caption === 'string', `${p}`, 'title and caption are required strings', 'add both');
86
107
  const jids = new Set();
87
108
  (st.journeys || []).forEach((j, k) => {
@@ -95,6 +116,7 @@ export function validate(s) {
95
116
  }
96
117
  ok(Array.isArray(j.route) && j.route.length >= 2, `${q}.route`, 'needs at least two node ids', 'list ordered node ids for the hops');
97
118
  j.route.forEach((id, h) => ok(ids.has(id), `${q}.route[${h}]`, `unknown node "${id}"`, 'use an id from nodes[]'));
119
+ j.route.forEach((id, h) => ok(present(id), `${q}.route[${h}]`, ...absent(id)));
98
120
  j.route.slice(1).forEach((b, h) => ok(pairs.has([j.route[h], b].sort().join('~')), `${q}.route[${h + 1}]`, `no link between ${j.route[h]} and ${b}`, 'add the link or fix the route order'));
99
121
  const ref = (x, where) => {
100
122
  if (typeof x === 'number') return;
@@ -106,6 +128,7 @@ export function validate(s) {
106
128
  (st.chips || []).forEach((c, k) => {
107
129
  const q = `${p}.chips[${k}]`;
108
130
  ok(ids.has(c.node), `${q}.node`, 'unknown node', 'use an id from nodes[]');
131
+ ok(present(c.node), `${q}.node`, ...absent(c.node));
109
132
  ok(typeof c.text === 'string' && textWidth(c.text, 12) <= 240, `${q}.text`, 'chip text is too long for a status pill', 'shorten it to at most about 30 characters');
110
133
  ok(typeof c.dur === 'number' && c.dur > 0, `${q}.dur`, 'must be a positive number', 'set a duration in seconds');
111
134
  const m = typeof c.at === 'string' && /^([\w-]+)\.(start|turn|end)$/.exec(c.at);
@@ -114,6 +137,7 @@ export function validate(s) {
114
137
  for (const key of ['appear', 'ghost']) (st[key] || []).forEach((id, k) => ok(ids.has(id), `${p}.${key}[${k}]`, 'unknown node', 'use an id from nodes[]'));
115
138
  for (const [id, b] of Object.entries(st.badges || {})) {
116
139
  ok(ids.has(id), `${p}.badges.${id}`, 'unknown node', 'use an id from nodes[]');
140
+ ok(present(id), `${p}.badges.${id}`, ...absent(id));
117
141
  ok(BADGES[b], `${p}.badges.${id}`, `unknown badge "${b}"`, `use ${Object.keys(BADGES).join(', ')}`);
118
142
  }
119
143
  });
@@ -0,0 +1,57 @@
1
+ # Interview: settle the story before writing a spec
2
+
3
+ Use this at workflow step 1, before any JSON. A brief that says "show how X changes" leaves most of the story open, and every open point becomes a guess in the spec. Ask what the brief and the code do not already answer, in one message of at most five questions; where the user cannot say, propose a default, build with it and list it as a guess in your reply.
4
+
5
+ ## 1. Entities (nodes)
6
+
7
+ - Which parts does the story show? One short title each, and at most two short sub-lines (technology, role).
8
+ - Which kind is each part (user, front end, gateway, service, store, agent...)? Parts of one kind share a colour and an icon.
9
+ - Which belong together in a box (a team, a layer, a trust boundary)? That is a `group`; a group that crosses columns uses `spanLayers`.
10
+ - Which parts are new in the target? They get `from` and `newAt` at the step where they appear.
11
+
12
+ → `nodes[].title`, `sub`, `kind`, `group`, `from`, `newAt`; `kinds`; `groups`.
13
+
14
+ ## 2. Current and target state
15
+
16
+ - What does the first step show: the current state, exactly as it is today?
17
+ - What does the last step show: the target state, once everything has landed?
18
+ - Between the two: what is added, what is changed, what stays as it is? A part the viewer should expect but that does not exist yet can be shown `ghost` one step before it appears.
19
+
20
+ → `from`, `ghost`, `newAt`, `links[].from_step`.
21
+
22
+ ## 3. Steps
23
+
24
+ - How many steps? Four to seven read well; each one should add one idea.
25
+ - For each step: a short `title`, and a `caption` of one or two sentences saying what the viewer should notice.
26
+ - What appears in the step, and which journey (the ordered route a request takes through the nodes) plays?
27
+ - Is the order of reveal the order of the argument (problem, then change, then result)?
28
+
29
+ → `steps[].title`, `caption`, `journeys`, `checklist`.
30
+
31
+ ## 4. Traffic kinds
32
+
33
+ - What moves between the parts: requests, responses, events, agent actions, files?
34
+ - Which of them are round trips, and which are fire-and-forget?
35
+ - Request and response must differ by shape or fill, not colour alone. How else do the kinds differ?
36
+ - Keep the legend to the kinds the viewer needs; the build refuses more than six entries.
37
+
38
+ → `traffic` (colour, shape, filled, icon), `edgeKinds`, `legend`.
39
+
40
+ ## 5. Badges
41
+
42
+ - Which parts carry NEW, CHANGED, UNCHANGED or NOT YET, and from which step?
43
+ - Is a badge a rule ("every gateway is CHANGED from step 3") or a single part? A rule is a `badgeRules` entry; a single part is `badges`.
44
+
45
+ → `badgeRules`, `nodes[].badges`, `steps[].badges`.
46
+
47
+ ## 6. Chip wording
48
+
49
+ - Which moments need a small text label over a part while the animation runs ("consent checked", "tool call")?
50
+ - Chip wording is a few words, one line, no sentences. Pick the tone that matches the meaning: `ok` for success, `warn` for a refusal or a limit, `idle` for waiting, `def` for neutral.
51
+ - When does each chip appear relative to the journey (`at`, `offset`) and for how long (`dur`, 1.2–2.2 s reads well)?
52
+
53
+ → `steps[].chips` (`node`, `text`, `at`, `dur`, `tone`).
54
+
55
+ ## After the answers
56
+
57
+ Write the spec from the answers, validate, build and verify. In the reply, list each default you chose without asking as a guess, so the user can correct the story and not the diagram.
@@ -0,0 +1,144 @@
1
+ // Static export: one standalone SVG per step, drawn from the geometry the build baked into the page.
2
+ // Usage: node scripts/export.mjs spec.json out-dir -> out-dir/step-1.svg ... step-N.svg
3
+ import { spawnSync } from 'node:child_process';
4
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { dirname, join } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const dir = dirname(fileURLToPath(import.meta.url));
10
+ const read = (f) => readFileSync(join(dir, f), 'utf8');
11
+ const rnd = (v) => Math.round(v * 10) / 10;
12
+ const esc = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
13
+
14
+ // The page holds the baked geometry as `const DATA={...};` on one line; read it back from a build.
15
+ export const bakedData = (html) => {
16
+ const start = html.indexOf('const DATA=') + 'const DATA='.length;
17
+ let depth = 0, inString = false;
18
+ for (let i = start; i < html.length; i++) {
19
+ const c = html[i];
20
+ if (inString) { if (c === '\\') i++; else if (c === '"') inString = false; continue; }
21
+ if (c === '"') inString = true;
22
+ else if (c === '{') depth++;
23
+ else if (c === '}' && --depth === 0) return JSON.parse(html.slice(start, i + 1));
24
+ }
25
+ throw new Error('export: no baked DATA found in the built page');
26
+ };
27
+
28
+ // Same state rules as scripts/runtime.js: a step is 1-based here.
29
+ const stateOf = (o, step) => (o.ghost || []).includes(step) ? 'ghost' : step >= (o.from || 1) ? 'on' : 'off';
30
+ const badgeOf = (data, n, step) => n.newAt === step ? 'new' : stateOf(n, step) === 'ghost' ? 'ghost'
31
+ : data.steps[step - 1]?.badges?.[n.id] || n.badges[step]
32
+ || data.badgeRules.find((r) => step >= r.from && r.kinds.includes(n.kind))?.badge || '';
33
+ const rounded = (pts, r = 8) => {
34
+ let d = 'M' + pts[0].join(' ');
35
+ for (let i = 1; i < pts.length - 1; i++) {
36
+ const [p, q, s] = [pts[i - 1], pts[i], pts[i + 1]];
37
+ const l1 = Math.hypot(q[0] - p[0], q[1] - p[1]), l2 = Math.hypot(s[0] - q[0], s[1] - q[1]), k = Math.min(r, l1 / 2, l2 / 2);
38
+ d += ` L${rnd(q[0] - (q[0] - p[0]) / l1 * k)} ${rnd(q[1] - (q[1] - p[1]) / l1 * k)} Q${q[0]} ${q[1]} ${rnd(q[0] + (s[0] - q[0]) / l2 * k)} ${rnd(q[1] + (s[1] - q[1]) / l2 * k)}`;
39
+ }
40
+ return d + ' L' + pts[pts.length - 1].join(' ');
41
+ };
42
+
43
+ const symbols = () => Object.fromEntries([...read('../assets/icons.txt').matchAll(/<symbol id="([^"]+)"[\s\S]*?<\/symbol>/g)].map((m) => [m[1], m[0]]));
44
+ // The page's own rules for what a step shows; motion-only rules (trail, packets, chips) are left out.
45
+ const pageCss = () => read('style.css').split('\n').filter((l) => /^(text\{|\.group|\.node|\.edge)|\.bdg/.test(l)).join('\n');
46
+
47
+ // Text must not depend on the page's CSS (slides and document tools often ignore <style>), so each
48
+ // <text> carries its own presentation attributes. Badge text colours are read from the page's rules.
49
+ const FONT = 'Arial,Helvetica,sans-serif';
50
+ const badgeFill = (badge, fallback) => (pageCss().match(new RegExp(String.raw`\.bdg\.${badge} text\{fill:(#[0-9a-fA-F]{3,8})\}`)) || [])[1] || fallback;
51
+ const text = (a, content) => `<text${Object.entries({ ...a, 'font-family': FONT }).map(([k, v]) => ` ${k}="${esc(v)}"`).join('')}>${esc(content)}</text>`;
52
+
53
+ // A shape's presentation attributes, read from the page's own CSS rules (in file order, later rules win),
54
+ // so the export cannot drift from the page. var(--x) is resolved against the theme and the node colour.
55
+ const cssRules = () => [...pageCss().matchAll(/([^{}]+)\{([^}]*)\}/g)].map(([, sel, body]) => ({
56
+ sels: sel.split(',').map((s) => s.trim()),
57
+ decls: body.split(';').map((d) => d.trim()).filter(Boolean).map((d) => [d.slice(0, d.indexOf(':')).trim(), d.slice(d.indexOf(':') + 1).trim()]),
58
+ }));
59
+ const PRESENTATION = new Set(['fill', 'stroke', 'stroke-width', 'stroke-dasharray', 'opacity', 'color']);
60
+ const cssAttrs = (selectors, vars = {}) => {
61
+ const out = {};
62
+ for (const rule of cssRules()) {
63
+ if (!rule.sels.some((s) => selectors.includes(s))) continue;
64
+ for (const [k, v] of rule.decls) if (PRESENTATION.has(k)) out[k] = v.replace(/var\((--[\w-]+)\)/g, (_, name) => vars[name] ?? '');
65
+ }
66
+ const rgba = /^rgba\((\d+),\s*(\d+),\s*(\d+),\s*([\d.]+)\)$/.exec(out.fill || '');
67
+ if (rgba) { out.fill = '#' + rgba.slice(1, 4).map((c) => Number(c).toString(16).padStart(2, '0')).join(''); out['fill-opacity'] = rgba[4]; }
68
+ return out;
69
+ };
70
+ const asAttrs = (o) => Object.entries(o).map(([k, v]) => ` ${k}="${esc(v)}"`).join('');
71
+
72
+ export function renderStep(data, step, icons = symbols()) {
73
+ const [x, y, w, h] = data.view, t = data.theme;
74
+ const themeVars = { '--bg': t.bg, '--panel': t.panel, '--card': t.card, '--ink': t.ink, '--mute': t.muted };
75
+ const used = new Set();
76
+ const useIcon = (name, attrs) => { if (!name || !icons[`i-${name}`]) return ''; used.add(`i-${name}`); return `<use href="#i-${esc(name)}" ${attrs}/>`; };
77
+ const nodes = new Map(data.nodes.map((n) => [n.id, n]));
78
+ const edgeState = (ed) => {
79
+ const s = [stateOf(ed, step), stateOf(nodes.get(ed.a), step), stateOf(nodes.get(ed.b), step)];
80
+ return s.includes('off') ? 'off' : s.includes('ghost') ? 'ghost' : 'on';
81
+ };
82
+
83
+ const groups = data.groups.filter((g) => step >= (g.from || 1)).map((g) => {
84
+ let tx = g.x + 12, icon = '';
85
+ if (g.icon) { icon = useIcon(g.icon, `x="${tx}" y="${rnd(g.y + 5)}" width="15" height="15"${asAttrs(cssAttrs(['.group use'], themeVars))}`); tx += 20; }
86
+ return `<g class="group" data-group="${esc(g.id)}" data-state="on"><rect x="${g.x}" y="${g.y}" width="${g.w}" height="${g.h}" rx="13"${asAttrs(cssAttrs(['.group rect'], themeVars))}/>${icon}${text({ x: tx, y: rnd(g.spanLayers ? g.y + 18 : g.y + g.h - 6), 'font-size': 12, 'font-weight': 700, 'letter-spacing': 0.72, fill: t.muted }, g.title.toUpperCase())}</g>`;
87
+ });
88
+ const edges = data.edges.map((ed) => [ed, edgeState(ed)]).filter(([, s]) => s !== 'off').map(([ed, s]) => {
89
+ const k = data.edgeKinds[ed.kind], dash = k.dash ? ` stroke-dasharray="${esc(k.dash)}"` : '';
90
+ const ghost = s === 'ghost' ? asAttrs(cssAttrs(['.edge[data-state=ghost]'], themeVars)) : '';
91
+ return `<g class="edge" data-id="${esc(ed.id)}" data-kind="${esc(ed.kind)}" data-state="${s}"${ghost}><path d="${rounded(ed.pts)}" stroke="${k.color}" stroke-width="${k.width || 2}"${dash}${asAttrs({ fill: cssAttrs(['.edge path']).fill || 'none' })} marker-end="url(#m-${esc(ed.kind)})"/></g>`;
92
+ });
93
+ const shown = data.nodes.filter((n) => stateOf(n, step) !== 'off');
94
+ const nodeSvg = shown.map((n) => {
95
+ const badge = badgeOf(data, n, step), state = stateOf(n, step), vars = { ...themeVars, '--c': n.color };
96
+ const ghost = state === 'ghost', changed = badge === 'changed';
97
+ const card = cssAttrs(['.node .card', ...(changed ? ['.node.changed .card'] : []), ...(ghost ? ['.node[data-state=ghost] .card'] : [])], vars);
98
+ const bar = cssAttrs(['.node .bar', ...(changed ? ['.node.changed .bar'] : [])], vars);
99
+ const icon = n.icon ? useIcon(n.icon, `x="11" y="${rnd(n.h / 2 - 9)}" width="18" height="18"${asAttrs(cssAttrs(['.node use'], vars))}`) : '';
100
+ const lines = n.lines.map((l) => text({ class: l.cls, x: l.x, y: l.y, ...(l.cls === 't' ? { 'font-size': 13, 'font-weight': 700, fill: t.ink } : { 'font-size': 12, fill: t.muted }) }, l.text)).join('');
101
+ return `<g class="node${badge === 'changed' ? ' changed' : ''}" data-id="${esc(n.id)}" data-state="${stateOf(n, step)}" transform="translate(${n.x} ${n.y})" style="--c:${n.color}"${ghost ? asAttrs(cssAttrs(['.node[data-state=ghost]'], vars)) : ''}>`
102
+ + `<rect class="card" width="${n.w}" height="${n.h}" rx="8"${asAttrs(card)}/><rect class="bar" x="0" y="8" width="4" height="${rnd(n.h - 16)}" rx="2"${asAttrs(bar)}/>${icon}${lines}</g>`;
103
+ });
104
+ const badges = shown.map((n) => [n, badgeOf(data, n, step)]).filter(([, b]) => b).map(([n, b]) => {
105
+ const bw = data.badgeW[b];
106
+ return `<g class="bdg ${b}" data-node="${esc(n.id)}" transform="translate(${rnd(n.x + n.w - bw - 6)} ${n.y})"><rect width="${bw}" height="16" rx="8" y="-12"${asAttrs(cssAttrs(['.bdg rect', `.bdg.${b} rect`], themeVars))}/>${text({ x: rnd(bw / 2), y: 0, 'font-size': 12, 'font-weight': 700, 'text-anchor': 'middle', fill: badgeFill(b, t.ink) }, data.badgeLabels[b])}</g>`;
107
+ });
108
+ const markers = Object.entries(data.edgeKinds).map(([k, v]) =>
109
+ `<marker id="m-${esc(k)}" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto"><path d="M0 1l9 4-9 4z" fill="${v.color}"/></marker>`).join('');
110
+ const st = data.steps[step - 1] || {};
111
+ const title = [data.title, st.title].filter(Boolean).join(' - ');
112
+ const css = `:root{--bg:${t.bg};--panel:${t.panel};--card:${t.card};--ink:${t.ink};--mute:${t.muted}}\nsvg text{font-family:Arial,Helvetica,sans-serif}\n${pageCss()}`;
113
+
114
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="${x} ${y} ${w} ${h}" width="${w}" height="${h}" role="img">`
115
+ + `<title>${esc(title)}</title>${st.caption ? `<desc>${esc(st.caption)}</desc>` : ''}`
116
+ + `<defs>${markers}${[...used].map((id) => icons[id]).join('')}<style>${css}</style></defs>`
117
+ + `<rect x="${x}" y="${y}" width="${w}" height="${h}" fill="${t.bg}"/>`
118
+ + `<g id="L-groups">${groups.join('')}</g><g id="L-edges">${edges.join('')}</g><g id="L-nodes">${nodeSvg.join('')}</g><g id="L-badges">${badges.join('')}</g></svg>\n`;
119
+ }
120
+
121
+ export function exportSteps(specPath, outDir) {
122
+ const tmp = mkdtempSync(join(tmpdir(), 'arch-storyboard-export-'));
123
+ try {
124
+ const built = spawnSync(process.execPath, [join(dir, 'build.mjs'), specPath, tmp], { encoding: 'utf8' });
125
+ if (built.status !== 0) { process.stderr.write(built.stderr); process.exit(built.status || 1); }
126
+ const data = bakedData(readFileSync(join(tmp, 'index.html'), 'utf8'));
127
+ const icons = symbols();
128
+ mkdirSync(outDir, { recursive: true });
129
+ const files = data.steps.map((_, i) => {
130
+ const file = join(outDir, `step-${i + 1}.svg`);
131
+ writeFileSync(file, renderStep(data, i + 1, icons));
132
+ return file;
133
+ });
134
+ return files;
135
+ } finally { rmSync(tmp, { recursive: true, force: true }); }
136
+ }
137
+
138
+ import { pathToFileURL } from 'node:url';
139
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
140
+ const [spec, out] = process.argv.slice(2);
141
+ if (!spec || !out) { process.stderr.write('Usage: node scripts/export.mjs <spec.json> <out-dir>\n'); process.exit(2); }
142
+ const files = exportSteps(spec, out);
143
+ console.log(`${spec} -> ${files.length} SVGs in ${out}`);
144
+ }
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env python3
2
+ """Render every step-N.svg in a folder to step-N.png with headless Chrome (Playwright).
3
+ Usage: python3 scripts/export_png.py OUT_DIR
4
+ Exit codes: 0 done, 2 bad input, 3 no Chrome could be started. CHROME_PATH overrides the browser."""
5
+ import os, re, sys
6
+ from pathlib import Path
7
+ from playwright.sync_api import sync_playwright
8
+
9
+
10
+ def launch(p):
11
+ attempts = []
12
+ if os.environ.get('CHROME_PATH'):
13
+ attempts.append({'executable_path': os.environ['CHROME_PATH']})
14
+ attempts += [{'channel': 'chrome'}, {}]
15
+ for kwargs in attempts:
16
+ try:
17
+ return p.chromium.launch(**kwargs)
18
+ except Exception:
19
+ continue
20
+ return None
21
+
22
+
23
+ def main(out):
24
+ folder = Path(out)
25
+ files = sorted(folder.glob('step-*.svg'), key=lambda f: int(re.search(r'(\d+)', f.stem).group(1)))
26
+ if not files:
27
+ print(f'export_png: no step-N.svg files in {out}', file=sys.stderr)
28
+ return 2
29
+ with sync_playwright() as p:
30
+ browser = launch(p)
31
+ if browser is None:
32
+ print('export_png: could not start Chrome; install Chrome or set CHROME_PATH', file=sys.stderr)
33
+ return 3
34
+ for svg in files:
35
+ head = svg.read_text(encoding='utf8')[:400]
36
+ w = int(float(re.search(r'width="([\d.]+)"', head).group(1)))
37
+ h = int(float(re.search(r'height="([\d.]+)"', head).group(1)))
38
+ page = browser.new_page(viewport={'width': w, 'height': h}, device_scale_factor=2)
39
+ page.goto(svg.resolve().as_uri())
40
+ page.screenshot(path=str(svg.with_suffix('.png')))
41
+ page.close()
42
+ browser.close()
43
+ print(f'{len(files)} PNGs in {out}')
44
+ return 0
45
+
46
+
47
+ if __name__ == '__main__':
48
+ if len(sys.argv) != 2:
49
+ print('Usage: python3 scripts/export_png.py OUT_DIR', file=sys.stderr)
50
+ sys.exit(2)
51
+ sys.exit(main(sys.argv[1]))
@@ -1,7 +1,8 @@
1
1
  // Materialise provider artifacts from the canonical root skill. dist/ and marketplace/ are generated, not authored.
2
- import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { toPluginDoc } from './plugin-docs.mjs';
5
6
 
6
7
  const root = join(dirname(fileURLToPath(import.meta.url)), '..');
7
8
  const skillFiles = ['SKILL.md', 'references', 'scripts', 'assets'];
@@ -9,15 +10,20 @@ const copySkill = (to) => skillFiles.forEach((f) => cpSync(join(root, f), join(t
9
10
  const clean = (p) => rmSync(p, { recursive: true, force: true });
10
11
  const icon = join(root, 'assets/icon.png');
11
12
 
12
- // Committed Claude marketplace artifact: self-contained, no out-of-folder symlinks.
13
- const market = join(root, 'marketplace/plugins/arch-storyboard');
14
- clean(market);
15
- mkdirSync(join(market, '.claude-plugin'), { recursive: true });
16
- cpSync(join(root, 'plugins/claude/.claude-plugin/plugin.json'), join(market, '.claude-plugin/plugin.json'));
17
- cpSync(join(root, 'plugins/claude/README.md'), join(market, 'README.md'));
18
- cpSync(icon, join(market, '.claude-plugin/icon.png'));
19
- copySkill(market);
20
- if (existsSync(join(root, 'LICENSE'))) cpSync(join(root, 'LICENSE'), join(market, 'LICENSE'));
13
+ // Committed Claude plugin: Markdown only, so the directory accepts it from any organization. The builder
14
+ // ships on npm (bin/arch-storyboard.mjs); the plugin's SKILL.md is authored, its references are generated.
15
+ const version = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')).version;
16
+ const plugin = join(root, 'skills/arch-storyboard');
17
+ const pluginSkill = join(plugin, 'skills/arch-storyboard');
18
+ clean(join(root, 'marketplace/plugins')); // retired: the marketplace now points at skills/arch-storyboard
19
+ clean(join(pluginSkill, 'references'));
20
+ clean(join(pluginSkill, 'assets'));
21
+ mkdirSync(join(pluginSkill, 'references'), { recursive: true });
22
+ mkdirSync(join(pluginSkill, 'assets'), { recursive: true });
23
+ for (const f of readdirSync(join(root, 'references')).filter((n) => n.endsWith('.md'))) {
24
+ writeFileSync(join(pluginSkill, 'references', f), toPluginDoc(readFileSync(join(root, 'references', f), 'utf8'), version));
25
+ }
26
+ cpSync(join(root, 'assets/icons.txt'), join(pluginSkill, 'assets/icons.txt'));
21
27
 
22
28
  // Published npm plugin needs its own skill copy.
23
29
  const ocSkill = join(root, 'plugins/opencode/skill');
@@ -28,12 +34,7 @@ copySkill(ocSkill);
28
34
  const dist = join(root, 'dist');
29
35
  for (const name of ['claude-plugin', 'opencode-plugin']) clean(join(dist, name));
30
36
  const claude = join(dist, 'claude-plugin');
31
- mkdirSync(join(claude, '.claude-plugin'), { recursive: true });
32
- cpSync(join(market, '.claude-plugin/plugin.json'), join(claude, '.claude-plugin/plugin.json'));
33
- cpSync(join(market, '.claude-plugin/icon.png'), join(claude, '.claude-plugin/icon.png'));
34
- cpSync(join(market, 'README.md'), join(claude, 'README.md'));
35
- mkdirSync(join(claude, 'skills/arch-storyboard'), { recursive: true });
36
- copySkill(join(claude, 'skills/arch-storyboard'));
37
+ cpSync(plugin, claude, { recursive: true });
37
38
 
38
39
  const oc = join(dist, 'opencode-plugin');
39
40
  mkdirSync(oc, { recursive: true });
@@ -41,4 +42,4 @@ cpSync(join(root, 'plugins/opencode/package.json'), join(oc, 'package.json'));
41
42
  cpSync(join(root, 'plugins/opencode/index.js'), join(oc, 'index.js'));
42
43
  copySkill(oc);
43
44
 
44
- console.log(`packaged: ${market}\npackaged: ${ocSkill}\npackaged: ${claude}\npackaged: ${oc}`);
45
+ console.log(`packaged: ${plugin}\npackaged: ${ocSkill}\npackaged: ${claude}\npackaged: ${oc}`);
@@ -0,0 +1,16 @@
1
+ // The Claude plugin ships Markdown only; its copy of the reference docs calls the npm package, not repo scripts.
2
+ const rules = (version) => {
3
+ const npx = `npx arch-storyboard@${version}`;
4
+ return [
5
+ [/^npm install[^\n]*\n/gm, ''],
6
+ [/node scripts\/validate\.mjs\s+tests\/fixture-a\/spec\.json/g, `${npx} validate spec.json`],
7
+ [/node scripts\/build\.mjs\s+tests\/fixture-a\/spec\.json tests\/out\/a/g, `${npx} build spec.json out/`],
8
+ [/python3 scripts\/verify\.py tests\/fixture-a\/spec\.json tests\/out\/a --shots tests\/screenshots\/a/g, `${npx} verify spec.json out/ --shots shots/`],
9
+ [/`node scripts\/build\.mjs`/g, '`arch-storyboard build`'],
10
+ [/`verify\.py` needs/g, '`verify` needs'],
11
+ [/`scripts\/metrics\.mjs`/g, 'its text-metrics module'],
12
+ [/`scripts\/validate\.mjs`/g, 'the packaged validator'],
13
+ ];
14
+ };
15
+
16
+ export const toPluginDoc = (text, version) => rules(version).reduce((t, [from, to]) => t.replace(from, to), text);
@@ -7,6 +7,8 @@ const obj = (v) => v && typeof v === 'object' && !Array.isArray(v);
7
7
  const hex = (v) => typeof v === 'string' && /^#[0-9a-fA-F]{6}$/.test(v);
8
8
  const SHAPES = ['circle', 'square', 'diamond', 'triangle'];
9
9
  export const BADGES = { new: 'NEW', changed: 'CHANGED', unchanged: 'UNCHANGED', ghost: 'NOT YET' };
10
+ // Icon names the page can draw: the symbols in assets/icons.txt.
11
+ const ICONS = new Set([...readFileSync(new URL('../assets/icons.txt', import.meta.url), 'utf8').matchAll(/<symbol id="i-([^"]+)"/g)].map((m) => m[1]));
10
12
 
11
13
  export function validate(s) {
12
14
  const fail = (p, m, f) => { throw new Error(`Invalid spec at ${p}: ${m}. Fix: ${f}`); };
@@ -17,13 +19,15 @@ export function validate(s) {
17
19
  for (const key of ['nodes', 'links', 'steps']) ok(Array.isArray(s[key]) && s[key].length, `$.${key}`, 'must be a non-empty array', `add at least one ${key.slice(0, -1)}`);
18
20
 
19
21
  const kinds = s.kinds || {}, edgeKinds = s.edgeKinds || {}, traffic = s.traffic || {};
20
- for (const [k, v] of Object.entries(kinds)) ok(hex(v.color), `$.kinds.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour');
22
+ const checkIcon = (path, name) => ok(name === undefined || ICONS.has(name), path, `unknown icon "${name}"`, `use one of ${[...ICONS].join(', ')}`);
23
+ for (const [k, v] of Object.entries(kinds)) { ok(hex(v.color), `$.kinds.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour'); checkIcon(`$.kinds.${k}.icon`, v.icon); }
21
24
  for (const [k, v] of Object.entries(edgeKinds)) {
22
25
  ok(hex(v.color), `$.edgeKinds.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour');
23
26
  ok(v.dash === undefined || typeof v.dash === 'string', `$.edgeKinds.${k}.dash`, 'must be a string', 'use a CSS dash array like "7 4" or omit it');
24
27
  ok(v.width === undefined || typeof v.width === 'number', `$.edgeKinds.${k}.width`, 'must be a number', 'use a stroke width number or omit it');
25
28
  }
26
29
  for (const [k, v] of Object.entries(traffic)) {
30
+ checkIcon(`$.traffic.${k}.icon`, v.icon);
27
31
  ok(hex(v.color), `$.traffic.${k}.color`, 'must be #rrggbb', 'use a six-digit hex colour');
28
32
  ok(SHAPES.includes(v.shape), `$.traffic.${k}.shape`, `must be one of ${SHAPES.join(', ')}`, 'choose a listed shape');
29
33
  ok(typeof v.filled === 'boolean', `$.traffic.${k}.filled`, 'must be a boolean', 'set filled true or false');
@@ -40,12 +44,17 @@ export function validate(s) {
40
44
  });
41
45
 
42
46
  const ids = new Set();
47
+ const groupIds = new Set((s.groups || []).map((g) => g.id));
43
48
  s.nodes.forEach((n, i) => {
44
49
  const p = `$.nodes[${i}]`;
50
+ ok(n.group === undefined || groupIds.has(n.group), `${p}.group`, `unknown group "${n.group}"`, 'declare it in groups or remove group from the node');
45
51
  ok(typeof n.id === 'string' && !ids.has(n.id), `${p}.id`, 'missing or duplicate node id', 'use a unique string id');
46
52
  ids.add(n.id);
47
53
  for (const bad of ['x', 'y', 'cx', 'cy', 'pos', 'position']) ok(!(bad in n), `${p}.${bad}`, 'specs contain no coordinates', 'delete it; ELK decides geometry from layer/order/ports');
48
54
  ok(typeof n.kind === 'string' && (kinds[n.kind] || n.kind), `${p}.kind`, 'must be a string', 'name a key from kinds or add one');
55
+ // Kinds are optional, but once a spec declares some, a node's kind must be one of them.
56
+ ok(!Object.keys(kinds).length || kinds[n.kind], `${p}.kind`, `unknown node kind "${n.kind}"`, `use one of ${Object.keys(kinds).join(', ')} or add it to kinds`);
57
+ checkIcon(`${p}.icon`, n.icon);
49
58
  ok(typeof n.title === 'string' && n.title.length, `${p}.title`, 'must be a non-empty string', 'add a short title');
50
59
  ok(Array.isArray(n.sub) && n.sub.every((x) => typeof x === 'string'), `${p}.sub`, 'must be an array of strings', 'use [] or short single-line strings');
51
60
  ok(Array.isArray(n.size) && n.size.length === 2 && n.size.every((v) => typeof v === 'number' && v > 0), `${p}.size`, 'must be [width, height]', 'give a positive [w,h] size hint');
@@ -61,6 +70,7 @@ export function validate(s) {
61
70
  const portOf = (ref) => { const [id, pn] = String(ref).split('.'); const n = s.nodes.find((x) => x.id === id); return n && n.ports.some((p) => p === pn || p.endsWith(':' + pn)) ? id : null; };
62
71
  const pairs = new Set();
63
72
  const linkIds = new Set();
73
+ const linkKeys = new Set();
64
74
  s.links.forEach((l, i) => {
65
75
  const p = `$.links[${i}]`;
66
76
  ok(typeof l.id === 'string' && !linkIds.has(l.id), `${p}.id`, 'missing or duplicate link id', 'use a unique string id');
@@ -68,11 +78,18 @@ export function validate(s) {
68
78
  ok(portOf(l.from), `${p}.from`, `unknown port "${l.from}"`, 'use an existing node.port from nodes[].ports');
69
79
  ok(portOf(l.to), `${p}.to`, `unknown port "${l.to}"`, 'use an existing node.port from nodes[].ports');
70
80
  ok(edgeKinds[l.kind], `${p}.kind`, 'unknown edge kind', `add it to edgeKinds or use ${Object.keys(edgeKinds).join(', ')}`);
81
+ const declared = `${l.from}>${l.to}>${l.kind}`;
82
+ ok(!linkKeys.has(declared), p, `link ${l.from} -> ${l.to} (${l.kind}) is declared more than once`, 'delete the repeat, or give it another kind if it means something else');
83
+ linkKeys.add(declared);
71
84
  pairs.add([portOf(l.from), portOf(l.to)].sort().join('~'));
72
85
  });
86
+ const seenGroups = new Set();
73
87
  (s.groups || []).forEach((g, i) => {
74
88
  const p = `$.groups[${i}]`;
75
89
  ok(typeof g.id === 'string', `${p}.id`, 'must be a string', 'add a unique group id');
90
+ checkIcon(`${p}.icon`, g.icon);
91
+ ok(!seenGroups.has(g.id), `${p}.id`, `duplicate group id "${g.id}"`, 'give each group its own id');
92
+ seenGroups.add(g.id);
76
93
  ok(!g.spanLayers || g.layer === undefined, `${p}.layer`, 'a layer-spanning group needs no layer', 'remove layer or set spanLayers false');
77
94
  ok(g.gapNode === undefined || (typeof g.gapNode === 'number' && g.gapNode > 0), `${p}.gapNode`, 'must be a positive number', 'use a positive row gap or omit it');
78
95
  ok(g.padBottom === undefined || (typeof g.padBottom === 'number' && g.padBottom >= 0), `${p}.padBottom`, 'must be a non-negative number', 'use a padding number or omit it');
@@ -80,8 +97,12 @@ export function validate(s) {
80
97
  const members = s.nodes.filter((n) => n.group === g.id);
81
98
  ok(members.length, `${p}.id`, 'no nodes belong to this group', 'set group on at least one node or delete the group');
82
99
  });
100
+ const nodeById = new Map(s.nodes.map((n) => [n.id, n]));
83
101
  s.steps.forEach((st, i) => {
84
102
  const p = `$.steps[${i}]`;
103
+ // A node exists at a step from its first step on, or while it is ghosted (shown as "not yet").
104
+ const present = (id) => { const n = nodeById.get(id); return !n || (n.from || 1) <= i + 1 || (n.ghost || []).includes(i + 1); };
105
+ const absent = (id) => [`node "${id}" does not exist at step ${i + 1}`, `set its from to ${i + 1} or earlier, or add ${i + 1} to its ghost list`];
85
106
  ok(typeof st.title === 'string' && typeof st.caption === 'string', `${p}`, 'title and caption are required strings', 'add both');
86
107
  const jids = new Set();
87
108
  (st.journeys || []).forEach((j, k) => {
@@ -95,6 +116,7 @@ export function validate(s) {
95
116
  }
96
117
  ok(Array.isArray(j.route) && j.route.length >= 2, `${q}.route`, 'needs at least two node ids', 'list ordered node ids for the hops');
97
118
  j.route.forEach((id, h) => ok(ids.has(id), `${q}.route[${h}]`, `unknown node "${id}"`, 'use an id from nodes[]'));
119
+ j.route.forEach((id, h) => ok(present(id), `${q}.route[${h}]`, ...absent(id)));
98
120
  j.route.slice(1).forEach((b, h) => ok(pairs.has([j.route[h], b].sort().join('~')), `${q}.route[${h + 1}]`, `no link between ${j.route[h]} and ${b}`, 'add the link or fix the route order'));
99
121
  const ref = (x, where) => {
100
122
  if (typeof x === 'number') return;
@@ -106,6 +128,7 @@ export function validate(s) {
106
128
  (st.chips || []).forEach((c, k) => {
107
129
  const q = `${p}.chips[${k}]`;
108
130
  ok(ids.has(c.node), `${q}.node`, 'unknown node', 'use an id from nodes[]');
131
+ ok(present(c.node), `${q}.node`, ...absent(c.node));
109
132
  ok(typeof c.text === 'string' && textWidth(c.text, 12) <= 240, `${q}.text`, 'chip text is too long for a status pill', 'shorten it to at most about 30 characters');
110
133
  ok(typeof c.dur === 'number' && c.dur > 0, `${q}.dur`, 'must be a positive number', 'set a duration in seconds');
111
134
  const m = typeof c.at === 'string' && /^([\w-]+)\.(start|turn|end)$/.exec(c.at);
@@ -114,6 +137,7 @@ export function validate(s) {
114
137
  for (const key of ['appear', 'ghost']) (st[key] || []).forEach((id, k) => ok(ids.has(id), `${p}.${key}[${k}]`, 'unknown node', 'use an id from nodes[]'));
115
138
  for (const [id, b] of Object.entries(st.badges || {})) {
116
139
  ok(ids.has(id), `${p}.badges.${id}`, 'unknown node', 'use an id from nodes[]');
140
+ ok(present(id), `${p}.badges.${id}`, ...absent(id));
117
141
  ok(BADGES[b], `${p}.badges.${id}`, `unknown badge "${b}"`, `use ${Object.keys(BADGES).join(', ')}`);
118
142
  }
119
143
  });