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    LintVacuousCondition, "HARN-LNT-058", Lnt, "if / while / guard condition is statically known to always succeed or always fail";
337    SandboxCapabilityDenied, "HARN-CAP-201", Cap, "harness capability denied by active sandbox profile";
338    FormatterParseFailed, "HARN-FMT-001", Fmt, "formatter could not parse the source";
339    FormatterWouldReformat, "HARN-FMT-002", Fmt, "source is not in canonical format";
340    FormatterTrailingComma, "HARN-FMT-003", Fmt, "formatter normalized trailing comma layout";
341    ImportResolutionFailed, "HARN-IMP-001", Imp, "import target cannot be resolved";
342    ImportSymbolMissing, "HARN-IMP-002", Imp, "imported symbol does not exist";
343    ImportCycle, "HARN-IMP-003", Imp, "import graph contains a cycle";
344    ImmutableAssignment, "HARN-OWN-001", Own, "immutable binding is reassigned";
345    MutableNeverReassigned, "HARN-OWN-002", Own, "mutable binding is never reassigned";
346    OwnershipEscape, "HARN-OWN-003", Own, "owned value escapes its valid scope";
347    BoundaryValueUnvalidated, "HARN-OWN-004", Own, "unvalidated boundary value is used directly";
348    RescueOutsideFunction, "HARN-RCV-001", Rcv, "rescue construct is outside a function body";
349    TryOutsideFunction, "HARN-RCV-002", Rcv, "try construct is outside a function body";
350    InvalidRescueConstruct, "HARN-RCV-003", Rcv, "rescue construct is invalid";
351    NonExhaustiveMatch, "HARN-MAT-001", Mat, "match expression is not exhaustive";
352    DuplicateMatchArm, "HARN-MAT-002", Mat, "match expression contains a duplicate arm";
353    InvalidMatchPattern, "HARN-MAT-003", Mat, "match pattern is invalid";
354    PoolBackpressureFull, "HARN-POL-001", Pol, "pool backpressure rejected a submit";
355    PoolFailFastFull, "HARN-POL-002", Pol, "fail-fast pool has no immediate capacity";
356    ConstEvalDisallowedExpression, "HARN-MET-001", Met, "expression is not permitted in a const initializer";
357    ConstEvalStepLimit, "HARN-CST-001", Cst, "const initializer exceeded the step budget";
358    ConstEvalRecursionLimit, "HARN-CST-002", Cst, "const initializer exceeded the recursion depth budget";
359    ConstEvalSandboxViolation, "HARN-CST-003", Cst, "const initializer attempted a sandboxed capability";
360    ConstEvalRuntimeError, "HARN-CST-004", Cst, "const initializer raised a runtime error during evaluation";
361}
362
363impl Code {
364    pub const fn registry() -> &'static [RegistryEntry] {
365        REGISTRY
366    }
367
368    /// Codes that an agent should consider alongside this one when planning
369    /// repairs. Curated per-code — typically near-neighbours in the same
370    /// category that share a fix shape. Returns an empty slice for codes
371    /// without curated cross-references.
372    pub const fn related(self) -> &'static [Code] {
373        match self {
374            // Type mismatches form a family — surfacing the others helps an
375            // agent disambiguate between assignment, argument, return, etc.
376            Code::TypeMismatch => &[
377                Code::AssignmentTypeMismatch,
378                Code::ArgumentTypeMismatch,
379                Code::ReturnTypeMismatch,
380                Code::VariableTypeMismatch,
381                Code::FieldTypeMismatch,
382            ],
383            Code::AssignmentTypeMismatch => &[Code::TypeMismatch, Code::VariableTypeMismatch],
384            Code::ArgumentTypeMismatch => &[Code::TypeMismatch, Code::GenericTypeArgumentMismatch],
385            Code::ReturnTypeMismatch => &[Code::TypeMismatch, Code::ClosureReturnTypeMismatch],
386            Code::VariableTypeMismatch => &[Code::TypeMismatch, Code::AssignmentTypeMismatch],
387            Code::ClosureReturnTypeMismatch => &[Code::ReturnTypeMismatch],
388            Code::FieldTypeMismatch => &[Code::TypeMismatch, Code::InvalidStructLiteral],
389            Code::MethodTypeMismatch => &[Code::TypeMismatch, Code::CallableExpected],
390            // Generic type-argument family.
391            Code::GenericTypeArgumentUnsupported => &[
392                Code::GenericTypeArgumentMismatch,
393                Code::GenericTypeArgumentArity,
394            ],
395            Code::GenericTypeArgumentMismatch => &[
396                Code::GenericTypeArgumentArity,
397                Code::WhereConstraintMismatch,
398            ],
399            Code::GenericTypeArgumentArity => {
400                &[Code::GenericTypeArgumentMismatch, Code::TypeParameterArity]
401            }
402            Code::TypeParameterArity => &[Code::GenericTypeArgumentArity],
403            Code::WhereConstraintMismatch => &[Code::GenericTypeArgumentMismatch],
404            // Naming.
405            Code::UndefinedVariable => &[Code::UndefinedFunction, Code::UnknownDeclaration],
406            Code::UndefinedFunction => &[Code::UnknownBuiltin, Code::UnknownDeclaration],
407            Code::UnknownField => &[Code::UnknownMethod, Code::InvalidStructLiteral],
408            Code::UnknownMethod => &[Code::UnknownField, Code::CallableExpected],
409            Code::UnknownAttribute => {
410                &[Code::InvalidAttributeArgument, Code::InvalidAttributeTarget]
411            }
412            Code::InvalidAttributeArgument => {
413                &[Code::UnknownAttribute, Code::InvalidAttributeTarget]
414            }
415            Code::InvalidAttributeTarget => {
416                &[Code::UnknownAttribute, Code::InvalidAttributeArgument]
417            }
418            // LLM call family — schema, options, provider branching.
419            Code::LlmSchemaMissing => &[Code::LlmSchemaInvalid, Code::UnknownLlmOption],
420            Code::LlmSchemaInvalid => &[Code::LlmSchemaMissing, Code::UnknownLlmOption],
421            Code::UnknownLlmOption => &[Code::DeprecatedLlmOption, Code::LlmSchemaInvalid],
422            Code::DeprecatedLlmOption => &[Code::UnknownLlmOption],
423            Code::LlmProviderIdentityBranch => &[Code::PromptProviderIdentityBranch],
424            // Prompt-template family.
425            Code::PromptTemplateParse => &[Code::PromptTargetMissing],
426            Code::PromptInjectionRisk => &[Code::LintPromptInjectionRisk],
427            Code::PromptProviderIdentityBranch => &[
428                Code::LlmProviderIdentityBranch,
429                Code::LintTemplateProviderIdentityBranch,
430            ],
431            Code::PromptVariantExplosion => &[Code::LintTemplateVariantExplosion],
432            // Capabilities.
433            Code::CapabilityResultUnchecked => {
434                &[Code::RescueOutsideFunction, Code::TryOutsideFunction]
435            }
436            Code::CapabilityUnknownOperation => &[Code::CapabilityCallStaticNameRequired],
437            Code::EffectInheritanceViolation => &[
438                Code::CapabilityPayloadInvalid,
439                Code::CapabilityBindingInvalid,
440            ],
441            // Recovery / match.
442            Code::RescueOutsideFunction => {
443                &[Code::TryOutsideFunction, Code::InvalidRescueConstruct]
444            }
445            Code::TryOutsideFunction => &[Code::RescueOutsideFunction],
446            Code::NonExhaustiveMatch => &[Code::InvalidMatchPattern, Code::DuplicateMatchArm],
447            Code::DuplicateMatchArm => &[Code::NonExhaustiveMatch, Code::LintDuplicateMatchArm],
448            // Module / import family.
449            Code::ModuleImportUnresolved => {
450                &[Code::ImportResolutionFailed, Code::ImportSymbolMissing]
451            }
452            Code::ModuleImportUnused => &[Code::LintUnusedImport],
453            Code::ImportResolutionFailed => {
454                &[Code::ModuleImportUnresolved, Code::ImportSymbolMissing]
455            }
456            Code::ImportCycle => &[Code::ImportResolutionFailed],
457            // Suspend / resume lifecycle.
458            Code::SuspendWorkerNotRunning => {
459                &[Code::ResumeWorkerNotSuspended, Code::ResumeWorkerClosed]
460            }
461            Code::ResumeConditionsInvalid => &[
462                Code::ResumeTriggerRegistrationFailed,
463                Code::ResumeTimeoutUnsupported,
464            ],
465            Code::ResumeWorkerNotSuspended => &[
466                Code::SuspendWorkerNotRunning,
467                Code::ConcurrentResumeConflict,
468            ],
469            Code::ResumeSnapshotInvalid => &[Code::ResumeWorkerNotSuspended],
470            Code::AwaitResumptionOutsideAgentLoop => &[Code::ResumeConditionsInvalid],
471            Code::ConcurrentResumeConflict => {
472                &[Code::ResumeWorkerNotSuspended, Code::ResumeWorkerClosed]
473            }
474            Code::ResumeTriggerRegistrationFailed => &[
475                Code::ResumeConditionsInvalid,
476                Code::ResumeTimeoutUnsupported,
477            ],
478            Code::ResumeTimeoutUnsupported => &[
479                Code::ResumeConditionsInvalid,
480                Code::ResumeTriggerRegistrationFailed,
481            ],
482            Code::ResumeInputInvalid => &[Code::ResumeWorkerNotSuspended],
483            Code::ResumeWorkerClosed => &[
484                Code::ResumeWorkerNotSuspended,
485                Code::ConcurrentResumeConflict,
486            ],
487            // Reminder lifecycle diagnostics share the same payload shape and
488            // propagation field, so nearby codes help route runtime vs lint
489            // failures to the right fix.
490            Code::ReminderUnknownOption => {
491                &[Code::ReminderInvalidShape, Code::ReminderUnknownPropagate]
492            }
493            Code::ReminderInvalidShape => {
494                &[Code::ReminderUnknownOption, Code::ReminderUnknownPropagate]
495            }
496            Code::ReminderUnknownPropagate => {
497                &[Code::ReminderUnknownOption, Code::ReminderInvalidShape]
498            }
499            Code::ReminderProviderMalformedSpec => &[Code::ReminderInvalidShape],
500            Code::ReminderProviderBloat => &[Code::ReminderInfiniteDiscardable],
501            Code::ReminderUnsupportedHookEvent => &[Code::ReminderProviderMalformedSpec],
502            // Ownership.
503            Code::ImmutableAssignment => &[Code::MutableNeverReassigned],
504            Code::MutableNeverReassigned => &[Code::LintMutableNeverReassigned],
505            // Lint pairs (drift between lint and runtime/typecheck codes).
506            Code::LintDeprecatedLlmOptions => &[Code::DeprecatedLlmOption, Code::UnknownLlmOption],
507            Code::LintPromptInjectionRisk => &[Code::PromptInjectionRisk],
508            Code::LintTemplateVariantExplosion => &[Code::PromptVariantExplosion],
509            Code::LintTemplateProviderIdentityBranch => &[Code::PromptProviderIdentityBranch],
510            Code::LintRenamedStdlibSymbol => &[Code::DeprecatedStdlibSymbol],
511            Code::LintAmbientClockBuiltin
512            | Code::LintAmbientStdioBuiltin
513            | Code::LintAmbientFsBuiltin
514            | Code::LintAmbientEnvBuiltin
515            | Code::LintAmbientRandomBuiltin
516            | Code::LintAmbientNetBuiltin => {
517                &[Code::InvalidMainSignature, Code::LintRenamedStdlibSymbol]
518            }
519            Code::SandboxCapabilityDenied => &[Code::CapabilityPayloadInvalid],
520            Code::LintMutableNeverReassigned => &[Code::MutableNeverReassigned],
521            Code::LintUnusedImport => &[Code::ModuleImportUnused],
522            Code::LintDuplicateMatchArm => &[Code::DuplicateMatchArm],
523            _ => &[],
524        }
525    }
526}
527
528impl fmt::Display for Code {
529    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
530        f.write_str(self.as_str())
531    }
532}
533
534/// Error returned when parsing an unknown diagnostic code.
535#[derive(Debug, Clone, Copy, PartialEq, Eq)]
536pub struct ParseCodeError;
537
538impl fmt::Display for ParseCodeError {
539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540        f.write_str("unknown Harn diagnostic code")
541    }
542}
543
544impl std::error::Error for ParseCodeError {}
545
546impl FromStr for Code {
547    type Err = ParseCodeError;
548
549    fn from_str(value: &str) -> Result<Self, Self::Err> {
550        Code::ALL
551            .iter()
552            .copied()
553            .find(|code| code.as_str() == value)
554            .ok_or(ParseCodeError)
555    }
556}
557
558/// Autonomy ceiling of a proposed repair.
559///
560/// Agents and IDEs dispatch on this class to decide whether to auto-apply
561/// a fix, propose it as a suggestion, or escalate to a human. Variants
562/// are ordered from least to most disruptive — call sites can compare
563/// with `<=` to enforce a configured ceiling like
564/// `"apply anything up to behavior-preserving"`.
565///
566/// The wire-format strings (`format-only`, `behavior-preserving`, …) are
567/// the contract surface; renaming a variant string is a breaking change.
568#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
569pub enum RepairSafety {
570    /// Whitespace, trivia, or canonical layout only. No code structure
571    /// changes; safe to auto-apply.
572    FormatOnly,
573    /// Intended not to change observable runtime behavior (e.g. delete an
574    /// unreachable branch, drop a redundant cast).
575    BehaviorPreserving,
576    /// Confined to the current local scope or file. Runtime behavior may
577    /// change, but the blast radius does not cross a declaration boundary
578    /// or a public surface.
579    ScopeLocal,
580    /// Touches a signature, export, or call-site surface that other files
581    /// or external consumers can observe.
582    SurfaceChanging,
583    /// Required capabilities or sandbox profile may change as a result of
584    /// applying the repair (e.g. swapping `provider: "openai"` for a
585    /// capability flag widens the routing surface).
586    CapabilityChanging,
587    /// Planning hint only — agents should propose, never auto-apply.
588    /// Aligned with the `AutonomyTier::Suggest`/`ActWithApproval` rungs
589    /// in `trust_graph.rs`.
590    NeedsHuman,
591}
592
593impl RepairSafety {
594    pub const ALL: &'static [RepairSafety] = &[
595        RepairSafety::FormatOnly,
596        RepairSafety::BehaviorPreserving,
597        RepairSafety::ScopeLocal,
598        RepairSafety::SurfaceChanging,
599        RepairSafety::CapabilityChanging,
600        RepairSafety::NeedsHuman,
601    ];
602
603    /// Stable wire-format string. The contract surface — do not rename
604    /// without coordinating with `harn fix --safety <…>` callers and
605    /// downstream LSP/IDE clients.
606    pub const fn as_str(self) -> &'static str {
607        match self {
608            RepairSafety::FormatOnly => "format-only",
609            RepairSafety::BehaviorPreserving => "behavior-preserving",
610            RepairSafety::ScopeLocal => "scope-local",
611            RepairSafety::SurfaceChanging => "surface-changing",
612            RepairSafety::CapabilityChanging => "capability-changing",
613            RepairSafety::NeedsHuman => "needs-human",
614        }
615    }
616
617    /// True when `self` sits at or below `ceiling`. Used by
618    /// `harn fix --apply --safety <ceiling>` and IDE auto-apply policies
619    /// to decide whether a repair clears the configured autonomy bar.
620    pub const fn is_at_most(self, ceiling: RepairSafety) -> bool {
621        (self as u8) <= (ceiling as u8)
622    }
623}
624
625impl fmt::Display for RepairSafety {
626    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
627        f.write_str(self.as_str())
628    }
629}
630
631/// Error returned when parsing an unknown repair-safety string.
632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633pub struct ParseRepairSafetyError;
634
635impl fmt::Display for ParseRepairSafetyError {
636    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
637        f.write_str("unknown Harn repair-safety class")
638    }
639}
640
641impl std::error::Error for ParseRepairSafetyError {}
642
643impl FromStr for RepairSafety {
644    type Err = ParseRepairSafetyError;
645
646    fn from_str(value: &str) -> Result<Self, Self::Err> {
647        RepairSafety::ALL
648            .iter()
649            .copied()
650            .find(|safety| safety.as_str() == value)
651            .ok_or(ParseRepairSafetyError)
652    }
653}
654
655/// Namespaced kebab-case repair identifier (e.g. `imports/fix-path`).
656///
657/// Wraps a `Cow` so registry-driven values reuse a `'static` literal and
658/// per-site overrides can still attach an owned string. The wire-format
659/// string is the contract surface — never normalize or reformat on read.
660#[derive(Debug, Clone, PartialEq, Eq, Hash)]
661pub struct RepairId(std::borrow::Cow<'static, str>);
662
663impl RepairId {
664    pub const fn from_static(s: &'static str) -> Self {
665        RepairId(std::borrow::Cow::Borrowed(s))
666    }
667
668    pub fn from_owned(s: String) -> Self {
669        RepairId(std::borrow::Cow::Owned(s))
670    }
671
672    pub fn as_str(&self) -> &str {
673        &self.0
674    }
675}
676
677impl fmt::Display for RepairId {
678    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
679        f.write_str(&self.0)
680    }
681}
682
683/// A structured repair proposal attached to a diagnostic.
684///
685/// `id` and `summary` are agent-readable metadata; `safety` is the
686/// dispatch dimension that decides whether the repair clears an
687/// autonomy ceiling. The concrete edits, when known statically, live on
688/// the diagnostic's `fix: Option<Vec<FixEdit>>`; this `Repair` is the
689/// classifier above those edits, not a replacement for them.
690#[derive(Debug, Clone)]
691pub struct Repair {
692    pub id: RepairId,
693    pub summary: String,
694    pub safety: RepairSafety,
695}
696
697impl Repair {
698    pub fn from_template(template: &RepairTemplate) -> Self {
699        Repair {
700            id: RepairId::from_static(template.id),
701            summary: template.summary.to_string(),
702            safety: template.safety,
703        }
704    }
705}
706
707/// Static-lifetime repair template bound to a diagnostic code.
708///
709/// Stored in the registry alongside `Code`. Construction sites can
710/// materialize a `Repair` via [`Repair::from_template`] or override
711/// `summary` for instance-specific detail by building a `Repair`
712/// directly.
713#[derive(Debug, Clone, Copy)]
714pub struct RepairTemplate {
715    pub id: &'static str,
716    pub summary: &'static str,
717    pub safety: RepairSafety,
718}
719
720impl Code {
721    /// Look up the default repair template attached to this diagnostic
722    /// code, or `None` if no actionable fix shape is registered.
723    pub const fn repair_template(self) -> Option<&'static RepairTemplate> {
724        match self {
725            // --- TYP: type mismatches & coercions -------------------------
726            Code::TypeMismatch
727            | Code::ReturnTypeMismatch
728            | Code::AssignmentTypeMismatch
729            | Code::ArgumentTypeMismatch
730            | Code::VariableTypeMismatch
731            | Code::ClosureReturnTypeMismatch
732            | Code::FieldTypeMismatch
733            | Code::MethodTypeMismatch
734            | Code::InvalidIndexType => Some(&REPAIR_INSERT_EXPLICIT_CONVERSION),
735            Code::StringInterpolationRewrite => Some(&REPAIR_REWRITE_STRING_INTERPOLATION),
736            Code::UnknownTypeName => Some(&REPAIR_IMPORTS_FIX_PATH),
737            Code::InvalidCast => Some(&REPAIR_CASTS_REMOVE_UNCHECKED),
738
739            // --- NAM / IMP: imports & names -------------------------------
740            Code::UndefinedVariable
741            | Code::UndefinedFunction
742            | Code::UnknownField
743            | Code::UnknownMethod
744            | Code::UnknownBuiltin
745            | Code::UnknownDeclaration => Some(&REPAIR_BINDINGS_RENAME_TO_CLOSEST),
746            Code::InvalidMainSignature => Some(&REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM),
747            Code::DeprecatedFunction => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
748            Code::ModuleImportUnresolved | Code::ImportResolutionFailed => {
749                Some(&REPAIR_IMPORTS_FIX_PATH)
750            }
751            Code::ModuleImportUnused => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
752            Code::ModuleImportOrder => Some(&REPAIR_IMPORTS_REORDER),
753
754            // --- CAP / RCV: capabilities & error recovery -----------------
755            Code::CapabilityResultUnchecked => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
756            Code::CapabilityBindingInvalid => Some(&REPAIR_MANUAL_REVIEW_CAPABILITY),
757            Code::EffectInheritanceViolation => Some(&REPAIR_POLICY_NARROW_CHILD_EFFECTS),
758            Code::RescueOutsideFunction | Code::TryOutsideFunction => {
759                Some(&REPAIR_ERRORS_WRAP_IN_FN)
760            }
761
762            // --- LLM / PRM: model + prompt contract -----------------------
763            Code::DeprecatedLlmOption => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
764            Code::LlmSchemaMissing => Some(&REPAIR_LLM_ADD_SCHEMA),
765            Code::LlmProviderIdentityBranch | Code::PromptProviderIdentityBranch => {
766                Some(&REPAIR_LLM_USE_CAPABILITY_FLAG)
767            }
768            Code::PromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
769            Code::PromptToolSurfaceUnknown | Code::PromptToolSurfaceDeferredReference => {
770                Some(&REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE)
771            }
772            Code::PromptVariantExplosion => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
773
774            // --- STD: stdlib usage ----------------------------------------
775            Code::DeprecatedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
776            Code::LintMissingStdlibMetadata => Some(&REPAIR_DOC_ADD_STDLIB_METADATA),
777
778            // --- OWN: ownership & mutability ------------------------------
779            Code::ImmutableAssignment => Some(&REPAIR_BINDINGS_MAKE_MUTABLE),
780            Code::MutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
781
782            // --- MAT: match exhaustiveness --------------------------------
783            Code::NonExhaustiveMatch => Some(&REPAIR_MATCH_ADD_MISSING_ARMS),
784            Code::DuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
785
786            // --- ORC: orchestration ---------------------------------------
787            Code::UnreachableCode => Some(&REPAIR_DEAD_CODE_REMOVE),
788
789            // --- FMT: formatter -------------------------------------------
790            Code::FormatterWouldReformat | Code::FormatterTrailingComma => {
791                Some(&REPAIR_FORMAT_REFORMAT)
792            }
793
794            // --- LNT: lints with structured fixes -------------------------
795            Code::LintUnusedVariable
796            | Code::LintUnusedPatternBinding
797            | Code::LintUnusedParameter => Some(&REPAIR_BINDINGS_RENAME_UNUSED),
798            Code::LintUnusedImport => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
799            Code::LintUnusedFunction | Code::LintUnusedType => {
800                Some(&REPAIR_DECLARATIONS_REMOVE_UNUSED)
801            }
802            Code::LintMutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
803            Code::LintImportOrder => Some(&REPAIR_IMPORTS_REORDER),
804            Code::LintBlankLineBetweenItems
805            | Code::LintTrailingComma
806            | Code::LintUnnecessaryParentheses
807            | Code::LintRequireFileHeader => Some(&REPAIR_FORMAT_REFORMAT),
808            Code::LintLegacyDocComment => Some(&REPAIR_DOC_COMMENT_MIGRATE),
809            Code::LintEmptyBlock => Some(&REPAIR_BLOCK_REMOVE_EMPTY),
810            Code::LintUnnecessaryElseReturn | Code::LintLetThenReturn => {
811                Some(&REPAIR_CONTROL_FLOW_FLATTEN)
812            }
813            Code::LintRedundantNilTernary
814            | Code::LintUnnecessarySafeNavigation
815            | Code::LintPreferOptionalShorthand
816            | Code::LintComparisonToBool
817            | Code::LintPointlessComparison
818            | Code::LintConstantLogicalOperand => Some(&REPAIR_EXPRESSION_SIMPLIFY),
819            Code::LintUnnecessaryCast => Some(&REPAIR_CASTS_REMOVE_REDUNDANT),
820            Code::LintRedundantClone => Some(&REPAIR_CLONE_REMOVE_REDUNDANT),
821            Code::LintEagerCollectionConversion => Some(&REPAIR_COLLECTION_PREFER_LAZY),
822            Code::LintDeadCodeAfterReturn => Some(&REPAIR_DEAD_CODE_REMOVE),
823            Code::LintRenamedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
824            Code::LintAmbientClockBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_CLOCK),
825            Code::LintAmbientFsBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_FS),
826            Code::LintAmbientEnvBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_ENV),
827            Code::LintAmbientRandomBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_RANDOM),
828            Code::LintAmbientNetBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_NET),
829            Code::LintAmbientStdioBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS),
830            Code::LintDeprecatedLlmOptions => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
831            Code::LintTemplateProviderIdentityBranch => Some(&REPAIR_LLM_USE_CAPABILITY_FLAG),
832            Code::LintPromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
833            Code::LintShadowVariable => Some(&REPAIR_BINDINGS_RENAME_SHADOW),
834            Code::LintNamingConvention => Some(&REPAIR_STYLE_RENAME_TO_CONVENTION),
835            Code::LintUnhandledApprovalResult => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
836            Code::LintMissingHarndoc => Some(&REPAIR_DOC_ADD_HARNDOC),
837            Code::LintDuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
838            Code::LintUntypedDictAccess => Some(&REPAIR_TYPES_ADD_SHAPE_ANNOTATION),
839            Code::LintMcpToolAnnotations => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
840            Code::LintTemplateVariantExplosion | Code::LintLongRunningWithoutCleanup => {
841                Some(&REPAIR_MANUAL_NEEDS_HUMAN)
842            }
843
844            // Everything else: no statically known repair shape. Agents
845            // should treat these as "diagnose only" until a repair is
846            // registered.
847            _ => None,
848        }
849    }
850}
851
852// Repair-id catalog. Each `RepairTemplate` carries a kebab-case
853// namespaced id (`<namespace>/<verb-noun>`), a one-line summary written
854// in the imperative voice, and a `RepairSafety` class.
855//
856// Conventions:
857//   - Namespaces stay short: `bindings/`, `imports/`, `errors/`, `casts/`,
858//     `format/`, `llm/`, `prompts/`, `match/`, `stdlib/`, `lint/`,
859//     `doc/`, `style/`, `types/`, `manual/`.
860//   - Summary starts with a verb ("Replace…", "Remove…", "Insert…").
861//   - Safety must be the most permissive class that is still always true
862//     for every site this template attaches to. When unsure, pick the
863//     stricter class — agents tighten too-loose policies later, never
864//     too-tight ones.
865
866const REPAIR_INSERT_EXPLICIT_CONVERSION: RepairTemplate = RepairTemplate {
867    id: "casts/insert-explicit-conversion",
868    summary: "Insert an explicit conversion or correct the operand type",
869    safety: RepairSafety::ScopeLocal,
870};
871
872const REPAIR_REWRITE_STRING_INTERPOLATION: RepairTemplate = RepairTemplate {
873    id: "style/string-interpolation",
874    summary: "Rewrite string concatenation as an interpolation literal",
875    safety: RepairSafety::BehaviorPreserving,
876};
877
878const REPAIR_CASTS_REMOVE_UNCHECKED: RepairTemplate = RepairTemplate {
879    id: "casts/remove-unchecked",
880    summary: "Remove the unchecked cast or guard it with a type test",
881    safety: RepairSafety::ScopeLocal,
882};
883
884const REPAIR_CASTS_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
885    id: "casts/remove-redundant",
886    summary: "Remove the redundant cast",
887    safety: RepairSafety::BehaviorPreserving,
888};
889
890const REPAIR_BINDINGS_RENAME_TO_CLOSEST: RepairTemplate = RepairTemplate {
891    id: "bindings/rename-to-closest",
892    summary: "Rename to the closest in-scope identifier",
893    safety: RepairSafety::ScopeLocal,
894};
895
896const REPAIR_BINDINGS_MAKE_MUTABLE: RepairTemplate = RepairTemplate {
897    id: "bindings/make-mutable",
898    summary: "Mark the binding `mut` so it can be reassigned",
899    safety: RepairSafety::ScopeLocal,
900};
901
902const REPAIR_BINDINGS_MAKE_IMMUTABLE: RepairTemplate = RepairTemplate {
903    id: "bindings/make-immutable",
904    summary: "Drop `mut` since the binding is never reassigned",
905    safety: RepairSafety::BehaviorPreserving,
906};
907
908const REPAIR_BINDINGS_RENAME_UNUSED: RepairTemplate = RepairTemplate {
909    id: "bindings/rename-unused",
910    summary: "Prefix the unused binding with `_` to silence the lint",
911    safety: RepairSafety::BehaviorPreserving,
912};
913
914const REPAIR_BINDINGS_RENAME_SHADOW: RepairTemplate = RepairTemplate {
915    id: "bindings/rename-shadow",
916    summary: "Rename the shadowing binding to a distinct name",
917    safety: RepairSafety::ScopeLocal,
918};
919
920const REPAIR_BINDINGS_THREAD_HARNESS: RepairTemplate = RepairTemplate {
921    id: "bindings/thread-harness",
922    summary: "Thread the existing `harness` binding through local helper calls and replace the ambient stdio builtin with `harness.stdio.*`",
923    safety: RepairSafety::ScopeLocal,
924};
925
926const REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM: RepairTemplate = RepairTemplate {
927    id: "bindings/thread-harness-needs-param",
928    summary: "Add a `harness: Harness` parameter where the stdio capability handle is required and update local callers",
929    safety: RepairSafety::SurfaceChanging,
930};
931
932const REPAIR_BINDINGS_THREAD_HARNESS_CLOCK: RepairTemplate = RepairTemplate {
933    id: "bindings/thread-harness-clock",
934    summary: "Replace the ambient clock builtin with the corresponding `harness.clock.*` method",
935    safety: RepairSafety::ScopeLocal,
936};
937
938const REPAIR_BINDINGS_THREAD_HARNESS_FS: RepairTemplate = RepairTemplate {
939    id: "bindings/thread-harness-fs",
940    summary: "Replace the ambient fs builtin with the corresponding `harness.fs.*` method",
941    safety: RepairSafety::ScopeLocal,
942};
943
944const REPAIR_BINDINGS_THREAD_HARNESS_ENV: RepairTemplate = RepairTemplate {
945    id: "bindings/thread-harness-env",
946    summary: "Replace the ambient env builtin with the corresponding `harness.env.*` method",
947    safety: RepairSafety::ScopeLocal,
948};
949
950const REPAIR_BINDINGS_THREAD_HARNESS_RANDOM: RepairTemplate = RepairTemplate {
951    id: "bindings/thread-harness-random",
952    summary: "Replace the ambient random builtin with the corresponding `harness.random.*` method",
953    safety: RepairSafety::ScopeLocal,
954};
955
956const REPAIR_BINDINGS_THREAD_HARNESS_NET: RepairTemplate = RepairTemplate {
957    id: "bindings/thread-harness-net",
958    summary: "Replace the ambient net builtin with the corresponding `harness.net.*` method",
959    safety: RepairSafety::ScopeLocal,
960};
961
962const REPAIR_DECLARATIONS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
963    id: "declarations/remove-unused",
964    summary: "Remove the unused declaration",
965    safety: RepairSafety::SurfaceChanging,
966};
967
968const REPAIR_IMPORTS_FIX_PATH: RepairTemplate = RepairTemplate {
969    id: "imports/fix-path",
970    summary: "Replace the import path with a resolvable target",
971    safety: RepairSafety::ScopeLocal,
972};
973
974const REPAIR_IMPORTS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
975    id: "imports/remove-unused",
976    summary: "Remove the unused import",
977    safety: RepairSafety::BehaviorPreserving,
978};
979
980const REPAIR_IMPORTS_REORDER: RepairTemplate = RepairTemplate {
981    id: "imports/reorder",
982    summary: "Reorder imports into canonical grouping",
983    safety: RepairSafety::FormatOnly,
984};
985
986const REPAIR_ERRORS_CHECK_OR_RESCUE: RepairTemplate = RepairTemplate {
987    id: "errors/check-or-rescue",
988    summary: "Check the result or wrap the call in a `rescue` block",
989    safety: RepairSafety::ScopeLocal,
990};
991
992const REPAIR_ERRORS_WRAP_IN_FN: RepairTemplate = RepairTemplate {
993    id: "errors/wrap-in-fn",
994    summary: "Move the construct inside a function body",
995    safety: RepairSafety::SurfaceChanging,
996};
997
998const REPAIR_MATCH_ADD_MISSING_ARMS: RepairTemplate = RepairTemplate {
999    id: "match/add-missing-arms",
1000    summary: "Add arms covering the missing variants",
1001    safety: RepairSafety::ScopeLocal,
1002};
1003
1004const REPAIR_MATCH_REMOVE_DUPLICATE_ARM: RepairTemplate = RepairTemplate {
1005    id: "match/remove-duplicate-arm",
1006    summary: "Remove the duplicated match arm",
1007    safety: RepairSafety::BehaviorPreserving,
1008};
1009
1010const REPAIR_FORMAT_REFORMAT: RepairTemplate = RepairTemplate {
1011    id: "format/reformat",
1012    summary: "Apply canonical formatting",
1013    safety: RepairSafety::FormatOnly,
1014};
1015
1016const REPAIR_DOC_COMMENT_MIGRATE: RepairTemplate = RepairTemplate {
1017    id: "doc/migrate-comment-style",
1018    summary: "Migrate the legacy comment to canonical doc syntax",
1019    safety: RepairSafety::FormatOnly,
1020};
1021
1022const REPAIR_DOC_ADD_HARNDOC: RepairTemplate = RepairTemplate {
1023    id: "doc/add-harndoc",
1024    summary: "Add a `///` doc comment describing this declaration",
1025    safety: RepairSafety::BehaviorPreserving,
1026};
1027
1028const REPAIR_DOC_ADD_STDLIB_METADATA: RepairTemplate = RepairTemplate {
1029    id: "doc/add-stdlib-metadata",
1030    summary: "Add `@effects`, `@allocation`, `@errors`, `@api_stability`, and `@example` fields to the stdlib function's doc block",
1031    safety: RepairSafety::BehaviorPreserving,
1032};
1033
1034const REPAIR_BLOCK_REMOVE_EMPTY: RepairTemplate = RepairTemplate {
1035    id: "blocks/remove-empty",
1036    summary: "Remove the empty block or fill in an explicit body",
1037    safety: RepairSafety::ScopeLocal,
1038};
1039
1040const REPAIR_CONTROL_FLOW_FLATTEN: RepairTemplate = RepairTemplate {
1041    id: "control-flow/flatten",
1042    summary: "Flatten the unnecessary control flow construct",
1043    safety: RepairSafety::BehaviorPreserving,
1044};
1045
1046const REPAIR_EXPRESSION_SIMPLIFY: RepairTemplate = RepairTemplate {
1047    id: "expressions/simplify",
1048    summary: "Simplify the expression to its canonical form",
1049    safety: RepairSafety::BehaviorPreserving,
1050};
1051
1052const REPAIR_CLONE_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
1053    id: "clones/remove-redundant",
1054    summary: "Remove the redundant clone",
1055    safety: RepairSafety::BehaviorPreserving,
1056};
1057
1058const REPAIR_COLLECTION_PREFER_LAZY: RepairTemplate = RepairTemplate {
1059    id: "collections/prefer-lazy",
1060    summary: "Replace the eager collection step with a lazy variant",
1061    safety: RepairSafety::ScopeLocal,
1062};
1063
1064const REPAIR_DEAD_CODE_REMOVE: RepairTemplate = RepairTemplate {
1065    id: "control-flow/remove-dead",
1066    summary: "Remove the unreachable code",
1067    safety: RepairSafety::BehaviorPreserving,
1068};
1069
1070const REPAIR_STDLIB_MIGRATE_RENAMED: RepairTemplate = RepairTemplate {
1071    id: "stdlib/migrate-renamed",
1072    summary: "Rename the call to the renamed stdlib symbol",
1073    safety: RepairSafety::ScopeLocal,
1074};
1075
1076const REPAIR_LLM_MIGRATE_DEPRECATED_OPTION: RepairTemplate = RepairTemplate {
1077    id: "llm/migrate-deprecated-option",
1078    summary: "Replace the deprecated option with its supported equivalent",
1079    safety: RepairSafety::ScopeLocal,
1080};
1081
1082const REPAIR_LLM_ADD_SCHEMA: RepairTemplate = RepairTemplate {
1083    id: "llm/add-schema",
1084    summary: "Add a typed output schema to the LLM call",
1085    safety: RepairSafety::SurfaceChanging,
1086};
1087
1088const REPAIR_LLM_USE_CAPABILITY_FLAG: RepairTemplate = RepairTemplate {
1089    id: "llm/use-capability-flag",
1090    summary: "Branch on a capability flag instead of provider identity",
1091    safety: RepairSafety::CapabilityChanging,
1092};
1093
1094const REPAIR_PROMPTS_ESCAPE_INJECTION: RepairTemplate = RepairTemplate {
1095    id: "prompts/escape-injection",
1096    summary: "Pass the untrusted input through a structured placeholder",
1097    safety: RepairSafety::ScopeLocal,
1098};
1099
1100const REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE: RepairTemplate = RepairTemplate {
1101    id: "prompts/add-tool-to-surface",
1102    summary: "Add the referenced tool to the declared tool surface",
1103    safety: RepairSafety::SurfaceChanging,
1104};
1105
1106const REPAIR_STYLE_RENAME_TO_CONVENTION: RepairTemplate = RepairTemplate {
1107    id: "style/rename-to-convention",
1108    summary: "Rename to match the casing convention for this kind",
1109    safety: RepairSafety::SurfaceChanging,
1110};
1111
1112const REPAIR_TYPES_ADD_SHAPE_ANNOTATION: RepairTemplate = RepairTemplate {
1113    id: "types/add-shape-annotation",
1114    summary: "Annotate the dict with a concrete shape type",
1115    safety: RepairSafety::SurfaceChanging,
1116};
1117
1118const REPAIR_MANUAL_REVIEW_CAPABILITY: RepairTemplate = RepairTemplate {
1119    id: "manual/review-capability-binding",
1120    summary: "Review the capability binding; the fix is not mechanical",
1121    safety: RepairSafety::NeedsHuman,
1122};
1123
1124const REPAIR_POLICY_NARROW_CHILD_EFFECTS: RepairTemplate = RepairTemplate {
1125    id: "policy/narrow-child-effects",
1126    summary: "Narrow the child agent's effects to a subset of the parent's, or widen the parent's declared effects",
1127    safety: RepairSafety::SurfaceChanging,
1128};
1129
1130const REPAIR_MANUAL_NEEDS_HUMAN: RepairTemplate = RepairTemplate {
1131    id: "manual/needs-human",
1132    summary: "Plan a human-led change; auto-apply is not safe here",
1133    safety: RepairSafety::NeedsHuman,
1134};
1135
1136/// Every distinct repair template registered by [`Code::repair_template`],
1137/// in source order. Used by the catalog wire-up in E1.7 and by tests
1138/// asserting the catalog is healthy.
1139pub const REPAIR_REGISTRY: &[&RepairTemplate] = &[
1140    &REPAIR_INSERT_EXPLICIT_CONVERSION,
1141    &REPAIR_REWRITE_STRING_INTERPOLATION,
1142    &REPAIR_CASTS_REMOVE_UNCHECKED,
1143    &REPAIR_CASTS_REMOVE_REDUNDANT,
1144    &REPAIR_BINDINGS_RENAME_TO_CLOSEST,
1145    &REPAIR_BINDINGS_MAKE_MUTABLE,
1146    &REPAIR_BINDINGS_MAKE_IMMUTABLE,
1147    &REPAIR_BINDINGS_RENAME_UNUSED,
1148    &REPAIR_BINDINGS_RENAME_SHADOW,
1149    &REPAIR_BINDINGS_THREAD_HARNESS,
1150    &REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM,
1151    &REPAIR_BINDINGS_THREAD_HARNESS_CLOCK,
1152    &REPAIR_BINDINGS_THREAD_HARNESS_FS,
1153    &REPAIR_BINDINGS_THREAD_HARNESS_ENV,
1154    &REPAIR_BINDINGS_THREAD_HARNESS_RANDOM,
1155    &REPAIR_BINDINGS_THREAD_HARNESS_NET,
1156    &REPAIR_DECLARATIONS_REMOVE_UNUSED,
1157    &REPAIR_IMPORTS_FIX_PATH,
1158    &REPAIR_IMPORTS_REMOVE_UNUSED,
1159    &REPAIR_IMPORTS_REORDER,
1160    &REPAIR_ERRORS_CHECK_OR_RESCUE,
1161    &REPAIR_ERRORS_WRAP_IN_FN,
1162    &REPAIR_MATCH_ADD_MISSING_ARMS,
1163    &REPAIR_MATCH_REMOVE_DUPLICATE_ARM,
1164    &REPAIR_FORMAT_REFORMAT,
1165    &REPAIR_DOC_COMMENT_MIGRATE,
1166    &REPAIR_DOC_ADD_HARNDOC,
1167    &REPAIR_DOC_ADD_STDLIB_METADATA,
1168    &REPAIR_BLOCK_REMOVE_EMPTY,
1169    &REPAIR_CONTROL_FLOW_FLATTEN,
1170    &REPAIR_EXPRESSION_SIMPLIFY,
1171    &REPAIR_CLONE_REMOVE_REDUNDANT,
1172    &REPAIR_COLLECTION_PREFER_LAZY,
1173    &REPAIR_DEAD_CODE_REMOVE,
1174    &REPAIR_STDLIB_MIGRATE_RENAMED,
1175    &REPAIR_LLM_MIGRATE_DEPRECATED_OPTION,
1176    &REPAIR_LLM_ADD_SCHEMA,
1177    &REPAIR_LLM_USE_CAPABILITY_FLAG,
1178    &REPAIR_PROMPTS_ESCAPE_INJECTION,
1179    &REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE,
1180    &REPAIR_STYLE_RENAME_TO_CONVENTION,
1181    &REPAIR_TYPES_ADD_SHAPE_ANNOTATION,
1182    &REPAIR_MANUAL_REVIEW_CAPABILITY,
1183    &REPAIR_MANUAL_NEEDS_HUMAN,
1184    &REPAIR_POLICY_NARROW_CHILD_EFFECTS,
1185];
1186
1187#[cfg(test)]
1188mod tests {
1189    use super::{Category, Code, ParseRepairSafetyError, RepairSafety, REPAIR_REGISTRY};
1190    use std::collections::HashSet;
1191    use std::str::FromStr;
1192
1193    #[test]
1194    fn parses_registered_code() {
1195        assert_eq!(Code::from_str("HARN-TYP-014"), Ok(Code::TypeParameterArity));
1196    }
1197
1198    #[test]
1199    fn registry_has_unique_identifiers() {
1200        let mut seen = HashSet::new();
1201        for entry in Code::registry() {
1202            assert!(
1203                seen.insert(entry.identifier),
1204                "duplicate diagnostic code {}",
1205                entry.identifier
1206            );
1207            assert_eq!(entry.code.as_str(), entry.identifier);
1208            assert_eq!(entry.code.category(), entry.category);
1209            let expected_prefix = format!("HARN-{}-", entry.category);
1210            assert!(entry.identifier.starts_with(&expected_prefix));
1211            let suffix = entry.identifier.trim_start_matches(&expected_prefix);
1212            assert_eq!(suffix.len(), 3);
1213            assert!(suffix.chars().all(|ch| ch.is_ascii_digit()));
1214            assert!(!entry.summary.is_empty());
1215        }
1216        assert!(Code::registry().len() >= 40);
1217    }
1218
1219    #[test]
1220    fn every_category_is_populated() {
1221        for category in Category::ALL {
1222            assert!(
1223                Code::registry()
1224                    .iter()
1225                    .any(|entry| entry.category == *category),
1226                "missing diagnostic code category {category}"
1227            );
1228        }
1229    }
1230
1231    #[test]
1232    fn every_code_has_non_empty_explanation() {
1233        for entry in Code::registry() {
1234            let body = entry.code.explanation();
1235            assert!(
1236                !body.trim().is_empty(),
1237                "diagnostic code {} has an empty explanation file",
1238                entry.identifier
1239            );
1240            assert!(
1241                body.contains(entry.identifier),
1242                "explanation for {} should reference its identifier",
1243                entry.identifier
1244            );
1245        }
1246    }
1247
1248    #[test]
1249    fn related_codes_are_registered_and_non_self() {
1250        for entry in Code::registry() {
1251            for &other in entry.code.related() {
1252                assert_ne!(
1253                    other, entry.code,
1254                    "{} lists itself as a related code",
1255                    entry.identifier
1256                );
1257                assert!(
1258                    Code::registry().iter().any(|e| e.code == other),
1259                    "{} lists unregistered related code {}",
1260                    entry.identifier,
1261                    other
1262                );
1263            }
1264        }
1265    }
1266
1267    #[test]
1268    fn repair_safety_string_roundtrip() {
1269        for safety in RepairSafety::ALL {
1270            let parsed = RepairSafety::from_str(safety.as_str()).unwrap();
1271            assert_eq!(parsed, *safety);
1272            assert_eq!(parsed.to_string(), safety.as_str());
1273        }
1274        assert_eq!(
1275            RepairSafety::from_str("not-a-safety-class"),
1276            Err(ParseRepairSafetyError)
1277        );
1278    }
1279
1280    #[test]
1281    fn repair_safety_ordering_is_monotonic_low_to_high() {
1282        // The is_at_most ceiling check relies on this ordering being
1283        // least-to-most disruptive; a regression here flips the meaning
1284        // of `harn fix --safety <ceiling>` for every caller.
1285        let order = RepairSafety::ALL;
1286        for window in order.windows(2) {
1287            assert!(
1288                window[0] < window[1],
1289                "{:?} should be safer than {:?}",
1290                window[0],
1291                window[1]
1292            );
1293            assert!(window[0].is_at_most(window[1]));
1294            assert!(!window[1].is_at_most(window[0]));
1295        }
1296    }
1297
1298    #[test]
1299    fn repair_registry_has_at_least_twenty_entries() {
1300        assert!(
1301            REPAIR_REGISTRY.len() >= 20,
1302            "expected ≥20 repair templates, found {}",
1303            REPAIR_REGISTRY.len()
1304        );
1305    }
1306
1307    #[test]
1308    fn repair_ids_are_kebab_case_namespaced_and_unique() {
1309        let mut seen = HashSet::new();
1310        for template in REPAIR_REGISTRY {
1311            assert!(
1312                seen.insert(template.id),
1313                "duplicate repair id {}",
1314                template.id
1315            );
1316            let (namespace, leaf) = template.id.split_once('/').unwrap_or_else(|| {
1317                panic!(
1318                    "repair id `{}` is missing `<namespace>/` prefix",
1319                    template.id
1320                )
1321            });
1322            assert!(
1323                !namespace.is_empty() && !leaf.is_empty(),
1324                "repair id `{}` has empty namespace or leaf",
1325                template.id
1326            );
1327            for ch in template.id.chars() {
1328                assert!(
1329                    ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '/',
1330                    "repair id `{}` has non-kebab character {ch:?}",
1331                    template.id
1332                );
1333            }
1334            assert!(
1335                !template.summary.is_empty(),
1336                "repair {} has empty summary",
1337                template.id
1338            );
1339            // Summaries are imperative: start with a capital ASCII letter.
1340            let first = template.summary.chars().next().unwrap();
1341            assert!(
1342                first.is_ascii_uppercase(),
1343                "repair {} summary `{}` should start with a capital",
1344                template.id,
1345                template.summary
1346            );
1347        }
1348    }
1349
1350    #[test]
1351    fn manual_namespace_is_needs_human() {
1352        for template in REPAIR_REGISTRY {
1353            if let Some(("manual", _)) = template.id.split_once('/') {
1354                assert_eq!(
1355                    template.safety,
1356                    RepairSafety::NeedsHuman,
1357                    "manual/* repair {} must be NeedsHuman",
1358                    template.id
1359                );
1360            }
1361        }
1362    }
1363
1364    #[test]
1365    fn known_codes_carry_expected_safety_class() {
1366        // Spot-check: the autonomy contract for several representative
1367        // diagnostics. Lock in the safety class so cross-repo agents that
1368        // dispatch on these don't silently drift when the catalog moves.
1369        let expected: &[(Code, RepairSafety, &str)] = &[
1370            (
1371                Code::FormatterWouldReformat,
1372                RepairSafety::FormatOnly,
1373                "format/reformat",
1374            ),
1375            (
1376                Code::ModuleImportUnused,
1377                RepairSafety::BehaviorPreserving,
1378                "imports/remove-unused",
1379            ),
1380            (
1381                Code::ImmutableAssignment,
1382                RepairSafety::ScopeLocal,
1383                "bindings/make-mutable",
1384            ),
1385            (
1386                Code::LintUnusedFunction,
1387                RepairSafety::SurfaceChanging,
1388                "declarations/remove-unused",
1389            ),
1390            (
1391                Code::LlmProviderIdentityBranch,
1392                RepairSafety::CapabilityChanging,
1393                "llm/use-capability-flag",
1394            ),
1395            (
1396                Code::PromptVariantExplosion,
1397                RepairSafety::NeedsHuman,
1398                "manual/needs-human",
1399            ),
1400            (
1401                Code::NonExhaustiveMatch,
1402                RepairSafety::ScopeLocal,
1403                "match/add-missing-arms",
1404            ),
1405            (
1406                Code::LintAmbientClockBuiltin,
1407                RepairSafety::ScopeLocal,
1408                "bindings/thread-harness-clock",
1409            ),
1410            (
1411                Code::LintAmbientStdioBuiltin,
1412                RepairSafety::ScopeLocal,
1413                "bindings/thread-harness",
1414            ),
1415            (
1416                Code::InvalidMainSignature,
1417                RepairSafety::SurfaceChanging,
1418                "bindings/thread-harness-needs-param",
1419            ),
1420        ];
1421        for (code, safety, repair_id) in expected {
1422            let template = code
1423                .repair_template()
1424                .unwrap_or_else(|| panic!("{code} should have a repair template"));
1425            assert_eq!(template.safety, *safety, "{code} safety class drifted");
1426            assert_eq!(template.id, *repair_id, "{code} repair id drifted");
1427        }
1428    }
1429
1430    #[test]
1431    fn repair_templates_cover_at_least_twenty_codes() {
1432        let covered = Code::ALL
1433            .iter()
1434            .filter(|code| code.repair_template().is_some())
1435            .count();
1436        assert!(
1437            covered >= 20,
1438            "expected ≥20 codes with a repair template, found {covered}"
1439        );
1440    }
1441
1442    #[test]
1443    fn every_registered_repair_is_referenced_by_some_code() {
1444        let referenced: HashSet<&'static str> = Code::ALL
1445            .iter()
1446            .filter_map(|code| code.repair_template())
1447            .map(|template| template.id)
1448            .collect();
1449        for template in REPAIR_REGISTRY {
1450            assert!(
1451                referenced.contains(template.id),
1452                "repair {} is in REPAIR_REGISTRY but no Code maps to it",
1453                template.id
1454            );
1455        }
1456    }
1457
1458    #[test]
1459    fn every_referenced_repair_template_is_in_registry() {
1460        let registered: HashSet<&'static str> =
1461            REPAIR_REGISTRY.iter().map(|template| template.id).collect();
1462        for code in Code::ALL {
1463            let Some(template) = code.repair_template() else {
1464                continue;
1465            };
1466            assert!(
1467                registered.contains(template.id),
1468                "repair {} (used by {}) is missing from REPAIR_REGISTRY",
1469                template.id,
1470                code
1471            );
1472        }
1473    }
1474}