diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 2fe309c2..1f069e6f 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -9,7 +9,7 @@ "name": "pstack", "source": "./plugins/pstack", "description": "if you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence.", - "version": "1.16.0-adam.20261101", + "version": "1.16.0-adam.20261102", "author": { "name": "Lauren Tan (original)" }, diff --git a/.claude/skills/verify-open-pstack/features/registry.json b/.claude/skills/verify-open-pstack/features/registry.json index d82807cd..c4119b9b 100644 --- a/.claude/skills/verify-open-pstack/features/registry.json +++ b/.claude/skills/verify-open-pstack/features/registry.json @@ -15,7 +15,7 @@ "principle-redesign-from-first-principles", "principle-separate-before-serializing-shared-state", "principle-sequence-verifiable-units", "principle-subtract-before-you-add", "principle-test-behavior-not-implementation", "principle-type-system-discipline", - "recall", "reflect", "setup-pstack", "sharpen", "show-me-your-work", "statechart", "swarm", "tdd", "teach", + "recall", "reflect", "setup-pstack", "sharpen", "show-me-your-work", "statechart", "statechart-diagram", "swarm", "tdd", "teach", "technical-writing", "thermo-nuclear-code-quality-review", "typescript-best-practices", "unslop", "what-did-i-get-done", "why" ], @@ -70,7 +70,9 @@ "plugins/pstack/skills/poteto-mode/scripts/bun.lock", "plugins/pstack/skills/poteto-mode/scripts/check-plan.tsconfig.json", "plugins/pstack/skills/show-me-your-work/scripts/log.sh", - "plugins/pstack/skills/statechart/scripts/**" + "plugins/pstack/skills/statechart/scripts/**", + "plugins/pstack/skills/statechart-diagram/scripts/**", + "plugins/pstack/skills/statechart-diagram/hooks/**" ], "project": [ ".claude/skills/verify-open-pstack/**", ".agents/skills/verify-open-pstack", @@ -78,6 +80,7 @@ ".github/workflows/windows-hooks.yml" ], "nonRuntime": [ + "plugins/pstack/skills/statechart-diagram/assets/**", "plugins/pstack/skills/statechart-diagram/evals/**", "README.md", "REVIEW.md", "CHANGES.md", "LICENSE", "LICENSE.md", "UPSTREAM.md", "FORK.md", "TEAM-INSTALL.md", "NOTICE.md", "README-UPSTREAM.md", "LICENSE-cursor-team-kit", "LICENSE-superpowers", ".gitignore", ".mergify.yml", "docs/**", "assets/**", diff --git a/CHANGES.md b/CHANGES.md index 6ec0910c..22e76fe2 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,14 @@ Mergify auto-queue is live: ready PRs to main require passing verify, Unfret and exact-head live-gate, and no unresolved review thread; workflow changes require operator queueing. This port applies the Cursor → Claude Code substitutions in skill bodies. Earlier drafts left them flagged; this revision resolves them. A later pass added a Codex build that shares the same skills; see [Codex port](#codex-port) below. +## 1.16.0-adam.20261102 adds /statechart-diagram + +**New skill.** `/statechart-diagram` draws the `chart.mmd` and `report.md` that `/statechart` writes as a square plate in pen and coloured pencil on paper, after Kevin Ngo's statechart-art: Pele lays the chart out in a hand font, `scripts/plate.mjs` draws it with `@napi-rs/canvas` (no browser), objects from the reader's world sit beside the states they belong to, TLC's marks are drawn as red cards, red paths and a "rule broken" stamp, and the small line under the title reports what TLC checked. It runs on Node 20 or later and installs Pele, the canvas and two Open Font License fonts with `npm install` in its `scripts/` on first use. The skill is model-invocable; `/statechart` stays typed only. + +**New hook.** `PostToolUse` on Bash runs `hooks/after-statechart` through the existing `run-hook.cmd` wrapper. The script reads the tool call, and when the `/statechart` runner has just written a `chart.mmd`, it adds one note to the model's context asking for the plate; on every other command it is silent and exits in a few milliseconds, and without Node it exits 0. `/statechart`'s hand-off asks for the plate as well, so the chain also holds where hooks do not run. + +**Listings.** `README.md`, `docs/reference.md`, `poteto-help` and the verifier's skill registry name the new skill. + ## 1.16.0-adam.20261101 syncs to Cursor pstack 0.15.36 Adam's fork at `1.16.0-adam.20261101` merges released Open Pstack 1.16.0 and layers Lauren Tan's pstack skill changes from 0.15.30 to 0.15.36 (`ae5650f`) on top. The fork's front-door gate, cloud installer, verifier additions and model sheet stay. See `FORK.md` for the patch table and `UPSTREAM.md` for every exclusion. diff --git a/FORK.md b/FORK.md index aacc1ddc..d4133dea 100644 --- a/FORK.md +++ b/FORK.md @@ -15,6 +15,7 @@ This fork is the pinned source for the pstack plugin on Adam Vellequette's Claud | 4 | `scripts/front-door.py`, `plugins/pstack/.front-door.json`, every `SKILL.md`, `skills/*/agents/openai.yaml` | `front-door.py passive` makes every skill explicit-only (Claude Code: `disable-model-invocation: true`; Codex: `allow_implicit_invocation: false`) and adds a read-by-path note to the router. `front-door.py active` restores the port byte for byte. The release branch shipped passive until the front-door switch on 2026-10-05; it is active since (the commit that made it so says so). | Installed skills must not steer running lanes before the front door switches. The safety review (2026-10-04) found the port lets every skill start on its own. | | 6 | `plugins/pstack/skills/poteto-mode/scripts/orch/` (`orch.ts`, `store.ts`, `orch.test.ts`), `scripts/package.json` | Kept after Cursor pstack 0.15.36 deleted them with the agentic Orchestrate playbook; the test list keeps `orch`. | The harness's `chief-of-staff` skill runs its program against this store CLI (`PSTACK_ORCH`). The playbook text no longer names it. Dropping the files is Adam's call, after the chief-of-staff runtime moves off them. | | 5 | `scripts/cloud-setup.sh`, `tests/cloud-setup-test.sh` | New files. The script installs the kit into a Claude Code cloud session as the personal skills-directory plugin `pstack@skills-dir`. | A cloud session loads no plugin from the Mac or from a repo's settings. See "Cloud sessions" below. | +| 8 | `plugins/pstack/skills/statechart-diagram/`, `plugins/pstack/hooks/after-statechart`, `plugins/pstack/hooks/hooks.json`, `plugins/pstack/skills/statechart/SKILL.md` | New skill and hook. `/statechart-diagram` draws a `/statechart` chart as a hand-drawn plate; the `PostToolUse` hook asks for it once the statechart runner has written `chart.mmd`, and `/statechart`'s hand-off asks for it too. | A chart the owner keeps is a drawing, not Mermaid text; the chain runs without anyone remembering to ask (decided 2026-11-02). | | 7 | `.claude/skills/verify-open-pstack/` | `REPO` is this fork. `features/formal.ts` holds the recipes for the two formal verification skills, `skill-invocation:poteto-mode` runs a route-only case, a skill's `agents/openai.yaml` selects its Codex invocation surface, and `FORK.md`, `TEAM-INSTALL.md`, the operator scripts and the cloud-setup test are non-runtime paths. With `--account-router` and `--native-model`, `scripts/routing.ts` runs each native session through the harness account router and its `pstack-verify-run` launcher and checks the admission and completion receipts; `harness.ts` and `io.ts` carry the auth-link cleanup and cancellation handling that go with it. Dependency: `~/.agents/harness/scripts/account-router` and `pstack-verify-run`. The two formal cases run Claude with `bypassPermissions` inside their fixture, as the port's setup cases do, because Claude Code 2.1.316 refuses a `Write` under any `.claude/skills/` folder in `dontAsk` mode; a routed Claude run therefore cannot select them, while a routed Codex run can. | The verifier publishes live-gate evidence only to this fork and must exercise the surfaces the fork ships. | Last upstream sync: port release `v1.16.0`, merged 2026-11-01, with Cursor pstack 0.15.30 to 0.15.36 layered on top (the November 1, 2026 update below). Patch 3 (the two router index lines) is retired: upstream's router names both skills. diff --git a/NOTICE.md b/NOTICE.md index 6926b034..ac7cccf0 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -61,6 +61,7 @@ Files authored for this port (not derived from upstream): - `plugins/pstack/skills/babysit/SKILL.md` (independently authored; workflow informed by Cursor's public `/babysit` behavior) - `plugins/pstack/agents/pstack--.md` for the Fable, Opus, Sonnet, Opus 5.5 and Haiku 5.5 families (Claude-native lanes at each selectable effort) - `plugins/pstack/hooks/hooks.json`, `plugins/pstack/hooks/session-start`, `plugins/pstack/hooks/session-start-context.md`, and `plugins/pstack/hooks/.gitattributes` (the auto-fire hook, its mandate, and LF checkout on Windows) +- `plugins/pstack/skills/statechart-diagram/` (fork addition: draws a `/statechart` chart as a plate in pen and coloured pencil; an independent re-implementation of the technique in Kevin Ngo's statechart-art, MIT; its `scripts/` install Pele (MIT), `@napi-rs/canvas` (MIT) and the Caveat and Patrick Hand fonts (SIL Open Font License) from npm on first use) and `plugins/pstack/hooks/after-statechart` (the hook that asks for the plate once `/statechart` has written a chart) - `NOTICE.md` (this file) - `README.md` - `REVIEW.md` (the review panel's usage and waiver-scope mandate, #153; adapted from mastra-pilot's `REVIEW.md`, not from upstream) diff --git a/README.md b/README.md index 2bfeb45c..dc460772 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ That is the main workflow. The other skills are there when poteto-mode needs the | `sharpen` | You want a prompt rewritten deeper, not bigger, before you send it. It returns the rewritten prompt and does not do the task. | | `ketchup-video` | You want the `/ketchup` catch-up as a short subtitled video of slides, with the calls waiting on you as text under it. | | `statechart` | Someone who owns the behavior needs to see it as a chart checked by a TLA+ model, with the shortest path to each state that breaks a rule. | +| `statechart-diagram` | A `/statechart` chart should become a hand-drawn plate in pen and coloured pencil that a client or a team will keep. It runs by itself after `/statechart` writes a chart. | Plugin skills include `pstack:` in their name. In Claude Code, invoke a native skill such as `/pstack:architect`. In Codex, ask for the skill, such as `Use pstack:architect for this design.` See the [technical reference](docs/reference.md) for the full list. diff --git a/UPSTREAM.md b/UPSTREAM.md index 24e27c3c..c5829e8c 100644 --- a/UPSTREAM.md +++ b/UPSTREAM.md @@ -10,7 +10,7 @@ open-pstack tracks [Cursor's pstack](https://github.com/cursor/plugins/tree/main | Path | `pstack/` | | Commit | `ae5650febf4320793844c12c4adaa937f417f8da` | | Upstream version | `0.15.36` | -| open-pstack version | `1.16.0-adam.20261101` | +| open-pstack version | `1.16.0-adam.20261102` | The table above is the current Cursor sync point. Open Pstack 1.16.0 imported the 0.15.29 sync at `88d47514b82e7c44f00f2b2a72ff6dd12158038c`; Adam's fork (`FORK.md`) layers the skill changes from 0.15.30 to 0.15.36 on top of it. `README-UPSTREAM.md` preserves the upstream pstack README verbatim. `CHANGES.md` and `NOTICE.md` describe the adaptations and provenance. @@ -49,6 +49,8 @@ The table above is the current Cursor sync point. Open Pstack 1.16.0 imported th ## Local port-patch ledger +- **statechart hand-off draws the plate**: Cursor's `statechart` ends its Hand off with the chart, the bug lines and the rerun command. The fork adds one more sentence: invoke `statechart-diagram` on the output folder, once, because the plugin's `after-statechart` hook asks for the same. `statechart-diagram` and the hook are fork additions, not upstream content. + - **#235 — Claude transcript folder encoding**: the port wrote Claude Code's per-project transcript path into `recall`, `automate-me` and the `session-pickup` playbook. Claude Code encodes each `/` and each `.` in the workspace path as `-`, so a `.claude/worktrees/` session's folder holds `--claude-worktrees-`. Keep both characters in those three lines during syncs. - **#140 — Reflect transcript resolution**: Cursor's Reflect step 1 reads the `agent-transcripts/` directory its system prompt names; the port had substituted Claude Code's per-project directory, which left Codex without a lookup. The port replaces that step's body with one line that points to `plugins/pstack/skills/poteto-mode/references/codex-tools.md#active-transcripts`, and leaves the rest of `reflect/SKILL.md` unchanged. That mapping section holds the harness specifics: the Claude per-project scope, layouts, candidate and scan limits, opening-message verification, the Codex resolver call, and the 2,000-word digest fallback. The port-authored Bun resolver `plugins/pstack/skills/poteto-mode/scripts/resolve-codex-transcript.ts`, started through the `sh` launcher `resolve-codex-transcript` next to it so project Bun config and `.env` files cannot affect it, looks up the parent's known chat ID in Codex's read-only `threads` index, checks rollout scope and ownership, and prints opening-message metadata without transcript text. Preserve this divergence during upstream syncs: keep step 1 as the one-line pointer and keep the mapping section and resolver. - **#120 — harness config homes** (tracked for #105): Cursor's setup destination is `~/.cursor/rules/`. The shared port resolves nonempty `CLAUDE_CONFIG_DIR` / `CODEX_HOME`, otherwise `$HOME/.claude` / `$HOME/.codex`, once at `plugins/pstack/skills/poteto-mode/references/codex-tools.md#harness-config-homes`. `setup-pstack/SKILL.md` reuses that home for reads, sheet/integration writes, snapshots, restoration, and readback; Claude preserves the literal legacy import at the default home and renders exactly `@./pstack-models.md` for redirected homes, keeping spaces and `#` in the config-directory name out of the import line; reruns replace the one import whose target basename is `pstack-models.md`, append if absent, and stop if duplicated. Preserve this intentional divergence during upstream syncs. The named config-home invariant in `tests/skill-collision-repro.sh` rejects literal default destinations outside the legacy import, requires the literal default-home rendering and zero/one/many import rules, and verifies unset/empty/space-containing resolution without daily writes. See `CHANGES.md` for the port correction and `tests/setup-config-home-repro.sh` for redirected live-evidence preparation. The Cursor sync point is unchanged. diff --git a/docs/reference.md b/docs/reference.md index 4e89f527..97603424 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -161,6 +161,7 @@ The table uses the short upstream names. Claude Code exposes each native skill w | `/ketchup` | catch up on everything in this session since your last message (typed only) | | `/ketchup-video` | the same catch-up as a short subtitled video of slides, with the waiting calls as text under it (typed only) | | `/statechart` | check a TLA+ model and draw it as a Mermaid statechart, with the shortest path to each state that breaks a rule (typed only) | +| `/statechart-diagram` | draw a `/statechart` chart as a hand-drawn plate in pen and coloured pencil; called by the `after-statechart` hook once `/statechart` writes a chart | | `/poteto-help` | find the skill, playbook, or principle for a question about pstack (typed only) | | `/in-your-own-words` | play back your goal and the problem before work starts (typed only) | | `/sharpen` | rewrite a prompt deeper, not bigger, before you send it; returns the rewritten prompt and does not do the task (typed only) | diff --git a/plugins/pstack/.claude-plugin/plugin.json b/plugins/pstack/.claude-plugin/plugin.json index f5e89b12..2ba9ce41 100644 --- a/plugins/pstack/.claude-plugin/plugin.json +++ b/plugins/pstack/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "pstack", "displayName": "pstack", - "version": "1.16.0-adam.20261101", + "version": "1.16.0-adam.20261102", "description": "if you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Ported from cursor/plugins/pstack for Claude Code and Codex.", "author": { "name": "Lauren Tan" diff --git a/plugins/pstack/.codex-plugin/plugin.json b/plugins/pstack/.codex-plugin/plugin.json index 8c16d582..0e4226ae 100644 --- a/plugins/pstack/.codex-plugin/plugin.json +++ b/plugins/pstack/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "pstack", - "version": "1.16.0-adam.20261101", + "version": "1.16.0-adam.20261102", "description": "if you want to go fast, go deep first. pstack helps you write less, but higher quality code. rigorous agent workflows you can parallelize with confidence. Codex port of the Claude Code plugin; skills are shared, tool names resolve via skills/poteto-mode/references/codex-tools.md.", "author": { "name": "Lauren Tan" diff --git a/plugins/pstack/hooks/after-statechart b/plugins/pstack/hooks/after-statechart new file mode 100755 index 00000000..cb4c26dc --- /dev/null +++ b/plugins/pstack/hooks/after-statechart @@ -0,0 +1,12 @@ +#!/usr/bin/env bash +# Runs the statechart-diagram hand-off check after a Bash tool call. The check is a Node script; without +# Node the hook has nothing to say and exits 0, so the plugin still works where only bash is installed. +set -euo pipefail + +case "$0" in + */*|*\\*) dir="${0%[/\\]*}" ;; + *) dir=. ;; +esac +node_bin="$(command -v node 2>/dev/null || true)" +[ -n "$node_bin" ] || exit 0 +exec "$node_bin" "$dir/../skills/statechart-diagram/hooks/after-statechart.mjs" diff --git a/plugins/pstack/hooks/hooks.json b/plugins/pstack/hooks/hooks.json index 800f7ffe..fa1cb770 100644 --- a/plugins/pstack/hooks/hooks.json +++ b/plugins/pstack/hooks/hooks.json @@ -12,6 +12,20 @@ } ] } + ], + "PostToolUse": [ + { + "matcher": "Bash", + "hooks": [ + { + "type": "command", + "command": "\"${CLAUDE_PLUGIN_ROOT}/hooks/run-hook.cmd\" after-statechart", + "commandWindows": "C:\\Windows\\System32\\cmd.exe /d /v:on /s /c \"\"!PLUGIN_ROOT!\\hooks\\run-hook.cmd\" after-statechart\"", + "timeout": 10, + "statusMessage": "Checking whether /statechart wrote a chart" + } + ] + } ] } } diff --git a/plugins/pstack/skills/poteto-help/SKILL.md b/plugins/pstack/skills/poteto-help/SKILL.md index d2c3d0a6..2aa8cd1e 100644 --- a/plugins/pstack/skills/poteto-help/SKILL.md +++ b/plugins/pstack/skills/poteto-help/SKILL.md @@ -88,6 +88,7 @@ The default answer is `/poteto-mode`, which runs most of the others when its ste | Formally verify a race, invariant, or other property that tests rarely reach | [`/create-formal-verification-skill`](../create-formal-verification-skill/SKILL.md) | | Bring a formal verification back in line after the code it covers changed, and learn whether a failure is drift or a bug | [`/maintain-formal-verification-skill`](../maintain-formal-verification-skill/SKILL.md) | | Show a PM or designer what the user sees as a chart checked by a TLA+ model, with the shortest path to each state that breaks a rule | [`/statechart`](../statechart/SKILL.md) | +| Turn a `/statechart` chart into a hand-drawn plate in pen and coloured pencil, with the reader's world around it, for a client, a post or a deck | [`/statechart-diagram`](../statechart-diagram/SKILL.md) | | Vet a performance number before reporting or acting on it | [`/benchmark-checklist`](../benchmark-checklist/SKILL.md) | | Run a large or cross-cutting change, or one to review after stepping away | [`/figure-it-out`](../figure-it-out/SKILL.md) | | Keep a decision log during a run, and review it afterward | [`/show-me-your-work`](../show-me-your-work/SKILL.md) | diff --git a/plugins/pstack/skills/statechart-diagram/SKILL.md b/plugins/pstack/skills/statechart-diagram/SKILL.md new file mode 100644 index 00000000..7e0b3802 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/SKILL.md @@ -0,0 +1,109 @@ +--- +name: statechart-diagram +description: Draws a /statechart chart (the Mermaid chart.mmd and report.md that pstack's statechart skill writes) as a hand-drawn plate in pen and coloured pencil on paper, with the reader's world set around it, ready to share as a PNG or JPG. Use whenever someone wants a statechart, state machine, flow or TLA+ model turned into a drawing, illustration, poster, "something I can show the client", a picture for a post or a deck, or asks to "draw it like the boba plates" or "make it look hand-drawn", and whenever /statechart has just produced a chart that a non-engineer will read. Also use for any Mermaid stateDiagram-v2 file, even one /statechart did not write. When its hook is installed, a note arrives right after /statechart's command has written chart.mmd, asking for this skill; follow it. +--- + +# Statechart diagram + +A chart that TLC checked is right; a plate is the same chart drawn so that the people it is about will look +at it, keep it, and argue about it. This skill draws the chart `/statechart` wrote as a square picture in pen +and coloured pencil, in Kevin Ngo's manner (`references/technique.md` says how and why). Nothing in the model +changes: every box and arrow on the plate is one TLC explored. + +## Run + +Work in a scratch folder, not inside a repo. The command reads the chart and writes a folder of pictures: + +```sh +node /scripts/plate.mjs CHART.mmd --out DIR [--fast] [options] +``` + +The first time on a machine, install once (Node 20 or later; downloads the renderer, the canvas and two fonts): + +```sh +cd /scripts && npm install +``` + +`node /scripts/plate.mjs --help` lists every option and the object catalogue; read it once rather +than guessing spellings. + +**Automatic hand-off from /statechart.** The pstack plugin's `after-statechart` hook watches every Bash +command and speaks once: when the `/statechart` runner has just written a `chart.mmd`, it adds a note asking +for a plate of that chart, and `/statechart`'s own hand-off asks for the same. Outside the plugin, wire the +hook once with `node /hooks/install.mjs` (it merges one PostToolUse entry into +`~/.claude/settings.json`, takes effect after `/hooks` is opened or on restart, and `--remove` undoes it). + +`CHART.mmd` is the `chart.mmd` from a `/statechart` output folder, or any Mermaid `stateDiagram-v2`. When +`report.md` sits beside it, the plate's small line says what TLC checked ("52 states, 155 steps · 5 rules +hold"). Without `report.md` the plate carries no proof line and the small print says "a chart, not a checked +model"; say the same in your hand-off. The folder gets `plate.png` (2160 px), `plate-x.jpg` (2048 px, for a +post), `plate-preview.png` (1080 px, to look at), `plate-layout.svg` (Pele's layout) and `plate-plate.json` +(where everything landed, and every state id with its words). + +## Do it in this order + +1. **Get the chart.** If there is no `chart.mmd` yet, run `/statechart` first: the plate is only worth drawing + for a chart whose rules have been checked. Read `report.md` so you know which rules hold and which break. +2. **Draw it fast, look, then decide the words.** Run with `--fast` and open `plate-preview.png` with your + image reader. Pele wraps an arrow label at about 30 characters whatever the room, so a wrapped label is + normal; shorten one only when its lines crowd a box or another label, with `--say "old words=new words"` + (repeatable, aim under 30 characters for one line), never by editing `chart.mmd`, so the checked chart + stays as written and the change is visible in the command. Keep the reader's words: "the client signs", + not "transition fires". +3. **Check the direction.** With no `--dir`, the command lays the chart out both ways and keeps the one whose + words come out bigger, and says so. Force `--dir TB` or `--dir LR` only when the reader's habit matters + more than legibility (a timeline reads left to right). +4. **Set the reader's world around it.** Choose three to six things that mean something to the people the + chart is about (the "rule broken" stamps the command adds by itself do not count), and put each beside + the state it belongs to: `--near s7=document:signed:Contract`, + `--near s3=stamp:APPROVED`, `--near s6=bin`, `--anywhere person:wave`. The ids are the `sN` in the chart; + `plate-plate.json` lists them with their words. `references/objects.md` is the catalogue. The command says + what it could not place for want of room; move that one with `--anywhere`, or drop it. For a thing the + catalogue lacks, write a scene module (`references/scene-modules.md`, with `references/scene-example.mjs`). +5. **Write the top and bottom.** `--title` (the chart's title by default), `--subtitle` (one line under 60 + characters, what the reader should take away; longer runs into the legend), and, when the chart came from + a repo, `--source "repo @ commit"` for the small print; leave it out otherwise. Leave `--note` alone + unless `report.md` is missing; it is the proof line. +6. **Draw at full size, look again, deliver.** Drop `--fast`. Check the preview for words cut by arrows, a + thing sitting on a label, or a title that ran into the legend, and fix the command, not the picture. Send + `plate-x.jpg` for a feed or a message and `plate.png` for a deck or print. Keep the exact command, with + the direction pinned (`--dir TB` or `--dir LR`, whichever the command said it chose): the drawing is + seeded, so the same command draws the same plate, and a change in the model shows as a change in the + picture and nothing else. + +## When /statechart hands the chart to you + +The hook's note names the `chart.mmd` just written. Finish the statechart hand-off first, as that skill asks +(the chart, each rule, each bug path), because the plate illustrates that verdict and must not replace it. +Then run the steps above without asking the user anything: `--fast`, look, choose the words and three to six +things from the model's own world (a kitchen for a remodel, a parcel for a shipment, a stamp where someone +approves), full size, and write the plate into `plate/` beside the chart folder. Add one line to the hand-off +saying the plate was drawn automatically and how to stop that (`hooks/install.mjs --remove`, or disable the +plugin's hook in `/hooks`). + +## Reading the marks + +The plate draws TLC's verdicts the way `/statechart` marks them: a state that breaks a rule is red with a +"rule broken" stamp beside it; one that breaks it for some values behind it is orange; states on the shortest +path to a break carry a second red outline and the arrows between them are traced in red; a state where a +property's counterexample loops has a dashed purple outline. The stamps are placed like any other thing, so +the command counts them among the things placed, and leaves one out when there is no room. The legend top right comes from the chart's own +Legend block. When you hand the plate over, name the broken rule in the reader's words and point at the red +path; the picture is the argument, your sentence is the verdict. + +## When it looks wrong + +- **Words tiny:** too many states or labels too long for one plate. Shorten with `--say`, try `--dir LR`, or + ask `/statechart` for coarser state labels in its view and draw that chart. +- **Title ran into the legend:** it wraps itself at 112 mm; give a shorter `--title` and move the long form + into `--subtitle`. +- **A thing was skipped:** there was no free room beside that state. Use `--anywhere`, or a smaller scale + (`--near s7=document@0.7`). +- **"Font missing" or "Cannot find package":** run `npm install` in `/scripts`. +- **A different hand:** `--seed any-words`. Same seed, same picture. + +## Hand-off + +Give the reader `plate-x.jpg`, the sentence about any broken rule, the list of what was shortened with +`--say`, and the command that draws it again. Credit the technique ("after Kevin Ngo's statechart-art") and +the check ("the chart TLC checked with /statechart"); the small print carries both by default. diff --git a/plugins/pstack/skills/statechart-diagram/assets/examples/parcel/chart.mmd b/plugins/pstack/skills/statechart-diagram/assets/examples/parcel/chart.mmd new file mode 100644 index 00000000..e55e38ba --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/assets/examples/parcel/chart.mmd @@ -0,0 +1,45 @@ +--- +title: "a parcel, from checkout to doorstep" +--- +stateDiagram-v2 + state "Legend" as legend { + lg0: Not yet paid for + lg1: Paid: the shop owes a parcel + lg2: Out of the shop's hands + lg3: Breaks NeverShipUnpaid + lg4: Path to the NeverShipUnpaid bug + } + class lg0 tan + class lg1 teal + class lg2 blue + class lg3 breaks + class lg4 bugPath + s0: In the basket + s1: Ordered, awaiting payment + s2: Paid + s3: Packed + s4: Handed to the courier + s5: Delivered + s6: Refunded + s7: Shipped before payment cleared + [*] --> s0 + s0 --> s1: you check out + s1 --> s2: the card clears + s1 --> s0: you give up [after 24 hours] + s2 --> s3: the warehouse packs it + s3 --> s4: the courier scans it + s4 --> s5: it reaches your door + s2 --> s6: you cancel [before it is packed] + s1 --> s7: the warehouse packs it [the payment is still pending] + classDef breaks fill:#ffecee,stroke:#e72e3b,stroke-width:2.5px,color:#cd2834 + class s0 tan + class s1 tan + class s2 teal + class s3 teal + class s4 blue + class s5 blue + class s6 tan + class s7 breaks + class s0 bugPath + class s1 bugPath + class s7 bugPath diff --git a/plugins/pstack/skills/statechart-diagram/assets/examples/parcel/report.md b/plugins/pstack/skills/statechart-diagram/assets/examples/parcel/report.md new file mode 100644 index 00000000..ac4ec674 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/assets/examples/parcel/report.md @@ -0,0 +1,14 @@ +# Parcel + +TLC reached 11 states and 19 steps. The chart draws 8 states and 8 arrows. + +## Rules that break + +### NeverShipUnpaid + +1. In the basket +2. Ordered, awaiting payment: you check out +3. Shipped before payment cleared: the warehouse packs it [the payment is still pending] + +## Rules that hold +TypeOK, RefundOnlyAfterPayment, NoDeadlock diff --git a/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/case.yaml b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/case.yaml new file mode 100644 index 00000000..a68f2a78 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/case.yaml @@ -0,0 +1,6 @@ +schema_version: "1.1" +name: draws-statechart-output-as-plate +expected_outcome: | + A plate was drawn from the given chart.mmd without editing it: a square PNG and a 2048 px JPG exist, the state that breaks NeverShipUnpaid is drawn red with a stamp beside it, a parcel sits beside Packed and a house beside Delivered, the small line under the title reports TLC's 11 states and 19 steps, and the final message gives the exact plate.mjs command and names the broken rule in plain words. +context: + scaffold_script: place-files.sh diff --git a/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/files/chart.mmd b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/files/chart.mmd new file mode 100644 index 00000000..e55e38ba --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/files/chart.mmd @@ -0,0 +1,45 @@ +--- +title: "a parcel, from checkout to doorstep" +--- +stateDiagram-v2 + state "Legend" as legend { + lg0: Not yet paid for + lg1: Paid: the shop owes a parcel + lg2: Out of the shop's hands + lg3: Breaks NeverShipUnpaid + lg4: Path to the NeverShipUnpaid bug + } + class lg0 tan + class lg1 teal + class lg2 blue + class lg3 breaks + class lg4 bugPath + s0: In the basket + s1: Ordered, awaiting payment + s2: Paid + s3: Packed + s4: Handed to the courier + s5: Delivered + s6: Refunded + s7: Shipped before payment cleared + [*] --> s0 + s0 --> s1: you check out + s1 --> s2: the card clears + s1 --> s0: you give up [after 24 hours] + s2 --> s3: the warehouse packs it + s3 --> s4: the courier scans it + s4 --> s5: it reaches your door + s2 --> s6: you cancel [before it is packed] + s1 --> s7: the warehouse packs it [the payment is still pending] + classDef breaks fill:#ffecee,stroke:#e72e3b,stroke-width:2.5px,color:#cd2834 + class s0 tan + class s1 tan + class s2 teal + class s3 teal + class s4 blue + class s5 blue + class s6 tan + class s7 breaks + class s0 bugPath + class s1 bugPath + class s7 bugPath diff --git a/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/files/report.md b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/files/report.md new file mode 100644 index 00000000..ac4ec674 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/files/report.md @@ -0,0 +1,14 @@ +# Parcel + +TLC reached 11 states and 19 steps. The chart draws 8 states and 8 arrows. + +## Rules that break + +### NeverShipUnpaid + +1. In the basket +2. Ordered, awaiting payment: you check out +3. Shipped before payment cleared: the warehouse packs it [the payment is still pending] + +## Rules that hold +TypeOK, RefundOnlyAfterPayment, NoDeadlock diff --git a/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/graders/01-expected-output.md b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/graders/01-expected-output.md new file mode 100644 index 00000000..a02b18fd --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/graders/01-expected-output.md @@ -0,0 +1,7 @@ +--- +type: llm +focus: trace +weight: 1 +--- + +The result matches this description: A plate was drawn from the given chart.mmd without editing it: a square PNG and a 2048 px JPG exist, the state that breaks NeverShipUnpaid is drawn red with a stamp beside it, a parcel sits beside Packed and a house beside Delivered, the small line under the title reports TLC's 11 states and 19 steps, and the final message gives the exact plate.mjs command and names the broken rule in plain words. diff --git a/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/place-files.sh b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/place-files.sh new file mode 100755 index 00000000..98883e6a --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/place-files.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -eu +cp -R "$(dirname "$0")/files/." . diff --git a/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/prompt.md b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/prompt.md new file mode 100644 index 00000000..883142f0 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/draws-statechart-output-as-plate/prompt.md @@ -0,0 +1,8 @@ +--- +tags: [statechart-diagram] +max_turns: 30 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill, Write, Edit, Bash] +--- + +The /statechart run for our parcel flow is in this folder: chart.mmd and report.md. Draw it as one of those hand-drawn pen-and-pencil plates I can send to the warehouse team, with the broken rule obvious, a parcel beside the Packed state and a house beside Delivered. Tell me the command you used. Input files: chart.mmd, report.md diff --git a/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/case.yaml b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/case.yaml new file mode 100644 index 00000000..00885bc0 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/case.yaml @@ -0,0 +1,6 @@ +schema_version: "1.1" +name: plain-mermaid-without-report +expected_outcome: | + A plate was drawn from hiring.mmd with the title 'Hiring at Northwind', a person beside the Interviewing state and a document beside Offer sent; because there is no report.md the small proof line is absent or empty rather than invented; the final message says the chart was not model-checked. +context: + scaffold_script: place-files.sh diff --git a/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/files/hiring.mmd b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/files/hiring.mmd new file mode 100644 index 00000000..f27b0e16 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/files/hiring.mmd @@ -0,0 +1,15 @@ +stateDiagram-v2 + s0: Applied + s1: Screening call + s2: Interviewing + s3: Offer sent + s4: Hired + s5: Declined + [*] --> s0 + s0 --> s1: a recruiter calls + s1 --> s2: the panel is booked + s1 --> s5: not a fit + s2 --> s3: the panel says yes + s2 --> s5: the panel says no + s3 --> s4: the candidate signs + s3 --> s5: the candidate walks away [after 7 days] diff --git a/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/graders/01-expected-output.md b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/graders/01-expected-output.md new file mode 100644 index 00000000..934a8d2a --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/graders/01-expected-output.md @@ -0,0 +1,7 @@ +--- +type: llm +focus: trace +weight: 1 +--- + +The result matches this description: A plate was drawn from hiring.mmd with the title 'Hiring at Northwind', a person beside the Interviewing state and a document beside Offer sent; because there is no report.md the small proof line is absent or empty rather than invented; the final message says the chart was not model-checked. diff --git a/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/place-files.sh b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/place-files.sh new file mode 100755 index 00000000..98883e6a --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/place-files.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -eu +cp -R "$(dirname "$0")/files/." . diff --git a/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/prompt.md b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/prompt.md new file mode 100644 index 00000000..67b532ed --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/plain-mermaid-without-report/prompt.md @@ -0,0 +1,8 @@ +--- +tags: [statechart-diagram] +max_turns: 30 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill, Write, Edit, Bash] +--- + +I don't have the TLA+ stuff, just this Mermaid state diagram of our hiring pipeline (hiring.mmd). Can you draw it in that sketchy pencil style, title 'Hiring at Northwind', with a person next to Interviewing and a document next to Offer sent? Input files: hiring.mmd diff --git a/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/case.yaml b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/case.yaml new file mode 100644 index 00000000..54be17e8 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/case.yaml @@ -0,0 +1,6 @@ +schema_version: "1.1" +name: shortens-words-without-editing-chart +expected_outcome: | + The plate was drawn with --say replacements for the long labels; chart.mmd is byte-identical to the input; the final message lists each old and new wording and the command that reproduces the plate. +context: + scaffold_script: place-files.sh diff --git a/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/files/chart.mmd b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/files/chart.mmd new file mode 100644 index 00000000..acb36b58 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/files/chart.mmd @@ -0,0 +1,29 @@ +--- +title: "an order at the counter" +--- +stateDiagram-v2 + state "Legend" as legend { + lg0: Nothing owed yet + lg1: The customer has paid + } + class lg0 tan + class lg1 teal + s0: Waiting in line + s1: Order taken by the cashier + s2: Paid at the register + s3: Being made by the barista + s4: Ready on the counter + s5: In the customer's hand + [*] --> s0 + s0 --> s1: the customer tells the cashier what they would like to drink today + s1 --> s2: the customer pays by card or with cash at the register + s2 --> s3: the barista picks up the ticket and starts making the drink + s3 --> s4: the barista calls the customer's name and sets the cup down + s4 --> s3: the customer says it is the wrong drink and the barista remakes it + s4 --> s5: the customer picks the cup up from the counter + class s0 tan + class s1 tan + class s2 teal + class s3 teal + class s4 teal + class s5 teal diff --git a/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/graders/01-expected-output.md b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/graders/01-expected-output.md new file mode 100644 index 00000000..d9a2c516 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/graders/01-expected-output.md @@ -0,0 +1,7 @@ +--- +type: llm +focus: trace +weight: 1 +--- + +The result matches this description: The plate was drawn with --say replacements for the long labels; chart.mmd is byte-identical to the input; the final message lists each old and new wording and the command that reproduces the plate. diff --git a/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/place-files.sh b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/place-files.sh new file mode 100755 index 00000000..98883e6a --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/place-files.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +set -eu +cp -R "$(dirname "$0")/files/." . diff --git a/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/prompt.md b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/prompt.md new file mode 100644 index 00000000..704ecc82 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/evals/shortens-words-without-editing-chart/prompt.md @@ -0,0 +1,8 @@ +--- +tags: [statechart-diagram] +max_turns: 30 +timeout_seconds: 900 +allowed_tools: [Read, Glob, Grep, Skill, Write, Edit, Bash] +--- + +Here is chart.mmd from /statechart for our order flow. Make the hand-drawn plate but the labels are way too long, they wrap everywhere. Shorten them for the drawing but do NOT change chart.mmd, the model owner wants it untouched. Input files: chart.mmd diff --git a/plugins/pstack/skills/statechart-diagram/hooks/after-statechart.mjs b/plugins/pstack/skills/statechart-diagram/hooks/after-statechart.mjs new file mode 100644 index 00000000..6434049e --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/hooks/after-statechart.mjs @@ -0,0 +1,48 @@ +#!/usr/bin/env node +// after-statechart.mjs — a PostToolUse hook on Bash. When the pstack /statechart runner has just written a +// chart, it tells Claude to draw the plate with the statechart-diagram skill. On every other command it +// says nothing and exits 0. A hook must never break the tool it follows, so every failure is swallowed. +import fs from 'node:fs'; +import path from 'node:path'; + +const chunks = []; +process.stdin.on('data', (d) => chunks.push(d)); +process.stdin.on('end', () => { + let input; + try { input = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return; } + try { run(input); } catch { /* silent */ } +}); + +const unquote = (s) => s.replace(/^["']|["']$/g, ''); + +function run(input) { + if (input.tool_name !== 'Bash') return; + const cmd = String(input.tool_input?.command ?? ''); + if (!/statechart/.test(cmd) || /plate\.mjs/.test(cmd)) return; + const r = input.tool_response; + const text = typeof r === 'string' ? r : [r?.stdout, r?.output, r?.content, r?.stderr].filter((s) => typeof s === 'string').join('\n'); + const cwd = input.cwd || process.cwd(); + // "cd DIR && …" moves the base that relative paths resolve against + const cdm = cmd.match(/(?:^|[;&|]\s*)cd\s+("[^"]+"|'[^']+'|\S+)\s*(?:&&|;)/); + const base = cdm ? path.resolve(cwd, unquote(cdm[1])) : cwd; + const candidates = []; + // the runner ends with "Wrote DIR" + const wrote = text.match(/^Wrote (.+)$/m); + if (wrote) candidates.push(wrote[1].trim()); + // or read the command itself: /scripts/statechart SPEC.tla [--out DIR] + const runner = cmd.match(/(\S*statechart(?:\.ts)?)\s+("[^"]+\.tla"|'[^']+\.tla'|\S+\.tla)/); + if (runner) { + const spec = unquote(runner[2]), out = cmd.match(/--out[=\s]+("[^"]+"|'[^']+'|\S+)/); + candidates.push(out ? unquote(out[1]) : spec.replace(/\.tla$/, '-chart')); + } + for (const c of candidates) { + const dir = path.resolve(base, c); + if (fs.existsSync(path.join(dir, 'chart.mmd'))) return say(dir, fs.existsSync(path.join(dir, 'report.md'))); + } +} + +function say(dir, hasReport) { + const chart = path.join(dir, 'chart.mmd'); + const additionalContext = `The /statechart run just wrote ${chart}${hasReport ? ' and report.md' : ''}. The user wants every finished statechart drawn as a plate as well: first give the statechart hand-off as that skill asks (the chart, each rule, each bug path), then invoke the statechart-diagram skill (Skill tool, skill "statechart-diagram") on ${chart}, choose three to six things from the reader's world for it, and deliver plate-x.jpg with the exact plate command in the same hand-off.`; + process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext } })); +} diff --git a/plugins/pstack/skills/statechart-diagram/hooks/install.mjs b/plugins/pstack/skills/statechart-diagram/hooks/install.mjs new file mode 100644 index 00000000..c481521f --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/hooks/install.mjs @@ -0,0 +1,36 @@ +#!/usr/bin/env node +// install.mjs — wires the after-statechart hook into Claude Code's user settings, for a plain skill install +// (a plugin install ships the hook by itself). Idempotent. `--remove` takes it out again. +// node /hooks/install.mjs [--settings PATH] [--remove] +import fs from 'node:fs'; +import path from 'node:path'; +import os from 'node:os'; +import { fileURLToPath } from 'node:url'; + +const here = path.dirname(fileURLToPath(import.meta.url)), script = path.join(here, 'after-statechart.mjs'); +const args = process.argv.slice(2), opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : undefined; }; +const configDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude'); +const file = opt('--settings') || path.join(configDir, 'settings.json'); +const MARK = 'after-statechart.mjs'; +const entry = { matcher: 'Bash', hooks: [{ type: 'command', command: `node "${script}"`, timeout: 10, statusMessage: 'Checking whether /statechart wrote a chart' }] }; + +let settings = {}; +if (fs.existsSync(file)) { + const raw = fs.readFileSync(file, 'utf8'); + try { settings = raw.trim() ? JSON.parse(raw) : {}; } catch (e) { console.error(`${file} is not valid JSON (${e.message}). Fix it first; a broken settings file disables every setting in it.`); process.exit(2); } + fs.copyFileSync(file, file + '.bak'); +} +settings.hooks ??= {}; settings.hooks.PostToolUse ??= []; +const list = settings.hooks.PostToolUse; +const isOurs = (h) => h.hooks?.some((x) => typeof x.command === 'string' && x.command.includes(MARK)); +const had = list.some(isOurs); +if (args.includes('--remove')) { + settings.hooks.PostToolUse = list.filter((h) => !isOurs(h)); + if (!settings.hooks.PostToolUse.length) delete settings.hooks.PostToolUse; + if (!Object.keys(settings.hooks).length) delete settings.hooks; + write(); console.log(had ? `Removed the after-statechart hook from ${file}.` : `No after-statechart hook in ${file}; nothing to remove.`); +} else { + settings.hooks.PostToolUse = list.filter((h) => !isOurs(h)).concat([entry]); + write(); console.log(`${had ? 'Updated' : 'Added'} the after-statechart hook in ${file}.\nIt runs after every Bash command and speaks only when /statechart has written a chart.mmd.\nA running Claude Code session picks it up after /hooks is opened once, or on restart.`); +} +function write() { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n'); } diff --git a/plugins/pstack/skills/statechart-diagram/references/objects.md b/plugins/pstack/skills/statechart-diagram/references/objects.md new file mode 100644 index 00000000..bee7efd8 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/references/objects.md @@ -0,0 +1,24 @@ +# Objects + +Each object is drawn to fit the box the placer finds for it, so sizes below are natural sizes in mm at +`@1`; `@0.8` after an object scales it. An argument follows a colon. + +| object | size | argument | good beside | +|---|---|---|---| +| `document` | 26 x 32 | a title; `signed:Title` adds a signature and a pen | a contract, an order, a form, anything signed or filed | +| `envelope` | 22 x 15 | – | a thing sent to someone | +| `stamp` | 26 x 12 | the word; `WORD\|#hex` picks the ink | an approval, a rejection, a verdict | +| `pencil` | 18 x 5 | – | a draft, an edit | +| `pen` | 20 x 6 | – | a signature, a review | +| `house` | 20 x 18 | – | a home, a project, a delivery | +| `bin` | 13 x 17 | – | a void, a deletion, a rejection | +| `clock` | 14 x 14 | `h:mm` | a deadline, a wait, a timeout | +| `coin` | 12 x 12 | the sign (`$` by default) | payment, a refund, money owed | +| `parcel` | 18 x 16 | a label | a shipment, stock, an order | +| `flag` | 14 x 20 | a word; `WORD\|#hex` picks the colour | a milestone, a release, a finish | +| `person` | 12 x 24 | `pose\|#shirt`, pose: stand, wave, hold, point | the customer, the staff, the reviewer | +| `check` | 6 x 6 | a colour | done, approved | +| `cross` | 6 x 6 | a colour | refused, voided | + +Add your own in a scene module (see `scene-modules.md`), or in `scripts/lib/objects.mjs` with the same shape: +`{ w, h, draw(S, box, arg) }`, registered in `OBJECTS`. diff --git a/plugins/pstack/skills/statechart-diagram/references/scene-example.mjs b/plugins/pstack/skills/statechart-diagram/references/scene-example.mjs new file mode 100644 index 00000000..d86dc2a2 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/references/scene-example.mjs @@ -0,0 +1,28 @@ +// An example scene: a counter with a till in a free corner, and a hand-written note beside the state that +// breaks a rule. Run: plate.mjs chart.mmd --scene references/scene-example.mjs +export default function scene({ S, kit, objects, res, placer, u }) { + const { rrect, ell, part, C } = kit; + // a counter, wherever there is room for 44 x 22 mm + const b = placer.anywhere(44 * u, 22 * u, [[36 * u, 204 * u], [180 * u, 204 * u], [36 * u, 110 * u]]); + if (b) { + const cx = (b.x0 + b.x1) / 2, y = b.y1 - 0.6 * u, T = (p) => kit.tf(p, { x: cx, y, s: u }); + S.ink(T([[-22, 0.3], [22, 0.3]]), { nib: 0.24 }); + part(S, T([[-16, -14], [16, -14], [16, 0], [-16, 0]]), C.cream, { pressure: 0.42, nib: 0.3 }); + for (let x = -10; x < 16; x += 8) S.ink(T([[x, -12], [x, -1.6]]), { nib: 0.12, color: '#6b6270' }); + part(S, T([[-18, -17], [18, -17], [18, -14], [-18, -14]]), C.wood, { pressure: 0.7, nib: 0.3, angle: 8 }); + part(S, T(rrect(4, -24, 14, -17, 0.6)), C.slate, { pressure: 0.6, nib: 0.26 }); + part(S, T(ell(-8, -19.4, 3.6, 1.6)), '#f2f2f2', { pressure: 0.2, passes: 1, nib: 0.22 }); + } + // a note beside the broken state, in the reader's words + const broken = res.nodeBoxes.find((nb) => nb.n.classes.includes('breaks')); + const nb = broken && placer.near(broken, 30 * u, 14 * u, ['below', 'right', 'left']); + if (nb) { + const shape = rrect(nb.x0, nb.y0, nb.x1, nb.y1, 0.6 * u); + S.hatch(shape.map(([x, y]) => [x + u, y + 1.1 * u]), { cut: [shape] }); S.fill(shape); S.pencil(shape, '#fbf3dc', { pressure: 0.45, passes: 1 }); S.outline(shape, { nib: 0.28 }); + S.text('TLC found this in 3 steps.', (nb.x0 + nb.x1) / 2, nb.y0 + 5.6 * u, { size: 3.2 * u, align: 'center', font: 'Caveat', weight: 700 }); + S.text('Who should have waited?', (nb.x0 + nb.x1) / 2, nb.y0 + 10.6 * u, { size: 3.0 * u, align: 'center', font: 'Caveat' }); + } + // the objects library is there too + const pb = placer.anywhere(objects.pen.w * u, objects.pen.h * u, [[196 * u, 60 * u]]); + if (pb) objects.pen.draw(S, pb); +} diff --git a/plugins/pstack/skills/statechart-diagram/references/scene-modules.md b/plugins/pstack/skills/statechart-diagram/references/scene-modules.md new file mode 100644 index 00000000..9e4c620c --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/references/scene-modules.md @@ -0,0 +1,31 @@ +# Scene modules + +When `--near` and `--anywhere` are not enough, give `--scene FILE.mjs`. It runs after the chart and the +objects are drawn and before the small print, with one argument: + +```js +export default function scene(ctx) { /* draw */ } +``` + +`ctx` holds: + +| field | what it is | +|---|---| +| `S` | the sheet: `S.ink(points, {nib, tremor, color, dash})`, `S.outline(poly, …)`, `S.box(x0,y0,x1,y1, …)`, `S.pencil(poly, color, {pressure, angle, passes})`, `S.hatch(poly, {cut})`, `S.fill(poly)`, `S.dot(x,y,r,color)`, `S.text(str, x, y, {size, font, weight, align, color, rot})`, `S.measure(str, {size})`, `S.R` the seeded random (`S.R()`, `S.R.range(a,b)`, `S.R.gauss(m,s)`, `S.R.pick(list)`). Units are millimetres, origin top left. | +| `kit` | `rrect(x0,y0,x1,y1,r)`, `ell(cx,cy,rx,ry,rot)`, `tf(points, {x,y,rot,s})`, `part(S, poly, color, {shadow, pressure, nib})`, `C` (named colours), `GROUP` and `MARK` (the chart colours) | +| `objects` | the object library: each is `{ w, h, draw(S, box, arg) }`; `box` is `{x0,y0,x1,y1}` in mm | +| `res` | what the chart drawer placed: `nodeBoxes` (`{x0,y0,x1,y1,n}` with `n.id`, `n.lines`, `n.classes`), `labelBoxes`, `clusterBoxes`, `edgeInfo` (`{id, from, to, bug}`), `stateSize`, `labelSize` | +| `placer` | `near(box, w, h, ['right','left','below','above'])` and `anywhere(w, h, [[x,yBottom], …])` return a free box and claim it, or `null`; `free(box)` tests one; `claim(box)` reserves one you drew into by hand | +| `L`, `m` | Pele's layout in its pixels, and the mapper into plate mm: `m.P([x,y])`, `m.X(x)`, `m.Y(y)`, `m.k` | +| `u` | the plate scale: 1 at 216 mm. Multiply hand-placed coordinates by it. | +| `title`, `legend`, `report`, `placed`, `skipped` | the words at the top, the legend entries, what `report.md` said, and what was placed or skipped so far | + +Three habits keep a scene honest: + +- Ask the placer before drawing anything free-standing, and draw into the box it returns. That is how the + plate stays uncluttered as the chart changes. +- Build a thing from `kit.part` (paper, pencil, pen, in that order) and `S.ink` lines, the way the objects + in `scripts/lib/objects.mjs` do. Read one of those before writing your own. +- Scale with `u`, so the scene still works at `--size 180`. + +`references/scene-example.mjs` draws a shop counter under a chart and a note beside the broken state. diff --git a/plugins/pstack/skills/statechart-diagram/references/technique.md b/plugins/pstack/skills/statechart-diagram/references/technique.md new file mode 100644 index 00000000..5257e55f --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/references/technique.md @@ -0,0 +1,67 @@ +# The technique + +How a checked statechart becomes a drawing that a reader keeps. Kevin Ngo worked it out for his boba-shop +plates (`statechart-art`, MIT); this skill re-implements it so that any `/statechart` chart can have one. + +## The four steps + +1. **Model.** A TLA+ spec says what can happen, and its config lists the rules that must hold. `/statechart` + checks it with TLC, which takes every step from every reachable state and checks each rule in each one. +2. **Chart.** `/statechart` writes the chart in Mermaid, in the words the reader uses for each state and step, + plus `report.md`: how many states and steps TLC reached, which rules hold, which break, and the shortest + path to each break. The plate never redraws the model: every box and arrow is one TLC checked. +3. **Lay out.** Pele (the Mermaid renderer) places the boxes and arrows, measuring every word in the plate's + own hand font, so that words fit the boxes they will be written in. `plate.mjs` reads the places back + out of Pele's SVG. +4. **Draw.** The kit lays the layout down on paper with simulated dry media, and sets the things of the + reader's world around it where there is room. + +## What makes it look drawn + +- **Paper first.** A warm base, a fine per-pixel grain, a few fibres, a faint vignette. Everything else + multiplies onto it, so colour sits *in* the paper rather than on top of it. +- **The pen trembles and presses.** Every line is resampled to half-millimetre steps and pushed sideways by + slow noise (tremor); its width varies along the stroke (pressure). A box is four separate strokes that + overshoot their corners, as a hand's do. +- **Colour is hatched, not filled.** A coloured-pencil area is a few hundred short parallel strokes at an + angle, with random length, alpha and width, inside a clip edge that was itself jittered, then a lighter + second pass at a slightly different angle. Multiply blending makes the overlaps darker, like real pencil. +- **Shadows are pen hatching**, offset a millimetre down and right, cut by the shape itself. +- **Nothing is placed twice in the same spot.** Words sit in gaps cut out of the arrows; things are placed only + where no box, word or arrow is, and are skipped when there is no room (the command says which). +- **Seeded.** All randomness comes from one seed (the title by default). The same inputs draw the same + picture, so a change in the chart shows as a change in the picture and nothing else. +- **Square, sized for a phone.** 216 mm at 10 px/mm = 2160 px; the `-x.jpg` is 2048 px for a feed. + +## The colours + +`/statechart` gives each state a group colour (`class s3 yellow`) and puts the group names in a Legend block. +The plate draws the legend by hand from that block and uses stronger pencil versions of the same colours, so +the hatching reads. Marks are drawn the way TLC's report means them: + +| mark on a state | on the plate | +|---|---| +| `breaks` (the rule fails here) | red pencil fill, red pen, a "rule broken" stamp beside it when there is room | +| `mayBreak` (fails for some values behind this box) | orange fill and pen, a "may break" stamp | +| `bugPath` (on the shortest path to a break) | a second red outline; arrows between two such states are drawn in red with a pink wash | +| `repeats` (a property's counterexample loops here) | a dashed purple outline | + +## Knobs worth knowing + +- **Words.** The chart's words are the reader's, so keep them. When a label is too long to sit on an arrow, + shorten it with `--say "old words=new words"` rather than editing `chart.mmd`, so the checked chart stays as + TLC wrote it and the change is visible in the command. +- **Direction.** Tall charts (many states in a line) read best top to bottom; wide ones (few ranks, many + siblings) left to right. `--dir LR` flips it. The chart is scaled to fit either way; if the words come out + small, there are too many states for one plate, or the labels are too long. +- **Spacing.** `--spacing 26,36` is Pele's rank and node spacing. Tighter spacing means bigger words on the + plate, until arrows start to crowd the labels. +- **Things.** Choose objects that mean something in the reader's world and put each beside the state it + belongs to (`--near s7=document:signed`). Three to six is plenty; a plate is not a sticker sheet. +- **Seed.** Change `--seed` to get a different hand; keep it to keep the picture. + +## Credits + +Technique: Kevin Ngo, *The business of boba* (statechart-art, MIT). Charts: the pstack `/statechart` skill by +Lauren Tan. Layout: Pele (MIT). Drawing: `@napi-rs/canvas` (MIT). Fonts: Caveat and Patrick Hand (SIL Open +Font License) via `@fontsource`. The code here is its own, MIT-licensed re-implementation. diff --git a/plugins/pstack/skills/statechart-diagram/scripts/lib/chart.mjs b/plugins/pstack/skills/statechart-diagram/scripts/lib/chart.mjs new file mode 100644 index 00000000..d45a8120 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/lib/chart.mjs @@ -0,0 +1,92 @@ +// chart.mjs — draws a laid-out chart on the sheet: parent states, arrows, cards, the words on the arrows, +// the start dot, and the marks /statechart puts on states (breaks, mayBreak, bugPath, repeats). +import { rrect, ell, resample, trim, polyLen } from './kit.mjs'; + +/** Pencil colours for /statechart's groups: stronger than the screen tints, so the hatching shows. */ +export const GROUP = { blue: '#8fb8e8', orange: '#e8a57a', purple: '#c4a9e6', yellow: '#f0c75a', teal: '#86c7bb', tan: '#d9b98f', pink: '#f2a3c4' }; +export const MARK = { breaks: '#b8352f', mayBreak: '#d0700f', bugPath: '#b8352f', repeats: '#8a3fc4', breaksFill: '#f3c2bb', mayBreakFill: '#f6d7b0' }; +const PLAIN = '#efe4cc'; + +export function drawChart(S, L, m, o = {}) { + const INK = S.INK, COND = o.condColor || '#a8443b', LINE = o.lineColor || '#3a3340'; + const k = m.k, stateSize = (o.stateSize ?? 16) * k * (o.textScale ?? 1), labelSize = (o.labelSize ?? 14) * k * (o.textScale ?? 1); + const colourOf = (classes) => { const g = classes.find((c) => GROUP[c]); return o.groupColors?.[g] || (g ? GROUP[g] : PLAIN); }; + const nodeBoxes = L.nodes.map((n) => ({ x0: m.X(n.cx - n.w / 2) - 1.2, y0: m.Y(n.cy - n.h / 2) - 0.6, x1: m.X(n.cx + n.w / 2) + 1.2, y1: m.Y(n.cy + n.h / 2) + 0.6, n })); + const labelBoxes = L.labels.map((l) => ({ x0: m.X(l.x), y0: m.Y(l.y), x1: m.X(l.x + l.w), y1: m.Y(l.y + l.h), l })); + const clusterBoxes = L.clusters.map((c) => ({ x0: m.X(c.x), y0: m.Y(c.y), x1: m.X(c.x + c.w), y1: m.Y(c.y + c.h), headY: c.headY !== undefined ? m.Y(c.headY) : undefined, c })); + const nodeAt = (p, pad = 2.5) => nodeBoxes.find((b) => p[0] > b.x0 - pad && p[0] < b.x1 + pad && p[1] > b.y0 - pad && p[1] < b.y1 + pad); + const has = (n, cls) => n.classes.includes(cls); + + // parent states: a soft container with its name along the top + for (const b of clusterBoxes) { + const shape = rrect(b.x0, b.y0, b.x1, b.y1, 2.2); + S.pencil(shape, o.clusterColor || '#e9e0cf', { pressure: 0.22, passes: 1, angle: 60, pitch: 0.9, width: 0.9 }); + S.outline(shape, { nib: 0.36, tremor: 0.16 }); + if (b.headY !== undefined) S.ink([[b.x0 + 0.4, b.headY], [b.x1 - 0.4, b.headY]], { nib: 0.22, tremor: 0.1 }); + const words = b.c.label.map((q) => q.text).join(' '); + if (words) S.text(words, (b.x0 + b.x1) / 2, (b.headY !== undefined ? (b.y0 + b.headY) / 2 : b.y0 + stateSize * 1.3) + stateSize * 0.36, { size: stateSize, align: 'center', font: 'Caveat', weight: 700 }); + } + for (const d of L.dividers) S.ink(d.map(m.P), { nib: 0.26, tremor: 0.1, dash: [1.6, 1.2], color: '#5a5260' }); + + // arrows first, so that the cards sit on their ends + const edgeInfo = []; + for (const e of L.edges) { + let pts = e.pts.map(m.P); if (e.tip) pts = pts.concat([m.P(e.tip)]); + const fromStart = L.starts.some((s) => Math.hypot(s.cx - e.pts[0][0], s.cy - e.pts[0][1]) < 14); + const a = nodeAt(pts[0]), b = nodeAt(pts[pts.length - 1]); + const bug = !!(a && b && has(a.n, 'bugPath') && has(b.n, 'bugPath')) && o.markBugArrows !== false; + edgeInfo.push({ id: e.id, from: a?.n.id, to: b?.n.id, bug }); + pts = trim(pts, fromStart ? 1.4 : 0.9, 0.15); + const gap = 0.9, runs = [[]]; + for (const p of resample(pts, 0.3)) { const hit = labelBoxes.some((lb) => p[0] > lb.x0 - gap && p[0] < lb.x1 + gap && p[1] > lb.y0 - gap && p[1] < lb.y1 + gap); if (hit) { if (runs[runs.length - 1].length) runs.push([]); } else runs[runs.length - 1].push(p); } + for (const r of runs) if (polyLen(r) > 0.6) { + if (bug) { S.ctx.save(); S.ctx.globalAlpha = 0.5; S.ctx.strokeStyle = '#f0b3a8'; S.ctx.lineWidth = 1.6; S.ctx.lineCap = 'round'; S.ctx.lineJoin = 'round'; S.path(r.map(([x, y]) => [x + 0.5, y + 0.6]), false); S.ctx.stroke(); S.ctx.restore(); } + S.ink(r, { nib: bug ? 0.5 : 0.3, tremor: 0.14, color: bug ? MARK.bugPath : LINE }); + } + const end = pts[pts.length - 1], back = resample(pts, 0.4).slice(-7)[0], ang = Math.atan2(end[1] - back[1], end[0] - back[0]), c = Math.cos(ang), s = Math.sin(ang), len = 2.5 * (bug ? 1.15 : 1), wing = 1.0; + const pt = (u, v) => [end[0] - u * c + v * -s, end[1] - u * s + v * c], head = [pt(0, 0), pt(len, wing), pt(len * 0.7, 0), pt(len, -wing)]; + S.ctx.save(); S.ctx.fillStyle = bug ? MARK.bugPath : LINE; S.path(head); S.ctx.fill(); S.ctx.restore(); S.outline(head, { nib: 0.2, tremor: 0.05, color: bug ? MARK.bugPath : LINE }); + } + + // the cards + for (const b of nodeBoxes) { + const n = b.n, shape = rrect(b.x0, b.y0, b.x1, b.y1, 1.1), broke = has(n, 'breaks'), may = has(n, 'mayBreak'), onPath = has(n, 'bugPath'), repeats = has(n, 'repeats'); + S.hatch(shape.map(([x, y]) => [x + 1.0, y + 1.15]), { cut: [shape], angle: 45, pitch: 0.5, nib: 0.1 }); + S.fill(shape); S.pencil(shape, broke ? MARK.breaksFill : may ? MARK.mayBreakFill : colourOf(n.classes), { pressure: 0.6, angle: 32 }); + if (onPath) S.outline(rrect(b.x0 - 1.2, b.y0 - 1.2, b.x1 + 1.2, b.y1 + 1.2, 2), { nib: 0.42, color: MARK.bugPath, tremor: 0.12 }); + if (repeats) S.outline(rrect(b.x0 - 1.2, b.y0 - 1.2, b.x1 + 1.2, b.y1 + 1.2, 2), { nib: 0.36, color: MARK.repeats, dash: [1.4, 1.1] }); + S.box(b.x0, b.y0, b.x1, b.y1, { nib: broke ? 0.52 : 0.4, overshoot: 0.9, color: broke ? MARK.breaks : may ? MARK.mayBreak : INK }); + const cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, lh = stateSize * 1.18, top = cy - ((n.lines.length - 1) * lh) / 2 + stateSize * 0.36; + n.lines.forEach((q, i) => S.text(q.text, cx, top + i * lh, { size: stateSize, align: 'center', rot: S.R.gauss(0, 0.006), color: broke ? MARK.breaks : may ? '#8a4a08' : INK })); + if (o.cornerMark) o.cornerMark(S, b, n); + } + + // the words on the arrows; a condition in [brackets] in its own colour + for (const b of labelBoxes) { + const cx = (b.x0 + b.x1) / 2, lh = labelSize * 1.22, n = b.l.lines.length, top = (b.y0 + b.y1) / 2 - ((n - 1) * lh) / 2 + labelSize * 0.36; + b.l.lines.forEach((q, i) => { const runs = q.text.split(/(\[[^\]]*\])/).filter(Boolean), widths = runs.map((t) => S.measure(t, { size: labelSize })), total = widths.reduce((a, c) => a + c, 0); let x = cx - total / 2; runs.forEach((t, j) => { S.text(t, x, top + i * lh, { size: labelSize, color: t[0] === '[' ? COND : INK }); x += widths[j]; }); }); + } + for (const s of L.starts) { const [x, y] = m.P([s.cx, s.cy]); S.dot(x, y, 1.6, INK); S.outline(ell(x, y, 2.7, 2.7), { nib: 0.22 }); } + + const edgePts = L.edges.flatMap((e) => resample(e.pts.map(m.P), 1.5)); + return { nodeBoxes, labelBoxes, clusterBoxes, edgePts, edgeInfo, stateSize, labelSize }; +} + +/** The hand-drawn legend: a swatch and the words for each entry /statechart put in its Legend block. */ +export function drawLegend(S, items, { x0, y0, width, groupColors }) { + if (!items.length) return { x0, y0, x1: x0, y1: y0 }; + const pitch = items.length > 5 ? 5.3 : 6.3, swW = 9.6, swH = pitch > 6 ? 4.4 : 3.8; + S.text('the colours', x0, y0 + 5.2, { size: 3.4, color: '#4a4350' }); S.ink([[x0, y0 + 6.4], [x0 + 16, y0 + 6.6]], { nib: 0.18 }); + items.forEach((it, i) => { + const y = y0 + 9.2 + i * pitch, sw = rrect(x0, y, x0 + swW, y + swH, 0.5), g = it.classes.find((c) => GROUP[c]); + const breaks = it.classes.includes('breaks'), may = it.classes.includes('mayBreak'), path = it.classes.includes('bugPath'), rep = it.classes.includes('repeats'); + S.fill(sw); + if (breaks || may || g) S.pencil(sw, breaks ? MARK.breaksFill : may ? MARK.mayBreakFill : (groupColors?.[g] || GROUP[g]), { pressure: 0.62 }); + if (path) S.outline(rrect(x0 - 0.8, y - 0.8, x0 + swW + 0.8, y + swH + 0.8, 1), { nib: 0.4, color: MARK.bugPath }); + if (rep) S.outline(rrect(x0 - 0.8, y - 0.8, x0 + swW + 0.8, y + swH + 0.8, 1), { nib: 0.34, color: MARK.repeats, dash: [1.4, 1.1] }); + S.box(x0, y, x0 + swW, y + swH, { nib: 0.26, overshoot: 0.5, color: breaks ? MARK.breaks : may ? MARK.mayBreak : S.INK }); + let size = 3.3; const room = width - swW - 3; while (size > 2.5 && S.measure(it.text, { size }) > room) size -= 0.1; + S.text(it.text, x0 + swW + 2.8, y + swH * 0.82, { size, color: breaks ? MARK.breaks : S.INK }); + }); + return { x0: x0 - 2, y0: y0, x1: x0 + width, y1: y0 + 9.2 + items.length * pitch + 1 }; +} diff --git a/plugins/pstack/skills/statechart-diagram/scripts/lib/kit.mjs b/plugins/pstack/skills/statechart-diagram/scripts/lib/kit.mjs new file mode 100644 index 00000000..356df89a --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/lib/kit.mjs @@ -0,0 +1,150 @@ +// kit.mjs — dry media on paper, for a 2-D canvas. Units are millimetres; the context is scaled by ppm. +// The look comes from four habits of a hand: strokes tremble, lines overshoot corners, colour is laid in +// hatched passes that multiply where they overlap, and nothing is placed twice in the same spot. +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createCanvas, GlobalFonts } from '@napi-rs/canvas'; + +export const TAU = Math.PI * 2; +export const FONTS = { hand: 'Patrick Hand', display: 'Caveat' }; +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +/** Registers the bundled fonts once. Returns the family names in use. */ +export function registerFonts() { + const nm = path.join(HERE, '..', 'node_modules', '@fontsource'); + const files = [ + ['patrick-hand/files/patrick-hand-latin-400-normal.woff2', FONTS.hand], + ['caveat/files/caveat-latin-400-normal.woff2', FONTS.display], + ['caveat/files/caveat-latin-700-normal.woff2', FONTS.display], + ]; + for (const [f, fam] of files) { const p = path.join(nm, f); if (!fs.existsSync(p)) throw new Error(`Font missing: ${p}. Run "npm install" in ${path.join(HERE, '..')}.`); GlobalFonts.registerFromPath(p, fam); } + return FONTS; +} + +export function makeRng(seed) { + let h = 1779033703 ^ seed.length; + for (let i = 0; i < seed.length; i++) { h = Math.imul(h ^ seed.charCodeAt(i), 3432918353); h = (h << 13) | (h >>> 19); } + let a = h >>> 0; + const r = () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; + r.range = (lo, hi) => lo + (hi - lo) * r(); + r.gauss = (m = 0, s = 1) => { let u = 0, v = 0; while (!u) u = r(); while (!v) v = r(); return m + s * Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * v); }; + r.pick = (arr) => arr[Math.floor(r() * arr.length)]; + return r; +} +export const rrect = (x0, y0, x1, y1, r, n = 7) => { + r = Math.max(0.01, Math.min(r, (x1 - x0) / 2, (y1 - y0) / 2)); const out = []; + const corner = (cx, cy, a0) => { for (let i = 0; i <= n; i++) { const t = a0 + (i / n) * Math.PI / 2; out.push([cx + Math.cos(t) * r, cy + Math.sin(t) * r]); } }; + corner(x1 - r, y0 + r, -Math.PI / 2); corner(x1 - r, y1 - r, 0); corner(x0 + r, y1 - r, Math.PI / 2); corner(x0 + r, y0 + r, Math.PI); + return out; +}; +export const ell = (cx, cy, rx, ry = rx, rot = 0, n = 64) => { const out = [], c = Math.cos(rot), s = Math.sin(rot); for (let i = 0; i < n; i++) { const t = (i / n) * TAU, x = Math.cos(t) * rx, y = Math.sin(t) * ry; out.push([cx + x * c - y * s, cy + x * s + y * c]); } return out; }; +export const tf = (pts, { x = 0, y = 0, rot = 0, s = 1, sx = 1 } = {}) => { const c = Math.cos(rot), si = Math.sin(rot); return pts.map((p) => { const px = p[0] * s * sx, py = p[1] * s; return [x + px * c - py * si, y + px * si + py * c]; }); }; +export const lerp2 = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]; +export function polyLen(p) { let L = 0; for (let i = 1; i < p.length; i++) L += Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1]); return L; } +export function resample(p, step) { + if (p.length < 2) return p.slice(); + const out = [p[0].slice()]; let need = step; + for (let i = 1; i < p.length; i++) { const a = p[i - 1], b = p[i], d = Math.hypot(b[0] - a[0], b[1] - a[1]); let t = need; while (t <= d) { out.push(lerp2(a, b, t / d)); t += step; } need = t - d; } + const last = p[p.length - 1]; if (Math.hypot(last[0] - out[out.length - 1][0], last[1] - out[out.length - 1][1]) > step * 0.2) out.push(last.slice()); + return out; +} +export function trim(p, d0, d1) { + const L = polyLen(p); if (L <= d0 + d1 + 0.1) return p; + const at = (dist) => { let acc = 0; for (let i = 1; i < p.length; i++) { const seg = Math.hypot(p[i][0] - p[i - 1][0], p[i][1] - p[i - 1][1]); if (acc + seg >= dist) return [i, lerp2(p[i - 1], p[i], (dist - acc) / (seg || 1))]; acc += seg; } return [p.length - 1, p[p.length - 1]]; }; + const [i0, a] = at(d0), [i1, b] = at(L - d1), out = [a]; for (let i = i0; i < i1; i++) out.push(p[i]); out.push(b); return out; +} +export const bbox = (pts) => { let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const [x, y] of pts) { if (x < x0) x0 = x; if (y < y0) y0 = y; if (x > x1) x1 = x; if (y > y1) y1 = y; } return { x0, y0, x1, y1 }; }; +export function noise1(R, lambda) { + const vals = new Map(); const v = (i) => { if (!vals.has(i)) vals.set(i, R.range(-1, 1)); return vals.get(i); }; + return (t) => { const u = t / lambda, i = Math.floor(u), f = u - i, k = (1 - Math.cos(f * Math.PI)) / 2; return v(i) * (1 - k) + v(i + 1) * k; }; +} +export const jitter = (pts, amt, R) => pts.map(([x, y]) => [x + R.gauss(0, amt), y + R.gauss(0, amt)]); +export const darker = (hex, k = 0.22) => { const h = hex.replace('#', ''), c = [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)); return '#' + c.map((v) => Math.round(v * (1 - k)).toString(16).padStart(2, '0')).join(''); }; + +export class Sheet { + constructor({ w = 216, h = 216, ppm = 10, seed = 'plate', paper = '#f6efe1', ink = '#2a2430' }) { + this.w = w; this.h = h; this.ppm = ppm; this.W = Math.round(w * ppm); this.H = Math.round(h * ppm); + this.canvas = createCanvas(this.W, this.H); this.ctx = this.canvas.getContext('2d'); this.ctx.scale(ppm, ppm); + this.R = makeRng(seed); this.INK = ink; this.PAPER = paper; + } + path(pts, close = true) { const c = this.ctx; c.beginPath(); c.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) c.lineTo(pts[i][0], pts[i][1]); if (close) c.closePath(); } + pathAdd(pts) { const c = this.ctx; c.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) c.lineTo(pts[i][0], pts[i][1]); c.closePath(); } + /** The sheet itself: a warm base, a fine grain, a few fibres, and a faint vignette. */ + paper() { + const c = this.ctx, { W, H, R } = this; + c.save(); c.setTransform(1, 0, 0, 1, 0, 0); c.fillStyle = this.PAPER; c.fillRect(0, 0, W, H); + const img = c.getImageData(0, 0, W, H), d = img.data; let s = 0x9e3779b9 ^ Math.floor(R() * 1e9); + for (let i = 0; i < d.length; i += 4) { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; const n = ((s >>> 0) % 1000) / 1000 - 0.5, g = n * 11; d[i] += g; d[i + 1] += g * 0.95; d[i + 2] += g * 0.8; } + c.putImageData(img, 0, 0); c.restore(); + c.save(); c.globalAlpha = 0.07; c.strokeStyle = '#b8a27e'; c.lineWidth = 0.12; c.lineCap = 'round'; + for (let i = 0; i < Math.round(this.w * this.h / 110); i++) { const x = R() * this.w, y = R() * this.h, a = R() * TAU, l = R.range(0.6, 3.2); c.beginPath(); c.moveTo(x, y); c.lineTo(x + Math.cos(a) * l, y + Math.sin(a) * l); c.stroke(); } + c.restore(); + const g = c.createRadialGradient(this.w / 2, this.h / 2, Math.min(this.w, this.h) * 0.35, this.w / 2, this.h / 2, Math.max(this.w, this.h) * 0.78); g.addColorStop(0, 'rgba(120,90,50,0)'); g.addColorStop(1, 'rgba(120,90,50,0.10)'); + c.save(); c.fillStyle = g; c.fillRect(0, 0, this.w, this.h); c.restore(); + } + /** Clean paper under a shape, so that what was drawn there before disappears. */ + fill(poly, color = '#f9f4e8') { const c = this.ctx; c.save(); this.path(poly); c.fillStyle = color; c.fill(); c.restore(); } + /** Coloured pencil: hatched strokes inside a roughened edge, two passes, multiplied where they cross. */ + pencil(poly, color, o = {}) { + const c = this.ctx, R = this.R, angle = (o.angle ?? 32) * Math.PI / 180, pitch = o.pitch ?? 0.56, pressure = o.pressure ?? 0.62, passes = o.passes ?? 2, width = o.width ?? 0.72; + c.save(); c.globalCompositeOperation = 'multiply'; this.path(jitter(poly, o.clipJitter ?? 0.3, R)); c.clip(); + const b = bbox(poly), cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, L = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) + 4; + for (let p = 0; p < passes; p++) { + const a = angle + p * 0.5 + R.gauss(0, 0.03), dx = Math.cos(a), dy = Math.sin(a), nx = -dy, ny = dx, pt = pitch * (p ? 1.4 : 1), pr = pressure * (p ? 0.5 : 1); + c.strokeStyle = color; c.lineCap = 'round'; + for (let d = -L / 2; d <= L / 2; d += pt * R.range(0.8, 1.2)) { + const sx = cx + nx * d, sy = cy + ny * d, l0 = L / 2 - R.range(0, 2.5), l1 = L / 2 - R.range(0, 2.5), bow = R.gauss(0, 0.28); + c.globalAlpha = pr * R.range(0.5, 1); c.lineWidth = width * R.range(0.7, 1.3); + c.beginPath(); c.moveTo(sx - dx * l0, sy - dy * l0); c.quadraticCurveTo(sx + nx * bow, sy + ny * bow, sx + dx * l1, sy + dy * l1); c.stroke(); + } + } + c.restore(); + } + /** Thin pen hatching, for shadows and dark things. `cut` lists shapes to leave clean. */ + hatch(poly, o = {}) { + const c = this.ctx, R = this.R, angle = (o.angle ?? 45) * Math.PI / 180, pitch = o.pitch ?? 0.5; + c.save(); this.path(poly); if (o.cut) { for (const q of o.cut) this.pathAdd(q); c.clip('evenodd'); } else c.clip(); + const b = bbox(poly), cx = (b.x0 + b.x1) / 2, cy = (b.y0 + b.y1) / 2, L = Math.hypot(b.x1 - b.x0, b.y1 - b.y0) + 2, dx = Math.cos(angle), dy = Math.sin(angle), nx = -dy, ny = dx; + c.strokeStyle = o.color || '#514852'; c.globalAlpha = o.alpha ?? 0.85; c.lineWidth = o.nib ?? 0.11; c.lineCap = 'round'; + for (let d = -L / 2; d <= L / 2; d += pitch * R.range(0.85, 1.15)) { const sx = cx + nx * d, sy = cy + ny * d; c.beginPath(); c.moveTo(sx - dx * L / 2, sy - dy * L / 2 + R.gauss(0, 0.05)); c.lineTo(sx + dx * L / 2, sy + dy * L / 2 + R.gauss(0, 0.05)); c.stroke(); } + c.restore(); + } + /** A pen line: trembling, with the pressure of a hand. */ + ink(pts, o = {}) { + if (!pts || pts.length < 2) return; + const c = this.ctx, R = this.R, nib = o.nib ?? 0.34, tremor = o.tremor ?? 0.13, P = resample(pts, 0.45); + const n = noise1(R, 3.2), n2 = noise1(R, 6.5); let s = 0; const Q = []; + for (let i = 0; i < P.length; i++) { const a = P[Math.max(0, i - 1)], b = P[Math.min(P.length - 1, i + 1)], dx = b[0] - a[0], dy = b[1] - a[1], d = Math.hypot(dx, dy) || 1; if (i) s += Math.hypot(P[i][0] - P[i - 1][0], P[i][1] - P[i - 1][1]); const off = n(s) * tremor; Q.push([P[i][0] - dy / d * off, P[i][1] + dx / d * off]); } + c.save(); c.strokeStyle = o.color || this.INK; c.globalAlpha = o.alpha ?? 1; c.lineCap = 'round'; c.lineJoin = 'round'; + if (o.dash) c.setLineDash(o.dash); + const seg = 5; + for (let i = 0; i < Q.length - 1; i += seg - 1) { const part = Q.slice(i, i + seg); c.lineWidth = nib * (0.8 + 0.4 * ((n2(i * 0.45) + 1) / 2)); c.beginPath(); c.moveTo(part[0][0], part[0][1]); for (let j = 1; j < part.length; j++) c.lineTo(part[j][0], part[j][1]); c.stroke(); } + c.restore(); + } + /** A closed outline in one stroke, overlapping itself a little where it ends. */ + outline(poly, o = {}) { const R = this.R, k = Math.floor(R() * poly.length), pts = poly.slice(k).concat(poly.slice(0, k)); const extra = resample(pts.concat([pts[0]]), 0.4).slice(0, 3); this.ink(pts.concat([pts[0]], extra), o); } + /** A box drawn as four strokes that overshoot the corners. */ + box(x0, y0, x1, y1, o = {}) { + const R = this.R, ov = () => R.range(0.25, 0.9) * (o.overshoot ?? 1), sides = [[[x0, y0], [x1, y0]], [[x1, y0], [x1, y1]], [[x1, y1], [x0, y1]], [[x0, y1], [x0, y0]]]; + for (const [a, b] of sides) { const d = Math.hypot(b[0] - a[0], b[1] - a[1]) || 1, ux = (b[0] - a[0]) / d, uy = (b[1] - a[1]) / d, e0 = ov(), e1 = ov(); this.ink([[a[0] - ux * e0, a[1] - uy * e0], [b[0] + ux * e1, b[1] + uy * e1]], o); } + } + dot(x, y, r, color) { const c = this.ctx; c.save(); c.fillStyle = color || this.INK; this.path(jitter(ell(x, y, r, r, 0, 24), r * 0.06, this.R)); c.fill(); c.restore(); } + text(str, x, y, o = {}) { + const c = this.ctx; c.save(); c.translate(x, y); c.rotate(o.rot ?? 0); if (o.slant) c.transform(1, 0, -o.slant, 1, 0, 0); + c.font = `${o.weight || 400} ${o.size || 4}px "${o.font || FONTS.hand}"`; c.textAlign = o.align || 'left'; c.textBaseline = o.baseline || 'alphabetic'; c.fillStyle = o.color || this.INK; c.globalAlpha = o.alpha ?? 0.96; c.fillText(str, 0, 0); c.restore(); + } + measure(str, o = {}) { const c = this.ctx; c.save(); c.font = `${o.weight || 400} ${o.size || 4}px "${o.font || FONTS.hand}"`; const w = c.measureText(str).width; c.restore(); return w; } + /** Writes the plate as PNG, with any smaller copies asked for: [['-x.jpg', 2048, 93], ['-preview.png', 1080]]. */ + save(file, { sizes = [] } = {}) { + fs.mkdirSync(path.dirname(file), { recursive: true }); + fs.writeFileSync(file, this.canvas.toBuffer('image/png')); + const written = [file], base = file.replace(/\.png$/i, ''); + for (const [suffix, px, quality] of sizes) { + const k = px / Math.max(this.W, this.H), c2 = createCanvas(Math.round(this.W * k), Math.round(this.H * k)), g = c2.getContext('2d'); + g.drawImage(this.canvas, 0, 0, c2.width, c2.height); + const out = base + suffix; fs.writeFileSync(out, /\.jpe?g$/i.test(suffix) ? c2.toBuffer('image/jpeg', quality ?? 92) : c2.toBuffer('image/png')); written.push(out); + } + return written; + } +} diff --git a/plugins/pstack/skills/statechart-diagram/scripts/lib/layout.mjs b/plugins/pstack/skills/statechart-diagram/scripts/lib/layout.mjs new file mode 100644 index 00000000..9877514f --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/lib/layout.mjs @@ -0,0 +1,113 @@ +// layout.mjs — from the Mermaid that /statechart wrote to a laid-out chart: pele places every box and arrow, +// measuring each word in the hand font, and this file reads the places back out of pele's SVG. +import { createCanvas } from '@napi-rs/canvas'; +import { FONTS, registerFonts } from './kit.mjs'; + +let pele; + +/** + * Takes the chart as /statechart wrote it. Drops the title (the plate writes its own), lifts the Legend block + * out (the plate draws it by hand), applies word changes, and sets the direction when asked. + */ +export function prepareMmd(text, { direction, say = [] } = {}) { + let fm = null, body = text.replace(/\r\n/g, '\n'); + const m = body.match(/^---\n([\s\S]*?)\n---\n/); + if (m) { fm = m[1]; body = body.slice(m[0].length); } + const title = fm?.match(/^title:\s*(.*?)\s*$/m)?.[1]?.replace(/^"(.*)"$/, '$1') ?? null; + const fmKept = fm ? fm.split('\n').filter((l) => !/^title:/.test(l)).join('\n').trim() : ''; + const legend = []; + const lg = body.match(/^[ \t]*state "Legend" as legend \{\n([\s\S]*?)\n[ \t]*\}[ \t]*\n/m); + if (lg) { for (const line of lg[1].split('\n')) { const mm = line.match(/^\s*(lg\d+):\s*(.*)$/); if (mm) legend.push({ id: mm[1], text: mm[2].trim(), classes: [] }); } body = body.replace(lg[0], ''); } + body = body.split('\n').filter((line) => { + const mm = line.match(/^\s*class (lg\d+) (.+)$/); + if (mm) { const item = legend.find((l) => l.id === mm[1]); if (item) item.classes.push(...mm[2].trim().split(/[\s,]+/)); return false; } + return !/^\s*classDef /.test(line); + }).join('\n'); + for (const [from, to] of say) body = body.split(from).join(to); + if (direction) body = /^\s*direction\s+\w+/m.test(body) ? body.replace(/^(\s*)direction\s+\w+/m, `$1direction ${direction}`) : body.replace(/(stateDiagram-v2[ \t]*\n)/, `$1 direction ${direction}\n`); + return { mmd: (fmKept ? `---\n${fmKept}\n---\n` : '') + body, title, legend }; +} + +const num = (s) => Number(s); +const attr = (tag, name) => { const m = tag.match(new RegExp(`\\s${name}="([^"]*)"`)); return m ? m[1] : undefined; }; +const unescape = (s) => s.replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); + +/** Points along an SVG path. Pele writes absolute M, L, H, V, C and Z. */ +export function pathPoints(d) { + const out = [], tok = d.match(/[MLHVCQZ]|-?\d*\.?\d+(?:e-?\d+)?/gi) || []; let i = 0, cmd = '', x = 0, y = 0; + const n = () => num(tok[i++]); + while (i < tok.length) { + if (/^[A-Z]$/i.test(tok[i])) cmd = tok[i++].toUpperCase(); + if (cmd === 'M' || cmd === 'L') { x = n(); y = n(); out.push([x, y]); } + else if (cmd === 'H') { x = n(); out.push([x, y]); } + else if (cmd === 'V') { y = n(); out.push([x, y]); } + else if (cmd === 'C') { const x1 = n(), y1 = n(), x2 = n(), y2 = n(), x3 = n(), y3 = n(), x0 = x, y0 = y; for (let k = 1; k <= 16; k++) { const t = k / 16, u = 1 - t; out.push([u * u * u * x0 + 3 * u * u * t * x1 + 3 * u * t * t * x2 + t * t * t * x3, u * u * u * y0 + 3 * u * u * t * y1 + 3 * u * t * t * y2 + t * t * t * y3]); } x = x3; y = y3; } + else if (cmd === 'Q') { const x1 = n(), y1 = n(), x2 = n(), y2 = n(), x0 = x, y0 = y; for (let k = 1; k <= 10; k++) { const t = k / 10, u = 1 - t; out.push([u * u * x0 + 2 * u * t * x1 + t * t * x2, u * u * y0 + 2 * u * t * y1 + t * t * y2]); } x = x2; y = y2; } + else if (cmd === 'Z') { if (out.length) out.push(out[0].slice()); } + else i++; + } + return out; +} +function textLines(t) { + if (!t) return []; + const spans = [...t.matchAll(/]*)>([^<]*)<\/tspan>/g)]; + if (spans.length) return spans.map((m) => ({ text: unescape(m[2]), x: num(attr(m[1], 'x') ?? 0), y: num(attr(m[1], 'y') ?? 0) })); + const m = t.match(/]*)>([^<]*)<\/text>/); + return m ? [{ text: unescape(m[2]), x: num(attr(m[1], 'x') ?? 0), y: num(attr(m[1], 'y') ?? 0) }] : []; +} + +/** Reads pele's SVG into boxes and lines, in pele's own pixels. */ +export function readSvg(svg) { + const vb = svg.match(/viewBox="0 0 ([\d.]+) ([\d.]+)"/); + const L = { width: num(vb[1]), height: num(vb[2]), clusters: [], dividers: [], edges: [], labels: [], nodes: [], starts: [] }; + const off = svg.match(//), ox = off ? num(off[1]) : 0, oy = off ? num(off[2]) : 0; + const P = (p) => [p[0] + ox, p[1] + oy]; + for (const m of svg.matchAll(/([\s\S]*?)<\/g>/g)) { + const rect = m[2].match(/]*>/)?.[0]; if (!rect) continue; + const head = m[2].match(/([\s\S]*?)<\/g>/g)) { + const paths = [...m[2].matchAll(/ !p[1]), marker = paths.find((p) => p[1]); + if (!line) continue; + const mk = marker ? pathPoints(marker[2]).map(P) : undefined; + L.edges.push({ id: m[1], pts: pathPoints(line[2]).map(P), tip: mk ? mk[0] : undefined }); + } + for (const m of svg.matchAll(/([\s\S]*?)<\/g>/g)) { + const rect = m[2].match(/]*>/)?.[0]; if (!rect) continue; + L.labels.push({ edge: m[1], x: num(attr(rect, 'x')) + ox, y: num(attr(rect, 'y')) + oy, w: num(attr(rect, 'width')), h: num(attr(rect, 'height')), lines: textLines(m[2].match(//)?.[0]).map((l) => ({ ...l, x: l.x + ox, y: l.y + oy })) }); + } + for (const m of svg.matchAll(/([\s\S]*?)<\/g>/g)) { + const rect = m[5].match(/]*>/)?.[0]; if (!rect) continue; + const cx = num(m[3]) + ox, cy = num(m[4]) + oy; + L.nodes.push({ id: m[2], classes: m[1].trim().split(/\s+/).filter(Boolean), cx, cy, w: num(attr(rect, 'width')), h: num(attr(rect, 'height')), rx: num(attr(rect, 'rx') || 0), lines: textLines(m[5].match(//)?.[0]).map((l) => ({ ...l, x: l.x + cx, y: l.y + cy })) }); + } + for (const m of svg.matchAll(/\s* [ox + (p[0] - box.x) * k, oy + (p[1] - box.y) * k], X: (x) => ox + (x - box.x) * k, Y: (y) => oy + (y - box.y) * k }; +} diff --git a/plugins/pstack/skills/statechart-diagram/scripts/lib/objects.mjs b/plugins/pstack/skills/statechart-diagram/scripts/lib/objects.mjs new file mode 100644 index 00000000..3d525d1d --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/lib/objects.mjs @@ -0,0 +1,88 @@ +// objects.mjs — small things to set around a chart, each drawn to fit a box {x0,y0,x1,y1}. +// An object is { w, h, draw(S, box, arg) }: w and h are its natural size in mm, so the placer knows what to ask for. +import { rrect, ell, tf, darker } from './kit.mjs'; + +export const C = { ink: '#2a2430', wood: '#c99b6b', woodDeep: '#9c7148', cream: '#f3e9d6', clay: '#c98a6a', teal: '#8fcbbf', slate: '#aeb4bb', red: '#b8352f', yellow: '#f0c75a', pink: '#f2b9c2', paper: '#faf5ea', graphite: '#3b3640', navy: '#3a4a5c', sky: '#cfe5ec', green: '#9dbb86', skin: '#f6e3d2' }; +const shadow = (S, poly, dx = 1.0, dy = 1.1) => S.hatch(poly.map(([x, y]) => [x + dx, y + dy]), { cut: [poly], angle: 45, pitch: 0.5, nib: 0.1 }); +/** A filled, outlined part: paper first, then pencil colour, then the pen. */ +export function part(S, poly, color, o = {}) { if (o.shadow) shadow(S, poly); S.fill(poly); if (color) S.pencil(poly, color, { pressure: o.pressure ?? 0.62, passes: o.passes ?? 2, angle: o.angle ?? 32 }); if (o.outline !== false) S.outline(poly, { nib: o.nib ?? 0.3 }); } +const fit = (b, w, h) => { const s = Math.min((b.x1 - b.x0) / w, (b.y1 - b.y0) / h); return { s, cx: (b.x0 + b.x1) / 2, cy: (b.y0 + b.y1) / 2, bottom: (b.y0 + b.y1) / 2 + h * s / 2 }; }; + +export const pen = { w: 20, h: 6, draw(S, b) { const { s, cx, cy } = fit(b, 20, 6), rot = -0.5, T = (p) => tf(p, { x: cx, y: cy, rot, s }); + part(S, T(rrect(-9, -1.1, 5.4, 1.1, 0.5)), C.navy, { pressure: 0.85, nib: 0.26 }); + part(S, T([[5.4, -1.1], [9.2, -0.15], [9.2, 0.15], [5.4, 1.1]]), '#d7c7a8', { pressure: 0.5, nib: 0.22 }); + part(S, T(rrect(-9.6, -1.3, -6.4, 1.3, 0.5)), '#2a3542', { pressure: 0.9, nib: 0.24 }); + S.ink(T([[-8.6, -1.3], [-8.6, -2.6], [-3.2, -2.6], [-3.2, -1.6]]), { nib: 0.2 }); } }; +/** A sheet with ruled lines. arg: a title; "signed:Title" adds a signature and a pen. */ +export const document = { w: 26, h: 32, draw(S, b, arg = '') { const signed = /^signed/.test(arg), title = arg.replace(/^signed:?/, '') || 'Contract'; const { s, cx, cy } = fit(b, 26, 32), rot = 0.06, T = (p) => tf(p, { x: cx - 1.5 * s, y: cy - 0.5 * s, rot, s }); + part(S, T(rrect(-11, -15, 11, 15, 0.4)), '#f3ead6', { shadow: true, pressure: 0.28, passes: 1, nib: 0.3 }); + S.text(title, ...T([[-8.6, -10.6]])[0], { font: 'Caveat', weight: 700, size: 4.2 * s, rot }); + for (let i = 0; i < 7; i++) S.ink(T([[-8.6, -6.4 + i * 2.3], [i === 6 ? 2 : 8.6, -6.4 + i * 2.3]]), { nib: 0.12, tremor: 0.08, color: '#6b6270' }); + if (signed) { const sig = []; for (let t = 0; t <= 1.001; t += 0.02) sig.push([-8.4 + t * 11, 11.6 - Math.sin(t * 17) * (1.3 - t) * 1.6 - Math.sin(t * 5) * 0.8]); S.ink(T(sig), { nib: 0.26, tremor: 0.05 }); S.ink(T([[-8.8, 13.2], [3.4, 13.2]]), { nib: 0.1, color: '#6b6270' }); pen.draw(S, { x0: cx + 1 * s, y0: cy + 5 * s, x1: cx + 15 * s, y1: cy + 15 * s }); } } }; +export const envelope = { w: 22, h: 15, draw(S, b) { const { s, cx, cy } = fit(b, 22, 15), rot = -0.08, T = (p) => tf(p, { x: cx, y: cy, rot, s }), body = T(rrect(-10, -6.5, 10, 6.5, 0.4)); + part(S, body, '#f0e3c6', { shadow: true, pressure: 0.3, passes: 1, nib: 0.3 }); + S.ink(T([[-10, -6.5], [0, 1.6], [10, -6.5]]), { nib: 0.26 }); + S.ink(T([[-10, 6.5], [-2.6, 0.2]]), { nib: 0.14, color: '#6b6270' }); S.ink(T([[10, 6.5], [2.6, 0.2]]), { nib: 0.14, color: '#6b6270' }); + part(S, T(ell(0, 1.6, 1.6, 1.5)), C.red, { pressure: 0.9, nib: 0.2 }); } }; +/** A rubber stamp. arg: the word; "word|#hex" picks the ink. */ +export const stamp = { w: 26, h: 12, draw(S, b, arg = 'APPROVED') { const [word, color = C.red] = arg.split('|'); const { s, cx, cy } = fit(b, 26, 12), rot = -0.22, w = S.measure(word, { size: 4.4 * s }) + 5 * s, h = 8.2 * s, T = (p) => tf(p, { x: cx, y: cy, rot }); + S.outline(T(rrect(-w / 2, -h / 2, w / 2, h / 2, 1.4 * s)), { nib: 0.5 * s, color, tremor: 0.1 }); + S.outline(T(rrect(-w / 2 + 1 * s, -h / 2 + 1 * s, w / 2 - 1 * s, h / 2 - 1 * s, 0.9 * s)), { nib: 0.16 * s, color, tremor: 0.08 }); + S.text(word, cx, cy, { size: 4.4 * s, color, align: 'center', baseline: 'middle', rot, alpha: 0.9 }); } }; +export const pencil = { w: 18, h: 5, draw(S, b) { const { s, cx, cy } = fit(b, 18, 5), rot = -0.08, T = (p) => tf(p, { x: cx, y: cy, rot, s }); + part(S, T([[-7, -1.2], [5, -1.2], [5, 1.2], [-7, 1.2]]), C.yellow, { pressure: 0.78, nib: 0.24, angle: 0 }); + S.ink(T([[-7, -0.1], [5, -0.1]]), { nib: 0.1, color: C.woodDeep }); + part(S, T([[5, -1.2], [8.4, 0], [5, 1.2]]), '#e8d7b6', { pressure: 0.45, nib: 0.2, passes: 1 }); + part(S, T([[7.4, -0.36], [8.4, 0], [7.4, 0.36]]), C.graphite, { pressure: 0.95, nib: 0.12, passes: 1 }); + part(S, T([[-8.6, -1.2], [-7, -1.2], [-7, 1.2], [-8.6, 1.2]]), C.pink, { pressure: 0.7, nib: 0.2, passes: 1 }); + part(S, T([[-7, -1.3], [-6, -1.3], [-6, 1.3], [-7, 1.3]]), C.slate, { pressure: 0.7, nib: 0.14, passes: 1 }); } }; +export const house = { w: 20, h: 18, draw(S, b) { const { s, cx, bottom } = fit(b, 20, 18), y = bottom - 0.6 * s, T = (p) => tf(p, { x: cx, y, s }); + S.ink(T([[-10, 0.3], [10, 0.3]]), { nib: 0.22 }); + part(S, T([[-7, -9], [7, -9], [7, 0], [-7, 0]]), '#f1e4c9', { pressure: 0.4, nib: 0.3, angle: 90 }); + part(S, T([[-8.4, -9], [0, -16.4], [8.4, -9]]), C.clay, { pressure: 0.7, nib: 0.3, angle: 20 }); + part(S, T([[4, -15.2], [6.2, -15.2], [6.2, -10.8], [4, -12.8]]), C.woodDeep, { pressure: 0.75, nib: 0.2, passes: 1 }); + part(S, T(rrect(-1.6, -5.6, 1.6, 0, 0.2)), C.woodDeep, { pressure: 0.78, nib: 0.22, passes: 1 }); + for (const sd of [-1, 1]) { part(S, T(rrect(sd * 2.8 - (sd < 0 ? 2.8 : 0), -7, sd * 2.8 + (sd > 0 ? 2.8 : 0), -4.2, 0.2)), C.sky, { pressure: 0.5, nib: 0.2, passes: 1 }); S.ink(T([[sd * 4.2, -7], [sd * 4.2, -4.2]]), { nib: 0.12 }); } } }; +export const bin = { w: 13, h: 17, draw(S, b) { const { s, cx, bottom } = fit(b, 13, 17), y = bottom - 0.5 * s, T = (p) => tf(p, { x: cx + 0.6 * s, y, s }), R = S.R; + const ball = []; for (let i = 0; i < 14; i++) { const a = (i / 14) * Math.PI * 2, r = 2.6 * R.range(0.72, 1.18); ball.push([-1.2 + Math.cos(a) * r, -12.4 + Math.sin(a) * r * 0.9]); } + part(S, T(ball), '#f4ecdb', { pressure: 0.25, passes: 1, nib: 0.22 }); + for (let i = 0; i < 4; i++) S.ink(T([[-1.2 + R.range(-2, 2), -12.4 + R.range(-1.6, 1.6)], [-1.2 + R.range(-2, 2), -12.4 + R.range(-1.6, 1.6)]]), { nib: 0.1, color: '#6b6270' }); + part(S, T([[-5.2, -10], [5.2, -10], [4.2, 0], [-4.2, 0]]), C.slate, { shadow: true, pressure: 0.42, nib: 0.3, angle: 90 }); + for (const lx of [-2.6, 0, 2.6]) S.ink(T([[lx * 1.15, -8.6], [lx, -1.2]]), { nib: 0.12, color: '#6b6270' }); + S.ink(T([[-5.8, -10], [5.8, -10]]), { nib: 0.3 }); } }; +/** A wall clock. arg: "h:mm" sets the hands. */ +export const clock = { w: 14, h: 14, draw(S, b, arg = '10:10') { const [hh, mm] = arg.split(':').map(Number); const { s, cx, cy } = fit(b, 14, 14), r = 6 * s, T = (p) => tf(p, { x: cx, y: cy, s }); + part(S, T(ell(0, 0, 6.6, 6.6)), '#f7f1e3', { shadow: true, pressure: 0.25, passes: 1, nib: 0.34 }); + for (let i = 0; i < 12; i++) { const a = i / 12 * Math.PI * 2, l = i % 3 ? 0.7 : 1.3; S.ink(T([[Math.cos(a) * 5.4, Math.sin(a) * 5.4], [Math.cos(a) * (5.4 - l), Math.sin(a) * (5.4 - l)]]), { nib: i % 3 ? 0.14 : 0.24 }); } + const ah = ((hh % 12) + (mm || 0) / 60) / 12 * Math.PI * 2 - Math.PI / 2, am = (mm || 0) / 60 * Math.PI * 2 - Math.PI / 2; + S.ink(T([[0, 0], [Math.cos(ah) * 3, Math.sin(ah) * 3]]), { nib: 0.4 }); S.ink(T([[0, 0], [Math.cos(am) * 4.4, Math.sin(am) * 4.4]]), { nib: 0.28 }); S.dot(cx, cy, 0.45 * s); void r; } }; +/** A coin or a note. arg: the sign, "$" by default. */ +export const coin = { w: 12, h: 12, draw(S, b, arg = '$') { const { s, cx, cy } = fit(b, 12, 12), T = (p) => tf(p, { x: cx, y: cy, s }); + part(S, T(ell(0, 0, 5.4, 5.4)), C.yellow, { shadow: true, pressure: 0.7, nib: 0.3 }); S.outline(T(ell(0, 0, 4.2, 4.2)), { nib: 0.14, color: C.woodDeep }); + S.text(arg, cx, cy, { size: 6 * s, align: 'center', baseline: 'middle', color: C.woodDeep }); } }; +/** A parcel, taped. arg: a label. */ +export const parcel = { w: 18, h: 16, draw(S, b, arg = '') { const { s, cx, bottom } = fit(b, 18, 16), y = bottom - 0.6 * s, T = (p) => tf(p, { x: cx, y, s }); + S.ink(T([[-9.4, 0.3], [9.4, 0.3]]), { nib: 0.22 }); + part(S, T([[-7.5, -13], [7.5, -13], [7.5, 0], [-7.5, 0]]), C.wood, { shadow: true, pressure: 0.55, nib: 0.3, angle: 0 }); + S.ink(T([[-7.5, -6.5], [7.5, -6.5]]), { nib: 0.14, color: C.woodDeep }); S.ink(T([[0, -13], [0, 0]]), { nib: 0.14, color: C.woodDeep }); + part(S, T(rrect(-1, -13.2, 1, 0.2, 0.1)), '#e9dcb8', { pressure: 0.5, passes: 1, nib: 0.12 }); + if (arg) { part(S, T(rrect(-6.2, -5, -1.8, -1.6, 0.2)), '#faf5ea', { pressure: 0.2, passes: 1, nib: 0.14 }); S.text(arg, cx - 4 * s, y - 2.6 * s, { size: 2.2 * s, align: 'center' }); } } }; +/** A pennant on a pole. arg: a word on the flag, or "|#hex" for its colour. */ +export const flag = { w: 14, h: 20, draw(S, b, arg = '') { const [word, color = C.red] = arg.split('|'); const { s, cx, bottom } = fit(b, 14, 20), y = bottom - 0.4 * s, T = (p) => tf(p, { x: cx - 4 * s, y, s }); + S.ink(T([[0, 0], [0, -18.6]]), { nib: 0.36 }); S.dot(...T([[0, -18.8]])[0], 0.5 * s); + part(S, T([[0.4, -18], [11.6, -14.6], [0.4, -11.2]]), color, { pressure: 0.75, nib: 0.28, angle: 10 }); + if (word) S.text(word, cx - 0.6 * s, y - 13.8 * s, { size: 2.4 * s, align: 'center', color: '#fff6ee' }); } }; +/** A person. arg: "pose|shirt" with pose stand, wave, hold or point, and a shirt colour. */ +export const person = { w: 12, h: 24, draw(S, b, arg = '') { const [pose = 'stand', shirt = C.teal] = arg.split('|'); const { s, cx, bottom } = fit(b, 12, 24), y = bottom - 0.4 * s, T = (p) => tf(p, { x: cx, y, s }), R = S.R; + const arm = (side, kind) => { const sh = [side * 3.2, -16.2]; const hand = kind === 'wave' ? [side * 6.4, -22.6] : kind === 'hold' ? [side * 2.2, -11.2] : kind === 'point' ? [side * 8.2, -15.4] : [side * 4.4, -9.8]; const el = kind === 'wave' ? [side * 5.6, -18.6] : [(sh[0] + hand[0]) / 2 + side * 0.8, (sh[1] + hand[1]) / 2]; S.ink(T([sh, el, hand]), { nib: 0.9 * s, color: shirt === 'paper' ? C.ink : darker(shirt, 0.1) }); S.ink(T([el, hand]), { nib: 0.75 * s, color: C.skin }); part(S, T(ell(hand[0], hand[1], 1.1, 1.05)), C.skin, { pressure: 0.5, passes: 1, nib: 0.18 }); }; + for (const sd of [-1, 1]) { part(S, T([[sd * 0.6, -9.6], [sd * 2.8, -9.6], [sd * 3.1, -1.2], [sd * 1.2, -1.2]]), C.navy, { pressure: 0.8, nib: 0.24, passes: 1 }); part(S, T(ell(sd * 2.4, -0.6, 2.2, 1.1)), C.graphite, { pressure: 0.9, nib: 0.22, passes: 1 }); } + arm(-1, pose === 'wave' || pose === 'point' ? 'stand' : pose); + part(S, T([[-3.4, -17.2], [3.4, -17.2], [3.9, -9.4], [-3.9, -9.4]]), shirt, { pressure: 0.68, nib: 0.28 }); + part(S, T(ell(0, -20.4, 2.7, 2.9)), C.skin, { pressure: 0.42, passes: 1, nib: 0.28 }); + part(S, T([[-2.9, -20.8], [-2.4, -23.4], [0, -23.9], [2.4, -23.4], [2.9, -20.8], [1.6, -21.6], [0, -22.2], [-1.6, -21.6]]), R.pick(['#3b2f2a', '#6b4a2e', '#2a2430', '#b5713b']), { pressure: 0.9, nib: 0.22, passes: 1 }); + for (const sd of [-1, 1]) S.dot(...T([[sd * 0.9, -20.6]])[0], 0.28 * s); + S.ink(T([[-0.9, -19.1], [0, -18.6], [0.9, -19.1]]), { nib: 0.18 }); + arm(1, pose); } }; +export const check = { w: 6, h: 6, draw(S, b, arg) { const { s, cx, cy } = fit(b, 6, 6); S.ink([[cx - 2.2 * s, cy], [cx - 0.5 * s, cy + 1.8 * s], [cx + 2.6 * s, cy - 2.4 * s]], { nib: 0.5 * s, color: arg || C.green }); } }; +export const cross = { w: 6, h: 6, draw(S, b, arg) { const { s, cx, cy } = fit(b, 6, 6), c = arg || C.red; S.ink([[cx - 2 * s, cy - 2 * s], [cx + 2 * s, cy + 2 * s]], { nib: 0.45 * s, color: c }); S.ink([[cx + 2 * s, cy - 2 * s], [cx - 2 * s, cy + 2 * s]], { nib: 0.45 * s, color: c }); } }; +export const OBJECTS = { pen, document, envelope, stamp, pencil, house, bin, clock, coin, parcel, flag, person, check, cross }; diff --git a/plugins/pstack/skills/statechart-diagram/scripts/lib/place.mjs b/plugins/pstack/skills/statechart-diagram/scripts/lib/place.mjs new file mode 100644 index 00000000..5d788a6c --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/lib/place.mjs @@ -0,0 +1,30 @@ +// place.mjs — finds room on the plate for a thing, beside the card it belongs to, where no arrow or word is. +export function makePlacer({ taken, edgePts, bounds }) { + const inside = (b, x, y) => x > b.x0 && x < b.x1 && y > b.y0 && y < b.y1; + const free = (b) => b.x0 > bounds.x0 && b.x1 < bounds.x1 && b.y0 > bounds.y0 && b.y1 < bounds.y1 + && !taken.some((t) => b.x0 < t.x1 + 1.2 && b.x1 > t.x0 - 1.2 && b.y0 < t.y1 + 1.2 && b.y1 > t.y0 - 1.2) + && !edgePts.some(([x, y]) => inside({ x0: b.x0 - 1, x1: b.x1 + 1, y0: b.y0 - 1, y1: b.y1 + 1 }, x, y)); + const claim = (b) => { taken.push(b); return b; }; + /** Beside a box: tries each side at growing distances, sliding along the side. */ + const near = (nb, w, h, prefs = ['right', 'left', 'below', 'above']) => { + if (!nb) return null; + for (const off of [3, 6, 10, 15, 22]) for (const side of prefs) { + const horizontal = side === 'right' || side === 'left'; + const cx = side === 'right' ? nb.x1 + off + w / 2 : side === 'left' ? nb.x0 - off - w / 2 : (nb.x0 + nb.x1) / 2; + const cy = side === 'below' ? nb.y1 + off + h / 2 : side === 'above' ? nb.y0 - off - h / 2 : (nb.y0 + nb.y1) / 2; + for (const slide of [0, -0.5, 0.5, -1, 1]) { + const dx = horizontal ? 0 : slide * w, dy = horizontal ? slide * h : 0; + const b = { x0: cx - w / 2 + dx, x1: cx + w / 2 + dx, y0: cy - h / 2 + dy, y1: cy + h / 2 + dy }; + if (free(b)) return claim(b); + } + } + return null; + }; + /** Anywhere: tries the given spots (bottom-centre points), then a coarse sweep of the plate. */ + const anywhere = (w, h, spots = []) => { + for (const [x, y] of spots) for (const dx of [0, 6, -6, 12, -12]) { const b = { x0: x + dx - w / 2, y0: y - h, x1: x + dx + w / 2, y1: y }; if (free(b)) return claim(b); } + for (let y = bounds.y1 - 1; y > bounds.y0 + h; y -= 8) for (let x = bounds.x0 + 1 + w / 2; x < bounds.x1 - w / 2; x += 8) { const b = { x0: x - w / 2, y0: y - h, x1: x + w / 2, y1: y }; if (free(b)) return claim(b); } + return null; + }; + return { free, near, anywhere, claim }; +} diff --git a/plugins/pstack/skills/statechart-diagram/scripts/package-lock.json b/plugins/pstack/skills/statechart-diagram/scripts/package-lock.json new file mode 100644 index 00000000..aff0d4f8 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/package-lock.json @@ -0,0 +1,231 @@ +{ + "name": "statechart-diagram-scripts", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "statechart-diagram-scripts", + "license": "MIT", + "dependencies": { + "@fontsource/caveat": "^5.0.0", + "@fontsource/patrick-hand": "^5.0.0", + "@napi-rs/canvas": "0.1.84", + "pele": "1.9.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@fontsource/caveat": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/caveat/-/caveat-5.3.0.tgz", + "integrity": "sha512-eHTfzQxFSW9ABERRLNruHoNJmKed2J7pqTUc5lp4a4POMgXGKpxmWj3d9Hz10kmAg6iuTTLe6UagbA4bnsmfQw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@fontsource/patrick-hand": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/patrick-hand/-/patrick-hand-5.3.0.tgz", + "integrity": "sha512-V8C38IlIFfdWg0Xtri3F7sLCVpm069rUwn6w4n+oyn38gt7H4arOJmuReg3tAw1Q6jHqZp89wTnAAJagq4Atxw==", + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@napi-rs/canvas": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-0.1.84.tgz", + "integrity": "sha512-88FTNFs4uuiFKP0tUrPsEXhpe9dg7za9ILZJE08pGdUveMIDeana1zwfVkqRHJDPJFAmGY3dXmJ99dzsy57YnA==", + "license": "MIT", + "workspaces": [ + "e2e/*" + ], + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@napi-rs/canvas-android-arm64": "0.1.84", + "@napi-rs/canvas-darwin-arm64": "0.1.84", + "@napi-rs/canvas-darwin-x64": "0.1.84", + "@napi-rs/canvas-linux-arm-gnueabihf": "0.1.84", + "@napi-rs/canvas-linux-arm64-gnu": "0.1.84", + "@napi-rs/canvas-linux-arm64-musl": "0.1.84", + "@napi-rs/canvas-linux-riscv64-gnu": "0.1.84", + "@napi-rs/canvas-linux-x64-gnu": "0.1.84", + "@napi-rs/canvas-linux-x64-musl": "0.1.84", + "@napi-rs/canvas-win32-x64-msvc": "0.1.84" + } + }, + "node_modules/@napi-rs/canvas-android-arm64": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-0.1.84.tgz", + "integrity": "sha512-pdvuqvj3qtwVryqgpAGornJLV6Ezpk39V6wT4JCnRVGy8I3Tk1au8qOalFGrx/r0Ig87hWslysPpHBxVpBMIww==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-darwin-arm64": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-0.1.84.tgz", + "integrity": "sha512-A8IND3Hnv0R6abc6qCcCaOCujTLMmGxtucMTZ5vbQUrEN/scxi378MyTLtyWg+MRr6bwQJ6v/orqMS9datIcww==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-darwin-x64": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-0.1.84.tgz", + "integrity": "sha512-AUW45lJhYWwnA74LaNeqhvqYKK/2hNnBBBl03KRdqeCD4tKneUSrxUqIv8d22CBweOvrAASyKN3W87WO2zEr/A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-0.1.84.tgz", + "integrity": "sha512-8zs5ZqOrdgs4FioTxSBrkl/wHZB56bJNBqaIsfPL4ZkEQCinOkrFF7xIcXiHiKp93J3wUtbIzeVrhTIaWwqk+A==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-gnu": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-0.1.84.tgz", + "integrity": "sha512-i204vtowOglJUpbAFWU5mqsJgH0lVpNk/Ml4mQtB4Lndd86oF+Otr6Mr5KQnZHqYGhlSIKiU2SYnUbhO28zGQA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-linux-arm64-musl": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-0.1.84.tgz", + "integrity": "sha512-VyZq0EEw+OILnWk7G3ZgLLPaz1ERaPP++jLjeyLMbFOF+Tr4zHzWKiKDsEV/cT7btLPZbVoR3VX+T9/QubnURQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-linux-riscv64-gnu": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-0.1.84.tgz", + "integrity": "sha512-PSMTh8DiThvLRsbtc/a065I/ceZk17EXAATv9uNvHgkgo7wdEfTh2C3aveNkBMGByVO3tvnvD5v/YFtZL07cIg==", + "cpu": [ + "riscv64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-gnu": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-0.1.84.tgz", + "integrity": "sha512-N1GY3noO1oqgEo3rYQIwY44kfM11vA0lDbN0orTOHfCSUZTUyiYCY0nZ197QMahZBm1aR/vYgsWpV74MMMDuNA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-linux-x64-musl": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-0.1.84.tgz", + "integrity": "sha512-vUZmua6ADqTWyHyei81aXIt9wp0yjeNwTH0KdhdeoBb6azHmFR8uKTukZMXfLCC3bnsW0t4lW7K78KNMknmtjg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@napi-rs/canvas-win32-x64-msvc": { + "version": "0.1.84", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-0.1.84.tgz", + "integrity": "sha512-YSs8ncurc1xzegUMNnQUTYrdrAuaXdPMOa+iYYyAxydOtg0ppV386hyYMsy00Yip1NlTgLCseRG4sHSnjQx6og==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/pele": { + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/pele/-/pele-1.9.0.tgz", + "integrity": "sha512-KUmBt7P5JduVKQaP6FKfXiRgH3LBVIKsmdgPJZU7jD3ye6F+Z8fbms+OjivE7rWY09Qx+5X65VKe/9ywKFJ9Sw==", + "license": "MIT", + "engines": { + "node": ">=20" + } + } + } +} diff --git a/plugins/pstack/skills/statechart-diagram/scripts/package.json b/plugins/pstack/skills/statechart-diagram/scripts/package.json new file mode 100644 index 00000000..f47b2935 --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/package.json @@ -0,0 +1,14 @@ +{ + "name": "statechart-diagram-scripts", + "private": true, + "type": "module", + "description": "Draws a /statechart chart as a plate in pen and coloured pencil: pele lays the chart out, the kit draws it on paper.", + "license": "MIT", + "engines": { "node": ">=20" }, + "dependencies": { + "@fontsource/caveat": "^5.0.0", + "@fontsource/patrick-hand": "^5.0.0", + "@napi-rs/canvas": "0.1.84", + "pele": "1.9.0" + } +} diff --git a/plugins/pstack/skills/statechart-diagram/scripts/plate.mjs b/plugins/pstack/skills/statechart-diagram/scripts/plate.mjs new file mode 100644 index 00000000..d5f5d7bd --- /dev/null +++ b/plugins/pstack/skills/statechart-diagram/scripts/plate.mjs @@ -0,0 +1,140 @@ +#!/usr/bin/env node +// plate.mjs — draws a /statechart chart as a plate in pen and coloured pencil. +import fs from 'node:fs'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { Sheet, rrect, ell, tf, registerFonts, FONTS } from './lib/kit.mjs'; +import { prepareMmd, layOut, contentBox, mapper } from './lib/layout.mjs'; +import { drawChart, drawLegend, GROUP, MARK } from './lib/chart.mjs'; +import { OBJECTS, part, C } from './lib/objects.mjs'; +import { makePlacer } from './lib/place.mjs'; + +const USAGE = `Usage: plate.mjs CHART.mmd [options] + +Draws the chart as a square plate: the title block top left, the legend top right, the chart in the middle, +and small things of the reader's world around it where there is room. Reads report.md beside the chart, +when there is one, for the line under the title. + + --out DIR where to write (default: /plate) + --name NAME file name stem (default: plate) -> NAME.png, NAME-x.jpg, NAME-preview.png, + NAME-layout.svg, NAME-plate.json + --title WORDS the big words (default: the chart's title, else the file name) + --subtitle WORDS the line under the title + --note WORDS the small line (default: what report.md says TLC checked) + --footer WORDS the small print, bottom left (default: the credit line) + --source WORDS a second small-print line, e.g. the repo and commit + --say "OLD=NEW" change words in the chart before drawing; repeatable + --dir TB|LR chart direction; with no --dir both are tried and the one whose words + come out bigger is kept + --near ID=OBJECT[:ARG][@SCALE] put a thing beside the state with that id; repeatable + objects: ${Object.keys(OBJECTS).join(', ')} + --anywhere OBJECT[:ARG][@SCALE] put a thing wherever there is room; repeatable + --scene FILE.mjs a module that draws more (see references/scene-modules.md) + --no-legend leave the legend out + --no-marks do not stamp "rule broken" beside a state that breaks a rule + --seed WORDS the hand's seed; same seed, same picture (default: the title) + --size MM plate side in mm (default 216) + --ppm N pixels per mm (default 10 -> 2160 px; --fast uses 5) + --text-scale X grow or shrink the chart's words (default 1) + --spacing R,N pele's rankSpacing,nodeSpacing when the chart has none (default 26,36) + --fast half size, for a quick look +Exit 0 when the plate is written, 2 on a bad input.`; + +function parseArgs(argv) { + const o = { say: [], near: [], anywhere: [] }; const pos = []; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--help' || a === '-h') { console.log(USAGE); process.exit(0); } + if (a === '--fast' || a === '--no-legend' || a === '--no-marks') { o[a.slice(2).replace(/-(\w)/g, (_, c) => c.toUpperCase())] = true; continue; } + if (a.startsWith('--')) { const key = a.slice(2).replace(/-(\w)/g, (_, c) => c.toUpperCase()), v = argv[++i]; if (v === undefined) fail(`${a} needs a value`); if (Array.isArray(o[key])) o[key].push(v); else o[key] = v; continue; } + pos.push(a); + } + if (pos.length !== 1) fail('Give one chart file.'); + return { ...o, chart: pos[0] }; +} +function fail(msg) { console.error(`${msg}\n\n${USAGE}`); process.exit(2); } + +function readReport(chartFile) { + const f = path.join(path.dirname(chartFile), 'report.md'); if (!fs.existsSync(f)) return null; + const t = fs.readFileSync(f, 'utf8'), r = {}; + const m = t.match(/TLC reached (\d[\d,]*) states? and (\d[\d,]*) steps?/); if (m) { r.states = m[1]; r.steps = m[2]; } + const section = (name) => { const mm = t.match(new RegExp(`^## ${name}[^\\n]*\\n([\\s\\S]*?)(?=\\n## |$)`, 'm')); return mm ? mm[1].trim() : null; }; + const hold = section('Rules that hold'); r.hold = hold ? hold.split('\n')[0].split(/,\s*/).map((s) => s.trim()).filter(Boolean) : []; + const broke = section('Rules that break'); r.break = broke ? [...new Set([...broke.matchAll(/^###\s+(\S+)/gm)].map((x) => x[1]).concat(broke.split('\n')[0].startsWith('#') ? [] : broke.split('\n')[0].split(/,\s*/).map((s) => s.trim()).filter((s) => /^\w+$/.test(s))))] : []; + const unchecked = section('Rules not checked'); r.unchecked = unchecked ? unchecked.split('\n')[0].split(/,\s*/).map((s) => s.trim()).filter(Boolean) : []; + return r; +} +const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`; +function defaultNote(rep) { + if (!rep) return ''; + const bits = []; + if (rep.states) bits.push(`checked by TLC: ${rep.states} states, ${rep.steps} steps`); + if (rep.hold.length) bits.push(`${plural(rep.hold.length, 'rule')} hold`); + if (rep.break.length) bits.push(`${plural(rep.break.length, 'rule')} break: ${rep.break.join(', ')}`); + if (rep.unchecked.length) bits.push(`${plural(rep.unchecked.length, 'rule')} not checked`); + return bits.join(' · '); +} +const fitSize = (S, text, o, max, maxSize, minSize) => { let s = maxSize; while (s > minSize && S.measure(text, { ...o, size: s }) > max) s -= 0.2; return s; }; +const parseThing = (spec) => { const m = spec.match(/^([a-zA-Z]+)(?::(.*?))?(?:@([\d.]+))?$/); if (!m || !OBJECTS[m[1]]) fail(`Unknown object in "${spec}". Objects: ${Object.keys(OBJECTS).join(', ')}`); return { name: m[1], arg: m[2], scale: m[3] ? Number(m[3]) : 1 }; }; + +async function main() { + const a = parseArgs(process.argv.slice(2)); + if (!fs.existsSync(a.chart)) fail(`Cannot find ${a.chart}`); + const size = Number(a.size || 216), ppm = a.fast ? 5 : Number(a.ppm || 10), u = size / 216; + const outDir = a.out || path.join(path.dirname(a.chart), 'plate'), name = a.name || 'plate'; + const say = a.say.map((s) => { const i = s.indexOf('='); if (i < 0) fail(`--say wants OLD=NEW, got "${s}"`); return [s.slice(0, i), s.slice(i + 1)]; }); + const raw = fs.readFileSync(a.chart, 'utf8'); + const withSpacing = (mmd) => { if (/^---\n[\s\S]*config:/m.test(mmd)) return mmd; const [rs, ns] = (a.spacing || '26,36').split(',').map(Number), cfg = `config:\n state:\n rankSpacing: ${rs}\n nodeSpacing: ${ns}`; return /^---\n/.test(mmd) ? mmd.replace(/^---\n([\s\S]*?)\n---\n/, (_, fm) => `---\n${fm}\n${cfg}\n---\n`) : `---\n${cfg}\n---\n` + mmd; }; + registerFonts(); + const chartTo = { x: 8 * u, y: 48 * u, w: 200 * u, h: 158 * u }; + // lay it out; with no --dir, try both ways and keep the one whose words come out bigger + let laid = []; + for (const dir of a.dir ? [a.dir] : ['TB', 'LR']) { const prep = prepareMmd(raw, { direction: dir, say }); const L = await layOut(withSpacing(prep.mmd)); if (!L.nodes.length) fail('pele found no states in the chart. Is it a stateDiagram-v2?'); const box = contentBox(L); laid.push({ dir, prep, L, box, k: Math.min(chartTo.w / box.w, chartTo.h / box.h) }); } + laid.sort((p, q) => q.k - p.k); + const { dir: chosenDir, prep: { title: chartTitle, legend }, L } = laid[0]; + let title = a.title || chartTitle || path.basename(a.chart, path.extname(a.chart)); + const rep = readReport(a.chart), note = a.note ?? defaultNote(rep); + const S = new Sheet({ w: size, h: size, ppm, seed: a.seed || title }); + S.paper(); + + // the words at the top: the title on one line, or two when it is long, then the subtitle and the small line + const left = 11.5 * u, titleRoom = (a.noLegend || !legend.length ? 190 : 112) * u, disp = { font: FONTS.display, weight: 700 }; + let titleLines = [title], titleSize = fitSize(S, title, disp, titleRoom, 19 * u, 12 * u); + if (S.measure(title, { ...disp, size: titleSize }) > titleRoom) { + const cut = title.match(/^(.{8,}?[:,;])\s+(.+)$/) || (() => { const w = title.split(' '); const h = Math.ceil(w.length / 2); return w.length > 1 ? [null, w.slice(0, h).join(' '), w.slice(h).join(' ')] : null; })(); + if (cut) { titleLines = [cut[1], cut[2]]; titleSize = Math.min(...titleLines.map((t) => fitSize(S, t, disp, titleRoom, 13.5 * u, 8 * u))); } + } + let y = (titleLines.length > 1 ? 18 : 24) * u; + titleLines.forEach((t, i) => { S.text(t, left, y, { ...disp, size: titleSize, rot: -0.012 }); if (i < titleLines.length - 1) y += titleSize * 0.95; }); + if (a.subtitle) { const ss = fitSize(S, a.subtitle, { font: FONTS.display }, titleRoom + 6 * u, (titleLines.length > 1 ? 6 : 7.6) * u, 4.2 * u); y += ss * 1.15 + 0.6 * u; S.text(a.subtitle, left + 1 * u, y, { font: FONTS.display, size: ss, rot: -0.008 }); } + if (note) { const ns = fitSize(S, note, {}, titleRoom + 10 * u, 3.3 * u, 2.4 * u); y += ns * 2.0; S.text(note, left + 1.1 * u, y, { size: ns, color: '#4a4350' }); } + const titleBox = { x0: 8 * u, x1: (a.noLegend || !legend.length ? 212 : 126) * u, y0: 10 * u, y1: 46 * u }; + const legendBox = a.noLegend ? null : drawLegend(S, legend, { x0: 130 * u, y0: 10 * u, width: 80 * u }); + + // the chart + const box = contentBox(L), kMax = 0.42 * u, fit = Math.min(chartTo.w / box.w, chartTo.h / box.h), to = fit > kMax ? { x: chartTo.x + (chartTo.w - box.w * kMax) / 2, y: chartTo.y + (chartTo.h - box.h * kMax) / 2, w: box.w * kMax, h: box.h * kMax } : chartTo, m = mapper(box, to); + const res = drawChart(S, L, m, { textScale: Number(a.textScale || 1) }); + const taken = [...res.nodeBoxes, ...res.labelBoxes, titleBox].concat(legendBox ? [legendBox] : []); + const placer = makePlacer({ taken, edgePts: res.edgePts, bounds: { x0: 5 * u, x1: 211 * u, y0: 8 * u, y1: 208 * u } }); + const placed = [], skipped = []; + const put = (thing, where, label) => { const ob = OBJECTS[thing.name], w = ob.w * thing.scale * u, h = ob.h * thing.scale * u, b = where(w, h); if (b) { ob.draw(S, b, thing.arg); placed.push({ what: label, box: b }); } else skipped.push(label); }; + if (!a.noMarks) for (const b of res.nodeBoxes) { const broke = b.n.classes.includes('breaks'), may = b.n.classes.includes('mayBreak'); if (broke || may) put({ name: 'stamp', arg: `${broke ? 'rule broken' : 'may break'}|${broke ? MARK.breaks : MARK.mayBreak}`, scale: 0.85 }, (w, h) => placer.near(b, w, h, ['right', 'left', 'above', 'below']), `stamp beside ${b.n.id}`); } + for (const spec of a.near) { const i = spec.indexOf('='); if (i < 0) fail(`--near wants ID=OBJECT, got "${spec}"`); const id = spec.slice(0, i), thing = parseThing(spec.slice(i + 1)), nb = res.nodeBoxes.find((b) => b.n.id === id); if (!nb) { skipped.push(`${thing.name} near ${id} (no state with that id; ids: ${res.nodeBoxes.map((b) => b.n.id).join(' ')})`); continue; } put(thing, (w, h) => placer.near(nb, w, h), `${thing.name} near ${id}`); } + for (const spec of a.anywhere) { const thing = parseThing(spec); put(thing, (w, h) => placer.anywhere(w, h, [[33 * u, 100 * u], [186 * u, 196 * u], [36 * u, 206 * u], [190 * u, 150 * u], [196 * u, 92 * u]]), `${thing.name} anywhere`); } + if (a.scene) { const mod = await import(pathToFileURL(path.resolve(a.scene)).href); const ctx = { S, L, m, res, placer, placed, skipped, objects: OBJECTS, kit: { rrect, ell, tf, part, C, GROUP, MARK }, u, title, legend, report: rep }; if (typeof mod.default === 'function') await mod.default(ctx); else fail(`${a.scene} must export a default function (ctx) => void`); } + + // the small print + const footer = a.footer ?? (rep ? 'drawn by code with statechart-diagram, after Kevin Ngo’s statechart-art \u00b7 the states and arrows are the model TLC checked' : 'drawn by code with statechart-diagram, after Kevin Ngo’s statechart-art \u00b7 a chart, not a checked model'); + S.text(footer, left, (a.source ? 210.4 : 212.2) * u, { size: fitSize(S, footer, {}, 196 * u, 2.7 * u, 2.1 * u), color: '#5a5260' }); + if (a.source) S.text(a.source, left, 214 * u, { size: fitSize(S, a.source, {}, 196 * u, 2.7 * u, 2.1 * u), color: '#5a5260' }); + + fs.mkdirSync(outDir, { recursive: true }); + const files = S.save(path.join(outDir, `${name}.png`), { sizes: [['-x.jpg', 2048, 93], ['-preview.png', 1080]] }); + fs.writeFileSync(path.join(outDir, `${name}-layout.svg`), L.svg); + const r2 = (v) => Math.round(v * 10) / 10, bx = (b) => ({ x0: r2(b.x0), y0: r2(b.y0), x1: r2(b.x1), y1: r2(b.y1) }); + const json = { title, note, chart: a.chart, direction: chosenDir, size, ppm, seed: a.seed || title, states: res.nodeBoxes.map((b) => ({ id: b.n.id, words: b.n.lines.map((q) => q.text).join(' '), classes: b.n.classes, box: bx(b) })), arrows: res.edgeInfo, placed: placed.map((p) => ({ what: p.what, box: bx(p.box) })), skipped, legend }; + fs.writeFileSync(path.join(outDir, `${name}-plate.json`), JSON.stringify(json, null, 1)); + console.log(`Drew "${title}" ${chosenDir}${a.dir ? '' : ' (chosen: the words come out bigger than ' + laid[1].dir + ')'}: ${plural(res.nodeBoxes.length, 'state')}, ${plural(L.edges.length, 'arrow')}, ${plural(placed.length, 'thing')} placed${skipped.length ? `, ${skipped.length} skipped for want of room (${skipped.join('; ')})` : ''}.`); + console.log(`Look at ${path.join(outDir, `${name}-preview.png`)}. Files: ${files.map((f) => path.basename(f)).join(', ')}, ${name}-layout.svg, ${name}-plate.json in ${outDir}`); +} +main().catch((e) => { console.error(e.stack || e); process.exit(2); }); diff --git a/plugins/pstack/skills/statechart/SKILL.md b/plugins/pstack/skills/statechart/SKILL.md index f5a64a8d..e22b2128 100644 --- a/plugins/pstack/skills/statechart/SKILL.md +++ b/plugins/pstack/skills/statechart/SKILL.md @@ -77,6 +77,6 @@ Render charts with Pele. When the user asks for an image, or a chart is too larg ## Hand off -Give each chart and its Mermaid text to the person who must decide. Add one line for each bug: the rule, the reader's sentence for that rule, and the path as the report numbers it. Say what the model leaves out. Give the command that makes the files again, with a new `--out` folder. +Give each chart and its Mermaid text to the person who must decide. Add one line for each bug: the rule, the reader's sentence for that rule, and the path as the report numbers it. Say what the model leaves out. Give the command that makes the files again, with a new `--out` folder. Then draw the plate: invoke the `statechart-diagram` skill on the output folder, so the reader gets the chart as a picture they will keep. The plugin's `after-statechart` hook asks for the same thing once the chart is written; do it once. When the model describes code, replay each bug path against the real code, as a test or a live repro, one step for each action. If a bug does not occur, think that the model is wrong until you show that it is not. diff --git a/scripts/__pycache__/release.cpython-313.pyc b/scripts/__pycache__/release.cpython-313.pyc new file mode 100644 index 00000000..4d0ef195 Binary files /dev/null and b/scripts/__pycache__/release.cpython-313.pyc differ