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