SLOPSHOPPER

Spec Kit X-Ref

Keeps a GitHub Spec Kit feature and its code tied together inside Claude Code: a new idea researched and shaped with you (or your PRD reviewed and cut into a…

panebandrowsguardcommandprompt
★ 1v0.12.0MITupdated 2026-10-16moinsen-dev/speckit-xref/mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · speckit-xref
│ ┃ speckit-xref ✕ › fix the failing auth test and add an audit log call │ ┃ This folder has code, but no Spec Kit yet │ ┃ (no .specify/). ⏺ Read(src/auth.ts) │ ┃ Folder: /work/app ⎿ Read 6 lines │ ┃ Say "set up Spec Kit here" to bring this ⏺ Update(src/auth.ts) │ ┃ project under Spec Kit, or press Set up Spec ⎿ Added 2 lines, removed 1 line │ ┃ Kit in the pane. ⏺ Bash(bun test) │ ┃ ⎿ 3 pass, 1 fail │ ┃ [ Set up Spec Kit here ] │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /xref │ ⎿ speckit-xref: This folder has code, but no Spec Kit yet (no .spe │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · speckit-xref
This folder has code, but no Spec Kit yet (no .specify/). Folder: /work/app Say "set up Spec Kit here" to bring this project under Spec Kit, or press Set up Spec Kit in the pane. [ Set up Spec Kit here ]
README

Spec Kit X-Ref for Claude Code

A Claude Code mod that keeps a GitHub Spec Kit feature and its code tied together while the agent works: the spec rides every request, every edit is booked against a task, and after each turn a drift check asks whether the change still matches what the user said and what the spec says.

It complements read-only viewers such as SpecKit Companion: they show the run; this one keeps the run on the spec.

What it does

How
Spec in the system promptprompt.compose adds one section: active feature, the user's original words, user stories, constitution MUST rules, out of scope, open NEEDS CLARIFICATION, and the rules of the game. It changes only when the spec does, so the prompt cache survives.
Current task on every promptprompt.submit attaches a note: current task, its planned files, the requirements it serves, the next tasks, the drift status.
Intent logEvery prompt the person types is logged (intents in xref.json): their own words, the ground truth of the idea.
Edit bookingtool.call on Edit/Write/NotebookEdit books the file against the current task (paths come from tasks.md). A file planned for another task makes that task current. A file planned for none is drift: the model reads a note beside the tool result right away. Files Bash changed during a turn (sed, a generator, npm) are found at its end and booked the same way. Lockfiles and build output never count; manifests and configs are unclear, not drift; .xrefignore adds your own patterns.
Strict modeOptional: refuses an unplanned edit and names the way forward (focus another task, link the file, or extend the spec). If the guard itself fails, it refuses too.
Proof ladderEach requirement is specified, planned, implemented, tested or passing. Tested means a test file with real tests anchors it; passing means the test run proved it for its current text. A changed requirement drops back and asks to be re-verified.
Anchors// @spec 001-feature/FR-003 comments count as coverage; one that names a requirement the spec no longer has is drift.
Intent checkAfter a turn that wrote files, one tool-less $.model.fork over the session compares the user's words, the spec and the diff. It returns a score, reasons and requests the spec lacks. With no transcript to fork yet, one completion fed by the intent log stands in.
Fix it from the paneTo spec runs /speckit-clarify with the request; As task appends a [Drift] task to tasks.md; Map FR→tasks lets a small model map requirements to tasks once and keeps the map.
Band and paneA line above the prompt (▲ xref T004 · tasks 3/8 · FR 4/5 · watch (1)) that stacks with other mods' bands; while the autopilot waits, it shows the whole question with Resume, Stop and Pane. The pane: a phase strip, Goal, Vision, Now, Todo, Status, Proof, Next, a review card at the spec gate, "Away" after an autopilot run, open decisions, Auto, Tests and Drift. Each unplanned file is a card with Link to (a task picker) and Accept this; Accept all asks first. Under 70 columns the pane is compact; d shows the rest.
TranscriptEach booked write carries a chip (● T006 · FR-003, ▲ unplanned), and the autopilot's long prompts fold to one line (▶ auto 3/25 · implement · …); ctrl+o shows them whole.
Spec Kit's own commands/speckit-implement, -plan, -tasks, -clarify, -analyze and -converge get the current task, its files, coverage and drift appended. A compaction keeps the task in focus, your open requests and the decisions.

The model gets five tools: mcp__speckit-xref__status (CLI, setup, integration, workflow phase, autopilot and the next command), mcp__speckit-xref__ask (a question for the person, answered in place where they are there; blocks names the stories it holds up), mcp__speckit-xref__focus (make a task current), __where (which tasks and requirements a file belongs to) and __link (tie a file to a task, requirement or scenario). In a repository without Spec Kit they wait behind ToolSearch, and nothing polls.

What the mod keeps per feature lives in two files:

  • specs/<feature>/xref.json, committed: which tasks serve which requirement, which files are linked to what, which unplanned files were accepted, and each requirement's fingerprint. Sorted, without timestamps, so it merges and reviews cleanly.
  • .specify/xref/local/<feature>.json, git-ignored by a .gitignore of its own: your logged prompts, the intent verdicts, test results, approvals, decisions, and the autopilot's run log (<feature>.run.jsonl). Your words stay on your machine.

A 0.3 xref.json is migrated on first load.

Install

In a terminal (the marketplace is added on the way):

claude plugin install speckit-xref --marketplace moinsen-dev/speckit-xref

Autopilot

/xref auto on [steps] lets the work run: after every turn the mod hands the next Spec Kit step to Claude by itself, so nobody has to answer "next is X, shall I go on?". It follows Spec Kit's whole loop: constitution, specify, clarify, your review of the spec, plan, tasks, map, analyze (and the fixes it finds), implement one phase per step, converge until the tasks stop changing, verify. One step at a time: started while a turn runs, or while you type, the next step waits until the session is free.

It stops only for what is yours:

  • the product idea;
  • the spec gate: once the spec is written, the pane shows your words beside the requirements, the out-of-scope list and the assumptions Claude added. Approve spec (in the pane or the band, /xref approve, the dialog, or running /speckit-plan yourself) lets it go on; the plugin option review sets spec+plan or none. An approval holds for that text: a changed spec asks again;
  • a [NEEDS CLARIFICATION] question, or open checklist items;
  • a request that contradicts the spec (one that only extends it becomes a revise step);
  • destructive or irreversible actions: while it runs, git push, reset --hard, rm -rf and writes to .env files are refused and turned into a question. Your yes in that dialog allows exactly that action once; allowPush: on lets it push a feature branch by itself once the tests are green (never main, never --force).
  • releasing the app: deploys, store builds and submissions, publishes (wrangler deploy, eas build|submit|update, vercel, netlify deploy, firebase deploy, fastlane, npm publish, npm run deploy, gh release create …, and MCP tools that deploy, publish or submit) are refused the same way. Only Ship it opens them: for the release step it approves, and only the commands it approves, as written (another flag, another project, npx in front or an MCP deploy tool still waits for you).

Claude asks through mcp__speckit-xref__ask. Where you are there, the question opens as a dialog and the run goes on with your answer in the same turn. A question that blocks only some stories waits in the pane's Decide row while the rest goes on. When an answer ends on a question anyway, a small model decides whether it is a real decision or just "shall I go on?".

Tests gate the progress. After each implement step the mod runs the test command: the testCommand option, else the project's test script (npm test, or pnpm, yarn, bun), else what plan.md's Testing: line names. A command that is not there counts as "could not run", not as a failure. A failure becomes a repair step, at most three in a row; then it is your call. A passing suite proves every requirement with a real test (with junitPath, each one by the tests that name or anchor it; for Vitest and Playwright, whose reports carry the test file as the classname, anchors count too). The run ends only when the suite passes once more.

Each phase gets its brief. An implement step does not just say "run /speckit-implement": it hands over the phase's goal, its Independent Test and Checkpoint from tasks.md, the acceptance scenarios it has to prove (tests named after US2-AS1), the quickstart rows and the screens that show them, and the last test run. What a step learns about the environment (a port, a flag, a permission's name) goes into .specify/memory/runbook.md, and every later step starts from it.

Verify sorts what it finds. Only HIGH and MEDIUM findings (a requirement, a scenario or a point of your words not met, or met only in part) become tasks; LOW ones (polish, wording) are listed, not built. After two verify rounds in a run that each found new work, closing the feature is your call: Call it done, or Resume for one more round.

The mod orchestrates (0.8). The heavy steps run in subagents with a fresh context: each implement phase, each repair and each user test. The mod decides the step, the model and the brief; the session only relays (it calls the Agent tool, the mod's spawn hook gives the agent its model and brief and runs it in the foreground) and writes no code meanwhile. So the session keeps the spec, your decisions and short reports instead of every phase's work, and the context stays small. The model per step (option models, auto): Sonnet implements, repairs and tests, Opus takes over a repair that failed once already, Haiku does phases of docs and configuration; the spec, the reviews, verify and ship stay with the session's own model. The run log names the model of each step. Option orchestrate (on) switches it off. When a feature is done the mod writes .specify/xref/local/handoff.md, and /clear before the next feature keeps the context small.

Tests prove requirements. One test per requirement or acceptance scenario, at the boundary where its behaviour shows; no render-only tests, no tests of what the framework or the types guarantee, no test per task (the phase brief, the implementer and the preset say so).

The user test. A feature with a user interface is used as a person would, in the iOS Simulator of the Claude desktop app or in a browser (or a short Playwright script with the installed Chrome where neither is there): each story right after it is built, before the next phase builds on it, and the whole app before it counts as done. It follows the stories and the paths people take by accident (a permission denied, offline, back and forth, empty input), with screenshots in specs/<feature>/try/ and a log in try.md; a HIGH or MEDIUM finding becomes a fix task. Option userTest (on) switches it off.

It listens (0.12). The plan is a means, not the master. When you write in the middle of a run, your words come first. The step the autopilot handed over is set aside, nothing of the autopilot's holds your turn, and it does not push its old plan back at the end of your turn. Instead the deputy weighs your words, Claude's answer and the planned step, and decides: the plan stands (with a note), a step it writes itself to carry out what you asked (put tasks off, close the feature, start the next one, do something first), or wait for you. After a step, it may also redirect when the work shows the plan no longer fits ("this belongs in feature 2"). A task marked [~], [-] or "deferred/verschoben" is decided, not open, and proves nothing. Claude may pause the run when you say so (mcp__speckit-xref__pause); stopping it stays your command.

Tests, CI/CD and git are yours to switch on (0.11). Building and fixing test suites costs coding agents much of their time and rarely pays off in a proof of concept, an MVP or an idea to try. So by default (option tests: off) nobody plans or writes tests. The type check of the project's language gates each step instead: its own typecheck script, tsc --noEmit, flutter analyze, cargo check, go vet, swift build, mypy, or option checkCommand. A failing check becomes a repair step, and the user test and the deputy check the work. run keeps an existing suite as the gate and adds nothing; lean writes one test per requirement as before. With option ci (off) the autopilot plans and writes no CI/CD pipeline (GitHub Actions, GitLab, CircleCI, EAS workflows, fastlane …), and a write in its steps is refused; asked for in your own words, it is yours. Option git (current) builds every feature on the branch you are on and refuses branches of the autopilot's own. branch gives a feature its own branch (its folder's name) once its spec is written. pr also commits the feature's own work (never yours besides, never a secret), pushes and opens a pull request against the branch you started from when the feature is done, and the pane links it. Merging stays yours. Without a suite the pane's ladder stops at implemented; a project that keeps its suite as the gate sets tests: run, or lean for the behaviour before 0.11.

The deputy (0.10). While the autopilot runs, a deputy on Opus thinks between the steps the way you would. After each step that builds, repairs, tries or restyles the app it reads the agent's whole report, the step's diff, the test run and the requirements behind the checked tasks. It looks for claims without evidence, weakened tests, work outside the tasks, and what was left open, and at the end of a phase it asks whether this is still the right thing to build. Then it sends the step on with a note for the next one, back to the same agent with a concrete list (twice at most), or to you with one question and its recommendation. It answers Claude's questions for you from the spec, the briefs, your own words and your earlier decisions, and shows each one under For you in the pane, with Change. It never approves a gate, and money, keys, deletions, releases, measurements, checks by hand and real devices stay yours, in code. It learns how you work from your own words into .specify/xref/local/person.md (git-ignored). Option deputy: full, review or off.

Polish (0.9). The first version is built plain on purpose: it has to prove that it works and makes sense. Polish in the pane after done (or /xref polish, or "make it beautiful") then lifts its look and feel to the level of the best apps on its platform, without changing what it does. A design lead (Opus, the speckit-xref:designer agent) uses the app, writes specs/<feature>/polish.md (the direction, a plan per screen) and brings DESIGN.md along, appends a ## Phase N: Design pass with a task per screen, and builds the shared parts and two or three sample screens, with before and after shots in specs/<feature>/polish/. You approve the direction at the samples (Approve direction), or say what to change; then the implementer builds the other screens, every test still green, and the design lead reviews fresh shots of every screen, light and dark (HIGH and MEDIUM findings become a Design review phase, three rounds at most), before the user test tries the whole app again. On iOS that means the current design language: content edge to edge under translucent material, large titles, sheets, SF Symbols, Dynamic Type, system colours, haptics and motion, with native controls; Material 3 on Android, the same direction in CSS on the web. With the Expo plugin installed, its expo-ui, expo-native-ui, expo-router and expo-animation skills do the native parts. Once the design pass is done, other work clears the wish, so a later change or bug starts no new reviews. Without the desktop app's simulator tool (in a terminal), the tester and the design lead use the iOS Simulator through xcrun simctl for shots and links, and Maestro for taps.

Scripted acceptance, on request. With option acceptance: auto, a feature with a user interface is also played through after verify by a scripted driver: one test per acceptance scenario under e2e/acceptance/, Playwright for the web with the installed Google Chrome (nothing is downloaded; a project without Playwright gets a setup task first), Maestro for iOS and Android where it is installed, a development build rather than Expo Go. Only the driver's fresh JUnit report accepts a scenario (★ accepted in the pane and the dashboard, with its screenshot); a scenario whose text changes has to be accepted again. A scenario that fails because of the app becomes a fix task, built before the next acceptance run (three rounds, then it is your call). What no driver here can check (a real device, real users, a paid service) is listed in acceptance.md as your part. Since 0.8 it is off by default: the user test is the check.

Decided or assumed. At the spec review the pane puts what you decided (the product brief, your answers) beside what Claude assumed: Keep marks an assumption as yours, Change asks what should hold instead and hands it to Claude, and the spec changes before you approve it. Why the autopilot waited or stopped is in the run log beside its steps.

After done comes the next thing. A feature that passed converge, verify and the tests stays done while its spec, its tasks and the working tree stay as they are: the next start does not verify again, it asks what comes next. Press New feature, Change or Bug in the pane and say it in your own words, or type it, or /xref next feature|change|bug <words>:

  • a new feature goes to /speckit-specify and becomes the next feature;
  • a change reaches the spec first (new requirements, appended tasks), then gets built;
  • a bug is reproduced with a failing test, fixed and recorded (with Spec Kit's bug extension where it is installed), with a task of its own in the trace.

Ship. Ship in the pane (or /xref ship, or "ship it") releases the done app, in three steps. First a release check with the speckit-xref:ship skill, after the tests passed once more: version and store fields, a usage text for every OS permission the code asks for, privacy, accessibility, tracked secrets (paths, never values), the production build run locally. It writes .specify/memory/release.md: the checks with their evidence, the exact release commands per platform (a static web host the project is set up for, Expo EAS for iOS and Android, or what the project configured), and your part before and after the release. Nothing goes out in the check, and nothing is downloaded for it. A HIGH or MEDIUM gap becomes a task under ## Phase N: Release readiness; the autopilot builds, verifies and plays it through, then checks again. The release waits on the tests, the drift, failing acceptance scenarios and your open boxes before the release. Then Ship it is yours: the release step runs the commands as written, once each, stops at a login or a prompt, and logs the result under ## Releases. Every release asks anew. Your Ship holds until the release is handed over, through the readiness rounds and across sessions (a check for the same tree is not repeated); Not now puts it aside. While a step still runs, the pane offers nothing to approve. The pane's Ship row and the dashboard's Release section show the checks and what went out.

It also stops on Esc or /xref-stop (both end the running turn), on an API error or a refusal, when the drift turns red, after three steps without progress, at the step budget (25 by default) and when the feature is done. After five minutes of waiting it sends a notification. The band shows auto ▶ 3/25 · 5h 34% · 7d 12% · 23m while it runs (on a subscription, the usage windows; with an API key, /cost's dollars) and the whole question when it waits; the pane tab reads Spec X-Ref ⏸. Back at the keyboard, the pane's Away card says what happened.

More, all off by default:

  • /xref auto night: a night run of up to 100 steps; it writes .specify/xref/local/briefing.md when it stops.
  • commitPerTask: on: a step whose tests pass commits the tasks it checked off, on a feature branch only; nothing you staged is mixed in, and files outside the plan or .env files stop it.
  • parallel: on: a phase's open [P] tasks go to speckit-xref:task-runner subagents, one per task.
  • Headless: SPECKIT_XREF_AUTOPILOT=on|night|<steps> claude -p "…" runs the autopilot in a -p session; each next step rides the Stop hook.

The pane's Auto row switches it:

  • off: Start autopilot (p);
  • running: Stop (p);
  • waiting: Resume (r) and Stop. A spent budget restarts on Resume.

Click the buttons, or give the pane the keyboard with ctrl+x tab (once more if the band takes it first). /xref pane looks at the folder first, opens the pane without taking the keyboard (so the next key never presses a button), and says where things stand.

The autopilot never sets Spec Kit up by itself: specify init and specify integration install write into the repository, so it waits there for you. To start every session with the autopilot on, set the plugin options autopilot: on and autopilotMaxSteps. It is off by default, because every step is a model turn.

A new project starts at the idea

In an empty folder the autopilot does not go straight to a spec:

  1. Validate. The idea is researched on the web by an agent of the mod's own: who has the problem, what already exists, what makes the idea different, the riskiest assumption, when to stop. The result is .specify/memory/idea-brief.md, with a score out of 5 and a recommendation. Alternatives count as verified only with a URL that was fetched. You decide in the pane, the band or a dialog: Build, Sharpen (say what should change, it is researched again) or Drop. The idea's wording goes to the web search Claude uses.
  2. Shape. Claude asks what the idea leaves open (first-version scope, platforms, language, design direction, data) and writes .specify/memory/product-brief.md.
  3. Then the constitution and the spec, which treat those decisions as yours.

Options validate and shape (both on) switch the two off; a project that already has a feature skips them.

A project that starts from a PRD

Wrote a PRD first? Put it in the empty folder as Markdown (PRD_Show.md; a file with "PRD" or "product requirements" in its name), or import it from anywhere with /xref prd <path>. Instead of Validate:

  1. Import. The mod copies it to .specify/memory/prd.md.
  2. Review and roadmap. Claude reads it as the one who has to build it: .specify/memory/prd-review.md (contradictions, untestable criteria, gaps, the open decisions that block the first feature) and .specify/memory/roadmap.md (the features in build order, each with its phase, the PRD's own ids, the PRD sections it implements, and the gate before it). It does not rewrite the PRD or research it again.
  3. Your approval. The pane shows the roadmap and the open decisions: Approve roadmap.
  4. Shape asks only the blocking decisions; the PRD's other decisions are yours already. Then the constitution, and the first feature is specified from the roadmap.

Every requirement carries the PRD id it comes from ((PRD F01)), stories and scenarios theirs; the pane's PRD row counts the feature's PRD ids its spec carries, and the intent check reads the PRD sections the feature implements. When a feature is done, Next from roadmap specifies the next one; a gate before it (a test with real users, a review) is named as your part.

A feature's look: Design

A feature with a user interface (plan.md's Project Type says mobile, web app, desktop …) gets its look after the plan and before the tasks:

  1. Design. Claude writes DESIGN.md at the root, the design system in Google Stitch's format (colours, type, spacing, radii as YAML tokens, the reasons in prose), from the product brief's design direction. Where the app already has a look, it writes that down instead of redesigni
Source 18 files
hooks/register.tsx 3607 lines
1import { atom, read, update } from 'claude-code'
2import type { Color, EngineInterface, Register } from 'claude-code'
3
4import type { Autopilot, Ledger, NextWork, RunEntry, Snapshot } from '../types'
5import { renderDashboard } from './dashboard'
6import type { DashboardDoc } from './dashboard'
7import { ACCEPTANCE_ARTIFACT, ACCEPT_REPORT, ACCEPT_REPORTS, POLISH_ARTIFACT, TRY_ARTIFACT, acceptanceCounts, acceptanceDoc, acceptanceFrom, flowIncludes, parseAcceptanceDoc, platformsFromPlan, tapsByCoordinates } from './accept'
8import { DESIGNER, IMPLEMENTER, IMPLEMENTER_PROMPT, MODELS, TESTER, TESTER_PROMPT, relayPrompt, routeModel, writesCode } from './orchestrate'
9import { DESIGNER_PROMPT, parsePolish, polishDoc } from './polish'
10import { GIT_MODES, TEST_MODES, branchName, branches, checkCommandFor, gateWords, prBody, touchesCi } from './gitci'
11import type { GitMode, TestMode } from './gitci'
12import { DEPUTY_PROMPT, MAX_REWORKS, PROFILE, REVIEWED, answerLine, answerRequest, noteLine, parseAnswer, parseSteer, parseVerdict, profileAdditions, requirementsOf, reviewRequest, reworkBrief, steerLine, steerRequest } from './deputy'
13import type { Steer, Verdict } from './deputy'
14import type { Delegate, Models } from './orchestrate'
15import { PRD, PRD_NAME, PRD_REVIEW, ROADMAP, parsePrdReview, parseRoadmap, prdCoverage, prdFingerprint, prdSections, prdSourceOf, roadmapItemOf, roadmapSpecify } from './prd'
16import { NEXT_LABELS, NO_WORK, RUNBOOK, doneAsk, nextKindOf, parsePhaseNotes, parseQuickstart, treeOf, untrackedLine, verifyKey } from './brief'
17import { DEPLOY_TOOLS, RELEASE, approvedRelease, deployToolsOf, lastRelease, parseRelease, releaseBlockers, releaseLine, releaseRuns, releasesApp, releasesByTool } from './ship'
18import { DESIGN_FILE, designChangeFromGit, designDir, designState, designTokens, screensPath, uiFromPlan } from './design'
19import { LOCAL_IGNORE, ledgerFromParts, ledgerToParts, localPath, rebaseline, runLogPath } from './ledger'
20import { LADDER, isActive, levelOf, parseJunit, verificationFrom, verificationFromExit } from './proof'
21import type { Rung } from './proof'
22import { featureFromBranch, fingerprint, hasRealTests, isTestFile, matchesAny, rulesFrom, specFingerprint } from './rules'
23import { invokeSeparator, parseConstitution, parseFeatureJson, parseSpec, parseTasks } from './speckit'
24import type { Flow, Review, Step } from './workflow'
25import {
26  AUTONOMY_RULES,
27  REVIEWS,
28  QUESTION_LABELS,
29  autopilotPrompt,
30  endsWithQuestion,
31  idleAutopilot,
32  nextStep,
33  openChecklistItems,
34  openPhase,
35  persistenceModel,
36  progressKey,
37  MAX_REPAIRS,
38  phaseStrip,
39  setupNote,
40  stepLine,
41  takesIdea,
42  couldNotRun,
43  failureLine,
44  parseIdeaBrief,
45  phaseLabel,
46  phaseNumber,
47  specReview,
48  taskPhases,
49  tasksFingerprint,
50  gatesOf,
51  testCommandFrom,
52  testScriptCommand,
53} from './workflow'
54import {
55  acknowledgeAll,
56  anchorsIn,
57  appendRemediation,
58  applyMapping,
59  applySemantic,
60  classify,
61  composeSection,
62  currentTask,
63  editNote,
64  emptyLedger,
65  evaluate,
66  isSpecArtifact,
67  forkPrompt,
68  link,
69  logIntent,
70  mapPrompt,
71  parseSemantic,
72  recordTouch,
73  relPath,
74  reqsOf,
75  resolveIntent,
76  openUnplanned,
77  short,
78  speckitCommand,
79  turnContext,
80} from './xref'
81import type { Anchor } from '../types'
82import type { Classified, Level, Report } from './xref'
83
84type $ = EngineInterface
85type Options = {
86  mode: string
87  driftCheck: string
88  mapModel: string
89  autopilot: string
90  autopilotMaxSteps: number
91  testCommand: string
92  junitPath: string
93  review: string
94  commitPerTask: string
95  parallel: string
96  pane: string
97  validate: string
98  shape: string
99  design: string
100  allowPush: string
101  acceptance: string
102  orchestrate: string
103  models: string
104  userTest: string
105  deputy: string
106  tests: string
107  ci: string
108  git: string
109  checkCommand: string
110}
111
112const PLUGIN = 'speckit-xref'
113const PANE = 'speckit-xref'
114const TITLE = 'Spec X-Ref'
115const COMMAND = 'xref'
116const STOP_COMMAND = 'xref-stop'
117const REFRESH_MS = 4000
118const WRITE_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
119// Prompts the person typed, wherever they typed them; a plugin's or a peer's are not their intent.
120const PERSON = new Set(['composer', 'bridge', 'sdk'])
121const LEVEL_COLOR = { none: 'subtle', green: 'success', yellow: 'warning', red: 'error' } as const
122const RANK: Record<Level, number> = { none: 0, green: 1, yellow: 2, red: 3 }
123// What the person reads: a word and a glyph, the color only on top.
124const STATE: Record<Level, { glyph: string; word: string }> = {
125  none: { glyph: '·', word: 'no feature' },
126  green: { glyph: '●', word: 'ok' },
127  yellow: { glyph: '▲', word: 'watch' },
128  red: { glyph: '✖', word: 'off-spec' },
129}
130// `@spec` and every id after it on the line (§5): -o prints the whole list, anchorsIn splits it.
131const RG_ID = '(?:[\\w.-]+/)?(?:(?:FR|SC)-\\d{3,}|T-?\\d{3,}|US\\d+-AS\\d+)'
132const ANCHOR_RG = `@spec\\s+${RG_ID}(?:[ \\t,]+${RG_ID})*`
133const GIT_ID = '([[:alnum:]_.-]+/)?((FR|SC)-[0-9]{3,}|T-?[0-9]{3,}|US[0-9]+-AS[0-9]+)'
134const ANCHOR_GIT = `@spec[[:space:]]+${GIT_ID}([[:blank:],]+${GIT_ID})*`
135
136const snapshotA = atom({ plugin: 'speckit-xref', key: 'snapshot' } as const, null)
137const ledgerA = atom({ plugin: 'speckit-xref', key: 'ledger' } as const, emptyLedger())
138const activeA = atom({ plugin: 'speckit-xref', key: 'active' } as const, null)
139const checkingA = atom({ plugin: 'speckit-xref', key: 'checking' } as const, false)
140const autopilotA = atom({ plugin: 'speckit-xref', key: 'autopilot' } as const, idleAutopilot())
141// Turn state lives in atoms, so a reload or a /config change in the middle of a turn keeps it.
142const askedA = atom({ plugin: 'speckit-xref', key: 'asked' } as const, null)
143const turnFilesA = atom({ plugin: 'speckit-xref', key: 'turnFiles' } as const, [] as string[])
144const turnA = atom({ plugin: 'speckit-xref', key: 'turn' } as const, null)
145const detailsA = atom({ plugin: 'speckit-xref', key: 'details' } as const, false)
146const seenAtA = atom({ plugin: 'speckit-xref', key: 'seenAt' } as const, 0)
147const chipsA = atom({ plugin: 'speckit-xref', key: 'chips' } as const, {} as Record<string, string>)
148const queueA = atom({ plugin: 'speckit-xref', key: 'queue' } as const, { auto: false, person: false })
149// What the person allowed once through the ask tool: a rail's label and until when it holds.
150const permitsA = atom({ plugin: 'speckit-xref', key: 'permits' } as const, [] as { label: string; until: number; many?: boolean; commands?: string[] }[])
151
152// The module's own: they start over on a reload, and session.start or register fills them again.
153let root = ''
154let signature = ''
155let offered = false
156let interactive = true
157let lastLevel: Level = 'none'
158let timer: { cancel: () => void } | null = null
159// What can run Spec Kit's CLI here, looked up once a session.
160let cli: Snapshot['tools'] = { specify: false, uvx: false }
161let mapModel = 'haiku'
162let defaultMax = 25
163let testCommandOption = ''
164let junitPath = ''
165let review: Review = 'spec+design'
166// Read by the strict guard's fallback, which has to be a top-level function.
167let strict = false
168let parallel = false
169let commitPerTask = false
170// When the pane opens without being asked: auto (where it is a sidebar), always (every Spec Kit project), off.
171let paneMode: 'auto' | 'always' | 'off' = 'auto'
172let driftCheckOn = true
173let validateOn = true
174let shapeOn = true
175let designOn = true
176// On: the autopilot may push a feature branch (never main, never --force) once the tests are green.
177let allowPush = false
178// auto: a feature with a user interface is played through after verify. off: no acceptance step.
179let acceptanceOn = false
180// on: implement, repair and the user test run in subagents, a model per step (0.8.0). off: all in the session.
181let orchestrateOn = true
182let modelsOption: Models = 'auto'
183// on: each story is tried as a person would after it is built, and the whole app before done (0.8.0).
184let userTestOn = true
185// full: the deputy reviews each heavy step and answers Claude's questions for the person; review: only the reviews (0.10.0).
186let deputyMode: 'full' | 'review' | 'off' = 'full'
187// off: no test suite, the type check is the gate; run: the existing suite, nothing added; lean: tests per requirement (0.11.0).
188let testsMode: TestMode = 'off'
189// off: the autopilot writes no CI/CD pipeline (0.11.0).
190let ciOn = false
191// current: the work stays on the person's branch; branch: a branch per feature; pr: and a pull request when done (0.11.0).
192let gitMode: GitMode = 'current'
193let checkCommandOption = ''
194// In a `-p` run the next step rides the Stop hook's re-prompt instead of a prompt of its own.
195let pendingPrompt: string | null = null
196// When the step running now was handed over: its length in the run log, where a -p run reports none.
197let stepStartedAt = 0
198
199const at = (rel: string) => (rel.startsWith('/') ? rel : `${root}/${rel}`)
200const at$ = at
201const stamp = async ($: $) => new Date(await $.clock.now()).toISOString()
202
203async function readText($: $, rel: string): Promise<string | null> {
204  try {
205    return await $.fs.read(at(rel))
206  } catch {
207    return null
208  }
209}
210
211async function mtime($: $, rel: string): Promise<number> {
212  try {
213    return (await $.fs.stat(at(rel))).mtimeMs
214  } catch {
215    return 0
216  }
217}
218
219async function exists($: $, rel: string): Promise<boolean> {
220  try {
221    return await $.fs.exists(at(rel))
222  } catch {
223    return false
224  }
225}
226
227/**
228 * The project root: the nearest folder at or above the working directory that holds `.specify/`, as Spec Kit's
229 * own scripts find it. Claude started in a subfolder of a Spec Kit project must not be offered a nested setup.
230 */
231async function projectRoot($: $, cwd: string): Promise<string> {
232  let dir = cwd.replace(/\/+$/, '') || '/'
233  for (let depth = 0; depth < 16; depth++) {
234    if (await $.fs.exists(`${dir === '/' ? '' : dir}/.specify`).catch(() => false)) return dir
235    const parent = dir.slice(0, dir.lastIndexOf('/')) || '/'
236    if (parent === dir) break
237    dir = parent
238  }
239  return cwd
240}
241
242// A PRD the person wrote first does not make the folder a codebase: it is where a new product starts.
243const IGNORABLE = /^(\.|README|LICENSE|CHANGELOG)/i
244const ignorable = (name: string) => IGNORABLE.test(name) || (PRD_NAME.test(name) && /\.(md|markdown|docx|pdf)$/i.test(name))
245
246/** Empty: nothing at the top but dotfiles, a README, a license or a changelog. */
247async function folderKind($: $): Promise<'empty' | 'existing'> {
248  try {
249    return (await $.fs.list(root)).some(entry => !ignorable(entry.name)) ? 'existing' : 'empty'
250  } catch {
251    return 'existing'
252  }
253}
254
255/** Whether a program is on the PATH. */
256async function onPath($: $, program: string): Promise<boolean> {
257  try {
258    return (await $.process.run(['which', program], { cwd: root, timeoutMs: 3000 })).exitCode === 0
259  } catch {
260    return false
261  }
262}
263
264/** Every feature directory with a spec.md, and when its spec or tasks last changed. */
265async function listFeatures($: $): Promise<{ dir: string; time: number }[]> {
266  const found: { dir: string; time: number }[] = []
267  for (const base of ['specs', '.specify/specs']) {
268    let entries
269    try {
270      entries = await $.fs.list(at(base))
271    } catch {
272      continue
273    }
274    for (const entry of entries) {
275      if (entry.kind !== 'dir') continue
276      const dir = `${base}/${entry.name}`
277      const spec = await mtime($, `${dir}/spec.md`)
278      if (spec) found.push({ dir, time: Math.max(spec, await mtime($, `${dir}/tasks.md`)) })
279    }
280  }
281  return found.sort((a, b) => a.dir.localeCompare(b.dir))
282}
283
284/** The git branch checked out; null outside git or on a detached HEAD. */
285async function currentBranch($: $): Promise<string | null> {
286  try {
287    const ran = await $.process.run(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, timeoutMs: 3000 })
288    const branch = ran.exitCode === 0 ? ran.stdout.trim() : ''
289    return branch && branch !== 'HEAD' ? branch : null
290  } catch {
291    return null
292  }
293}
294
295/**
296 * The active feature, as docs/contract-0.4.md §7 orders it: SPECIFY_FEATURE_DIRECTORY, .specify/feature.json,
297 * SPECIFY_FEATURE, the feature the git branch names (`001-…`), else the spec written last.
298 */
299async function resolveFeature($: $, features?: { dir: string; time: number }[], branch?: string | null): Promise<string | null> {
300  const named = await $.env.get('SPECIFY_FEATURE')
301  const pointers = [
302    await $.env.get('SPECIFY_FEATURE_DIRECTORY'),
303    parseFeatureJson((await readText($, '.specify/feature.json')) ?? ''),
304    named ? `specs/${named}` : null,
305  ]
306  for (const pointer of pointers) {
307    if (!pointer) continue
308    const rel = relPath(pointer, root).replace(/\/$/, '')
309    if (await exists($, `${rel}/spec.md`)) return rel
310  }
311  const all = features ?? (await listFeatures($))
312  const fromBranch = featureFromBranch(branch === undefined ? ((await currentBranch($)) ?? '') : (branch ?? ''), all.map(f => f.dir))
313  if (fromBranch) return fromBranch
314  const latest = [...all].sort((a, b) => b.time - a.time)[0]
315  return latest?.dir ?? null
316}
317
318async function currentSignature($: $, featureDir: string | null): Promise<string> {
319  const files = ['.specify/feature.json', '.specify/memory/constitution.md', '.specify/integration.json', '.specify/extensions.yml']
320  if (featureDir) files.push(`${featureDir}/spec.md`, `${featureDir}/tasks.md`, `${featureDir}/plan.md`, '.xrefignore', 'package.json', DESIGN_FILE, screensPath(featureDir), `${featureDir}/quickstart.md`, RUNBOOK, acceptanceDoc(featureDir), RELEASE, polishDoc(featureDir))
321  const times = await Promise.all(files.map(f => mtime($, f)))
322  return [featureDir ?? '-', ...times].join('|')
323}
324
325/** Reads Spec Kit's files into the snapshot; a new feature brings its own ledger. */
326async function scan($: $): Promise<void> {
327  const features = await listFeatures($)
328  const branch = await currentBranch($)
329  const featureDir = await resolveFeature($, features, branch)
330  const [specMd, tasksMd, planMd, constitutionMd, integrationJson, initOptions, ignoreText, designMd, screensMd] = await Promise.all([
331    featureDir ? readText($, `${featureDir}/spec.md`) : null,
332    featureDir ? readText($, `${featureDir}/tasks.md`) : null,
333    featureDir ? readText($, `${featureDir}/plan.md`) : null,
334    readText($, '.specify/memory/constitution.md'),
335    readText($, '.specify/integration.json'),
336    readText($, '.specify/init-options.json'),
337    readText($, '.xrefignore'),
338    readText($, DESIGN_FILE),
339    featureDir ? readText($, screensPath(featureDir)) : null,
340  ])
341  const [quickstartMd, runbookMd, acceptanceMd, releaseMd, packageJson, polishMd] = await Promise.all([
342    featureDir ? readText($, `${featureDir}/quickstart.md`) : null,
343    readText($, RUNBOOK),
344    featureDir ? readText($, acceptanceDoc(featureDir)) : null,
345    readText($, RELEASE),
346    readText($, 'package.json'),
347    featureDir ? readText($, polishDoc(featureDir)) : null,
348  ])
349  let extensions: string[] = []
350  try {
351    extensions = (await $.fs.list(at('.specify/extensions'))).filter(e => e.kind === 'dir' && !e.name.startsWith('.')).map(e => e.name)
352  } catch {
353    extensions = []
354  }
355  // integration.json says how commands are invoked; without it, a commands-only layout is the old one.
356  const separator = integrationJson ? invokeSeparator(integrationJson) : null
357  const commandsOnly = separator ? separator === '.' : (await exists($, '.claude/commands/speckit.clarify.md')) && !(await exists($, '.claude/skills/speckit-clarify/SKILL.md'))
358  const tasks = tasksMd ? parseTasks(tasksMd) : []
359  const previous = await read($, snapshotA)
360  const snapshot: Snapshot = {
361    initialized: await exists($, '.specify'),
362    featureDir,
363    features: features.map(f => f.dir),
364    hasPlan: planMd !== null,
365    extensions,
366    claudeIntegration: await hasClaudeIntegration($),
367    speckitVersion: speckitVersionOf(initOptions),
368    tools: { ...cli, deploy: [...new Set([...(cli.deploy ?? []), ...deployToolsOf(packageJson)])] },
369    folder: await folderKind($),
370    spec: specMd ? parseSpec(specMd) : null,
371    tasks,
372    constitution: constitutionMd ? parseConstitution(constitutionMd) : null,
373    commandStyle: commandsOnly ? 'commands' : 'skills',
374    rules: rulesFrom(ignoreText),
375    realTests: previous?.featureDir === featureDir ? previous.realTests : [],
376    planFingerprint: planMd ? fingerprint(planMd) : null,
377    // The gate (0.11.0): without a test suite the language's type check; else the option, the project's own test
378    // script, or what plan.md's Testing line implies.
379    testCommand: testsMode === 'off' ? checkCommandOption || (await projectCheck($, packageJson)) : testCommandOption || (await projectTestScript($)) || testCommandFrom(planMd),
380    gate: testsMode === 'off' ? 'check' : 'tests',
381    testMode: testsMode,
382    ciOn,
383    branch,
384    phase: openPhase(tasks),
385    tasksFingerprint: tasksFingerprint(tasks),
386    commands: await installedCommands($),
387    checklists: featureDir ? await checklists($, featureDir) : [],
388    persistence: persistenceModel(constitutionMd),
389    commits: await hasCommits($),
390    ...(await ideaState($)),
391    ...(await prdState($, featureDir, features.map(f => f.dir))),
392    ui: uiFromPlan(planMd),
393    platforms: platformsFromPlan(planMd),
394    playwright: /"@playwright\/test"\s*:/.test(packageJson ?? ''),
395    acceptanceDoc: acceptanceMd ? parseAcceptanceDoc(acceptanceMd) : null,
396    release: releaseMd ? parseRelease(releaseMd) : null,
397    polish: polishMd ? parsePolish(polishMd) : null,
398    design: featureDir ? designState(designMd, screensMd) : null,
399    phaseNotes: tasksMd ? parsePhaseNotes(tasksMd) : {},
400    quickstart: quickstartMd ? parseQuickstart(quickstartMd) : [],
401    runbook: runbookMd,
402    // Only a feature whose tasks are all checked can be done: the content fingerprint is taken only then.
403    tree: featureDir && tasks.length && tasks.every(t => t.done) ? await workingTree($) : null,
404  }
405  // At the design review the mod checks screens.md's word on DESIGN.md against git, where there is a commit to compare with.
406  if (snapshot.design?.screens && tasks.length === 0 && snapshot.commits) snapshot.design.verified = await designGit($)
407  if (!previous || previous.featureDir !== featureDir) {
408    const ledger = featureDir ? rebaseline(ledgerFromParts(await readText($, `${featureDir}/xref.json`), await readText($, localPath(featureDir))), specMd) : emptyLedger()
409    const anchors = featureDir ? await scanAnchors($) : null
410    await update($, ledgerA, () => (anchors ? { ...ledger, anchors } : ledger))
411    await update($, activeA, () => null)
412    snapshot.realTests = await findRealTests($, anchors ? { ...ledger, anchors } : ledger)
413  }
414  await update($, snapshotA, () => snapshot)
415  signature = await currentSignature($, featureDir)
416}
417
418/** The type check of the project's language (0.11.0): its own script, else tsc, dart, cargo, go, swift or mypy. */
419async function projectCheck($: $, packageJson: string | null): Promise<string | null> {
420  return checkCommandFor({
421    packageJson,
422    typescript: (await exists($, 'tsconfig.json')) && (await exists($, 'node_modules/typescript/package.json')),
423    pubspec: await readText($, 'pubspec.yaml'),
424    cargo: await exists($, 'Cargo.toml'),
425    goMod: await exists($, 'go.mod'),
426    swiftPackage: await exists($, 'Package.swift'),
427    mypy: (await exists($, 'mypy.ini')) || /\[tool\.mypy\]/.test((await readText($, 'pyproject.toml')) ?? ''),
428    run: (await exists($, 'pnpm-lock.yaml')) ? 'pnpm' : (await exists($, 'yarn.lock')) ? 'yarn' : (await exists($, 'bun.lock')) || (await exists($, 'bun.lockb')) ? 'bun run' : 'npm run',
429  })
430}
431
432async function projectTestScript($: $): Promise<string | null> {
433  const pkg = await readText($, 'package.json')
434  if (!pkg) return null
435  return testScriptCommand(pkg, { pnpm: await exists($, 'pnpm-lock.yaml'), yarn: await exists($, 'yarn.lock'), bun: (await exists($, 'bun.lock')) || (await exists($, 'bun.lockb')) })
436}
437
438const IDEA_BRIEF = '.specify/memory/idea-brief.md'
439const PRODUCT_BRIEF = '.specify/memory/product-brief.md'
440const PROJECT_STATE = '.specify/xref/local/project.json'
441
442/** The PRD's state: a PRD file at the root, its import, review and roadmap, and whether the person approved the roadmap. */
443async function prdState($: $, featureDir: string | null, features: string[]): Promise<Pick<Snapshot, 'prdSource' | 'prd' | 'prdReview' | 'roadmap' | 'prdFingerprint' | 'prdApproved' | 'prdExcerpt'>> {
444  let names: string[] = []
445  try {
446    names = (await $.fs.list(root)).filter(e => e.kind === 'file').map(e => e.name)
447  } catch {
448    names = []
449  }
450  const [prd, review, roadmap] = await Promise.all([readText($, PRD), readText($, PRD_REVIEW), readText($, ROADMAP)])
451  const items = roadmap ? parseRoadmap(roadmap) : []
452  const fp = review !== null && roadmap !== null ? prdFingerprint(review, roadmap) : null
453  let approved: string | null = null
454  try {
455    approved = (JSON.parse((await readText($, PROJECT_STATE)) ?? '{}') as { prd?: { fingerprint?: string } }).prd?.fingerprint ?? null
456  } catch {
457    approved = null
458  }
459  const item = roadmapItemOf({ featureDir, features, roadmap: items })
460  return {
461    prdSource: prdSourceOf(names),
462    prd: prd !== null,
463    prdReview: review !== null ? parsePrdReview(review) : null,
464    roadmap: items,
465    prdFingerprint: fp,
466    prdApproved: !!fp && approved === fp,
467    prdExcerpt: prd && item ? prdSections(prd, item.sections) || null : null,
468  }
469}
470
471/** Imports the PRD as it is: Markdown only; false for any other file or one that cannot be read. */
472async function importPrd($: $, source: string): Promise<boolean> {
473  const rel = relPath(source, root)
474  if (!/\.(md|markdown)$/i.test(rel)) return false
475  const text = await readText($, rel)
476  if (text === null) return false
477  await $.fs.write(at(PRD), text)
478  return true
479}
480
481/** The person approves the roadmap: kept in the local project state with its fingerprint, like the idea decision. */
482async function decidePrd($: $, value: string): Promise<string> {
483  let state: Record<string, unknown> = {}
484  try {
485    state = JSON.parse((await readText($, PROJECT_STATE)) ?? '{}') as Record<string, unknown>
486  } catch {
487    state = {}
488  }
489  await $.fs.write(at(PROJECT_STATE), JSON.stringify({ ...state, prd: { fingerprint: value, at: await stamp($) } }, null, 2) + '\n')
490  if (!(await exists($, LOCAL_IGNORE.path))) await $.fs.write(at(LOCAL_IGNORE.path), LOCAL_IGNORE.text)
491  await scan($)
492  const ap = await read($, autopilotA)
493  if (ap.on && ap.paused) await resumeAutopilot($)
494  const first = (await read($, snapshotA))?.roadmap?.[0]
495  return `Approved the roadmap${first ? `: the first feature is "${first.title}"` : ''}.`
496}
497
498/** `/xref prd <path>`: imports a PRD now, from any path in the project. */
499async function prdByCommand($: $, path: string): Promise<string> {
500  const source = path || (await read($, snapshotA))?.prdSource
501  if (!source) return 'Name the PRD: /xref prd <path to the Markdown file>.'
502  if (!/\.(md|markdown)$/i.test(source)) return `A PRD is read as Markdown: ${source} is no .md file.`
503  if (!(await importPrd($, source))) return `Could not read ${source}.`
504  await scan($)
505  return `Imported ${source} to ${PRD}. Next: the PRD review and the roadmap (the autopilot, or the speckit-xref:prd skill).`
506}
507
508/** The idea's state before the first feature: the brief Validate wrote, the person's decision on it, Shape's brief. */
509async function ideaState($: $): Promise<Pick<Snapshot, 'ideaBrief' | 'ideaDecision' | 'productBrief'>> {
510  const brief = await readText($, IDEA_BRIEF)
511  let decision: Snapshot['ideaDecision'] = null
512  try {
513    const raw = JSON.parse((await readText($, PROJECT_STATE)) ?? '{}') as { idea?: Snapshot['ideaDecision'] }
514    if (raw.idea && (raw.idea.decision === 'build' || raw.idea.decision === 'drop')) decision = raw.idea
515  } catch {
516    decision = null
517  }
518  const product = await readText($, PRODUCT_BRIEF)
519  return { ideaBrief: brief ? parseIdeaBrief(brief) : null, ideaDecision: decision, productBrief: product !== null, briefDecisions: product ? briefDecisionsOf(product) : [] }
520}
521
522/** The product brief's `## Decisions (the person's)` bullets: what the person decided before the spec. */
523function briefDecisionsOf(markdown: string): string[] {
524  const out: string[] = []
525  let inside = false
526  for (const line of markdown.split('\n')) {
527    const h = /^##\s+(.+)$/.exec(line)
528    if (h) {
529      inside = /decision|entscheid/i.test(h[1]!) && !/assum|annahme/i.test(h[1]!)
530      continue
531    }
532    const bullet = inside ? /^\s*[-*]\s+(.+)$/.exec(line) : null
533    if (bullet) out.push(bullet[1]!.replace(/\*\*/g, '').trim())
534  }
535  return out
536}
537
538/**
539 * The person decides on the idea brief: Build goes on, Drop stops the run. Kept in the local project state with the
540 * brief's fingerprint, so only the person's press counts and a rewritten brief asks again; the brief shows the line.
541 */
542async function decideIdea($: $, decision: 'build' | 'drop'): Promise<string> {
543  const snap = await read($, snapshotA)
544  const brief = snap?.ideaBrief
545  if (!brief) return 'No idea brief to decide on.'
546  const at = await stamp($)
547  let state: Record<string, unknown> = {}
548  try {
549    state = JSON.parse((await readText($, PROJECT_STATE)) ?? '{}') as Record<string, unknown>
550  } catch {
551    state = {}
552  }
553  await $.fs.write(at$(PROJECT_STATE), JSON.stringify({ ...state, idea: { decision, fingerprint: brief.fingerprint, at } }, null, 2) + '\n')
554  if (!(await exists($, LOCAL_IGNORE.path))) await $.fs.write(at$(LOCAL_IGNORE.path), LOCAL_IGNORE.text)
555  const text = (await readText($, IDEA_BRIEF)) ?? ''
556  const line = `**Decision**: ${decision} (the person, ${at.slice(0, 10)})`
557  const lines = text.split('\n').filter(l => !/^\*\*Decision\*\*:/i.test(l))
558  const after = lines.findIndex(l => /^\*\*(Recommendation|Score)\*\*:/i.test(l))
559  lines.splice(after >= 0 ? after + 1 : 1, 0, line)
560  await $.fs.write(at$(IDEA_BRIEF), lines.join('\n'))
561  await scan($)
562  const ap = await read($, autopilotA)
563  if (decision === 'drop') {
564    if (ap.on) await stopAutopilot($, `Idea dropped: "${brief.title}". The brief stays in ${IDEA_BRIEF}.`)
565    return `Dropped the idea "${brief.title}".`
566  }
567  if (ap.on && ap.paused) await resumeAutopilot($)
568  return `Building "${brief.title}": shape, constitution and spec come next.`
569}
570
571/** Sharpen: the person says what should change, and Validate runs again on the sharper idea. */
572async function sharpenIdea($: $): Promise<void> {
573  let change = ''
574  try {
575    change = await $.ui.ask('What should change about the idea?', { options: ['Narrow the audience', 'Change the core feature'], header: 'Sharpen' })
576  } catch {
577    return
578  }
579  if (!change.trim()) return
580  if ((await read($, autopilotA)).paused) await update($, autopilotA, a => ({ ...a, paused: null, stalls: 0 }))
581  void $.prompt.submit({ text: `Sharpen the idea: ${change}. Run the speckit-xref:validate skill again on the sharper idea and rewrite ${IDEA_BRIEF}.`, asUser: true })
582}
583
584/** A dropped idea reopens, or a new one starts: the old brief moves aside, the decision goes. */
585async function reopenIdea($: $, fresh: boolean): Promise<string> {
586  let state: Record<string, unknown> = {}
587  try {
588    state = JSON.parse((await readText($, PROJECT_STATE)) ?? '{}') as Record<string, unknown>
589  } catch {
590    state = {}
591  }
592  delete state.idea
593  await $.fs.write(at$(PROJECT_STATE), JSON.stringify(state, null, 2) + '\n')
594  if (fresh) {
595    const text = await readText($, IDEA_BRIEF)
596    if (text !== null) {
597      // Moved aside, never deleted: the old brief stays readable beside the new one.
598      await $.process.run(['mv', '--', at$(IDEA_BRIEF), at$(`.specify/memory/idea-brief-${(await stamp($)).slice(0, 10)}-dropped.md`)], { cwd: root, timeoutMs: 3000 }).catch(() => undefined)
599    }
600    await update($, autopilotA, a => ({ ...a, idea: null }))
601  }
602  await scan($)
603  return fresh ? 'The old brief is kept beside it; describe the new idea.' : 'The idea is open again: Build, Sharpen or Drop.'
604}
605
606const DASHBOARD = '.specify/xref/local/dashboard.html'
607
608/** The documents the dashboard shows in place: Spec Kit's artifacts of the feature, the constitution, the briefs. */
609async function dashboardDocs($: $, featureDir: string): Promise<DashboardDoc[]> {
610  const docs: DashboardDoc[] = []
611  const add = async (path: string, title: string) => {
612    const markdown = await readText($, path)
613    if (markdown !== null) docs.push({ path, title, markdown })
614  }
615  for (const [name, title] of [['spec.md', 'Spec'], ['plan.md', 'Plan'], ['tasks.md', 'Tasks'], ['research.md', 'Research'], ['data-model.md', 'Data model'], ['quickstart.md', 'Quickstart']] as const) {
616    await add(`${featureDir}/${name}`, title)
617  }
618  for (const dir of ['contracts', 'checklists']) {
619    try {
620      for (const e of await $.fs.list(at(`${featureDir}/${dir}`))) if (e.kind === 'file' && e.name.endsWith('.md')) await add(`${featureDir}/${dir}/${e.name}`, `${dir}/${e.name}`)
621    } catch {
622      // The feature has none.
623    }
624  }
625  await add(ROADMAP, 'Roadmap')
626  await add(PRD_REVIEW, 'PRD review')
627  await add(PRD, 'PRD')
628  await add(screensPath(featureDir), 'Screens')
629  await add(DESIGN_FILE, 'Design system')
630  await add('.specify/memory/constitution.md', 'Constitution')
631  await add(IDEA_BRIEF, 'Idea brief')
632  await add(PRODUCT_BRIEF, 'Product brief')
633  return docs
634}
635
636/** Writes the dashboard: after every step and on /xref web, never on every edit. Local and git-ignored. */
637async function writeDashboard($: $): Promise<string | null> {
638  const snap = await read($, snapshotA)
639  if (!snap?.featureDir) return null
640  const ledger = await read($, ledgerA)
641  const ap = await read($, autopilotA)
642  const report = evaluate(snap, ledger)
643  const proof = { featureDir: snap.featureDir, tasks: snap.tasks, reqs: snap.spec?.reqs ?? [], realTests: snap.realTests }
644  const levels: Record<string, Rung> = {}
645  for (const r of snap.spec?.reqs ?? []) if ((r.kind === 'FR' || r.kind === 'SC') && isActive(r)) levels[r.id] = levelOf(r.id, proof, ledger)
646  const step = nextStep(snap, ledger, ap.idea, flowOf(ap))
647  const html = renderDashboard({
648    generatedAt: await stamp($),
649    root,
650    snap,
651    ledger,
652    report,
653    levels,
654    step: { phase: step.phase, line: stepLine(step), needsUser: step.needsUser },
655    strip: phaseStrip(snap, step, review !== 'none' && specReview(snap, ledger) !== 'approved'),
656    autopilot: ap,
657    runLog: await runLog($),
658    docs: await dashboardDocs($, snap.featureDir),
659    design: snap.design?.screens
660      ? { dir: designDir(snap.featureDir), screens: snap.design.screens, tokens: designTokens((await readText($, DESIGN_FILE)) ?? ''), approved: ledger.approvals.design === snap.design.fingerprint }
661      : null,
662    refreshSeconds: 5,
663  })
664  try {
665    if (!(await exists($, LOCAL_IGNORE.path))) await $.fs.write(at(LOCAL_IGNORE.path), LOCAL_IGNORE.text)
666    await $.fs.write(at(DASHBOARD), html)
667    return at(DASHBOARD)
668  } catch {
669    return null
670  }
671}
672
673/** Writes the dashboard and opens it in the default browser; where nothing opens it, the path is the way in. */
674async function openDashboard($: $): Promise<string> {
675  await scan($)
676  const path = await writeDashboard($)
677  if (!path) return 'No Spec Kit feature yet: the dashboard starts with the first spec.'
678  const opener = (await $.process.run(['uname'], { cwd: root, timeoutMs: 3000 }).catch(() => null))?.stdout.trim() === 'Darwin' ? 'open' : 'xdg-open'
679  const opened = await $.process.run([opener, path], { cwd: root, timeoutMs: 5000 }).then(r => r.exitCode === 0).catch(() => false)
680  return `${opened ? 'Dashboard opened' : 'Dashboard written'}: file://${path}\nIt reloads itself and is rewritten after every step. Local only: it holds your own words.`
681}
682
683/**
684 * The working tree's content, committed or not: `git stash create` makes a commit object of the tracked changes
685 * without touching the tree or any ref (empty when there are none, then HEAD stands for it), and the untracked files
686 * count by their hashes. Null where git cannot say.
687 */
688async function workingTree($: $): Promise<string | null> {
689  const git = (argv: string[]) => $.process.run(['git', ...argv], { cwd: root, timeoutMs: 10_000 })
690  try {
691    const stash = await git(['stash', 'create'])
692    const ref = (stash.exitCode === 0 && stash.stdout.trim()) || 'HEAD'
693    const tree = await git(['ls-tree', '-r', `${ref}^{tree}`])
694    if (tree.exitCode !== 0) return null
695    const others = (await git(['ls-files', '--others', '--exclude-standard'])).stdout.split('\n').filter(f => f.trim() && !/(^|\/)xref\.json$/.test(f))
696    const hashes = others.length ? (await git(['hash-object', '--', ...others.slice(0, 500)])).stdout.split('\n') : []
697    return treeOf([tree.stdout, ...others.slice(0, 500).map((f, i) => untrackedLine(hashes[i] ?? '', f))].join('\n'))
698  } catch {
699    return null
700  }
701}
702
703/** What git shows for DESIGN.md since the last commit; null where git cannot say. */
704async function designGit($: $): Promise<'created' | 'extended' | 'unchanged' | null> {
705  try {
706    const ran = await $.process.run(['git', 'status', '--porcelain', '--', DESIGN_FILE], { cwd: root, timeoutMs: 3000 })
707    return ran.exitCode === 0 ? designChangeFromGit(ran.stdout) : null
708  } catch {
709    return null
710  }
711}
712
713/** Whether the repository has a commit: true, false (a repository without one), null (no git here). */
714async function hasCommits($: $): Promise<boolean | null> {
715  try {
716    const inside = await $.process.run(['git', 'rev-parse', '--is-inside-work-tree'], { cwd: root, timeoutMs: 3000 })
717    if (inside.exitCode !== 0) return null
718    return (await $.process.run(['git', 'rev-parse', '--verify', '--quiet', 'HEAD'], { cwd: root, timeoutMs: 3000 })).exitCode === 0
719  } catch {
720    return null
721  }
722}
723
724/** Spec Kit's commands installed for Claude Code, by name without prefix: `plan`, `analyze`, `xref-check`. */
725async function installedCommands($: $): Promise<string[]> {
726  const names = new Set<string>()
727  try {
728    for (const e of await $.fs.list(at('.claude/skills'))) if (e.kind === 'dir' && e.name.startsWith('speckit-')) names.add(e.name.slice('speckit-'.length))
729  } catch {
730    // No skills folder: the commands layout, or no integration.
731  }
732  try {
733    for (const e of await $.fs.list(at('.claude/commands'))) {
734      const m = /^speckit\.(.+)\.md$/.exec(e.name)
735      if (m) names.add(m[1]!.replace(/\./g, '-'))
736    }
737  } catch {
738    // No commands folder.
739  }
740  return [...names].sort()
741}
742
743/** The feature's checklists with open items. */
744async function checklists($: $, featureDir: string): Promise<{ file: string; open: number }[]> {
745  const files: Record<string, string> = {}
746  try {
747    for (const e of await $.fs.list(at(`${featureDir}/checklists`))) {
748      if (e.kind !== 'file' || !e.name.endsWith('.md')) continue
749      const text = await readText($, `${featureDir}/checklists/${e.name}`)
750      if (text !== null) files[`checklists/${e.name}`] = text
751    }
752  } catch {
753    return []
754  }
755  return openChecklistItems(files)
756}
757
758/** The test files tied to the feature (anchored, linked or touched) that hold real tests, not only test.todo. */
759async function findRealTests($: $, ledger: Ledger): Promise<string[]> {
760  const candidates = new Set<string>()
761  for (const a of ledger.anchors) candidates.add(a.file)
762  for (const r of Object.values(ledger.requirements)) r.files.forEach(f => candidates.add(f))
763  for (const t of Object.values(ledger.tasks)) [...t.touched, ...t.linked].forEach(f => candidates.add(f))
764  const real: string[] = []
765  for (const file of [...candidates].filter(isTestFile).slice(0, 200)) {
766    const text = await readText($, file)
767    if (text !== null && hasRealTests(text)) real.push(file)
768  }
769  return real.sort()
770}
771
772/**
773 * Spec Kit's Claude Code integration: its core commands are there, as skills or as commands. integration.json
774 * alone is not enough, and neither is a stray speckit-* skill: the autopilot has to be able to run the next step.
775 */
776async function hasClaudeIntegration($: $): Promise<boolean> {
777  for (const name of ['plan', 'implement']) {
778    if ((await exists($, `.claude/skills/speckit-${name}/SKILL.md`)) || (await exists($, `.claude/commands/speckit.${name}.md`))) return true
779  }
780  return false
781}
782
783function speckitVersionOf(initOptions: string | null): string | null {
784  try {
785    const value = JSON.parse(initOptions ?? '') as { speckit_version?: unknown }
786    return typeof value.speckit_version === 'string' ? value.speckit_version : null
787  } catch {
788    return null
789  }
790}
791
792async function refresh($: $): Promise<void> {
793  const snap = await read($, snapshotA)
794  const featureDir = await resolveFeature($, undefined, snap?.branch)
795  if (featureDir !== (snap?.featureDir ?? null) || (await currentSignature($, featureDir)) !== signature) await scan($)
796}
797
798/**
799 * After every turn: the anchors and the files with real tests as the repository has them now, so a test written
800 * outside a booked write (a Bash heredoc, a subagent, a commit) still lifts its requirement on the ladder (Fund 38).
801 */
802async function refreshProof($: $): Promise<void> {
803  const snap = await read($, snapshotA)
804  if (!snap?.featureDir) return
805  const anchors = await scanAnchors($)
806  if (!anchors) return
807  await update($, ledgerA, l => ({ ...l, anchors }))
808  const realTests = await findRealTests($, await read($, ledgerA))
809  await update($, snapshotA, s => (s ? { ...s, realTests } : s))
810}
811
812/** Every `@spec <id>` comment in the repository, by ripgrep or else git grep; none when neither runs. */
813async function scanAnchors($: $): Promise<Anchor[] | null> {
814  const runs = [
815    ['rg', '-n', '--no-heading', '-o', '-e', ANCHOR_RG, '--glob', '!specs/**', '--glob', '!.specify/**', '.'],
816    // --untracked: a new file the person has not committed yet holds anchors too.
817    ['git', 'grep', '--untracked', '-n', '-o', '-E', ANCHOR_GIT, '--', '.', ':!specs', ':!.specify'],
818  ]
819  for (const argv of runs) {
820    try {
821      const ran = await $.process.run(argv, { cwd: root, timeoutMs: 5000 })
822      if (ran.exitCode > 1) continue
823      const anchors: Anchor[] = []
824      for (const line of ran.stdout.split('\n')) {
825        const m = /^(.+?):(\d+):(.*)$/.exec(line)
826        if (!m) continue
827        for (const a of anchorsIn(m[3] ?? '', relPath(m[1] ?? '', root))) anchors.push({ ...a, line: Number(m[2]) })
828      }
829      return anchors
830    } catch {
831      continue
832    }
833  }
834  return null
835}
836
837/**
838 * Writes both halves of the ledger: the committed `xref.json` (deterministic, reviewable) and the local file
839 * under `.specify/xref/local/`, which a `.gitignore` of its own keeps out of commits.
840 */
841async function persist($: $): Promise<void> {
842  const snap = await read($, snapshotA)
843  if (!snap?.featureDir) return
844  const ledger = await read($, ledgerA)
845  const parts = ledgerToParts(ledger, snap.featureDir)
846  try {
847    if ((await readText($, `${snap.featureDir}/xref.json`)) !== parts.committed) await $.fs.write(at(`${snap.featureDir}/xref.json`), parts.committed)
848    if (!(await exists($, LOCAL_IGNORE.path))) await $.fs.write(at(LOCAL_IGNORE.path), LOCAL_IGNORE.text)
849    await $.fs.write(at(localPath(snap.featureDir)), parts.local)
850  } catch {
851    // A read-only checkout keeps the ledger for the session alone.
852  }
853}
854
855/** Tells the person once the drift gets worse, never on every write. */
856async function notifyLevel($: $): Promise<void> {
857  const snap = await read($, snapshotA)
858  if (!snap) return
859  const report = evaluate(snap, await read($, ledgerA))
860  if (RANK[report.level] > RANK[lastLevel] && (report.level === 'yellow' || report.level === 'red')) {
861    $.ui.toast(`Spec drift ${report.level}: ${report.findings[0]?.text ?? ''}`)
862  }
863  lastLevel = report.level
864}
865
866async function afterWrite($: $, rel: string, c: Classified, newText: string): Promise<void> {
867  if (c.verdict === 'spec') {
868    await scan($)
869    return
870  }
871  // Lockfiles, build output, caches: no evidence for a task, no drift, no part of the turn's changes.
872  if (c.verdict === 'exempt') return
873  const when = await stamp($)
874  // A file's anchors are read again when the write may have added or removed one.
875  const hadAnchors = (await read($, ledgerA)).anchors.some(a => a.file === rel)
876  const text = hadAnchors || newText.includes('@spec') ? await readText($, rel) : null
877  const fresh = text === null ? null : anchorsIn(text, rel)
878  await update($, ledgerA, l => {
879    const next = recordTouch(l, rel, c, when)
880    return fresh ? { ...next, anchors: [...next.anchors.filter(a => a.file !== rel), ...fresh] } : next
881  })
882  // A file of a finished task is rework: it does not pull the focus back to that task.
883  const task = (await read($, snapshotA))?.tasks.find(t => t.id === c.task)
884  if (task && !task.done && (c.verdict === 'in-scope' || c.verdict === 'other-task')) await update($, activeA, () => task.id)
885  await update($, turnFilesA, files => (files.includes(rel) ? files : [...files, rel]))
886  // A test file written is read once: whether it holds real tests decides the ladder's `tested`.
887  if (isTestFile(rel)) {
888    const body = text ?? (await readText($, rel))
889    await update($, snapshotA, s => (s ? { ...s, realTests: body && hasRealTests(body) ? [...new Set([...s.realTests, rel])].sort() : s.realTests.filter(f => f !== rel) } : s))
890  }
891  await notifyLevel($)
892}
893
894/**
895 * The files the working tree changed, for a check the person asked for between turns: relative to the project
896 * and only inside it, since the project may be one folder of a larger repository.
897 */
898async function changedFiles($: $, since = 'HEAD', max = 40): Promise<string[]> {
899  const files = new Set<string>()
900  for (const argv of [
901    // Against the commit the turn started from: what was written and committed in the same turn counts too (Fund 38).
902    ['git', 'diff', '--name-only', '--relative', since],
903    ['git', 'ls-files', '--others', '--exclude-standard'],
904  ]) {
905    try {
906      const ran = await $.process.run(argv, { cwd: root, timeoutMs: 5000 })
907      if (ran.exitCode === 0) for (const line of ran.stdout.split('\n')) if (line.trim()) files.add(line.trim())
908    } catch {
909      // No git, or no commit yet: the files of this session's turns are all there is.
910    }
911  }
912  return [...files].filter(f => !isSpecArtifact(f)).slice(0, max)
913}
914
915async function diffOf($: $, files: string[]): Promise<string> {
916  let diff = ''
917  try {
918    diff = (await $.process.run(['git', 'diff', '--no-color', '--relative', '-U2', 'HEAD', '--', ...files], { cwd: root, timeoutMs: 5000 })).stdout
919  } catch {
920    diff = ''
921  }
922  // A new file is no part of `git diff`; its head stands in for it.
923  for (const file of files) {
924    if (diff.length > 6000 || diff.includes(`b/${file}`)) continue
925    const text = await readText($, file)
926    if (text !== null) diff += `\n--- new or untracked: ${file}\n${text.split('\n').slice(0, 60).join('\n')}\n`
927  }
928  return diff
929}
930
931/** The semantic check: one tool-less question over the session's own transcript. */
932async function runCheck($: $, files: string[], model: string): Promise<string> {
933  const snap = await read($, snapshotA)
934  if (!snap?.featureDir) return 'No Spec Kit feature to check against.'
935  if (await read($, checkingA)) return 'A drift check is already running.'
936  await update($, checkingA, () => true)
937  try {
938    const changed = files.length ? files : await changedFiles($)
939    const ledger = await read($, ledgerA)
940    const active = await read($, activeA)
941    const diff = await diffOf($, changed)
942    let reply = await $.model.fork({ prompt: forkPrompt(snap, ledger, active, changed, diff) })
943    // Before the session's first turn there is no transcript to fork; the intent log carries the user's words instead.
944    if (!reply.isAnswered && reply.reason === 'nothing-to-fork') {
945      reply = await $.model.complete({ model, prompt: forkPrompt(snap, ledger, active, changed, diff, true), maxTokens: 1000 })
946    }
947    if (!reply.isAnswered) return `The drift check got no answer (${reply.reason}).`
948    const semantic = parseSemantic(reply.text, await stamp($))
949    if (!semantic) return 'The drift check answered in a shape the mod could not read.'
950    await update($, ledgerA, l => applySemantic(l, semantic))
951    await persist($)
952    await notifyLevel($)
953    const conflict = (await read($, ledgerA)).semantic?.changes.find(c => c.kind === 'contradicts')
954    if (conflict && (await read($, autopilotA)).on) await pauseAutopilot($, `your request "${conflict.text}" contradicts the spec; decide in the pane`)
955    return `Intent check ${semantic.score}/100 (${semantic.verdict})${semantic.reasons[0] ? `: ${semantic.reasons[0]}` : ''}`
956  } finally {
957    await update($, checkingA, () => false)
958  }
959}
960
961async function runMap($: $, model: string): Promise<string> {
962  const snap = await read($, snapshotA)
963  if (!snap?.spec || snap.tasks.length === 0) return 'Mapping needs a spec.md with requirements and a tasks.md.'
964  const reply = await $.model.complete({ model, prompt: mapPrompt(snap.spec, snap.tasks), maxTokens: 2000 })
965  if (!reply.isAnswered) return `The mapping got no answer (${reply.reason}).`
966  let mapped = 0
967  await update($, ledgerA, l => {
968    const result = applyMapping(l, reply.text, snap)
969    mapped = result.mapped
970    return result.ledger
971  })
972  await persist($)
973  const report = evaluate(snap, await read($, ledgerA))
974  return `Mapped ${mapped} requirements to tasks; ${report.covered}/${report.total} FRs covered.`
975}
976
977async function toSpec($: $, intent: string): Promise<void> {
978  const snap = await read($, snapshotA)
979  if (!snap) return
980  await update($, ledgerA, l => resolveIntent(l, intent))
981  await persist($)
982  const args = `The user asked during implementation: "${intent}". Fold this into the spec, or record why it stays out of scope.`
983  // The extension's revise keeps ids stable (new, SUPERSEDED, RETIRED) and logs revisions.md; clarify is the fallback.
984  const revise = snap.extensions.includes('xref') && snap.commands.includes('xref-revise')
985  // A plugin runs a slash command through $.command.run; a prompt may not start with one.
986  const command = speckitCommand(snap, revise ? 'xref.revise' : 'clarify').slice(1)
987  try {
988    await $.command.run({ command, args })
989  } catch {
990    void $.prompt.submit({ text: `Spec Kit: ${args} Use ${speckitCommand(snap, 'clarify')} for it.` })
991  }
992}
993
994async function asTask($: $, intent: string): Promise<string> {
995  const snap = await read($, snapshotA)
996  if (!snap?.featureDir) return 'No active feature.'
997  const path = `${snap.featureDir}/tasks.md`
998  const markdown = (await readText($, path)) ?? '# Tasks\n'
999  const added = appendRemediation(markdown, snap.tasks, intent)
1000  await $.fs.write(at(path), added.markdown)
1001  await update($, ledgerA, l => resolveIntent(l, intent))
1002  await scan($)
1003  await persist($)
1004  return `Added ${added.id} to ${path}.`
1005}
1006
1007async function focus($: $, id: string): Promise<string> {
1008  const snap = await read($, snapshotA)
1009  const task = snap?.tasks.find(t => t.id === id.trim().toUpperCase())
1010  if (!snap || !task) return `No task ${id} in tasks.md.`
1011  await update($, activeA, () => task.id)
1012  const reqs = reqsOf(task, await read($, ledgerA))
1013  return [
1014    `Current task: ${task.id}${task.story ? ` [${task.story}]` : ''} ${task.text}`,
1015    `Planned files: ${task.paths.join(', ') || '(none named)'}`,
1016    `Serves: ${reqs.join(', ') || '(no requirement mapped yet)'}`,
1017  ].join('\n')
1018}
1019
1020async function where($: $, file: string): Promise<string> {
1021  const snap = await read($, snapshotA)
1022  if (!snap?.featureDir) return 'No active Spec Kit feature.'
1023  const rel = relPath(file, root)
1024  const ledger = await read($, ledgerA)
1025  const c = classify(rel, snap, ledger, await read($, activeA))
1026  const planned = snap.tasks.filter(t => t.paths.some(p => rel === p || rel.endsWith('/' + p) || rel.startsWith(p.replace(/\/?$/, '/'))))
1027  const touched = Object.entries(ledger.tasks).filter(([, e]) => e.touched.includes(rel) || e.linked.includes(rel)).map(([id]) => id)
1028  const reqs = Object.entries(ledger.requirements).filter(([, r]) => r.files.includes(rel)).map(([id]) => id)
1029  const anchors = ledger.anchors.filter(a => a.file === rel).map(a => `${a.id} (line ${a.line})`)
1030  return [
1031    `${rel} in ${snap.featureDir}: ${c.verdict}${c.task ? ` (${c.task})` : ''}`,
1032    `Planned by: ${planned.map(t => t.id).join(', ') || '-'}`,
1033    `Touched or linked by: ${touched.join(', ') || '-'}`,
1034    `Requirements: ${[...reqs, ...anchors].join(', ') || '-'}`,
1035  ].join('\n')
1036}
1037
1038async function linkFile($: $, file: string, id: string): Promise<string> {
1039  const snap = await read($, snapshotA)
1040  if (!snap?.featureDir) return 'No active Spec Kit feature.'
1041  const rel = relPath(file, root)
1042  let error: string | undefined
1043  await update($, ledgerA, l => {
1044    const result = link(l, rel, id, snap)
1045    error = result.error
1046    return result.ledger
1047  })
1048  if (error) return error
1049  await persist($)
1050  await notifyLevel($)
1051  return `Linked ${rel} to ${id}.`
1052}
1053
1054/** What the workflow reads beside the snapshot: the review option and the last test run. */
1055const flowOf = (ap: Autopilot): Flow => ({ review, lastTest: ap.lastTest, repairs: ap.repairs, validate: validateOn, shape: shapeOn, design: designOn, next: ap.next ?? null, nextKind: ap.nextKind ?? null, verifies: ap.verifies ?? 0, acceptance: acceptanceOn, orchestrate: orchestrateOn, models: modelsOption, userTest: userTestOn })
1056
1057/** Starts a fresh autopilot run; its first step follows as soon as the session is free. */
1058async function startAutopilot($: $, max?: number, night = false): Promise<void> {
1059  const cost = await sessionCost($)
1060  const now = await $.clock.now()
1061  await update($, autopilotA, a => ({ ...a, on: true, paused: null, steps: 0, stalls: 0, last: null, lastPhase: null, idea: null, max: max ?? defaultMax, repairs: 0, lastTest: null, startedAt: now, costAtStart: cost, night, scope: null, remediate: false, remediations: 0, testNote: null, verifies: 0, delegation: null, steer: null, rework: null, reworks: 0, heard: null, deputyNote: null }))
1062  // A release's yes never carries into a new run.
1063  await update($, permitsA, ps => ps.filter(p => !p.many))
1064  await update($, seenAtA, () => now)
1065  await retitle($)
1066  $.clock.after(0, () => void advance($).catch(() => undefined))
1067}
1068
1069/** Goes on after a pause; a run whose budget is spent gets a new one. */
1070async function resumeAutopilot($: $): Promise<void> {
1071  // Resume past the verify limit is the person asking for one more verification.
1072  await update($, autopilotA, a => ({ ...a, paused: null, stalls: 0, repairs: a.repairs > MAX_REPAIRS ? 0 : a.repairs, steps: a.steps >= a.max ? 0 : a.steps, verifies: 0 }))
1073  await retitle($)
1074  $.clock.after(0, () => void advance($).catch(() => undefined))
1075}
1076
1077/** Stop: the autopilot goes off, and a turn it is running ends now rather than at its end. */
1078async function turnOffAutopilot($: $): Promise<void> {
1079  const wasOn = (await read($, autopilotA)).on
1080  await update($, autopilotA, a => ({ ...a, on: false, paused: null, idea: null, delegation: null, steer: null, rework: null, heard: null, deputyNote: null }))
1081  await update($, permitsA, ps => ps.filter(p => !p.many))
1082  await update($, queueA, q => ({ ...q, auto: false }))
1083  await retitle($)
1084  const turn = await read($, turnA)
1085  if (wasOn && turn) await $.turn.abort({ turnId: turn.id }).catch(() => undefined)
1086  if (wasOn) await writeBriefing($, 'stopped by you')
1087}
1088
1089/** The session's cost so far in US dollars, or 0 where the host keeps none. */
1090async function sessionCost($: $): Promise<number> {
1091  try {
1092    return (await $.session.usage()).cost?.usd ?? 0
1093  } catch {
1094    return 0
1095  }
1096}
1097
1098/** The pane's tab says when the autopilot waits, so it shows behind the changes pane too. */
1099async function retitle($: $): Promise<void> {
1100  try {
1101    const pane = (await $.ui.panes()).find(p => p.id === PANE)
1102    if (!pane) return
1103    const ap = await read($, autopilotA)
1104    await $.ui.open({ id: PANE, title: ap.on && ap.paused ? `${TITLE} ⏸` : TITLE })
1105  } catch {
1106    // A host without panes has no tab to name.
1107  }
1108}
1109
1110/** The requests the pane's setup actions hand to Claude, as the person's own words: a press is their consent. */
1111const SETUP_ASKS = {
1112  idea: 'I want to start something new in this empty folder (an app, a project, or a problem to solve). Ask me what it is, then set Spec Kit up for it with the speckit-xref:speckit skill (with a git repository and a first commit, so Spec Kit can open a branch per feature) and write the spec in my own words.',
1113  setup: 'Set Spec Kit up in this existing project with the speckit-xref:speckit skill: run specify init, draft the constitution from the code and the README and mark the assumptions, then ask me which change to specify first.',
1114  commit:
1115    "Make the first commit of this repository: first make sure a .gitignore keeps out dependencies, build output and secrets (node_modules/, dist/, .env*, and whatever this stack needs), then git add -A and commit with the message 'Initial commit'. Spec Kit can then open a branch per feature.",
1116  integration: "Install Spec Kit's Claude Code integration in this project (specify integration install claude), so its /speckit-* commands run here.",
1117} as const
1118
1119async function askClaude($: $, kind: keyof typeof SETUP_ASKS): Promise<void> {
1120  // A press answers what the autopilot waits on: it goes on once Claude has done it.
1121  if ((await read($, autopilotA)).paused) await update($, autopilotA, a => ({ ...a, paused: null, stalls: 0 }))
1122  void $.prompt.submit({ text: SETUP_ASKS[kind], asUser: true })
1123}
1124
1125/** Approvals only the person gives: the idea, the spec, the plan, the design, open checklists. The autopilot records checkpoints, never these. */
1126const APPROVALS = new Set(['idea', 'prd', 'spec', 'plan', 'design', 'checklists', 'done', 'release', 'polish'])
1127/** The button an approval wears. */
1128const approveLabel = (key: string) => ({ checklists: 'Proceed anyway', idea: 'Build', prd: 'Approve roadmap', done: 'Call it done', release: 'Ship it', polish: 'Approve direction' })[key] ?? `Approve ${key}`
1129const CHECKPOINTS = new Set(['analyze', 'converge', 'verify', 'accept', 'ship', 'released', 'polishCheck'])
1130
1131/** The person approves what the autopilot waits on (spec, plan, design, open checklists); the run goes on. */
1132async function approve($: $): Promise<string> {
1133  const snap = await read($, snapshotA)
1134  if (!snap) return 'Nothing to approve.'
1135  const ap = await read($, autopilotA)
1136  const ledger = await read($, ledgerA)
1137  const step = nextStep(snap, ledger, ap.idea, flowOf(ap))
1138  if (!step.approve || !APPROVALS.has(step.approve.key)) {
1139    // No gate stands, but the spec was never approved (◌spec): the person can approve it now, for this text.
1140    if (snap.spec && specReview(snap, ledger) !== 'approved') {
1141      await update($, ledgerA, l => ({ ...l, approvals: { ...l.approvals, spec: specFingerprint(snap.spec!) } }))
1142      await persist($)
1143      return `Approved the spec of ${snap.featureDir}.`
1144    }
1145    return 'Nothing waits for an approval.'
1146  }
1147  const { key, value } = step.approve
1148  if (key === 'idea') return decideIdea($, 'build')
1149  if (key === 'prd') return decidePrd($, value)
1150  if (key === 'done') {
1151    // Closing the feature as it is: the verification and the acceptance count for this tree, and what comes next is asked.
1152    await update($, ledgerA, l => ({ ...l, checkpoints: { ...l.checkpoints, verify: value, accept: value } }))
1153    await persist($)
1154    // Closed by the person under option git pr: it goes up as a pull request too (0.11.0).
1155    const pr = gitMode === 'pr' ? ` ${await openPullRequest($)}` : ''
1156    if (ap.on && ap.paused) await resumeAutopilot($)
1157    return `Closed ${snap.featureDir} as done.${pr}`
1158  }
1159  await update($, ledgerA, l => ({ ...l, approvals: { ...l.approvals, [key]: value } }))
1160  await persist($)
1161  if (ap.on && ap.paused) await resumeAutopilot($)
1162  if (key === 'release') return `Approved the release: ${releaseLine(snap.release)}. ${ap.on ? 'Its commands run now.' : 'Its commands run when the autopilot goes on (/xref auto on).'}`
1163  return key === 'checklists' ? 'Going on despite the open checklist items.' : `Approved the ${key} of ${snap.featureDir}.`
1164}
1165
1166/**
1167 * The person's own command for a later phase is their approval of the review that stands before it: running
1168 * `/speckit-plan` approves the spec, `/speckit-tasks` the plan or the design. The autopilot never runs past a review,
1169 * so it never approves this way; a plugin's or the model's call is no command of the person's.
1170 */
1171const COMMAND_ORDER: Record<string, number> = { plan: 1, tasks: 2, implement: 3 }
1172const GATE_ORDER: Record<string, number> = { spec: 1, plan: 2, design: 2, checklists: 3 }
1173async function approveByCommand($: $, text: string): Promise<void> {
1174  const m = /(?:^|\s)\/?speckit[-.](plan|tasks|implement)\b/.exec(text)
1175  if (!m) return
1176  const snap = await read($, snapshotA)
1177  if (!snap) return
1178  const ap = await read($, autopilotA)
1179  const step = nextStep(snap, await read($, ledgerA), ap.idea, flowOf(ap))
1180  const key = step.phase === 'review' ? step.approve?.key : null
1181  if (!key || !step.approve || !GATE_ORDER[key] || COMMAND_ORDER[m[1]!]! < GATE_ORDER[key]!) return
1182  const { value } = step.approve
1183  await update($, ledgerA, l => ({ ...l, approvals: { ...l.approvals, [key]: value } }))
1184  await persist($)
1185  $.ui.toast(`Approved the ${key}: you ran /speckit-${m[1]}.`)
1186}
1187
1188/** Keep: the person agrees with an assumption the spec makes; it is shown as kept until its text changes. */
1189async function keepAssumption($: $, text: string): Promise<string> {
1190  await update($, ledgerA, l => ({ ...l, assumed: { ...(l.assumed ?? {}), [fingerprint(text)]: 'keep' } }))
1191  await persist($)
1192  return 'Kept the assumption.'
1193}
1194
1195/** Change: what should hold instead goes to Claude as the person's words, and the spec changes before it is approved. */
1196async function changeAssumption($: $, text: string): Promise<void> {
1197  const drop = 'Drop it'
1198  const open = 'Make it an open question'
1199  let answer = ''
1200  try {
hooks/dashboard.ts 663 lines
1// The dashboard: one self-contained HTML page with more than the pane can hold. Pure: register.tsx writes it to
2// .specify/xref/local/dashboard.html after every autopilot step; the person opens it via file://.
3
4import type { Autopilot, Ledger, RunEntry, Screen, Snapshot, Task } from '../types'
5import type { designTokens } from './design'
6import { acceptanceCounts, scenarioState, scenariosOf } from './accept'
7import type { ScenarioState } from './accept'
8import { LADDER, owners } from './proof'
9import type { Rung } from './proof'
10import { isTestFile, localId } from './rules'
11import { phaseLabel, phaseNumber, taskPhases } from './workflow'
12import { openUnplanned, reqsOf } from './xref'
13import type { Level, Report } from './xref'
14
15/** A Spec Kit document shown on the page; `path` is project-relative (`specs/001-x/spec.md`). */
16export type DashboardDoc = { path: string; title: string; markdown: string }
17export type DashboardInput = {
18  generatedAt: string
19  root: string
20  snap: Snapshot
21  ledger: Ledger
22  report: Report
23  levels: Record<string, Rung>
24  step: { phase: string; line: string; needsUser: string | null }
25  strip: string
26  autopilot: Autopilot
27  runLog: RunEntry[]
28  docs: DashboardDoc[]
29  /** The feature's screens and DESIGN.md's tokens, once the design step has drawn them. */
30  design?: { dir: string; screens: Screen[]; tokens: ReturnType<typeof designTokens>; approved: boolean } | null
31  refreshSeconds: number
32}
33
34// ---- Escaping and links ----
35
36const ESC: Record<string, string> = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }
37/** Text and attribute values alike: every attribute on the page is double-quoted. */
38const esc = (text: string) => String(text).replace(/[&<>"']/g, c => ESC[c]!)
39
40/** A project file as a file:// URL, each path segment encoded (a drive letter keeps its colon). */
41function fileUrl(root: string, rel: string): string {
42  const base = root.replace(/\\/g, '/').replace(/\/+$/, '')
43  const path = `${base}/${rel.replace(/\\/g, '/').replace(/^\.?\//, '')}`
44  const abs = path.startsWith('/') ? path : `/${path}`
45  return 'file://' + abs.split('/').map(s => encodeURIComponent(s).replace(/%3A/gi, ':')).join('/')
46}
47const fileLink = (root: string, rel: string) => `<a class="path" href="${esc(fileUrl(root, rel))}">${esc(rel)}</a>`
48
49/** Only http(s), file and relative links; no whitespace or control character a browser would strip. */
50const safeUrl = (url: string) => !!url && !/[\u0000- \u007f]/.test(url) && (/^(?:https?|file):/i.test(url) || !/^[^/?#]*:/.test(url))
51
52const decode = (s: string) => {
53  try {
54    return decodeURIComponent(s)
55  } catch {
56    return s
57  }
58}
59
60/** A doc's relative links point next to the doc, not next to the dashboard. */
61function rebaser(root: string, docPath: string): (url: string) => string {
62  const dir = docPath.includes('/') ? docPath.slice(0, docPath.lastIndexOf('/') + 1) : ''
63  return url => {
64    if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('#') || url.startsWith('//')) return url
65    const cut = url.search(/[?#]/)
66    const path = cut === -1 ? url : url.slice(0, cut)
67    const parts: string[] = []
68    for (const seg of ((path.startsWith('/') ? '' : dir) + path).split('/')) {
69      if (seg === '..') parts.pop()
70      else if (seg && seg !== '.') parts.push(decode(seg))
71    }
72    return fileUrl(root, parts.join('/')) + (cut === -1 ? '' : url.slice(cut))
73  }
74}
75
76// ---- Markdown (a safe subset: everything escaped, then formatted) ----
77
78const FENCE = /^\s*(`{3,}|~{3,})\s*([\w+-]*)/
79const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/
80const HR = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/
81const QUOTE = /^\s{0,3}>/
82const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/
83const TABLE_SEP = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/
84
85const emph = (t: string) =>
86  t
87    .replace(/\*\*(?=\S)([\s\S]*?\S)\*\*/g, '<strong>$1</strong>')
88    .replace(/(^|[^\w])__(?=\S)([\s\S]*?\S)__(?!\w)/g, '$1<strong>$2</strong>')
89    .replace(/(^|[^*\w])\*([^\s*](?:[^*]*?[^\s*])?)\*(?![*\w])/g, '$1<em>$2</em>')
90    .replace(/(^|[^\w])_([^\s_](?:[^_]*?[^\s_])?)_(?!\w)/g, '$1<em>$2</em>')
91    .replace(/~~(?=\S)([\s\S]*?\S)~~/g, '<del>$1</del>')
92
93function inline(raw: string, rebase?: (url: string) => string): string {
94  const held: string[] = []
95  const hold = (html: string) => `\u0000${held.push(html) - 1}\u0000`
96  const restore = (t: string): string => t.replace(/\u0000(\d+)\u0000/g, (_m, k: string) => restore(held[Number(k)] ?? ''))
97  const lines = raw.split('\n')
98  // A soft break is a space; two trailing spaces, a backslash, or a next line opening on **Label** break the line.
99  let s = lines
100    .map((l, k) => (k === lines.length - 1 ? l.trim() : l.replace(/(?: {2,}|\\)$/, '').trim() + (/ {2,}$|\\$/.test(l) || /^\s*\*\*/.test(lines[k + 1]!) ? '\u0001' : ' ')))
101    .join('')
102  s = s.replace(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g, (_m, _t, code: string) => hold(`<code>${esc(code.trim())}</code>`))
103  s = s.replace(/\[([^\]]+)\]\(\s*([^)\s]*)(?:\s+"[^"]*")?\s*\)/g, (m, label: string, url: string) =>
104    safeUrl(url) ? hold(`<a href="${esc(rebase ? rebase(url) : url)}">${emph(esc(label))}</a>`) : m,
105  )
106  return restore(emph(esc(s))).replace(/\u0001/g, '<br>')
107}
108
109function cells(row: string): string[] {
110  const out: string[] = []
111  const s = row.trim().replace(/^\|/, '')
112  let cur = ''
113  for (let k = 0; k < s.length; k++) {
114    if (s[k] === '\\' && s[k + 1] === '|') (cur += '|'), (k += 1)
115    else if (s[k] === '|') out.push(cur.trim()), (cur = '')
116    else cur += s[k]
117  }
118  if (cur.trim()) out.push(cur.trim())
119  return out
120}
121
122type Item = { indent: number; ordered: boolean; n: number; text: string }
123function list(items: Item[], fmt: (t: string) => string): string {
124  let html = ''
125  const stack: { indent: number; tag: string }[] = []
126  for (const it of items) {
127    const tag = it.ordered ? 'ol' : 'ul'
128    const open = `<${tag}${it.ordered && it.n !== 1 ? ` start="${it.n}"` : ''}>`
129    while (stack.length && it.indent < stack[stack.length - 1]!.indent) html += `</li></${stack.pop()!.tag}>`
130    const top = stack[stack.length - 1]
131    if (top && it.indent === top.indent && top.tag === tag) html += '</li>'
132    else if (top && it.indent === top.indent) (html += `</li></${top.tag}>${open}`), (top.tag = tag)
133    else html += open, stack.push({ indent: it.indent, tag })
134    const box = /^\[([ xX])\]\s+/.exec(it.text)
135    html += box ? `<li class="task"><input type="checkbox" disabled${box[1] !== ' ' ? ' checked' : ''}> ${fmt(it.text.slice(box[0].length))}` : `<li>${fmt(it.text)}`
136  }
137  while (stack.length) html += `</li></${stack.pop()!.tag}>`
138  return html
139}
140
141const startsBlock = (lines: string[], i: number) => {
142  const l = lines[i]!
143  return FENCE.test(l) || HEADING.test(l) || HR.test(l) || QUOTE.test(l) || ITEM.test(l) || (l.includes('|') && TABLE_SEP.test(lines[i + 1] ?? '') && (lines[i + 1] ?? '').includes('|'))
144}
145
146function md(markdown: string, rebase?: (url: string) => string): string {
147  const lines = markdown.replace(/[\u0000\u0001]/g, '').replace(/\r\n?/g, '\n').replace(/<!--[\s\S]*?-->/g, '').split('\n')
148  const fmt = (t: string) => inline(t, rebase)
149  const width = (s: string) => s.replace(/\t/g, '    ').length
150  const out: string[] = []
151  let i = 0
152  while (i < lines.length) {
153    const line = lines[i]!
154    if (!line.trim()) {
155      i += 1
156      continue
157    }
158    const fence = FENCE.exec(line)
159    if (fence) {
160      const body: string[] = []
161      for (i += 1; i < lines.length && !lines[i]!.trim().startsWith(fence[1]!); i++) body.push(lines[i]!)
162      i += 1
163      out.push(`<pre><code${fence[2] ? ` class="lang-${esc(fence[2])}"` : ''}>${esc(body.join('\n'))}</code></pre>`)
164      continue
165    }
166    const h = HEADING.exec(line)
167    if (h) {
168      out.push(`<h${h[1]!.length}>${fmt(h[2]!)}</h${h[1]!.length}>`)
169      i += 1
170      continue
171    }
172    if (HR.test(line)) {
173      out.push('<hr>')
174      i += 1
175      continue
176    }
177    if (QUOTE.test(line)) {
178      const body: string[] = []
179      while (i < lines.length && QUOTE.test(lines[i]!)) body.push(lines[i++]!.replace(/^\s{0,3}>\s?/, ''))
180      out.push(`<blockquote>${md(body.join('\n'), rebase)}</blockquote>`)
181      continue
182    }
183    if (line.includes('|') && (lines[i + 1] ?? '').includes('|') && TABLE_SEP.test(lines[i + 1] ?? '')) {
184      const head = cells(line)
185      const align = cells(lines[i + 1]!).map(c => (/^:-+:$/.test(c) ? 'center' : /-:$/.test(c) ? 'right' : ''))
186      const rows: string[][] = []
187      for (i += 2; i < lines.length && lines[i]!.includes('|') && lines[i]!.trim(); i++) rows.push(cells(lines[i]!))
188      const cell = (tag: string, c: string, k: number) => `<${tag}${align[k] ? ` style="text-align:${align[k]}"` : ''}>${fmt(c)}</${tag}>`
189      out.push(
190        `<div class="scroll"><table><thead><tr>${head.map((c, k) => cell('th', c, k)).join('')}</tr></thead><tbody>` +
191          rows.map(r => `<tr>${head.map((_, k) => cell('td', r[k] ?? '', k)).join('')}</tr>`).join('') +
192          '</tbody></table></div>',
193      )
194      continue
195    }
196    if (ITEM.test(line)) {
197      const items: Item[] = []
198      while (i < lines.length) {
199        const l = lines[i]!
200        const m = ITEM.exec(l)
201        if (m && !HR.test(l)) {
202          items.push({ indent: width(m[1]!), ordered: /\d/.test(m[2]!), n: parseInt(m[2]!, 10) || 1, text: m[3]! })
203          i += 1
204        } else if (!l.trim()) {
205          // A blank line ends the list unless an item or an indented line follows it.
206          let j = i + 1
207          while (j < lines.length && !lines[j]!.trim()) j++
208          if (j < lines.length && (ITEM.test(lines[j]!) || /^\s{2,}\S/.test(lines[j]!)) && !FENCE.test(lines[j]!) && !HR.test(lines[j]!)) i = j
209          else break
210        } else if (/^\s+\S/.test(l) && !FENCE.test(l)) {
211          items[items.length - 1]!.text += '\n' + l.trim()
212          i += 1
213        } else break
214      }
215      out.push(list(items, fmt))
216      continue
217    }
218    const para = [line]
219    for (i += 1; i < lines.length && lines[i]!.trim() && !startsBlock(lines, i); i++) para.push(lines[i]!)
220    out.push(`<p>${fmt(para.join('\n'))}</p>`)
221  }
222  return out.join('\n')
223}
224
225/** Markdown to HTML: headings, paragraphs, emphasis, code, lists, task boxes, tables, safe links, quotes, rules. */
226export function markdownToHtml(markdown: string): string {
227  return md(markdown)
228}
229
230const ID = /\b(?:(?:FR|SC)-\d{3,}|US\d+-AS\d+|T\d{3,})\b/g
231const SKIP = /^<(\/?)(a|code|pre|script|style|title|textarea)\b/i
232
233/** FR-### / SC-### / USn-ASm link to their matrix row, T### to its task; text inside links and code stays as it is. */
234export function linkIds(html: string): string {
235  let skip = 0
236  return html.replace(/<[^>]*>|[^<]+/g, part => {
237    if (part.startsWith('<')) {
238      const m = SKIP.exec(part)
239      if (m) skip = Math.max(0, skip + (m[1] ? -1 : 1))
240      return part
241    }
242    return skip ? part : part.replace(ID, id => `<a href="#${id.startsWith('T') ? 'task' : 'req'}-${id}">${id}</a>`)
243  })
244}
245
246// ---- The page ----
247
248const DRIFT: Record<Level, { glyph: string; word: string }> = {
249  green: { glyph: '●', word: 'ok' },
250  yellow: { glyph: '▲', word: 'watch' },
251  red: { glyph: '✖', word: 'off-spec' },
252  none: { glyph: '·', word: 'no feature' },
253}
254const RUNG_GLYPH: Record<Rung, string> = { specified: '○', planned: '◔', implemented: '◑', tested: '◕', passing: '●' }
255
256const time = (iso: string) => esc(iso.replace('T', ' ').replace(/(\.\d+)?Z$/, ' UTC'))
257const two = (n: number) => String(n).padStart(2, '0')
258const duration = (ms: number) => {
259  const s = Math.max(0, Math.round((Number(ms) || 0) / 1000))
260  return `${two(Math.floor(s / 60))}:${two(s % 60)}`
261}
262const thousands = (n: number) => String(Math.round(Number(n) || 0)).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
263const text = (s: string) => linkIds(esc(s))
264const section = (id: string, title: string, body: string) => `<section id="${id}"><h2>${title}</h2>\n${body}\n</section>`
265const ul = (items: string[], cls = '') => `<ul${cls ? ` class="${cls}"` : ''}>${items.map(i => `<li>${i}</li>`).join('')}</ul>`
266
267const autopilotLabel = (a: Autopilot) => (!a.on ? '○ off' : a.paused ? `⏸ on · waiting for you: ${a.paused}` : `▶ on · step ${a.steps}/${a.max}`)
268
269function header(input: DashboardInput): string {
270  const { snap, report, autopilot } = input
271  const d = DRIFT[report.level] ?? DRIFT.none
272  const facts = [
273    snap.featureDir ? `<code>${esc(snap.featureDir)}</code>` : 'no feature yet',
274    snap.branch ? `branch <code>${esc(snap.branch)}</code>` : '',
275    `generated <time datetime="${esc(input.generatedAt)}">${time(input.generatedAt)}</time>`,
276  ].filter(Boolean)
277  const counts = snap.featureDir ? [`tasks ${report.done}/${report.tasks}`, `FR planned or further ${report.covered}/${report.total}`] : []
278  return [
279    '<header>',
280    '<p class="kicker">Spec X-Ref dashboard</p>',
281    `<h1>${esc(snap.spec?.title ?? 'No feature yet')}</h1>`,
282    `<p class="meta">${facts.join(' · ')}</p>`,
283    `<p class="state"><span class="pill drift-${report.level}">drift ${d.glyph} ${d.word}</span> <span class="pill${autopilot.paused && autopilot.on ? ' wait' : ''}">autopilot ${esc(autopilotLabel(autopilot))}</span>${counts.map(c => ` <span class="pill quiet">${c}</span>`).join('')}</p>`,
284    '</header>',
285  ].join('\n')
286}
287
288function goal(input: DashboardInput): string {
289  const { snap, autopilot } = input
290  const words = snap.spec?.input
291    ? `<blockquote class="words">${esc(snap.spec.input)}</blockquote>`
292    : autopilot.idea
293      ? `<p class="muted">Not specified yet. Your idea:</p><blockquote class="words">${esc(autopilot.idea)}</blockquote>`
294      : '<p class="muted">No spec yet: your words appear here once spec.md is written.</p>'
295  const principles = snap.constitution?.principles.length ? `<ol>${snap.constitution.principles.map(p => `<li>${esc(p)}</li>`).join('')}</ol>` : '<p class="muted">No constitution yet.</p>'
296  return section('goal', 'Goal &amp; vision', `<h3>In your words</h3>\n${words}\n<h3>Principles of the constitution</h3>\n${principles}`)
297}
298
299function workflow(input: DashboardInput): string {
300  const tokens = input.strip.match(/[✓◌▶·][^\s✓◌▶·]+(?: \d+\/\d+)?/g)
301  const cls: Record<string, string> = { '✓': 'done', '◌': 'unreviewed', '▶': 'now', '·': 'todo' }
302  const strip = tokens ? tokens.map(t => `<span class="st st-${cls[t[0]!] ?? 'todo'}">${esc(t)}</span>`).join(' ') : esc(input.strip)
303  const waiting = input.step.needsUser ? `<div class="waiting" role="status"><strong>⏸ Waiting for you</strong><p>${text(input.step.needsUser)}</p></div>` : ''
304  return section('workflow', 'Workflow', `<p class="strip">${strip}</p>\n<p><span class="label">Next step</span> ${text(input.step.line)}</p>\n${waiting}`)
305}
306
307/** The look: DESIGN.md's colours and fonts, and each screen with its mock in place (a sandboxed frame, no scripts). */
308function design(input: DashboardInput): string {
309  const d = input.design
310  if (!d) return ''
311  const { colors, fonts, name } = d.tokens
312  const swatches = colors.length
313    ? `<div class="swatches">${colors.map(([n, v]) => `<span class="swatch"><span class="chip" style="background:${esc(v)}"></span><code>${esc(n)}</code> <span class="muted">${esc(v)}</span></span>`).join('')}</div>`
314    : '<p class="muted">DESIGN.md names no colours yet.</p>'
315  const type = fonts.length ? `<p><span class="label">Type</span>${fonts.map(f => esc(f)).join(' · ')}</p>` : ''
316  const cards = d.screens.map(sc => {
317    const rel = sc.mock ? `${d.dir}/${sc.mock}` : null
318    const url = rel ? fileUrl(input.root, rel) : null
319    const view = !url
320      ? '<p class="muted">No mock.</p>'
321      : /\.html?$/i.test(sc.mock!)
322        ? `<div class="frame"><iframe src="${esc(url)}" title="${esc(sc.name)}" loading="lazy" sandbox></iframe></div>`
323        : `<img class="mock" src="${esc(url)}" alt="${esc(sc.name)}" loading="lazy">`
324    return (
325      `<figure class="screen"><figcaption><strong>${esc(sc.name)}</strong>${sc.serves.length ? ` <span class="ids">${text(sc.serves.join(' '))}</span>` : ''}` +
326      `${sc.notes ? `<br><span class="muted">${esc(sc.notes)}</span>` : ''}</figcaption>${view}${url ? `<p class="open-file"><a href="${esc(url)}">Open the mock</a></p>` : ''}</figure>`
327    )
328  })
329  const state = `<p class="state"><span class="pill${d.approved ? ' drift-green' : ' wait'}">${d.approved ? '✓ approved by you' : '⏸ not approved yet'}</span>${name ? ` <span class="pill quiet">${esc(name)}</span>` : ''}</p>`
330  return section('design', 'Design', `${state}\n${swatches}\n${type}\n${d.screens.length ? `<div class="screens">${cards.join('')}</div>` : '<p class="muted">No screen changes in this feature.</p>'}`)
331}
332
333function phases(input: DashboardInput): string {
334  const { snap, autopilot, step } = input
335  const { phases: list, current } = taskPhases(snap.tasks)
336  if (!list.length) return section('phases', 'Phases', '<p class="muted">No tasks.md yet.</p>')
337  const named = snap.phase ? list.findIndex(p => p.title === snap.phase) : -1
338  const run = named >= 0 ? named : current
339  const running = autopilot.on && !autopilot.paused && ['implement', 'repair'].includes(step.phase)
340  const rows = list.map((p, i) => {
341    const pct = p.total ? Math.round((p.done / p.total) * 100) : 0
342    const state = i === run ? (running ? '▶ running' : '▶ next') : p.done === p.total ? '✓ done' : '· open'
343    const cls = i === run ? 'now' : p.done === p.total ? 'done' : ''
344    return (
345      `<tr class="${cls}"><td class="num">${phaseNumber(p.title, i)}</td><td><a href="#phase-${i}">${esc(phaseLabel(p.title))}</a></td>` +
346      `<td class="progress"><span class="bar" role="progressbar" aria-valuemin="0" aria-valuemax="${p.total}" aria-valuenow="${p.done}"><span style="width:${pct}%"></span></span> ${p.done}/${p.total}</td>` +
347      `<td class="nowrap">${state}</td></tr>`
348    )
349  })
350  return section('phases', 'Phases of tasks.md', `<div class="scroll"><table class="phases"><thead><tr><th>#</th><th>Phase</th><th>Progress</th><th>State</th></tr></thead><tbody>${rows.join('')}</tbody></table></div>`)
351}
352
353function matrix(input: DashboardInput): string {
354  const { snap, ledger, levels, root } = input
355  const spec = snap.spec
356  if (!spec) return section('matrix', 'Traceability', '<p class="muted">No spec yet.</p>')
357  const proof = { featureDir: snap.featureDir, tasks: snap.tasks, reqs: spec.reqs, realTests: snap.realTests ?? [] }
358  const row = (id: string, body: string, rung: string, cls: string) => {
359    const own = owners(id, proof, ledger)
360    const files = new Set<string>()
361    for (const t of own) for (const f of [...(ledger.tasks[t.id]?.touched ?? []), ...(ledger.tasks[t.id]?.linked ?? [])]) files.add(f)
362    for (const f of ledger.requirements[id]?.files ?? []) files.add(f)
363    for (const a of ledger.anchors) if (localId(a.id, snap.featureDir) === id) files.add(a.file)
364    const tasks = own.map(t => `<a class="${t.done ? 'done' : ''}" href="#task-${esc(t.id)}">${esc(t.id)}</a>${t.done ? ' ✓' : ''}`).join(', ')
365    const fileList = [...files].map(f => `${fileLink(root, f)}${isTestFile(f) ? ' <span class="tag">test</span>' : ''}`).join('<br>')
366    const v = ledger.verification[id]
367    const verified = v
368      ? `<span class="${v.status === 'passing' ? 'ok' : 'bad'}" title="${esc(v.tests.join('\n'))}">${v.status === 'passing' ? '✓ passing' : '✖ failing'}</span> · ${v.tests.length} test${v.tests.length === 1 ? '' : 's'} · ${esc(v.at.slice(0, 10))}`
369      : '<span class="muted">—</span>'
370    return `<tr id="req-${esc(id)}" class="${cls}"><td class="id"><a href="#req-${esc(id)}">${esc(id)}</a></td><td>${body}</td><td>${rung}</td><td class="ids">${tasks || '<span class="muted">none</span>'}</td><td class="files">${fileList || '<span class="muted">none</span>'}</td><td>${verified}</td></tr>`
371  }
372  const reqs = [...spec.reqs.filter(r => r.kind === 'FR'), ...spec.reqs.filter(r => r.kind === 'SC')]
373  const rows = reqs.map(r => {
374    const active = r.status === 'active'
375    const level = levels[r.id]
376    const rung = !active
377      ? `<span class="rung r-gone">${r.status === 'superseded' ? '↷ superseded' : '✕ retired'}</span>`
378      : level && (LADDER as readonly string[]).includes(level)
379        ? `<span class="rung r-${level}">${RUNG_GLYPH[level]} ${level}</span>`
380        : '<span class="muted">—</span>'
381    const flags = [r.needsClarification ? '<span class="tag warn">▲ needs clarification</span>' : '', r.supersededBy ? `<span class="tag">→ ${text(r.supersededBy)}</span>` : ''].filter(Boolean).join(' ')
382    const body = `${active ? text(r.text) : `<s>${text(r.text)}</s>`}${flags ? ` ${flags}` : ''}`
383    return row(r.id, body, rung, active ? '' : 'gone')
384  })
385  const scenarios = spec.stories.flatMap(s =>
386    s.scenarios.map(x => row(x.id, `<span class="muted">${esc(s.id)} ${esc(s.title)}:</span> ${text(x.text)}`, stateBadge(scenarioState(x.id, x.text, ledger)), 'scenario')),
387  )
388  const all = [...rows, ...scenarios]
389  const legend = `<p class="legend">${LADDER.map(r => `<span class="rung r-${r}">${RUNG_GLYPH[r]} ${r}</span>`).join(' ')}</p>`
390  return section(
391    'matrix',
392    'Traceability',
393    `${legend}\n<div class="scroll"><table class="matrix"><thead><tr><th>Id</th><th>Requirement</th><th>Proof</th><th>Tasks</th><th>Files</th><th>Verified</th></tr></thead><tbody>${all.join('\n') || '<tr><td colspan="6" class="muted">No requirements in spec.md.</td></tr>'}</tbody></table></div>`,
394  )
395}
396
397function taskRow(t: Task, input: DashboardInput): string {
398  const reqs = reqsOf(t, input.ledger)
399  const tags = [t.story ? `<span class="tag">${esc(t.story)}</span>` : '', t.parallel ? '<span class="tag" title="parallel">P</span>' : ''].filter(Boolean).join(' ')
400  return (
401    `<tr id="task-${esc(t.id)}" class="${t.done ? 'done' : ''}"><td class="check" title="${t.done ? 'done' : 'open'}">${t.done ? '☑' : '☐'}</td>` +
402    `<td class="id"><a href="#task-${esc(t.id)}">${esc(t.id)}</a></td><td>${tags ? `${tags} ` : ''}${text(t.text)}</td>` +
403    `<td class="files">${t.paths.map(p => fileLink(input.root, p)).join('<br>')}</td><td class="ids">${text(reqs.join(', '))}</td></tr>`
404  )
405}
406
407function tasks(input: DashboardInput): string {
408  const { phases: list } = taskPhases(input.snap.tasks)
409  if (!list.length) return section('tasks', 'Tasks', '<p class="muted">No tasks.md yet.</p>')
410  const body = list.map((p, i) => {
411    const own = input.snap.tasks.filter(t => (t.phase || 'Tasks') === p.title)
412    return `<h3 id="phase-${i}">${phaseNumber(p.title, i)} · ${esc(phaseLabel(p.title))} <span class="muted">${p.done}/${p.total}</span></h3>\n<div class="scroll"><table class="tasks"><tbody>${own.map(t => taskRow(t, input)).join('')}</tbody></table></div>`
413  })
414  return section('tasks', 'Tasks', body.join('\n'))
415}
416
417const STATE_BADGE: Record<ScenarioState, string> = {
418  accepted: '<span class="rung r-accepted">★ accepted</span>',
419  failing: '<span class="rung r-failing">✖ failing</span>',
420  stale: '<span class="rung r-stale">↻ re-accept</span>',
421  passing: '<span class="rung r-passing">● passing</span>',
422  untested: '<span class="muted">—</span>',
423}
424const stateBadge = (state: ScenarioState) => STATE_BADGE[state]
425
426/** Acceptance: each scenario as a person would play it, the driver's verdict and its evidence, and what is the person's. */
427function acceptance(input: DashboardInput): string {
428  const { snap, ledger, root } = input
429  const scenarios = scenariosOf(snap.spec)
430  if (!snap.ui || !scenarios.length) return ''
431  const counts = acceptanceCounts(snap, ledger)
432  const doc = snap.acceptanceDoc
433  const rows = scenarios.map(s => {
434    const state = scenarioState(s.id, s.text, ledger)
435    const a = ledger.acceptance?.[s.id]
436    const ev = doc?.evidence[s.id]
437    const shot = ev?.shot ? `<a href="${esc(fileUrl(root, ev.shot))}"><img class="shot" src="${esc(fileUrl(root, ev.shot))}" alt="${esc(s.id)}" loading="lazy"></a>` : ''
438    const flow = ev?.flow ? fileLink(root, ev.flow) : ''
439    const report = a ? `<span class="muted">${esc(a.file)} · ${esc(a.at.slice(0, 10))}</span>` : ''
440    return `<tr><td class="id">${esc(s.id)}</td><td>${text(s.text)}</td><td>${stateBadge(state)}</td><td>${[flow, report].filter(Boolean).join('<br>') || '<span class="muted">—</span>'}</td><td>${shot}</td></tr>`
441  })
442  const yours = doc?.yourPart.length ? `<h3>Your part</h3>\n${ul(doc.yourPart.map(t => text(t)))}` : ''
443  const summary = `<p class="state"><span class="pill${counts.accepted === counts.total ? ' drift-green' : ''}">★ ${counts.accepted}/${counts.total} accepted</span>${counts.failing ? ` <span class="pill drift-red">✖ ${counts.failing} failing</span>` : ''}${counts.stale ? ` <span class="pill wait">↻ ${counts.stale} to accept again</span>` : ''}${counts.yourPart ? ` <span class="pill quiet">${counts.yourPart} your part</span>` : ''}</p>`
444  return section(
445    'acceptance',
446    'Acceptance',
447    `${summary}\n<p class="muted">Only a driver's fresh JUnit report accepts a scenario.</p>\n<div class="scroll"><table class="acceptance"><thead><tr><th>Scenario</th><th>As the spec says</th><th>State</th><th>Flow and report</th><th>Evidence</th></tr></thead><tbody>${rows.join('\n')}</tbody></table></div>\n${yours}`,
448  )
449}
450
451const CHECK_BADGE: Record<string, string> = {
452  pass: '<span class="rung r-accepted">✓ pass</span>',
453  fail: '<span class="rung r-failing">✖ fail</span>',
454  'your part': '<span class="pill quiet">your part</span>',
455  'n/a': '<span class="muted">n/a</span>',
456}
457
458/** Release (0.7.0): the release check, what runs on the person's yes, what stays theirs, and what went out. */
459function release(input: DashboardInput): string {
460  const r = input.snap.release
461  if (!r) return ''
462  const checks = r.checks.map(c => `<tr><td>${esc(c.area)}</td><td>${text(c.check)}</td><td>${CHECK_BADGE[c.result] ?? ''}</td><td>${text(c.evidence)}</td></tr>`)
463  const ready = r.ready === null ? '' : r.ready ? '<span class="pill drift-green">ready</span>' : `<span class="pill drift-red">not ready</span>${r.readyNote ? ` ${text(r.readyNote)}` : ''}`
464  const yours = (when: 'before' | 'after') => r.yourPart.filter(y => y.when === when).map(y => `${y.done ? '☑' : '☐'} ${text(y.text)}`)
465  const releases = r.releases.map(x => `<tr><td>${esc(x.date)}</td><td>${esc(x.version)}</td><td>${esc(x.target)}</td><td>${x.ok ? '<span class="rung r-accepted">✓ out</span>' : '<span class="rung r-failing">✖ failed</span>'}</td><td>${text(x.where)}</td></tr>`)
466  return section(
467    'release',
468    'Release',
469    [
470      `<p class="state"><span class="pill">${esc(r.version ? `v${r.version.replace(/^v/i, '')}` : 'no version')}</span> ${esc(r.targets.join(', ') || 'no target')} ${ready}</p>`,
471      checks.length ? `<div class="scroll"><table><thead><tr><th>Area</th><th>Check</th><th>Result</th><th>Evidence</th></tr></thead><tbody>${checks.join('\n')}</tbody></table></div>` : '',
472      r.commands.length ? `<h3>Runs on your yes</h3>\n${ul(r.commands.map(c => `<code>${esc(c)}</code>`))}` : '',
473      yours('before').length ? `<h3>Your part before the release</h3>\n${ul(yours('before'))}` : '',
474      yours('after').length ? `<h3>Your part after the release</h3>\n${ul(yours('after'))}` : '',
475      releases.length ? `<h3>Releases</h3>\n<div class="scroll"><table><thead><tr><th>Date</th><th>Version</th><th>Target</th><th>Result</th><th>Where</th></tr></thead><tbody>${releases.join('\n')}</tbody></table></div>` : '',
476    ].filter(Boolean).join('\n'),
477  )
478}
479
480function drift(input: DashboardInput): string {
481  const { snap, ledger, report, root } = input
482  const d = DRIFT[report.level] ?? DRIFT.none
483  const parts: string[] = [`<p><span class="pill drift-${report.level}">${d.glyph} ${d.word}</span></p>`]
484  if (report.findings.length) {
485    parts.push(ul(report.findings.map(f => `<span class="${f.level === 'red' ? 'bad' : 'warn'}">${f.level === 'red' ? '✖' : '▲'} ${f.level}</span> ${text(f.text)}`), 'findings'))
486  } else parts.push('<p>● Nothing off the spec right now.</p>')
487  if (report.notes.length) parts.push('<h3>Notes</h3>', ul(report.notes.map(text)))
488  const open = openUnplanned(snap, ledger)
489  if (open.length) {
490    parts.push(
491      '<h3>Edits outside the plan</h3>',
492      `<div class="scroll"><table><thead><tr><th>File</th><th>Since</th><th>Task in focus</th></tr></thead><tbody>${open
493        .map(u => `<tr><td class="files">${fileLink(root, u.file)}</td><td class="nowrap">${time(u.at)}</td><td>${u.task ? text(u.task) : '—'}</td></tr>`)
494        .join('')}</tbody></table></div>`,
495    )
496  }
497  if (ledger.decisions.length) {
498    parts.push(
499      '<h3>Decisions</h3>',
500      ul(
501        ledger.decisions.map(dec => {
502          const answer = dec.answer ? `<span class="ok">✓</span> ${esc(dec.answer)}${dec.by === 'deputy' ? ` <span class="muted">(decided for you by the deputy${dec.why ? `: ${esc(dec.why)}` : ''})</span>` : ''}` : `<span class="warn">▲ open</span>${dec.options.length ? ` <span class="muted">(${esc(dec.options.join(' / '))})</span>` : ''}`
503          return `${text(dec.question)} → ${answer}${dec.blocks.length ? ` <span class="muted">blocks ${esc(dec.blocks.join(', '))}</span>` : ''}`
504        }),
505      ),
506    )
507  }
508  const s = ledger.semantic
509  const changed = ledger.intents.filter(i => i.status !== 'logged').slice().reverse()
510  if (s || changed.length) {
511    const status = { extends: '▲ beyond the spec', contradicts: '✖ contradicts the spec', resolved: '✓ in the spec now', logged: '· logged' } as const
512    const check = s ? `<p>Intent check <strong>${s.score}/100</strong> · ${esc(s.verdict)} · ${time(s.at)}</p>${s.reasons.length ? ul(s.reasons.map(text)) : ''}` : ''
513    const list = changed.length ? ul(changed.map(i => `<span class="${i.status === 'contradicts' ? 'bad' : i.status === 'resolved' ? 'ok' : 'warn'}">${status[i.status]}</span> "${text(i.text)}" <span class="muted">${time(i.at)}</span>`)) : ''
514    parts.push('<h3>Intent changes</h3>', check, list)
515  }
516  return section('drift', 'Drift', parts.join('\n'))
517}
518
519function runLog(input: DashboardInput): string {
520  if (!input.runLog.length) return section('runlog', 'Run log', '<p class="muted">No autopilot step yet.</p>')
521  const rows = [...input.runLog].sort((a, b) => (a.at < b.at ? 1 : a.at > b.at ? -1 : b.step - a.step))
522  const body = rows
523    .map(
524      r =>
525        // A pause or a stop is no step: it says why the run waited or ended.
526        `<tr${r.phase === 'pause' || r.phase === 'stop' ? ' class="halt"' : ''}><td class="nowrap">${time(r.at)}</td><td class="num">${r.step}</td><td>${r.phase === 'pause' ? '⏸ waits' : r.phase === 'stop' ? '■ stopped' : esc(r.phase)}</td><td class="ids">${r.task ? text(r.task) : '—'}</td>` +
527        `<td class="num">${duration(r.durationMs)}</td><td class="num">${thousands(r.tokens)}</td><td class="num" title="${esc(r.files.join('\n'))}">${r.files.length}</td><td>${text(r.outcome)}</td></tr>`,
528    )
529    .join('')
530  return section('runlog', 'Run log', `<div class="scroll"><table><thead><tr><th>Time</th><th>Step</th><th>Phase</th><th>Task(s)</th><th>Duration</th><th>Tokens</th><th>Files</th><th>Outcome</th></tr></thead><tbody>${body}</tbody></table></div>`)
531}
532
533function docs(input: DashboardInput): string {
534  if (!input.docs.length) return section('docs', 'Documents', '<p class="muted">No documents yet.</p>')
535  const body = input.docs.map(doc => {
536    const open = /(^|\/)spec\.md$/.test(doc.path) ? ' open' : ''
537    return (
538      `<details class="doc" data-key="${esc(doc.path)}"${open}><summary><strong>${esc(doc.title)}</strong> <code>${esc(doc.path)}</code></summary>` +
539      `<p class="open-file"><a href="${esc(fileUrl(input.root, doc.path))}">Open the file</a></p>` +
540      `<div class="md">${linkIds(md(doc.markdown, rebaser(input.root, doc.path)))}</div></details>`
541    )
542  })
543  return section('docs', 'Documents', body.join('\n'))
544}
545
546/** Reloads every `seconds`, keeping the scroll position and the open documents; waits while text is selected or the tab is hidden. */
547function refreshScript(seconds: number): string {
548  const ms = Math.max(1, Math.min(86400, Math.floor(seconds))) * 1000
549  return `<script>
550(function () {
551  var KEY = 'speckit-xref-dashboard';
552  function docs() { return Array.prototype.slice.call(document.querySelectorAll('details[data-key]')); }
553  try { if ('scrollRestoration' in history) history.scrollRestoration = 'manual'; } catch (e) {}
554  try {
555    var saved = JSON.parse(sessionStorage.getItem(KEY) || 'null');
556    if (saved && saved.open) {
557      docs().forEach(function (d) { d.open = saved.open.indexOf(d.getAttribute('data-key')) !== -1; });
558      window.scrollTo(0, saved.y || 0);
559    }
560  } catch (e) {}
561  function tick() {
562    var selected = false;
563    try { selected = !!window.getSelection && String(window.getSelection()) !== ''; } catch (e) {}
564    if (document.hidden || selected) { setTimeout(tick, 2000); return; }
565    try {
566      sessionStorage.setItem(KEY, JSON.stringify({ y: window.scrollY, open: docs().filter(function (d) { return d.open; }).map(function (d) { return d.getAttribute('data-key'); }) }));
567    } catch (e) {}
568    location.reload();
569  }
570  setTimeout(tick, ${ms});
571})();
572</script>`
573}
574
575const CSS = `
576:root{color-scheme:light dark;--bg:#fbfaf7;--fg:#1d1d1f;--muted:#6b6b70;--line:#e3e1db;--card:#fff;--accent:#2f5bd3;--ok:#1f7a3f;--warn:#8a6100;--bad:#b3261e;--ok-bg:#e6f4ea;--warn-bg:#fff4d6;--bad-bg:#fde8e6;--hl:#fff8e1;
577--r-specified:#6b6b70;--r-planned:#2f5bd3;--r-implemented:#7a4cc2;--r-tested:#0e7c86;--r-passing:#1f7a3f}
578@media (prefers-color-scheme:dark){:root{--bg:#141416;--fg:#ececef;--muted:#9a9aa2;--line:#2e2e33;--card:#1c1c20;--accent:#8fb0ff;--ok:#6fd08f;--warn:#e8c25a;--bad:#ff8a80;--ok-bg:#16301f;--warn-bg:#33290f;--bad-bg:#3a1714;--hl:#2a2614;
579--r-specified:#a0a0a8;--r-planned:#8fb0ff;--r-implemented:#c4a2ff;--r-tested:#5fd4dc;--r-passing:#6fd08f}}
580*{box-sizing:border-box}
581body{margin:0 auto;max-width:76rem;padding:0 16px 2rem;background:var(--bg);color:var(--fg);font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;overflow-wrap:break-word}
582section,[id^="req-"],[id^="task-"]{scroll-margin-top:3rem}h1{font-size:1.6rem;margin:.2rem 0}h2{font-size:1.2rem;margin:2rem 0 .6rem;padding-bottom:.3rem;border-bottom:1px solid var(--line)}h3{font-size:1rem;margin:1.2rem 0 .4rem}
583a{color:var(--accent)}a.done{color:var(--ok)}code,pre,.strip{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:.9em}
584code{background:var(--card);border:1px solid var(--line);border-radius:4px;padding:0 .25em}pre{overflow-x:auto;background:var(--card);border:1px solid var(--line);border-radius:6px;padding:.75em}pre code{border:0;padding:0}
585header{padding:1.2rem 0 .6rem}.kicker{margin:0;color:var(--muted);font-size:.8rem;text-transform:uppercase;letter-spacing:.06em}.meta{margin:.2rem 0;color:var(--muted)}
586.state{display:flex;flex-wrap:wrap;gap:.4rem;margin:.5rem 0}.pill{display:inline-block;border:1px solid var(--line);border-radius:999px;padding:.1em .7em;background:var(--card);font-size:.9em}
587.pill.quiet{color:var(--muted)}.pill.wait{background:var(--warn-bg);color:var(--warn);border-color:currentColor}
588.drift-green{background:var(--ok-bg);color:var(--ok);border-color:currentColor}.drift-yellow{background:var(--warn-bg);color:var(--warn);border-color:currentColor}.drift-red{background:var(--bad-bg);color:var(--bad);border-color:currentColor}.drift-none{color:var(--muted)}
589nav{position:sticky;top:0;z-index:1;background:var(--bg);border-bottom:1px solid var(--line);display:flex;flex-wrap:wrap;gap:.2rem 1rem;padding:.45rem 0;font-size:.9em}
590.muted{color:var(--muted)}.ok{color:var(--ok)}.warn{color:var(--warn)}.bad{color:var(--bad)}.nowrap{white-space:nowrap}.num{text-align:right;white-space:nowrap;font-variant-numeric:tabular-nums}
591.words{white-space:pre-wrap;margin:0;padding:.6em 1em;border-left:3px solid var(--accent);background:var(--card);font-size:1.05em}
592.strip{display:flex;flex-wrap:wrap;gap:.35rem}.st{border-radius:4px;padding:0 .35em;border:1px solid var(--line)}.st-done{color:var(--ok)}.st-unreviewed{color:var(--warn)}.st-now{background:var(--accent);color:var(--bg);border-color:var(--accent)}.st-todo{color:var(--muted)}
593.label{font-weight:600;margin-right:.4em}.waiting{border:2px solid var(--warn);background:var(--warn-bg);border-radius:8px;padding:.6em 1em;margin:.8em 0}.waiting p{margin:.3em 0 0}
594.scroll{overflow-x:auto;max-width:100%}table{border-collapse:collapse;width:100%;font-size:.92em}th,td{text-align:left;vertical-align:top;padding:.35em .5em;border-bottom:1px solid var(--line)}th{color:var(--muted);font-weight:600}
595td.files,td.ids,td.id{overflow-wrap:anywhere}td.id{white-space:nowrap}.matrix td:nth-child(2){min-width:16em}.tasks td:nth-child(3){min-width:14em}
596tr.now td{background:var(--hl)}tr.halt td{color:var(--warn);font-style:italic}tr.done td{color:var(--muted)}tr.gone td{color:var(--muted)}tr:target td{background:var(--warn-bg)}
597.bar{display:inline-block;width:7em;height:.55em;background:var(--line);border-radius:999px;overflow:hidden;vertical-align:middle}.bar>span{display:block;height:100%;background:var(--accent)}tr.done .bar>span{background:var(--ok)}
598.rung{display:inline-block;white-space:nowrap;border:1px solid currentColor;border-radius:999px;padding:0 .5em;font-size:.85em}
599.r-accepted{color:var(--ok);background:var(--ok-bg);font-weight:600}.r-failing{color:var(--bad);background:var(--bad-bg)}.r-stale{color:var(--warn)}img.shot{max-width:120px;max-height:240px;border:1px solid var(--line);border-radius:6px}
600.r-specified{color:var(--r-specified)}.r-planned{color:var(--r-planned)}.r-implemented{color:var(--r-implemented)}.r-tested{color:var(--r-tested)}.r-passing{color:var(--r-passing);background:var(--ok-bg)}.r-gone{color:var(--muted)}
601.tag{display:inline-block;font-size:.78em;border:1px solid var(--line);border-radius:4px;padding:0 .3em;color:var(--muted)}.tag.warn{color:var(--warn);border-color:currentColor}
602.legend{display:flex;flex-wrap:wrap;gap:.35rem}.findings{padding-left:1.2em}
603details.doc{border:1px solid var(--line);border-radius:8px;background:var(--card);margin:.6rem 0}details.doc>summary{cursor:pointer;padding:.6em .9em}details.doc>.md,details.doc>.open-file{padding:0 .9em}.open-file{margin:0}
604.md h1{font-size:1.3rem}.md h2{font-size:1.1rem;border:0;margin-top:1.2rem}.md blockquote{border-left:3px solid var(--line);margin:.5em 0;padding:0 1em;color:var(--muted)}.md li.task{list-style:none}.md li.task input{margin:0 .3em 0 -1.2em}
605.swatches{display:flex;flex-wrap:wrap;gap:.5rem 1rem;margin:.4rem 0}.swatch{display:inline-flex;align-items:center;gap:.35em}.chip{display:inline-block;width:1.4em;height:1.4em;border-radius:4px;border:1px solid var(--line)}
606.screens{display:flex;flex-wrap:wrap;gap:1rem}.screen{margin:0;width:211px}.screen figcaption{font-size:.9em;margin-bottom:.3rem;min-height:2.6em}
607.frame{width:197px;height:424px;overflow:hidden;border:1px solid var(--line);border-radius:10px;background:#fff}.frame iframe{width:390px;height:844px;border:0;transform:scale(.5);transform-origin:0 0}img.mock{max-width:100%;border:1px solid var(--line);border-radius:10px}
608footer{margin-top:2.5rem;padding-top:.8rem;border-top:1px solid var(--line);color:var(--muted);font-size:.9em}
609`
610
611const NAV = [
612  ['goal', 'Goal'],
613  ['workflow', 'Workflow'],
614  ['design', 'Design'],
615  ['acceptance', 'Acceptance'],
616  ['release', 'Release'],
617  ['phases', 'Phases'],
618  ['matrix', 'Traceability'],
619  ['tasks', 'Tasks'],
620  ['drift', 'Drift'],
621  ['runlog', 'Run log'],
622  ['docs', 'Documents'],
623]
624
625const FOOTER = 'This page is local and is regenerated after every step. It holds your own words: keep it out of commits and do not share it.'
626
627/** The whole dashboard as one HTML document: deterministic for the same input, nothing loaded from outside. */
628export function renderDashboard(input: DashboardInput): string {
629  const refresh = Number(input.refreshSeconds)
630  const auto = Number.isFinite(refresh) && refresh > 0
631  return [
632    '<!doctype html>',
633    '<html lang="en">',
634    '<head>',
635    '<meta charset="utf-8">',
636    '<meta name="viewport" content="width=device-width, initial-scale=1">',
637    `<title>${esc(input.snap.spec?.title ?? 'Spec X-Ref')} · Spec X-Ref</title>`,
638    `<style>${CSS}</style>`,
639    '</head>',
640    '<body>',
641    header(input),
642    `<nav>${NAV.filter(([id]) => (id !== 'design' || input.design) && (id !== 'acceptance' || (input.snap.ui && scenariosOf(input.snap.spec).length)) && (id !== 'release' || input.snap.release)).map(([id, label]) => `<a href="#${id}">${label}</a>`).join('')}</nav>`,
643    '<main>',
644    goal(input),
645    workflow(input),
646    design(input),
647    acceptance(input),
648    release(input),
649    phases(input),
650    matrix(input),
651    tasks(input),
652    drift(input),
653    runLog(input),
654    docs(input),
655    '</main>',
656    `<footer><p>${FOOTER}</p>${auto ? `<p>Refreshes every ${Math.floor(refresh)} s; it waits while you select text or the tab is hidden.</p>` : ''}</footer>`,
657    auto ? refreshScript(refresh) : '',
658    '</body>',
659    '</html>',
660    '',
661  ].join('\n')
662}
663
hooks/accept.ts 162 lines
1// Acceptance (0.6.0): after verify, a feature people use is played through as a person would, scenario by scenario,
2// by a driver that leaves evidence (Playwright for the web, Maestro for mobile). Only a fresh JUnit report of that
3// driver accepts a scenario; acceptance.md lists what only a person can check. Pure: register.tsx reads the files.
4
5import type { AcceptanceNote, Ledger, Snapshot, Spec } from '../types'
6import type { JunitCase } from './proof'
7import { fingerprint } from './rules'
8
9export const ACCEPT_DIR = 'e2e/acceptance'
10export const ACCEPT_REPORTS = 'reports'
11/** The driver's reports the step writes: `reports/acceptance-web.xml`, `reports/acceptance-mobile.xml`. */
12export const ACCEPT_REPORT = /^acceptance[\w.-]*\.xml$/
13export const acceptanceDoc = (featureDir: string) => `${featureDir}/acceptance.md`
14
15/** Files the acceptance step writes about the app, not into it: they do not change what was verified. */
16export const ACCEPTANCE_ARTIFACT = /(^|\/)(e2e\/acceptance\/|reports\/acceptance[^/]*$|specs\/[^/]+\/acceptance\.md$|\.specify\/memory\/runbook\.md$)/
17
18/** What the user test (0.8.0) writes about the app, not into it: its log and its screenshots. */
19export const TRY_ARTIFACT = /(^|\/)specs\/[^/]+\/(try\.md$|try\/)/
20/** The design pass's record and screenshots (0.9.0): a review that finds nothing changes nothing verified. */
21export const POLISH_ARTIFACT = /(^|\/)specs\/[^/]+\/(polish\.md$|polish\/)/
22
23const SCENARIO = /\bUS\d+-AS\d+\b/g
24const clip = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
25
26/** The platforms plan.md's Target Platform names: what the app is played on. */
27export function platformsFromPlan(planMd: string | null): { web: boolean; ios: boolean; android: boolean } {
28  const line = /^\*\*Target Platform\*\*:\s*(.+)$/im.exec(planMd ?? '')?.[1] ?? ''
29  const type = /^\*\*Project Type\*\*:\s*(.+)$/im.exec(planMd ?? '')?.[1] ?? ''
30  const text = `${line} ${type}`
31  return {
32    web: /\b(web|browsers?|spa|website)\b/i.test(text),
33    ios: /\b(iOS|iPhone|iPad)\b/i.test(text),
34    android: /\bAndroid\b/i.test(text),
35  }
36}
37
38/** Every acceptance scenario of the spec, in order. */
39export const scenariosOf = (spec: Spec | null) => (spec?.stories ?? []).flatMap(s => s.scenarios)
40
41/**
42 * The scenarios a driver's report accepts or fails: a testcase counts for every scenario id in its name or class.
43 * A scenario with any failed case fails; one with only skipped cases says nothing. Each result keeps the scenario's
44 * fingerprint, so a changed scenario has to be accepted again.
45 */
46export function acceptanceFrom(cases: JunitCase[], spec: Spec | null, at: string, file: string): Ledger['acceptance'] {
47  const texts = new Map(scenariosOf(spec).map(s => [s.id, s.text]))
48  const out: Ledger['acceptance'] = {}
49  for (const c of cases) {
50    if (c.status === 'skipped') continue
51    for (const id of new Set(`${c.name} ${c.classname}`.match(SCENARIO) ?? [])) {
52      const text = texts.get(id)
53      if (text === undefined) continue
54      const ok = c.status === 'passed' && (out[id]?.ok ?? true)
55      out[id] = { ok, fingerprint: fingerprint(text), at, file }
56    }
57  }
58  return out
59}
60
61/** A flow that taps by screen coordinates proves nothing about its scenario (0.7.1): a Maestro `point:`, a Playwright `mouse.click(`. */
62export const COORDINATE_TAP = /^\s*-?\s*point:|\bmouse\.click\s*\(/m
63export const tapsByCoordinates = (flow: string) => COORDINATE_TAP.test(flow)
64
65/** The sub-flows a Maestro flow runs (`runFlow: common/start.yaml`, or `runFlow:` with `file:`), as paths relative to the project (0.8.0, Fund 39). */
66export function flowIncludes(flow: string, flowPath: string): string[] {
67  const dir = flowPath.includes('/') ? flowPath.slice(0, flowPath.lastIndexOf('/')) : ''
68  const out: string[] = []
69  for (const m of flow.matchAll(/runFlow:\s*(?:\n\s+(?:when:[\s\S]*?\n\s+)?file:\s*)?["']?([\w./-]+\.ya?ml)["']?/g)) {
70    const parts = [...(dir ? dir.split('/') : []), ...m[1]!.split('/')]
71    const norm: string[] = []
72    for (const p of parts) {
73      if (p === '..') norm.pop()
74      else if (p && p !== '.') norm.push(p)
75    }
76    out.push(norm.join('/'))
77  }
78  return [...new Set(out)]
79}
80
81/** Where a scenario stands for the person: accepted by a driver, failing there, passing unit tests only, or untested. */
82export type ScenarioState = 'accepted' | 'failing' | 'stale' | 'passing' | 'untested'
83export function scenarioState(id: string, text: string, ledger: Ledger): ScenarioState {
84  const a = ledger.acceptance?.[id]
85  if (a) {
86    if (a.fingerprint !== fingerprint(text)) return 'stale'
87    return a.ok ? 'accepted' : 'failing'
88  }
89  return ledger.verification[id]?.status === 'passing' ? 'passing' : 'untested'
90}
91
92/** acceptance.md: the evidence per scenario (a screenshot, a flow) and the list of what only a person can check. */
93export function parseAcceptanceDoc(markdown: string): AcceptanceNote {
94  const evidence: Record<string, { shot: string | null; flow: string | null }> = {}
95  const yourPart: string[] = []
96  let inYourPart = false
97  for (const line of markdown.split('\n')) {
98    const h = /^##\s+(.+)$/.exec(line)
99    if (h) {
100      inYourPart = /your part|dein teil|by hand|manual/i.test(h[1]!)
101      continue
102    }
103    if (inYourPart) {
104      const bullet = /^\s*[-*]\s+(.+)$/.exec(line)
105      if (bullet) yourPart.push(clip(bullet[1]!.replace(/\*\*/g, '').trim(), 240))
106      continue
107    }
108    if (!/^\s*\|/.test(line)) continue
109    const id = /\bUS\d+-AS\d+\b/.exec(line)?.[0]
110    if (!id) continue
111    const paths = [...line.matchAll(/`?([\w./-]+\.(png|jpe?g|webp|yaml|yml|spec\.ts|test\.ts))`?/gi)].map(m => m[1]!)
112    evidence[id] = { shot: paths.find(p => /\.(png|jpe?g|webp)$/i.test(p)) ?? null, flow: paths.find(p => /\.(ya?ml|ts)$/i.test(p)) ?? null }
113  }
114  return { evidence, yourPart }
115}
116
117/** The pane's and the dashboard's count: accepted, failing, the rest, and what is the person's. */
118export function acceptanceCounts(snap: Pick<Snapshot, 'spec' | 'acceptanceDoc'>, ledger: Ledger): { total: number; accepted: number; failing: number; stale: number; yourPart: number } {
119  const states = scenariosOf(snap.spec).map(s => scenarioState(s.id, s.text, ledger))
120  return {
121    total: states.length,
122    accepted: states.filter(s => s === 'accepted').length,
123    failing: states.filter(s => s === 'failing').length,
124    stale: states.filter(s => s === 'stale').length,
125    yourPart: snap.acceptanceDoc?.yourPart.length ?? 0,
126  }
127}
128
129/** What the acceptance step hands Claude: the scenarios, the driver this machine has, the time box, the rules. */
130export function acceptPrompt(snap: Snapshot): string {
131  const dir = snap.featureDir ?? 'specs/<feature>'
132  const p = snap.platforms ?? { web: false, ios: false, android: false }
133  const web = p.web && !!snap.tools.npx
134  const maestro = (p.ios || p.android) && !!snap.tools.maestro
135  const scenarios = scenariosOf(snap.spec)
136  // The web driver plays only where it can without downloading anything: a browser on this machine, the runner in the project.
137  const webLine = !web
138    ? null
139    : !snap.tools.chrome
140      ? 'Web: no Google Chrome is installed here, and this step never downloads a browser: the web scenarios go under Your part, with a note that Playwright needs a browser.'
141      : !snap.playwright
142        ? `Web: Playwright is not set up in this project yet, so play nothing on the web in this step. Append one task under '## Phase N: Acceptance setup' in ${dir}/tasks.md: add @playwright/test as a devDependency, a playwright.config.ts whose \`use\` has \`channel: 'chrome'\` (the installed Google Chrome; no browser download), and an npm script test:acceptance that writes ${ACCEPT_REPORTS}/acceptance-web.xml. The autopilot builds it, and the next acceptance run plays the scenarios.`
143        : `Web first, with Playwright and the installed Google Chrome (\`channel: 'chrome'\`; never download a browser): one test file per scenario in ${ACCEPT_DIR}/<id>.spec.ts whose test title starts with the scenario id; run them with PLAYWRIGHT_JUNIT_OUTPUT_NAME=${ACCEPT_REPORTS}/acceptance-web.xml npx playwright test ${ACCEPT_DIR} --reporter=junit.`
144  const drivers = [
145    webLine,
146    maestro
147      ? `Mobile with Maestro: one flow per scenario in ${ACCEPT_DIR}/<id>.yaml with \`name: "<id> …"\`; run them with maestro test --format junit --output ${ACCEPT_REPORTS}/acceptance-mobile.xml ${ACCEPT_DIR}. Play on what the emulator or simulator already has: a development build of the app if one is installed, else Expo Go (opened on the app's exp:// link). Building a development build (npx expo run:android, run:ios) downloads native dependencies: that is no part of this step, but a task under '## Phase N: Acceptance setup' when Expo Go is not there either. Maestro cannot stub network data as Playwright does: play now what holds without live data, and for the rest append a task under '## Phase N: Acceptance setup' for a fixture mode (an environment flag that makes the app's service adapters return the fixtures the web tests use). Never leave out the mobile platform as a whole while Maestro and a device are there.`
148      : null,
149  ].filter((d): d is string => !!d)
150  return [
151    `Accept ${dir} as a person would use it, with the speckit-xref:accept skill: start the app and play each acceptance scenario of the spec through with a driver that leaves a JUnit report.`,
152    `Scenarios: ${scenarios.map(s => `${s.id} "${clip(s.text, 120)}"`).join('; ') || '(the spec names none: take the quickstart rows)'}.`,
153    ...(drivers.length
154      ? drivers
155      : ['No driver is available on this machine for these platforms: run nothing; list every scenario under Your part with the steps a person takes to check it.']),
156    'Time box: about 20 minutes for bringing the app up and getting the flows to run. Then stop: keep what passed; a flow that still fails because of the flow itself goes under Your part with its manual steps. Start servers and simulators in the background and stop the ones you started at the end.',
157    "Select by label, text or testID, never by screen coordinates: a tap on a point is no evidence. An element with nothing to select it by gets a task under '## Phase N: Acceptance setup' (a testID or an accessibility label), and its scenario waits for it.",
158    `Do not change the app's code in this step: each scenario that fails because of the app becomes a task under '## Phase N: Acceptance fixes' in ${dir}/tasks.md (the next free T### id, the files in backticks, the scenario id), and the autopilot builds it.`,
159    `Write ${acceptanceDoc(dir)}: a table (Scenario | Driver | Flow | Result | Evidence, a screenshot path) and a '## Your part' list of what only a person can check (a real device, real users, a paid service), each with its steps.`,
160  ].join('\n')
161}
162
hooks/orchestrate.ts 153 lines
1// Orchestration (0.8.0): the mod decides each step, its model and its brief; the heavy steps run in subagents with a
2// fresh context. The main session relays: it calls the Agent tool with the mod's agent type, and the mod's spawn hook
3// sets the model, the brief and the foreground run. The main context then grows by reports, not by the phase's work.
4// Pure: register.tsx registers the agent types, rewrites the spawn and guards the main loop's writes.
5
6import type { Autopilot, Snapshot, Task } from '../types'
7import { LEAN_TESTS, phaseBrief, runbookNote } from './brief'
8import { gateWords } from './gitci'
9export { LEAN_TESTS }
10
11export const IMPLEMENTER = 'implementer'
12export const TESTER = 'tester'
13export const DESIGNER = 'designer'
14export type Models = 'auto' | 'opus' | 'sonnet' | 'haiku'
15export const MODELS: Models[] = ['auto', 'sonnet', 'opus', 'haiku']
16export type Delegate = { agent: typeof IMPLEMENTER | typeof TESTER | typeof DESIGNER; model: string; description: string; brief: string }
17
18
19/** A task's files are all documentation or configuration: work a small model does as well. */
20const MECHANICAL = /(\.(md|json|ya?ml|toml|ini|txt|env\.example)$|(^|\/)\.[\w.-]+$|(^|\/)(package|tsconfig|app|eas|babel\.config|metro\.config|eslint\.config)\b)/i
21
22/**
23 * The model for a delegated step. A fixed `models` option wins; `auto`: Sonnet builds and repairs, Opus takes over a
24 * repair that failed once already, Haiku does a phase whose files are all docs or configuration; the design lead's
25 * direction and reviews are Opus's (0.9.0), and a design pass is never Haiku's.
26 */
27export function routeModel(kind: 'implement' | 'repair' | 'try' | 'design', models: Models, opts: { repairs?: number; tasks?: Task[]; designPass?: boolean } = {}): string {
28  if (models !== 'auto') return models
29  if (kind === 'design') return 'opus'
30  if (kind === 'repair') return (opts.repairs ?? 0) >= 2 ? 'opus' : 'sonnet'
31  if (kind === 'implement') {
32    const paths = (opts.tasks ?? []).flatMap(t => t.paths)
33    if (!opts.designPass && paths.length && paths.every(p => MECHANICAL.test(p))) return 'haiku'
34  }
35  return 'sonnet'
36}
37
38/** The agent type's system prompt: one phase of tasks, the project's rules, and the record the mod keeps. */
39export const IMPLEMENTER_PROMPT = [
40  'You implement one phase of a GitHub Spec Kit feature, delegated by the speckit-xref autopilot. Your prompt is the phase brief: its tasks, what they must prove, the test command, the runbook.',
41  'Read the spec.md and plan.md of the feature and the files the tasks name. Work through the tasks in order. Before each task call mcp__speckit-xref__focus with its id; a file no task names gets mcp__speckit-xref__link to the task it serves.',
42  'Mark code that implements a requirement with a comment `@spec <feature>/FR-###`; a test, where the project writes them, carries the anchor of what it proves and the id in its name.',
43  'Follow the phase brief on tests: it says whether this project writes tests at all (0.11.0).',
44  'A task that asks for a check by hand (the app on a simulator, an emulator or in a browser, screenshots against the design, a measured time) is done only when you did it now, on this code: results written down earlier (quickstart.md, notes, an older run) are no evidence. Look for the tools before you give up (the simulator and browser tools, maestro, adb, also outside PATH); when none here can do it, leave the task open, say so in your report and ask the person with mcp__speckit-xref__ask.',
45  'Check a task off ([X] in tasks.md) only when its code is in place and the check the brief names passes (the test command, or the type check where the project runs without tests). Do not edit spec.md or plan.md. Decide what the brief leaves open and note it in your report; a product decision only the person can make goes to mcp__speckit-xref__ask.',
46  'When you get past a problem of the environment (a port, a flag, a permission name), add one line to .specify/memory/runbook.md.',
47  'End with a report of at most eight lines: tasks done, tasks left and why, the test run (passed/failed, counts), files changed, decisions you took.',
48].join('\n')
49
50/** The tester's system prompt: use the app as a person would and report what breaks. */
51export const TESTER_PROMPT = [
52  'You test an app the way a person uses it, delegated by the speckit-xref autopilot: not by reading code, by using the running app. Your prompt names what to try and with which tool.',
53  'Follow each user story\'s goal in the app, then the paths people take by accident: a permission denied, no network, back and forth, empty or very long input, a second try. Look for crashes, dead ends, endless spinners, wrong numbers or dates, text cut off or unreadable, a screen that contradicts the spec.',
54  'Take a screenshot of every finding and of each story\'s end state. Do not change the app\'s code.',
55  'Rate each finding: HIGH (a story cannot be completed, data is wrong or lost, a crash), MEDIUM (a person would stumble or misread), LOW (polish).',
56  'End with a report of at most ten lines: per story passed or the findings, each with its rating and screenshot path.',
57].join('\n')
58
59/** What the main session is told for a delegated step: relay it, do not do it. */
60export function relayPrompt(d: Delegate): string {
61  return [
62    `Delegate this step; do not do its work yourself: call the Agent tool once with subagent_type "speckit-xref:${d.agent}", description "${d.description}", and the prompt "Carry out your brief." The autopilot gives the agent its brief and its model (${d.model}); it runs in the foreground, so wait for its report.`,
63    d.agent === TESTER
64      ? 'When it reports, write its findings as the brief says (try.md and tasks for HIGH and MEDIUM findings) if it did not, then end your turn with the report in at most five lines.'
65      : 'When it reports, end your turn with its report in at most five lines. Writing code in this turn is refused: the work is the agent\'s.',
66  ].join('\n')
67}
68
69/** The implementer's brief for one phase: its tasks, what to prove, how to test, what the environment taught. */
70export function implementBrief(snap: Snapshot, phase: string, lastTest: Autopilot['lastTest']): string {
71  const tasks = snap.tasks.filter(t => t.phase === phase && !t.done)
72  const runbook = runbookNote(snap.runbook)
73  return [
74    `Feature: ${snap.featureDir}. Phase: ${phase}.`,
75    'Tasks (tasks.md):',
76    ...tasks.map(t => `- ${t.id} ${t.text}`),
77    ...phaseBrief(snap, phase, lastTest),
78    snap.testCommand ? (snap.gate === 'check' ? `Type check: \`${snap.testCommand}\` (this project runs without a test suite).` : `Test command: \`${snap.testCommand}\`.`) : 'No test or check command is known: say how you checked the phase.',
79    ...(runbook ? [runbook] : []),
80  ].join('\n')
81}
82
83/** The implementer's brief for a failing suite. */
84export function repairBrief(snap: Snapshot, output: string): string {
85  return [
86    `Feature: ${snap.featureDir}. ${gateWords(snap).fails}. Run \`${snap.testCommand}\`, find the cause and fix the code${snap.gate === 'check' ? '' : ' (not the tests, unless a test contradicts the spec)'}. Check off no new tasks.`,
87    `Last output:\n${output.slice(-1500)}`,
88    ...(runbookNote(snap.runbook) ? [runbookNote(snap.runbook)!] : []),
89  ].join('\n')
90}
91
92/** Where a user test runs here: the iOS Simulator tool of the desktop app, a browser, or a headless browser script. */
93export function tryTools(snap: Snapshot): string {
94  const p = snap.platforms ?? { web: false, ios: false, android: false }
95  const lines: string[] = []
96  if (p.ios) {
97    lines.push('iOS: if the mcp__Claude_Code_iOS_Simulator__control tool is available, start the app (Expo: `npx expo start`, then open its exp:// URL in Expo Go with open_url, or a development build if one is installed) and use it with screenshot, tap, swipe and text.')
98    // A console session has no simulator tool: simctl shows the app, and only Maestro can tap (0.9.0).
99    // The samples are already in the app at the direction: light and dark are switched, not assumed (0.9.0).
100    lines.push('Light and dark: `xcrun simctl ui <device> appearance light` or `dark` switches the simulator.')
101    lines.push('Without that tool, on a Mac with Xcode: boot a simulator (`xcrun simctl boot <device>`), open the app\'s URL with `xcrun simctl openurl <device> <url>`, take shots with `xcrun simctl io <device> screenshot <file>` and read them with the Read tool; taps and typing need Maestro (a short flow with `maestro test`) where it is installed. Without Maestro you can only look: say which screens you saw but did not use.')
102  }
103  if (p.web || !lines.length) lines.push('Web: if browser tools are available (mcp__Claude_Browser__* or mcp__claude-in-chrome__*), use them on the app\'s dev server; else write a short Playwright script with `channel: \'chrome\'` (the installed Chrome; never download a browser) that clicks through like a person and saves screenshots.')
104  lines.push('No tool here for a platform: that platform is the person\'s part, with the steps to try.')
105  return lines.join('\n')
106}
107
108/**
109 * A new user first, then a returning one (0.8.1): the first-run screens and the permission dialogs only show on an
110 * empty app, and an older build's data only breaks the app of a returning user (both found in the first live test).
111 */
112export const FRESH_START =
113  "Start as a new user: the app's stored data empty and its permissions not yet asked, so the first-run screens and the permission dialogs appear. Reset the permissions before the app starts, never while it runs (the system ends it): iOS `xcrun simctl privacy <device> reset all <bundle id>` (Expo Go: `host.exp.Exponent`), Android `adb shell pm revoke <package> <permission>`. Data an older build left (Expo Go keeps a project's data between builds) is cleared after you keep a copy. Then try once more as a returning user, with the data the first pass left; data of an older version that breaks the app is a finding."
114
115/** The tester's brief: one story right after it is built, or the whole app at the end. */
116export function tryBrief(snap: Snapshot, scope: { story: string | null }): string {
117  const dir = snap.featureDir ?? 'specs/<feature>'
118  const stories = (snap.spec?.stories ?? []).filter(s => !scope.story || scope.story.includes(s.id) || scope.story.includes(`User Story ${s.id.slice(2)}`))
119  return [
120    scope.story
121      ? `Try the story just built, as a person would: ${scope.story}. Time box: about 10 minutes.`
122      : `Try the whole app of ${dir} as a person would, story after story, before it counts as done. Time box: about 20 minutes.`,
123    'Stories:',
124    ...stories.map(s => `- ${s.id} ${s.title}${s.scenarios.length ? `: ${s.scenarios.map(x => x.text).join(' / ')}` : ''}`),
125    tryTools(snap),
126    FRESH_START,
127    `Write ${dir}/try.md: the date, the platform and tool, per story what you did and saw, each finding with its rating and screenshot (save them under ${dir}/try/). Each HIGH or MEDIUM finding becomes a task under '## Phase N: User test fixes' in ${dir}/tasks.md (the next free T### id, the steps to reproduce, the files it likely touches in backticks, the story id); LOW ones stay in try.md.`,
128    'Start servers, simulators and browsers in the background and stop the ones you started at the end.',
129  ].join('\n')
130}
131
132/** Spec Kit's own files: the session still keeps them while a subagent writes the code. */
133const RECORD = /^(\.\/)?(specs|\.specify)\//
134
135/**
136 * Whether a call of the main session writes code (0.8.0): the file tools on anything but the feature's record, and
137 * a shell command that redirects into a file, tees, or edits in place. Reading, testing and git pass.
138 */
139export function writesCode(tool: string, input: Record<string, unknown>, root = ''): boolean {
140  const rel = (p: string) => (root && p.startsWith(root + '/') ? p.slice(root.length + 1) : p)
141  if (tool === 'Write' || tool === 'Edit' || tool === 'NotebookEdit') {
142    const file = rel(String(input.file_path ?? input.notebook_path ?? ''))
143    return !!file && !RECORD.test(file)
144  }
145  if (tool !== 'Bash') return false
146  // A heredoc's body is the program or the text, not the shell's redirects (0.12.0, found live: a Python script that
147  // wrote only spec.md and tasks.md was refused for the `>` in its code). Its first line keeps its own redirect.
148  const command = String(input.command ?? '').replace(/(<<-?\s*(['"]?)(\w+)\2[^\n]*)\n[\s\S]*?\n\s*\3[ \t]*(?=\n|$)/g, '$1')
149  const targets = [...command.matchAll(/(?:^|[^\d&<>])>>?\s*([^\s;&|<>]+)/g)].map(m => m[1]!).filter(t => !/^(\/dev\/null|&\d)$/.test(t))
150  if (targets.some(t => !RECORD.test(rel(t)))) return true
151  return /\btee\b(?!\s+(-a\s+)?(\.\/)?(specs|\.specify)\/)|\b(?:sed|perl)\s+(?:-[a-zA-Z]*\s+)*-i\b/.test(command)
152}
153
hooks/polish.ts 89 lines
1// The design pass (0.9.0): a done feature that works and was tried is lifted to the look and feel of its platform's best
2// apps, on the person's word. A design lead sets the direction and builds two or three sample screens, the person
3// approves it at the samples, the implementer builds the rest, and the design lead reviews fresh screenshots of every
4// screen (three rounds at most). Pure: workflow.ts hands the steps over, register.tsx reads polish.md.
5
6import type { PolishNote, Snapshot, Task } from '../types'
7import { tryTools } from './orchestrate'
8import { fingerprint } from './rules'
9
10export const polishDoc = (featureDir: string) => `${featureDir}/polish.md`
11/** The phases a design pass writes. Not "Polish": Spec Kit's own tasks end with "Polish & Cross-Cutting Concerns". */
12export const DESIGN_PHASE = /^Phase\s+\d+:\s*Design (pass|review)\b/i
13export const isDesignPhase = (phase: string | null | undefined) => !!phase && DESIGN_PHASE.test(phase)
14/** Review rounds of a design pass before it counts as done. */
15export const MAX_DESIGN_REVIEWS = 3
16
17/** The review rounds so far: one `Design review N` phase per round that found something. */
18export const designRounds = (tasks: Task[]) => new Set(tasks.filter(t => /^Phase\s+\d+:\s*Design review\b/i.test(t.phase)).map(t => t.phase)).size
19
20/** polish.md as the mod reads it: the direction's first line, and the fingerprint the person approves (the rounds aside). */
21export function parsePolish(md: string): PolishNote {
22  const head = md.split(/^##\s+Rounds\b/m)[0]!
23  const lines = head.split('\n')
24  const at = lines.findIndex(l => /^##\s+Direction\b/i.test(l))
25  const direction = at >= 0 ? (lines.slice(at + 1).find(l => l.trim() && !l.startsWith('#'))?.trim() ?? null) : null
26  return { direction, fingerprint: fingerprint(head.trim()), rounds: (md.match(/^###\s+Round\s+\d+/gm) ?? []).length }
27}
28
29/** What the best apps of each platform look and feel like today, by their conventions rather than by version. */
30export const PLATFORM_LOOK = [
31  'iOS: content runs edge to edge, and navigation and controls sit on translucent material that floats above it (tab bar, toolbars, floating buttons), not on opaque bars; large titles that collapse as the content scrolls; sheets with detents for secondary tasks instead of full screens; system symbols (SF Symbols) with or instead of text; Dynamic Type text styles, no fixed font sizes; semantic system colours and materials that follow light and dark mode; haptics when something is committed (saved, liked, done); springy, interruptible motion; native controls (segmented control, menu, picker, switch) over home-made ones; swipe actions and context menus where a list invites them; empty, loading and error states designed, not left to defaults.',
32  'Android: Material 3 in its expressive form: dynamic colour, large shapes, motion that carries meaning, edge to edge, predictive back.',
33  'Web: the same direction in CSS: backdrop-filter materials, the system font stack, prefers-color-scheme and prefers-reduced-motion, a visible focus ring.',
34  'Always: one clear primary action per screen, touch targets of at least 44 pt, contrast AA, labels for VoiceOver and TalkBack, Reduce Motion and Reduce Transparency honoured.',
35].join('\n')
36
37/** How to build it: the platform's own parts, the skills that know them, and what stays out of the step. */
38export const DESIGN_TOOLS =
39  "Build with the platform's own components first: for Expo the expo-ui, expo-native-ui, expo-router and expo-animation skills where they are installed (native controls, materials and blur, native stack and tabs, motion); for Flutter Cupertino and Material 3; for SwiftUI the system materials and controls. Adding a package of the app's framework is fine (with the project's package manager, e.g. `npx expo install`); a change that needs a new native build (a development build, pods) becomes a task of its own with the reason, never part of this step."
40
41/** The design lead's system prompt: the look rises, what the app does stays. */
42export const DESIGNER_PROMPT = [
43  'You are the design lead for an app that works and that people have tried: you lift its look and feel to the level of the best apps on its platform, without changing what it does. The speckit-xref autopilot delegates to you; your prompt says whether you set the direction or review a built design pass.',
44  `What "best" means here:\n${PLATFORM_LOOK}`,
45  DESIGN_TOOLS,
46  'What the app does stays: the same screens, flows and the texts that carry meaning, and every test green (run the test command after each change). A test that checks only the old look may follow the new one.',
47  'Only what you saw on this build counts: a "before" shot may come from the user test (specs/<feature>/try/), every "after" shot is taken now.',
48  'Before each task call mcp__speckit-xref__focus with its id; a file no task names gets mcp__speckit-xref__link to the task it serves.',
49  'End with a report of at most eight lines.',
50].join('\n\n')
51
52/** The design lead's first step: the direction, the tasks, two or three sample screens. The rest waits for the person. */
53export function directionBrief(snap: Snapshot): string {
54  const dir = snap.featureDir ?? 'specs/<feature>'
55  const screens = (snap.design?.screens ?? []).map(s => s.name)
56  return [
57    `Set the design direction for ${dir}: the app works and was tried; now it should look and feel like the best apps on its platform. Time box: about 30 minutes.`,
58    ...(screens.length ? [`Screens: ${screens.join(', ')}.`] : []),
59    tryTools(snap),
60    `1. Use the app and take a "before" shot of every screen, light and dark, under ${dir}/polish/before/ (a shot of this build from ${dir}/try/ will do).`,
61    `2. Write ${dir}/polish.md: \`## Direction\` (its first line says the feel in one sentence; then the materials, type, colour, symbols, motion and haptics, and what stays), \`## Screens\` (per screen: what changes and with which native components), \`## Samples\` (filled in at step 4), \`## Rounds\` (empty; the reviews add to it). Bring DESIGN.md to the new direction, in its own format.`,
62    `3. Before any code, append \`## Phase N: Design pass\` to ${dir}/tasks.md (the next phase number, the next free T### ids): first one task for the shared parts (theme, type, components, navigation), then one task per screen, each with its files in backticks and the story it serves.`,
63    `4. Build the shared task and two or three screens that show the direction best, as samples, each under its task; check those tasks off once the tests pass. Take an "after" shot of each sample under ${dir}/polish/after/ and list before → after per sample under \`## Samples\`.`,
64    '5. Leave the other screens\' tasks open: the person approves the direction at the samples first.',
65    'Start servers, simulators and browsers in the background and stop the ones you started at the end.',
66  ].join('\n')
67}
68
69/** The design lead's review of a built pass: fresh shots of every screen against the direction. */
70export function critiqueBrief(snap: Snapshot, round: number): string {
71  const dir = snap.featureDir ?? 'specs/<feature>'
72  return [
73    `Review round ${round} of ${MAX_DESIGN_REVIEWS}: is the built design pass of ${dir} what polish.md promises, on this build? Time box: about 20 minutes. Change no code in this step.`,
74    tryTools(snap),
75    `Take a fresh shot of every screen, light and dark, under ${dir}/polish/round-${round}/, and compare each with polish.md (direction and screen plan), DESIGN.md and the platform's conventions.`,
76    'Rate each finding: HIGH (a screen still looks as before, or the new look breaks something: text cut off, contrast below AA, a control hidden under material, a flow that no longer works), MEDIUM (a deviation from the direction a person notices: spacing, alignment, an inconsistent component, a missing state), LOW (taste).',
77    `Each HIGH or MEDIUM finding becomes a task under \`## Phase N: Design review ${round}\` in ${dir}/tasks.md (the next phase number and free T### ids, the screen, what to change, its files in backticks). Add \`### Round ${round}\` under \`## Rounds\` in polish.md: the date, per screen OK or its findings, the shot paths; LOW findings stay there.`,
78    'Without a way to tap (no simulator tool, no Maestro) say which screens you only looked at and did not use. No HIGH or MEDIUM finding: say so; the design pass is then done.',
79    'Start servers, simulators and browsers in the background and stop the ones you started at the end.',
80  ].join('\n')
81}
82
83/** What an implement step of a design pass adds to its brief. */
84export const DESIGN_PASS_RULES = [
85  'This phase is a design pass: change how the app looks and feels, not what it does. Follow polish.md (direction, screen plan, samples) and DESIGN.md, and reuse the shared parts the samples introduced.',
86  DESIGN_TOOLS,
87  'Keep every test green; a test that checks only the old look may follow the new one. Take an "after" shot of each screen you finish, under the feature\'s polish/after/.',
88].join('\n')
89
hooks/gitci.ts 108 lines
1// Tests, CI/CD and git (0.11.0): what a project builds besides the app, and where its work lands. A proof of concept or
2// an MVP needs a type check and a person trying the app, not a test suite or a pipeline the agents spend their time on;
3// and a feature lands on the branch the person works on unless they ask for a branch or a pull request. Pure.
4
5import type { Ledger, Snapshot } from '../types'
6
7export type TestMode = 'off' | 'run' | 'lean'
8export type GitMode = 'current' | 'branch' | 'pr'
9export const TEST_MODES: TestMode[] = ['off', 'run', 'lean']
10export const GIT_MODES: GitMode[] = ['current', 'branch', 'pr']
11
12/** CI/CD pipelines: written only when the person switches option ci on. */
13export const CI_PATH = /(^|\/)(\.github\/workflows\/|\.gitlab-ci\.ya?ml$|\.circleci\/|bitbucket-pipelines\.ya?ml$|azure-pipelines\.ya?ml$|\.eas\/workflows\/|Jenkinsfile$|\.buildkite\/|\.travis\.ya?ml$|codemagic\.ya?ml$|fastlane\/)/
14/** The same paths inside a shell command, after a space, a quote or a slash. */
15const CI_IN_COMMAND = new RegExp(CI_PATH.source.replace('(^|\\/)', '(^|[\\s/\'"=])').replace(/\$/g, '(?![\\w.-])'))
16const WRITES = /(>|\btee\b|\bcp\b|\bmv\b|\bmkdir\b|\btouch\b|\bln\b|\binstall\b|\b(?:sed|perl)\s+(?:-[a-zA-Z]*\s+)*-i\b)/
17
18/** Whether a call writes a CI/CD pipeline: a file tool on one, or a shell command that names one and writes. */
19export function touchesCi(tool: string, input: Record<string, unknown>, root = ''): boolean {
20  const rel = (p: string) => (root && p.startsWith(root + '/') ? p.slice(root.length + 1) : p)
21  if (tool === 'Write' || tool === 'Edit' || tool === 'NotebookEdit') return CI_PATH.test(rel(String(input.file_path ?? input.notebook_path ?? '')))
22  if (tool !== 'Bash') return false
23  const command = String(input.command ?? '')
24  return CI_IN_COMMAND.test(command) && WRITES.test(command)
25}
26
27/** A git command that makes or changes branches: the run stays on the person's branch unless option git says otherwise. */
28const BRANCHING = /\bgit\s+(?:-C\s+\S+\s+)?(switch\b|checkout\s+(?:-[bB]|--orphan)\b|branch\s+(?!-)[^\s;&|]+|worktree\s+add\b)/
29export const branches = (tool: string, input: Record<string, unknown>) => tool === 'Bash' && BRANCHING.test(String(input.command ?? ''))
30
31/** A feature's branch: its folder's name, as Spec Kit numbers it. */
32export const branchName = (featureDir: string) => featureDir.slice(featureDir.lastIndexOf('/') + 1)
33
34/** What the steps that plan or build are told about tests. */
35export function testsNote(mode: TestMode | undefined): string | null {
36  if (mode === 'off') return 'Write no test tasks and no tests: this project runs without a test suite (option tests: off). The type check and the user test are its checks.'
37  if (mode === 'run') return 'Write no new tests or test tasks (option tests: run): the existing suite is the gate; keep it green.'
38  return null
39}
40
41/** What the steps are told about CI/CD. */
42export const ciNote = (on: boolean | undefined) => (on === false ? 'Plan and write no CI/CD pipeline (no workflow files): option ci is off, and writing one is refused.' : null)
43
44/** What the autopilot's gate is called: the project's tests, or its type check where it runs without tests. */
45export function gateWords(snap: Pick<Snapshot, 'gate'>): { what: string; fails: string; still: string; passes: string; label: string } {
46  return snap.gate === 'check'
47    ? { what: 'the type check', fails: 'The type check fails', still: 'The type check still fails', passes: 'the type check passes', label: 'Check' }
48    : { what: 'the tests', fails: 'The tests fail', still: 'The tests still fail', passes: 'the tests pass', label: 'Tests' }
49}
50
51/** What the project shows of its language: enough to name its type check. */
52export type Project = {
53  packageJson: string | null
54  typescript: boolean
55  pubspec: string | null
56  cargo: boolean
57  goMod: boolean
58  swiftPackage: boolean
59  mypy: boolean
60  /** The package manager's run command: `npm run`, `pnpm`, `yarn`, `bun run`. */
61  run: string
62}
63
64/** The type check of the project's language, or null: a script of its own first, else the language's usual one. */
65export function checkCommandFor(p: Project): string | null {
66  if (p.packageJson) {
67    let scripts: Record<string, unknown> = {}
68    try {
69      scripts = (JSON.parse(p.packageJson) as { scripts?: Record<string, unknown> }).scripts ?? {}
70    } catch {
71      scripts = {}
72    }
73    const own = ['typecheck', 'type-check', 'check-types', 'types', 'tsc'].find(s => typeof scripts[s] === 'string')
74    if (own) return `${p.run} ${own}`
75  }
76  if (p.typescript) return 'npx --no-install tsc --noEmit'
77  if (p.pubspec) return /^\s*flutter\s*:/m.test(p.pubspec) ? 'flutter analyze --no-fatal-infos' : 'dart analyze'
78  if (p.cargo) return 'cargo check'
79  if (p.goMod) return 'go vet ./...'
80  if (p.swiftPackage) return 'swift build'
81  if (p.mypy) return 'mypy .'
82  return null
83}
84
85/** The pull request's text: what the feature is, what it covers, how it was checked. */
86export function prBody(snap: Snapshot, ledger: Ledger): string {
87  const spec = snap.spec
88  const done = snap.tasks.filter(t => t.done).length
89  const reqs = (spec?.reqs ?? []).filter(r => r.kind === 'FR' && r.status === 'active').slice(0, 20)
90  const checked = [
91    ledger.checkpoints.verify ? 'verified against the spec' : null,
92    ledger.checkpoints.try ? 'tried as a person would (user test)' : null,
93    snap.gate === 'check' ? 'type check green' : 'tests green',
94  ].filter(Boolean)
95  return [
96    `## ${spec?.title ?? branchName(snap.featureDir ?? '')}`,
97    '',
98    spec?.input ? `> ${spec.input.replace(/\s+/g, ' ').slice(0, 600)}` : '',
99    '',
100    `Spec: \`${snap.featureDir}/spec.md\` · Tasks: ${done}/${snap.tasks.length} · ${checked.join(' · ')}`,
101    '',
102    ...(reqs.length ? ['### Requirements', ...reqs.map(r => `- **${r.id}** ${r.text.slice(0, 200)}`), ''] : []),
103    'Built with GitHub Spec Kit and the speckit-xref autopilot. Merging is yours.',
104  ]
105    .filter((l, i, all) => l !== '' || all[i - 1] !== '')
106    .join('\n')
107}
108
hooks/deputy.ts 271 lines
1// The deputy (0.10.0): the autopilot thinks between its steps the way the person would. After each heavy step it
2// reviews the work like a lead who reads the report and the diff (go on, send it back with a list, or ask the person),
3// it answers the questions Claude asks from the spec, the briefs and the person's own earlier words, and it says what
4// it decided and why. The workflow stays the frame; the deputy never approves a gate. Pure: register.tsx calls it.
5
6import type { Snapshot, Task } from '../types'
7
8/** The person's profile, learned from their own words only: local, like their prompts, never committed. */
9export const PROFILE = '.specify/xref/local/person.md'
10/** The steps whose work the deputy reviews: the ones that build, repair, try or restyle the app. */
11export const REVIEWED = new Set(['implement', 'repair', 'rework', 'try', 'polish', 'bug'])
12/** Send-backs of one step before it becomes the person's call. */
13export const MAX_REWORKS = 2
14
15export type Verdict = {
16  verdict: 'go' | 'rework' | 'ask' | 'redirect'
17  /** The next step the deputy writes itself when the plan no longer fits (redirect, 0.12.0). */
18  prompt: string
19  /** For the next step: what to watch, in a line or two; empty when there is nothing to say. */
20  note: string
21  /** What the step has to fix before it counts (rework). */
22  rework: string[]
23  /** The person's question and the deputy's recommendation (ask). */
24  question: string
25  recommendation: string
26  /** What the person said that is worth keeping about how they work (from their own words only). */
27  profile: string[]
28}
29
30export type Answer = { decided: true; answer: string; why: string } | { decided: false; question: string; recommendation: string }
31
32/** What only the person decides, whatever the deputy thinks: checked in code, not left to the prompt. */
33const PERSON_ONLY = /\b(passwords?|credentials?|api[- ]keys?|secrets?|payments?|purchases?|billing|subscriptions?|wipe|force[- ]push|publish(ing)?|releases?|deploy(ing|ment)?|approv\w*|real (users?|devices?|data)|measur\w*|by hand|manually|passw(ort|örter)|zugangsdaten|api-schlüssel|zahlung\w*|bezahl\w*|kauf\w*|abonnement\w*|lösch\w*|veröffentlich\w*|freigabe\w*|freigeben|messung\w*|messen|von hand|manuell\w*|echte[nrs]? (nutzer\w*|geräte?\w*|daten)|smoke[- ]?tests?|simulator|emulator|on (a|the) (real )?device|check(ed)? by hand)\b|\b(delete|drop)\b/i
34
35/** A question the deputy may not answer for the person, whatever the model says. */
36export const personOnly = (question: string) => PERSON_ONLY.test(question)
37
38/** The deputy's system prompt: the person's stand-in, with the person's limits. */
39export const DEPUTY_PROMPT = [
40  'You stand in for the person who owns this product while an autopilot builds it with GitHub Spec Kit. You are their deputy between the steps: you read what each step did the way they would, critically and with their goals in mind, and you decide what they would decide. You are thorough, not quick: read the report, the diff and the test run before you judge.',
41  'Your sources, in this order: the person\'s own words and earlier decisions, their profile, the spec and its requirements, the constitution, the plan. Where they settle a question, decide it; where they do not, decide what serves the spec and record it, unless the question is one only the person can answer.',
42  'Only the person decides: approvals of the spec, the plan, a design direction or a release; anything that costs money, needs credentials or an account, deletes or publishes something, or cannot be undone; a check by hand or a measurement on real users, data or devices; a matter of taste where the person never gave a direction; a conflict between their words and the spec.',
43  'Answer with one JSON object and nothing else.',
44].join('\n\n')
45
46/** What a step review sees: what was asked, what came back, what changed, whether it holds. */
47export type ReviewInput = {
48  feature: string
49  phase: string
50  why: string
51  /** The step's report: the subagent's whole report where it ran in one, else the session's answer. */
52  report: string
53  /** Every file changed since the step started, from git: the diff may be cut, this list is whole. */
54  files: string[]
55  diff: string
56  tests: { ok: boolean; output: string } | null
57  checked: string[]
58  open: string[]
59  requirements: string[]
60  profile: string | null
61  /** The person's own recent words and decisions, newest last. */
62  words: string[]
63  decisions: string[]
64  principles: string[]
65  /** The step finished a phase or the feature: look ahead too. */
66  boundary: boolean
67  reworks: number
68  /** Option tests (0.11.0): without a suite a missing test is no reason to send a step back. */
69  testMode?: 'off' | 'run' | 'lean'
70}
71
72const section = (title: string, lines: string[] | string | null) => {
73  const body = Array.isArray(lines) ? lines.filter(Boolean).join('\n') : (lines ?? '').trim()
74  return body ? `## ${title}\n${body}` : ''
75}
76
77/** The review request: the evidence, then the questions a lead asks, then the answer's shape. */
78export function reviewRequest(i: ReviewInput): string {
79  return [
80    `Feature ${i.feature}. The step just done: ${i.phase} (${i.why}).${i.reworks ? ` It was sent back ${i.reworks} time${i.reworks === 1 ? '' : 's'} already.` : ''}`,
81    section('Report of the step', i.report.slice(-8000)),
82    section('Files changed since the step started (from git; the diff below may be cut, this list is whole)', i.files.slice(0, 80)),
83    section('Diff of the step', i.diff),
84    section('Test run', i.tests ? `${i.tests.ok ? 'passed' : 'FAILED'}\n${i.tests.output.slice(-1500)}` : 'not run'),
85    section('Tasks checked in this step', i.checked.join(', ') || 'none'),
86    section('Tasks still open', i.open.slice(0, 12)),
87    section('Requirements these tasks serve', i.requirements.slice(0, 20)),
88    section("The person's profile", i.profile),
89    section("The person's own words, newest last", i.words.slice(-8)),
90    section('Decisions so far', i.decisions.slice(-8)),
91    section('Constitution', i.principles.slice(0, 12)),
92    [
93      '## Judge it as the person would',
94      '- Does the work do what the tasks and requirements say, or does the report claim more than the diff and the test run show?',
95      '- Evidence: is anything checked off on results written earlier, on a test that was weakened or skipped, or on "should work"? A check by hand or a measurement counts only when done now; one no tool here can do is the person\'s part and stays open, which is no reason to send the step back.',
96      '- Scope: work no task asked for, a decision taken that the spec or the person left open, a deviation from the plan or a contract, a TODO or a stub left behind.',
97      '- Anything the report says is left open or unsure: is that fine to carry on with, or does it block?',
98      '- A file the report names that is in the file list but not in the diff was cut from the diff for length: that is no reason to send the step back. Send a step back only for what the evidence shows is missing or wrong.',
99      ...(i.testMode === 'off' ? ['- This project runs without a test suite on purpose (option tests: off): the type check is its gate. A missing test is no reason to send a step back; a test written anyway is work nobody asked for.'] : i.testMode === 'run' ? ['- This project adds no new tests (option tests: run): the existing suite is the gate. A missing new test is no reason to send a step back.'] : []),
100      ...(i.boundary ? ['- This step ended a phase or the feature: are we still building the right thing? Does anything the step or a user test found change what should come next, or need the person?'] : []),
101      '',
102      'verdict "go": the step holds; "note" is what the next step should keep in mind (empty if nothing). verdict "rework": it does not hold; "rework" lists what to fix, concretely, each with the file or task. verdict "ask": only the person can settle what blocks; "question" asks it in one or two sentences, "recommendation" says what you would choose and why. verdict "redirect": the step holds, but what it found means the plan no longer fits (a task belongs to a later feature, an order that cannot work, a prerequisite missing): "prompt" is the next step written by you for Claude, concrete and complete, and the plan goes on from what it leaves; mark a task put off as deferred in tasks.md with [~] and the reason.',
103      '"profile": at most three short lines about how the person works or what they want, only where their own words above show it and the profile does not say it yet; else [].',
104      'Answer: {"verdict": "go|rework|ask|redirect", "note": "", "rework": [], "question": "", "recommendation": "", "prompt": "", "profile": []}',
105    ].join('\n'),
106  ]
107    .filter(Boolean)
108    .join('\n\n')
109}
110
111/** What an answer to Claude's question sees. */
112export type AnswerInput = {
113  feature: string
114  question: string
115  /** The answer it ends, or the agent's context for the ask. */
116  context: string
117  options: string[]
118  spec: string[]
119  profile: string | null
120  words: string[]
121  decisions: string[]
122  principles: string[]
123  brief: string | null
124}
125
126export function answerRequest(i: AnswerInput): string {
127  return [
128    `Feature ${i.feature}. Claude asks the person, mid-run: "${i.question}"${i.options.length ? ` Options: ${i.options.join(' | ')}.` : ''}`,
129    section('What Claude said before the question', i.context.slice(-3000)),
130    section('Spec (requirements and assumptions)', i.spec.slice(0, 40)),
131    section('Product brief', i.brief),
132    section("The person's profile", i.profile),
133    section("The person's own words, newest last", i.words.slice(-8)),
134    section('Decisions so far', i.decisions.slice(-8)),
135    section('Constitution', i.principles.slice(0, 12)),
136    [
137      '## Answer it as the person would',
138      'Decide it yourself where the sources settle it or a sound default serves the spec; say why in one sentence, naming the source. Leave it to the person only where it is theirs alone (see your instructions), and then say what you would recommend.',
139      'A question that only asks whether to go on is answered "yes, go on".',
140      'Answer: {"decided": true, "answer": "", "why": ""} or {"decided": false, "question": "", "recommendation": ""}',
141    ].join('\n'),
142  ]
143    .filter(Boolean)
144    .join('\n\n')
145}
146
147/** The first JSON object in a reply, or null. */
148function jsonOf(text: string): Record<string, unknown> | null {
149  const start = text.indexOf('{')
150  const end = text.lastIndexOf('}')
151  if (start < 0 || end <= start) return null
152  try {
153    const value = JSON.parse(text.slice(start, end + 1))
154    return value && typeof value === 'object' ? (value as Record<string, unknown>) : null
155  } catch {
156    return null
157  }
158}
159const strOf = (v: unknown, max = 600) => (typeof v === 'string' ? v.trim().slice(0, max) : '')
160const listOf = (v: unknown, n: number, max = 300) => (Array.isArray(v) ? v.map(x => strOf(x, max)).filter(Boolean).slice(0, n) : [])
161
162/** The review's verdict, or null when the reply is none (the autopilot then goes on as without a deputy). */
163export function parseVerdict(text: string): Verdict | null {
164  const j = jsonOf(text)
165  if (!j || !['go', 'rework', 'ask', 'redirect'].includes(String(j.verdict))) return null
166  const v: Verdict = {
167    verdict: j.verdict as Verdict['verdict'],
168    prompt: strOf(j.prompt, 3000),
169    note: strOf(j.note, 400),
170    rework: listOf(j.rework, 8),
171    question: strOf(j.question, 400),
172    recommendation: strOf(j.recommendation, 400),
173    profile: listOf(j.profile, 3, 160),
174  }
175  // A send-back without a list, or a question without one, is no verdict to act on.
176  if (v.verdict === 'rework' && !v.rework.length) return { ...v, verdict: 'go' }
177  if (v.verdict === 'ask' && !v.question) return { ...v, verdict: 'go' }
178  if (v.verdict === 'redirect' && !v.prompt) return { ...v, verdict: 'go' }
179  return v
180}
181
182/** What the deputy reads after the person spoke in the middle of the run (0.12.0). */
183export type SteerInput = {
184  feature: string
185  /** The person's words, and Claude's answer to them. */
186  words: string
187  answer: string
188  /** The step the plan would hand over next: its kind and why, and whether only the person can take it. */
189  planned: string
190  open: string[]
191  deferred: string[]
192  profile: string | null
193  decisions: string[]
194}
195
196export type Steer = { action: 'plan' | 'custom' | 'pause'; note: string; prompt: string; question: string }
197
198/** The steering request: the person's words first, the plan second. */
199export function steerRequest(i: SteerInput): string {
200  return [
201    `Feature ${i.feature}. The person spoke to Claude in the middle of the autopilot's run.`,
202    section("The person's words", i.words.slice(-3000)),
203    section("Claude's answer to them", i.answer.slice(-4000)),
204    section("The autopilot's planned next step", i.planned),
205    section('Tasks still open', i.open.slice(0, 15)),
206    section('Tasks the person put off', i.deferred.slice(0, 15)),
207    section("The person's profile", i.profile),
208    section('Decisions so far', i.decisions.slice(-8)),
209    [
210      "## Decide what comes next, as the person's deputy",
211      'The person\'s words come before the plan. The plan is a means: follow it where the person\'s words leave it standing, change it where they changed course.',
212      '- "plan": the words leave the plan as it is (a remark, a question Claude answered, something Claude already did in its answer). The planned step follows; "note" is what it should keep in mind.',
213      '- "custom": the person changed course and it is not done yet (close or skip something, put tasks off, reorder, a different next feature, do something first). Write the next step yourself in "prompt", concrete and complete, for Claude to carry out what the person asked. Tasks the person put off are marked deferred in tasks.md with [~] and the reason. The plan goes on from the state it leaves.',
214      '- "pause": the person wants to take over, stop, or decide something first; "question" says what the run waits for.',
215      'A step you write never approves the spec, the plan, a design or a release, never deploys or pushes, and never undoes the person\'s work.',
216      'Answer: {"action": "plan|custom|pause", "note": "", "prompt": "", "question": ""}',
217    ].join('\n'),
218  ]
219    .filter(Boolean)
220    .join('\n\n')
221}
222
223/** The steering answer, or null when the reply is none (the run then goes on as without a deputy). */
224export function parseSteer(text: string): Steer | null {
225  const j = jsonOf(text)
226  if (!j || !['plan', 'custom', 'pause'].includes(String(j.action))) return null
227  const s: Steer = { action: j.action as Steer['action'], note: strOf(j.note, 400), prompt: strOf(j.prompt, 3000), question: strOf(j.question, 400) }
228  if (s.action === 'custom' && !s.prompt) return { ...s, action: 'plan' }
229  if (s.action === 'pause' && !s.question) return { ...s, question: 'the person wants to decide how to go on' }
230  return s
231}
232
233/** The step a person's change of course becomes: the deputy's prompt, with the person's words beside it. */
234export const steerLine = (words: string) => `The person said, mid-run: "${words.replace(/\s+/g, ' ').slice(0, 300)}". Their words come before the plan.`
235
236/** The answer to a question, or null when the reply is none. What only the person decides stays theirs, in code. */
237export function parseAnswer(text: string, question: string): Answer | null {
238  const j = jsonOf(text)
239  if (!j || typeof j.decided !== 'boolean') return null
240  if (j.decided && strOf(j.answer) && !personOnly(question)) return { decided: true, answer: strOf(j.answer, 500), why: strOf(j.why, 300) }
241  return { decided: false, question: strOf(j.question, 400) || question, recommendation: strOf(j.recommendation, 400) }
242}
243
244/** The send-back's brief: the step again, with the deputy's list first. */
245export function reworkBrief(feature: string, phase: string, items: string[], report: string): string {
246  return [
247    `Feature: ${feature}. The person's deputy reviewed the last ${phase} step and sends it back. Fix these, then run the tests:`,
248    ...items.map(x => `- ${x}`),
249    'Uncheck a task in tasks.md whose work is not done after all; check nothing new off. A point you cannot fix here (no tool, a decision only the person can make) stays open: say so in your report.',
250    `The step's report was:\n${report.slice(-1500)}`,
251  ].join('\n')
252}
253
254/** The note the next step carries: the deputy's word on the last one. */
255export const noteLine = (note: string) => `The person's deputy on the last step: ${note}`
256
257/** What the deputy decided, as the next step reads it. */
258export const answerLine = (question: string, answer: string, why: string) => `The person's deputy answered your question "${question.slice(0, 200)}": ${answer}${why ? ` (${why})` : ''}. Go on with it.`
259
260/** The requirements a step's tasks serve, as the review reads them. */
261export function requirementsOf(snap: Snapshot, tasks: Task[]): string[] {
262  const ids = new Set(tasks.flatMap(t => t.reqs))
263  return (snap.spec?.reqs ?? []).filter(r => ids.has(r.id)).map(r => `${r.id}: ${r.text}`)
264}
265
266/** Lines of the profile to add: new ones only. */
267export function profileAdditions(current: string | null, lines: string[]): string[] {
268  const have = (current ?? '').toLowerCase()
269  return lines.filter(l => l && !have.includes(l.toLowerCase()))
270}
271
hooks/prd.ts 146 lines
1// The PRD entrance (0.5.3): a product requirements document the person wrote first. It is imported once to
2// .specify/memory/prd.md, reviewed and cut into features (prd-review.md, roadmap.md), and each feature's spec carries
3// the PRD's own ids, so the trace runs PRD → spec → tasks → code. Pure: register.tsx reads and writes the files.
4
5import type { PrdReview, RoadmapItem, Snapshot, Spec } from '../types'
6import { fingerprint } from './rules'
7
8export const PRD = '.specify/memory/prd.md'
9export const PRD_REVIEW = '.specify/memory/prd-review.md'
10export const ROADMAP = '.specify/memory/roadmap.md'
11
12/** A file at the root that is a PRD by its name: `PRD_Show.md`, `product-requirements.md`. Markdown only. */
13export const PRD_NAME = /(^|[^a-z])prd([^a-z]|$)|product[-_ ]?requirements/i
14const PRD_EXT = /\.(md|markdown)$/i
15
16/** The PRD among the root's files: a Markdown file named so, never a dotfile. */
17export function prdSourceOf(names: string[]): string | null {
18  return names.find(n => PRD_NAME.test(n) && PRD_EXT.test(n) && !n.startsWith('.')) ?? null
19}
20
21const clip = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
22const plain = (text: string) => text.replace(/\*\*/g, '').replace(/`/g, '').trim()
23
24/** `US01–US06, F01, AC01-AC11` → every id, ranges expanded with the width they are written in. */
25export function expandIds(scope: string): string[] {
26  const out: string[] = []
27  for (const part of scope.split(/[,;]|\s+und\s+|\s+and\s+/)) {
28    const range = /([A-Z]+)-?(\d+)\s*[–—-]\s*(?:([A-Z]+)-?)?(\d+)/.exec(part)
29    if (range && (!range[3] || range[3] === range[1])) {
30      const [, prefix, from, , to] = range
31      const width = from!.length
32      for (let n = Number(from); n <= Number(to) && n - Number(from) < 200; n++) out.push(`${prefix}${String(n).padStart(width, '0')}`)
33      continue
34    }
35    for (const m of part.matchAll(/\b([A-Z]{1,4}\d{1,3}[a-z]?)\b/g)) out.push(m[1]!)
36  }
37  return [...new Set(out)]
38}
39
40/** roadmap.md: one `##` section per feature, in build order, with its phase, scope, PRD sections, gate and spec text. */
41export function parseRoadmap(markdown: string): RoadmapItem[] {
42  const items: RoadmapItem[] = []
43  let item: RoadmapItem | null = null
44  for (const line of markdown.split('\n')) {
45    const heading = /^##\s+(?:\d+[.)]?\s*)?(.+)$/.exec(line)
46    if (heading) {
47      item = { title: plain(heading[1]!), phase: null, scope: [], sections: [], gate: null, spec: '' }
48      items.push(item)
49      continue
50    }
51    const field = item ? /^\*\*(Phase|Scope|Sections|Gate before|Gate|Spec)\*\*\s*:\s*(.*)$/i.exec(line.trim()) : null
52    if (!item) continue
53    if (field) {
54      const key = field[1]!.toLowerCase()
55      const value = plain(field[2]!)
56      if (key === 'phase') item.phase = value || null
57      else if (key === 'scope') item.scope = expandIds(value)
58      else if (key === 'sections') item.sections = [...value.matchAll(/§\s*(\d+(?:[ .]\d+)*)/g)].map(m => m[1]!.replace(/\s+/g, '.'))
59      else if (key.startsWith('gate')) item.gate = /^(none|keine?|-|—)$/i.test(value) ? null : value
60      else item.spec = value
61    } else if (item.spec && line.trim() && !/^\s*(#|\*\*)/.test(line)) {
62      // The spec text may wrap over several lines.
63      item.spec += ' ' + line.trim()
64    }
65  }
66  return items.filter(i => i.spec || i.scope.length)
67}
68
69/** prd-review.md: the recommendation and the decisions that block the first feature. */
70export function parsePrdReview(markdown: string): PrdReview {
71  const rec = /^\*\*Recommendation\*\*:\s*(.+)$/im.exec(markdown)?.[1]?.toLowerCase().match(/build|sharpen/)?.[0] as PrdReview['recommendation'] | undefined
72  const blocking: string[] = []
73  let inside = false
74  for (const line of markdown.split('\n')) {
75    const h = /^##\s+(.+)$/.exec(line)
76    if (h) {
77      inside = /blocking|blockier/i.test(h[1]!)
78      continue
79    }
80    const bullet = inside ? /^\s*[-*]\s+(.+)$/.exec(line) : null
81    if (bullet) blocking.push(clip(plain(bullet[1]!), 200))
82  }
83  return { recommendation: rec ?? null, blocking }
84}
85
86/** What the person approves at the roadmap review: the review and the roadmap together. */
87export const prdFingerprint = (review: string, roadmap: string) => fingerprint(`${review}\n---\n${roadmap}`)
88
89/**
90 * The PRD's sections a feature names (`§5`, `§6.1`), with their subsections, from headings numbered as the PRD
91 * writes them (`## 5 Kleinster spielbarer Kern`, `### 6 1 Aufbau`, `### 6.1 …`). Bounded for the intent check.
92 */
93export function prdSections(prd: string, refs: string[], max = 4000): string {
94  if (!refs.length) return ''
95  const lines = prd.split('\n')
96  const numbered = lines.map(l => /^(#{1,4})\s+(\d+(?:[ .]\d+)*)\.?\s+\D/.exec(l)).map(m => (m ? { level: m[1]!.length, num: m[2]!.replace(/\s+/g, '.') } : null))
97  const out: string[] = []
98  for (const ref of refs) {
99    const start = numbered.findIndex(h => h && h.num === ref)
100    if (start < 0) continue
101    let end = lines.length
102    for (let i = start + 1; i < lines.length; i++) {
103      const h = numbered[i]
104      if (h && h.level <= numbered[start]!.level && !h.num.startsWith(`${ref}.`)) {
105        end = i
106        break
107      }
108    }
109    out.push(lines.slice(start, end).join('\n').trim())
110  }
111  return clip(out.join('\n\n'), max)
112}
113
114/** Which of a feature's PRD ids its spec carries: in a requirement's text, a story's title or a scenario. */
115export function prdCoverage(scope: string[], spec: Spec | null): { covered: string[]; missing: string[] } {
116  const text = spec ? [...spec.reqs.map(r => r.text), ...spec.stories.flatMap(s => [s.title, ...s.scenarios.map(x => x.text)]), spec.input ?? ''].join('\n') : ''
117  const has = (id: string) => new RegExp(`(^|[^A-Za-z0-9])${id}([^0-9]|$)`).test(text)
118  return { covered: scope.filter(has), missing: scope.filter(id => !has(id)) }
119}
120
121/** The roadmap item a feature directory stands for: `specs/002-…` is the second. */
122export function roadmapItemOf(snap: Pick<Snapshot, 'featureDir' | 'features' | 'roadmap'>): RoadmapItem | null {
123  if (!snap.roadmap?.length || !snap.featureDir) return null
124  const n = Number(/(?:^|\/)(\d{3})-/.exec(snap.featureDir)?.[1])
125  const index = Number.isFinite(n) && n > 0 ? n - 1 : snap.features.indexOf(snap.featureDir)
126  return snap.roadmap[index] ?? null
127}
128
129/** What /speckit-specify gets for a roadmap feature: its text and where it comes from. */
130export const roadmapSpecify = (item: RoadmapItem) =>
131  `${item.spec}${item.sections.length || item.scope.length ? ` (Source: ${PRD}${item.sections.length ? ` ${item.sections.map(s => `§${s}`).join(', ')}` : ''}${item.scope.length ? `; PRD ids ${item.scope.join(', ')}` : ''})` : ''}`
132
133export const PRD_PROMPT = [
134  `Review the person's PRD (${PRD}) and cut it into features, with the speckit-xref:prd skill.`,
135  `Write ${PRD_REVIEW} (contradictions, untestable criteria, gaps per phase, and the open decisions that block the first feature, each with your recommendation) and ${ROADMAP} (one section per feature in build order: phase, scope as the PRD's own ids, the PRD sections it implements, the gate before it, and the spec text), in the formats the skill gives.`,
136  'The PRD is the person\'s: do not rewrite it, do not research what it already researched, and do not decide its open decisions. The first feature is the smallest one the PRD itself says to build first.',
137].join('\n')
138
139export const PRD_SHAPE_PROMPT = [
140  'Shape the first version from the PRD, with the speckit-xref:shape skill: its decisions (scope, platforms, language, design, data, stack) are the person\'s; take them as decided.',
141  `Ask in the AskUserQuestion dialog only the open decisions ${PRD_REVIEW} lists as blocking the first feature, in one round, your recommendation first. Write .specify/memory/product-brief.md with them.`,
142].join('\n')
143
144export const PRD_NOTE =
145  `The product comes from the person's PRD (${PRD}; review and roadmap beside it). Its decisions are the person's. Carry its ids: every requirement ends with the PRD id it comes from, e.g. "(PRD F01)"; every user story names its PRD story ("PRD US01"); acceptance scenarios cite the PRD's acceptance criteria ("PRD AC04").`
146
hooks/brief.ts 185 lines
1// What a step is handed beyond "run the command" (0.5.2): the phase's own goal, independent test and checkpoint from
2// tasks.md, the acceptance scenarios it has to prove, the quickstart rows and screens that show them, the last test
3// run and the project's runbook. And what "done" means: a verification that still holds for this spec, these tasks
4// and this working tree. Pure: register.tsx reads the files.
5
6import type { Autopilot, NextWork, PhaseNote, QuickRow, Snapshot } from '../types'
7import { ACCEPTANCE_ARTIFACT, POLISH_ARTIFACT, TRY_ARTIFACT } from './accept'
8import { SHIP_ARTIFACT } from './ship'
9import { designDir } from './design'
10import { fingerprint, specFingerprint } from './rules'
11
12export const RUNBOOK = '.specify/memory/runbook.md'
13const MAX_RUNBOOK = 1500
14
15const clip = (text: string, max: number) => (text.length > max ? text.slice(0, max - 1) + '…' : text)
16const plain = (text: string) => text.replace(/\*\*/g, '').replace(/`/g, '').trim()
17
18/** tasks.md's notes per `##` phase: `**Goal**:`, `**Independent Test**:`, `**Checkpoint**:`, keyed by the heading. */
19export function parsePhaseNotes(tasksMd: string): Record<string, PhaseNote> {
20  const notes: Record<string, PhaseNote> = {}
21  const lines = tasksMd.split('\n')
22  // A field is a paragraph: the lines after it belong to it until a blank line or the next structure.
23  const structure = /^\s*(#|[-*+]\s|\d+[.)]\s|\||```|~~~|\*\*[^*]+\*\*\s*:)/
24  let phase: string | null = null
25  for (let i = 0; i < lines.length; i++) {
26    const line = lines[i]!
27    const heading = /^##\s+(.+)$/.exec(line)
28    if (heading) {
29      phase = plain(heading[1] ?? '')
30      continue
31    }
32    const field = /^\s*\*\*(Goal|Purpose|Independent Test|Checkpoint)\*\*\s*:\s*(.+)$/i.exec(line)
33    if (!phase || !field) continue
34    let text = field[2]!.trim()
35    while (i + 1 < lines.length && lines[i + 1]!.trim() && !structure.test(lines[i + 1]!)) text += ' ' + lines[++i]!.trim()
36    const note = (notes[phase] ??= { goal: null, test: null, checkpoint: null })
37    const key = field[1]!.toLowerCase()
38    const value = clip(plain(text), 300)
39    if (key === 'goal' || key === 'purpose') note.goal ??= value
40    else if (key === 'independent test') note.test ??= value
41    else note.checkpoint ??= value
42  }
43  return notes
44}
45
46const IDS = /\b(?:US\d+(?:-AS\d+)?|(?:FR|SC)-\d{3,}|Q\d+)\b/g
47
48/** quickstart.md's table rows that name a story, a scenario or a requirement: the runnable checks of the feature. */
49export function parseQuickstart(markdown: string): QuickRow[] {
50  const rows: QuickRow[] = []
51  for (const line of markdown.split('\n')) {
52    if (!/^\s*\|/.test(line) || /^\s*\|?\s*:?-{3,}/.test(line)) continue
53    const cells = line.trim().replace(/^\||\|$/g, '').split('|').map(c => plain(c))
54    const ids = [...new Set(line.match(IDS) ?? [])].filter(id => !/^Q\d+$/.test(id))
55    if (!ids.length || cells.every(c => !c)) continue
56    rows.push({ ids, text: clip(cells.filter(Boolean).join(' · '), 200) })
57  }
58  return rows
59}
60
61/** The phase brief of an implement step: what the phase is for, what proves it, and when it is done. */
62export function phaseBrief(snap: Snapshot, phase: string, lastTest: Autopilot['lastTest'] = null): string[] {
63  const note = snap.phaseNotes?.[phase]
64  const stories = [...new Set(snap.tasks.filter(t => t.phase === phase && t.story).map(t => t.story!))]
65  const scenarios = (snap.spec?.stories ?? []).filter(s => stories.includes(s.id)).flatMap(s => s.scenarios)
66  const ids = new Set([...stories, ...scenarios.map(s => s.id)])
67  const rows = (snap.quickstart ?? []).filter(r => r.ids.some(id => ids.has(id)))
68  const screens = (snap.design?.screens ?? []).filter(s => s.serves.some(id => ids.has(id) || stories.some(st => id.startsWith(`${st}-`))))
69  const lines: string[] = []
70  if (note?.goal) lines.push(`Goal: ${note.goal}`)
71  if (note?.test) lines.push(`Independent test: ${note.test}`)
72  if (scenarios.length) {
73    lines.push(`Prove: ${scenarios.map(s => `${s.id} "${clip(s.text, 110)}"`).join('; ')}. Name each test after the scenario it proves (its id in the test name).`)
74  }
75  if (rows.length) lines.push(`Quickstart: ${rows.slice(0, 4).map(r => r.text).join(' | ')}`)
76  if (screens.length && snap.featureDir) {
77    lines.push(`Screens: ${screens.map(s => `${s.name}${s.mock ? ` (${designDir(snap.featureDir!)}/${s.mock})` : ''}`).join(', ')}; build them to DESIGN.md.`)
78  }
79  lines.push(testRule(snap.testMode))
80  if (lastTest) lines.push(`Last test run: ${lastTest.ok ? 'green' : `red: ${clip(lastTest.output.trim().split('\n').at(-1) ?? '', 140)}`}.`)
81  if (note?.checkpoint) lines.push(`Done when: ${note.checkpoint}. Check that before you end the step, and say how you checked it.`)
82  return lines.length ? ['Phase brief (tasks.md, spec.md, quickstart.md):', ...lines.map(l => `- ${l}`)] : []
83}
84
85/** No suite (0.11.0, the default): a proof of concept or an MVP is checked by its type check and by a person using it. */
86export const NO_TESTS =
87  'Write no tests and no test tasks: this project runs without a test suite (option tests: off), because building and fixing suites costs more than it finds here. Check your work with the type check the brief names and, where you can, by running the app; leave existing tests as they are.'
88/** The existing suite as the gate, and nothing added (0.11.0). */
89export const RUN_TESTS = 'Write no new tests (option tests: run): the existing suite is the gate. Keep it green; change a test only where the spec changed what it checks.'
90/** The rule on tests a phase brief carries, by option tests; a snapshot that names none keeps the lean rule. */
91export const testRule = (mode: Snapshot['testMode']) => (mode === 'off' ? NO_TESTS : mode === 'run' ? RUN_TESTS : LEAN_TESTS)
92
93/** Tests prove requirements, not tasks (0.8.0): what makes a test worth its lines. */
94export const LEAN_TESTS =
95  'Tests prove requirements: one test per requirement or acceptance scenario, at the boundary where its behaviour shows (a function\'s result, a screen\'s text after an action, a request that goes out). No render-only test, no test of what the framework or the types already guarantee, no test per task; extend an existing test file before adding one. A test whose result depends on the clock or on chance fixes them (a set date and time, a seeded random).'
96
97/** The runbook as a note: what earlier steps learned about this project's environment. */
98export function runbookNote(runbook: string | null | undefined): string | null {
99  const text = (runbook ?? '').trim()
100  if (!text) return null
101  const tail = text.length > MAX_RUNBOOK ? '…' + text.slice(-MAX_RUNBOOK) : text
102  return `Runbook (${RUNBOOK}, what earlier steps learned about this project's environment):\n${tail}`
103}
104
105/**
106 * What a verification holds for: this spec, these tasks and this content of the working tree. While it holds the
107 * feature is done, and another verify would only say the same again; committing what was verified changes nothing.
108 */
109export function verifyKey(snap: Snapshot, tasksFp: string): string {
110  return fingerprint([snap.spec ? specFingerprint(snap.spec) : '', tasksFp, snap.tree ?? ''].join('|'))
111}
112
113/**
114 * The working tree's content from `git ls-tree -r` of `git stash create` (or HEAD) plus `<hash> <path>` of the untracked
115 * files: one line per file, without the ledger's own file, which the mod rewrites as it links.
116 */
117export const treeOf = (lines: string) =>
118  fingerprint(
119    lines
120      .split('\n')
121      .filter(l => {
122        if (!l.trim()) return false
123        // `<mode> <type> <hash>\t<path>` from ls-tree, `<hash> <path>` for an untracked file.
124        const path = l.includes('\t') ? l.slice(l.indexOf('\t') + 1) : l.trim().slice(l.trim().indexOf(' ') + 1)
125        // The ledger's own file, and what acceptance and the release check write about the app, change nothing that was verified.
126        return !/(^|\/)xref\.json$/.test(path) && !ACCEPTANCE_ARTIFACT.test(path) && !SHIP_ARTIFACT.test(path) && !TRY_ARTIFACT.test(path) && !POLISH_ARTIFACT.test(path)
127      })
128      .sort()
129      .join('\n'),
130  )
131
132/** What a small model sorts the person's words after a done feature into; the question is no work. */
133const NEXT_KINDS: Record<string, NextWork['kind'] | null> = {
134  'a new feature, separate from the finished one': 'feature',
135  'a change to what the finished feature does': 'change',
136  'a bug: something the finished feature does wrong': 'bug',
137  'ship it: release what is done to its users (deploy, app stores)': 'ship',
138  "polish it: make the finished app look and feel like the best apps of its platform (design, not function)": 'polish',
139  'no new work: a question or a remark': null,
140}
141export const NEXT_LABELS = Object.keys(NEXT_KINDS)
142
143/**
144 * An untracked file as `git ls-tree` writes it once committed (`100644 blob <hash>\t<path>`): committing the files of a
145 * done feature changes nothing that was verified (found live in 0.7.0).
146 */
147export const untrackedLine = (hash: string, path: string) => `100644 blob ${hash}\t${path}`
148export const NO_WORK = 'no new work: a question or a remark'
149/** The kind of work a label names; null for a question or a remark, which stays a conversation. */
150export const nextKindOf = (label: string): NextWork['kind'] | null => NEXT_KINDS[label] ?? null
151
152/** What the person is asked once a feature is done; with a kind chosen in the pane, only its words are missing. */
153export function doneAsk(kind: NextWork['kind'] | null | undefined): string {
154  if (kind === 'feature') return 'Describe the new feature in your own words; the autopilot specifies it as the next feature.'
155  if (kind === 'change') return 'Describe the change in your own words; the autopilot folds it into the spec and builds it.'
156  if (kind === 'bug') return 'Describe the bug: what you did, what happened, what you expected; the autopilot reproduces and fixes it.'
157  return 'The feature is done. Say what comes next (a new feature, a change to this one, a bug, polish its look, or ship it), or press New feature, Change, Bug, Polish or Ship in the pane.'
158}
159
160/** The bug step: Spec Kit's bug extension where it is installed, else the same three steps by hand. */
161export function bugPrompt(snap: Snapshot, text: string, command: (name: string) => string, has: (name: string) => boolean): string {
162  const steps = has('bug-assess')
163    ? [`Run ${command('bug.assess')} with the report below, then ${command('bug.fix')}, then ${command('bug.test')}, each through the Skill tool, without asking in between.`]
164    : [
165        'Reproduce it first: find the code path, and write a test that fails because of the bug, named after the requirement or scenario it breaks (FR-###, USn-ASm).',
166        'Then fix the code (not the test), and run the tests until they pass.',
167        'Record it in .specify/bugs/<slug>/report.md: symptom, cause, fix, the test that proves it.',
168      ]
169  return [
170    `A bug in ${snap.featureDir}, in the person's words: "${text}"`,
171    ...steps,
172    `Append a checked task for it to ${snap.featureDir}/tasks.md under '## Phase N: Fixes' (the next free T### id, the files in backticks, the requirement ids), so the fix has its place in the trace.`,
173  ].join('\n')
174}
175
176/** The change step: the request reaches the spec first, then the tasks it needs. */
177export function changePrompt(snap: Snapshot, text: string, revise: string | null): string {
178  return [
179    revise
180      ? `Run ${revise} through the Skill tool with this change request from the person: "${text}".`
181      : `The person asks for a change to ${snap.featureDir}: "${text}". Fold it into spec.md first: new requirements under the next free FR-### ids, a changed one marked SUPERSEDED by its successor.`,
182    `Then append the tasks it needs to ${snap.featureDir}/tasks.md under '## Phase N: Changes' (the next free T### ids, files in backticks, requirement ids). Do not implement them in this step.`,
183  ].join('\n')
184}
185
hooks/ship.ts 247 lines
1// Ship (0.7.0): after a done feature the person can release the app. A release check writes .specify/memory/release.md
2// (checks, the release commands, the person's part); its code gaps become tasks, and its commands run only after the
3// person's yes. The rail below holds every deploy, submit and publish until then. Pure: register.tsx reads the files.
4
5import type { Ledger, ReleaseNote, Snapshot } from '../types'
6import { acceptanceCounts } from './accept'
7import { fingerprint, specFingerprint } from './rules'
8import { evaluate } from './xref'
9
10export const RELEASE = '.specify/memory/release.md'
11
12/** What the release check and the release write about the app, not into it: release.md and the local build output. */
13export const SHIP_ARTIFACT = /(^|\/)\.specify\/memory\/release\.md$|^(dist|web-build|build|out)\//
14
15/** The deploy CLIs the mod looks for, on PATH or in the project, by the package that brings each. */
16export const DEPLOY_TOOLS: Record<string, string> = { eas: 'eas-cli', wrangler: 'wrangler', vercel: 'vercel', netlify: 'netlify-cli', firebase: 'firebase-tools', fastlane: '' }
17
18/** The deploy CLIs package.json brings: they run through npx without a download. */
19export function deployToolsOf(packageJson: string | null): string[] {
20  let deps: Record<string, unknown> = {}
21  try {
22    const pkg = JSON.parse(packageJson ?? '') as { dependencies?: Record<string, unknown>; devDependencies?: Record<string, unknown> }
23    deps = { ...pkg.dependencies, ...pkg.devDependencies }
24  } catch {
25    return []
26  }
27  return Object.entries(DEPLOY_TOOLS).filter(([, pkg]) => pkg && pkg in deps).map(([name]) => name)
28}
29
30const cells = (line: string) => line.trim().replace(/^\||\|$/g, '').split('|').map(c => c.replace(/`/g, '').trim())
31const plain = (text: string) => text.replace(/\*\*|`/g, '').trim()
32
33function resultOf(text: string): ReleaseNote['checks'][number]['result'] {
34  const t = text.toLowerCase()
35  if (/your part|person|manual|dein teil/.test(t)) return 'your part'
36  if (/^(fail|✗|✖|no\b)|→\s*t\d/.test(t)) return 'fail'
37  if (/^(pass|ok|✓|✔|yes\b)/.test(t)) return 'pass'
38  return 'n/a'
39}
40
41/** `.specify/memory/release.md` as the mod reads it (the format the speckit-xref:ship skill gives). */
42export function parseRelease(markdown: string): ReleaseNote {
43  const field = (name: string) => new RegExp(`^\\*\\*${name}\\*\\*:\\s*(.+)$`, 'mi').exec(markdown)?.[1]?.trim() ?? null
44  const ready = field('Ready')
45  const note: ReleaseNote = {
46    version: field('Version'),
47    // Commas inside a target's parentheses (`web (Cloudflare Pages, recommended)`) do not split it.
48    targets: (field('Targets') ?? '').split(/,\s*(?![^()]*\))/).map(plain).filter(Boolean),
49    ready: ready === null ? null : /^yes\b/i.test(ready),
50    readyNote: ready?.replace(/^(yes|no)\s*[—–:-]?\s*/i, '') || null,
51    checks: [],
52    commands: [],
53    yourPart: [],
54    releases: [],
55    fingerprint: '',
56  }
57  let section = ''
58  let when: 'before' | 'after' = 'before'
59  let fence = false
60  const kept: string[] = []
61  for (const line of markdown.split('\n')) {
62    const h = /^##\s+(.+)$/.exec(line)
63    if (h) {
64      const title = h[1]!.toLowerCase()
65      section = /^checks?/.test(title) ? 'checks' : /command/.test(title) ? 'commands' : /your part|dein teil/.test(title) ? 'yours' : /^releases?\b/.test(title) ? 'releases' : ''
66      when = 'before'
67    }
68    if (section !== 'releases') kept.push(line)
69    if (h) continue
70    if (/^```/.test(line.trim())) {
71      fence = !fence
72      continue
73    }
74    if (section === 'commands') {
75      const command = fence ? line.trim() : /^\s*(?:\d+[.)]|[-*])\s+`([^`]+)`/.exec(line)?.[1]?.trim()
76      if (command && !command.startsWith('#')) note.commands.push(command)
77    } else if (section === 'yours') {
78      if (/^(?:###\s+)?\**\s*after\b/i.test(line.trim())) when = 'after'
79      else if (/^(?:###\s+)?\**\s*before\b/i.test(line.trim())) when = 'before'
80      const item = /^\s*[-*]\s+(?:\[([ xX])\]\s+)?(.+)$/.exec(line)
81      if (item) note.yourPart.push({ text: plain(item[2]!), done: !!item[1] && item[1] !== ' ', when })
82    } else if ((section === 'checks' || section === 'releases') && /^\s*\|/.test(line) && !/^\s*\|[\s:|-]+\|\s*$/.test(line)) {
83      const c = cells(line)
84      if (section === 'checks' && c.length >= 3 && !/^area$/i.test(c[0]!)) note.checks.push({ area: c[0]!, check: c[1]!, result: resultOf(c[2]!), evidence: c[3] ?? '' })
85      if (section === 'releases' && c.length >= 4 && !/^date$/i.test(c[0]!)) note.releases.push({ date: c[0]!, version: c[1]!, target: c[2]!, ok: /^(shipped|ok|pass|✓|✔|live|submitted)/i.test(c[3]!), where: c[4] ?? '' })
86    }
87  }
88  // The person approves the plan; the log the release appends to is not part of it.
89  note.fingerprint = fingerprint(kept.join('\n'))
90  return note
91}
92
93/** One line for the pane and the review: `v1.0.0 → web, ios · 14 pass · 2 your part`. */
94export function releaseLine(release: ReleaseNote | null | undefined): string {
95  if (!release) return 'no release check yet'
96  const pass = release.checks.filter(c => c.result === 'pass').length
97  const fail = release.checks.filter(c => c.result === 'fail').length
98  const yours = release.yourPart.filter(y => !y.done).length
99  return [
100    `${release.version ? `v${release.version.replace(/^v/i, '').split(/\s/)[0]}` : 'no version'} → ${release.targets.map(t => t.split(/\s/)[0]).join(', ') || 'no target'}`,
101    `${pass} pass`,
102    ...(fail ? [`${fail} fail${fail === 1 ? 's' : ''}`] : []),
103    ...(yours ? [`${yours} your part`] : []),
104  ].join(' · ')
105}
106
107/** What the person's yes runs, in one line: the first commands as written and how many more. */
108export function releaseRuns(release: ReleaseNote): string {
109  const shown = release.commands.slice(0, 3).map(c => `\`${c}\``).join(', ')
110  return release.commands.length > 3 ? `${shown} (+${release.commands.length - 3} more)` : shown
111}
112
113/**
114 * The last release: the rows it appended (one per target), whether all went out, and one line on each. With `since`
115 * (the log's length before the release step) exactly the rows that step added; else the last date's rows.
116 */
117export function lastRelease(release: ReleaseNote | null | undefined, since?: number): { status: 'out' | 'partly out' | 'failed'; date: string; version: string; line: string } | null {
118  const last = release?.releases.at(-1)
119  if (!last) return null
120  const rows = since !== undefined ? release!.releases.slice(since) : release!.releases.filter(r => r.date === last.date && r.version === last.version)
121  if (!rows.length) return null
122  const status = rows.every(r => r.ok) ? 'out' : rows.some(r => r.ok) ? 'partly out' : 'failed'
123  const line = rows.map(r => `${r.target} ${r.ok ? 'out' : 'failed'}${r.where ? `: ${r.where.length > 90 ? r.where.slice(0, 89) + '…' : r.where}` : ''}`).join('; ')
124  return { status, date: last.date, version: last.version, line }
125}
126
127/**
128 * What holds a release, before any model looks: the tests, the drift, a failing acceptance scenario, a spec nobody
129 * approved; then what release.md itself says: not ready, a failing check, the person's part before the release, no command.
130 */
131export function releaseBlockers(snap: Snapshot, ledger: Ledger, lastTest: { ok: boolean } | null, specGate: boolean): string[] {
132  const out: string[] = []
133  if (lastTest && !lastTest.ok) out.push(snap.gate === 'check' ? 'the type check fails' : 'the tests fail')
134  if (evaluate(snap, ledger).level === 'red') out.push('the drift is red')
135  const failing = acceptanceCounts(snap, ledger).failing
136  if (failing) out.push(`${failing} acceptance scenario${failing === 1 ? '' : 's'} fail${failing === 1 ? 's' : ''}`)
137  // As the workflow counts it: a project planned before the spec review existed counts as reviewed until its spec changes.
138  const specApproved = !snap.spec || (ledger.approvals.spec ? ledger.approvals.spec === specFingerprint(snap.spec) : snap.hasPlan)
139  if (specGate && !specApproved) out.push('the spec is not approved (Approve spec in the pane)')
140  const release = snap.release
141  if (!release) return [...out, `the release check wrote no ${RELEASE}`]
142  if (release.ready === false) out.push(`${RELEASE} says it is not ready${release.readyNote ? `: ${release.readyNote}` : ''}`)
143  const failed = release.checks.filter(c => c.result === 'fail')
144  if (failed.length) out.push(`${failed.length} check${failed.length === 1 ? '' : 's'} fail${failed.length === 1 ? 's' : ''} (${failed.slice(0, 3).map(c => c.check).join('; ')})`)
145  const before = release.yourPart.filter(y => !y.done && y.when === 'before')
146  if (before.length) out.push(`your part before the release: ${before.slice(0, 3).map(y => y.text).join('; ')}${before.length > 3 ? ` (+${before.length - 3})` : ''}`)
147  if (!release.commands.length) out.push(`${RELEASE} names no release command`)
148  return out
149}
150
151/** What the release check hands Claude: the targets, the tools on this machine, the rules. Nothing goes out in it. */
152export function shipPrompt(snap: Snapshot): string {
153  const dir = snap.featureDir ?? 'specs/<feature>'
154  const p = snap.platforms ?? { web: false, ios: false, android: false }
155  const targets = [p.web ? 'web' : null, p.ios ? 'iOS' : null, p.android ? 'Android' : null].filter(Boolean).join(', ') || "the platforms plan.md names"
156  const tools = snap.tools.deploy ?? []
157  return [
158    `Check that the app is ready to release, with the speckit-xref:ship skill, and write ${RELEASE} in the format it gives. Nothing goes out in this step: no deploy, no store build, no submit, no publish, no push.`,
159    ...(snap.testCommand ? [`The mod ran ${snap.gate === 'check' ? 'the type check' : 'the test suite'} (\`${snap.testCommand}\`) right before this step and stops on a failure: do not run it again.`] : []),
160    `Targets: ${targets}. Deploy tools on this machine: ${tools.length ? tools.join(', ') : 'none'}. Never run npx with a package the project does not have (eas-cli, wrangler, lighthouse, serve …): a missing tool is the person's part.`,
161    'Check: the version and build numbers; the store fields (app name, bundle identifier, Android package, icon, splash); a usage text for every OS permission the code asks for; privacy (what leaves the device, a privacy-policy URL; the stores\' privacy answers drafted under Your part); accessibility (labels on controls, the contrast of DESIGN.md\'s colours); secrets (no .env, *.p8, *.p12, keystore or service-account file tracked by git; .env.example names every variable the code reads; name paths, never values); the production build, run locally where it needs no account (e.g. `npx expo export -p web`), with its size.',
162    `Rate each finding as verify does: HIGH (blocks the release or breaks a store rule), MEDIUM (a user or a reviewer would hit it), LOW (polish). HIGH and MEDIUM findings that are code or configuration work become tasks under '## Phase N: Release readiness' in ${dir}/tasks.md (the next free T### ids, the files in backticks); list the LOW ones in your answer under 'Low, no task'. Do not change the app in this step.`,
163    `Write the release commands the person will approve: the exact commands, in order, with the tools that are here. What only the person can do (an account, a login, a key, a store listing, a review, testers) goes under Your part, split into before and after the release.`,
164  ].join('\n')
165}
166
167/** The release step: the commands the person approved, once each, and a row in the log. */
168export function releasePrompt(release: ReleaseNote): string {
169  return [
170    `The person approved this release (${RELEASE}). Run its release commands now, in order, once each:`,
171    ...release.commands.map((c, i) => `${i + 1}. \`${c}\``),
172    'A command that asks for a login, a password, a two-factor code or any interactive answer: stop there and do not work around it; add it to Your part before the release. Stop at the first command that fails.',
173    `Then append a row to '## Releases' in ${RELEASE} for each target of this attempt, also when an earlier attempt left the same rows: | today's date (YYYY-MM-DD) | version | target | shipped or failed | the URL, the build id or the error |. Do not change the app, do not commit, do not push.`,
174  ].join('\n')
175}
176
177// ---- The rail: what releases the app waits for the person ----
178
179/** Where a word is a command, not an argument (`ls fastlane` is no release): at the start, after `;` `&&` `|` `(`, or `npx`, `exec` and the like. */
180const AT_COMMAND = String.raw`(?:^\s*|[;&|(]\s*|\b(?:npx|bunx|exec|dlx|sudo|env|time)\s+)(?:\w+=\S*\s+)*`
181
182const RELEASING: RegExp[] = [
183  /\beas(?:-cli(?:@\S+)?)?\s+(?:build|submit|update)(?![:\w-])/,
184  /\bexpo(?:-cli)?\s+publish\b/,
185  /\bwrangler(?:@\S+)?\s+(?:pages\s+)?(?:deploy|publish)\b|\bwrangler(?:@\S+)?\s+versions\s+(?:upload|deploy)\b/,
186  new RegExp(String.raw`${AT_COMMAND}vercel(?:@\S+)?(?=\s|$)(?!\s+(?:dev|build|env|login|logout|whoami|link|pull|ls|list|inspect|logs|help|--version|-v)\b)`),
187  /\bnetlify(?:-cli)?\s+deploy\b/,
188  /\bfirebase(?:-tools)?\s+(?:deploy|hosting:channel:deploy)\b/,
189  new RegExp(String.raw`${AT_COMMAND}fastlane(?=\s|$)(?!\s+(?:init|lanes|list|env|help|--version|-v)\b)`),
190  /\b(?:npm|pnpm|yarn|bun)\s+publish\b/,
191  /\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:deploy|release|publish|ship)\b/,
192  /\bgh\s+release\s+create\b/,
193  /\b(?:fly|flyctl)\s+deploy\b/,
194  /\bsupabase\s+(?:functions\s+deploy|db\s+push)\b/,
195  /\bdocker\s+push\b/,
196  /\bgcloud\b.*\bdeploy\b/,
197  /\bxcrun\s+altool\b.*--upload/,
198]
199
200/** A shell command's parts: what `;`, `&&`, `||` and `|` separate. */
201const SEGMENTS = /\n|;|&&|\|\|?/
202
203/**
204 * A command without the text it only writes: the body of a heredoc fed to `cat` or `tee`, a message after `-m`,
205 * `--body`, `--title` or `--notes`, what `echo` and `printf` print. Text that runs (`bash -c`, `eval`, a script's
206 * heredoc) stays.
207 */
208export const commandText = (command: string) =>
209  command
210    .replace(/(\b(?:cat|tee)\b[^\n]*<<-?\s*(['"]?)(\w+)\2[^\n]*)\n[\s\S]*?\n\s*\3\s*(?=\n|$)/g, '$1')
211    .replace(/(\s(?:-m|--message|--body|--title|--notes)(?:\s+|=))(['"])(?:\\.|(?!\2)[^\\])*\2/g, "$1''")
212    .replace(/(\b(?:echo|printf)\s+(?:-\w+\s+)*)(['"])(?:\\.|(?!\2)[^\\])*\2/g, "$1''")
213
214/** Whether a shell command releases the app: deploys, builds or submits for a store, publishes. Asking a tool for its help does not. */
215export const releasesApp = (command: string) =>
216  commandText(command)
217    .split(SEGMENTS)
218    .some(part => !/\s(?:--help|-h)(?:\s|$)/.test(part) && RELEASING.some(re => re.test(part)))
219
220const normalized = (command: string) =>
221  command
222    .replace(/\s+(?:\d*>>?|&>)\s*&?\S+/g, '')
223    .replace(/^\s*\(+|\)+\s*$/g, '')
224    // A time limit or a stopwatch around a command does not change where it goes.
225    .replace(/^(?:\s*(?:timeout\s+(?:-\S+\s+)*\S+|time|nohup)\s+)+/, '')
226    .replace(/\s+/g, ' ')
227    .trim()
228
229/**
230 * Whether a shell command releases only what the person approved: every part of it that releases is one of the
231 * approved commands as written (`cd web && <cmd> 2>&1 | tail` is that command; `npx <cmd>`, another flag or another
232 * project is not). The person's yes is to these commands, not to releasing in general.
233 */
234export function approvedRelease(command: string, approved: string[]): boolean {
235  const ok = new Set(approved.flatMap(c => commandText(c).split(SEGMENTS).filter(part => releasesApp(part)).map(normalized)))
236  const releasing = commandText(command).split(SEGMENTS).filter(part => releasesApp(part))
237  return releasing.length > 0 && releasing.every(part => ok.has(normalized(part)))
238}
239
240/** An MCP tool that deploys, publishes or submits (`deploy_worker`, `submit_build`); reading tools pass. */
241export function releasesByTool(tool: string): boolean {
242  if (!tool.startsWith('mcp__')) return false
243  const name = tool.slice(tool.lastIndexOf('__') + 2).toLowerCase()
244  if (/^(get|list|read|search|describe|fetch|view|show|find)[_-]/.test(name)) return false
245  return /(?:^|[_-])(deploy|publish|submit|release|rollback|promote)(?:$|[_-])/.test(name)
246}
247
hooks/design.ts 140 lines
1// The design step (0.5.1): a feature people look at gets its look settled after the plan and before the tasks.
2// DESIGN.md at the project root is the design system (Google Stitch's format: YAML tokens on top, the reasons in
3// prose); specs/<feature>/design/ holds the feature's screens: screens.md says which screen serves which story,
4// and one static HTML mock per screen shows it. Pure: register.tsx reads the files.
5
6import type { Design, Screen, Snapshot } from '../types'
7import { fingerprint } from './rules'
8
9export const DESIGN_FILE = 'DESIGN.md'
10export const designDir = (featureDir: string) => `${featureDir}/design`
11export const screensPath = (featureDir: string) => `${designDir(featureDir)}/screens.md`
12
13const field = (markdown: string | null, name: string) => {
14  const value = new RegExp(`^\\*\\*${name}\\*\\*:\\s*(.+)$`, 'mi').exec(markdown ?? '')?.[1]?.trim()
15  // The plan template's own placeholder (`[e.g., library/cli/web-service/mobile-app …]`) says nothing yet.
16  return value && !/NEEDS CLARIFICATION|^\[/.test(value) ? value : null
17}
18
19/** Whether plan.md describes something people look at: its Project Type, else its Target Platform. */
20export function uiFromPlan(planMd: string | null): boolean {
21  const type = field(planMd, 'Project Type')
22  if (type) {
23    if (/\b(mobile|desktop|frontend|front-end|gui|ui|spa|website|web[- ]?app|web application|browser extension|game)\b/i.test(type)) return true
24    if (/\b(cli|library|lib|compiler|sdk|web[- ]?service|api|backend|server|daemon|service)\b/i.test(type)) return false
25    if (/\bweb\b/i.test(type)) return true
26  }
27  const platform = field(planMd, 'Target Platform')
28  return !!platform && /\b(iOS|iPadOS|Android|browsers?|web|watchOS|tvOS)\b/i.test(platform)
29}
30
31const IDS = /\b(?:US\d+(?:-AS\d+)?|(?:FR|SC)-\d{3,})\b/g
32/** A mock is a file beside screens.md: no way up, no scheme, a page or a picture. */
33const MOCK = /^(?!.*\.\.)[\w][\w./-]*\.(?:html?|png|svg|jpe?g|webp)$/i
34
35const cells = (row: string) =>
36  row
37    .trim()
38    .replace(/^\|/, '')
39    .replace(/\|$/, '')
40    .split('|')
41    .map(c => c.trim())
42
43/** screens.md: its table of screens (Screen | Serves | Mock | Notes) and what the step did to DESIGN.md. */
44export function parseScreens(markdown: string): { screens: Screen[]; change: Design['change'] } {
45  const change = field(markdown, 'Design system')?.toLowerCase().match(/created|extended|unchanged/)?.[0] as Design['change'] | undefined
46  const lines = markdown.split('\n')
47  const screens: Screen[] = []
48  for (let i = 0; i < lines.length - 1; i++) {
49    const head = cells(lines[i]!).map(c => c.toLowerCase())
50    if (!lines[i]!.includes('|') || !head.some(c => c.startsWith('screen')) || !/^\s*\|?\s*:?-+/.test(lines[i + 1]!)) continue
51    const col = (re: RegExp) => head.findIndex(c => re.test(c))
52    const at = { name: col(/^screen/), serves: col(/serves|stor|requirement/), mock: col(/^mock/), notes: col(/^notes?/) }
53    for (let j = i + 2; j < lines.length && lines[j]!.includes('|'); j++) {
54      const row = cells(lines[j]!)
55      const name = (row[at.name] ?? '').replace(/\*\*/g, '').trim()
56      if (!name) continue
57      const raw = at.mock >= 0 ? (row[at.mock] ?? '') : ''
58      const target = (/\]\(([^)\s]+)\)/.exec(raw)?.[1] ?? /`([^`]+)`/.exec(raw)?.[1] ?? raw).replace(/^\.\//, '')
59      screens.push({
60        name,
61        serves: [...new Set((at.serves >= 0 ? (row[at.serves] ?? '') : '').match(IDS) ?? [])],
62        mock: MOCK.test(target) ? target : null,
63        notes: at.notes >= 0 ? (row[at.notes] ?? '') : '',
64      })
65    }
66    break
67  }
68  return { screens, change: change ?? null }
69}
70
71/** The feature's design as the snapshot holds it; the fingerprint is what the person approves at the design review. */
72export function designState(designMd: string | null, screensMd: string | null): Design {
73  const parsed = screensMd === null ? null : parseScreens(screensMd)
74  return {
75    system: designMd !== null,
76    screens: parsed?.screens ?? null,
77    change: parsed?.change ?? null,
78    fingerprint: fingerprint(`${designMd ?? ''}\n---\n${screensMd ?? ''}`),
79  }
80}
81
82/** What `git status --porcelain -- DESIGN.md` says happened to it since the last commit. */
83export function designChangeFromGit(porcelain: string): 'created' | 'extended' | 'unchanged' {
84  const code = porcelain.split('\n').find(l => l.trim())?.slice(0, 2) ?? ''
85  return !code ? 'unchanged' : /\?\?|A/.test(code) ? 'created' : 'extended'
86}
87
88/** What the person is told about DESIGN.md at the review: what git shows, and where screens.md claims otherwise. */
89export function designChangeLine(design: Design): string {
90  const shown = design.verified ?? design.change
91  const said = shown === 'created' ? ', a new DESIGN.md' : shown === 'extended' ? ', DESIGN.md extended' : ''
92  const differs = design.verified && design.change && design.verified !== design.change
93  return differs ? `${said} (screens.md says "${design.change}", but git shows DESIGN.md ${design.verified === 'unchanged' ? 'unchanged' : design.verified})` : said
94}
95
96/** Whether the design step still has to run: no screens.md yet, or screens without a design system to draw on. */
97export const designDue = (design: Design | null | undefined) => !design || design.screens === null || (design.screens.length > 0 && !design.system)
98
99/** Whether there is something for the person to look at: screens, or a design system this step wrote or extended. */
100export const designToReview = (design: Design) => (design.screens?.length ?? 0) > 0 || (design.verified ?? design.change) === 'created' || (design.verified ?? design.change) === 'extended'
101
102/** DESIGN.md's tokens the dashboard shows: its name, its colours (name and value), its font families. */
103export function designTokens(designMd: string): { name: string | null; colors: [string, string][]; fonts: string[] } {
104  const front = /^---\s*\n([\s\S]*?)\n---\s*(?:\n|$)/.exec(designMd)?.[1] ?? ''
105  const colors: [string, string][] = []
106  let block = ''
107  for (const line of front.split('\n')) {
108    const top = /^([A-Za-z][\w-]*):\s*(.*)$/.exec(line)
109    if (top) {
110      block = top[1]!
111      continue
112    }
113    const entry = block === 'colors' ? /^\s+([\w-]+):\s*["']?(#[0-9a-f]{3,8}|(?:rgb|hsl)a?\([\d\s.,%/]+\))["']?\s*(?:#.*)?$/i.exec(line) : null
114    if (entry) colors.push([entry[1]!, entry[2]!])
115  }
116  const fonts = [...new Set([...front.matchAll(/fontFamily:\s*["']?([^,}"'\n]+)/g)].map(m => m[1]!.trim()))]
117  return { name: /^name:\s*["']?(.+?)["']?\s*$/m.exec(front)?.[1] ?? null, colors, fonts }
118}
119
120/** What the design step hands Claude. */
121export function designPrompt(snap: Snapshot): string {
122  const dir = designDir(snap.featureDir ?? 'specs/<feature>')
123  return [
124    `Settle the look of ${snap.featureDir} before its tasks are written, with the speckit-xref:design skill.`,
125    snap.design?.system
126      ? `${DESIGN_FILE} at the root is the project's design system: keep its tokens; add one only where this feature needs it, and say so in screens.md.`
127      : snap.folder === 'existing'
128        ? `There is no ${DESIGN_FILE} yet. Where the code already has a look (a theme, colours, fonts, spacing), write down what is there instead of redesigning it; otherwise create it in the format the skill gives.`
129        : `There is no ${DESIGN_FILE} yet: create it in the format the skill gives.`,
130    `The direction comes from ${snap.productBrief ? ".specify/memory/product-brief.md (its Design line is the person's decision), " : ''}the constitution and the spec; what nobody decided, decide and list under Assumptions in ${DESIGN_FILE}.`,
131    `Write ${dir}/screens.md (which screen serves which user story and FR) and one static HTML mock per screen beside it: no scripts, ${DESIGN_FILE}'s tokens as CSS variables, real text in the app's language, the main platform's frame. No @spec anchors in the mocks.`,
132    'A feature that adds or changes no screen writes screens.md with "No screen changes" and no mocks.',
133    "Do not ask the person here: they look at the design system and the mocks at the design review that follows.",
134  ].join('\n')
135}
136
137/** What the tasks and implement steps are told once the feature has screens. */
138export const designNote = (featureDir: string) =>
139  `Build to ${DESIGN_FILE} and ${screensPath(featureDir)}: its tokens go into the app's theme (one early task, if the app has none yet), and each screen is built in the story it serves, to its mock in ${designDir(featureDir)}/.`
140
hooks/ledger.ts 227 lines
1// The ledger's two files (docs/contract-0.4.md §1): what is committed and reviewed, what stays on this machine.
2
3import type { Ledger, Semantic, Unplanned } from '../types'
4import { fingerprint, specFingerprint } from './rules'
5import { parseSpec } from './speckit'
6
7/** 2 (0.5.0): requirement texts include their wrapped continuation lines (docs/contract-0.4.md §6). */
8export const FINGERPRINT_VERSION = 2
9
10export const emptyLedger = (): Ledger => ({
11  tasks: {},
12  requirements: {},
13  unplanned: [],
14  intents: [],
15  anchors: [],
16  semantic: null,
17  semanticHistory: [],
18  fingerprints: {},
19  verification: {},
20  acceptance: {},
21  approvals: {},
22  decisions: [],
23  checkpoints: {},
24  fingerprintVersion: FINGERPRINT_VERSION,
25  extra: { committed: {}, local: {} },
26})
27
28const COMMITTED_KEYS = new Set(['schema_version', 'feature', 'map', 'links', 'accepted', 'fingerprints', 'fingerprintVersion'])
29const LOCAL_KEYS = new Set(['schema_version', 'feature', 'touched', 'unplanned', 'intents', 'semantic', 'semanticHistory', 'verification', 'acceptance', 'assumed', 'approvals', 'decisions', 'anchors', 'checkpoints', 'fingerprintVersion'])
30const MAX_HISTORY = 10
31
32/** Where the local half lives: `.specify/xref/local/<feature-slug>.json`. */
33export const localPath = (featureDir: string) => `.specify/xref/local/${featureDir.slice(featureDir.lastIndexOf('/') + 1)}.json`
34export const runLogPath = (featureDir: string) => `.specify/xref/local/${featureDir.slice(featureDir.lastIndexOf('/') + 1)}.run.jsonl`
35export const LOCAL_IGNORE = { path: '.specify/xref/.gitignore', text: 'local/\n' }
36
37type Raw = Record<string, unknown>
38const obj = (v: unknown): Raw => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Raw) : {})
39const arr = <T>(v: unknown): T[] => (Array.isArray(v) ? (v as T[]) : [])
40const strs = (v: unknown) => arr<unknown>(v).filter((x): x is string => typeof x === 'string')
41const parse = (text: string | null): Raw | null => {
42  if (!text) return null
43  try {
44    return obj(JSON.parse(text))
45  } catch {
46    return null
47  }
48}
49const others = (raw: Raw, known: Set<string>) => Object.fromEntries(Object.entries(raw).filter(([k]) => !known.has(k)))
50
51/** A v1 ledger (one file, `schema_version` 1 or none) as the two v2 halves. */
52export function migrateV1(v1: Raw): { committed: Raw; local: Raw } {
53  const map: Record<string, string[]> = {}
54  const links: Record<string, string[]> = {}
55  const add = (file: string, id: string) => (links[file] = [...new Set([...(links[file] ?? []), id])].sort())
56  for (const [id, r] of Object.entries(obj(v1.requirements))) {
57    const entry = obj(r)
58    const tasks = strs(entry.tasks)
59    if (tasks.length) map[id] = [...new Set(tasks)].sort()
60    for (const file of strs(entry.files)) add(file, id)
61  }
62  const touched: Record<string, string[]> = {}
63  for (const [id, t] of Object.entries(obj(v1.tasks))) {
64    const entry = obj(t)
65    for (const file of strs(entry.linked)) add(file, id)
66    if (strs(entry.touched).length) touched[id] = strs(entry.touched)
67  }
68  const unplanned = arr<Raw>(v1.unplanned)
69  return {
70    committed: {
71      schema_version: 2,
72      feature: v1.feature ?? null,
73      map,
74      links,
75      accepted: [...new Set(unplanned.filter(u => u.acknowledged === true).map(u => String(u.file)))].sort(),
76      fingerprints: {},
77    },
78    local: {
79      schema_version: 2,
80      feature: v1.feature ?? null,
81      touched,
82      unplanned: unplanned.filter(u => u.acknowledged !== true).map(u => ({ file: u.file, at: u.at, task: u.task ?? null })),
83      intents: arr(v1.intents),
84      semantic: v1.semantic ?? null,
85      semanticHistory: [],
86      verification: {},
87      approvals: {},
88      decisions: [],
89      anchors: arr(v1.anchors),
90    },
91  }
92}
93
94/** The in-memory ledger from both files; a v1 file is migrated on the way in, the next write makes it v2. */
95export function ledgerFromParts(committedText: string | null, localText: string | null): Ledger {
96  let committed = parse(committedText) ?? {}
97  let local = parse(localText) ?? {}
98  // A file written before 0.5.0 carries no version: its fingerprints read one physical line per requirement.
99  const versionOf = (half: Raw) => (typeof half.fingerprintVersion === 'number' ? half.fingerprintVersion : 1)
100  const halves = [committedText ? committed : null, localText ? local : null].filter((h): h is Raw => h !== null)
101  const version = halves.length ? Math.min(...halves.map(versionOf)) : FINGERPRINT_VERSION
102  if (committedText && committed.schema_version !== 2) {
103    const migrated = migrateV1(committed)
104    committed = migrated.committed
105    // A local file next to a v1 ledger is newer than the migration; it wins where it says something.
106    local = { ...migrated.local, ...local }
107  }
108  const ledger = emptyLedger()
109  for (const [id, tasks] of Object.entries(obj(committed.map))) {
110    if (strs(tasks).length) ledger.requirements[id] = { tasks: strs(tasks), files: [], sources: ['map'] }
111  }
112  for (const [file, ids] of Object.entries(obj(committed.links))) {
113    for (const id of strs(ids)) {
114      if (/^T-?\d{3,}$/.test(id)) {
115        const entry = (ledger.tasks[id] ??= { touched: [], linked: [] })
116        if (!entry.linked.includes(file)) entry.linked.push(file)
117      } else {
118        const entry = (ledger.requirements[id] ??= { tasks: [], files: [], sources: [] })
119        if (!entry.files.includes(file)) entry.files.push(file)
120        if (!entry.sources.includes('link')) entry.sources.push('link')
121      }
122    }
123  }
124  for (const [id, files] of Object.entries(obj(local.touched))) {
125    const entry = (ledger.tasks[id] ??= { touched: [], linked: [] })
126    entry.touched = strs(files)
127  }
128  ledger.unplanned = [
129    ...arr<Raw>(local.unplanned).map((u): Unplanned => ({ file: String(u.file), at: String(u.at ?? ''), task: typeof u.task === 'string' ? u.task : null, acknowledged: false })),
130    ...strs(committed.accepted).map((file): Unplanned => ({ file, at: '', task: null, acknowledged: true })),
131  ]
132  ledger.fingerprints = Object.fromEntries(Object.entries(obj(committed.fingerprints)).filter(([, v]) => typeof v === 'string')) as Record<string, string>
133  ledger.intents = arr(local.intents)
134  ledger.anchors = arr(local.anchors)
135  ledger.semantic = (local.semantic as Semantic | null) ?? null
136  ledger.semanticHistory = arr(local.semanticHistory)
137  ledger.verification = obj(local.verification) as Ledger['verification']
138  ledger.acceptance = obj(local.acceptance) as Ledger['acceptance']
139  ledger.assumed = obj(local.assumed) as Ledger['assumed']
140  ledger.approvals = obj(local.approvals) as Ledger['approvals']
141  ledger.decisions = arr(local.decisions)
142  ledger.checkpoints = obj(local.checkpoints) as Ledger['checkpoints']
143  ledger.fingerprintVersion = version
144  ledger.extra = { committed: others(committed, COMMITTED_KEYS), local: others(local, LOCAL_KEYS) }
145  return ledger
146}
147
148/** JSON with every object's keys sorted, so the committed file is the same bytes for the same state. */
149function sortedJson(value: unknown): unknown {
150  if (Array.isArray(value)) return value.map(sortedJson)
151  if (value && typeof value === 'object') return Object.fromEntries(Object.keys(value as Raw).sort().map(k => [k, sortedJson((value as Raw)[k])]))
152  return value
153}
154const uniqSorted = (xs: string[]) => [...new Set(xs)].sort()
155
156/** Both files' text for a ledger: the committed half deterministic and without timestamps. */
157export function ledgerToParts(ledger: Ledger, featureDir: string): { committed: string; local: string } {
158  const map: Record<string, string[]> = {}
159  const links: Record<string, string[]> = {}
160  const add = (file: string, id: string) => (links[file] = [...(links[file] ?? []), id])
161  for (const [id, r] of Object.entries(ledger.requirements)) {
162    if (r.tasks.length) map[id] = uniqSorted(r.tasks)
163    for (const file of r.files) add(file, id)
164  }
165  const touched: Record<string, string[]> = {}
166  for (const [id, t] of Object.entries(ledger.tasks)) {
167    for (const file of t.linked) add(file, id)
168    if (t.touched.length) touched[id] = t.touched
169  }
170  for (const file of Object.keys(links)) links[file] = uniqSorted(links[file]!)
171  // An accepted file that was linked since is the link's, not an acceptance.
172  const accepted = uniqSorted(ledger.unplanned.filter(u => u.acknowledged && !links[u.file]).map(u => u.file))
173  const committed = sortedJson({
174    ...ledger.extra.committed,
175    schema_version: 2,
176    feature: featureDir,
177    map,
178    links,
179    accepted,
180    fingerprints: ledger.fingerprints,
181    fingerprintVersion: FINGERPRINT_VERSION,
182  })
183  const local = {
184    ...ledger.extra.local,
185    schema_version: 2,
186    feature: featureDir,
187    touched,
188    unplanned: ledger.unplanned.filter(u => !u.acknowledged).map(u => ({ file: u.file, at: u.at, task: u.task })),
189    intents: ledger.intents,
190    semantic: ledger.semantic,
191    semanticHistory: ledger.semanticHistory.slice(-MAX_HISTORY),
192    verification: ledger.verification,
193    acceptance: ledger.acceptance,
194    assumed: ledger.assumed ?? {},
195    approvals: ledger.approvals,
196    decisions: ledger.decisions,
197    anchors: ledger.anchors,
198    checkpoints: ledger.checkpoints,
199    fingerprintVersion: FINGERPRINT_VERSION,
200  }
201  return { committed: JSON.stringify(committed, null, 2) + '\n', local: JSON.stringify(local, null, 2) + '\n' }
202}
203
204/**
205 * §6: a fingerprint stored by the pre-0.5.0 parser (one physical line per requirement) moves to today's text, and so
206 * do the spec approval and the analyze checkpoint taken over that reading. Only a value equal to the old reading of
207 * the same spec moves; any other stays, since it is a real change.
208 */
209export function rebaseline(ledger: Ledger, specMd: string | null): Ledger {
210  if (ledger.fingerprintVersion >= FINGERPRINT_VERSION || !specMd) return { ...ledger, fingerprintVersion: FINGERPRINT_VERSION }
211  const now = parseSpec(specMd)
212  const old = parseSpec(specMd, { wrap: false })
213  const oldText = new Map(old.reqs.map(r => [r.id, r.text]))
214  const nowText = new Map(now.reqs.map(r => [r.id, r.text]))
215  const moved = (id: string, stored: string) => (oldText.has(id) && nowText.has(id) && stored === fingerprint(oldText.get(id)!) ? fingerprint(nowText.get(id)!) : stored)
216  const oldSpec = specFingerprint(old)
217  const nowSpec = specFingerprint(now)
218  return {
219    ...ledger,
220    fingerprints: Object.fromEntries(Object.entries(ledger.fingerprints).map(([id, fp]) => [id, moved(id, fp)])),
221    verification: Object.fromEntries(Object.entries(ledger.verification).map(([id, v]) => [id, { ...v, fingerprint: moved(id, v.fingerprint) }])),
222    approvals: ledger.approvals.spec === oldSpec ? { ...ledger.approvals, spec: nowSpec } : ledger.approvals,
223    checkpoints: ledger.checkpoints.analyze === oldSpec ? { ...ledger.checkpoints, analyze: nowSpec } : ledger.checkpoints,
224    fingerprintVersion: FINGERPRINT_VERSION,
225  }
226}
227