SLOPSHOPPER

craftsman

Stack-agnostic doc-first command loop plus a deterministic quality engine — regression-only lint/type gates, acceptance-criteria enforcement, routed review…

statusprocess
v?MITupdated 2026-10-26plantgreytrees/craftsman
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · craftsman
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ craftsman: craftsman · ctx 49%
README

craftsman

v2.3.1 — see CHANGELOG.md for what changed.

A Claude Code plugin that makes code better automatically, in any language. It runs your formatters, linters and type-checkers on every edit and reports only the issues you introduce. It won't let a task count as "done" if the tests broke, a secret leaked or a plan criterion is still open. On top of that it adds a doc-first workflow (idea → architecture → plan → build → review → docs → merge) that can run unattended, with guards that keep it inside the lines.

Drop it into a Python, Go, Rust, Java, Ruby, JS/TS, C#, Swift, Kotlin, PHP, C++, Terraform or Kubernetes repo and run /craftsman:init. It detects your stack and configures itself. It is dependency-free: Node only, which ships with Claude Code.

Contents: Quick start · How it works · Features · Commands · Configure it · Full update · Good to know · Safety · Layout


What's new in 2.3.1

  • Automatic archive hardened. The in-process landing capability can be obtained only through one function and a wiring test limits who names it. Injected test seams get a marker the real retire refuses, and a landing retire with no archive project refuses before removing anything.
  • Unit merges respect approval. With the approval gate on, a unit merge to base needs your approval too.
  • Claims and the unit runner. Claims anchor at the main checkout, and the runner's helper runs from the project root so workspace mode resolves it.
  • UI gate. It routes to the Artist agent or an accessibility fallback.

The full list is in CHANGELOG.md.

What's new in 2.3.0

  • Approval before base. With planning.featureBranches on, a run stops at one private page (Merge now / Open PR) and lands only on your own checked click. Headless runs fall back to Markdown and one terminal question.
  • Guards fail closed. Every hook runs through hooks/run.sh. Only CRAFTSMAN_SAFETY=off in your own environment turns the safety guards off, and the model cannot switch them off.
  • Evidence-based worktree sweep. A branch counts as merged only into a remote-tracking ref, and every deleted branch is logged and recoverable.
  • Dashboard, notes export and archive. /digest --html, an Obsidian/Foam/Quartz notes folder, and automatic archiving of closed plans through an in-process landing capability.
  • Ledger guard, measurement and tool slots. Tracker publishing never drops a committed row. Per-session context is measured, and just check leads the stop-gate commands.
  • Docs. This README now explains how craftsman works and gives a step-by-step full update.

The full list is in CHANGELOG.md.


Quick start

# 1 — install  (from GitHub once published; see PUBLISH.md)
/plugin marketplace add plantgreytrees/craftsman
/plugin install craftsman@craftsman-marketplace

# 2 — restart Claude Code so the hooks load, then in your repo:
/craftsman:init        # audit, upgrade older setup, and repair required structure
/craftsman:baseline    # snapshot existing lint issues so only NEW ones get flagged

That's the whole setup. To install from a local folder instead of GitHub, use /plugin marketplace add /absolute/path/to/craftsman. The full walkthrough and troubleshooting are in INSTALL.md.

A first piece of work then looks like this:

/craftsman:auto add rate limiting to the public API

/auto asks its open questions up front, plans the work, builds each unit in its own worktree with gates and reviews, asks once more about anything that came back, and lands the result.


How it works

Craftsman is three things working together: hooks that run on every tool call, a set of commands and agents that make up the workflow, and state on disk that both of them read and write.

1. Hooks: the part that runs itself

Claude Code calls craftsman's hooks at fixed points in every session (hooks/hooks.json). Every hook goes through one launcher, hooks/run.sh, which fails closed for the safety hooks.

WhenHookWhat it does
Session startsession-context, tracker-syncstates that the guards are on, names unlanded approvals, restores the last hand-off, re-renders the tracker
Before Read/Glob/Grep/Write/Edit/Bashpre-guardprotected paths, unit scope, doc-write authority, tracker block, hook-bypass flags, force-push and other git rules
Before Task/Agent/Workflowagent-mode-guardenforces root-only agent mode and its named exceptions
Before Skillbuiltin-skill-contexthands the built-in simplify / code-review skills the governing rules and open criteria
After Write/Editquality-gateformat → lint → type-check the edited file; feeds new issues back to Claude mid-turn
After Bash/Write/Edittracker-syncre-renders TRACKER.md from the ledger
Prompt submit, after Skillorchestrate-scope-guardbinds a running /orchestrate to its plan unit
Stopstop-gate, tracker-sync, telemetrysecrets scan, test-regression check, extraChecks, open acceptance criteria, unpushed-work report, gate telemetry
Session endsession-endunpushed-work report and hand-off

