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