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