2. The quality engine: three layers, cheapest first

Each layer does only what the one below it can't:

LayerWhat happensCost
Deterministicon every edit: format → lint → type-check. At "done": secrets scan + test-regression check, skipped when nothing changed since the last check. Only newly introduced issues are reported.~free
Feedbackwhen a check fails, its output is fed straight back to Claude mid-turn to fix~free
JudgmentLLM review (correctness, security, house-style conformance, plan soundness) runs only where linters are structurally blind, and only when a cheap router says the diff is worth itgated

Every check is a config entry that silently skips if its tool isn't installed. So the same plugin lints Python with ruff, Go with staticcheck and Rust with clippy, wherever those tools exist. Adding a language is a one-block config edit, never a code change.

3. The workflow: a doc-first loop

flowchart LR
  idea["/idea<br/>vet it"] --> arch["/architect<br/>decide + rules"]
  arch --> plan["/plan<br/>plan doc + tracker rows"]
  und["/understand<br/>/investigate"] --> plan
  plan --> orch["/orchestrate<br/>unit by unit"]
  orch --> scr["/scrutinise<br/>isolated review"]
  scr -->|findings| plan
  scr --> sync["/sync-docs<br/>docs = code"]
  sync --> merge["/craftsman:merge<br/>land + clean up"]
  auto(["/craftsman:auto"]) -.drives.-> plan
  auto -.-> orch
  auto -.-> merge
  • One slug names the work from idea doc to plan, fix round and sync.
  • /idea checks a new idea for overlap and whole-system fit, then has it judged by one isolated critic. The result is a scored verdict in docs/ideas/.
  • /architect turns a vetted idea into decisions you confirm. Each area is written as a pair: <area>.md for people and <area>.rules.md, a list of numbered ARCH-… rules the loop enforces.
  • /plan writes the only plan docs (docs/plans/<slug>.md). Each unit gets scope, acceptance criteria, cited rules and a tooling manifest.
  • /orchestrate executes a plan one unit at a time, each in its own git worktree. gate-select.mjs reads the unit's actual diff and routes it to the specialists that apply: security-auditor, the ui gate (ui-gate.mjs: Artist when present, else the ui-ux-reviewer accessibility floor), migration-reviewer, api-reviewer, dependency-auditor, performance-reviewer, observability-reviewer. It doesn't rely on anyone remembering a file-pattern rule.
  • /scrutinise sends one fresh-context reviewer to audit the merged work against every open criterion. Its findings become the next plan round.
  • /sync-docs reconciles docs and tracker chips with shipped code. /craftsman:merge lands the branch and cleans up.
  • /craftsman:auto is the single entry for the whole loop. It asks every open decision first, runs the units unattended in fresh agent contexts, asks about parked rows, and lands the result. It repeats until every row is COMPLETE.
  • /instruction packs the same loop into one paste-ready /goal prompt with a size estimate.

4. State on disk

WhereWhatCommitted?
craftsman.config.json (+ optional craftsman.project.json)your overrides, deep-merged over the plugin defaultsyes
docs/ideas/, docs/architecture/, docs/plans/idea verdicts, decisions + rules, plan docsyes
docs/plans/TRACKER.md, TRACKER-archive.mdthe readable tracker and retired rowsyes
docs/errors/KNOWN_ISSUES.mdpre-existing lint debt, written by /craftsman:baselineyes
.craftsman/tracker/events.jsonlthe validated tracker ledger (source of truth for status)no
.craftsman/sessions/<id>/per-session baseline, criteria and doc authorityno
.craftsman/claims/, runs/, approvals/, instructions/unit claims, run manifests, pending approvals, /goal filesno
.craftsman/events.jsonl, sweep-log.jsonlgate telemetry for /craftsman:stats, deleted-branch logno

Features

