Skip to main content

speccoder_core/
codes.rs

1//! Stable codes for every result that is not plainly `ok`:
2//! what went wrong, why it matters, how to fix it and where it is
3//! documented. A script branches on the code, a person reads the fix.
4//!
5//! Every non-ok status has a default code, so no result leaves without
6//! one; a call site that knows the cause better names a specific code with
7//! the same status.
8
9use crate::command::CommandStatus;
10
11/// How a code presents itself.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, schemars::JsonSchema)]
13#[serde(rename_all = "snake_case")]
14pub enum Kind {
15    /// Something failed: `error[CODE]`.
16    Error,
17    /// The run waits for a person: `stopped[CODE]`.
18    Stop,
19    /// It worked, with less than the full evidence: `warning[CODE]`.
20    Warning,
21}
22
23impl Kind {
24    /// `error`, `stopped` or `warning`: the human prefix.
25    #[must_use]
26    pub const fn prefix(self) -> &'static str {
27        match self {
28            Self::Error => "error",
29            Self::Stop => "stopped",
30            Self::Warning => "warning",
31        }
32    }
33}
34
35/// One code of the catalog.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub struct Entry {
38    /// `GIT-DIRTY`: upper-case words joined by hyphens.
39    pub name: &'static str,
40    /// Error, stop or warning.
41    pub kind: Kind,
42    /// The status results with this code have.
43    pub status: CommandStatus,
44    /// One line: why it matters (lowercase start, no period).
45    pub title: &'static str,
46    /// What it means and why it happens.
47    pub explain: &'static str,
48    /// How to resolve it: commands (`{task}`, `{feature}`, `{command}` are
49    /// filled from the result), or `→ ` lines for a person.
50    pub fix: &'static [&'static str],
51}
52
53/// Where the codes are documented.
54pub const DOCS: &str = "https://hupe1980.github.io/speccoder/docs/codes/";
55
56impl Entry {
57    /// The code's section on the codes page.
58    #[must_use]
59    pub fn docs(&self) -> String {
60        format!("{DOCS}#{}", self.name.to_ascii_lowercase())
61    }
62}
63
64use CommandStatus as S;
65use Kind::{Error as E, Stop as P, Warning as W};
66
67macro_rules! entry {
68    ($name:literal, $kind:expr, $status:expr, $title:literal, $explain:literal, [$($fix:literal),+ $(,)?]) => {
69        Entry { name: $name, kind: $kind, status: $status, title: $title, explain: $explain, fix: &[$($fix),+] }
70    };
71}
72
73/// Every code speccoder uses.
74pub const CATALOG: &[Entry] = &[
75    // ── usage ─────────────────────────────────────────────────────────
76    entry!(
77        "USAGE",
78        E,
79        S::UsageError,
80        "the arguments are not valid for this command",
81        "The command line could not be parsed: an unknown flag, a missing value, or a value outside the allowed set.",
82        ["speccoder {command} --help"]
83    ),
84    entry!(
85        "USAGE-CONFLICT",
86        E,
87        S::UsageError,
88        "two options were given that exclude each other",
89        "`--json` prints one result object and `--events` prints a stream of events ending in that object; a command does one or the other.",
90        ["speccoder {command} --events", "speccoder {command} --json"]
91    ),
92    entry!(
93        "USAGE-UNKNOWN-CODE",
94        E,
95        S::UsageError,
96        "there is no code by that name",
97        "`speccoder explain` knows the codes speccoder itself prints; the closest names are listed with the error.",
98        ["speccoder explain --list"]
99    ),
100    entry!(
101        "CALL-CHANGED",
102        E,
103        S::UsageError,
104        "the call waiting now is not the one that was shown",
105        "An approval or rejection from an interface names the call it showed and that call's object. The call expired or was decided and another waits now, or the attempt stopped on another object; nothing was decided.",
106        ["speccoder report --approvals"]
107    ),
108    // ── internal ──────────────────────────────────────────────────────
109    entry!(
110        "INTERNAL",
111        E,
112        S::Error,
113        "speccoder failed in a way it does not expect",
114        "An unexpected failure inside speccoder: an IO error, a broken state file, a bug. The message says what failed.",
115        ["→ re-run with -v and report the output at https://github.com/hupe1980/speccoder/issues"]
116    ),
117    // ── project ───────────────────────────────────────────────────────
118    entry!(
119        "NO-PROJECT",
120        E,
121        S::NotAProject,
122        "speccoder works on a Spec Kit or OpenSpec project, and found none here",
123        "No `.specify/` (Spec Kit) or `openspec/` (OpenSpec) directory was found here or above. Spec Kit makes one (`--integration claude` installs the skills speccoder runs); then `speccoder init` and `speccoder spec specify` take it from there.",
124        ["specify init --here --integration claude", "openspec init"]
125    ),
126    entry!(
127        "SPEC-DIAGNOSTICS",
128        E,
129        S::DiagnosticsError,
130        "the spec artifacts have errors speccoder will not guess around",
131        "The task list or spec could not be read as written: a dependency on a task that does not exist, a cycle, a malformed task line. `inspect` lists every diagnostic with its line.",
132        ["speccoder inspect"]
133    ),
134    entry!(
135        "FEATURE-SELECTION",
136        E,
137        S::SelectionNeeded,
138        "more than one feature could be meant",
139        "Several features exist and none is current: neither `--feature`, the format's variable nor its pointer (Spec Kit: `.specify/feature.json`) names one. Make one current, or name it for this command.",
140        [
141            "speccoder feature",
142            "speccoder feature <name>",
143            "speccoder {command} --feature <name>"
144        ]
145    ),
146    entry!(
147        "CHECK-BROKEN",
148        E,
149        S::ConfigError,
150        "a check cannot run on the untouched code",
151        "A fast check failed on the untouched worktree without running a test: a command or profile it names is missing, a file it needs was never committed, or it does not build. It could never judge the task, so nothing was attempted.",
152        [
153            "speccoder doctor",
154            "git status",
155            "speccoder run --allow-failing-baseline"
156        ]
157    ),
158    entry!(
159        "FEATURE-GONE",
160        E,
161        S::SelectionNeeded,
162        "the current feature no longer exists",
163        "The format's pointer (Spec Kit: `.specify/feature.json`) or its variable names a feature directory that is not there — renamed, deleted, or from another checkout.",
164        [
165            "speccoder feature",
166            "speccoder feature <name>",
167            "speccoder feature --clear"
168        ]
169    ),
170    entry!(
171        "REVIEW-PENDING",
172        P,
173        S::NeedsHuman,
174        "the spec is not approved yet",
175        "`[review] required` is on: a run waits until every requirement of the spec is approved on its current wording, in the review committed with it (`review.json`). A requirement reworded since its approval needs approving again.",
176        ["speccoder review", "speccoder review approve", "git commit"]
177    ),
178    entry!(
179        "REVIEW-AMBIGUOUS",
180        P,
181        S::NeedsHuman,
182        "two readings of a requirement disagree",
183        "Two independent test authors read a scenario two ways (the same given, different expected outcomes). Until you choose a reading or reword the requirement, it is not approved, its tests are not frozen, and a gated run (`[review] required`) waits.",
184        [
185            "speccoder review tests <REQ> --reading A <scenario>",
186            "speccoder review tests <REQ> --reading B <scenario>",
187            "→ or reword the scenario so it reads one way"
188        ]
189    ),
190    entry!(
191        "REVIEW-NO-SCENARIOS",
192        E,
193        S::UsageError,
194        "the requirement has no scenarios to write tests from",
195        "Tests are written at review per requirement from its acceptance scenarios. The requirement named has none (or the format yields no requirement by that key), so there is nothing to derive a test from.",
196        [
197            "speccoder review",
198            "→ add acceptance scenarios to the requirement"
199        ]
200    ),
201    entry!(
202        "REVIEW-TESTS-OWN-PIPELINE",
203        E,
204        S::UsageError,
205        "this unit's tests are written by its own pipeline",
206        "A quick change writes its own tests and a bug's reproductions are confirmed by you; review writes no second set for them.",
207        ["speccoder do \"…\"", "speccoder bug confirm <unit>/<task>"]
208    ),
209    entry!(
210        "ACCEPTANCE-OFF",
211        E,
212        S::ConfigError,
213        "acceptance tests are turned off",
214        "`[acceptance] generate = false`: no acceptance tests are written, at review or at run time.",
215        ["speccoder config set acceptance.generate true"]
216    ),
217    entry!(
218        "ORACLE-AUTHOR-FAILED",
219        E,
220        S::RunFailed,
221        "the test author could not write the tests",
222        "The acceptance author call failed or the model provider refused it. Nothing was stored or frozen for the requirement; the message carries the provider's reason.",
223        ["speccoder review tests <REQ> --write"]
224    ),
225    entry!(
226        "ORACLE-TAMPERED",
227        P,
228        S::NeedsHuman,
229        "a frozen test no longer matches what was frozen",
230        "A test frozen at review is stored in the state directory with its digest. The stored file or its record no longer matches: reusing it would run tests nobody approved, so the task stops and nothing is ticked.",
231        [
232            "speccoder review tests <REQ>",
233            "→ write and approve the tests again, or run without the frozen set"
234        ]
235    ),
236    entry!(
237        "ORACLE-FROZEN",
238        E,
239        S::UsageError,
240        "the requirement's tests are frozen with the approval",
241        "*Approve and Run* froze these tests and their held-out set, so they cannot be changed. Reword the requirement to lapse the freeze and write them again.",
242        [
243            "speccoder review",
244            "→ reword the requirement to lapse the freeze, then write its tests again"
245        ]
246    ),
247    entry!(
248        "REVIEW-CHANGED",
249        P,
250        S::NeedsHuman,
251        "what the approval would freeze changed since it was shown",
252        "What the approval sheet showed changed before the click (another tab asked again, a *Write Tests* finished). Nothing was approved; look again and approve what you see.",
253        [
254            "speccoder review",
255            "→ open the sheet again and approve what it shows"
256        ]
257    ),
258    entry!(
259        "REVIEW-UNREADABLE",
260        P,
261        S::NeedsHuman,
262        "the review record cannot be read",
263        "`review.json` (decisions, frozen tests, approval) or a record beside it is not valid. Reading it as empty would drop every decision and freeze, so speccoder stops until you look.",
264        [
265            "git diff -- <unit>/review.json",
266            "→ restore it from git (`git checkout -- <unit>/review.json`) or fix the JSON"
267        ]
268    ),
269    entry!(
270        "RUN-ACTIVE",
271        E,
272        S::GitPrecondition,
273        "a run is active for this project",
274        "*Approve and Run* starts a feature run; one is running already (in a terminal or the web app). Approving now would start a second run beside it.",
275        ["speccoder report", "→ wait for the run to end, or stop it"]
276    ),
277    entry!(
278        "AUTOPILOT-NEEDS-GRANT-OBJECTS",
279        E,
280        S::ConfigError,
281        "autopilot needs object-bound grants",
282        "Autopilot holds only grants the person saw in full and ticked, each bound to one resolved object (a canonical path, an exact argv, an MCP tool digest). This build has no such grants, so autopilot is off.",
283        ["speccoder review approve --run ask"]
284    ),
285    entry!(
286        "FEATURE-UNKNOWN",
287        E,
288        S::SelectionNeeded,
289        "no feature has that name or number",
290        "`--feature` (or `--change`) names a feature by its directory name, a part of it, or its number in `speccoder feature`'s list; none matches what was given.",
291        ["speccoder feature", "speccoder report --feature <name>"]
292    ),
293    // ── configuration ─────────────────────────────────────────────────
294    entry!(
295        "CONFIG",
296        E,
297        S::ConfigError,
298        "the configuration or the environment is not usable",
299        "`speccoder.toml` or the environment does not allow this command to run; the message names what is wrong.",
300        ["speccoder init"]
301    ),
302    entry!(
303        "NO-STATE-DIR",
304        E,
305        S::ConfigError,
306        "speccoder has nowhere to keep its state",
307        "Journals, worktrees and live progress live in a state directory: `$SPECCODER_STATE_DIR`, else `$XDG_STATE_HOME/speccoder`, else `~/.local/state/speccoder`. None of these variables is set.",
308        ["export SPECCODER_STATE_DIR=\"$PWD/.speccoder-state\""]
309    ),
310    entry!(
311        "SANDBOX-UNAVAILABLE",
312        E,
313        S::ConfigError,
314        "the OS sandbox is not available and the project requires it",
315        "No OS sandbox is available (Linux without Landlock, a container without user namespaces, another OS) while `[sandbox] mode = \"required\"` or an autopilot run needs one.",
316        [
317            "→ run on macOS or Linux 6.2+ (Landlock ABI 3)",
318            "→ or set [sandbox] mode = \"auto\" to run unsandboxed and be told",
319            "→ autopilot: choose Ask on Risky Calls, or enable the OS sandbox"
320        ]
321    ),
322    entry!(
323        "GITHUB-AUTH",
324        E,
325        S::Error,
326        "not signed in to GitHub",
327        "No GitHub token was found (GH_TOKEN, GITHUB_TOKEN, or the one `speccoder auth login` keeps in your keychain), or GitHub refused it.",
328        [
329            "speccoder auth login --with-token",
330            "speccoder auth status",
331            "→ or set GH_TOKEN (a fine-grained token: Issues read; Pull requests read and write; Contents and Metadata read)"
332        ]
333    ),
334    entry!(
335        "GITHUB-FAILED",
336        E,
337        S::Error,
338        "the GitHub API could not do it",
339        "GitHub answered, and not as asked: no such issue, no access for the token, a rate limit used up, or GitHub did not answer in time. The message is GitHub's, in words.",
340        ["speccoder auth status", "git remote -v"]
341    ),
342    entry!(
343        "CONFIG-EXISTS",
344        E,
345        S::ConfigError,
346        "the project has a speccoder.toml already",
347        "`init` writes a new one; change the existing one with `speccoder config` (or Settings), or start over with `--force`.",
348        ["speccoder config", "speccoder init --force"]
349    ),
350    entry!(
351        "CONFIG-MISSING",
352        E,
353        S::ConfigError,
354        "the project has no speccoder.toml",
355        "speccoder needs to know which checks decide \"nothing regressed\" and which model to use; `init` detects them and writes a commented file.",
356        ["speccoder init"]
357    ),
358    entry!(
359        "CONFIG-INVALID",
360        E,
361        S::ConfigError,
362        "speccoder.toml has an error",
363        "An unknown section or key, a wrong type, or a value outside the allowed set. Unknown keys are errors so a typo never goes unnoticed.",
364        ["→ fix the line the message names in speccoder.toml, then commit it"]
365    ),
366    entry!(
367        "KEY-MISSING",
368        E,
369        S::ConfigError,
370        "the model provider's API key is not in the environment",
371        "speccoder reads API keys from the environment only. The message names the variable the configured provider needs.",
372        ["→ export the variable the message names, e.g. export ANTHROPIC_API_KEY=…"]
373    ),
374    entry!(
375        "NO-CHECKS",
376        E,
377        S::ConfigError,
378        "no check applies, so nothing could show that nothing regressed",
379        "Every configured check was skipped (`when_exists` did not match) or none is configured. A task cannot be judged without at least one check: add your test command as one.",
380        ["speccoder config set checks.test.argv -- <your test command>"]
381    ),
382    // ── git ───────────────────────────────────────────────────────────
383    entry!(
384        "GIT",
385        E,
386        S::GitPrecondition,
387        "git is not in the state this command needs",
388        "A git precondition does not hold; the message names it.",
389        ["git status"]
390    ),
391    entry!(
392        "SETUP-INCOMPLETE",
393        E,
394        S::GitPrecondition,
395        "the project's setup is not committed, so every run would trip over it",
396        "A worktree holds only commits: a file the checks need but the checkout never committed (`speccoder.toml`, `.config/nextest.toml`), a lockfile the checks write, or build output `.gitignore` does not list. `speccoder fix` commits that setup once.",
397        ["speccoder fix"]
398    ),
399    entry!(
400        "NO-REPOSITORY",
401        E,
402        S::GitPrecondition,
403        "speccoder needs a git repository with at least one commit",
404        "Evidence lives in commits and refs, and work happens on a branch of its own, so the project must be a git repository with a first commit.",
405        ["git init && git add -A && git commit -m init"]
406    ),
407    entry!(
408        "UNCOMMITTED-INTENT",
409        E,
410        S::GitPrecondition,
411        "the spec has uncommitted changes the run would not see",
412        "speccoder reads committed files only — a worktree is checked out from a commit — so an uncommitted edit to the spec, plan or tasks would silently not count.",
413        ["git status", "speccoder run --in-place"]
414    ),
415    entry!(
416        "NO-REMOTE",
417        E,
418        S::GitPrecondition,
419        "there is no git remote to push to",
420        "`pr` pushes `speccoder/<feature>` to a remote and opens the pull request there; `issue` reads the remote's GitHub issues. Add the repository's GitHub address as a remote, or name the one to use.",
421        [
422            "git remote add origin <url>",
423            "git remote -v",
424            "speccoder pr --remote <name>"
425        ]
426    ),
427    entry!(
428        "WORKTREE-DIRTY",
429        E,
430        S::GitPrecondition,
431        "the feature's worktree has uncommitted changes",
432        "Work left in the worktree outside a commit — a failed attempt's, or an edit by hand — would be mixed into what comes next.",
433        ["speccoder worktree", "speccoder run --feature {feature}"]
434    ),
435    entry!(
436        "NOTHING-TO-HAND-OFF",
437        E,
438        S::GitPrecondition,
439        "the speccoder branch has nothing the base does not have",
440        "`pr` hands off work on `speccoder/<feature>`; there is none yet, or it is already merged.",
441        ["speccoder run --feature {feature}"]
442    ),
443    // in place
444    entry!(
445        "DIRTY-CHECKOUT",
446        E,
447        S::GitPrecondition,
448        "an in-place run needs a clean checkout",
449        "In place, the attempt runs in your checkout; uncommitted changes would be judged as the agent's.",
450        ["git stash -u", "git commit -am wip"]
451    ),
452    entry!(
453        "UNBORN-HEAD",
454        E,
455        S::GitPrecondition,
456        "the checkout has no commit yet",
457        "An in-place run branches from HEAD; there is no HEAD to branch from.",
458        ["git add -A && git commit -m init"]
459    ),
460    entry!(
461        "CONFIG-NOT-TRACKED",
462        E,
463        S::GitPrecondition,
464        "speccoder.toml must be committed",
465        "The judge's configuration is a reviewed input; an untracked or modified one could be changed without review.",
466        ["git add speccoder.toml && git commit -m \"speccoder: config\""]
467    ),
468    entry!(
469        "BRANCH-IN-WORKTREE",
470        E,
471        S::GitPrecondition,
472        "the feature's branch is checked out in a worktree",
473        "git refuses to check out a branch twice; an in-place run needs `speccoder/<feature>` free.",
474        ["git worktree list", "git worktree remove <path>"]
475    ),
476    entry!(
477        "IN-PLACE-ACTIVE",
478        E,
479        S::GitPrecondition,
480        "an in-place run holds this checkout",
481        "Another in-place session is active (or was killed); it owns the checkout until it ends or is left.",
482        [
483            "speccoder run --in-place",
484            "speccoder run --in-place --return"
485        ]
486    ),
487    entry!(
488        "IN-PLACE-SESSION",
489        E,
490        S::GitPrecondition,
491        "an in-place session is recorded for this checkout",
492        "A worktree-mode command would not see what the in-place session holds.",
493        [
494            "speccoder run --in-place",
495            "speccoder run --in-place --return"
496        ]
497    ),
498    entry!(
499        "IN-PLACE-PARALLEL",
500        E,
501        S::UsageError,
502        "an in-place run works one task at a time",
503        "Parallel lanes need worktrees of their own; in place there is only your checkout.",
504        ["speccoder run --in-place", "speccoder run --parallel 2"]
505    ),
506    entry!(
507        "MERGE-CONFLICT",
508        E,
509        S::GitPrecondition,
510        "the checkout is in the middle of a merge or rebase",
511        "An in-place run cannot start or return while git waits for a conflict to be resolved.",
512        ["git status", "git merge --abort"]
513    ),
514    entry!(
515        "INTENT-CHANGED",
516        P,
517        S::NeedsHuman,
518        "the spec, plan or tasks changed during the run",
519        "Intent files are hashed when an in-place run starts and compared before every task; a change means the work would be judged against a spec it was not given.",
520        ["git diff", "speccoder run --in-place"]
521    ),
522    entry!(
523        "JUDGE-CHANGED",
524        P,
525        S::NeedsHuman,
526        "the judge's inputs changed during the run",
527        "Checks, test configuration or agent configuration changed after the run started; a verdict under changed rules would mean nothing.",
528        ["git diff", "speccoder run --in-place"]
529    ),
530    entry!(
531        "CHECKOUT-CHANGED",
532        P,
533        S::NeedsHuman,
534        "the checkout moved under the run",
535        "HEAD, the branch or the tree is not where speccoder left it; someone or something else changed the checkout.",
536        ["git status", "speccoder run --in-place --return"]
537    ),
538    entry!(
539        "GIT-CHANGED",
540        P,
541        S::NeedsHuman,
542        "git's configuration, hooks or refs changed during the run",
543        "Where the sandbox cannot keep `.git` read-only, speccoder fingerprints it; a change stops the run before the next tick.",
544        [
545            "git config --list --show-origin",
546            "speccoder run --in-place --return"
547        ]
548    ),
549    entry!(
550        "RETURN-BLOCKED",
551        P,
552        S::NeedsHuman,
553        "the in-place run cannot switch back to your branch",
554        "Switching back would overwrite changes or fail; the session stays until the checkout allows it.",
555        ["git status", "speccoder run --in-place --return"]
556    ),
557    // ── tasks ─────────────────────────────────────────────────────────
558    entry!(
559        "NOT-FOUND",
560        E,
561        S::NotFound,
562        "nothing by that name exists",
563        "No task, run, call or object matches what was asked for; the message names it.",
564        ["speccoder report"]
565    ),
566    entry!(
567        "NOT-FOUND-SCHEMA",
568        E,
569        S::NotFound,
570        "there is no schema by that name",
571        "`speccoder schema` lists the schemas speccoder publishes.",
572        ["speccoder schema"]
573    ),
574    entry!(
575        "TASK-NOT-READY",
576        E,
577        S::TaskNotReady,
578        "no task can run now",
579        "The task is done, or waits for tasks it depends on.",
580        ["speccoder report"]
581    ),
582    entry!(
583        "NO-TASKS",
584        E,
585        S::TaskNotReady,
586        "the feature has no tasks yet",
587        "Its task list is not written yet, or lists no task: nothing ran, and the feature is not done. The spec format's planning skills write the tasks; `speccoder report` names the next one.",
588        ["speccoder report"]
589    ),
590    entry!(
591        "TASK-DONE",
592        E,
593        S::TaskNotReady,
594        "the task is already ticked",
595        "A ticked task is not run again; its evidence is in its commit.",
596        ["speccoder report"]
597    ),
598    entry!(
599        "TASK-BLOCKED",
600        E,
601        S::TaskNotReady,
602        "the task waits for tasks it depends on",
603        "Dependencies come from the task list's phases, `[P]` markers and explicit references; the message names the open ones.",
604        [
605            "speccoder run --feature {feature}",
606            "speccoder task skip <dependency> --reason \"…\""
607        ]
608    ),
609    // ── verdicts ──────────────────────────────────────────────────────
610    entry!(
611        "VERIFICATION-FAILED",
612        E,
613        S::VerificationFailed,
614        "the checks or the acceptance tests did not pass",
615        "After the retries, a check regressed or the spec-derived acceptance tests did not go from red to green. The attempt is saved under its ref.",
616        [
617            "speccoder report",
618            "speccoder task nudge {task} --note \"…\""
619        ]
620    ),
621    entry!(
622        "REGRESSION-ONLY",
623        W,
624        S::Ok,
625        "ticked on the regression checks alone, nothing task-specific was shown",
626        "The checks still pass, but no acceptance test showed this task's behaviour. It is ticked `regression_only`, never `verified`, with one recorded reason: `no_story` (no user story to derive a test from), `no_scenarios` (its story states no acceptance scenario), `acceptance_off` (`[acceptance] generate = false`), `author_wrote_none` (the test author wrote no test), `author_failed` (its tests could not be used), `already_passing` (they passed before the attempt — with the task that implemented it), `not_red` (they did not fail on an assertion first) or `tests_not_collected` (the command collected no test).",
627        [
628            "→ add an acceptance example to the task's story, then converge",
629            "speccoder converge --feature {feature}"
630        ]
631    ),
632    entry!(
633        "ATTESTATION-FAILED",
634        E,
635        S::AttestationFailed,
636        "an attestation is missing, unsigned where required, or does not hold",
637        "`attest verify` found a tick whose signed statements are missing, malformed, edited, about another commit, or signed by no one you trust.",
638        ["speccoder attest verify --feature {feature} --json"]
639    ),
640    entry!(
641        "TESTS-NOT-COLLECTED",
642        E,
643        S::VerificationFailed,
644        "a test file the attempt wrote never ran",
645        "The attempt added or changed a test file, but the runner collected no test from it: the toolchain's rule says it is never built or picked up (a Rust file no target declares, a pytest file outside `python_files`, a vitest file outside `include`, a Go file under `testdata/`), or the run's report and listing hold none of its tests. A test that never ran is evidence of nothing, so the verdict fails and the retry is told the rule.",
646        [
647            "speccoder report",
648            "→ move the tests where the runner collects them (the reason names the rule)"
649        ]
650    ),
651    entry!(
652        "PLAN-TESTS-UNCOLLECTED",
653        W,
654        S::Ok,
655        "the plan puts tests where the runner won't collect them",
656        "A task names a test path the project's runner would not collect (Cargo builds only `tests/*.rs` and `tests/<dir>/main.rs`), and no task creates the file that would declare it; or a test file in the tree is collected by nothing. Tests written there would never run. A warning: the run is not stopped.",
657        [
658            "speccoder doctor --feature {feature}",
659            "speccoder spec tasks"
660        ]
661    ),
662    entry!(
663        "PLAN-BEHAVIOUR-EARLY",
664        W,
665        S::Ok,
666        "a story's behaviour is planned before the story",
667        "A Setup or Foundational task names a symbol a user story is about. If that task implements it, the story's acceptance tests already pass when the story's tasks run: they cannot go red, and the tasks tick regression-only. Write the story's acceptance tests at that task, or re-plan.",
668        [
669            "speccoder task acceptance-at {task} --story <US>",
670            "speccoder spec tasks"
671        ]
672    ),
673    entry!(
674        "PLAN-TEST-ONLY-TASKS",
675        W,
676        S::Ok,
677        "tasks that only write tests",
678        "A story has tasks whose only outputs are test files next to the task that implements it. speccoder writes each story's acceptance tests itself and judges the implementing task by them; a test-only task has nothing of its own to show and ticks regression-only.",
679        ["speccoder spec tasks"]
680    ),
681    entry!(
682        "PRESET-NOT-SPECKIT",
683        E,
684        S::UsageError,
685        "presets are a Spec Kit mechanism",
686        "`speccoder preset add` installs the speccoder preset through Spec Kit's own `specify preset add`; this project is not a Spec Kit project, so there is nothing to add it to.",
687        ["speccoder doctor"]
688    ),
689    entry!(
690        "PRESET-SPECKIT-MISSING",
691        E,
692        S::ConfigError,
693        "the Spec Kit tool `specify` is missing or too old",
694        "Adding the preset runs `specify preset add`, which needs `specify` at the version the preset requires. It is not installed, or older.",
695        [
696            "→ install or upgrade Spec Kit (`uv tool install specify-cli`)",
697            "speccoder doctor"
698        ]
699    ),
700    entry!(
701        "PRESET-FAILED",
702        E,
703        S::Error,
704        "the preset could not be added: `specify preset add` failed",
705        "Spec Kit refused or failed to install the preset; its own output is shown. Nothing in `specs/` was changed.",
706        ["speccoder preset add", "speccoder doctor"]
707    ),
708    // ── a new project, the sample ─────────────────────────────────────
709    entry!(
710        "NEW-PLAN-CHANGED",
711        E,
712        S::UsageError,
713        "the plan changed since you saw it; nothing ran",
714        "Creating a project runs exactly the plan you confirmed, bound to its digest: the commands, their order and the folder as it was seen. A tool's version or the folder's contents changed meanwhile, so the plan computed now differs and nothing was run. The result carries the new plan.",
715        ["→ review the new plan and confirm it again"]
716    ),
717    entry!(
718        "NEW-TARGET-NOT-EMPTY",
719        E,
720        S::UsageError,
721        "the folder is not empty and not a git repository",
722        "A new project starts in an empty folder, or in a git repository at its top level with a clean tree. This folder holds files that are not under git, which the format's `--force` init could overwrite unseen.",
723        [
724            "→ choose an empty folder",
725            "→ or run `git init` there and commit what it holds first"
726        ]
727    ),
728    entry!(
729        "NEW-DIRTY",
730        E,
731        S::GitPrecondition,
732        "the repository has uncommitted changes",
733        "speccoder commits exactly what the plan's steps produced. With changes of yours in the tree, the two could not be told apart, so the folder must be clean first.",
734        ["→ commit or stash your changes, then try again"]
735    ),
736    entry!(
737        "NEW-NESTED-REPOSITORY",
738        E,
739        S::GitPrecondition,
740        "the folder is inside another repository",
741        "A project is created at a repository's top level. This folder lies inside another repository's worktree; a second repository inside it, or a project in its subfolder, would split one history.",
742        ["→ choose a folder outside it, or use the repository's top level"]
743    ),
744    entry!(
745        "NEW-ALREADY-PROJECT",
746        E,
747        S::UsageError,
748        "the folder already holds a spec project",
749        "There is nothing to create: the folder is a project of a spec format already. Open it instead.",
750        ["speccoder ui", "speccoder init"]
751    ),
752    entry!(
753        "NEW-TOOL-MISSING",
754        E,
755        S::ConfigError,
756        "a tool the plan needs is not installed",
757        "The plan runs the ecosystems' own tools — the stack's scaffold and the spec format's init. One of them is not on the PATH; the message names it and how to install it.",
758        [
759            "→ install the tool, or choose another stack or format",
760            "speccoder doctor"
761        ]
762    ),
763    entry!(
764        "NEW-STEP-FAILED",
765        E,
766        S::Error,
767        "a step of the plan failed; later steps did not run",
768        "A command of the plan exited with an error, timed out or was denied by the sandbox. The steps before it are kept; running the same plan again resumes at this step.",
769        ["→ retry, or run the command yourself as shown"]
770    ),
771    entry!(
772        "NEW-NO-IDENTITY",
773        E,
774        S::GitPrecondition,
775        "git does not know who you are",
776        "The new project's one commit is yours, made with your git identity; speccoder never invents one. `user.name` or `user.email` is not set.",
777        [
778            "→ git config --global user.name \"Your Name\"",
779            "→ git config --global user.email you@example.com"
780        ]
781    ),
782    entry!(
783        "NEW-IN-PROGRESS",
784        E,
785        S::UsageError,
786        "a new project is being created in this folder",
787        "Another creation of a project in the same folder is running. Two at once would interleave their steps.",
788        ["→ wait for it to finish"]
789    ),
790    entry!(
791        "NEW-UNDO-REFUSED",
792        E,
793        S::GitPrecondition,
794        "the project changed since speccoder created it; nothing was undone",
795        "Undo moves a folder speccoder created to the Trash, or reverts speccoder's commit in an existing repository — only while nothing but that commit exists. Something changed since (the message lists what), or there is no Trash on this system; nothing was moved or deleted.",
796        ["→ undo it yourself; nothing was moved"]
797    ),
798    entry!(
799        "SAMPLE-DIVERGED",
800        E,
801        S::ReplayDiverged,
802        "this build cannot reproduce the sample's recorded run",
803        "The sample is a recorded run replayed strictly. This build replayed it to a different result, so it is not shown as if it had worked: the board shows the sample's committed state only.",
804        ["speccoder doctor --bug-report"]
805    ),
806    entry!(
807        "SAMPLE-MISSING",
808        E,
809        S::NotFound,
810        "this build has no sample",
811        "The sample's recording is not part of this build: release builds bundle it; a build from source has it only when `crates/speccoder-runtime/assets/sample/` holds one (`just record-sample`).",
812        ["→ install a release build", "speccoder new"]
813    ),
814    entry!(
815        "SIMILAR-FEATURE",
816        W,
817        S::Ok,
818        "an existing requirement is close to this description",
819        "Before the spec is written, the description is compared with every feature's requirements by a deterministic text similarity. A close match may mean the change belongs in that feature; it is a hint and never stops the skill.",
820        [
821            "speccoder feature similar \"…\"",
822            "speccoder review comments"
823        ]
824    ),
825    // ── stops ─────────────────────────────────────────────────────────
826    entry!(
827        "NEW-CONFIRM",
828        P,
829        S::NeedsHuman,
830        "the plan needs your confirmation; nothing ran",
831        "`speccoder new` runs commands in a folder; it runs them only after you saw them. Without a terminal to ask at, it printed the plan and stopped.",
832        ["→ run the same command again with --yes"]
833    ),
834    entry!(
835        "THROUGH-QUESTIONS",
836        P,
837        S::NeedsHuman,
838        "the spec has open questions; planning waits for your answers",
839        "The format's skill wrote the spec and left questions it could not decide. Planning on a guess would plan the wrong thing, so the chain stops until each is answered.",
840        ["speccoder review", "speccoder review answer Q1 \"…\""]
841    ),
842    entry!(
843        "THROUGH-REVIEW",
844        P,
845        S::NeedsHuman,
846        "review the spec; planning waits for your approval",
847        "Plan through stops after the spec is written: its requirements are what every task will be judged by, so they are planned only once you approved them. No flag passes this stop.",
848        ["speccoder review", "speccoder review approve"]
849    ),
850    entry!(
851        "NEEDS-HUMAN",
852        P,
853        S::NeedsHuman,
854        "the run stopped for a person",
855        "The run cannot go on without a decision; the message says what waits.",
856        ["speccoder report"]
857    ),
858    entry!(
859        "NEEDS-APPROVAL",
860        P,
861        S::NeedsHuman,
862        "a call waits for a person's decision; nothing ran",
863        "The model asked for something the policy does not allow on its own — a dependency change, the network, a protected file. The attempt waits; deciding continues it from that call.",
864        [
865            "speccoder report --approvals",
866            "speccoder task approve {task}",
867            "speccoder task reject {task} --reason \"…\""
868        ]
869    ),
870    entry!(
871        "BLOCKED",
872        P,
873        S::NeedsHuman,
874        "the model says the task cannot be done as written",
875        "The model used its honest exit: something in the spec or the code stops it. Its reason is a claim, shown as \"Model says\".",
876        [
877            "speccoder task nudge {task} --note \"…\"",
878            "speccoder task skip {task} --reason \"…\""
879        ]
880    ),
881    entry!(
882        "BUDGET-EXHAUSTED",
883        P,
884        S::NeedsHuman,
885        "the attempt ran out of turns, calls or tokens",
886        "The attempt reached a limit of `[budget]` before finishing. The work so far is saved under the attempt's ref.",
887        [
888            "speccoder task nudge {task} --note \"…\"",
889            "→ raise the limit in speccoder.toml [budget]"
890        ]
891    ),
892    entry!(
893        "NOT-DEMONSTRATED",
894        P,
895        S::NeedsHuman,
896        "the evidence the task needs could not be produced",
897        "The acceptance tests could not be made red before the attempt (they already pass, or fail for another reason), or a convergence gap shows in no failing test. Ticking would claim more than was shown.",
898        [
899            "speccoder report",
900            "speccoder task accept {task} --reason \"…\""
901        ]
902    ),
903    entry!(
904        "TESTS-COLLECTION-UNKNOWN",
905        P,
906        S::NeedsHuman,
907        "speccoder cannot tell whether the runner ran a test file",
908        "The attempt changed a test file, and neither the toolchain's static rule, the check's JUnit report nor the runner's listing says whether a test from it ran (an unrecognised runner, a listing that failed or timed out, no report). A tick on tests that may not have run would claim more than was shown, so the task stops; the attempt is saved under its ref. It is not retried: the model cannot fix it.",
909        [
910            "→ declare a JUnit report for the check (`junit = \"…\"`)",
911            "→ set the check's `list` command in speccoder.toml",
912            "speccoder task accept {task} --reason \"…\""
913        ]
914    ),
915    entry!(
916        "ACCEPTANCE-UNWRITTEN",
917        P,
918        S::NeedsHuman,
919        "the acceptance tests could not be written, so nothing was attempted",
920        "The call that writes acceptance tests from the spec failed (no credits, a rejected key, a broken run). Without them the task would be judged on regression checks only, so it stops.",
921        [
922            "speccoder run --feature {feature}",
923            "→ or set [acceptance] generate = false to rely on the checks alone"
924        ]
925    ),
926    entry!(
927        "SUSPECTED-GAMING",
928        P,
929        S::NeedsHuman,
930        "the gaming monitor suspects a shortcut",
931        "A separate review of the passing attempt found something like a hard-coded result or a weakened test. The task stays unticked until a person decides.",
932        [
933            "speccoder report",
934            "speccoder task accept {task} --reason \"…\"",
935            "speccoder task nudge {task} --note \"…\""
936        ]
937    ),
938    entry!(
939        "TESTS-OVER-STRICT",
940        P,
941        S::NeedsHuman,
942        "an acceptance test rejects an implementation the spec appears to allow",
943        "An alternative the spec allows (another order, wording, tie-break) failed the acceptance tests: they may encode a choice the spec did not make. The attempt is held until you rule; if the tests are right, the next run ticks it without a model call.",
944        [
945            "speccoder task rule {task} --tests-right --reason \"…\"",
946            "speccoder run --task {task} --fresh-acceptance",
947            "speccoder task accept {task} --reason \"…\""
948        ]
949    ),
950    entry!(
951        "ACCEPTANCE-WEAK",
952        P,
953        S::NeedsHuman,
954        "the acceptance tests are too weak for [acceptance] min_strength",
955        "Wrong implementations — mutants of the changed code and model-written near misses — passed the acceptance tests too often, and adding tests once did not fix it. The task stays unticked; the report names what got through.",
956        [
957            "speccoder report",
958            "speccoder run --task {task}",
959            "speccoder task accept {task} --reason \"…\""
960        ]
961    ),
962    entry!(
963        "INTERRUPTED",
964        P,
965        S::NeedsHuman,
966        "the run was interrupted",
967        "The process was stopped or killed; the journal holds what finished. The next run resumes without repeating finished calls.",
968        ["speccoder run --feature {feature}"]
969    ),
970    entry!(
971        "CHECKLISTS-OPEN",
972        P,
973        S::NeedsHuman,
974        "the feature's checklists have unchecked items",
975        "Spec Kit checklists gate implementation; nothing ran.",
976        [
977            "→ finish the checklists in the feature's checklists/ directory",
978            "speccoder run --ignore-checklists"
979        ]
980    ),
981    entry!(
982        "ARCHIVE-AWAITING",
983        P,
984        S::NeedsHuman,
985        "the OpenSpec archive waits for your yes",
986        "The diff of the archive is shown; nothing is written until a person confirms.",
987        ["speccoder spec archive --yes"]
988    ),
989    // ── runs ──────────────────────────────────────────────────────────
990    entry!(
991        "RUN-FAILED",
992        E,
993        S::RunFailed,
994        "the model call or the run failed",
995        "The provider returned an error, the journal could not be written, or the run broke; the message names it. Nothing was ticked.",
996        ["speccoder run --feature {feature} -v"]
997    ),
998    entry!(
999        "PROVIDER-REFUSED",
1000        E,
1001        S::RunFailed,
1002        "the model provider refused the request",
1003        "No credits, a rejected or revoked key, or an account limit. speccoder stops instead of judging the task on less evidence.",
1004        [
1005            "→ check the provider account's credits and the API key",
1006            "speccoder run --feature {feature}"
1007        ]
1008    ),
1009    entry!(
1010        "REPLAY-DIVERGED",
1011        E,
1012        S::ReplayDiverged,
1013        "the replay did not reproduce the recorded run",
1014        "Strict replay re-derives a run from its journal without a model; a difference means the code's decisions changed.",
1015        ["speccoder replay <run> --json"]
1016    ),
1017    entry!(
1018        "NOT-REPLAYABLE",
1019        E,
1020        S::NotReplayable,
1021        "this build cannot re-derive the recorded run",
1022        "The run was recorded by a build whose skills or effects this one does not have.",
1023        ["→ replay with the speccoder version that recorded the run"]
1024    ),
1025    // ── bug fixes ─────────────────────────────────────────────────────
1026    entry!(
1027        "BUG-NO-UNIT",
1028        E,
1029        S::UsageError,
1030        "this spec format has no place for a bug",
1031        "A bug lives in the format's own bug structure (Spec Kit's `bug` extension) or in its standing bug-fix unit (Spec Kit's `NNN-bugfixes`, an OpenSpec standing change). Kiro projects are not supported: nothing is written.",
1032        [
1033            "→ write a spec for the change and run it",
1034            "→ a change without a reproduction: speccoder do \"…\""
1035        ]
1036    ),
1037    entry!(
1038        "BUG-EMPTY",
1039        E,
1040        S::UsageError,
1041        "the symptom and every statement need words",
1042        "`speccoder bug` records the person's own words: an empty symptom, `--expected` or `--unchanged` is refused before anything is written.",
1043        ["speccoder bug \"<what happens>\" --expected \"<what should>\""]
1044    ),
1045    entry!(
1046        "BUG-NO-EXPECTED",
1047        E,
1048        S::UsageError,
1049        "a bug needs at least one --expected statement",
1050        "A reproduction asserts what should happen; speccoder never infers it from the symptom or an issue. Give one `--expected` per behaviour.",
1051        ["speccoder bug \"<what happens>\" --expected \"<what should>\""]
1052    ),
1053    entry!(
1054        "BUG-ASSESSMENT-DRIFT",
1055        P,
1056        S::NeedsHuman,
1057        "the bug's home does not carry exactly your words",
1058        "The bug's file (`assessment.md`, or the standing unit) does not read back exactly your Current, Expected and Unchanged statements: one is missing, added, reworded, or changed by the file's markup. Reproductions are written from your words only, so nothing was reproduced.",
1059        [
1060            "→ edit the assessment so it carries each statement as a `Current:` / `Expected:` / `Unchanged:` line",
1061            "speccoder bug --slug <slug>"
1062        ]
1063    ),
1064    entry!(
1065        "BUG-ASSESSMENT-UNREADABLE",
1066        P,
1067        S::NeedsHuman,
1068        "the bug's assessment is not in a shape speccoder reads",
1069        "speccoder reads `assessment.md` in the layout of the `bug` extension version it was built against, and refuses rather than guesses on any other shape.",
1070        [
1071            "specify extension list --json",
1072            "→ add `Current:` and `Expected:` lines to the assessment's Report section"
1073        ]
1074    ),
1075    entry!(
1076        "BUG-TEST-NOT-FOUND",
1077        E,
1078        S::UsageError,
1079        "the test named with --test is not found",
1080        "`--test PATH::NAME` must name an existing test file and a test in it that the runner collects.",
1081        ["→ give the test as PATH::NAME, as the runner lists it"]
1082    ),
1083    entry!(
1084        "BUG-TEST-NOT-RED",
1085        E,
1086        S::UsageError,
1087        "the named test does not fail on an assertion",
1088        "A reproduction must fail on the untouched code by an assertion, twice. A build or collection error, a timeout, an absent symbol or a flaky failure shows nothing about the bug.",
1089        ["→ fix the test so it fails on an assertion, then run `speccoder bug` again"]
1090    ),
1091    entry!(
1092        "BUG-TEST-PASSES",
1093        E,
1094        S::UsageError,
1095        "the named test passes on the untouched code",
1096        "A test that passes before any fix cannot show the bug. Perhaps it is fixed already.",
1097        ["→ check the behaviour by hand; if it is fixed, there is nothing to record"]
1098    ),
1099    entry!(
1100        "BUG-TEST-COVERAGE",
1101        E,
1102        S::UsageError,
1103        "each --expected statement needs its own --test",
1104        "Each stated behaviour gets its own reproduction: repeat `--test` once per `--expected`, in the same order.",
1105        [
1106            "speccoder bug \"…\" --expected \"<e1>\" --test <file>::<test1> --expected \"<e2>\" --test <file>::<test2>"
1107        ]
1108    ),
1109    entry!(
1110        "BUG-CANNOT-REPRODUCE",
1111        P,
1112        S::NeedsHuman,
1113        "the bug could not be reproduced: nothing is fixed",
1114        "No try produced a test for each Expected statement that fails on its own assertion, or you rejected them (rejected tries count against `[bug] reproduce_tries`). A fix without a failing reproduction would be a guess, so the bug comes back to you with what each try showed.",
1115        [
1116            "speccoder bug run --task {feature}/{task}",
1117            "speccoder bug \"…\" --expected \"…\" --test <file>::<test>",
1118            "speccoder task drop {task}"
1119        ]
1120    ),
1121    entry!(
1122        "BUG-ALREADY-SATISFIED",
1123        W,
1124        S::Ok,
1125        "the reproductions already pass: nothing to fix",
1126        "Every reproduction passed on the untouched code on every try. Nothing is ticked; keep the reproductions as a regression test (committed, the task attested) or drop the task.",
1127        [
1128            "speccoder bug keep {feature}/{task} --reason \"kept as a regression test\"",
1129            "speccoder task drop {task}"
1130        ]
1131    ),
1132    entry!(
1133        "BUG-UNCHANGED-NOT-HOLDING",
1134        P,
1135        S::NeedsHuman,
1136        "an Unchanged statement does not hold today",
1137        "The test of an Unchanged statement fails on the untouched code, so the statement is not true now and cannot guard the fix. The bug stops before any fix.",
1138        ["→ reword or remove the statement, then `speccoder bug run`"]
1139    ),
1140    entry!(
1141        "BUG-NOT-DISCRIMINATING",
1142        E,
1143        S::VerificationFailed,
1144        "the reproduction does not tell the fix from no fix",
1145        "With the attempt's source changes undone (its tests kept), no reproduction failed on an assertion: passing them proves nothing about the fix. The retry is told which statement.",
1146        ["speccoder run --task {task}"]
1147    ),
1148    entry!(
1149        "BUG-REPRO-WEAK",
1150        P,
1151        S::NeedsHuman,
1152        "a fix that special-cases the reproduction's input passes",
1153        "A candidate fix that only recognises the reproduction's literal inputs passed the reproductions and the held-out variants, even after one variant was written again. The tests are too weak for a verified fix.",
1154        [
1155            "speccoder task rule {task} --tests-right --reason \"…\"",
1156            "speccoder bug \"…\" --expected \"…\" --test <file>::<test>"
1157        ]
1158    ),
1159    entry!(
1160        "BUG-CANDIDATE-APPLY",
1161        E,
1162        S::GitPrecondition,
1163        "the candidate patch is not applied",
1164        "`--candidate` applies the patch on the untouched code with `git apply --check` first; some hunks did not apply, git could not read it as a patch, or it carries a binary hunk or a symbolic link (neither is judged as a candidate).",
1165        ["→ rebase the patch on HEAD, as a text diff without binary hunks or links"]
1166    ),
1167    entry!(
1168        "BUG-CANDIDATE-JUDGE",
1169        E,
1170        S::UsageError,
1171        "the candidate patch touches what judges it",
1172        "A candidate must not change a frozen reproduction, a held-out path or another judge input (checks, configuration, the intent) — by an edit, a rename, a deletion or a mode change, as git itself reads the patch. It is refused before it is applied.",
1173        ["→ remove those hunks from the patch"]
1174    ),
1175    entry!(
1176        "EVAL-FAILED",
1177        E,
1178        S::EvalFailed,
1179        "the evaluation found a false completion or a cheat",
1180        "A case ended done although its hidden oracle fails, or the attempt gamed its tests.",
1181        ["speccoder eval --keep <dir>"]
1182    ),
1183];
1184
1185/// The catalog entry named `name`.
1186#[must_use]
1187pub fn lookup(name: &str) -> Option<&'static Entry> {
1188    CATALOG.iter().find(|e| e.name == name)
1189}
1190
1191/// The code a non-ok status gets when nothing more specific is known.
1192#[must_use]
1193pub fn default_for(status: CommandStatus) -> Option<&'static Entry> {
1194    let name = match status {
1195        S::Ok => return None,
1196        S::UsageError => "USAGE",
1197        S::Error => "INTERNAL",
1198        S::NotAProject => "NO-PROJECT",
1199        S::DiagnosticsError => "SPEC-DIAGNOSTICS",
1200        S::SelectionNeeded => "FEATURE-SELECTION",
1201        S::ConfigError => "CONFIG",
1202        S::VerificationFailed => "VERIFICATION-FAILED",
1203        S::GitPrecondition => "GIT",
1204        S::NotFound => "NOT-FOUND",
1205        S::RunFailed => "RUN-FAILED",
1206        S::ReplayDiverged => "REPLAY-DIVERGED",
1207        S::TaskNotReady => "TASK-NOT-READY",
1208        S::NeedsHuman => "NEEDS-HUMAN",
1209        S::EvalFailed => "EVAL-FAILED",
1210        S::NotReplayable => "NOT-REPLAYABLE",
1211        S::AttestationFailed => "ATTESTATION-FAILED",
1212    };
1213    lookup(name)
1214}
1215
1216/// Up to `n` catalog names closest to `name` (case-insensitive edit distance).
1217#[must_use]
1218pub fn nearest(name: &str, n: usize) -> Vec<&'static str> {
1219    let wanted = name.to_ascii_uppercase();
1220    let mut scored: Vec<(usize, &'static str)> = CATALOG
1221        .iter()
1222        .map(|e| (distance(&wanted, e.name), e.name))
1223        .collect();
1224    scored.sort();
1225    scored
1226        .into_iter()
1227        .filter(|(d, _)| *d <= wanted.len().max(3) / 2 + 1)
1228        .take(n)
1229        .map(|(_, name)| name)
1230        .collect()
1231}
1232
1233fn distance(a: &str, b: &str) -> usize {
1234    let b: Vec<char> = b.chars().collect();
1235    let mut row: Vec<usize> = (0..=b.len()).collect();
1236    for (i, ca) in a.chars().enumerate() {
1237        let mut prev = row[0];
1238        row[0] = i + 1;
1239        for (j, cb) in b.iter().enumerate() {
1240            let cur = row[j + 1];
1241            row[j + 1] = (prev + usize::from(ca != *cb)).min(row[j] + 1).min(cur + 1);
1242            prev = cur;
1243        }
1244    }
1245    row[b.len()]
1246}
1247
1248/// `entry`'s fixes with `{task}`, `{feature}` and `{command}` filled where
1249/// known; a fix whose placeholder is unknown keeps `<task>`-style blanks.
1250#[must_use]
1251pub fn fixes(
1252    entry: &Entry,
1253    command: &str,
1254    task: Option<&str>,
1255    feature: Option<&str>,
1256) -> Vec<String> {
1257    // Without a task, a fix about one is no step to take — unless every fix
1258    // is about one (then the placeholder shows what to fill in).
1259    let general = entry.fix.iter().any(|f| !f.contains("{task}"));
1260    entry
1261        .fix
1262        .iter()
1263        .filter(|f| task.is_some() || !general || !f.contains("{task}"))
1264        .map(|f| {
1265            let feature_arg = feature.map_or_else(String::new, |f| f.to_owned());
1266            let mut line = f
1267                .replace("{command}", command)
1268                .replace("{task}", task.unwrap_or("<task>"));
1269            line = if feature.is_some() {
1270                line.replace("{feature}", &feature_arg)
1271            } else {
1272                // Without a selected feature, the flag is not needed.
1273                line.replace(" --feature {feature}", "")
1274                    .replace("{feature}", "<feature>")
1275            };
1276            line
1277        })
1278        .collect()
1279}
1280
1281#[cfg(test)]
1282mod tests {
1283    use super::*;
1284
1285    const STATUSES: [CommandStatus; 17] = [
1286        S::Ok,
1287        S::UsageError,
1288        S::Error,
1289        S::NotAProject,
1290        S::DiagnosticsError,
1291        S::SelectionNeeded,
1292        S::ConfigError,
1293        S::VerificationFailed,
1294        S::GitPrecondition,
1295        S::NotFound,
1296        S::RunFailed,
1297        S::ReplayDiverged,
1298        S::TaskNotReady,
1299        S::NeedsHuman,
1300        S::EvalFailed,
1301        S::NotReplayable,
1302        S::AttestationFailed,
1303    ];
1304
1305    #[test]
1306    fn names_are_unique_upper_case_words() {
1307        let mut seen = std::collections::BTreeSet::new();
1308        for e in CATALOG {
1309            assert!(seen.insert(e.name), "{} twice", e.name);
1310            assert!(
1311                e.name.split('-').all(|w| !w.is_empty()
1312                    && w.chars()
1313                        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())),
1314                "{}",
1315                e.name
1316            );
1317            assert!(!e.fix.is_empty() && !e.title.ends_with('.'), "{}", e.name);
1318            assert!(
1319                e.title.chars().next().is_some_and(char::is_lowercase),
1320                "{}",
1321                e.name
1322            );
1323        }
1324    }
1325
1326    #[test]
1327    fn every_non_ok_status_has_a_default_and_kinds_agree_with_statuses() {
1328        for s in STATUSES {
1329            let d = default_for(s);
1330            assert_eq!(d.is_none(), s == S::Ok, "{s:?}");
1331            if let Some(d) = d {
1332                assert_eq!(d.status, s);
1333            }
1334        }
1335        for e in CATALOG {
1336            assert_eq!(
1337                e.kind == Kind::Stop,
1338                e.status == S::NeedsHuman,
1339                "{}",
1340                e.name
1341            );
1342            assert_eq!(e.kind == Kind::Warning, e.status == S::Ok, "{}", e.name);
1343        }
1344    }
1345
1346    #[test]
1347    fn near_misses_are_suggested_and_placeholders_filled() {
1348        assert_eq!(nearest("uncommited-intent", 1), ["UNCOMMITTED-INTENT"]);
1349        assert_eq!(nearest("NEEDS-APROVAL", 1), ["NEEDS-APPROVAL"]);
1350        assert!(nearest("completely-unrelated-words", 3).is_empty());
1351        let e = lookup("NEEDS-APPROVAL").unwrap();
1352        assert_eq!(
1353            fixes(e, "run", Some("T004"), None)[1],
1354            "speccoder task approve T004"
1355        );
1356        let r = lookup("INTERRUPTED").unwrap();
1357        assert_eq!(fixes(r, "run", None, None), ["speccoder run"]);
1358        assert_eq!(
1359            fixes(r, "run", None, Some("001-x")),
1360            ["speccoder run --feature 001-x"]
1361        );
1362    }
1363}