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