Only your issues are flagged. /craftsman:baseline snapshots existing findings, so the gate reports only what you introduce. It also writes what it skipped to docs/errors/KNOWN_ISSUES.md (worst file first, regenerated on every run). A legacy repo's debt stays visible instead of living only in a gitignored snapshot.

"Done" is a contract. The Stop gate blocks completion on a failed secrets scan, a test regression or an unticked acceptance criterion. Criteria are written at plan time and enforced before a task can finish.

Architecture is enforced, not just written down. /plan cites the rules for each unit, and plan-reviewer and the scrutineer check them. scope.mjs refuses to activate a unit that writes a governed path until it has loaded and cited the rules for that path. Breaking a decided rule takes /architect, never a workaround.

Unattended runs that stay light. /craftsman:auto runs each unit in a fresh agent context (execution.engine: workflow by default, else subagent or root). Every unit ends in a hand-off on disk, so auto-compact never loses the thread. /plan refuses a unit too large for one fresh agent (execution.unitContextBytes).

One approval page. With planning.featureBranches on, a run stops at a verification point: a private claude.ai page shows what changed, env keys touched, evidence, risk and rollback, with Merge now / Open PR buttons. Only your own click, re-read and checked against the feature head, lands it. Headless runs fall back to a Markdown page and one terminal question.

Concurrent sessions are safe. Session state is isolated, each unit runs in its own worktree, and the tracker lives in the main checkout so every session sees one board. Stale claims from crashed sessions are recoverable.

Progress you can read. /craftsman:digest gives done / decisions needed / next / % complete per plan. /digest --html renders a local dashboard, and the notes export produces an Obsidian/Foam/Quartz folder. /craftsman:stats shows which gates actually fire, so you can delete the ones that don't earn their keep.

Built-in skills, craftsman's rules. /orchestrate runs Claude Code's own simplify and code-review skills inside the loop. Their output is only a candidate list: code-reviewer owns the verdict.

Safety guards that fail closed. See Safety.


Commands

CommandWhat it's for
/craftsman:initaudit or upgrade the setup, detect the stack, and repair the required project structure (--check, --diff, --write, --update, --settings-diff)
/craftsman:upgradeupdate every Craftsman install (user and per-project) to the latest commit, then tell you what to reload and re-init (--dry-run)
/craftsman:workspace-initexplicitly register selected existing Git projects without scanning the workspace
/ideascrutinise an idea before building it: overlap scan, whole-system fit, research, one isolated critic, scored verdict (--deep for a stronger critic)
/architectturn a vetted idea into confirmed engineering, data and systems decisions, written as enforced architecture docs (--deep, --init, --update; --backfill derives them for a project with existing plans and legacy docs)
/craftsman:autoone entry for the whole loop: ask every open decision first, run the units unattended in fresh agent contexts, ask about parked rows, land; repeat until every row is COMPLETE
/craftsman:auto-goone key to launch the newest /craftsman:auto goal
/instructiongenerate one paste-ready /goal prompt that drives the whole loop to verified completion, plus an effort estimate
/understandbuild a cited understanding of a feature or area before touching it
/planturn a request into a build-ready plan doc (the only command that writes plans)
/orchestrateimplement a plan doc across the repo, with per-unit routed review
/investigateroot-cause a bug into a fix-ready analysis
/scrutinisereview what was built (routed, so trivial diffs stay cheap; --deep for a deeper round)
/sync-docsreconcile docs and tracker with shipped code (--arch, --tracker, --all, --archive, --prune)
/craftsman:mergeland a finished branch or worktree when you say "merge": tests, merge, push, then remove the worktree and the local and remote branch
/fix-testsget a red test suite green
/craftsman:digestprogress digest: done, decisions needed, next, % complete per plan
/craftsman:baselinesnapshot pre-existing lint issues (run once per repo, again after a tooling change)
/craftsman:statssee which gates actually fire, so you can delete the ones that don't earn their keep
/craftsman:toggleturn the gates on or off for this repo
/craftsman:account-switchswitch Claude account mid-session without losing the thread: prepare a hand-off before /login, restore it after, or recover one from the transcript; hands a running plan's claims to the new session
/craftsman:builtin-checkafter claude update: verify the wrapped Claude Code built-ins still match craftsman's assumptions, and propose new ones to wrap (--report-only)

Configure it for your stack

/craftsman:init writes a starter craftsman.config.json in your repo root; edit it any time. It deep-merges over the plugin's defaults, so you only write what you're changing. Common tweaks (full guide in EXTENDING.md):

