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    // ── internal ──────────────────────────────────────────────────────
101    entry!(
102        "INTERNAL",
103        E,
104        S::Error,
105        "speccoder failed in a way it does not expect",
106        "An unexpected failure inside speccoder: an IO error, a broken state file, a bug. The message says what failed.",
107        ["→ re-run with -v and report the output at https://github.com/hupe1980/speccoder/issues"]
108    ),
109    // ── project ───────────────────────────────────────────────────────
110    entry!(
111        "NO-PROJECT",
112        E,
113        S::NotAProject,
114        "speccoder works on a Spec Kit or OpenSpec project, and found none here",
115        "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.",
116        ["specify init --here --integration claude", "openspec init"]
117    ),
118    entry!(
119        "SPEC-DIAGNOSTICS",
120        E,
121        S::DiagnosticsError,
122        "the spec artifacts have errors speccoder will not guess around",
123        "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.",
124        ["speccoder inspect"]
125    ),
126    entry!(
127        "FEATURE-SELECTION",
128        E,
129        S::SelectionNeeded,
130        "more than one feature could be meant",
131        "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.",
132        [
133            "speccoder feature",
134            "speccoder feature <name>",
135            "speccoder {command} --feature <name>"
136        ]
137    ),
138    entry!(
139        "CHECK-BROKEN",
140        E,
141        S::ConfigError,
142        "a check cannot run on the untouched code",
143        "Before any model call, speccoder runs your fast checks on the worktree as it is. One failed without running a test — a command or profile it names does not exist there, a file it needs was never committed (a worktree holds only commits), or it does not build. It could never judge the task, so nothing was attempted.",
144        [
145            "speccoder doctor",
146            "git status",
147            "speccoder run --allow-failing-baseline"
148        ]
149    ),
150    entry!(
151        "FEATURE-GONE",
152        E,
153        S::SelectionNeeded,
154        "the current feature no longer exists",
155        "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.",
156        [
157            "speccoder feature",
158            "speccoder feature <name>",
159            "speccoder feature --clear"
160        ]
161    ),
162    entry!(
163        "REVIEW-PENDING",
164        P,
165        S::NeedsHuman,
166        "the spec is not approved yet",
167        "`[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.",
168        ["speccoder review", "speccoder review approve", "git commit"]
169    ),
170    entry!(
171        "FEATURE-UNKNOWN",
172        E,
173        S::SelectionNeeded,
174        "no feature has that name or number",
175        "`--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.",
176        ["speccoder feature", "speccoder report --feature <name>"]
177    ),
178    // ── configuration ─────────────────────────────────────────────────
179    entry!(
180        "CONFIG",
181        E,
182        S::ConfigError,
183        "the configuration or the environment is not usable",
184        "`speccoder.toml` or the environment does not allow this command to run; the message names what is wrong.",
185        ["speccoder init"]
186    ),
187    entry!(
188        "NO-STATE-DIR",
189        E,
190        S::ConfigError,
191        "speccoder has nowhere to keep its state",
192        "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.",
193        ["export SPECCODER_STATE_DIR=\"$PWD/.speccoder-state\""]
194    ),
195    entry!(
196        "SANDBOX-UNAVAILABLE",
197        E,
198        S::ConfigError,
199        "the OS sandbox is not available and the project requires it",
200        "`[sandbox] mode = \"required\"` refuses to run commands unsandboxed, and this OS offers no sandbox (Linux without Landlock, a container without user namespaces, another OS).",
201        [
202            "→ run on macOS or Linux 6.2+ (Landlock ABI 3)",
203            "→ or set [sandbox] mode = \"auto\" to run unsandboxed and be told"
204        ]
205    ),
206    entry!(
207        "GITHUB-AUTH",
208        E,
209        S::Error,
210        "not signed in to GitHub",
211        "speccoder reads issues and opens pull requests through GitHub's API as you: with GH_TOKEN (or GITHUB_TOKEN) from the environment, else the token `speccoder auth login` keeps in your system keychain. None was found, or GitHub refused it (expired or revoked).",
212        [
213            "speccoder auth login --with-token",
214            "speccoder auth status",
215            "→ or set GH_TOKEN (a fine-grained token: Issues read; Pull requests read and write; Contents and Metadata read)"
216        ]
217    ),
218    entry!(
219        "GITHUB-FAILED",
220        E,
221        S::Error,
222        "the GitHub API could not do it",
223        "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.",
224        ["speccoder auth status", "git remote -v"]
225    ),
226    entry!(
227        "CONFIG-EXISTS",
228        E,
229        S::ConfigError,
230        "the project has a speccoder.toml already",
231        "`init` writes a new one; change the existing one with `speccoder config` (or Settings), or start over with `--force`.",
232        ["speccoder config", "speccoder init --force"]
233    ),
234    entry!(
235        "CONFIG-MISSING",
236        E,
237        S::ConfigError,
238        "the project has no speccoder.toml",
239        "speccoder needs to know which checks decide \"nothing regressed\" and which model to use; `init` detects them and writes a commented file.",
240        ["speccoder init"]
241    ),
242    entry!(
243        "CONFIG-INVALID",
244        E,
245        S::ConfigError,
246        "speccoder.toml has an error",
247        "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.",
248        ["→ fix the line the message names in speccoder.toml, then commit it"]
249    ),
250    entry!(
251        "KEY-MISSING",
252        E,
253        S::ConfigError,
254        "the model provider's API key is not in the environment",
255        "speccoder reads API keys from the environment only. The message names the variable the configured provider needs.",
256        ["→ export the variable the message names, e.g. export ANTHROPIC_API_KEY=…"]
257    ),
258    entry!(
259        "NO-CHECKS",
260        E,
261        S::ConfigError,
262        "no check applies, so nothing could show that nothing regressed",
263        "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.",
264        ["speccoder config set checks.test.argv -- <your test command>"]
265    ),
266    // ── git ───────────────────────────────────────────────────────────
267    entry!(
268        "GIT",
269        E,
270        S::GitPrecondition,
271        "git is not in the state this command needs",
272        "A git precondition does not hold; the message names it.",
273        ["git status"]
274    ),
275    entry!(
276        "NO-REPOSITORY",
277        E,
278        S::GitPrecondition,
279        "speccoder needs a git repository with at least one commit",
280        "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.",
281        ["git init && git add -A && git commit -m init"]
282    ),
283    entry!(
284        "UNCOMMITTED-INTENT",
285        E,
286        S::GitPrecondition,
287        "the spec has uncommitted changes the run would not see",
288        "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.",
289        ["git status", "speccoder run --in-place"]
290    ),
291    entry!(
292        "NO-REMOTE",
293        E,
294        S::GitPrecondition,
295        "there is no git remote to push to",
296        "`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.",
297        [
298            "git remote add origin <url>",
299            "git remote -v",
300            "speccoder pr --remote <name>"
301        ]
302    ),
303    entry!(
304        "WORKTREE-DIRTY",
305        E,
306        S::GitPrecondition,
307        "the feature's worktree has uncommitted changes",
308        "Work left in the worktree outside a commit — a failed attempt's, or an edit by hand — would be mixed into what comes next.",
309        ["speccoder worktree", "speccoder run --feature {feature}"]
310    ),
311    entry!(
312        "NOTHING-TO-HAND-OFF",
313        E,
314        S::GitPrecondition,
315        "the speccoder branch has nothing the base does not have",
316        "`pr` hands off work on `speccoder/<feature>`; there is none yet, or it is already merged.",
317        ["speccoder run --feature {feature}"]
318    ),
319    // in place
320    entry!(
321        "DIRTY-CHECKOUT",
322        E,
323        S::GitPrecondition,
324        "an in-place run needs a clean checkout",
325        "In place, the attempt runs in your checkout; uncommitted changes would be judged as the agent's.",
326        ["git stash -u", "git commit -am wip"]
327    ),
328    entry!(
329        "UNBORN-HEAD",
330        E,
331        S::GitPrecondition,
332        "the checkout has no commit yet",
333        "An in-place run branches from HEAD; there is no HEAD to branch from.",
334        ["git add -A && git commit -m init"]
335    ),
336    entry!(
337        "CONFIG-NOT-TRACKED",
338        E,
339        S::GitPrecondition,
340        "speccoder.toml must be committed",
341        "The judge's configuration is a reviewed input; an untracked or modified one could be changed without review.",
342        ["git add speccoder.toml && git commit -m \"speccoder: config\""]
343    ),
344    entry!(
345        "BRANCH-IN-WORKTREE",
346        E,
347        S::GitPrecondition,
348        "the feature's branch is checked out in a worktree",
349        "git refuses to check out a branch twice; an in-place run needs `speccoder/<feature>` free.",
350        ["git worktree list", "git worktree remove <path>"]
351    ),
352    entry!(
353        "IN-PLACE-ACTIVE",
354        E,
355        S::GitPrecondition,
356        "an in-place run holds this checkout",
357        "Another in-place session is active (or was killed); it owns the checkout until it ends or is left.",
358        [
359            "speccoder run --in-place",
360            "speccoder run --in-place --return"
361        ]
362    ),
363    entry!(
364        "IN-PLACE-SESSION",
365        E,
366        S::GitPrecondition,
367        "an in-place session is recorded for this checkout",
368        "A worktree-mode command would not see what the in-place session holds.",
369        [
370            "speccoder run --in-place",
371            "speccoder run --in-place --return"
372        ]
373    ),
374    entry!(
375        "IN-PLACE-PARALLEL",
376        E,
377        S::UsageError,
378        "an in-place run works one task at a time",
379        "Parallel lanes need worktrees of their own; in place there is only your checkout.",
380        ["speccoder run --in-place", "speccoder run --parallel 2"]
381    ),
382    entry!(
383        "MERGE-CONFLICT",
384        E,
385        S::GitPrecondition,
386        "the checkout is in the middle of a merge or rebase",
387        "An in-place run cannot start or return while git waits for a conflict to be resolved.",
388        ["git status", "git merge --abort"]
389    ),
390    entry!(
391        "INTENT-CHANGED",
392        P,
393        S::NeedsHuman,
394        "the spec, plan or tasks changed during the run",
395        "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.",
396        ["git diff", "speccoder run --in-place"]
397    ),
398    entry!(
399        "JUDGE-CHANGED",
400        P,
401        S::NeedsHuman,
402        "the judge's inputs changed during the run",
403        "Checks, test configuration or agent configuration changed after the run started; a verdict under changed rules would mean nothing.",
404        ["git diff", "speccoder run --in-place"]
405    ),
406    entry!(
407        "CHECKOUT-CHANGED",
408        P,
409        S::NeedsHuman,
410        "the checkout moved under the run",
411        "HEAD, the branch or the tree is not where speccoder left it; someone or something else changed the checkout.",
412        ["git status", "speccoder run --in-place --return"]
413    ),
414    entry!(
415        "GIT-CHANGED",
416        P,
417        S::NeedsHuman,
418        "git's configuration, hooks or refs changed during the run",
419        "Where the sandbox cannot keep `.git` read-only, speccoder fingerprints it; a change stops the run before the next tick.",
420        [
421            "git config --list --show-origin",
422            "speccoder run --in-place --return"
423        ]
424    ),
425    entry!(
426        "RETURN-BLOCKED",
427        P,
428        S::NeedsHuman,
429        "the in-place run cannot switch back to your branch",
430        "Switching back would overwrite changes or fail; the session stays until the checkout allows it.",
431        ["git status", "speccoder run --in-place --return"]
432    ),
433    // ── tasks ─────────────────────────────────────────────────────────
434    entry!(
435        "NOT-FOUND",
436        E,
437        S::NotFound,
438        "nothing by that name exists",
439        "No task, run, call or object matches what was asked for; the message names it.",
440        ["speccoder report"]
441    ),
442    entry!(
443        "NOT-FOUND-SCHEMA",
444        E,
445        S::NotFound,
446        "there is no schema by that name",
447        "`speccoder schema` lists the schemas speccoder publishes.",
448        ["speccoder schema"]
449    ),
450    entry!(
451        "TASK-NOT-READY",
452        E,
453        S::TaskNotReady,
454        "no task can run now",
455        "The task is done, or waits for tasks it depends on.",
456        ["speccoder report"]
457    ),
458    entry!(
459        "TASK-DONE",
460        E,
461        S::TaskNotReady,
462        "the task is already ticked",
463        "A ticked task is not run again; its evidence is in its commit.",
464        ["speccoder report"]
465    ),
466    entry!(
467        "TASK-BLOCKED",
468        E,
469        S::TaskNotReady,
470        "the task waits for tasks it depends on",
471        "Dependencies come from the task list's phases, `[P]` markers and explicit references; the message names the open ones.",
472        [
473            "speccoder run --feature {feature}",
474            "speccoder task skip <dependency> --reason \"…\""
475        ]
476    ),
477    // ── verdicts ──────────────────────────────────────────────────────
478    entry!(
479        "VERIFICATION-FAILED",
480        E,
481        S::VerificationFailed,
482        "the checks or the acceptance tests did not pass",
483        "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.",
484        [
485            "speccoder report",
486            "speccoder task nudge {task} --note \"…\""
487        ]
488    ),
489    entry!(
490        "REGRESSION-ONLY",
491        W,
492        S::Ok,
493        "ticked on the regression checks alone, nothing task-specific was shown",
494        "The checks still pass, but no acceptance test showed this task's behaviour (the spec has no example for it, or the tests could not be made red first). It is ticked `regression_only`, never `verified`.",
495        [
496            "→ add an acceptance example to the task's story, then converge",
497            "speccoder converge --feature {feature}"
498        ]
499    ),
500    entry!(
501        "ATTESTATION-FAILED",
502        E,
503        S::AttestationFailed,
504        "an attestation is missing, unsigned where required, or does not hold",
505        "`attest verify` found a tick whose signed statements are missing, malformed, edited, about another commit, or signed by no one you trust.",
506        ["speccoder attest verify --feature {feature} --json"]
507    ),
508    // ── stops ─────────────────────────────────────────────────────────
509    entry!(
510        "NEEDS-HUMAN",
511        P,
512        S::NeedsHuman,
513        "the run stopped for a person",
514        "The run cannot go on without a decision; the message says what waits.",
515        ["speccoder report"]
516    ),
517    entry!(
518        "NEEDS-APPROVAL",
519        P,
520        S::NeedsHuman,
521        "a call waits for a person's decision; nothing ran",
522        "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.",
523        [
524            "speccoder report --approvals",
525            "speccoder task approve {task}",
526            "speccoder task reject {task} --reason \"…\""
527        ]
528    ),
529    entry!(
530        "BLOCKED",
531        P,
532        S::NeedsHuman,
533        "the model says the task cannot be done as written",
534        "The model used its honest exit: something in the spec or the code stops it. Its reason is a claim, shown as \"Model says\".",
535        [
536            "speccoder task nudge {task} --note \"…\"",
537            "speccoder task skip {task} --reason \"…\""
538        ]
539    ),
540    entry!(
541        "BUDGET-EXHAUSTED",
542        P,
543        S::NeedsHuman,
544        "the attempt ran out of turns, calls or tokens",
545        "The attempt reached a limit of `[budget]` before finishing. The work so far is saved under the attempt's ref.",
546        [
547            "speccoder task nudge {task} --note \"…\"",
548            "→ raise the limit in speccoder.toml [budget]"
549        ]
550    ),
551    entry!(
552        "NOT-DEMONSTRATED",
553        P,
554        S::NeedsHuman,
555        "the evidence the task needs could not be produced",
556        "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.",
557        [
558            "speccoder report",
559            "speccoder task accept {task} --reason \"…\""
560        ]
561    ),
562    entry!(
563        "ACCEPTANCE-UNWRITTEN",
564        P,
565        S::NeedsHuman,
566        "the acceptance tests could not be written, so nothing was attempted",
567        "The call that derives acceptance tests from the spec failed — the provider refused it (no credits, a rejected key) or the run broke. Without those tests the task could only be judged on the regression checks, which would look like a spec without examples.",
568        [
569            "speccoder run --feature {feature}",
570            "→ or set [acceptance] generate = false to rely on the checks alone"
571        ]
572    ),
573    entry!(
574        "SUSPECTED-GAMING",
575        P,
576        S::NeedsHuman,
577        "the gaming monitor suspects a shortcut",
578        "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.",
579        [
580            "speccoder report",
581            "speccoder task accept {task} --reason \"…\"",
582            "speccoder task nudge {task} --note \"…\""
583        ]
584    ),
585    entry!(
586        "TESTS-OVER-STRICT",
587        P,
588        S::NeedsHuman,
589        "an acceptance test rejects an implementation the spec appears to allow",
590        "After the task passed, an alternative the spec leaves open (another order, wording, tie-break) was run against the acceptance tests, and they failed it on an assertion: the tests may encode a choice the spec did not make. The attempt is held — its tree kept — until a person rules. A ruling that the tests are right ticks the held attempt on the next run without a model call.",
591        [
592            "speccoder task rule {task} --tests-right --reason \"…\"",
593            "speccoder run --task {task} --fresh-acceptance",
594            "speccoder task accept {task} --reason \"…\""
595        ]
596    ),
597    entry!(
598        "ACCEPTANCE-WEAK",
599        P,
600        S::NeedsHuman,
601        "the acceptance tests are too weak for [acceptance] min_strength",
602        "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.",
603        [
604            "speccoder report",
605            "speccoder run --task {task}",
606            "speccoder task accept {task} --reason \"…\""
607        ]
608    ),
609    entry!(
610        "INTERRUPTED",
611        P,
612        S::NeedsHuman,
613        "the run was interrupted",
614        "The process was stopped or killed; the journal holds what finished. The next run resumes without repeating finished calls.",
615        ["speccoder run --feature {feature}"]
616    ),
617    entry!(
618        "CHECKLISTS-OPEN",
619        P,
620        S::NeedsHuman,
621        "the feature's checklists have unchecked items",
622        "Spec Kit checklists gate implementation; nothing ran.",
623        [
624            "→ finish the checklists in the feature's checklists/ directory",
625            "speccoder run --ignore-checklists"
626        ]
627    ),
628    entry!(
629        "ARCHIVE-AWAITING",
630        P,
631        S::NeedsHuman,
632        "the OpenSpec archive waits for your yes",
633        "The diff of the archive is shown; nothing is written until a person confirms.",
634        ["speccoder spec archive --yes"]
635    ),
636    // ── runs ──────────────────────────────────────────────────────────
637    entry!(
638        "RUN-FAILED",
639        E,
640        S::RunFailed,
641        "the model call or the run failed",
642        "The provider returned an error, the journal could not be written, or the run broke; the message names it. Nothing was ticked.",
643        ["speccoder run --feature {feature} -v"]
644    ),
645    entry!(
646        "PROVIDER-REFUSED",
647        E,
648        S::RunFailed,
649        "the model provider refused the request",
650        "No credits, a rejected or revoked key, or an account limit. speccoder stops instead of judging the task on less evidence.",
651        [
652            "→ check the provider account's credits and the API key",
653            "speccoder run --feature {feature}"
654        ]
655    ),
656    entry!(
657        "REPLAY-DIVERGED",
658        E,
659        S::ReplayDiverged,
660        "the replay did not reproduce the recorded run",
661        "Strict replay re-derives a run from its journal without a model; a difference means the code's decisions changed.",
662        ["speccoder replay <run> --json"]
663    ),
664    entry!(
665        "NOT-REPLAYABLE",
666        E,
667        S::NotReplayable,
668        "this build cannot re-derive the recorded run",
669        "The run was recorded by a build whose skills or effects this one does not have.",
670        ["→ replay with the speccoder version that recorded the run"]
671    ),
672    entry!(
673        "EVAL-FAILED",
674        E,
675        S::EvalFailed,
676        "the evaluation found a false completion or a cheat",
677        "A case ended done although its hidden oracle fails, or the attempt gamed its tests.",
678        ["speccoder eval --keep <dir>"]
679    ),
680];
681
682/// The catalog entry named `name`.
683#[must_use]
684pub fn lookup(name: &str) -> Option<&'static Entry> {
685    CATALOG.iter().find(|e| e.name == name)
686}
687
688/// The code a non-ok status gets when nothing more specific is known.
689#[must_use]
690pub fn default_for(status: CommandStatus) -> Option<&'static Entry> {
691    let name = match status {
692        S::Ok => return None,
693        S::UsageError => "USAGE",
694        S::Error => "INTERNAL",
695        S::NotAProject => "NO-PROJECT",
696        S::DiagnosticsError => "SPEC-DIAGNOSTICS",
697        S::SelectionNeeded => "FEATURE-SELECTION",
698        S::ConfigError => "CONFIG",
699        S::VerificationFailed => "VERIFICATION-FAILED",
700        S::GitPrecondition => "GIT",
701        S::NotFound => "NOT-FOUND",
702        S::RunFailed => "RUN-FAILED",
703        S::ReplayDiverged => "REPLAY-DIVERGED",
704        S::TaskNotReady => "TASK-NOT-READY",
705        S::NeedsHuman => "NEEDS-HUMAN",
706        S::EvalFailed => "EVAL-FAILED",
707        S::NotReplayable => "NOT-REPLAYABLE",
708        S::AttestationFailed => "ATTESTATION-FAILED",
709    };
710    lookup(name)
711}
712
713/// Up to `n` catalog names closest to `name` (case-insensitive edit distance).
714#[must_use]
715pub fn nearest(name: &str, n: usize) -> Vec<&'static str> {
716    let wanted = name.to_ascii_uppercase();
717    let mut scored: Vec<(usize, &'static str)> = CATALOG
718        .iter()
719        .map(|e| (distance(&wanted, e.name), e.name))
720        .collect();
721    scored.sort();
722    scored
723        .into_iter()
724        .filter(|(d, _)| *d <= wanted.len().max(3) / 2 + 1)
725        .take(n)
726        .map(|(_, name)| name)
727        .collect()
728}
729
730fn distance(a: &str, b: &str) -> usize {
731    let b: Vec<char> = b.chars().collect();
732    let mut row: Vec<usize> = (0..=b.len()).collect();
733    for (i, ca) in a.chars().enumerate() {
734        let mut prev = row[0];
735        row[0] = i + 1;
736        for (j, cb) in b.iter().enumerate() {
737            let cur = row[j + 1];
738            row[j + 1] = (prev + usize::from(ca != *cb)).min(row[j] + 1).min(cur + 1);
739            prev = cur;
740        }
741    }
742    row[b.len()]
743}
744
745/// `entry`'s fixes with `{task}`, `{feature}` and `{command}` filled where
746/// known; a fix whose placeholder is unknown keeps `<task>`-style blanks.
747#[must_use]
748pub fn fixes(
749    entry: &Entry,
750    command: &str,
751    task: Option<&str>,
752    feature: Option<&str>,
753) -> Vec<String> {
754    // Without a task, a fix about one is no step to take — unless every fix
755    // is about one (then the placeholder shows what to fill in).
756    let general = entry.fix.iter().any(|f| !f.contains("{task}"));
757    entry
758        .fix
759        .iter()
760        .filter(|f| task.is_some() || !general || !f.contains("{task}"))
761        .map(|f| {
762            let feature_arg = feature.map_or_else(String::new, |f| f.to_owned());
763            let mut line = f
764                .replace("{command}", command)
765                .replace("{task}", task.unwrap_or("<task>"));
766            line = if feature.is_some() {
767                line.replace("{feature}", &feature_arg)
768            } else {
769                // Without a selected feature, the flag is not needed.
770                line.replace(" --feature {feature}", "")
771                    .replace("{feature}", "<feature>")
772            };
773            line
774        })
775        .collect()
776}
777
778#[cfg(test)]
779mod tests {
780    use super::*;
781
782    const STATUSES: [CommandStatus; 17] = [
783        S::Ok,
784        S::UsageError,
785        S::Error,
786        S::NotAProject,
787        S::DiagnosticsError,
788        S::SelectionNeeded,
789        S::ConfigError,
790        S::VerificationFailed,
791        S::GitPrecondition,
792        S::NotFound,
793        S::RunFailed,
794        S::ReplayDiverged,
795        S::TaskNotReady,
796        S::NeedsHuman,
797        S::EvalFailed,
798        S::NotReplayable,
799        S::AttestationFailed,
800    ];
801
802    #[test]
803    fn names_are_unique_upper_case_words() {
804        let mut seen = std::collections::BTreeSet::new();
805        for e in CATALOG {
806            assert!(seen.insert(e.name), "{} twice", e.name);
807            assert!(
808                e.name.split('-').all(|w| !w.is_empty()
809                    && w.chars()
810                        .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit())),
811                "{}",
812                e.name
813            );
814            assert!(!e.fix.is_empty() && !e.title.ends_with('.'), "{}", e.name);
815            assert!(
816                e.title.chars().next().is_some_and(char::is_lowercase),
817                "{}",
818                e.name
819            );
820        }
821    }
822
823    #[test]
824    fn every_non_ok_status_has_a_default_and_kinds_agree_with_statuses() {
825        for s in STATUSES {
826            let d = default_for(s);
827            assert_eq!(d.is_none(), s == S::Ok, "{s:?}");
828            if let Some(d) = d {
829                assert_eq!(d.status, s);
830            }
831        }
832        for e in CATALOG {
833            assert_eq!(
834                e.kind == Kind::Stop,
835                e.status == S::NeedsHuman,
836                "{}",
837                e.name
838            );
839            assert_eq!(e.kind == Kind::Warning, e.status == S::Ok, "{}", e.name);
840        }
841    }
842
843    #[test]
844    fn near_misses_are_suggested_and_placeholders_filled() {
845        assert_eq!(nearest("uncommited-intent", 1), ["UNCOMMITTED-INTENT"]);
846        assert_eq!(nearest("NEEDS-APROVAL", 1), ["NEEDS-APPROVAL"]);
847        assert!(nearest("completely-unrelated-words", 3).is_empty());
848        let e = lookup("NEEDS-APPROVAL").unwrap();
849        assert_eq!(
850            fixes(e, "run", Some("T004"), None)[1],
851            "speccoder task approve T004"
852        );
853        let r = lookup("INTERRUPTED").unwrap();
854        assert_eq!(fixes(r, "run", None, None), ["speccoder run"]);
855        assert_eq!(
856            fixes(r, "run", None, Some("001-x")),
857            ["speccoder run --feature 001-x"]
858        );
859    }
860}