Skip to main content

harn_parser/diagnostic_codes/
repairs.rs

1//! Repair vocabulary attached to a diagnostic code.
2//!
3//! A diagnostic says what is wrong; a repair says what an agent or editor may
4//! do about it and how far that action is allowed to reach. The safety ladder
5//! here is a contract surface — `harn fix --safety <class>` and IDE auto-apply
6//! ceilings both compare against it — so the wire strings are as stable as the
7//! codes themselves.
8//!
9//! Split out of `diagnostic_codes.rs` (#6126), which had reached its
10//! source-length ceiling and could not accept another code. The registry keeps
11//! the codes; this module keeps everything that answers "and what do I do".
12
13use std::{fmt, str::FromStr};
14
15use super::Code;
16
17/// Autonomy ceiling of a proposed repair.
18///
19/// Agents and IDEs use this class to auto-apply, suggest, or escalate a fix. Variants
20/// are ordered from least to most disruptive — call sites can compare
21/// with `<=` to enforce a configured ceiling like
22/// `"apply anything up to behavior-preserving"`.
23///
24/// The wire-format strings (`format-only`, `behavior-preserving`, …) are
25/// the contract surface; renaming a variant string is a breaking change.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
27pub enum RepairSafety {
28    /// Whitespace, trivia, or canonical layout only. No code structure
29    /// changes; safe to auto-apply.
30    FormatOnly,
31    /// Intended not to change observable runtime behavior (e.g. delete an
32    /// unreachable branch, drop a redundant cast).
33    BehaviorPreserving,
34    /// Confined to the current local scope or file. Runtime behavior may
35    /// change, but the blast radius does not cross a declaration boundary
36    /// or a public surface.
37    ScopeLocal,
38    /// Touches a signature, export, or call-site surface that other files
39    /// or external consumers can observe.
40    SurfaceChanging,
41    /// Required capabilities or sandbox profile may change as a result of
42    /// applying the repair (e.g. swapping `provider: "openai"` for a
43    /// capability flag widens the routing surface).
44    CapabilityChanging,
45    /// Planning hint only — agents should propose, never auto-apply.
46    /// Aligned with the `AutonomyTier::Suggest`/`ActWithApproval` rungs
47    /// in `trust_graph.rs`.
48    NeedsHuman,
49}
50
51impl RepairSafety {
52    pub const ALL: &'static [RepairSafety] = &[
53        RepairSafety::FormatOnly,
54        RepairSafety::BehaviorPreserving,
55        RepairSafety::ScopeLocal,
56        RepairSafety::SurfaceChanging,
57        RepairSafety::CapabilityChanging,
58        RepairSafety::NeedsHuman,
59    ];
60
61    /// Stable wire-format string. The contract surface — do not rename
62    /// without coordinating with `harn fix --safety <…>` callers and
63    /// downstream LSP/IDE clients.
64    pub const fn as_str(self) -> &'static str {
65        match self {
66            RepairSafety::FormatOnly => "format-only",
67            RepairSafety::BehaviorPreserving => "behavior-preserving",
68            RepairSafety::ScopeLocal => "scope-local",
69            RepairSafety::SurfaceChanging => "surface-changing",
70            RepairSafety::CapabilityChanging => "capability-changing",
71            RepairSafety::NeedsHuman => "needs-human",
72        }
73    }
74
75    /// True when `self` sits at or below `ceiling`. Used by
76    /// `harn fix --apply --safety <ceiling>` and IDE auto-apply policies
77    /// to decide whether a repair clears the configured autonomy bar.
78    pub const fn is_at_most(self, ceiling: RepairSafety) -> bool {
79        (self as u8) <= (ceiling as u8)
80    }
81}
82
83impl fmt::Display for RepairSafety {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.write_str(self.as_str())
86    }
87}
88
89/// Error returned when parsing an unknown repair-safety string.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub struct ParseRepairSafetyError;
92
93impl fmt::Display for ParseRepairSafetyError {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.write_str("unknown Harn repair-safety class")
96    }
97}
98
99impl std::error::Error for ParseRepairSafetyError {}
100
101impl FromStr for RepairSafety {
102    type Err = ParseRepairSafetyError;
103
104    fn from_str(value: &str) -> Result<Self, Self::Err> {
105        RepairSafety::ALL
106            .iter()
107            .copied()
108            .find(|safety| safety.as_str() == value)
109            .ok_or(ParseRepairSafetyError)
110    }
111}
112
113/// Namespaced kebab-case repair identifier (e.g. `imports/fix-path`).
114///
115/// Wraps a `Cow` so registry-driven values reuse a `'static` literal and
116/// per-site overrides can still attach an owned string. The wire-format
117/// string is the contract surface — never normalize or reformat on read.
118#[derive(Debug, Clone, PartialEq, Eq, Hash)]
119pub struct RepairId(std::borrow::Cow<'static, str>);
120
121impl RepairId {
122    pub const fn from_static(s: &'static str) -> Self {
123        RepairId(std::borrow::Cow::Borrowed(s))
124    }
125
126    pub fn from_owned(s: String) -> Self {
127        RepairId(std::borrow::Cow::Owned(s))
128    }
129
130    pub fn as_str(&self) -> &str {
131        &self.0
132    }
133}
134
135impl fmt::Display for RepairId {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        f.write_str(&self.0)
138    }
139}
140
141/// A structured repair proposal attached to a diagnostic.
142///
143/// `id` and `summary` are agent-readable metadata; `safety` is the
144/// dispatch dimension that decides whether the repair clears an
145/// autonomy ceiling. The concrete edits, when known statically, live on
146/// the diagnostic's `fix: Option<Vec<FixEdit>>`; this `Repair` is the
147/// classifier above those edits, not a replacement for them.
148#[derive(Debug, Clone)]
149pub struct Repair {
150    pub id: RepairId,
151    pub summary: String,
152    pub safety: RepairSafety,
153}
154
155impl Repair {
156    pub fn from_template(template: &RepairTemplate) -> Self {
157        Repair {
158            id: RepairId::from_static(template.id),
159            summary: template.summary.to_string(),
160            safety: template.safety,
161        }
162    }
163}
164
165/// Static-lifetime repair template bound to a diagnostic code.
166///
167/// Stored in the registry alongside `Code`. Construction sites can
168/// materialize a `Repair` via [`Repair::from_template`] or override
169/// `summary` for instance-specific detail by building a `Repair`
170/// directly.
171#[derive(Debug, Clone, Copy)]
172pub struct RepairTemplate {
173    pub id: &'static str,
174    pub summary: &'static str,
175    pub safety: RepairSafety,
176}
177
178impl Code {
179    /// Look up the default repair template attached to this diagnostic
180    /// code, or `None` if no actionable fix shape is registered.
181    pub const fn repair_template(self) -> Option<&'static RepairTemplate> {
182        match self {
183            // --- TYP: type mismatches & coercions -------------------------
184            Code::TypeMismatch
185            | Code::ReturnTypeMismatch
186            | Code::AssignmentTypeMismatch
187            | Code::ArgumentTypeMismatch
188            | Code::VariableTypeMismatch
189            | Code::ClosureReturnTypeMismatch
190            | Code::FieldTypeMismatch
191            | Code::MethodTypeMismatch
192            | Code::InvalidIndexType => Some(&REPAIR_INSERT_EXPLICIT_CONVERSION),
193            Code::StringInterpolationRewrite => Some(&REPAIR_REWRITE_STRING_INTERPOLATION),
194            Code::UnknownTypeName => Some(&REPAIR_IMPORTS_FIX_PATH),
195            Code::InvalidCast => Some(&REPAIR_CASTS_REMOVE_UNCHECKED),
196
197            // --- NAM / IMP: imports & names -------------------------------
198            Code::UndefinedVariable
199            | Code::UndefinedFunction
200            | Code::UnknownField
201            | Code::UnknownMethod
202            | Code::UnknownBuiltin
203            | Code::UnknownDeclaration => Some(&REPAIR_BINDINGS_RENAME_TO_CLOSEST),
204            Code::InvalidMainSignature => Some(&REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM),
205            Code::DeprecatedFunction => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
206            Code::ModuleImportUnresolved | Code::ImportResolutionFailed => {
207                Some(&REPAIR_IMPORTS_FIX_PATH)
208            }
209            Code::ModuleImportUnused => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
210            Code::ModuleImportOrder => Some(&REPAIR_IMPORTS_REORDER),
211
212            // --- CAP / RCV: capabilities & error recovery -----------------
213            Code::CapabilityResultUnchecked => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
214            Code::CapabilityBindingInvalid => Some(&REPAIR_MANUAL_REVIEW_CAPABILITY),
215            Code::EffectInheritanceViolation => Some(&REPAIR_POLICY_NARROW_CHILD_EFFECTS),
216            Code::RescueOutsideFunction | Code::TryOutsideFunction => {
217                Some(&REPAIR_ERRORS_WRAP_IN_FN)
218            }
219
220            // --- LLM / PRM: model + prompt contract -----------------------
221            Code::DeprecatedLlmOption => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
222            Code::LlmSchemaMissing => Some(&REPAIR_LLM_ADD_SCHEMA),
223            Code::LlmProviderIdentityBranch | Code::PromptProviderIdentityBranch => {
224                Some(&REPAIR_LLM_USE_CAPABILITY_FLAG)
225            }
226            Code::PromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
227            Code::PromptToolSurfaceUnknown | Code::PromptToolSurfaceDeferredReference => {
228                Some(&REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE)
229            }
230            Code::PromptVariantExplosion => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
231
232            // --- STD: stdlib usage ----------------------------------------
233            Code::DeprecatedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
234            Code::LintMissingStdlibMetadata => Some(&REPAIR_DOC_ADD_STDLIB_METADATA),
235
236            // --- OWN: ownership & mutability ------------------------------
237            Code::ImmutableAssignment => Some(&REPAIR_BINDINGS_MAKE_MUTABLE),
238            Code::MutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
239
240            // --- MAT: match exhaustiveness --------------------------------
241            Code::NonExhaustiveMatch => Some(&REPAIR_MATCH_ADD_MISSING_ARMS),
242            Code::DuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
243
244            // --- ORC: orchestration ---------------------------------------
245            Code::UnreachableCode => Some(&REPAIR_DEAD_CODE_REMOVE),
246
247            // --- FMT: formatter -------------------------------------------
248            Code::FormatterWouldReformat | Code::FormatterTrailingComma => {
249                Some(&REPAIR_FORMAT_REFORMAT)
250            }
251
252            // --- LNT: lints with structured fixes -------------------------
253            Code::LintUnusedVariable
254            | Code::LintUnusedPatternBinding
255            | Code::LintUnusedParameter => Some(&REPAIR_BINDINGS_RENAME_UNUSED),
256            Code::LintCapabilityParameterName => Some(&REPAIR_BINDINGS_NAME_CAPABILITY_PARAMETER),
257            Code::LintUnusedImport => Some(&REPAIR_IMPORTS_REMOVE_UNUSED),
258            Code::LintUnusedFunction | Code::LintUnusedType => {
259                Some(&REPAIR_DECLARATIONS_REMOVE_UNUSED)
260            }
261            Code::LintMutableNeverReassigned => Some(&REPAIR_BINDINGS_MAKE_IMMUTABLE),
262            Code::LintImportOrder => Some(&REPAIR_IMPORTS_REORDER),
263            Code::LintBlankLineBetweenItems
264            | Code::LintTrailingComma
265            | Code::LintUnnecessaryParentheses
266            | Code::LintRequireFileHeader => Some(&REPAIR_FORMAT_REFORMAT),
267            Code::LintLegacyDocComment => Some(&REPAIR_DOC_COMMENT_MIGRATE),
268            Code::LintEmptyBlock => Some(&REPAIR_BLOCK_REMOVE_EMPTY),
269            Code::LintUnnecessaryElseReturn | Code::LintLetThenReturn => {
270                Some(&REPAIR_CONTROL_FLOW_FLATTEN)
271            }
272            Code::LintNilCoalesceNoop
273            | Code::LintNilCoalesceSelfFallback
274            | Code::LintRedundantNilTernary
275            | Code::LintUnnecessarySafeNavigation
276            | Code::LintUnnecessaryNonNullAssert
277            | Code::LintPreferOptionalShorthand
278            | Code::LintComparisonToBool
279            | Code::LintPointlessComparison
280            | Code::LintConstantLogicalOperand => Some(&REPAIR_EXPRESSION_SIMPLIFY),
281            Code::LintUnnecessaryCast => Some(&REPAIR_CASTS_REMOVE_REDUNDANT),
282            Code::LintRedundantClone => Some(&REPAIR_CLONE_REMOVE_REDUNDANT),
283            Code::LintEagerCollectionConversion => Some(&REPAIR_COLLECTION_PREFER_LAZY),
284            Code::LintDeadCodeAfterReturn => Some(&REPAIR_DEAD_CODE_REMOVE),
285            Code::LintRenamedStdlibSymbol => Some(&REPAIR_STDLIB_MIGRATE_RENAMED),
286            Code::LintAmbientClockBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_CLOCK),
287            Code::LintAmbientFsBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_FS),
288            Code::LintAmbientEnvBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_ENV),
289            Code::LintAmbientRandomBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_RANDOM),
290            Code::LintAmbientNetBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS_NET),
291            Code::LintAmbientStdioBuiltin => Some(&REPAIR_BINDINGS_THREAD_HARNESS),
292            Code::LintAmbientHarnessMethod => Some(&REPAIR_BINDINGS_THREAD_HARNESS_METHOD),
293            Code::LintBroadHarnessParameter => Some(&REPAIR_BINDINGS_ATTENUATE_HARNESS),
294            Code::LintDeprecatedLlmOptions => Some(&REPAIR_LLM_MIGRATE_DEPRECATED_OPTION),
295            Code::LintTemplateProviderIdentityBranch => Some(&REPAIR_LLM_USE_CAPABILITY_FLAG),
296            Code::LintPromptInjectionRisk => Some(&REPAIR_PROMPTS_ESCAPE_INJECTION),
297            Code::LintShadowVariable => Some(&REPAIR_BINDINGS_RENAME_SHADOW),
298            Code::LintNamingConvention => Some(&REPAIR_STYLE_RENAME_TO_CONVENTION),
299            Code::LintUnhandledApprovalResult => Some(&REPAIR_ERRORS_CHECK_OR_RESCUE),
300            Code::LintMissingHarndoc => Some(&REPAIR_DOC_ADD_HARNDOC),
301            Code::LintDuplicateMatchArm => Some(&REPAIR_MATCH_REMOVE_DUPLICATE_ARM),
302            Code::LintUntypedDictAccess => Some(&REPAIR_TYPES_ADD_SHAPE_ANNOTATION),
303            Code::LintUnnormalizedOptions => Some(&REPAIR_TYPES_ADD_SHAPE_ANNOTATION),
304            Code::LintMcpToolAnnotations => Some(&REPAIR_MANUAL_NEEDS_HUMAN),
305            Code::LintTemplateVariantExplosion | Code::LintLongRunningWithoutCleanup => {
306                Some(&REPAIR_MANUAL_NEEDS_HUMAN)
307            }
308
309            // Everything else: no statically known repair shape. Agents
310            // should treat these as "diagnose only" until a repair is
311            // registered.
312            _ => None,
313        }
314    }
315}
316
317// Repair-id catalog. Each `RepairTemplate` carries a kebab-case
318// namespaced id (`<namespace>/<verb-noun>`), a one-line summary written
319// in the imperative voice, and a `RepairSafety` class.
320//
321// Conventions:
322//   - Namespaces stay short: `bindings/`, `imports/`, `errors/`, `casts/`,
323//     `format/`, `llm/`, `prompts/`, `match/`, `stdlib/`, `lint/`,
324//     `doc/`, `style/`, `types/`, `manual/`.
325//   - Summary starts with a verb ("Replace…", "Remove…", "Insert…").
326//   - Safety must be the most permissive class that is still always true
327//     for every site this template attaches to. When unsure, pick the
328//     stricter class — agents tighten too-loose policies later, never
329//     too-tight ones.
330
331const REPAIR_INSERT_EXPLICIT_CONVERSION: RepairTemplate = RepairTemplate {
332    id: "casts/insert-explicit-conversion",
333    summary: "Insert an explicit conversion or correct the operand type",
334    safety: RepairSafety::ScopeLocal,
335};
336
337const REPAIR_REWRITE_STRING_INTERPOLATION: RepairTemplate = RepairTemplate {
338    id: "style/string-interpolation",
339    summary: "Rewrite string concatenation as an interpolation literal",
340    safety: RepairSafety::BehaviorPreserving,
341};
342
343const REPAIR_CASTS_REMOVE_UNCHECKED: RepairTemplate = RepairTemplate {
344    id: "casts/remove-unchecked",
345    summary: "Remove the unchecked cast or guard it with a type test",
346    safety: RepairSafety::ScopeLocal,
347};
348
349const REPAIR_CASTS_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
350    id: "casts/remove-redundant",
351    summary: "Remove the redundant cast",
352    safety: RepairSafety::BehaviorPreserving,
353};
354
355const REPAIR_BINDINGS_RENAME_TO_CLOSEST: RepairTemplate = RepairTemplate {
356    id: "bindings/rename-to-closest",
357    summary: "Rename to the closest in-scope identifier",
358    safety: RepairSafety::ScopeLocal,
359};
360
361const REPAIR_BINDINGS_MAKE_MUTABLE: RepairTemplate = RepairTemplate {
362    id: "bindings/make-mutable",
363    summary: "Declare the binding with `let` so it can be reassigned",
364    safety: RepairSafety::ScopeLocal,
365};
366
367const REPAIR_BINDINGS_MAKE_IMMUTABLE: RepairTemplate = RepairTemplate {
368    id: "bindings/make-immutable",
369    summary: "Declare the never-reassigned binding with `const` instead of `let`",
370    safety: RepairSafety::BehaviorPreserving,
371};
372
373const REPAIR_BINDINGS_RENAME_UNUSED: RepairTemplate = RepairTemplate {
374    id: "bindings/rename-unused",
375    summary: "Use the `_` discard binding for an unused binding",
376    safety: RepairSafety::BehaviorPreserving,
377};
378
379const REPAIR_BINDINGS_NAME_CAPABILITY_PARAMETER: RepairTemplate = RepairTemplate {
380    id: "bindings/name-capability-parameter",
381    summary: "Rename the capability parameter and its references after the capability it carries",
382    safety: RepairSafety::SurfaceChanging,
383};
384
385const REPAIR_BINDINGS_RENAME_SHADOW: RepairTemplate = RepairTemplate {
386    id: "bindings/rename-shadow",
387    summary: "Rename the shadowing binding to a distinct name",
388    safety: RepairSafety::ScopeLocal,
389};
390
391const REPAIR_BINDINGS_THREAD_HARNESS: RepairTemplate = RepairTemplate {
392    id: "bindings/thread-harness",
393    summary: "Thread the existing `harness` binding through local helper calls and replace the ambient stdio builtin with `harness.stdio.*`",
394    safety: RepairSafety::ScopeLocal,
395};
396
397const REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM: RepairTemplate = RepairTemplate {
398    id: "bindings/thread-harness-needs-param",
399    summary: "Add a `harness: Harness` parameter where the stdio capability handle is required and update local callers",
400    safety: RepairSafety::SurfaceChanging,
401};
402
403const REPAIR_BINDINGS_THREAD_HARNESS_METHOD: RepairTemplate = RepairTemplate {
404    id: "bindings/thread-harness-method",
405    summary: "Replace the ambient runtime builtin with its typed `harness.*` method and thread authority through local callers",
406    safety: RepairSafety::ScopeLocal,
407};
408
409const REPAIR_BINDINGS_THREAD_HARNESS_CLOCK: RepairTemplate = RepairTemplate {
410    id: "bindings/thread-harness-clock",
411    summary: "Replace the ambient clock builtin with the corresponding `harness.clock.*` method",
412    safety: RepairSafety::ScopeLocal,
413};
414
415const REPAIR_BINDINGS_THREAD_HARNESS_FS: RepairTemplate = RepairTemplate {
416    id: "bindings/thread-harness-fs",
417    summary: "Replace the ambient fs builtin with the corresponding `harness.fs.*` method",
418    safety: RepairSafety::ScopeLocal,
419};
420
421const REPAIR_BINDINGS_THREAD_HARNESS_ENV: RepairTemplate = RepairTemplate {
422    id: "bindings/thread-harness-env",
423    summary: "Replace the ambient env builtin with the corresponding `harness.env.*` method",
424    safety: RepairSafety::ScopeLocal,
425};
426
427const REPAIR_BINDINGS_THREAD_HARNESS_RANDOM: RepairTemplate = RepairTemplate {
428    id: "bindings/thread-harness-random",
429    summary: "Replace the ambient random builtin with the corresponding `harness.random.*` method",
430    safety: RepairSafety::ScopeLocal,
431};
432
433const REPAIR_BINDINGS_THREAD_HARNESS_NET: RepairTemplate = RepairTemplate {
434    id: "bindings/thread-harness-net",
435    summary: "Replace the ambient net builtin with the corresponding `harness.net.*` method",
436    safety: RepairSafety::ScopeLocal,
437};
438
439const REPAIR_DECLARATIONS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
440    id: "declarations/remove-unused",
441    summary: "Remove the unused declaration",
442    safety: RepairSafety::SurfaceChanging,
443};
444
445const REPAIR_IMPORTS_FIX_PATH: RepairTemplate = RepairTemplate {
446    id: "imports/fix-path",
447    summary: "Replace the import path with a resolvable target",
448    safety: RepairSafety::ScopeLocal,
449};
450
451const REPAIR_IMPORTS_REMOVE_UNUSED: RepairTemplate = RepairTemplate {
452    id: "imports/remove-unused",
453    summary: "Remove the unused import",
454    safety: RepairSafety::BehaviorPreserving,
455};
456
457const REPAIR_IMPORTS_REORDER: RepairTemplate = RepairTemplate {
458    id: "imports/reorder",
459    summary: "Reorder imports into canonical grouping",
460    safety: RepairSafety::FormatOnly,
461};
462
463const REPAIR_ERRORS_CHECK_OR_RESCUE: RepairTemplate = RepairTemplate {
464    id: "errors/check-or-rescue",
465    summary: "Check the result or wrap the call in a `rescue` block",
466    safety: RepairSafety::ScopeLocal,
467};
468
469const REPAIR_ERRORS_WRAP_IN_FN: RepairTemplate = RepairTemplate {
470    id: "errors/wrap-in-fn",
471    summary: "Move the construct inside a function body",
472    safety: RepairSafety::SurfaceChanging,
473};
474
475const REPAIR_MATCH_ADD_MISSING_ARMS: RepairTemplate = RepairTemplate {
476    id: "match/add-missing-arms",
477    summary: "Add arms covering the missing variants",
478    safety: RepairSafety::ScopeLocal,
479};
480
481const REPAIR_MATCH_REMOVE_DUPLICATE_ARM: RepairTemplate = RepairTemplate {
482    id: "match/remove-duplicate-arm",
483    summary: "Remove the duplicated match arm",
484    safety: RepairSafety::BehaviorPreserving,
485};
486
487const REPAIR_FORMAT_REFORMAT: RepairTemplate = RepairTemplate {
488    id: "format/reformat",
489    summary: "Apply canonical formatting",
490    safety: RepairSafety::FormatOnly,
491};
492
493const REPAIR_DOC_COMMENT_MIGRATE: RepairTemplate = RepairTemplate {
494    id: "doc/migrate-comment-style",
495    summary: "Migrate the legacy comment to canonical doc syntax",
496    safety: RepairSafety::FormatOnly,
497};
498
499const REPAIR_DOC_ADD_HARNDOC: RepairTemplate = RepairTemplate {
500    id: "doc/add-harndoc",
501    summary: "Add a `///` doc comment describing this declaration",
502    safety: RepairSafety::BehaviorPreserving,
503};
504
505const REPAIR_DOC_ADD_STDLIB_METADATA: RepairTemplate = RepairTemplate {
506    id: "doc/add-stdlib-metadata",
507    summary: "Add `@effects` and `@errors` fields to the stdlib function's doc block",
508    safety: RepairSafety::BehaviorPreserving,
509};
510
511const REPAIR_BLOCK_REMOVE_EMPTY: RepairTemplate = RepairTemplate {
512    id: "blocks/remove-empty",
513    summary: "Remove the empty block or fill in an explicit body",
514    safety: RepairSafety::ScopeLocal,
515};
516
517const REPAIR_CONTROL_FLOW_FLATTEN: RepairTemplate = RepairTemplate {
518    id: "control-flow/flatten",
519    summary: "Flatten the unnecessary control flow construct",
520    safety: RepairSafety::BehaviorPreserving,
521};
522
523const REPAIR_EXPRESSION_SIMPLIFY: RepairTemplate = RepairTemplate {
524    id: "expressions/simplify",
525    summary: "Simplify the expression to its canonical form",
526    safety: RepairSafety::BehaviorPreserving,
527};
528
529const REPAIR_CLONE_REMOVE_REDUNDANT: RepairTemplate = RepairTemplate {
530    id: "clones/remove-redundant",
531    summary: "Remove the redundant clone",
532    safety: RepairSafety::BehaviorPreserving,
533};
534
535const REPAIR_COLLECTION_PREFER_LAZY: RepairTemplate = RepairTemplate {
536    id: "collections/prefer-lazy",
537    summary: "Replace the eager collection step with a lazy variant",
538    safety: RepairSafety::ScopeLocal,
539};
540
541const REPAIR_DEAD_CODE_REMOVE: RepairTemplate = RepairTemplate {
542    id: "control-flow/remove-dead",
543    summary: "Remove the unreachable code",
544    safety: RepairSafety::BehaviorPreserving,
545};
546
547const REPAIR_STDLIB_MIGRATE_RENAMED: RepairTemplate = RepairTemplate {
548    id: "stdlib/migrate-renamed",
549    summary: "Rename the call to the renamed stdlib symbol",
550    safety: RepairSafety::ScopeLocal,
551};
552
553const REPAIR_BINDINGS_ATTENUATE_HARNESS: RepairTemplate = RepairTemplate {
554    id: "bindings/attenuate-harness",
555    summary: "Replace the root Harness parameter with the single capability the helper uses",
556    safety: RepairSafety::SurfaceChanging,
557};
558
559const REPAIR_LLM_MIGRATE_DEPRECATED_OPTION: RepairTemplate = RepairTemplate {
560    id: "llm/migrate-deprecated-option",
561    summary: "Replace the deprecated option with its supported equivalent",
562    safety: RepairSafety::ScopeLocal,
563};
564
565const REPAIR_LLM_ADD_SCHEMA: RepairTemplate = RepairTemplate {
566    id: "llm/add-schema",
567    summary: "Add a typed output schema to the LLM call",
568    safety: RepairSafety::SurfaceChanging,
569};
570
571const REPAIR_LLM_USE_CAPABILITY_FLAG: RepairTemplate = RepairTemplate {
572    id: "llm/use-capability-flag",
573    summary: "Branch on a capability flag instead of provider identity",
574    safety: RepairSafety::CapabilityChanging,
575};
576
577const REPAIR_PROMPTS_ESCAPE_INJECTION: RepairTemplate = RepairTemplate {
578    id: "prompts/escape-injection",
579    summary: "Pass the untrusted input through a structured placeholder",
580    safety: RepairSafety::ScopeLocal,
581};
582
583const REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE: RepairTemplate = RepairTemplate {
584    id: "prompts/add-tool-to-surface",
585    summary: "Add the referenced tool to the declared tool surface",
586    safety: RepairSafety::SurfaceChanging,
587};
588
589const REPAIR_STYLE_RENAME_TO_CONVENTION: RepairTemplate = RepairTemplate {
590    id: "style/rename-to-convention",
591    summary: "Rename to match the casing convention for this kind",
592    safety: RepairSafety::SurfaceChanging,
593};
594
595const REPAIR_TYPES_ADD_SHAPE_ANNOTATION: RepairTemplate = RepairTemplate {
596    id: "types/add-shape-annotation",
597    summary: "Annotate the dict with a concrete shape type",
598    safety: RepairSafety::SurfaceChanging,
599};
600
601const REPAIR_MANUAL_REVIEW_CAPABILITY: RepairTemplate = RepairTemplate {
602    id: "manual/review-capability-binding",
603    summary: "Review the capability binding; the fix is not mechanical",
604    safety: RepairSafety::NeedsHuman,
605};
606
607const REPAIR_POLICY_NARROW_CHILD_EFFECTS: RepairTemplate = RepairTemplate {
608    id: "policy/narrow-child-effects",
609    summary: "Narrow the child agent's effects to a subset of the parent's, or widen the parent's declared effects",
610    safety: RepairSafety::SurfaceChanging,
611};
612
613const REPAIR_MANUAL_NEEDS_HUMAN: RepairTemplate = RepairTemplate {
614    id: "manual/needs-human",
615    summary: "Plan a human-led change; auto-apply is not safe here",
616    safety: RepairSafety::NeedsHuman,
617};
618
619/// Every repair template registered by [`Code::repair_template`], in source
620/// order for catalog generation and health checks.
621pub const REPAIR_REGISTRY: &[&RepairTemplate] = &[
622    &REPAIR_INSERT_EXPLICIT_CONVERSION,
623    &REPAIR_REWRITE_STRING_INTERPOLATION,
624    &REPAIR_CASTS_REMOVE_UNCHECKED,
625    &REPAIR_CASTS_REMOVE_REDUNDANT,
626    &REPAIR_BINDINGS_RENAME_TO_CLOSEST,
627    &REPAIR_BINDINGS_MAKE_MUTABLE,
628    &REPAIR_BINDINGS_MAKE_IMMUTABLE,
629    &REPAIR_BINDINGS_RENAME_UNUSED,
630    &REPAIR_BINDINGS_NAME_CAPABILITY_PARAMETER,
631    &REPAIR_BINDINGS_RENAME_SHADOW,
632    &REPAIR_BINDINGS_THREAD_HARNESS,
633    &REPAIR_BINDINGS_THREAD_HARNESS_NEEDS_PARAM,
634    &REPAIR_BINDINGS_THREAD_HARNESS_METHOD,
635    &REPAIR_BINDINGS_THREAD_HARNESS_CLOCK,
636    &REPAIR_BINDINGS_THREAD_HARNESS_FS,
637    &REPAIR_BINDINGS_THREAD_HARNESS_ENV,
638    &REPAIR_BINDINGS_THREAD_HARNESS_RANDOM,
639    &REPAIR_BINDINGS_THREAD_HARNESS_NET,
640    &REPAIR_DECLARATIONS_REMOVE_UNUSED,
641    &REPAIR_IMPORTS_FIX_PATH,
642    &REPAIR_IMPORTS_REMOVE_UNUSED,
643    &REPAIR_IMPORTS_REORDER,
644    &REPAIR_ERRORS_CHECK_OR_RESCUE,
645    &REPAIR_ERRORS_WRAP_IN_FN,
646    &REPAIR_MATCH_ADD_MISSING_ARMS,
647    &REPAIR_MATCH_REMOVE_DUPLICATE_ARM,
648    &REPAIR_FORMAT_REFORMAT,
649    &REPAIR_DOC_COMMENT_MIGRATE,
650    &REPAIR_DOC_ADD_HARNDOC,
651    &REPAIR_DOC_ADD_STDLIB_METADATA,
652    &REPAIR_BLOCK_REMOVE_EMPTY,
653    &REPAIR_CONTROL_FLOW_FLATTEN,
654    &REPAIR_EXPRESSION_SIMPLIFY,
655    &REPAIR_CLONE_REMOVE_REDUNDANT,
656    &REPAIR_COLLECTION_PREFER_LAZY,
657    &REPAIR_DEAD_CODE_REMOVE,
658    &REPAIR_STDLIB_MIGRATE_RENAMED,
659    &REPAIR_BINDINGS_ATTENUATE_HARNESS,
660    &REPAIR_LLM_MIGRATE_DEPRECATED_OPTION,
661    &REPAIR_LLM_ADD_SCHEMA,
662    &REPAIR_LLM_USE_CAPABILITY_FLAG,
663    &REPAIR_PROMPTS_ESCAPE_INJECTION,
664    &REPAIR_PROMPTS_ADD_TOOL_TO_SURFACE,
665    &REPAIR_STYLE_RENAME_TO_CONVENTION,
666    &REPAIR_TYPES_ADD_SHAPE_ANNOTATION,
667    &REPAIR_MANUAL_REVIEW_CAPABILITY,
668    &REPAIR_MANUAL_NEEDS_HUMAN,
669    &REPAIR_POLICY_NARROW_CHILD_EFFECTS,
670];
671
672#[cfg(test)]
673mod tests {
674    use super::super::Category;
675    use super::{Code, ParseRepairSafetyError, RepairSafety, REPAIR_REGISTRY};
676    use std::collections::HashSet;
677    use std::str::FromStr;
678
679    #[test]
680    fn parses_registered_code() {
681        assert_eq!(Code::from_str("HARN-TYP-014"), Ok(Code::TypeParameterArity));
682    }
683
684    #[test]
685    fn registry_has_unique_identifiers() {
686        let mut seen = HashSet::new();
687        for entry in Code::registry() {
688            assert!(
689                seen.insert(entry.identifier),
690                "duplicate diagnostic code {}",
691                entry.identifier
692            );
693            assert_eq!(entry.code.as_str(), entry.identifier);
694            assert_eq!(entry.code.category(), entry.category);
695            let expected_prefix = format!("HARN-{}-", entry.category);
696            assert!(entry.identifier.starts_with(&expected_prefix));
697            let suffix = entry.identifier.trim_start_matches(&expected_prefix);
698            assert_eq!(suffix.len(), 3);
699            assert!(suffix.chars().all(|ch| ch.is_ascii_digit()));
700            assert!(!entry.summary.is_empty());
701        }
702        assert!(Code::registry().len() >= 40);
703    }
704
705    #[test]
706    fn every_category_is_populated() {
707        for category in Category::ALL {
708            assert!(
709                Code::registry()
710                    .iter()
711                    .any(|entry| entry.category == *category),
712                "missing diagnostic code category {category}"
713            );
714        }
715    }
716
717    #[test]
718    fn every_code_has_non_empty_explanation() {
719        for entry in Code::registry() {
720            let body = entry.code.explanation();
721            assert!(
722                !body.trim().is_empty(),
723                "diagnostic code {} has an empty explanation file",
724                entry.identifier
725            );
726            assert!(
727                body.contains(entry.identifier),
728                "explanation for {} should reference its identifier",
729                entry.identifier
730            );
731        }
732    }
733
734    #[test]
735    fn related_codes_are_registered_and_non_self() {
736        for entry in Code::registry() {
737            for &other in entry.code.related() {
738                assert_ne!(
739                    other, entry.code,
740                    "{} lists itself as a related code",
741                    entry.identifier
742                );
743                assert!(
744                    Code::registry().iter().any(|e| e.code == other),
745                    "{} lists unregistered related code {}",
746                    entry.identifier,
747                    other
748                );
749            }
750        }
751    }
752
753    #[test]
754    fn repair_safety_string_roundtrip() {
755        for safety in RepairSafety::ALL {
756            let parsed = RepairSafety::from_str(safety.as_str()).unwrap();
757            assert_eq!(parsed, *safety);
758            assert_eq!(parsed.to_string(), safety.as_str());
759        }
760        assert_eq!(
761            RepairSafety::from_str("not-a-safety-class"),
762            Err(ParseRepairSafetyError)
763        );
764    }
765
766    #[test]
767    fn repair_safety_ordering_is_monotonic_low_to_high() {
768        // The is_at_most ceiling check relies on this ordering being
769        // least-to-most disruptive; a regression here flips the meaning
770        // of `harn fix --safety <ceiling>` for every caller.
771        let order = RepairSafety::ALL;
772        for window in order.windows(2) {
773            assert!(
774                window[0] < window[1],
775                "{:?} should be safer than {:?}",
776                window[0],
777                window[1]
778            );
779            assert!(window[0].is_at_most(window[1]));
780            assert!(!window[1].is_at_most(window[0]));
781        }
782    }
783
784    #[test]
785    fn repair_registry_has_at_least_twenty_entries() {
786        assert!(
787            REPAIR_REGISTRY.len() >= 20,
788            "expected ≥20 repair templates, found {}",
789            REPAIR_REGISTRY.len()
790        );
791    }
792
793    #[test]
794    fn repair_ids_are_kebab_case_namespaced_and_unique() {
795        let mut seen = HashSet::new();
796        for template in REPAIR_REGISTRY {
797            assert!(
798                seen.insert(template.id),
799                "duplicate repair id {}",
800                template.id
801            );
802            let (namespace, leaf) = template.id.split_once('/').unwrap_or_else(|| {
803                panic!(
804                    "repair id `{}` is missing `<namespace>/` prefix",
805                    template.id
806                )
807            });
808            assert!(
809                !namespace.is_empty() && !leaf.is_empty(),
810                "repair id `{}` has empty namespace or leaf",
811                template.id
812            );
813            for ch in template.id.chars() {
814                assert!(
815                    ch.is_ascii_lowercase() || ch.is_ascii_digit() || ch == '-' || ch == '/',
816                    "repair id `{}` has non-kebab character {ch:?}",
817                    template.id
818                );
819            }
820            assert!(
821                !template.summary.is_empty(),
822                "repair {} has empty summary",
823                template.id
824            );
825            // Summaries are imperative: start with a capital ASCII letter.
826            let first = template.summary.chars().next().unwrap();
827            assert!(
828                first.is_ascii_uppercase(),
829                "repair {} summary `{}` should start with a capital",
830                template.id,
831                template.summary
832            );
833        }
834    }
835
836    #[test]
837    fn manual_namespace_is_needs_human() {
838        for template in REPAIR_REGISTRY {
839            if let Some(("manual", _)) = template.id.split_once('/') {
840                assert_eq!(
841                    template.safety,
842                    RepairSafety::NeedsHuman,
843                    "manual/* repair {} must be NeedsHuman",
844                    template.id
845                );
846            }
847        }
848    }
849
850    #[test]
851    fn known_codes_carry_expected_safety_class() {
852        // Spot-check: the autonomy contract for several representative
853        // diagnostics. Lock in the safety class so cross-repo agents that
854        // dispatch on these don't silently drift when the catalog moves.
855        let expected: &[(Code, RepairSafety, &str)] = &[
856            (
857                Code::FormatterWouldReformat,
858                RepairSafety::FormatOnly,
859                "format/reformat",
860            ),
861            (
862                Code::ModuleImportUnused,
863                RepairSafety::BehaviorPreserving,
864                "imports/remove-unused",
865            ),
866            (
867                Code::ImmutableAssignment,
868                RepairSafety::ScopeLocal,
869                "bindings/make-mutable",
870            ),
871            (
872                Code::LintUnusedFunction,
873                RepairSafety::SurfaceChanging,
874                "declarations/remove-unused",
875            ),
876            (
877                Code::LlmProviderIdentityBranch,
878                RepairSafety::CapabilityChanging,
879                "llm/use-capability-flag",
880            ),
881            (
882                Code::PromptVariantExplosion,
883                RepairSafety::NeedsHuman,
884                "manual/needs-human",
885            ),
886            (
887                Code::NonExhaustiveMatch,
888                RepairSafety::ScopeLocal,
889                "match/add-missing-arms",
890            ),
891            (
892                Code::LintAmbientClockBuiltin,
893                RepairSafety::ScopeLocal,
894                "bindings/thread-harness-clock",
895            ),
896            (
897                Code::LintAmbientStdioBuiltin,
898                RepairSafety::ScopeLocal,
899                "bindings/thread-harness",
900            ),
901            (
902                Code::InvalidMainSignature,
903                RepairSafety::SurfaceChanging,
904                "bindings/thread-harness-needs-param",
905            ),
906        ];
907        for (code, safety, repair_id) in expected {
908            let template = code
909                .repair_template()
910                .unwrap_or_else(|| panic!("{code} should have a repair template"));
911            assert_eq!(template.safety, *safety, "{code} safety class drifted");
912            assert_eq!(template.id, *repair_id, "{code} repair id drifted");
913        }
914    }
915
916    #[test]
917    fn repair_templates_cover_at_least_twenty_codes() {
918        let covered = Code::ALL
919            .iter()
920            .filter(|code| code.repair_template().is_some())
921            .count();
922        assert!(
923            covered >= 20,
924            "expected ≥20 codes with a repair template, found {covered}"
925        );
926    }
927
928    #[test]
929    fn every_registered_repair_is_referenced_by_some_code() {
930        let referenced: HashSet<&'static str> = Code::ALL
931            .iter()
932            .filter_map(|code| code.repair_template())
933            .map(|template| template.id)
934            .collect();
935        for template in REPAIR_REGISTRY {
936            assert!(
937                referenced.contains(template.id),
938                "repair {} is in REPAIR_REGISTRY but no Code maps to it",
939                template.id
940            );
941        }
942    }
943
944    #[test]
945    fn every_referenced_repair_template_is_in_registry() {
946        let registered: HashSet<&'static str> =
947            REPAIR_REGISTRY.iter().map(|template| template.id).collect();
948        for code in Code::ALL {
949            let Some(template) = code.repair_template() else {
950                continue;
951            };
952            assert!(
953                registered.contains(template.id),
954                "repair {} (used by {}) is missing from REPAIR_REGISTRY",
955                template.id,
956                code
957            );
958        }
959    }
960}