{
  "stopGate": {
    "commands": { "package.json": "pnpm test" },   // your real test command
    "extraChecks": ["make lint"]                    // repo guards run before "done"
  },
  "languages": {
    "elixir": { "extensions": [".ex"], "format": ["mix format {file}"], "check": ["mix credo {file}"] }
  }
}
KeyDefaultMeaning
execution.agentModeroot-onlysubagents restores real fan-out
execution.engineworkflowhow /auto runs units: workflow, subagent or root
repoExec.landdirectpr lands each unit through an auto-merging PR (gh, glab, az)
planning.featureBranchesfalseunits land on a feature branch and stop at the approval page
stopGate.totalBudgetMs280000one shared wall-clock budget for every Stop check
architecture.enforcetruefalse switches off the ARCH-rule scope gate

Turn the quality, doc and tracker gates off with CRAFTSMAN=off (env) or /craftsman:toggle off; the safety guards stay on (see Safety).


Full update: taking every change and its knock-on changes

Craftsman has no pinned version. Each install tracks the marketplace's git commit, so every merge to main is an update. A full update means more than pulling the plugin. The project's own surfaces, the Claude Code built-ins craftsman wraps, the lint baseline, the architecture rules and the docs all have to follow. Run the steps in order. Each one is safe to repeat.

0. Start clean. Land or commit work in progress first, so the update doesn't tangle with it:

/craftsman:digest          # anything IN_PROGRESS or awaiting a decision?
git status                 # Stop also lists unpushed work in every worktree

1. Update Claude Code itself (if due). Some features have a minimum version (see the table under Safety):

claude update

2. Update every craftsman install. This covers the user install and each project that installed it:

/craftsman:upgrade --dry-run   # list what would move
/craftsman:upgrade             # refresh the marketplace, update each install

