Skip to main content

harn_parser/
diagnostic_codes.rs

1//! Stable diagnostic code registry.
2//!
3//! Codes use `HARN-<CATEGORY>-<NNN>` identifiers so CLI output, editor
4//! diagnostics, docs, and future `harn explain` lookups can refer to one
5//! durable namespace.
6//!
7//! ```
8//! use harn_parser::diagnostic_codes::Category;
9//!
10//! let categories: Vec<_> = Category::ALL.iter().map(|category| category.as_str()).collect();
11//! assert_eq!(
12//!     categories,
13//!     [
14//!         "TYP", "PAR", "NAM", "CAP", "LLM", "ORC", "STD", "PRM",
15//!         "MOD", "RMD", "SUS", "LNT", "FMT", "IMP", "OWN", "RCV",
16//!         "MAT", "POL", "MET", "CST",
17//!     ],
18//! );
19//! ```
20
21use std::fmt;
22use std::str::FromStr;
23
24/// Top-level diagnostic category used in a stable Harn diagnostic code.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub enum Category {
27    Typ,
28    Par,
29    Nam,
30    Cap,
31    Llm,
32    Orc,
33    Std,
34    Prm,
35    Mod,
36    Rmd,
37    Sus,
38    Lnt,
39    Fmt,
40    Imp,
41    Own,
42    Rcv,
43    Mat,
44    Pol,
45    /// Meta — restrictions on what may appear in compile-time-evaluated
46    /// positions (e.g. `const` initializers). Reserved by issue #1791
47    /// (bounded const-eval).
48    Met,
49    /// Const-eval sandbox — bounded compile-time interpreter limits and
50    /// capability violations (steps, recursion depth, fs/net/env/process
51    /// denial). Reserved by issue #1791.
52    Cst,
53}
54
55impl Category {
56    pub const ALL: &'static [Category] = &[
57        Category::Typ,
58        Category::Par,
59        Category::Nam,
60        Category::Cap,
61        Category::Llm,
62        Category::Orc,
63        Category::Std,
64        Category::Prm,
65        Category::Mod,
66        Category::Rmd,
67        Category::Sus,
68        Category::Lnt,
69        Category::Fmt,
70        Category::Imp,
71        Category::Own,
72        Category::Rcv,
73        Category::Mat,
74        Category::Pol,
75        Category::Met,
76        Category::Cst,
77    ];
78
79    pub const fn as_str(self) -> &'static str {
80        match self {
81            Category::Typ => "TYP",
82            Category::Par => "PAR",
83            Category::Nam => "NAM",
84            Category::Cap => "CAP",
85            Category::Llm => "LLM",
86            Category::Orc => "ORC",
87            Category::Std => "STD",
88            Category::Prm => "PRM",
89            Category::Mod => "MOD",
90            Category::Rmd => "RMD",
91            Category::Sus => "SUS",
92            Category::Lnt => "LNT",
93            Category::Fmt => "FMT",
94            Category::Imp => "IMP",
95            Category::Own => "OWN",
96            Category::Rcv => "RCV",
97            Category::Mat => "MAT",
98            Category::Pol => "POL",
99            Category::Met => "MET",
100            Category::Cst => "CST",
101        }
102    }
103}
104
105impl fmt::Display for Category {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.write_str(self.as_str())
108    }
109}
110
111/// One registered diagnostic code.
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct RegistryEntry {
114    pub code: Code,
115    pub identifier: &'static str,
116    pub category: Category,
117    pub summary: &'static str,
118}
119
120macro_rules! diagnostic_codes {
121    ($($variant:ident, $identifier:literal, $category:ident, $summary:literal;)*) => {
122        /// Stable diagnostic identifier.
123        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
124        pub enum Code {
125            $($variant,)*
126        }
127
128        impl Code {
129            pub const ALL: &'static [Code] = &[
130                $(Code::$variant,)*
131            ];
132
133            pub const fn as_str(self) -> &'static str {
134                match self {
135                    $(Code::$variant => $identifier,)*
136                }
137            }
138
139            pub const fn category(self) -> Category {
140                match self {
141                    $(Code::$variant => Category::$category,)*
142                }
143            }
144
145            pub const fn summary(self) -> &'static str {
146                match self {
147                    $(Code::$variant => $summary,)*
148                }
149            }
150
151            /// Full markdown explanation embedded at compile time. Every
152            /// registered code must ship a matching file under
153            /// `diagnostic_codes/explanations/`; missing files fail the build.
154            pub const fn explanation(self) -> &'static str {
155                match self {
156                    $(Code::$variant => include_str!(
157                        concat!("diagnostic_codes/explanations/", $identifier, ".md")
158                    ),)*
159                }
160            }
161        }
162
163        pub const REGISTRY: &[RegistryEntry] = &[
164            $(RegistryEntry {
165                code: Code::$variant,
166                identifier: $identifier,
167                category: Category::$category,
168                summary: $summary,
169            },)*
170        ];
171    };
172}
173
174diagnostic_codes! {
175    TypeMismatch, "HARN-TYP-001", Typ, "expected and actual types are incompatible";
176    InvalidBinaryOperator, "HARN-TYP-002", Typ, "binary operator is not defined for the operand types";
177    StringInterpolationRewrite, "HARN-TYP-003", Typ, "string concatenation should be rewritten as interpolation";
178    ReturnTypeMismatch, "HARN-TYP-004", Typ, "returned expression does not match the declared return type";
179    AssignmentTypeMismatch, "HARN-TYP-005", Typ, "assigned value does not match the target type";
180    ArgumentTypeMismatch, "HARN-TYP-006", Typ, "argument value does not match the parameter type";
181    VariableTypeMismatch, "HARN-TYP-007", Typ, "initializer does not match the declared variable type";
182    ClosureReturnTypeMismatch, "HARN-TYP-008", Typ, "closure return expression does not match its declared type";
183    FieldTypeMismatch, "HARN-TYP-009", Typ, "field value does not match its declared type";
184    MethodTypeMismatch, "HARN-TYP-010", Typ, "method receiver or result type is incompatible";
185    GenericTypeArgumentUnsupported, "HARN-TYP-011", Typ, "callable does not accept type arguments";
186    GenericTypeArgumentMismatch, "HARN-TYP-012", Typ, "type argument does not satisfy the generic parameter";
187    GenericTypeArgumentArity, "HARN-TYP-013", Typ, "generic call has the wrong number of type arguments";
188    TypeParameterArity, "HARN-TYP-014", Typ, "declaration has the wrong number of type parameters";
189    WhereConstraintMismatch, "HARN-TYP-015", Typ, "type argument does not satisfy a where-clause constraint";
190    IterableExpected, "HARN-TYP-016", Typ, "expression must be iterable";
191    InvalidIndexType, "HARN-TYP-017", Typ, "subscript index type is invalid";
192    CallableExpected, "HARN-TYP-018", Typ, "expression must be callable";
193    InvalidCast, "HARN-TYP-019", Typ, "cast cannot be proven valid";
194    UnknownTypeName, "HARN-TYP-020", Typ, "type name cannot be resolved";
195    InvalidVariantUse, "HARN-TYP-021", Typ, "variant type is used in an invalid position";
196    InvalidStructLiteral, "HARN-TYP-022", Typ, "struct literal is invalid";
197    InvalidEnumConstruct, "HARN-TYP-023", Typ, "enum construction is invalid";
198    InvalidPatternBinding, "HARN-TYP-024", Typ, "pattern binding is invalid for the expected type";
199    InvalidOptionalAccess, "HARN-TYP-025", Typ, "optional access is invalid for the receiver type";
200    ParserUnexpectedToken, "HARN-PAR-001", Par, "parser found an unexpected token";
201    ParserUnexpectedEof, "HARN-PAR-002", Par, "parser reached end of file while expecting syntax";
202    ParserUnexpectedCharacter, "HARN-PAR-003", Par, "lexer found an unexpected character";
203    ParserUnterminatedString, "HARN-PAR-004", Par, "string literal is unterminated";
204    ParserUnterminatedBlockComment, "HARN-PAR-005", Par, "block comment is unterminated";
205    UndefinedVariable, "HARN-NAM-001", Nam, "variable name cannot be resolved";
206    UndefinedFunction, "HARN-NAM-002", Nam, "function name cannot be resolved";
207    UnknownAttribute, "HARN-NAM-003", Nam, "attribute name is not recognized";
208    UnknownField, "HARN-NAM-004", Nam, "field name does not exist on the target type";
209    UnknownMethod, "HARN-NAM-005", Nam, "method name does not exist on the receiver type";
210    DuplicateArgument, "HARN-NAM-006", Nam, "argument name is duplicated";
211    UnknownOption, "HARN-NAM-007", Nam, "option key is not recognized";
212    UnknownBuiltin, "HARN-NAM-008", Nam, "builtin name cannot be resolved";
213    DeprecatedFunction, "HARN-NAM-009", Nam, "function call targets a deprecated declaration";
214    UnknownDeclaration, "HARN-NAM-010", Nam, "declaration reference cannot be resolved";
215    InvalidAttributeTarget, "HARN-NAM-011", Nam, "attribute is attached to an unsupported declaration";
216    InvalidAttributeArgument, "HARN-NAM-012", Nam, "attribute argument is invalid";
217    InvalidMainSignature, "HARN-NAM-101", Nam, "`main` entrypoint must take a single `harness: Harness` parameter";
218    CapabilityPayloadInvalid, "HARN-CAP-001", Cap, "capability payload is invalid";
219    HitlMissingApprovalPolicy, "HARN-CAP-002", Cap, "human approval construct is missing policy";
220    HitlInvalidApprovalArgument, "HARN-CAP-003", Cap, "human approval argument is invalid";
221    CapabilityResultUnchecked, "HARN-CAP-004", Cap, "capability result must be checked";
222    CapabilityUnknownOperation, "HARN-CAP-005", Cap, "host capability operation is not declared";
223    CapabilityCallStaticNameRequired, "HARN-CAP-006", Cap, "host capability call must use a static operation name";
224    CapabilityBindingInvalid, "HARN-CAP-007", Cap, "tool host capability binding is invalid";
225    EffectInheritanceViolation, "HARN-CAP-301", Cap, "child agent effect set exceeds the parent's declared effects";
226    UnknownLlmOption, "HARN-LLM-001", Llm, "LLM option key is not recognized";
227    DeprecatedLlmOption, "HARN-LLM-002", Llm, "LLM option key is deprecated";
228    LlmSchemaMissing, "HARN-LLM-003", Llm, "LLM call is missing schema validation";
229    LlmSchemaInvalid, "HARN-LLM-004", Llm, "LLM schema option is invalid";
230    LlmProviderIdentityBranch, "HARN-LLM-005", Llm, "prompt branches on provider identity instead of capability flags";
231    OrchestrationArity, "HARN-ORC-001", Orc, "orchestration construct has invalid arity";
232    OrchestrationType, "HARN-ORC-002", Orc, "orchestration construct argument has invalid type";
233    AgentDefinitionInvalid, "HARN-ORC-003", Orc, "agent declaration is invalid";
234    WorkflowDefinitionInvalid, "HARN-ORC-004", Orc, "workflow declaration is invalid";
235    ToolDefinitionInvalid, "HARN-ORC-005", Orc, "tool declaration is invalid";
236    PipelineDefinitionInvalid, "HARN-ORC-006", Orc, "pipeline declaration is invalid";
237    InvalidSelectConstruct, "HARN-ORC-007", Orc, "select construct is invalid";
238    UnreachableCode, "HARN-ORC-008", Orc, "statement cannot be reached";
239    FlowInvariantAttributeInvalid, "HARN-ORC-009", Orc, "Flow invariant attribute set is invalid";
240    ExecutionTargetMissing, "HARN-ORC-010", Orc, "execution target path cannot be found";
241    DeprecatedStdlibSymbol, "HARN-STD-001", Std, "stdlib symbol has been renamed or deprecated";
242    StdlibUsageInvalid, "HARN-STD-002", Std, "stdlib call is invalid";
243    BuiltinArity, "HARN-STD-003", Std, "builtin call has invalid arity";
244    LintMissingStdlibMetadata, "HARN-STD-101", Std, "public stdlib function is missing declared metadata";
245    PromptTemplateParse, "HARN-PRM-001", Prm, "prompt template cannot be parsed";
246    PromptVariantExplosion, "HARN-PRM-002", Prm, "prompt template has too many capability-aware branches";
247    PromptInjectionRisk, "HARN-PRM-003", Prm, "prompt construction risks direct injection";
248    PromptProviderIdentityBranch, "HARN-PRM-004", Prm, "prompt template branches on provider identity";
249    PromptToolSurfaceUnknown, "HARN-PRM-005", Prm, "prompt references a tool outside the declared surface";
250    PromptToolSurfaceDeferredReference, "HARN-PRM-006", Prm, "prompt references a deferred tool without tool search";
251    PromptTargetMissing, "HARN-PRM-007", Prm, "prompt or template target cannot be found";
252    ModuleImportUnresolved, "HARN-MOD-001", Mod, "module import cannot be resolved";
253    ModuleImportUnused, "HARN-MOD-002", Mod, "module import is unused";
254    ModuleImportOrder, "HARN-MOD-003", Mod, "module imports are not in canonical order";
255    ModuleExportInvalid, "HARN-MOD-004", Mod, "module export is invalid";
256    ModuleImportCollision, "HARN-MOD-005", Mod, "module imports expose colliding names";
257    ModuleReExportConflict, "HARN-MOD-006", Mod, "module re-exports conflict";
258    ReminderUnknownOption, "HARN-RMD-001", Rmd, "reminder lifecycle option key is not recognized";
259    ReminderInvalidShape, "HARN-RMD-002", Rmd, "reminder payload shape is invalid";
260    ReminderUnsupportedUserBlockRoleHint, "HARN-RMD-003", Rmd, "user_block reminder role hint is not supported by the selected provider";
261    ReminderInfiniteDiscardable, "HARN-RMD-004", Rmd, "discardable reminder has no TTL";
262    ReminderUnknownPropagate, "HARN-RMD-005", Rmd, "reminder propagate value is not recognized";
263    ReminderProviderMalformedSpec, "HARN-RMD-006", Rmd, "reminder provider returned a malformed reminder spec";
264    ReminderProviderBloat, "HARN-RMD-007", Rmd, "too many reminder providers are enabled";
265    ReminderUnsupportedHookEvent, "HARN-RMD-008", Rmd, "hook event does not support reminder effects";
266    SuspendWorkerNotRunning, "HARN-SUS-001", Sus, "suspend_agent target worker is not running";
267    ResumeConditionsInvalid, "HARN-SUS-002", Sus, "ResumeConditions validation failed";
268    ResumeWorkerNotSuspended, "HARN-SUS-003", Sus, "resume_agent target worker is not suspended";
269    ResumeSnapshotInvalid, "HARN-SUS-004", Sus, "resume snapshot cannot be loaded or used";
270    AwaitResumptionOutsideAgentLoop, "HARN-SUS-005", Sus, "agent_await_resumption was invoked outside agent_loop structural handling";
271    ConcurrentResumeConflict, "HARN-SUS-006", Sus, "concurrent resume changed the worker before resume could complete";
272    ResumeTriggerRegistrationFailed, "HARN-SUS-007", Sus, "ResumeConditions trigger could not be registered";
273    ResumeTimeoutUnsupported, "HARN-SUS-008", Sus, "resume timeout action is unsupported";
274    ResumeInputInvalid, "HARN-SUS-009", Sus, "resume input failed agent_loop input validation";
275    ResumeWorkerClosed, "HARN-SUS-010", Sus, "closed suspended worker cannot be resumed";
276    ReplayResumeInputHashMismatch, "HARN-SUS-011", Sus, "replay resume input hash diverges from journaled suspension";
277    ReplayDrainDecisionPromptHashMismatch, "HARN-SUS-012", Sus, "replay drain decision prompt hash diverges from journaled receipt";
278    LifecycleSignatureMismatch, "HARN-SUS-013", Sus, "lifecycle receipt signed timestamp failed verification";
279    LintRenamedStdlibSymbol, "HARN-LNT-001", Lnt, "renamed stdlib symbol lint";
280    LintCyclomaticComplexity, "HARN-LNT-002", Lnt, "cyclomatic complexity lint";
281    LintNamingConvention, "HARN-LNT-003", Lnt, "naming convention lint";
282    LintEagerCollectionConversion, "HARN-LNT-004", Lnt, "eager collection conversion lint";
283    LintRedundantClone, "HARN-LNT-005", Lnt, "redundant clone lint";
284    LintLongRunningWithoutCleanup, "HARN-LNT-006", Lnt, "long-running workflow cleanup lint";
285    LintMcpToolAnnotations, "HARN-LNT-007", Lnt, "MCP tool annotations lint";
286    LintPrOpenWithoutSecretScan, "HARN-LNT-008", Lnt, "PR open without secret scan lint";
287    LintShadowVariable, "HARN-LNT-009", Lnt, "shadow variable lint";
288    LintPersonaHookTarget, "HARN-LNT-010", Lnt, "persona hook target lint";
289    LintDeadCodeAfterReturn, "HARN-LNT-011", Lnt, "dead code after return lint";
290    LintLetThenReturn, "HARN-LNT-012", Lnt, "let then return lint";
291    LintUnhandledApprovalResult, "HARN-LNT-013", Lnt, "unhandled approval result lint";
292    LintUnusedVariable, "HARN-LNT-014", Lnt, "unused variable lint";
293    LintUnusedPatternBinding, "HARN-LNT-015", Lnt, "unused pattern binding lint";
294    LintUnusedParameter, "HARN-LNT-016", Lnt, "unused parameter lint";
295    LintUnusedImport, "HARN-LNT-017", Lnt, "unused import lint";
296    LintMutableNeverReassigned, "HARN-LNT-018", Lnt, "mutable never reassigned lint";
297    LintUnusedFunction, "HARN-LNT-019", Lnt, "unused function lint";
298    LintUnusedType, "HARN-LNT-020", Lnt, "unused type lint";
299    LintPersonaBodyMustCallSteps, "HARN-LNT-021", Lnt, "persona body must call steps lint";
300    LintUndefinedFunction, "HARN-LNT-022", Lnt, "undefined function lint";
301    LintPipelineReturnType, "HARN-LNT-023", Lnt, "pipeline return type lint";
302    LintMissingHarndoc, "HARN-LNT-024", Lnt, "missing harndoc lint";
303    LintAssertOutsideTest, "HARN-LNT-025", Lnt, "assert outside test lint";
304    LintPromptInjectionRisk, "HARN-LNT-026", Lnt, "prompt injection risk lint";
305    LintConnectorEffectPolicy, "HARN-LNT-027", Lnt, "connector effect policy lint";
306    LintUnnecessaryCast, "HARN-LNT-028", Lnt, "unnecessary cast lint";
307    LintUntypedDictAccess, "HARN-LNT-029", Lnt, "untyped dict access lint";
308    LintConstantLogicalOperand, "HARN-LNT-030", Lnt, "constant logical operand lint";
309    LintPointlessComparison, "HARN-LNT-031", Lnt, "pointless comparison lint";
310    LintComparisonToBool, "HARN-LNT-032", Lnt, "comparison to bool lint";
311    LintInvalidBinaryOpLiteral, "HARN-LNT-033", Lnt, "invalid binary operator literal lint";
312    LintRedundantNilTernary, "HARN-LNT-034", Lnt, "redundant nil ternary lint";
313    LintEmptyBlock, "HARN-LNT-035", Lnt, "empty block lint";
314    LintUnnecessaryElseReturn, "HARN-LNT-036", Lnt, "unnecessary else return lint";
315    LintDuplicateMatchArm, "HARN-LNT-037", Lnt, "duplicate match arm lint";
316    LintRequireInTest, "HARN-LNT-038", Lnt, "require in test lint";
317    LintBreakOutsideLoop, "HARN-LNT-039", Lnt, "break outside loop lint";
318    LintTemplateParse, "HARN-LNT-040", Lnt, "template parse lint";
319    LintBlankLineBetweenItems, "HARN-LNT-041", Lnt, "blank line between items lint";
320    LintTrailingComma, "HARN-LNT-042", Lnt, "trailing comma lint";
321    LintUnnecessaryParentheses, "HARN-LNT-043", Lnt, "unnecessary parentheses lint";
322    LintTemplateVariantExplosion, "HARN-LNT-044", Lnt, "template variant explosion lint";
323    LintRequireFileHeader, "HARN-LNT-045", Lnt, "require file header lint";
324    LintTemplateProviderIdentityBranch, "HARN-LNT-046", Lnt, "template provider identity branch lint";
325    LintImportOrder, "HARN-LNT-047", Lnt, "import order lint";
326    LintPreferOptionalShorthand, "HARN-LNT-048", Lnt, "prefer optional shorthand lint";
327    LintLegacyDocComment, "HARN-LNT-049", Lnt, "legacy doc comment lint";
328    LintDeprecatedLlmOptions, "HARN-LNT-050", Lnt, "deprecated LLM options lint";
329    LintUnnecessarySafeNavigation, "HARN-LNT-051", Lnt, "unnecessary safe navigation lint";
330    LintAmbientClockBuiltin, "HARN-LNT-052", Lnt, "ambient clock builtin replaced by `harness.clock.*`";
331    LintAmbientStdioBuiltin, "HARN-LNT-053", Lnt, "ambient stdio builtin replaced by `harness.stdio.*`";
332    LintAmbientFsBuiltin, "HARN-LNT-054", Lnt, "ambient fs builtin replaced by `harness.fs.*`";
333    LintAmbientEnvBuiltin, "HARN-LNT-055", Lnt, "ambient env builtin replaced by `harness.env.*`";
334    LintAmbientRandomBuiltin, "HARN-LNT-056", Lnt, "ambient random builtin replaced by `harness.random.*`";
335    LintAmbientNetBuiltin, "HARN-LNT-057", Lnt, "ambient net builtin replaced by `harness.net.*`";
336    SandboxCapabilityDenied, "HARN-CAP-201", Cap, "harness capability denied by active sandbox profile";
337    FormatterParseFailed, "HARN-FMT-001", Fmt, "formatter could not parse the source";
338    FormatterWouldReformat, "HARN-FMT-002", Fmt, "source is not in canonical format";
339    FormatterTrailingComma, "HARN-FMT-003", Fmt, "formatter normalized trailing comma layout";
340    ImportResolutionFailed, "HARN-IMP-001", Imp, "import target cannot be resolved";
341    ImportSymbolMissing, "HARN-IMP-002", Imp, "imported symbol does not exist";
342    ImportCycle, "HARN-IMP-003", Imp, "import graph contains a cycle";
343    ImmutableAssignment, "HARN-OWN-001", Own, "immutable binding is reassigned";
344    MutableNeverReassigned, "HARN-OWN-002", Own, "mutable binding is never reassigned";
345    OwnershipEscape, "HARN-OWN-003", Own, "owned value escapes its valid scope";
346    BoundaryValueUnvalidated, "HARN-OWN-004", Own, "unvalidated boundary value is used directly";
347    RescueOutsideFunction, "HARN-RCV-001", Rcv, "rescue construct is outside a function body";
348    TryOutsideFunction, "HARN-RCV-002", Rcv, "try construct is outside a function body";
349    InvalidRescueConstruct, "HARN-RCV-003", Rcv, "rescue construct is invalid";
350    NonExhaustiveMatch, "HARN-MAT-001", Mat, "match expression is not exhaustive";
351    DuplicateMatchArm, "HARN-MAT-002", Mat, "match expression contains a duplicate arm";
352    InvalidMatchPattern, "HARN-MAT-003", Mat, "match pattern is invalid";
353    PoolBackpressureFull, "HARN-POL-001", Pol, "pool backpressure rejected a submit";
354    PoolFailFastFull, "HARN-POL-002", Pol, "fail-fast pool has no immediate capacity";
355    ConstEvalDisallowedExpression, "HARN-MET-001", Met, "expression is not permitted in a const initializer";
356    ConstEvalStepLimit, "HARN-CST-001", Cst, "const initializer exceeded the step budget";
357    ConstEvalRecursionLimit, "HARN-CST-002", Cst, "const initializer exceeded the recursion depth budget";
358    ConstEvalSandboxViolation, "HARN-CST-003", Cst, "const initializer attempted a sandboxed capability";
359    ConstEvalRuntimeError, "HARN-CST-004", Cst, "const initializer raised a runtime error during evaluation";
360}
361
362impl Code {
363    pub const fn registry() -> &'static [RegistryEntry] {
364        REGISTRY
365    }
366
367    /// Codes that an agent should consider alongside this one when planning
368    /// repairs. Curated per-code — typically near-neighbours in the same
369    /// category that share a fix shape. Returns an empty slice for codes
370    /// without curated cross-references.
371    pub const fn related(self) -> &'static [Code] {
372        match self {
373            // Type mismatches form a family — surfacing the others helps an
374            // agent disambiguate between assignment, argument, return, etc.
375            Code::TypeMismatch => &[
376                Code::AssignmentTypeMismatch,
377                Code::ArgumentTypeMismatch,
378                Code::ReturnTypeMismatch,
379                Code::VariableTypeMismatch,
380                Code::FieldTypeMismatch,
381            ],
382            Code::AssignmentTypeMismatch => &[Code::TypeMismatch, Code::VariableTypeMismatch],
383            Code::ArgumentTypeMismatch => &[Code::TypeMismatch, Code::GenericTypeArgumentMismatch],
384            Code::ReturnTypeMismatch => &[Code::TypeMismatch, Code::ClosureReturnTypeMismatch],
385            Code::VariableTypeMismatch => &[Code::TypeMismatch, Code::AssignmentTypeMismatch],
386            Code::ClosureReturnTypeMismatch => &[Code::ReturnTypeMismatch],
387            Code::FieldTypeMismatch => &[Code::TypeMismatch, Code::InvalidStructLiteral],
388            Code::MethodTypeMismatch => &[Code::TypeMismatch, Code::CallableExpected],
389            // Generic type-argument family.
390            Code::GenericTypeArgumentUnsupported => &[
391                Code::GenericTypeArgumentMismatch,
392                Code::GenericTypeArgumentArity,
393            ],
394            Code::GenericTypeArgumentMismatch => &[
395                Code::GenericTypeArgumentArity,
396                Code::WhereConstraintMismatch,
397            ],
398            Code::GenericTypeArgumentArity => {
399                &[Code::GenericTypeArgumentMismatch, Code::TypeParameterArity]
400            }
401            Code::TypeParameterArity => &[Code::GenericTypeArgumentArity],
402            Code::WhereConstraintMismatch => &[Code::GenericTypeArgumentMismatch],
403            // Naming.
404            Code::UndefinedVariable => &[Code::UndefinedFunction, Code::UnknownDeclaration],
405            Code::UndefinedFunction => &[Code::UnknownBuiltin, Code::UnknownDeclaration],
406            Code::UnknownField => &[Code::UnknownMethod, Code::InvalidStructLiteral],
407            Code::UnknownMethod => &[Code::UnknownField, Code::CallableExpected],
408            Code::UnknownAttribute => {
409                &[Code::InvalidAttributeArgument, Code::InvalidAttributeTarget]
410            }
411            Code::InvalidAttributeArgument => {
412                &[Code::UnknownAttribute, Code::InvalidAttributeTarget]
413            }
414            Code::InvalidAttributeTarget => {
415                &[Code::UnknownAttribute, Code::InvalidAttributeArgument]
416            }
417            // LLM call family — schema, options, provider branching.
418            Code::LlmSchemaMissing => &[Code::LlmSchemaInvalid, Code::UnknownLlmOption],
419            Code::LlmSchemaInvalid => &[Code::LlmSchemaMissing, Code::UnknownLlmOption],
420            Code::UnknownLlmOption => &[Code::DeprecatedLlmOption, Code::LlmSchemaInvalid],
421            Code::DeprecatedLlmOption => &[Code::UnknownLlmOption],
422            Code::LlmProviderIdentityBranch => &[Code::PromptProviderIdentityBranch],
423            // Prompt-template family.
424            Code::PromptTemplateParse => &[Code::PromptTargetMissing],
425            Code::PromptInjectionRisk => &[Code::LintPromptInjectionRisk],
426            Code::PromptProviderIdentityBranch => &[
427                Code::LlmProviderIdentityBranch,
428                Code::LintTemplateProviderIdentityBranch,
429            ],
430            Code::PromptVariantExplosion => &[Code::LintTemplateVariantExplosion],
431            // Capabilities.
432            Code::CapabilityResultUnchecked => {
433                &[Code::RescueOutsideFunction, Code::TryOutsideFunction]
434            }
435            Code::CapabilityUnknownOperation => &[Code::CapabilityCallStaticNameRequired],
436            Code::EffectInheritanceViolation => &[
437                Code::CapabilityPayloadInvalid,
438                Code::CapabilityBindingInvalid,
439            ],
440            // Recovery / match.
441            Code::RescueOutsideFunction => {
442                &[Code::TryOutsideFunction, Code::InvalidRescueConstruct]
443            }
444            Code::TryOutsideFunction => &[Code::RescueOutsideFunction],
445            Code::NonExhaustiveMatch => &[Code::InvalidMatchPattern, Code::DuplicateMatchArm],
446            Code::DuplicateMatchArm => &[Code::NonExhaustiveMatch, Code::LintDuplicateMatchArm],
447            // Module / import family.
448            Code::ModuleImportUnresolved => {
449                &[Code::ImportResolutionFailed, Code::ImportSymbolMissing]
450            }
451            Code::ModuleImportUnused => &[Code::LintUnusedImport],
452            Code::ImportResolutionFailed => {
453                &[Code::ModuleImportUnresolved, Code::ImportSymbolMissing]
454            }
455            Code::ImportCycle => &[Code::ImportResolutionFailed],
456            // Suspend / resume lifecycle.
457            Code::SuspendWorkerNotRunning => {
458                &[Code::ResumeWorkerNotSuspended, Code::ResumeWorkerClosed]
459            }
460            Code::ResumeConditionsInvalid => &[
461                Code::ResumeTriggerRegistrationFailed,
462                Code::ResumeTimeoutUnsupported,
463            ],
464            Code::ResumeWorkerNotSuspended => &[
465                Code::SuspendWorkerNotRunning,
466                Code::ConcurrentResumeConflict,
467            ],
468            Code::ResumeSnapshotInvalid => &[Code::ResumeWorkerNotSuspended],
469            Code::AwaitResumptionOutsideAgentLoop => &[Code::ResumeConditionsInvalid],
470            Code::ConcurrentResumeConflict => {
471                &[Code::ResumeWorkerNotSuspended, Code::ResumeWorkerClosed]
472            }
473            Code::ResumeTriggerRegistrationFailed => &[
474                Code::ResumeConditionsInvalid,
475                Code::ResumeTimeoutUnsupported,
476            ],
477            Code::ResumeTimeoutUnsupported => &[
478                Code::ResumeConditionsInvalid,
479                Code::ResumeTriggerRegistrationFailed,
480            ],
481            Code::ResumeInputInvalid => &[Code::ResumeWorkerNotSuspended],
482            Code::ResumeWorkerClosed => &[
483                Code::ResumeWorkerNotSuspended,
484                Code::ConcurrentResumeConflict,
485            ],
486            // Reminder lifecycle diagnostics share the same payload shape and
487            // propagation field, so nearby codes help route runtime vs lint
488            // failures to the right fix.
489            Code::ReminderUnknownOption => {
490                &[Code::ReminderInvalidShape, Code::ReminderUnknownPropagate]
491            }
492            Code::ReminderInvalidShape => {
493                &[Code::ReminderUnknownOption, Code::ReminderUnknownPropagate]
494            }
495            Code::ReminderUnknownPropagate => {
496                &[Code::ReminderUnknownOption, Code::ReminderInvalidShape]
497            }
498            Code::ReminderProviderMalformedSpec => &[Code::ReminderInvalidShape],
499            Code::ReminderProviderBloat => &[Code::ReminderInfiniteDiscardable],
500            Code::ReminderUnsupportedHookEvent => &[Code::ReminderProviderMalformedSpec],
501            // Ownership.
502            Code::ImmutableAssignment => &[Code::MutableNeverReassigned],
503            Code::MutableNeverReassigned => &[Code::LintMutableNeverReassigned],
504            // Lint pairs (drift between lint and runtime/typecheck codes).
505            Code::LintDeprecatedLlmOptions => &[Code::DeprecatedLlmOption, Code::UnknownLlmOption],
506            Code::LintPromptInjectionRisk => &[Code::PromptInjectionRisk],
507            Code::LintTemplateVariantExplosion => &[Code::PromptVariantExplosion],
508            Code::LintTemplateProviderIdentityBranch => &[Code::PromptProviderIdentityBranch],
509            Code::LintRenamedStdlibSymbol => &[Code::DeprecatedStdlibSymbol],
510            Code::LintAmbientClockBuiltin
511            | Code::LintAmbientStdioBuiltin
512            | Code::LintAmbientFsBuiltin
513            | Code::LintAmbientEnvBuiltin
514            | Code::LintAmbientRandomBuiltin
515            | Code::LintAmbientNetBuiltin => {
516                &[Code::InvalidMainSignature, Code::LintRenamedStdlibSymbol]
517            }
518            Code::SandboxCapabilityDenied => &[Code::CapabilityPayloadInvalid],
519            Code::LintMutableNeverReassigned => &[Code::MutableNeverReassigned],
520            Code::LintUnusedImport => &[Code::ModuleImportUnused],
521            Code::LintDuplicateMatchArm => &[Code::DuplicateMatchArm],
522            _ => &[],
523        }
524    }
525}
526
527impl fmt::Display for Code {
528    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
529        f.write_str(self.as_str())
530    }
531}
532
533/// Error returned when parsing an unknown diagnostic code.
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535pub struct ParseCodeError;
536
537impl fmt::Display for ParseCodeError {
538    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
539        f.write_str("unknown Harn diagnostic code")
540    }
541}
542
543impl std::error::Error for ParseCodeError {}
544
545impl FromStr for Code {
546    type Err = ParseCodeError;
547
548    fn from_str(value: &str) -> Result<Self, Self::Err> {
549        Code::ALL
550            .iter()
551            .copied()
552            .find(|code| code.as_str() == value)
553            .ok_or(ParseCodeError)
554    }
555}
556
557/// Autonomy ceiling of a proposed repair.
558///
559/// Agents and IDEs dispatch on this class to decide whether to auto-apply
560/// a fix, propose it as a suggestion, or escalate to a human. Variants
561/// are ordered from least to most disruptive — call sites can compare
562/// with `<=` to enforce a configured ceiling like
563/// `"apply anything up to behavior-preserving"`.
564///
565/// The wire-format strings (`format-only`, `behavior-preserving`, …) are
566/// the contract surface; renaming a variant string is a breaking change.
567#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
568pub enum RepairSafety {
569    /// Whitespace, trivia, or canonical layout only. No code structure
570    /// changes; safe to auto-apply.
571    FormatOnly,
572    /// Intended not to change observable runtime behavior (e.g. delete an
573    /// unreachable branch, drop a redundant cast).
574    BehaviorPreserving,
575    /// Confined to the current local scope or file. Runtime behavior may
576    /// change, but the blast radius does not cross a declaration boundary
577    /// or a public surface.
578    ScopeLocal,
579    /// Touches a signature, export, or call-site surface that other files
580    /// or external consumers can observe.
581    SurfaceChanging,
582    /// Required capabilities or sandbox profile may change as a result of
583    /// applying the repair (e.g. swapping `provider: "openai"` for a
584    /// capability flag widens the routing surface).
585    CapabilityChanging,
586    /// Planning hint only — agents should propose, never auto-apply.
587    /// Aligned with the `AutonomyTier::Suggest`/`ActWithApproval` rungs
588    /// in `trust_graph.rs`.
589    NeedsHuman,
590}
591
592impl RepairSafety {
593    pub const ALL: &'static [RepairSafety] = &[
594        RepairSafety::FormatOnly,
595        RepairSafety::BehaviorPreserving,
596        RepairSafety::ScopeLocal,
597        RepairSafety::SurfaceChanging,
598        RepairSafety::CapabilityChanging,
599        RepairSafety::NeedsHuman,
600    ];
601
602    /// Stable wire-format string. The contract surface — do not rename
603    /// without coordinating with `harn fix --safety <…>` callers and
604    /// downstream LSP/IDE clients.
605    pub const fn as_str(self) -> &'static str {
606        match self {
607            RepairSafety::FormatOnly => "format-only",
608            RepairSafety::BehaviorPreserving => "behavior-preserving",
609            RepairSafety::ScopeLocal => "scope-local",
610            RepairSafety::SurfaceChanging => "surface-changing",
611            RepairSafety::CapabilityChanging => "capability-changing",
612            RepairSafety::NeedsHuman => "needs-human",
613        }
614    }
615
616    /// True when `self` sits at or below `ceiling`. Used by
617    /// `harn fix --apply --safety <ceiling>` and IDE auto-apply policies
618    /// to decide whether a repair clears the configured autonomy bar.
619    pub const fn is_at_most(self, ceiling: RepairSafety) -> bool {
620        (self as u8) <= (ceiling as u8)
621    }
622}
623
624impl fmt::Display for RepairSafety {
625    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
626        f.write_str(self.as_str())
627    }
628}
629
630/// Error returned when parsing an unknown repair-safety string.
631#[derive(Debug, Clone, Copy, PartialEq, Eq)]
632pub struct ParseRepairSafetyError;
633
634impl fmt::Display for ParseRepairSafetyError {
635    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
636        f.write_str("unknown Harn repair-safety class")
637    }
638}
639
640impl std::error::Error for ParseRepairSafetyError {}
641
642impl FromStr for RepairSafety {
643    type Err = ParseRepairSafetyError;
644
645    fn from_str(value: &str) -> Result<Self, Self::Err> {
646        RepairSafety::ALL
647            .iter()
648            .copied()
649            .find(|safety| safety.as_str() == value)
650            .ok_or(ParseRepairSafetyError)
651    }
652}
653
654/// Namespaced kebab-case repair identifier (e.g. `imports/fix-path`).
655///
656/// Wraps a `Cow` so registry-driven values reuse a `'static` literal and
657/// per-site overrides can still attach an owned string. The wire-format
658/// string is the contract surface — never normalize or reformat on read.
659#[derive(Debug, Clone, PartialEq, Eq, Hash)]
660pub struct RepairId(std::borrow::Cow<'static, str>);
661
662impl RepairId {
663    pub const fn from_static(s: &'static str) -> Self {
664        RepairId(std::borrow::Cow::Borrowed(s))
665    }
666
667    pub fn from_owned(s: String) -> Self {
668        RepairId(std::borrow::Cow::Owned(s))
669    }
670
671    pub fn as_str(&self) -> &str {
672        &self.0
673    }
674}
675
676impl fmt::Display for RepairId {
677    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
678        f.write_str(&self.0)
679    }
680}
681
682/// A structured repair proposal attached to a diagnostic.
683///
684/// `id` and `summary` are agent-readable metadata; `safety` is the
685/// dispatch dimension that decides whether the repair clears an
686/// autonomy ceiling. The concrete edits, when known statically, live on
687/// the diagnostic's `fix: Option<Vec<FixEdit>>`; this `Repair` is the
688/// classifier above those edits, not a replacement for them.
689#[derive(Debug, Clone)]
690pub struct Repair {
691    pub id: RepairId,
692    pub summary: String,
693    pub safety: RepairSafety,
694}
695
696impl Repair {
697    pub fn from_template(template: &RepairTemplate) -> Self {
698        Repair {
699            id: RepairId::from_static(template.id),
700            summary: template.summary.to_string(),
701            safety: template.safety,
702        }
703    }
704}
705
706/// Static-lifetime repair template bound to a diagnostic code.
707///
708/// Stored in the registry alongside `Code`. Construction sites can
709/// materialize a `Repair` via [`Repair::from_template`] or override
710/// `summary` for instance-specific detail by building a `Repair`
711/// directly.
712#[derive(Debug, Clone, Copy)]
713pub struct RepairTemplate {
714    pub id: &'static str,
715    pub summary: &'static str,
716    pub safety: RepairSafety,
717}
718
719impl Code {
720    /// Look up the default repair template attached to this diagnostic
721    /// code, or `None` if no actionable fix shape is registered.
722    pub const fn repair_template(self) -> Option<&'static RepairTemplate> {
723        match self {
724            // --- TYP: type mismatches & coercions -------------------------
725            Code::TypeMismatch
726            | Code::ReturnTypeMismatch
727            | Code::AssignmentTypeMismatch
728            | Code::ArgumentTypeMismatch
729            | Code::VariableTypeMismatch
730            | Code::ClosureReturnTypeMismatch
731            | Code::FieldTypeMismatch
732            | Code::MethodTypeMismatch
733            | Code::InvalidIndexType => Some(&REPAIR_INSERT_EXPLICIT_CONVERSION),
734            Code::StringInterpolationRewrite => Some(&REPAIR_REWRITE_STRING_INTERPOLATION),
735            Code::UnknownTypeName => Some(&REPAIR_IMPORTS_FIX_PATH),
736            Code::InvalidCast => Some(&REPAIR_CASTS_REMOVE_UNCHECKED),
737
738            // --- NAM / IMP: imports & names -------------------------------
739            Code::UndefinedVariable
740            | Code::UndefinedFunction
741            | Code::UnknownField
742            | Code::UnknownMethod
743            | Code::UnknownBuiltin
744            | Code::UnknownDeclaration => Some(&REPAIR_BINDINGS_RENAME_TO_CLOSEST),
745            Code::InvalidMainSignature => Some(&REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM),
746            Code::DeprecatedFunction => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
747            Code::ModuleImportUnresolved | Code::ImportResolutionFailed => {
748                Some(&REPAIR_IMPORTS_FIX_PATH)
749            }
750            Code::ModuleImportUnused => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
751            Code::ModuleImportOrder => Some(&REPAIR_IMPORTS_REORDER),
752
753            // --- CAP / RCV: capabilities & error recovery -----------------
754            Code::CapabilityResultUnchecked => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
755            Code::CapabilityBindingInvalid => Some(&REPAIR_MANUAL_REVIEW_CAPABILITY),
756            Code::EffectInheritanceViolation => Some(&REPAIR_POLICY_NARROW_CHILD_EFFECTS),
757            Code::RescueOutsideFunction | Code::TryOutsideFunction => {
758                Some(&REPAIR_ERRORS_WRAP_IN_FN)
759            }
760
761            // --- LLM / PRM: model + prompt contract -----------------------
762            Code::DeprecatedLlmOption => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
763            Code::LlmSchemaMissing => Some(&REPAIR_LLM_ADD_SCHEMA),
764            Code::LlmProviderIdentityBranch | Code::PromptProviderIdentityBranch => {
765                Some(&REPAIR_LLM_USE_CAPABILITY_FLAG)
766            }
767            Code::PromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
768            Code::PromptToolSurfaceUnknown | Code::PromptToolSurfaceDeferredReference => {
769                Some(&REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE)
770            }
771            Code::PromptVariantExplosion => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
772
773            // --- STD: stdlib usage ----------------------------------------
774            Code::DeprecatedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
775            Code::LintMissingStdlibMetadata => Some(&REPAIR_DOC_ADD_STDLIB_METADATA),
776
777            // --- OWN: ownership & mutability ------------------------------
778            Code::ImmutableAssignment => Some(&REPAIR_BINDINGS_MAKE_MUTABLE),
779            Code::MutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
780
781            // --- MAT: match exhaustiveness --------------------------------
782            Code::NonExhaustiveMatch => Some(&REPAIR_MATCH_ADD_MISSING_ARMS),
783            Code::DuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
784
785            // --- ORC: orchestration ---------------------------------------
786            Code::UnreachableCode => Some(&REPAIR_DEAD_CODE_REMOVE),
787
788            // --- FMT: formatter -------------------------------------------
789            Code::FormatterWouldReformat | Code::FormatterTrailingComma => {
790                Some(&REPAIR_FORMAT_REFORMAT)
791            }
792
793            // --- LNT: lints with structured fixes -------------------------
794            Code::LintUnusedVariable
795            | Code::LintUnusedPatternBinding
796            | Code::LintUnusedParameter => Some(&REPAIR_BINDINGS_RENAME_UNUSED),
797            Code::LintUnusedImport => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
798            Code::LintUnusedFunction | Code::LintUnusedType => {
799                Some(&REPAIR_DECLARATIONS_REMOVE_UNUSED)
800            }
801            Code::LintMutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
802            Code::LintImportOrder => Some(&REPAIR_IMPORTS_REORDER),
803            Code::LintBlankLineBetweenItems
804            | Code::LintTrailingComma
805            | Code::LintUnnecessaryParentheses
806            | Code::LintRequireFileHeader => Some(&REPAIR_FORMAT_REFORMAT),
807            Code::LintLegacyDocComment => Some(&REPAIR_DOC_COMMENT_MIGRATE),
808            Code::LintEmptyBlock => Some(&REPAIR_BLOCK_REMOVE_EMPTY),
809            Code::LintUnnecessaryElseReturn | Code::LintLetThenReturn => {
810                Some(&REPAIR_CONTROL_FLOW_FLATTEN)
811            }
812            Code::LintRedundantNilTernary
813            | Code::LintUnnecessarySafeNavigation
814            | Code::LintPreferOptionalShorthand
815            | Code::LintComparisonToBool
816            | Code::LintPointlessComparison
817            | Code::LintConstantLogicalOperand => Some(&REPAIR_EXPRESSION_SIMPLIFY),
818            Code::LintUnnecessaryCast => Some(&REPAIR_CASTS_REMOVE_REDUNDANT),
819            Code::LintRedundantClone => Some(&REPAIR_CLONE_REMOVE_REDUNDANT),
820            Code::LintEagerCollectionConversion => Some(&REPAIR_COLLECTION_PREFER_LAZY),
821            Code::LintDeadCodeAfterReturn => Some(&REPAIR_DEAD_CODE_REMOVE),
822            Code::LintRenamedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
823            Code::LintAmbientClockBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_CLOCK),
824            Code::LintAmbientFsBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_FS),
825            Code::LintAmbientEnvBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_ENV),
826            Code::LintAmbientRandomBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_RANDOM),
827            Code::LintAmbientNetBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_NET),
828            Code::LintAmbientStdioBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS),
829            Code::LintDeprecatedLlmOptions => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
830            Code::LintTemplateProviderIdentityBranch => Some(&REPAIR_LLM_USE_CAPABILITY_FLAG),
831            Code::LintPromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
832            Code::LintShadowVariable => Some(&REPAIR_BINDINGS_RENAME_SHADOW),
833            Code::LintNamingConvention => Some(&REPAIR_STYLE_RENAME_TO_CONVENTION),
834            Code::LintUnhandledApprovalResult => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
835            Code::LintMissingHarndoc => Some(&REPAIR_DOC_ADD_HARNDOC),
836            Code::LintDuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
837            Code::LintUntypedDictAccess => Some(&REPAIR_TYPES_ADD_SHAPE_ANNOTATION),
838            Code::LintMcpToolAnnotations => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
839            Code::LintTemplateVariantExplosion | Code::LintLongRunningWithoutCleanup => {
840                Some(&REPAIR_MANUAL_NEEDS_HUMAN)
841            }
842
843            // Everything else: no statically known repair shape. Agents
844            // should treat these as "diagnose only" until a repair is
845            // registered.
846            _ => None,
847        }
848    }
849}
850
851// Repair-id catalog. Each `RepairTemplate` carries a kebab-case
852// namespaced id (`<namespace>/<verb-noun>`), a one-line summary written
853// in the imperative voice, and a `RepairSafety` class.
854//
855// Conventions:
856//   - Namespaces stay short: `bindings/`, `imports/`, `errors/`, `casts/`,
857//     `format/`, `llm/`, `prompts/`, `match/`, `stdlib/`, `lint/`,
858//     `doc/`, `style/`, `types/`, `manual/`.
859//   - Summary starts with a verb ("Replace…", "Remove…", "Insert…").
860//   - Safety must be the most permissive class that is still always true
861//     for every site this template attaches to. When unsure, pick the
862//     stricter class — agents tighten too-loose policies later, never
863//     too-tight ones.
864
865const REPAIR_INSERT_EXPLICIT_CONVERSION: RepairTemplate = RepairTemplate {
866    id: "casts/insert-explicit-conversion",
867    summary: "Insert an explicit conversion or correct the operand type",
868    safety: RepairSafety::ScopeLocal,
869};
870
871const REPAIR_REWRITE_STRING_INTERPOLATION: RepairTemplate = RepairTemplate {
872    id: "style/string-interpolation",
873    summary: "Rewrite string concatenation as an interpolation literal",
874    safety: RepairSafety::BehaviorPreserving,
875};
876
877const REPAIR_CASTS_REMOVE_UNCHECKED: RepairTemplate = RepairTemplate {
878    id: "casts/remove-unchecked",
879    summary: "Remove the unchecked cast or guard it with a type test",
880    safety: RepairSafety::ScopeLocal,
881};
882
883const REPAIR_CASTS_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
884    id: "casts/remove-redundant",
885    summary: "Remove the redundant cast",
886    safety: RepairSafety::BehaviorPreserving,
887};
888
889const REPAIR_BINDINGS_RENAME_TO_CLOSEST: RepairTemplate = RepairTemplate {
890    id: "bindings/rename-to-closest",
891    summary: "Rename to the closest in-scope identifier",
892    safety: RepairSafety::ScopeLocal,
893};
894
895const REPAIR_BINDINGS_MAKE_MUTABLE: RepairTemplate = RepairTemplate {
896    id: "bindings/make-mutable",
897    summary: "Mark the binding `mut` so it can be reassigned",
898    safety: RepairSafety::ScopeLocal,
899};
900
901const REPAIR_BINDINGS_MAKE_IMMUTABLE: RepairTemplate = RepairTemplate {
902    id: "bindings/make-immutable",
903    summary: "Drop `mut` since the binding is never reassigned",
904    safety: RepairSafety::BehaviorPreserving,
905};
906
907const REPAIR_BINDINGS_RENAME_UNUSED: RepairTemplate = RepairTemplate {
908    id: "bindings/rename-unused",
909    summary: "Prefix the unused binding with `_` to silence the lint",
910    safety: RepairSafety::BehaviorPreserving,
911};
912
913const REPAIR_BINDINGS_RENAME_SHADOW: RepairTemplate = RepairTemplate {
914    id: "bindings/rename-shadow",
915    summary: "Rename the shadowing binding to a distinct name",
916    safety: RepairSafety::ScopeLocal,
917};
918
919const REPAIR_BINDINGS_THREAD_HARNESS: RepairTemplate = RepairTemplate {
920    id: "bindings/thread-harness",
921    summary: "Thread the existing `harness` binding through local helper calls and replace the ambient stdio builtin with `harness.stdio.*`",
922    safety: RepairSafety::ScopeLocal,
923};
924
925const REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM: RepairTemplate = RepairTemplate {
926    id: "bindings/thread-harness-needs-param",
927    summary: "Add a `harness: Harness` parameter where the stdio capability handle is required and update local callers",
928    safety: RepairSafety::SurfaceChanging,
929};
930
931const REPAIR_BINDINGS_THREAD_HARNESS_CLOCK: RepairTemplate = RepairTemplate {
932    id: "bindings/thread-harness-clock",
933    summary: "Replace the ambient clock builtin with the corresponding `harness.clock.*` method",
934    safety: RepairSafety::ScopeLocal,
935};
936
937const REPAIR_BINDINGS_THREAD_HARNESS_FS: RepairTemplate = RepairTemplate {
938    id: "bindings/thread-harness-fs",
939    summary: "Replace the ambient fs builtin with the corresponding `harness.fs.*` method",
940    safety: RepairSafety::ScopeLocal,
941};
942
943const REPAIR_BINDINGS_THREAD_HARNESS_ENV: RepairTemplate = RepairTemplate {
944    id: "bindings/thread-harness-env",
945    summary: "Replace the ambient env builtin with the corresponding `harness.env.*` method",
946    safety: RepairSafety::ScopeLocal,
947};
948
949const REPAIR_BINDINGS_THREAD_HARNESS_RANDOM: RepairTemplate = RepairTemplate {
950    id: "bindings/thread-harness-random",
951    summary: "Replace the ambient random builtin with the corresponding `harness.random.*` method",
952    safety: RepairSafety::ScopeLocal,
953};
954
955const REPAIR_BINDINGS_THREAD_HARNESS_NET: RepairTemplate = RepairTemplate {
956    id: "bindings/thread-harness-net",
957    summary: "Replace the ambient net builtin with the corresponding `harness.net.*` method",
958    safety: RepairSafety::ScopeLocal,
959};
960
961const REPAIR_DECLARATIONS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
962    id: "declarations/remove-unused",
963    summary: "Remove the unused declaration",
964    safety: RepairSafety::SurfaceChanging,
965};
966
967const REPAIR_IMPORTS_FIX_PATH: RepairTemplate = RepairTemplate {
968    id: "imports/fix-path",
969    summary: "Replace the import path with a resolvable target",
970    safety: RepairSafety::ScopeLocal,
971};
972
973const REPAIR_IMPORTS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
974    id: "imports/remove-unused",
975    summary: "Remove the unused import",
976    safety: RepairSafety::BehaviorPreserving,
977};
978
979const REPAIR_IMPORTS_REORDER: RepairTemplate = RepairTemplate {
980    id: "imports/reorder",
981    summary: "Reorder imports into canonical grouping",
982    safety: RepairSafety::FormatOnly,
983};
984
985const REPAIR_ERRORS_CHECK_OR_RESCUE: RepairTemplate = RepairTemplate {
986    id: "errors/check-or-rescue",
987    summary: "Check the result or wrap the call in a `rescue` block",
988    safety: RepairSafety::ScopeLocal,
989};
990
991const REPAIR_ERRORS_WRAP_IN_FN: RepairTemplate = RepairTemplate {
992    id: "errors/wrap-in-fn",
993    summary: "Move the construct inside a function body",
994    safety: RepairSafety::SurfaceChanging,
995};
996
997const REPAIR_MATCH_ADD_MISSING_ARMS: RepairTemplate = RepairTemplate {
998    id: "match/add-missing-arms",
999    summary: "Add arms covering the missing variants",
1000    safety: RepairSafety::ScopeLocal,
1001};
1002
1003const REPAIR_MATCH_REMOVE_DUPLICATE_ARM: RepairTemplate = RepairTemplate {
1004    id: "match/remove-duplicate-arm",
1005    summary: "Remove the duplicated match arm",
1006    safety: RepairSafety::BehaviorPreserving,
1007};
1008
1009const REPAIR_FORMAT_REFORMAT: RepairTemplate = RepairTemplate {
1010    id: "format/reformat",
1011    summary: "Apply canonical formatting",
1012    safety: RepairSafety::FormatOnly,
1013};
1014
1015const REPAIR_DOC_COMMENT_MIGRATE: RepairTemplate = RepairTemplate {
1016    id: "doc/migrate-comment-style",
1017    summary: "Migrate the legacy comment to canonical doc syntax",
1018    safety: RepairSafety::FormatOnly,
1019};
1020
1021const REPAIR_DOC_ADD_HARNDOC: RepairTemplate = RepairTemplate {
1022    id: "doc/add-harndoc",
1023    summary: "Add a `///` doc comment describing this declaration",
1024    safety: RepairSafety::BehaviorPreserving,
1025};
1026
1027const REPAIR_DOC_ADD_STDLIB_METADATA: RepairTemplate = RepairTemplate {
1028    id: "doc/add-stdlib-metadata",
1029    summary: "Add `@effects`, `@allocation`, `@errors`, `@api_stability`, and `@example` fields to the stdlib function's doc block",
1030    safety: RepairSafety::BehaviorPreserving,
1031};
1032
1033const REPAIR_BLOCK_REMOVE_EMPTY: RepairTemplate = RepairTemplate {
1034    id: "blocks/remove-empty",
1035    summary: "Remove the empty block or fill in an explicit body",
1036    safety: RepairSafety::ScopeLocal,
1037};
1038
1039const REPAIR_CONTROL_FLOW_FLATTEN: RepairTemplate = RepairTemplate {
1040    id: "control-flow/flatten",
1041    summary: "Flatten the unnecessary control flow construct",
1042    safety: RepairSafety::BehaviorPreserving,
1043};
1044
1045const REPAIR_EXPRESSION_SIMPLIFY: RepairTemplate = RepairTemplate {
1046    id: "expressions/simplify",
1047    summary: "Simplify the expression to its canonical form",
1048    safety: RepairSafety::BehaviorPreserving,
1049};
1050
1051const REPAIR_CLONE_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
1052    id: "clones/remove-redundant",
1053    summary: "Remove the redundant clone",
1054    safety: RepairSafety::BehaviorPreserving,
1055};
1056
1057const REPAIR_COLLECTION_PREFER_LAZY: RepairTemplate = RepairTemplate {
1058    id: "collections/prefer-lazy",
1059    summary: "Replace the eager collection step with a lazy variant",
1060    safety: RepairSafety::ScopeLocal,
1061};
1062
1063const REPAIR_DEAD_CODE_REMOVE: RepairTemplate = RepairTemplate {
1064    id: "control-flow/remove-dead",
1065    summary: "Remove the unreachable code",
1066    safety: RepairSafety::BehaviorPreserving,
1067};
1068
1069const REPAIR_STDLIB_MIGRATE_RENAMED: RepairTemplate = RepairTemplate {
1070    id: "stdlib/migrate-renamed",
1071    summary: "Rename the call to the renamed stdlib symbol",
1072    safety: RepairSafety::ScopeLocal,
1073};
1074
1075const REPAIR_LLM_MIGRATE_DEPRECATED_OPTION: RepairTemplate = RepairTemplate {
1076    id: "llm/migrate-deprecated-option",
1077    summary: "Replace the deprecated option with its supported equivalent",
1078    safety: RepairSafety::ScopeLocal,
1079};
1080
1081const REPAIR_LLM_ADD_SCHEMA: RepairTemplate = RepairTemplate {
1082    id: "llm/add-schema",
1083    summary: "Add a typed output schema to the LLM call",
1084    safety: RepairSafety::SurfaceChanging,
1085};
1086
1087const REPAIR_LLM_USE_CAPABILITY_FLAG: RepairTemplate = RepairTemplate {
1088    id: "llm/use-capability-flag",
1089    summary: "Branch on a capability flag instead of provider identity",
1090    safety: RepairSafety::CapabilityChanging,
1091};
1092
1093const REPAIR_PROMPTS_ESCAPE_INJECTION: RepairTemplate = RepairTemplate {
1094    id: "prompts/escape-injection",
1095    summary: "Pass the untrusted input through a structured placeholder",
1096    safety: RepairSafety::ScopeLocal,
1097};
1098
1099const REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE: RepairTemplate = RepairTemplate {
1100    id: "prompts/add-tool-to-surface",
1101    summary: "Add the referenced tool to the declared tool surface",
1102    safety: RepairSafety::SurfaceChanging,
1103};
1104
1105const REPAIR_STYLE_RENAME_TO_CONVENTION: RepairTemplate = RepairTemplate {
1106    id: "style/rename-to-convention",
1107    summary: "Rename to match the casing convention for this kind",
1108    safety: RepairSafety::SurfaceChanging,
1109};
1110
1111const REPAIR_TYPES_ADD_SHAPE_ANNOTATION: RepairTemplate = RepairTemplate {
1112    id: "types/add-shape-annotation",
1113    summary: "Annotate the dict with a concrete shape type",
1114    safety: RepairSafety::SurfaceChanging,
1115};
1116
1117const REPAIR_MANUAL_REVIEW_CAPABILITY: RepairTemplate = RepairTemplate {
1118    id: "manual/review-capability-binding",
1119    summary: "Review the capability binding; the fix is not mechanical",
1120    safety: RepairSafety::NeedsHuman,
1121};
1122
1123const REPAIR_POLICY_NARROW_CHILD_EFFECTS: RepairTemplate = RepairTemplate {
1124    id: "policy/narrow-child-effects",
1125    summary: "Narrow the child agent's effects to a subset of the parent's, or widen the parent's declared effects",
1126    safety: RepairSafety::SurfaceChanging,
1127};
1128
1129const REPAIR_MANUAL_NEEDS_HUMAN: RepairTemplate = RepairTemplate {
1130    id: "manual/needs-human",
1131    summary: "Plan a human-led change; auto-apply is not safe here",
1132    safety: RepairSafety::NeedsHuman,
1133};
1134
1135/// Every distinct repair template registered by [`Code::repair_template`],
1136/// in source order. Used by the catalog wire-up in E1.7 and by tests
1137/// asserting the catalog is healthy.
1138pub const REPAIR_REGISTRY: &[&RepairTemplate] = &[
1139    &REPAIR_INSERT_EXPLICIT_CONVERSION,
1140    &REPAIR_REWRITE_STRING_INTERPOLATION,
1141    &REPAIR_CASTS_REMOVE_UNCHECKED,
1142    &REPAIR_CASTS_REMOVE_REDUNDANT,
1143    &REPAIR_BINDINGS_RENAME_TO_CLOSEST,
1144    &REPAIR_BINDINGS_MAKE_MUTABLE,
1145    &REPAIR_BINDINGS_MAKE_IMMUTABLE,
1146    &REPAIR_BINDINGS_RENAME_UNUSED,
1147    &REPAIR_BINDINGS_RENAME_SHADOW,
1148    &REPAIR_BINDINGS_THREAD_HARNESS,
1149    &REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM,
1150    &REPAIR_BINDINGS_THREAD_HARNESS_CLOCK,
1151    &REPAIR_BINDINGS_THREAD_HARNESS_FS,
1152    &REPAIR_BINDINGS_THREAD_HARNESS_ENV,
1153    &REPAIR_BINDINGS_THREAD_HARNESS_RANDOM,
1154    &REPAIR_BINDINGS_THREAD_HARNESS_NET,
1155    &REPAIR_DECLARATIONS_REMOVE_UNUSED,
1156    &REPAIR_IMPORTS_FIX_PATH,
1157    &REPAIR_IMPORTS_REMOVE_UNUSED,
1158    &REPAIR_IMPORTS_REORDER,
1159    &REPAIR_ERRORS_CHECK_OR_RESCUE,
1160    &REPAIR_ERRORS_WRAP_IN_FN,
1161    &REPAIR_MATCH_ADD_MISSING_ARMS,
1162    &REPAIR_MATCH_REMOVE_DUPLICATE_ARM,
1163    &REPAIR_FORMAT_REFORMAT,
1164    &REPAIR_DOC_COMMENT_MIGRATE,
1165    &REPAIR_DOC_ADD_HARNDOC,
1166    &REPAIR_DOC_ADD_STDLIB_METADATA,
1167    &REPAIR_BLOCK_REMOVE_EMPTY,
1168    &REPAIR_CONTROL_FLOW_FLATTEN,
1169    &REPAIR_EXPRESSION_SIMPLIFY,
1170    &REPAIR_CLONE_REMOVE_REDUNDANT,
1171    &REPAIR_COLLECTION_PREFER_LAZY,
1172    &REPAIR_DEAD_CODE_REMOVE,
1173    &REPAIR_STDLIB_MIGRATE_RENAMED,
1174    &REPAIR_LLM_MIGRATE_DEPRECATED_OPTION,
1175    &REPAIR_LLM_ADD_SCHEMA,
1176    &REPAIR_LLM_USE_CAPABILITY_FLAG,
1177    &REPAIR_PROMPTS_ESCAPE_INJECTION,
1178    &REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE,
1179    &REPAIR_STYLE_RENAME_TO_CONVENTION,
1180    &REPAIR_TYPES_ADD_SHAPE_ANNOTATION,
1181    &REPAIR_MANUAL_REVIEW_CAPABILITY,
1182    &REPAIR_MANUAL_NEEDS_HUMAN,
1183    &REPAIR_POLICY_NARROW_CHILD_EFFECTS,
1184];
1185
1186#[cfg(test)]
1187mod tests {
1188    use super::{Category, Code, ParseRepairSafetyError, RepairSafety, REPAIR_REGISTRY};
1189    use std::collections::HashSet;
1190    use std::str::FromStr;
1191
1192    #[test]
1193    fn parses_registered_code() {
1194        assert_eq!(Code::from_str("HARN-TYP-014"), Ok(Code::TypeParameterArity));
1195    }
1196
1197    #[test]
1198    fn registry_has_unique_identifiers() {
1199        let mut seen = HashSet::new();
1200        for entry in Code::registry() {
1201            assert!(
1202                seen.insert(entry.identifier),
1203                "duplicate diagnostic code {}",
1204                entry.identifier
1205            );
1206            assert_eq!(entry.code.as_str(), entry.identifier);
1207            assert_eq!(entry.code.category(), entry.category);
1208            let expected_prefix = format!("HARN-{}-", entry.category);
1209            assert!(entry.identifier.starts_with(&expected_prefix));
1210            let suffix = entry.identifier.trim_start_matches(&expected_prefix);
1211            assert_eq!(suffix.len(), 3);
1212            assert!(suffix.chars().all(|ch| ch.is_ascii_digit()));
1213            assert!(!entry.summary.is_empty());
1214        }
1215        assert!(Code::registry().len() >= 40);
1216    }
1217
1218    #[test]
1219    fn every_category_is_populated() {
1220        for category in Category::ALL {
1221            assert!(
1222                Code::registry()
1223                    .iter()
1224                    .any(|entry| entry.category == *category),
1225                "missing diagnostic code category {category}"
1226            );
1227        }
1228    }
1229
1230    #[test]
1231    fn every_code_has_non_empty_explanation() {
1232        for entry in Code::registry() {
1233            let body = entry.code.explanation();
1234            assert!(
1235                !body.trim().is_empty(),
1236                "diagnostic code {} has an empty explanation file",
1237                entry.identifier
1238            );
1239            assert!(
1240                body.contains(entry.identifier),
1241                "explanation for {} should reference its identifier",
1242                entry.identifier
1243            );
1244        }
1245    }
1246
1247    #[test]
1248    fn related_codes_are_registered_and_non_self() {
1249        for entry in Code::registry() {
1250            for &other in entry.code.related() {
1251                assert_ne!(
1252                    other, entry.code,
1253                    "{} lists itself as a related code",
1254                    entry.identifier
1255                );
1256                assert!(
1257                    Code::registry().iter().any(|e| e.code == other),
1258                    "{} lists unregistered related code {}",
1259                    entry.identifier,
1260                    other
1261                );
1262            }
1263        }
1264    }
1265
1266    #[test]
1267    fn repair_safety_string_roundtrip() {
1268        for safety in RepairSafety::ALL {
1269            let parsed = RepairSafety::from_str(safety.as_str()).unwrap();
1270            assert_eq!(parsed, *safety);
1271            assert_eq!(parsed.to_string(), safety.as_str());
1272        }
1273        assert_eq!(
1274            RepairSafety::from_str("not-a-safety-class"),
1275            Err(ParseRepairSafetyError)
1276        );
1277    }
1278
1279    #[test]
1280    fn repair_safety_ordering_is_monotonic_low_to_high() {
1281        // The is_at_most ceiling check relies on this ordering being
1282        // least-to-most disruptive; a regression here flips the meaning
1283        // of `harn fix --safety <ceiling>` for every caller.
1284        let order = RepairSafety::ALL;
1285        for window in order.windows(2) {
1286            assert!(
1287                window[0] < window[1],
1288                "{:?} should be safer than {:?}",
1289                window[0],
1290                window[1]
1291            );
1292            assert!(window[0].is_at_most(window[1]));
1293            assert!(!window[1].is_at_most(window[0]));
1294        }
1295    }
1296
1297    #[test]
1298    fn repair_registry_has_at_least_twenty_entries() {
1299        assert!(
1300            REPAIR_REGISTRY.len() >= 20,
1301            "expected ≥20 repair templates, found {}",
1302            REPAIR_REGISTRY.len()
1303        );
1304    }
1305
1306    #[test]
1307    fn repair_ids_are_kebab_case_namespaced_and_unique() {
1308        let mut seen = HashSet::new();
1309        for template in REPAIR_REGISTRY {
1310            assert!(
1311                seen.insert(template.id),
1312                "duplicate repair id {}",
1313                template.id
1314            );
1315            let (namespace, leaf) = template.id.split_once('/').unwrap_or_else(|| {
1316                panic!(
1317                    "repair id `{}` is missing `<namespace>/` prefix",
1318                    template.id
1319                )
1320            });
1321            assert!(
1322                !namespace.is_empty() && !leaf.is_empty(),
1323                "repair id `{}` has empty namespace or leaf",
1324                template.id
1325            );
1326            for ch in template.id.chars() {
1327                assert!(
1328                    ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '/',
1329                    "repair id `{}` has non-kebab character {ch:?}",
1330                    template.id
1331                );
1332            }
1333            assert!(
1334                !template.summary.is_empty(),
1335                "repair {} has empty summary",
1336                template.id
1337            );
1338            // Summaries are imperative: start with a capital ASCII letter.
1339            let first = template.summary.chars().next().unwrap();
1340            assert!(
1341                first.is_ascii_uppercase(),
1342                "repair {} summary `{}` should start with a capital",
1343                template.id,
1344                template.summary
1345            );
1346        }
1347    }
1348
1349    #[test]
1350    fn manual_namespace_is_needs_human() {
1351        for template in REPAIR_REGISTRY {
1352            if let Some(("manual", _)) = template.id.split_once('/') {
1353                assert_eq!(
1354                    template.safety,
1355                    RepairSafety::NeedsHuman,
1356                    "manual/* repair {} must be NeedsHuman",
1357                    template.id
1358                );
1359            }
1360        }
1361    }
1362
1363    #[test]
1364    fn known_codes_carry_expected_safety_class() {
1365        // Spot-check: the autonomy contract for several representative
1366        // diagnostics. Lock in the safety class so cross-repo agents that
1367        // dispatch on these don't silently drift when the catalog moves.
1368        let expected: &[(Code, RepairSafety, &str)] = &[
1369            (
1370                Code::FormatterWouldReformat,
1371                RepairSafety::FormatOnly,
1372                "format/reformat",
1373            ),
1374            (
1375                Code::ModuleImportUnused,
1376                RepairSafety::BehaviorPreserving,
1377                "imports/remove-unused",
1378            ),
1379            (
1380                Code::ImmutableAssignment,
1381                RepairSafety::ScopeLocal,
1382                "bindings/make-mutable",
1383            ),
1384            (
1385                Code::LintUnusedFunction,
1386                RepairSafety::SurfaceChanging,
1387                "declarations/remove-unused",
1388            ),
1389            (
1390                Code::LlmProviderIdentityBranch,
1391                RepairSafety::CapabilityChanging,
1392                "llm/use-capability-flag",
1393            ),
1394            (
1395                Code::PromptVariantExplosion,
1396                RepairSafety::NeedsHuman,
1397                "manual/needs-human",
1398            ),
1399            (
1400                Code::NonExhaustiveMatch,
1401                RepairSafety::ScopeLocal,
1402                "match/add-missing-arms",
1403            ),
1404            (
1405                Code::LintAmbientClockBuiltin,
1406                RepairSafety::ScopeLocal,
1407                "bindings/thread-harness-clock",
1408            ),
1409            (
1410                Code::LintAmbientStdioBuiltin,
1411                RepairSafety::ScopeLocal,
1412                "bindings/thread-harness",
1413            ),
1414            (
1415                Code::InvalidMainSignature,
1416                RepairSafety::SurfaceChanging,
1417                "bindings/thread-harness-needs-param",
1418            ),
1419        ];
1420        for (code, safety, repair_id) in expected {
1421            let template = code
1422                .repair_template()
1423                .unwrap_or_else(|| panic!("{code} should have a repair template"));
1424            assert_eq!(template.safety, *safety, "{code} safety class drifted");
1425            assert_eq!(template.id, *repair_id, "{code} repair id drifted");
1426        }
1427    }
1428
1429    #[test]
1430    fn repair_templates_cover_at_least_twenty_codes() {
1431        let covered = Code::ALL
1432            .iter()
1433            .filter(|code| code.repair_template().is_some())
1434            .count();
1435        assert!(
1436            covered >= 20,
1437            "expected ≥20 codes with a repair template, found {covered}"
1438        );
1439    }
1440
1441    #[test]
1442    fn every_registered_repair_is_referenced_by_some_code() {
1443        let referenced: HashSet<&'static str> = Code::ALL
1444            .iter()
1445            .filter_map(|code| code.repair_template())
1446            .map(|template| template.id)
1447            .collect();
1448        for template in REPAIR_REGISTRY {
1449            assert!(
1450                referenced.contains(template.id),
1451                "repair {} is in REPAIR_REGISTRY but no Code maps to it",
1452                template.id
1453            );
1454        }
1455    }
1456
1457    #[test]
1458    fn every_referenced_repair_template_is_in_registry() {
1459        let registered: HashSet<&'static str> =
1460            REPAIR_REGISTRY.iter().map(|template| template.id).collect();
1461        for code in Code::ALL {
1462            let Some(template) = code.repair_template() else {
1463                continue;
1464            };
1465            assert!(
1466                registered.contains(template.id),
1467                "repair {} (used by {}) is missing from REPAIR_REGISTRY",
1468                template.id,
1469                code
1470            );
1471        }
1472    }
1473}