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