It prints one row per install: updated (old → new commit), current, skipped (the project directory is gone) or failed (usually the network; re-run once it's fixed). Outside Claude Code, run node <plugin>/scripts/self-update.mjs.

3. Load the new copy. The running session keeps the copy it started with:

/reload-plugins                # or restart Claude Code

The old copy stays on disk for 14 days, so other running sessions keep working.

4. Refresh each project. Run this in every project the upgrade listed, this one included:

/craftsman:init                # its --update pass

It backs up every managed file under .craftsman/init-backups/ first, then refreshes the project's craftsman.config.json, .claude/CLAUDE.md, .claudeignore and the craftsman_version stamp on each plan. It audits every shipped command, agent, hook, script and skill, and reports missing quality tools. It also offers --settings-diff, which adds the Claude Code sandbox and ask rules, and writes nothing until you agree.

5. Re-check the wrapped built-ins after a Claude Code update:

/craftsman:builtin-check       # updates docs/builtins.md

6. Re-baseline if the update or your own changes added a linter, a language or a new rule set. Otherwise new pre-existing findings would show up as "yours":

/craftsman:baseline

7. Bring the architecture rules up to date:

/architect --backfill          # only if init's architecture report says so (plans, no *.rules.md)
/architect --update            # re-verify every rule whose governed code moved since verified_at

--update refreshes stale cites and wording itself. A rule the code now contradicts is reported, never rewritten, and routed to /investigate or /plan.

8. Reconcile docs and tracker with the code:

/craftsman:sync-docs --all     # docs drift + tracker chips + archive shipped plans, then /architect --update

9. Verify. Run the real checks and read their output:

node --test scripts/*.test.mjs scripts/lib/*.test.mjs   # in the craftsman repo; elsewhere, your test command
node <plugin>/scripts/arch-check.mjs lint               # every rules doc must PASS
/craftsman:digest                                       # the board reads as expected

10. Land the doc changes. Steps 4–8 edit committed docs:

/craftsman:merge

To get updates without asking, open /plugin → Marketplaces → craftsman-marketplace → Enable auto-update. Steps 4–10 still apply after an auto-update. If a project-scope install still shows an older commit, run /craftsman:upgrade.

Holding projects on tested code. Installs from plantgreytrees/craftsman follow main. To update only to releases that passed craftsman's own loop, add the marketplace as plantgreytrees/craftsman#stable. That is a branch the owner moves forward after each release (git push origin main:stable), and rolls back by pushing an older commit to it (ARCH-MOD-06).

Changing craftsman itself? The same loop applies inside this repo. Plan and land the change, add a CHANGELOG.md entry under [Unreleased], keep this README's version line equal to the newest released CHANGELOG heading (a test checks it), and run the full suite plus claude plugin validate .. Every install then picks the change up through step 2 above. See CONTRIBUTING.md and PUBLISH.md.


Good to know

  • Plan levels. level: epic|story|feature in a plan's frontmatter, with parent:/children:, builds a tree. /orchestrate and /auto take --level and --feature. Epics and stories get generated rollup TRACKER.md files, and tracker.publish pushes progress to the base branch. planning.featureBranches, planning.featureUnitCap, execution.maxSubagents and execution.maxSessions default to behaviour that changes nothing; see EXTENDING.md.
  • Protected base branches (GitHub, GitLab, Azure DevOps). By default a finished unit is merged locally and the base branch is pushed. If your host rejects direct pushes, set repoExec.land: "pr". Each unit's branch is then pushed and lands through an auto-merging pull/merge request opened with gh, glab or az, so your branch protection, CI and approvals apply. See EXTENDING.md.
  • Doc-write authority. The guarded paths (docs/plans/, docs/ideas/, docs/architecture/**) are blocked until a writer command grants the session. /plan writes plans. /orchestrate, /scrutinise and /sync-docs --tracker update tracker rows. /idea writes idea docs, and /architect marks them architected. /architect writes paired architecture areas; unpaired legacy prose under docs/architecture/ belongs to /sync-docs until /architect --backfill pairs it. /understand and /investigate write nothing and hand off to /plan. The rest of docs/ is ordinary prose.
  • Structured tracker state. The readable tracker stays concise and link-first, while scripts/tracker.mjs records validated unit identities, legal status transitions (PENDING → IN_PROGRESS → MERGED → COMPLETE, plus BLOCKED, PARKED, CANCELLED) and terse evidence in .craftsman/tracker/events.jsonl. Both live in the main checkout, even when a session works in a worktree. pre-guard blocks writes to a worktree's copy and hand edits of the generated block. Once every row of a plan is COMPLETE or CANCELLED, {"action":"archive","plan":"docs/plans/<slug>.md"} moves it to the committed tracker archive, one line per unit with its criteria.
  • Root-only by default, mechanically enforced. execution.agentMode (default root-only) is enforced by a PreToolUse hook that hard-blocks Task calls. The standing exceptions are /plan's one decomposition step and one isolated fresh-context agent per run of /scrutinise (scrutineer), /idea (idea-critic) and /architect --deep (architect-analyst). Each run is granted exactly one such agent. The read-only built-ins in execution.builtinAgents (default ["Explore"]; add the optional artist:design-critic) also pass. /craftsman:auto is the other exception: it runs units in fresh contexts, because on a long unattended run the root context filling up is the real limit (ARCH-ENGINE-10). Measured, root grew ~20k
Source 1 files
hooks/register.js 177 lines
1// Craftsman's mod: launch, observe, draw — nothing else (ARCH-MOD-01). It
2// registers no tool.call, tool.check or agent.spawn handler and reads no
3// settings. Every engine call is feature-detected by trying it (ARCH-MOD-04).
4//
5// On turn end:
6//   observe — the engine's own context size goes to scripts/telemetry.mjs (ARCH-MOD-03);
7//   draw    — a status band: plan · unit · tracker % · context %;
8//   launch  — a .craftsman/instructions/<slug>.goal.txt written since the session
9//             started, AND recorded by craftsman this session (scripts/goal-token.mjs,
10//             ARCH-SAFETY-09), starts once: command.run("goal"), else prompt.submit,
11//             else the band asks for /craftsman:auto-go (ARCH-MOD-02). A goal file
12//             nobody recorded is named in the band and never submitted as the user.
13// /craftsman:auto-go (commands/auto-go.md) answers with the newest goal file.
14
15const GOALS = ".craftsman/instructions";
16const LAUNCHED = "craftsman.launched-goals";
17
18const SHA256_K = [
19  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
20  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
21  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
22  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
23];
24// SHA-256 of a string (UTF-8), as hex. The mod host has no node:crypto and the token must bind content (ARCH-SAFETY-09), so the
25// digest is computed here; hooks/register.test.ts feeds it digests made with node:crypto, so a wrong implementation fails there.
26function sha256Hex(text) {
27  const data = new TextEncoder().encode(String(text));
28  const padded = new Uint8Array(((data.length + 9 + 63) >> 6) << 6);
29  padded.set(data);
30  padded[data.length] = 0x80;
31  const view = new DataView(padded.buffer);
32  view.setUint32(padded.length - 8, Math.floor((data.length * 8) / 0x100000000));
33  view.setUint32(padded.length - 4, (data.length * 8) >>> 0);
34  let h = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19];
35  const w = new Uint32Array(64);
36  for (let i = 0; i < padded.length; i += 64) {
37    for (let t = 0; t < 16; t++) w[t] = view.getUint32(i + t * 4);
38    for (let t = 16; t < 64; t++) {
39      const a = w[t - 15], b = w[t - 2];
40      w[t] = (w[t - 16] + (((a >>> 7) | (a << 25)) ^ ((a >>> 18) | (a << 14)) ^ (a >>> 3)) + w[t - 7] + (((b >>> 17) | (b << 15)) ^ ((b >>> 19) | (b << 13)) ^ (b >>> 10))) >>> 0;
41    }
42    let [a, b, c, d, e, f, g, hh] = h;
43    for (let t = 0; t < 64; t++) {
44      const t1 = (hh + (((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7))) + ((e & f) ^ (~e & g)) + SHA256_K[t] + w[t]) >>> 0;
45      const t2 = ((((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10))) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
46      hh = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0;
47    }
48    h = [h[0] + a, h[1] + b, h[2] + c, h[3] + d, h[4] + e, h[5] + f, h[6] + g, h[7] + hh].map((x) => x >>> 0);
49  }
50  return h.map((x) => x.toString(16).padStart(8, "0")).join("");
51}
52
53// Every *.goal.txt in a fs.list result that is newer than `since` and not yet launched, newest first.
54function goalCandidates(entries, since = 0, launched = {}) {
55  return (Array.isArray(entries) ? entries : [])
56    .filter((f) => f && f.kind === "file" && /\.goal\.txt$/.test(f.name) && f.mtimeMs > since && launched[f.name] !== f.mtimeMs)
57    .sort((a, b) => b.mtimeMs - a.mtimeMs);
58}
59
60// The newest *.goal.txt in a fs.list result, optionally only those newer than `since`.
61function newestGoal(entries, since = 0, launched = {}) {
62  return goalCandidates(entries, since, launched)[0] || null;
63}
64
65// The newest scope file name in a session dir listing.
66function newestScope(entries) {
67  const scopes = (Array.isArray(entries) ? entries : [])
68    .filter((f) => f && f.kind === "file" && /^scope(?:@[A-Za-z0-9_-]+?)?(?:-[0-9a-f]{16})?\.json$/.test(f.name))
69    .sort((a, b) => b.mtimeMs - a.mtimeMs);
70  return scopes[0] ? scopes[0].name : null;
71}
72
73// Share of the plan's units at MERGED or COMPLETE, from the tracker ledger text.
74function trackerPercent(ledger, plan) {
75  if (typeof ledger !== "string" || !plan) return null;
76  const latest = new Map();
77  for (const line of ledger.split("\n")) {
78    let row;
79    try { row = JSON.parse(line); } catch { continue; }
80    if (row && row.plan === plan && row.unit) latest.set(row.unit, row.status);
81  }
82  if (!latest.size) return null;
83  const done = [...latest.values()].filter((s) => s === "MERGED" || s === "COMPLETE").length;
84  return Math.round((100 * done) / latest.size);
85}
86
87function band({ plan, unit, tracker, context }) {
88  const slug = plan ? String(plan).replace(/^.*\//, "").replace(/\.md$/, "") : null;
89  return ["craftsman", slug, unit, tracker === null || tracker === undefined ? null : `tracker ${tracker}%`,
90    context === null || context === undefined ? null : `ctx ${context}%`].filter(Boolean).join(" · ");
91}
92
93const goalArgs = (text) => String(text).trim().replace(/^\/goal\s+/, "");
94
95export function register(on) {
96  on("command.run", ($, e, next) => {
97    if (e.command !== "craftsman:auto-go" && e.command !== "auto-go") return next(e);
98    const none = { text: "No goal file under .craftsman/instructions — run /craftsman:auto <slug> first." };
99    return $.fs.list(GOALS)
100      .then((entries) => {
101        const goal = newestGoal(entries);
102        return goal ? $.fs.read(`${GOALS}/${goal.name}`).then((text) => ({ text: String(text).trim() })) : none;
103      })
104      .catch(() => none);
105  });
106
107  on("turn.complete", async ($, e, next) => {
108    const result = await next(e);
109    let sid = null;
110    let usage = null;
111    try { sid = await $.session.id({}); } catch { /* unsupported */ }
112    try { usage = await $.session.usage({}); } catch { /* unsupported */ }
113    const context = usage && usage.context ? usage.context : null;
114
115    let scope = null;
116    try {
117      const name = newestScope(await $.fs.list(`.craftsman/sessions/${sid}`));
118      if (name) scope = JSON.parse(await $.fs.read(`.craftsman/sessions/${sid}/${name}`));
119    } catch { /* no active scope */ }
120
121    if (sid && context && typeof context.tokens === "number") {
122      const argv = ["node", `${$.plugin.root}/scripts/telemetry.mjs`, "--sid", sid, "--tokens", String(context.tokens), "--percent", String(context.percent)];
123      if (usage.cost && typeof usage.cost.usd === "number") argv.push("--cost", String(usage.cost.usd));
124      if (scope && scope.unit) argv.push("--unit", scope.unit);
125      try { await $.process.run(argv); } catch { /* telemetry is best-effort */ }
126    }
127
128    let tracker = null;
129    try { tracker = trackerPercent(await $.fs.read(".craftsman/tracker/events.jsonl"), scope && scope.plan); } catch { /* no ledger */ }
130    let status = band({ plan: scope && scope.plan, unit: scope && scope.unit, tracker, context: context && context.percent });
131
132    let goal = null;
133    let launched = {};
134    let unrecorded = [];
135    try {
136      // Without the session's start time no goal file can be shown to be new, so none launches.
137      if (usage && typeof usage.startedAt === "number" && usage.startedAt > 0) {
138        launched = (await $.store.get(LAUNCHED)) || {};
139        const candidates = goalCandidates(await $.fs.list(GOALS), usage.startedAt, launched);
140        // Only a goal craftsman recorded in this session may be submitted as the user (ARCH-SAFETY-09):
141        // its name, mtime AND content digest must match a token goal-token.mjs wrote, so a rewritten file no longer does,
142        // not even with its mtime put back. The text that was hashed is the text that is submitted: it is read once.
143        let tokens = {};
144        try { if (sid) tokens = JSON.parse(await $.fs.read(`.craftsman/sessions/${sid}/goal-tokens.json`)) || {}; } catch { /* no tokens: nothing is recorded */ }
145        const verified = {};
146        for (const f of candidates) {
147          const token = tokens[f.name];
148          if (!token || typeof token !== "object" || token.mtimeMs !== f.mtimeMs || typeof token.sha256 !== "string") continue;
149          try {
150            const text = String(await $.fs.read(`${GOALS}/${f.name}`));
151            if (sha256Hex(text) === token.sha256) verified[f.name] = text;
152          } catch { /* unreadable: not recorded */ }
153        }
154        goal = candidates.find((f) => f.name in verified) || null;
155        unrecorded = candidates.filter((f) => !(f.name in verified)).map((f) => f.name);
156        if (goal) goal.text = verified[goal.name];
157      }
158    } catch { /* no goal dir or no store: nothing to launch */ }
159    if (goal) {
160      await $.store.set(LAUNCHED, { ...launched, [goal.name]: goal.mtimeMs });
161      const text = goal.text.trim();
162      let started = false;
163      try { await $.command.run({ command: "goal", args: goalArgs(text) }); started = true; } catch { /* no /goal here */ }
164      if (!started) {
165        // prompt.submit refuses a leading "/", so this submits the directive alone.
166        try { await $.prompt.submit({ text: goalArgs(text) }); started = true; } catch { /* cannot submit as the user */ }
167      }
168      status = started ? `${status} · launched ${goal.name}` : `${status} · type /craftsman:auto-go to launch ${goal.name}`;
169    }
170
171    if (unrecorded.length) status = `${status} · ${unrecorded.join(", ")} not written by craftsman this session — not launched (type /craftsman:auto-go to launch it yourself)`;
172
173    try { await $.ui.status(status); } catch { /* no status surface */ }
174    return result;
175  });
176}
177