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