1use std::fmt;
22use std::str::FromStr;
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
26pub enum Category {
27 Typ,
28 Par,
29 Nam,
30 Cap,
31 Llm,
32 Orc,
33 Std,
34 Prm,
35 Mod,
36 Rmd,
37 Sus,
38 Lnt,
39 Fmt,
40 Imp,
41 Own,
42 Rcv,
43 Mat,
44 Pol,
45 Met,
49 Cst,
53}
54
55impl Category {
56 pub const ALL: &'static [Category] = &[
57 Category::Typ,
58 Category::Par,
59 Category::Nam,
60 Category::Cap,
61 Category::Llm,
62 Category::Orc,
63 Category::Std,
64 Category::Prm,
65 Category::Mod,
66 Category::Rmd,
67 Category::Sus,
68 Category::Lnt,
69 Category::Fmt,
70 Category::Imp,
71 Category::Own,
72 Category::Rcv,
73 Category::Mat,
74 Category::Pol,
75 Category::Met,
76 Category::Cst,
77 ];
78
79 pub const fn as_str(self) -> &'static str {
80 match self {
81 Category::Typ => "TYP",
82 Category::Par => "PAR",
83 Category::Nam => "NAM",
84 Category::Cap => "CAP",
85 Category::Llm => "LLM",
86 Category::Orc => "ORC",
87 Category::Std => "STD",
88 Category::Prm => "PRM",
89 Category::Mod => "MOD",
90 Category::Rmd => "RMD",
91 Category::Sus => "SUS",
92 Category::Lnt => "LNT",
93 Category::Fmt => "FMT",
94 Category::Imp => "IMP",
95 Category::Own => "OWN",
96 Category::Rcv => "RCV",
97 Category::Mat => "MAT",
98 Category::Pol => "POL",
99 Category::Met => "MET",
100 Category::Cst => "CST",
101 }
102 }
103}
104
105impl fmt::Display for Category {
106 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107 f.write_str(self.as_str())
108 }
109}
110
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113pub struct RegistryEntry {
114 pub code: Code,
115 pub identifier: &'static str,
116 pub category: Category,
117 pub summary: &'static str,
118}
119
120macro_rules! diagnostic_codes {
121 ($($variant:ident, $identifier:literal, $category:ident, $summary:literal;)*) => {
122 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
124 pub enum Code {
125 $($variant,)*
126 }
127
128 impl Code {
129 pub const ALL: &'static [Code] = &[
130 $(Code::$variant,)*
131 ];
132
133 pub const fn as_str(self) -> &'static str {
134 match self {
135 $(Code::$variant => $identifier,)*
136 }
137 }
138
139 pub const fn category(self) -> Category {
140 match self {
141 $(Code::$variant => Category::$category,)*
142 }
143 }
144
145 pub const fn summary(self) -> &'static str {
146 match self {
147 $(Code::$variant => $summary,)*
148 }
149 }
150
151 pub const fn explanation(self) -> &'static str {
155 match self {
156 $(Code::$variant => include_str!(
157 concat!("diagnostic_codes/explanations/", $identifier, ".md")
158 ),)*
159 }
160 }
161 }
162
163 pub const REGISTRY: &[RegistryEntry] = &[
164 $(RegistryEntry {
165 code: Code::$variant,
166 identifier: $identifier,
167 category: Category::$category,
168 summary: $summary,
169 },)*
170 ];
171 };
172}
173
174diagnostic_codes! {
175 TypeMismatch, "HARN-TYP-001", Typ, "expected and actual types are incompatible";
176 InvalidBinaryOperator, "HARN-TYP-002", Typ, "binary operator is not defined for the operand types";
177 StringInterpolationRewrite, "HARN-TYP-003", Typ, "string concatenation should be rewritten as interpolation";
178 ReturnTypeMismatch, "HARN-TYP-004", Typ, "returned expression does not match the declared return type";
179 AssignmentTypeMismatch, "HARN-TYP-005", Typ, "assigned value does not match the target type";
180 ArgumentTypeMismatch, "HARN-TYP-006", Typ, "argument value does not match the parameter type";
181 VariableTypeMismatch, "HARN-TYP-007", Typ, "initializer does not match the declared variable type";
182 ClosureReturnTypeMismatch, "HARN-TYP-008", Typ, "closure return expression does not match its declared type";
183 FieldTypeMismatch, "HARN-TYP-009", Typ, "field value does not match its declared type";
184 MethodTypeMismatch, "HARN-TYP-010", Typ, "method receiver or result type is incompatible";
185 GenericTypeArgumentUnsupported, "HARN-TYP-011", Typ, "callable does not accept type arguments";
186 GenericTypeArgumentMismatch, "HARN-TYP-012", Typ, "type argument does not satisfy the generic parameter";
187 GenericTypeArgumentArity, "HARN-TYP-013", Typ, "generic call has the wrong number of type arguments";
188 TypeParameterArity, "HARN-TYP-014", Typ, "declaration has the wrong number of type parameters";
189 WhereConstraintMismatch, "HARN-TYP-015", Typ, "type argument does not satisfy a where-clause constraint";
190 IterableExpected, "HARN-TYP-016", Typ, "expression must be iterable";
191 InvalidIndexType, "HARN-TYP-017", Typ, "subscript index type is invalid";
192 CallableExpected, "HARN-TYP-018", Typ, "expression must be callable";
193 InvalidCast, "HARN-TYP-019", Typ, "cast cannot be proven valid";
194 UnknownTypeName, "HARN-TYP-020", Typ, "type name cannot be resolved";
195 InvalidVariantUse, "HARN-TYP-021", Typ, "variant type is used in an invalid position";
196 InvalidStructLiteral, "HARN-TYP-022", Typ, "struct literal is invalid";
197 InvalidEnumConstruct, "HARN-TYP-023", Typ, "enum construction is invalid";
198 InvalidPatternBinding, "HARN-TYP-024", Typ, "pattern binding is invalid for the expected type";
199 InvalidOptionalAccess, "HARN-TYP-025", Typ, "optional access is invalid for the receiver type";
200 ParserUnexpectedToken, "HARN-PAR-001", Par, "parser found an unexpected token";
201 ParserUnexpectedEof, "HARN-PAR-002", Par, "parser reached end of file while expecting syntax";
202 ParserUnexpectedCharacter, "HARN-PAR-003", Par, "lexer found an unexpected character";
203 ParserUnterminatedString, "HARN-PAR-004", Par, "string literal is unterminated";
204 ParserUnterminatedBlockComment, "HARN-PAR-005", Par, "block comment is unterminated";
205 UndefinedVariable, "HARN-NAM-001", Nam, "variable name cannot be resolved";
206 UndefinedFunction, "HARN-NAM-002", Nam, "function name cannot be resolved";
207 UnknownAttribute, "HARN-NAM-003", Nam, "attribute name is not recognized";
208 UnknownField, "HARN-NAM-004", Nam, "field name does not exist on the target type";
209 UnknownMethod, "HARN-NAM-005", Nam, "method name does not exist on the receiver type";
210 DuplicateArgument, "HARN-NAM-006", Nam, "argument name is duplicated";
211 UnknownOption, "HARN-NAM-007", Nam, "option key is not recognized";
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, "`main` entrypoint must take a single `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 UnknownLlmOption, "HARN-LLM-001", Llm, "LLM option key is not recognized";
227 DeprecatedLlmOption, "HARN-LLM-002", Llm, "LLM option key is deprecated";
228 LlmSchemaMissing, "HARN-LLM-003", Llm, "LLM call is missing schema validation";
229 LlmSchemaInvalid, "HARN-LLM-004", Llm, "LLM schema option is invalid";
230 LlmProviderIdentityBranch, "HARN-LLM-005", Llm, "prompt branches on provider identity instead of capability flags";
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 DeprecatedStdlibSymbol, "HARN-STD-001", Std, "stdlib symbol has been renamed or deprecated";
242 StdlibUsageInvalid, "HARN-STD-002", Std, "stdlib call is invalid";
243 BuiltinArity, "HARN-STD-003", Std, "builtin call has invalid arity";
244 LintMissingStdlibMetadata, "HARN-STD-101", Std, "public stdlib function is missing declared metadata";
245 PromptTemplateParse, "HARN-PRM-001", Prm, "prompt template cannot be parsed";
246 PromptVariantExplosion, "HARN-PRM-002", Prm, "prompt template has too many capability-aware branches";
247 PromptInjectionRisk, "HARN-PRM-003", Prm, "prompt construction risks direct injection";
248 PromptProviderIdentityBranch, "HARN-PRM-004", Prm, "prompt template branches on provider identity";
249 PromptToolSurfaceUnknown, "HARN-PRM-005", Prm, "prompt references a tool outside the declared surface";
250 PromptToolSurfaceDeferredReference, "HARN-PRM-006", Prm, "prompt references a deferred tool without tool search";
251 PromptTargetMissing, "HARN-PRM-007", Prm, "prompt or template target cannot be found";
252 ModuleImportUnresolved, "HARN-MOD-001", Mod, "module import cannot be resolved";
253 ModuleImportUnused, "HARN-MOD-002", Mod, "module import is unused";
254 ModuleImportOrder, "HARN-MOD-003", Mod, "module imports are not in canonical order";
255 ModuleExportInvalid, "HARN-MOD-004", Mod, "module export is invalid";
256 ModuleImportCollision, "HARN-MOD-005", Mod, "module imports expose colliding names";
257 ModuleReExportConflict, "HARN-MOD-006", Mod, "module re-exports conflict";
258 ReminderUnknownOption, "HARN-RMD-001", Rmd, "reminder lifecycle option key is not recognized";
259 ReminderInvalidShape, "HARN-RMD-002", Rmd, "reminder payload shape is invalid";
260 ReminderUnsupportedUserBlockRoleHint, "HARN-RMD-003", Rmd, "user_block reminder role hint is not supported by the selected provider";
261 ReminderInfiniteDiscardable, "HARN-RMD-004", Rmd, "discardable reminder has no TTL";
262 ReminderUnknownPropagate, "HARN-RMD-005", Rmd, "reminder propagate value is not recognized";
263 ReminderProviderMalformedSpec, "HARN-RMD-006", Rmd, "reminder provider returned a malformed reminder spec";
264 ReminderProviderBloat, "HARN-RMD-007", Rmd, "too many reminder providers are enabled";
265 ReminderUnsupportedHookEvent, "HARN-RMD-008", Rmd, "hook event does not support reminder effects";
266 SuspendWorkerNotRunning, "HARN-SUS-001", Sus, "suspend_agent target worker is not running";
267 ResumeConditionsInvalid, "HARN-SUS-002", Sus, "ResumeConditions validation failed";
268 ResumeWorkerNotSuspended, "HARN-SUS-003", Sus, "resume_agent target worker is not suspended";
269 ResumeSnapshotInvalid, "HARN-SUS-004", Sus, "resume snapshot cannot be loaded or used";
270 AwaitResumptionOutsideAgentLoop, "HARN-SUS-005", Sus, "agent_await_resumption was invoked outside agent_loop structural handling";
271 ConcurrentResumeConflict, "HARN-SUS-006", Sus, "concurrent resume changed the worker before resume could complete";
272 ResumeTriggerRegistrationFailed, "HARN-SUS-007", Sus, "ResumeConditions trigger could not be registered";
273 ResumeTimeoutUnsupported, "HARN-SUS-008", Sus, "resume timeout action is unsupported";
274 ResumeInputInvalid, "HARN-SUS-009", Sus, "resume input failed agent_loop input validation";
275 ResumeWorkerClosed, "HARN-SUS-010", Sus, "closed suspended worker cannot be resumed";
276 ReplayResumeInputHashMismatch, "HARN-SUS-011", Sus, "replay resume input hash diverges from journaled suspension";
277 ReplayDrainDecisionPromptHashMismatch, "HARN-SUS-012", Sus, "replay drain decision prompt hash diverges from journaled receipt";
278 LifecycleSignatureMismatch, "HARN-SUS-013", Sus, "lifecycle receipt signed timestamp failed verification";
279 LintRenamedStdlibSymbol, "HARN-LNT-001", Lnt, "renamed stdlib symbol lint";
280 LintCyclomaticComplexity, "HARN-LNT-002", Lnt, "cyclomatic complexity lint";
281 LintNamingConvention, "HARN-LNT-003", Lnt, "naming convention lint";
282 LintEagerCollectionConversion, "HARN-LNT-004", Lnt, "eager collection conversion lint";
283 LintRedundantClone, "HARN-LNT-005", Lnt, "redundant clone lint";
284 LintLongRunningWithoutCleanup, "HARN-LNT-006", Lnt, "long-running workflow cleanup lint";
285 LintMcpToolAnnotations, "HARN-LNT-007", Lnt, "MCP tool annotations lint";
286 LintPrOpenWithoutSecretScan, "HARN-LNT-008", Lnt, "PR open without secret scan lint";
287 LintShadowVariable, "HARN-LNT-009", Lnt, "shadow variable lint";
288 LintPersonaHookTarget, "HARN-LNT-010", Lnt, "persona hook target lint";
289 LintDeadCodeAfterReturn, "HARN-LNT-011", Lnt, "dead code after return lint";
290 LintLetThenReturn, "HARN-LNT-012", Lnt, "let then return lint";
291 LintUnhandledApprovalResult, "HARN-LNT-013", Lnt, "unhandled approval result lint";
292 LintUnusedVariable, "HARN-LNT-014", Lnt, "unused variable lint";
293 LintUnusedPatternBinding, "HARN-LNT-015", Lnt, "unused pattern binding lint";
294 LintUnusedParameter, "HARN-LNT-016", Lnt, "unused parameter lint";
295 LintUnusedImport, "HARN-LNT-017", Lnt, "unused import lint";
296 LintMutableNeverReassigned, "HARN-LNT-018", Lnt, "mutable never reassigned lint";
297 LintUnusedFunction, "HARN-LNT-019", Lnt, "unused function lint";
298 LintUnusedType, "HARN-LNT-020", Lnt, "unused type lint";
299 LintPersonaBodyMustCallSteps, "HARN-LNT-021", Lnt, "persona body must call steps lint";
300 LintUndefinedFunction, "HARN-LNT-022", Lnt, "undefined function lint";
301 LintPipelineReturnType, "HARN-LNT-023", Lnt, "pipeline return type lint";
302 LintMissingHarndoc, "HARN-LNT-024", Lnt, "missing harndoc lint";
303 LintAssertOutsideTest, "HARN-LNT-025", Lnt, "assert outside test lint";
304 LintPromptInjectionRisk, "HARN-LNT-026", Lnt, "prompt injection risk lint";
305 LintConnectorEffectPolicy, "HARN-LNT-027", Lnt, "connector effect policy lint";
306 LintUnnecessaryCast, "HARN-LNT-028", Lnt, "unnecessary cast lint";
307 LintUntypedDictAccess, "HARN-LNT-029", Lnt, "untyped dict access lint";
308 LintConstantLogicalOperand, "HARN-LNT-030", Lnt, "constant logical operand lint";
309 LintPointlessComparison, "HARN-LNT-031", Lnt, "pointless comparison lint";
310 LintComparisonToBool, "HARN-LNT-032", Lnt, "comparison to bool lint";
311 LintInvalidBinaryOpLiteral, "HARN-LNT-033", Lnt, "invalid binary operator literal lint";
312 LintRedundantNilTernary, "HARN-LNT-034", Lnt, "redundant nil ternary lint";
313 LintEmptyBlock, "HARN-LNT-035", Lnt, "empty block lint";
314 LintUnnecessaryElseReturn, "HARN-LNT-036", Lnt, "unnecessary else return lint";
315 LintDuplicateMatchArm, "HARN-LNT-037", Lnt, "duplicate match arm lint";
316 LintRequireInTest, "HARN-LNT-038", Lnt, "require in test lint";
317 LintBreakOutsideLoop, "HARN-LNT-039", Lnt, "break outside loop lint";
318 LintTemplateParse, "HARN-LNT-040", Lnt, "template parse lint";
319 LintBlankLineBetweenItems, "HARN-LNT-041", Lnt, "blank line between items lint";
320 LintTrailingComma, "HARN-LNT-042", Lnt, "trailing comma lint";
321 LintUnnecessaryParentheses, "HARN-LNT-043", Lnt, "unnecessary parentheses lint";
322 LintTemplateVariantExplosion, "HARN-LNT-044", Lnt, "template variant explosion lint";
323 LintRequireFileHeader, "HARN-LNT-045", Lnt, "require file header lint";
324 LintTemplateProviderIdentityBranch, "HARN-LNT-046", Lnt, "template provider identity branch lint";
325 LintImportOrder, "HARN-LNT-047", Lnt, "import order lint";
326 LintPreferOptionalShorthand, "HARN-LNT-048", Lnt, "prefer optional shorthand lint";
327 LintLegacyDocComment, "HARN-LNT-049", Lnt, "legacy doc comment lint";
328 LintDeprecatedLlmOptions, "HARN-LNT-050", Lnt, "deprecated LLM options lint";
329 LintUnnecessarySafeNavigation, "HARN-LNT-051", Lnt, "unnecessary safe navigation lint";
330 LintAmbientClockBuiltin, "HARN-LNT-052", Lnt, "ambient clock builtin replaced by `harness.clock.*`";
331 LintAmbientStdioBuiltin, "HARN-LNT-053", Lnt, "ambient stdio builtin replaced by `harness.stdio.*`";
332 FormatterParseFailed, "HARN-FMT-001", Fmt, "formatter could not parse the source";
333 FormatterWouldReformat, "HARN-FMT-002", Fmt, "source is not in canonical format";
334 FormatterTrailingComma, "HARN-FMT-003", Fmt, "formatter normalized trailing comma layout";
335 ImportResolutionFailed, "HARN-IMP-001", Imp, "import target cannot be resolved";
336 ImportSymbolMissing, "HARN-IMP-002", Imp, "imported symbol does not exist";
337 ImportCycle, "HARN-IMP-003", Imp, "import graph contains a cycle";
338 ImmutableAssignment, "HARN-OWN-001", Own, "immutable binding is reassigned";
339 MutableNeverReassigned, "HARN-OWN-002", Own, "mutable binding is never reassigned";
340 OwnershipEscape, "HARN-OWN-003", Own, "owned value escapes its valid scope";
341 BoundaryValueUnvalidated, "HARN-OWN-004", Own, "unvalidated boundary value is used directly";
342 RescueOutsideFunction, "HARN-RCV-001", Rcv, "rescue construct is outside a function body";
343 TryOutsideFunction, "HARN-RCV-002", Rcv, "try construct is outside a function body";
344 InvalidRescueConstruct, "HARN-RCV-003", Rcv, "rescue construct is invalid";
345 NonExhaustiveMatch, "HARN-MAT-001", Mat, "match expression is not exhaustive";
346 DuplicateMatchArm, "HARN-MAT-002", Mat, "match expression contains a duplicate arm";
347 InvalidMatchPattern, "HARN-MAT-003", Mat, "match pattern is invalid";
348 PoolBackpressureFull, "HARN-POL-001", Pol, "pool backpressure rejected a submit";
349 PoolFailFastFull, "HARN-POL-002", Pol, "fail-fast pool has no immediate capacity";
350 ConstEvalDisallowedExpression, "HARN-MET-001", Met, "expression is not permitted in a const initializer";
351 ConstEvalStepLimit, "HARN-CST-001", Cst, "const initializer exceeded the step budget";
352 ConstEvalRecursionLimit, "HARN-CST-002", Cst, "const initializer exceeded the recursion depth budget";
353 ConstEvalSandboxViolation, "HARN-CST-003", Cst, "const initializer attempted a sandboxed capability";
354 ConstEvalRuntimeError, "HARN-CST-004", Cst, "const initializer raised a runtime error during evaluation";
355}
356
357impl Code {
358 pub const fn registry() -> &'static [RegistryEntry] {
359 REGISTRY
360 }
361
362 pub const fn related(self) -> &'static [Code] {
367 match self {
368 Code::TypeMismatch => &[
371 Code::AssignmentTypeMismatch,
372 Code::ArgumentTypeMismatch,
373 Code::ReturnTypeMismatch,
374 Code::VariableTypeMismatch,
375 Code::FieldTypeMismatch,
376 ],
377 Code::AssignmentTypeMismatch => &[Code::TypeMismatch, Code::VariableTypeMismatch],
378 Code::ArgumentTypeMismatch => &[Code::TypeMismatch, Code::GenericTypeArgumentMismatch],
379 Code::ReturnTypeMismatch => &[Code::TypeMismatch, Code::ClosureReturnTypeMismatch],
380 Code::VariableTypeMismatch => &[Code::TypeMismatch, Code::AssignmentTypeMismatch],
381 Code::ClosureReturnTypeMismatch => &[Code::ReturnTypeMismatch],
382 Code::FieldTypeMismatch => &[Code::TypeMismatch, Code::InvalidStructLiteral],
383 Code::MethodTypeMismatch => &[Code::TypeMismatch, Code::CallableExpected],
384 Code::GenericTypeArgumentUnsupported => &[
386 Code::GenericTypeArgumentMismatch,
387 Code::GenericTypeArgumentArity,
388 ],
389 Code::GenericTypeArgumentMismatch => &[
390 Code::GenericTypeArgumentArity,
391 Code::WhereConstraintMismatch,
392 ],
393 Code::GenericTypeArgumentArity => {
394 &[Code::GenericTypeArgumentMismatch, Code::TypeParameterArity]
395 }
396 Code::TypeParameterArity => &[Code::GenericTypeArgumentArity],
397 Code::WhereConstraintMismatch => &[Code::GenericTypeArgumentMismatch],
398 Code::UndefinedVariable => &[Code::UndefinedFunction, Code::UnknownDeclaration],
400 Code::UndefinedFunction => &[Code::UnknownBuiltin, Code::UnknownDeclaration],
401 Code::UnknownField => &[Code::UnknownMethod, Code::InvalidStructLiteral],
402 Code::UnknownMethod => &[Code::UnknownField, Code::CallableExpected],
403 Code::UnknownAttribute => {
404 &[Code::InvalidAttributeArgument, Code::InvalidAttributeTarget]
405 }
406 Code::InvalidAttributeArgument => {
407 &[Code::UnknownAttribute, Code::InvalidAttributeTarget]
408 }
409 Code::InvalidAttributeTarget => {
410 &[Code::UnknownAttribute, Code::InvalidAttributeArgument]
411 }
412 Code::LlmSchemaMissing => &[Code::LlmSchemaInvalid, Code::UnknownLlmOption],
414 Code::LlmSchemaInvalid => &[Code::LlmSchemaMissing, Code::UnknownLlmOption],
415 Code::UnknownLlmOption => &[Code::DeprecatedLlmOption, Code::LlmSchemaInvalid],
416 Code::DeprecatedLlmOption => &[Code::UnknownLlmOption],
417 Code::LlmProviderIdentityBranch => &[Code::PromptProviderIdentityBranch],
418 Code::PromptTemplateParse => &[Code::PromptTargetMissing],
420 Code::PromptInjectionRisk => &[Code::LintPromptInjectionRisk],
421 Code::PromptProviderIdentityBranch => &[
422 Code::LlmProviderIdentityBranch,
423 Code::LintTemplateProviderIdentityBranch,
424 ],
425 Code::PromptVariantExplosion => &[Code::LintTemplateVariantExplosion],
426 Code::CapabilityResultUnchecked => {
428 &[Code::RescueOutsideFunction, Code::TryOutsideFunction]
429 }
430 Code::CapabilityUnknownOperation => &[Code::CapabilityCallStaticNameRequired],
431 Code::EffectInheritanceViolation => &[
432 Code::CapabilityPayloadInvalid,
433 Code::CapabilityBindingInvalid,
434 ],
435 Code::RescueOutsideFunction => {
437 &[Code::TryOutsideFunction, Code::InvalidRescueConstruct]
438 }
439 Code::TryOutsideFunction => &[Code::RescueOutsideFunction],
440 Code::NonExhaustiveMatch => &[Code::InvalidMatchPattern, Code::DuplicateMatchArm],
441 Code::DuplicateMatchArm => &[Code::NonExhaustiveMatch, Code::LintDuplicateMatchArm],
442 Code::ModuleImportUnresolved => {
444 &[Code::ImportResolutionFailed, Code::ImportSymbolMissing]
445 }
446 Code::ModuleImportUnused => &[Code::LintUnusedImport],
447 Code::ImportResolutionFailed => {
448 &[Code::ModuleImportUnresolved, Code::ImportSymbolMissing]
449 }
450 Code::ImportCycle => &[Code::ImportResolutionFailed],
451 Code::SuspendWorkerNotRunning => {
453 &[Code::ResumeWorkerNotSuspended, Code::ResumeWorkerClosed]
454 }
455 Code::ResumeConditionsInvalid => &[
456 Code::ResumeTriggerRegistrationFailed,
457 Code::ResumeTimeoutUnsupported,
458 ],
459 Code::ResumeWorkerNotSuspended => &[
460 Code::SuspendWorkerNotRunning,
461 Code::ConcurrentResumeConflict,
462 ],
463 Code::ResumeSnapshotInvalid => &[Code::ResumeWorkerNotSuspended],
464 Code::AwaitResumptionOutsideAgentLoop => &[Code::ResumeConditionsInvalid],
465 Code::ConcurrentResumeConflict => {
466 &[Code::ResumeWorkerNotSuspended, Code::ResumeWorkerClosed]
467 }
468 Code::ResumeTriggerRegistrationFailed => &[
469 Code::ResumeConditionsInvalid,
470 Code::ResumeTimeoutUnsupported,
471 ],
472 Code::ResumeTimeoutUnsupported => &[
473 Code::ResumeConditionsInvalid,
474 Code::ResumeTriggerRegistrationFailed,
475 ],
476 Code::ResumeInputInvalid => &[Code::ResumeWorkerNotSuspended],
477 Code::ResumeWorkerClosed => &[
478 Code::ResumeWorkerNotSuspended,
479 Code::ConcurrentResumeConflict,
480 ],
481 Code::ReminderUnknownOption => {
485 &[Code::ReminderInvalidShape, Code::ReminderUnknownPropagate]
486 }
487 Code::ReminderInvalidShape => {
488 &[Code::ReminderUnknownOption, Code::ReminderUnknownPropagate]
489 }
490 Code::ReminderUnknownPropagate => {
491 &[Code::ReminderUnknownOption, Code::ReminderInvalidShape]
492 }
493 Code::ReminderProviderMalformedSpec => &[Code::ReminderInvalidShape],
494 Code::ReminderProviderBloat => &[Code::ReminderInfiniteDiscardable],
495 Code::ReminderUnsupportedHookEvent => &[Code::ReminderProviderMalformedSpec],
496 Code::ImmutableAssignment => &[Code::MutableNeverReassigned],
498 Code::MutableNeverReassigned => &[Code::LintMutableNeverReassigned],
499 Code::LintDeprecatedLlmOptions => &[Code::DeprecatedLlmOption, Code::UnknownLlmOption],
501 Code::LintPromptInjectionRisk => &[Code::PromptInjectionRisk],
502 Code::LintTemplateVariantExplosion => &[Code::PromptVariantExplosion],
503 Code::LintTemplateProviderIdentityBranch => &[Code::PromptProviderIdentityBranch],
504 Code::LintRenamedStdlibSymbol => &[Code::DeprecatedStdlibSymbol],
505 Code::LintAmbientClockBuiltin => {
506 &[Code::InvalidMainSignature, Code::LintRenamedStdlibSymbol]
507 }
508 Code::LintAmbientStdioBuiltin => {
509 &[Code::InvalidMainSignature, Code::LintRenamedStdlibSymbol]
510 }
511 Code::LintMutableNeverReassigned => &[Code::MutableNeverReassigned],
512 Code::LintUnusedImport => &[Code::ModuleImportUnused],
513 Code::LintDuplicateMatchArm => &[Code::DuplicateMatchArm],
514 _ => &[],
515 }
516 }
517}
518
519impl fmt::Display for Code {
520 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
521 f.write_str(self.as_str())
522 }
523}
524
525#[derive(Debug, Clone, Copy, PartialEq, Eq)]
527pub struct ParseCodeError;
528
529impl fmt::Display for ParseCodeError {
530 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
531 f.write_str("unknown Harn diagnostic code")
532 }
533}
534
535impl std::error::Error for ParseCodeError {}
536
537impl FromStr for Code {
538 type Err = ParseCodeError;
539
540 fn from_str(value: &str) -> Result<Self, Self::Err> {
541 Code::ALL
542 .iter()
543 .copied()
544 .find(|code| code.as_str() == value)
545 .ok_or(ParseCodeError)
546 }
547}
548
549#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
560pub enum RepairSafety {
561 FormatOnly,
564 BehaviorPreserving,
567 ScopeLocal,
571 SurfaceChanging,
574 CapabilityChanging,
578 NeedsHuman,
582}
583
584impl RepairSafety {
585 pub const ALL: &'static [RepairSafety] = &[
586 RepairSafety::FormatOnly,
587 RepairSafety::BehaviorPreserving,
588 RepairSafety::ScopeLocal,
589 RepairSafety::SurfaceChanging,
590 RepairSafety::CapabilityChanging,
591 RepairSafety::NeedsHuman,
592 ];
593
594 pub const fn as_str(self) -> &'static str {
598 match self {
599 RepairSafety::FormatOnly => "format-only",
600 RepairSafety::BehaviorPreserving => "behavior-preserving",
601 RepairSafety::ScopeLocal => "scope-local",
602 RepairSafety::SurfaceChanging => "surface-changing",
603 RepairSafety::CapabilityChanging => "capability-changing",
604 RepairSafety::NeedsHuman => "needs-human",
605 }
606 }
607
608 pub const fn is_at_most(self, ceiling: RepairSafety) -> bool {
612 (self as u8) <= (ceiling as u8)
613 }
614}
615
616impl fmt::Display for RepairSafety {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 f.write_str(self.as_str())
619 }
620}
621
622#[derive(Debug, Clone, Copy, PartialEq, Eq)]
624pub struct ParseRepairSafetyError;
625
626impl fmt::Display for ParseRepairSafetyError {
627 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
628 f.write_str("unknown Harn repair-safety class")
629 }
630}
631
632impl std::error::Error for ParseRepairSafetyError {}
633
634impl FromStr for RepairSafety {
635 type Err = ParseRepairSafetyError;
636
637 fn from_str(value: &str) -> Result<Self, Self::Err> {
638 RepairSafety::ALL
639 .iter()
640 .copied()
641 .find(|safety| safety.as_str() == value)
642 .ok_or(ParseRepairSafetyError)
643 }
644}
645
646#[derive(Debug, Clone, PartialEq, Eq, Hash)]
652pub struct RepairId(std::borrow::Cow<'static, str>);
653
654impl RepairId {
655 pub const fn from_static(s: &'static str) -> Self {
656 RepairId(std::borrow::Cow::Borrowed(s))
657 }
658
659 pub fn from_owned(s: String) -> Self {
660 RepairId(std::borrow::Cow::Owned(s))
661 }
662
663 pub fn as_str(&self) -> &str {
664 &self.0
665 }
666}
667
668impl fmt::Display for RepairId {
669 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
670 f.write_str(&self.0)
671 }
672}
673
674#[derive(Debug, Clone)]
682pub struct Repair {
683 pub id: RepairId,
684 pub summary: String,
685 pub safety: RepairSafety,
686}
687
688impl Repair {
689 pub fn from_template(template: &RepairTemplate) -> Self {
690 Repair {
691 id: RepairId::from_static(template.id),
692 summary: template.summary.to_string(),
693 safety: template.safety,
694 }
695 }
696}
697
698#[derive(Debug, Clone, Copy)]
705pub struct RepairTemplate {
706 pub id: &'static str,
707 pub summary: &'static str,
708 pub safety: RepairSafety,
709}
710
711impl Code {
712 pub const fn repair_template(self) -> Option<&'static RepairTemplate> {
715 match self {
716 Code::TypeMismatch
718 | Code::ReturnTypeMismatch
719 | Code::AssignmentTypeMismatch
720 | Code::ArgumentTypeMismatch
721 | Code::VariableTypeMismatch
722 | Code::ClosureReturnTypeMismatch
723 | Code::FieldTypeMismatch
724 | Code::MethodTypeMismatch
725 | Code::InvalidIndexType => Some(&REPAIR_INSERT_EXPLICIT_CONVERSION),
726 Code::StringInterpolationRewrite => Some(&REPAIR_REWRITE_STRING_INTERPOLATION),
727 Code::UnknownTypeName => Some(&REPAIR_IMPORTS_FIX_PATH),
728 Code::InvalidCast => Some(&REPAIR_CASTS_REMOVE_UNCHECKED),
729
730 Code::UndefinedVariable
732 | Code::UndefinedFunction
733 | Code::UnknownField
734 | Code::UnknownMethod
735 | Code::UnknownBuiltin
736 | Code::UnknownDeclaration => Some(&REPAIR_BINDINGS_RENAME_TO_CLOSEST),
737 Code::InvalidMainSignature => Some(&REPAIR_BINDINGS_THREAD_HARNESS),
738 Code::DeprecatedFunction => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
739 Code::ModuleImportUnresolved | Code::ImportResolutionFailed => {
740 Some(&REPAIR_IMPORTS_FIX_PATH)
741 }
742 Code::ModuleImportUnused => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
743 Code::ModuleImportOrder => Some(&REPAIR_IMPORTS_REORDER),
744
745 Code::CapabilityResultUnchecked => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
747 Code::CapabilityBindingInvalid => Some(&REPAIR_MANUAL_REVIEW_CAPABILITY),
748 Code::EffectInheritanceViolation => Some(&REPAIR_POLICY_NARROW_CHILD_EFFECTS),
749 Code::RescueOutsideFunction | Code::TryOutsideFunction => {
750 Some(&REPAIR_ERRORS_WRAP_IN_FN)
751 }
752
753 Code::DeprecatedLlmOption => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
755 Code::LlmSchemaMissing => Some(&REPAIR_LLM_ADD_SCHEMA),
756 Code::LlmProviderIdentityBranch | Code::PromptProviderIdentityBranch => {
757 Some(&REPAIR_LLM_USE_CAPABILITY_FLAG)
758 }
759 Code::PromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
760 Code::PromptToolSurfaceUnknown | Code::PromptToolSurfaceDeferredReference => {
761 Some(&REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE)
762 }
763 Code::PromptVariantExplosion => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
764
765 Code::DeprecatedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
767 Code::LintMissingStdlibMetadata => Some(&REPAIR_DOC_ADD_STDLIB_METADATA),
768
769 Code::ImmutableAssignment => Some(&REPAIR_BINDINGS_MAKE_MUTABLE),
771 Code::MutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
772
773 Code::NonExhaustiveMatch => Some(&REPAIR_MATCH_ADD_MISSING_ARMS),
775 Code::DuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
776
777 Code::UnreachableCode => Some(&REPAIR_DEAD_CODE_REMOVE),
779
780 Code::FormatterWouldReformat | Code::FormatterTrailingComma => {
782 Some(&REPAIR_FORMAT_REFORMAT)
783 }
784
785 Code::LintUnusedVariable
787 | Code::LintUnusedPatternBinding
788 | Code::LintUnusedParameter => Some(&REPAIR_BINDINGS_RENAME_UNUSED),
789 Code::LintUnusedImport => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
790 Code::LintUnusedFunction | Code::LintUnusedType => {
791 Some(&REPAIR_DECLARATIONS_REMOVE_UNUSED)
792 }
793 Code::LintMutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
794 Code::LintImportOrder => Some(&REPAIR_IMPORTS_REORDER),
795 Code::LintBlankLineBetweenItems
796 | Code::LintTrailingComma
797 | Code::LintUnnecessaryParentheses
798 | Code::LintRequireFileHeader => Some(&REPAIR_FORMAT_REFORMAT),
799 Code::LintLegacyDocComment => Some(&REPAIR_DOC_COMMENT_MIGRATE),
800 Code::LintEmptyBlock => Some(&REPAIR_BLOCK_REMOVE_EMPTY),
801 Code::LintUnnecessaryElseReturn | Code::LintLetThenReturn => {
802 Some(&REPAIR_CONTROL_FLOW_FLATTEN)
803 }
804 Code::LintRedundantNilTernary
805 | Code::LintUnnecessarySafeNavigation
806 | Code::LintPreferOptionalShorthand
807 | Code::LintComparisonToBool
808 | Code::LintPointlessComparison
809 | Code::LintConstantLogicalOperand => Some(&REPAIR_EXPRESSION_SIMPLIFY),
810 Code::LintUnnecessaryCast => Some(&REPAIR_CASTS_REMOVE_REDUNDANT),
811 Code::LintRedundantClone => Some(&REPAIR_CLONE_REMOVE_REDUNDANT),
812 Code::LintEagerCollectionConversion => Some(&REPAIR_COLLECTION_PREFER_LAZY),
813 Code::LintDeadCodeAfterReturn => Some(&REPAIR_DEAD_CODE_REMOVE),
814 Code::LintRenamedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
815 Code::LintAmbientClockBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_CLOCK),
816 Code::LintAmbientStdioBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_STDIO),
817 Code::LintDeprecatedLlmOptions => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
818 Code::LintTemplateProviderIdentityBranch => Some(&REPAIR_LLM_USE_CAPABILITY_FLAG),
819 Code::LintPromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
820 Code::LintShadowVariable => Some(&REPAIR_BINDINGS_RENAME_SHADOW),
821 Code::LintNamingConvention => Some(&REPAIR_STYLE_RENAME_TO_CONVENTION),
822 Code::LintUnhandledApprovalResult => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
823 Code::LintMissingHarndoc => Some(&REPAIR_DOC_ADD_HARNDOC),
824 Code::LintDuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
825 Code::LintUntypedDictAccess => Some(&REPAIR_TYPES_ADD_SHAPE_ANNOTATION),
826 Code::LintMcpToolAnnotations => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
827 Code::LintTemplateVariantExplosion | Code::LintLongRunningWithoutCleanup => {
828 Some(&REPAIR_MANUAL_NEEDS_HUMAN)
829 }
830
831 _ => None,
835 }
836 }
837}
838
839const REPAIR_INSERT_EXPLICIT_CONVERSION: RepairTemplate = RepairTemplate {
854 id: "casts/insert-explicit-conversion",
855 summary: "Insert an explicit conversion or correct the operand type",
856 safety: RepairSafety::ScopeLocal,
857};
858
859const REPAIR_REWRITE_STRING_INTERPOLATION: RepairTemplate = RepairTemplate {
860 id: "style/string-interpolation",
861 summary: "Rewrite string concatenation as an interpolation literal",
862 safety: RepairSafety::BehaviorPreserving,
863};
864
865const REPAIR_CASTS_REMOVE_UNCHECKED: RepairTemplate = RepairTemplate {
866 id: "casts/remove-unchecked",
867 summary: "Remove the unchecked cast or guard it with a type test",
868 safety: RepairSafety::ScopeLocal,
869};
870
871const REPAIR_CASTS_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
872 id: "casts/remove-redundant",
873 summary: "Remove the redundant cast",
874 safety: RepairSafety::BehaviorPreserving,
875};
876
877const REPAIR_BINDINGS_RENAME_TO_CLOSEST: RepairTemplate = RepairTemplate {
878 id: "bindings/rename-to-closest",
879 summary: "Rename to the closest in-scope identifier",
880 safety: RepairSafety::ScopeLocal,
881};
882
883const REPAIR_BINDINGS_MAKE_MUTABLE: RepairTemplate = RepairTemplate {
884 id: "bindings/make-mutable",
885 summary: "Mark the binding `mut` so it can be reassigned",
886 safety: RepairSafety::ScopeLocal,
887};
888
889const REPAIR_BINDINGS_MAKE_IMMUTABLE: RepairTemplate = RepairTemplate {
890 id: "bindings/make-immutable",
891 summary: "Drop `mut` since the binding is never reassigned",
892 safety: RepairSafety::BehaviorPreserving,
893};
894
895const REPAIR_BINDINGS_RENAME_UNUSED: RepairTemplate = RepairTemplate {
896 id: "bindings/rename-unused",
897 summary: "Prefix the unused binding with `_` to silence the lint",
898 safety: RepairSafety::BehaviorPreserving,
899};
900
901const REPAIR_BINDINGS_RENAME_SHADOW: RepairTemplate = RepairTemplate {
902 id: "bindings/rename-shadow",
903 summary: "Rename the shadowing binding to a distinct name",
904 safety: RepairSafety::ScopeLocal,
905};
906
907const REPAIR_BINDINGS_THREAD_HARNESS: RepairTemplate = RepairTemplate {
908 id: "bindings/thread-harness",
909 summary: "Rewrite the entrypoint as `fn main(harness: Harness)` so the runtime can thread its capability handle",
910 safety: RepairSafety::SurfaceChanging,
911};
912
913const REPAIR_BINDINGS_THREAD_HARNESS_CLOCK: RepairTemplate = RepairTemplate {
914 id: "bindings/thread-harness-clock",
915 summary: "Replace the ambient clock builtin with the corresponding `harness.clock.*` method",
916 safety: RepairSafety::ScopeLocal,
917};
918
919const REPAIR_BINDINGS_THREAD_HARNESS_STDIO: RepairTemplate = RepairTemplate {
920 id: "bindings/thread-harness-stdio",
921 summary: "Replace the ambient stdio builtin with the corresponding `harness.stdio.*` method",
922 safety: RepairSafety::ScopeLocal,
923};
924
925const REPAIR_DECLARATIONS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
926 id: "declarations/remove-unused",
927 summary: "Remove the unused declaration",
928 safety: RepairSafety::SurfaceChanging,
929};
930
931const REPAIR_IMPORTS_FIX_PATH: RepairTemplate = RepairTemplate {
932 id: "imports/fix-path",
933 summary: "Replace the import path with a resolvable target",
934 safety: RepairSafety::ScopeLocal,
935};
936
937const REPAIR_IMPORTS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
938 id: "imports/remove-unused",
939 summary: "Remove the unused import",
940 safety: RepairSafety::BehaviorPreserving,
941};
942
943const REPAIR_IMPORTS_REORDER: RepairTemplate = RepairTemplate {
944 id: "imports/reorder",
945 summary: "Reorder imports into canonical grouping",
946 safety: RepairSafety::FormatOnly,
947};
948
949const REPAIR_ERRORS_CHECK_OR_RESCUE: RepairTemplate = RepairTemplate {
950 id: "errors/check-or-rescue",
951 summary: "Check the result or wrap the call in a `rescue` block",
952 safety: RepairSafety::ScopeLocal,
953};
954
955const REPAIR_ERRORS_WRAP_IN_FN: RepairTemplate = RepairTemplate {
956 id: "errors/wrap-in-fn",
957 summary: "Move the construct inside a function body",
958 safety: RepairSafety::SurfaceChanging,
959};
960
961const REPAIR_MATCH_ADD_MISSING_ARMS: RepairTemplate = RepairTemplate {
962 id: "match/add-missing-arms",
963 summary: "Add arms covering the missing variants",
964 safety: RepairSafety::ScopeLocal,
965};
966
967const REPAIR_MATCH_REMOVE_DUPLICATE_ARM: RepairTemplate = RepairTemplate {
968 id: "match/remove-duplicate-arm",
969 summary: "Remove the duplicated match arm",
970 safety: RepairSafety::BehaviorPreserving,
971};
972
973const REPAIR_FORMAT_REFORMAT: RepairTemplate = RepairTemplate {
974 id: "format/reformat",
975 summary: "Apply canonical formatting",
976 safety: RepairSafety::FormatOnly,
977};
978
979const REPAIR_DOC_COMMENT_MIGRATE: RepairTemplate = RepairTemplate {
980 id: "doc/migrate-comment-style",
981 summary: "Migrate the legacy comment to canonical doc syntax",
982 safety: RepairSafety::FormatOnly,
983};
984
985const REPAIR_DOC_ADD_HARNDOC: RepairTemplate = RepairTemplate {
986 id: "doc/add-harndoc",
987 summary: "Add a `///` doc comment describing this declaration",
988 safety: RepairSafety::BehaviorPreserving,
989};
990
991const REPAIR_DOC_ADD_STDLIB_METADATA: RepairTemplate = RepairTemplate {
992 id: "doc/add-stdlib-metadata",
993 summary: "Add `@effects`, `@allocation`, `@errors`, `@api_stability`, and `@example` fields to the stdlib function's doc block",
994 safety: RepairSafety::BehaviorPreserving,
995};
996
997const REPAIR_BLOCK_REMOVE_EMPTY: RepairTemplate = RepairTemplate {
998 id: "blocks/remove-empty",
999 summary: "Remove the empty block or fill in an explicit body",
1000 safety: RepairSafety::ScopeLocal,
1001};
1002
1003const REPAIR_CONTROL_FLOW_FLATTEN: RepairTemplate = RepairTemplate {
1004 id: "control-flow/flatten",
1005 summary: "Flatten the unnecessary control flow construct",
1006 safety: RepairSafety::BehaviorPreserving,
1007};
1008
1009const REPAIR_EXPRESSION_SIMPLIFY: RepairTemplate = RepairTemplate {
1010 id: "expressions/simplify",
1011 summary: "Simplify the expression to its canonical form",
1012 safety: RepairSafety::BehaviorPreserving,
1013};
1014
1015const REPAIR_CLONE_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
1016 id: "clones/remove-redundant",
1017 summary: "Remove the redundant clone",
1018 safety: RepairSafety::BehaviorPreserving,
1019};
1020
1021const REPAIR_COLLECTION_PREFER_LAZY: RepairTemplate = RepairTemplate {
1022 id: "collections/prefer-lazy",
1023 summary: "Replace the eager collection step with a lazy variant",
1024 safety: RepairSafety::ScopeLocal,
1025};
1026
1027const REPAIR_DEAD_CODE_REMOVE: RepairTemplate = RepairTemplate {
1028 id: "control-flow/remove-dead",
1029 summary: "Remove the unreachable code",
1030 safety: RepairSafety::BehaviorPreserving,
1031};
1032
1033const REPAIR_STDLIB_MIGRATE_RENAMED: RepairTemplate = RepairTemplate {
1034 id: "stdlib/migrate-renamed",
1035 summary: "Rename the call to the renamed stdlib symbol",
1036 safety: RepairSafety::ScopeLocal,
1037};
1038
1039const REPAIR_LLM_MIGRATE_DEPRECATED_OPTION: RepairTemplate = RepairTemplate {
1040 id: "llm/migrate-deprecated-option",
1041 summary: "Replace the deprecated option with its supported equivalent",
1042 safety: RepairSafety::ScopeLocal,
1043};
1044
1045const REPAIR_LLM_ADD_SCHEMA: RepairTemplate = RepairTemplate {
1046 id: "llm/add-schema",
1047 summary: "Add a typed output schema to the LLM call",
1048 safety: RepairSafety::SurfaceChanging,
1049};
1050
1051const REPAIR_LLM_USE_CAPABILITY_FLAG: RepairTemplate = RepairTemplate {
1052 id: "llm/use-capability-flag",
1053 summary: "Branch on a capability flag instead of provider identity",
1054 safety: RepairSafety::CapabilityChanging,
1055};
1056
1057const REPAIR_PROMPTS_ESCAPE_INJECTION: RepairTemplate = RepairTemplate {
1058 id: "prompts/escape-injection",
1059 summary: "Pass the untrusted input through a structured placeholder",
1060 safety: RepairSafety::ScopeLocal,
1061};
1062
1063const REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE: RepairTemplate = RepairTemplate {
1064 id: "prompts/add-tool-to-surface",
1065 summary: "Add the referenced tool to the declared tool surface",
1066 safety: RepairSafety::SurfaceChanging,
1067};
1068
1069const REPAIR_STYLE_RENAME_TO_CONVENTION: RepairTemplate = RepairTemplate {
1070 id: "style/rename-to-convention",
1071 summary: "Rename to match the casing convention for this kind",
1072 safety: RepairSafety::SurfaceChanging,
1073};
1074
1075const REPAIR_TYPES_ADD_SHAPE_ANNOTATION: RepairTemplate = RepairTemplate {
1076 id: "types/add-shape-annotation",
1077 summary: "Annotate the dict with a concrete shape type",
1078 safety: RepairSafety::SurfaceChanging,
1079};
1080
1081const REPAIR_MANUAL_REVIEW_CAPABILITY: RepairTemplate = RepairTemplate {
1082 id: "manual/review-capability-binding",
1083 summary: "Review the capability binding; the fix is not mechanical",
1084 safety: RepairSafety::NeedsHuman,
1085};
1086
1087const REPAIR_POLICY_NARROW_CHILD_EFFECTS: RepairTemplate = RepairTemplate {
1088 id: "policy/narrow-child-effects",
1089 summary: "Narrow the child agent's effects to a subset of the parent's, or widen the parent's declared effects",
1090 safety: RepairSafety::SurfaceChanging,
1091};
1092
1093const REPAIR_MANUAL_NEEDS_HUMAN: RepairTemplate = RepairTemplate {
1094 id: "manual/needs-human",
1095 summary: "Plan a human-led change; auto-apply is not safe here",
1096 safety: RepairSafety::NeedsHuman,
1097};
1098
1099pub const REPAIR_REGISTRY: &[&RepairTemplate] = &[
1103 &REPAIR_INSERT_EXPLICIT_CONVERSION,
1104 &REPAIR_REWRITE_STRING_INTERPOLATION,
1105 &REPAIR_CASTS_REMOVE_UNCHECKED,
1106 &REPAIR_CASTS_REMOVE_REDUNDANT,
1107 &REPAIR_BINDINGS_RENAME_TO_CLOSEST,
1108 &REPAIR_BINDINGS_MAKE_MUTABLE,
1109 &REPAIR_BINDINGS_MAKE_IMMUTABLE,
1110 &REPAIR_BINDINGS_RENAME_UNUSED,
1111 &REPAIR_BINDINGS_RENAME_SHADOW,
1112 &REPAIR_BINDINGS_THREAD_HARNESS,
1113 &REPAIR_BINDINGS_THREAD_HARNESS_CLOCK,
1114 &REPAIR_BINDINGS_THREAD_HARNESS_STDIO,
1115 &REPAIR_DECLARATIONS_REMOVE_UNUSED,
1116 &REPAIR_IMPORTS_FIX_PATH,
1117 &REPAIR_IMPORTS_REMOVE_UNUSED,
1118 &REPAIR_IMPORTS_REORDER,
1119 &REPAIR_ERRORS_CHECK_OR_RESCUE,
1120 &REPAIR_ERRORS_WRAP_IN_FN,
1121 &REPAIR_MATCH_ADD_MISSING_ARMS,
1122 &REPAIR_MATCH_REMOVE_DUPLICATE_ARM,
1123 &REPAIR_FORMAT_REFORMAT,
1124 &REPAIR_DOC_COMMENT_MIGRATE,
1125 &REPAIR_DOC_ADD_HARNDOC,
1126 &REPAIR_DOC_ADD_STDLIB_METADATA,
1127 &REPAIR_BLOCK_REMOVE_EMPTY,
1128 &REPAIR_CONTROL_FLOW_FLATTEN,
1129 &REPAIR_EXPRESSION_SIMPLIFY,
1130 &REPAIR_CLONE_REMOVE_REDUNDANT,
1131 &REPAIR_COLLECTION_PREFER_LAZY,
1132 &REPAIR_DEAD_CODE_REMOVE,
1133 &REPAIR_STDLIB_MIGRATE_RENAMED,
1134 &REPAIR_LLM_MIGRATE_DEPRECATED_OPTION,
1135 &REPAIR_LLM_ADD_SCHEMA,
1136 &REPAIR_LLM_USE_CAPABILITY_FLAG,
1137 &REPAIR_PROMPTS_ESCAPE_INJECTION,
1138 &REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE,
1139 &REPAIR_STYLE_RENAME_TO_CONVENTION,
1140 &REPAIR_TYPES_ADD_SHAPE_ANNOTATION,
1141 &REPAIR_MANUAL_REVIEW_CAPABILITY,
1142 &REPAIR_MANUAL_NEEDS_HUMAN,
1143 &REPAIR_POLICY_NARROW_CHILD_EFFECTS,
1144];
1145
1146#[cfg(test)]
1147mod tests {
1148 use super::{Category, Code, ParseRepairSafetyError, RepairSafety, REPAIR_REGISTRY};
1149 use std::collections::HashSet;
1150 use std::str::FromStr;
1151
1152 #[test]
1153 fn parses_registered_code() {
1154 assert_eq!(Code::from_str("HARN-TYP-014"), Ok(Code::TypeParameterArity));
1155 }
1156
1157 #[test]
1158 fn registry_has_unique_identifiers() {
1159 let mut seen = HashSet::new();
1160 for entry in Code::registry() {
1161 assert!(
1162 seen.insert(entry.identifier),
1163 "duplicate diagnostic code {}",
1164 entry.identifier
1165 );
1166 assert_eq!(entry.code.as_str(), entry.identifier);
1167 assert_eq!(entry.code.category(), entry.category);
1168 let expected_prefix = format!("HARN-{}-", entry.category);
1169 assert!(entry.identifier.starts_with(&expected_prefix));
1170 let suffix = entry.identifier.trim_start_matches(&expected_prefix);
1171 assert_eq!(suffix.len(), 3);
1172 assert!(suffix.chars().all(|ch| ch.is_ascii_digit()));
1173 assert!(!entry.summary.is_empty());
1174 }
1175 assert!(Code::registry().len() >= 40);
1176 }
1177
1178 #[test]
1179 fn every_category_is_populated() {
1180 for category in Category::ALL {
1181 assert!(
1182 Code::registry()
1183 .iter()
1184 .any(|entry| entry.category == *category),
1185 "missing diagnostic code category {category}"
1186 );
1187 }
1188 }
1189
1190 #[test]
1191 fn every_code_has_non_empty_explanation() {
1192 for entry in Code::registry() {
1193 let body = entry.code.explanation();
1194 assert!(
1195 !body.trim().is_empty(),
1196 "diagnostic code {} has an empty explanation file",
1197 entry.identifier
1198 );
1199 assert!(
1200 body.contains(entry.identifier),
1201 "explanation for {} should reference its identifier",
1202 entry.identifier
1203 );
1204 }
1205 }
1206
1207 #[test]
1208 fn related_codes_are_registered_and_non_self() {
1209 for entry in Code::registry() {
1210 for &other in entry.code.related() {
1211 assert_ne!(
1212 other, entry.code,
1213 "{} lists itself as a related code",
1214 entry.identifier
1215 );
1216 assert!(
1217 Code::registry().iter().any(|e| e.code == other),
1218 "{} lists unregistered related code {}",
1219 entry.identifier,
1220 other
1221 );
1222 }
1223 }
1224 }
1225
1226 #[test]
1227 fn repair_safety_string_roundtrip() {
1228 for safety in RepairSafety::ALL {
1229 let parsed = RepairSafety::from_str(safety.as_str()).unwrap();
1230 assert_eq!(parsed, *safety);
1231 assert_eq!(parsed.to_string(), safety.as_str());
1232 }
1233 assert_eq!(
1234 RepairSafety::from_str("not-a-safety-class"),
1235 Err(ParseRepairSafetyError)
1236 );
1237 }
1238
1239 #[test]
1240 fn repair_safety_ordering_is_monotonic_low_to_high() {
1241 let order = RepairSafety::ALL;
1245 for window in order.windows(2) {
1246 assert!(
1247 window[0] < window[1],
1248 "{:?} should be safer than {:?}",
1249 window[0],
1250 window[1]
1251 );
1252 assert!(window[0].is_at_most(window[1]));
1253 assert!(!window[1].is_at_most(window[0]));
1254 }
1255 }
1256
1257 #[test]
1258 fn repair_registry_has_at_least_twenty_entries() {
1259 assert!(
1260 REPAIR_REGISTRY.len() >= 20,
1261 "expected ≥20 repair templates, found {}",
1262 REPAIR_REGISTRY.len()
1263 );
1264 }
1265
1266 #[test]
1267 fn repair_ids_are_kebab_case_namespaced_and_unique() {
1268 let mut seen = HashSet::new();
1269 for template in REPAIR_REGISTRY {
1270 assert!(
1271 seen.insert(template.id),
1272 "duplicate repair id {}",
1273 template.id
1274 );
1275 let (namespace, leaf) = template.id.split_once('/').unwrap_or_else(|| {
1276 panic!(
1277 "repair id `{}` is missing `<namespace>/` prefix",
1278 template.id
1279 )
1280 });
1281 assert!(
1282 !namespace.is_empty() && !leaf.is_empty(),
1283 "repair id `{}` has empty namespace or leaf",
1284 template.id
1285 );
1286 for ch in template.id.chars() {
1287 assert!(
1288 ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '/',
1289 "repair id `{}` has non-kebab character {ch:?}",
1290 template.id
1291 );
1292 }
1293 assert!(
1294 !template.summary.is_empty(),
1295 "repair {} has empty summary",
1296 template.id
1297 );
1298 let first = template.summary.chars().next().unwrap();
1300 assert!(
1301 first.is_ascii_uppercase(),
1302 "repair {} summary `{}` should start with a capital",
1303 template.id,
1304 template.summary
1305 );
1306 }
1307 }
1308
1309 #[test]
1310 fn manual_namespace_is_needs_human() {
1311 for template in REPAIR_REGISTRY {
1312 if let Some(("manual", _)) = template.id.split_once('/') {
1313 assert_eq!(
1314 template.safety,
1315 RepairSafety::NeedsHuman,
1316 "manual/* repair {} must be NeedsHuman",
1317 template.id
1318 );
1319 }
1320 }
1321 }
1322
1323 #[test]
1324 fn known_codes_carry_expected_safety_class() {
1325 let expected: &[(Code, RepairSafety, &str)] = &[
1329 (
1330 Code::FormatterWouldReformat,
1331 RepairSafety::FormatOnly,
1332 "format/reformat",
1333 ),
1334 (
1335 Code::ModuleImportUnused,
1336 RepairSafety::BehaviorPreserving,
1337 "imports/remove-unused",
1338 ),
1339 (
1340 Code::ImmutableAssignment,
1341 RepairSafety::ScopeLocal,
1342 "bindings/make-mutable",
1343 ),
1344 (
1345 Code::LintUnusedFunction,
1346 RepairSafety::SurfaceChanging,
1347 "declarations/remove-unused",
1348 ),
1349 (
1350 Code::LlmProviderIdentityBranch,
1351 RepairSafety::CapabilityChanging,
1352 "llm/use-capability-flag",
1353 ),
1354 (
1355 Code::PromptVariantExplosion,
1356 RepairSafety::NeedsHuman,
1357 "manual/needs-human",
1358 ),
1359 (
1360 Code::NonExhaustiveMatch,
1361 RepairSafety::ScopeLocal,
1362 "match/add-missing-arms",
1363 ),
1364 (
1365 Code::LintAmbientClockBuiltin,
1366 RepairSafety::ScopeLocal,
1367 "bindings/thread-harness-clock",
1368 ),
1369 ];
1370 for (code, safety, repair_id) in expected {
1371 let template = code
1372 .repair_template()
1373 .unwrap_or_else(|| panic!("{code} should have a repair template"));
1374 assert_eq!(template.safety, *safety, "{code} safety class drifted");
1375 assert_eq!(template.id, *repair_id, "{code} repair id drifted");
1376 }
1377 }
1378
1379 #[test]
1380 fn repair_templates_cover_at_least_twenty_codes() {
1381 let covered = Code::ALL
1382 .iter()
1383 .filter(|code| code.repair_template().is_some())
1384 .count();
1385 assert!(
1386 covered >= 20,
1387 "expected ≥20 codes with a repair template, found {covered}"
1388 );
1389 }
1390
1391 #[test]
1392 fn every_registered_repair_is_referenced_by_some_code() {
1393 let referenced: HashSet<&'static str> = Code::ALL
1394 .iter()
1395 .filter_map(|code| code.repair_template())
1396 .map(|template| template.id)
1397 .collect();
1398 for template in REPAIR_REGISTRY {
1399 assert!(
1400 referenced.contains(template.id),
1401 "repair {} is in REPAIR_REGISTRY but no Code maps to it",
1402 template.id
1403 );
1404 }
1405 }
1406
1407 #[test]
1408 fn every_referenced_repair_template_is_in_registry() {
1409 let registered: HashSet<&'static str> =
1410 REPAIR_REGISTRY.iter().map(|template| template.id).collect();
1411 for code in Code::ALL {
1412 let Some(template) = code.repair_template() else {
1413 continue;
1414 };
1415 assert!(
1416 registered.contains(template.id),
1417 "repair {} (used by {}) is missing from REPAIR_REGISTRY",
1418 template.id,
1419 code
1420 );
1421 }
1422 }
1423}