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