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