heal-cli 0.3.1

Hook-driven Evaluation & Autonomous Loop — code-health harness CLI for AI coding agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
use std::path::PathBuf;

use anyhow::Result;
use clap::{Parser, Subcommand};

use crate::commands;

#[derive(Debug, Parser)]
#[command(name = "heal", version, about = "Code health hook-driven harness", long_about = None)]
pub struct Cli {
    /// Project root (defaults to the current directory).
    #[arg(long, global = true)]
    pub project: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Command,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Initialize `.heal/` and install hooks.
    Init {
        /// Overwrite an existing config.toml.
        #[arg(long)]
        force: bool,
        /// Assume "yes" for the Claude-skills install prompt
        /// (extracts the bundled plugin without asking).
        #[arg(long, short = 'y', conflicts_with = "no_skills")]
        yes: bool,
        /// Skip the Claude-skills install prompt entirely. Use when you
        /// don't have Claude Code installed, or for CI invocations.
        #[arg(long)]
        no_skills: bool,
        /// Emit a machine-readable JSON summary of the init outcome
        /// instead of the human-readable text. Stable contract for
        /// scripts and the `heal-config` skill.
        #[arg(long)]
        json: bool,
    },
    /// Hook entrypoint invoked by git hooks and Claude Code's
    /// `settings.json` hook commands. No-ops silently when the project
    /// has no `.heal/` directory.
    Hook {
        #[command(subcommand)]
        event: HookEvent,
    },
    /// Per-metric summary recomputed on every invocation. No history,
    /// no delta — `(commit, config, calibration)` determines the output.
    Metrics {
        #[arg(long)]
        json: bool,
        /// Restrict output to a single metric. Used by the
        /// `/heal-code-review` skill under `.claude/skills/` when
        /// narrowing focus.
        #[arg(long, value_enum)]
        metric: Option<MetricKind>,
        /// Restrict every observer to files under `<path>` (relative
        /// to the project root). Matches the `[[project.workspaces]]`
        /// path of one declared workspace; segment-wise prefix so
        /// `pkg/web` does not match `pkg/webapp`. Each observer scopes
        /// itself: Loc walks only that sub-tree, walk-based observers
        /// drop out-of-workspace files, and git-based observers
        /// recompute `commits_considered` against the in-workspace
        /// universe so lift / churn totals stay consistent.
        #[arg(long, value_name = "PATH")]
        workspace: Option<std::path::PathBuf>,
        /// Skip the pager and write directly to stdout. By default
        /// `heal metrics` pipes through `$PAGER` (or `less`) when
        /// stdout is a terminal. Has no effect with `--json` or when
        /// stdout is not a terminal.
        #[arg(long)]
        no_pager: bool,
    },
    /// Render the cached `FindingsRecord` from `.heal/findings/latest.json`
    /// — Critical / High view by default. Runs a fresh scan only when
    /// the cache is missing; pass `--refresh` to force a rescan and
    /// overwrite the cache. The single source of truth that
    /// `/heal-code-patch` (Claude side) and `heal diff` consume.
    Status(StatusArgs),
    /// Diff the current findings against a cached `FindingsRecord` whose
    /// `head_sha` matches the resolved git ref. Default ref is the
    /// calibration baseline (`meta.calibrated_at_sha`), falling back to
    /// `HEAD` when none is recorded. Outputs Resolved / Regressed /
    /// Improved / New / Unchanged buckets — like `git diff`, but for
    /// the TODO list.
    Diff(DiffArgs),
    /// Skill-driven per-finding state recorder. `mark fix` is called
    /// by `/heal-code-patch` after each fix commit; `mark accept` is
    /// called by `/heal-code-review` to record an intrinsic finding
    /// the team has decided not to refactor. Hidden from `--help`
    /// because no human invokes these directly — surfacing them
    /// invites running them outside the surrounding workflow that
    /// gives the entry meaning (a commit for `fix`, a documented
    /// `reason` for `accept`).
    #[command(hide = true)]
    Mark {
        #[command(subcommand)]
        action: MarkAction,
    },
    /// Deprecated alias for `heal mark fix`. Kept hidden so
    /// `/heal-code-patch` skill bundles from earlier HEAL versions
    /// keep working; emits a one-line stderr deprecation warning
    /// pointing users to `heal skills update`.
    #[command(hide = true, name = "mark-fixed")]
    MarkFixed {
        #[arg(long, value_name = "ID")]
        finding_id: String,
        #[arg(long, value_name = "SHA")]
        commit_sha: String,
        #[arg(long)]
        json: bool,
    },
    /// Manage the bundled Claude skill set under `.claude/skills/`.
    Skills {
        #[command(subcommand)]
        action: SkillsAction,
    },
    /// Calibrate codebase-relative Severity thresholds. Default
    /// behaviour:
    ///   * `calibration.toml` missing → run a fresh scan and write it.
    ///   * `calibration.toml` present → print the freshness summary and
    ///     surface `--force` as the way to refresh. The `heal-config`
    ///     skill is responsible for deciding when to suggest a
    ///     recalibration; HEAL itself never auto-fires.
    Calibrate {
        /// Force a fresh scan and overwrite `.heal/calibration.toml`
        /// even when one already exists.
        #[arg(long)]
        force: bool,
        /// Emit a JSON summary instead of the human-readable text.
        /// Stable contract for the `heal-config` skill and CI scripts.
        #[arg(long)]
        json: bool,
    },
}

/// Metric filter for `heal metrics --metric`. clap renders these in
/// kebab-case for the CLI flag (e.g. `--metric change-coupling`), and
/// [`Self::json_key`] returns the `snake_case` form that matches the
/// JSON object key under which the same metric's data is keyed
/// (`change_coupling`). The two forms are deliberately distinct: the
/// CLI follows shell convention, the JSON follows the rest of the
/// payload's `snake_case` keys, so a skill can do `payload[payload.metric]`
/// without translation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum MetricKind {
    Loc,
    Complexity,
    Churn,
    ChangeCoupling,
    Duplication,
    Hotspot,
    Lcom,
}

impl MetricKind {
    /// JSON object key matching this metric's data section. Identical
    /// to the field names used in `MetricsConfig` so skills can index
    /// `payload[payload.metric]`.
    #[must_use]
    pub fn json_key(self) -> &'static str {
        match self {
            Self::Loc => "loc",
            Self::Complexity => "complexity",
            Self::Churn => "churn",
            Self::ChangeCoupling => "change_coupling",
            Self::Duplication => "duplication",
            Self::Hotspot => "hotspot",
            Self::Lcom => "lcom",
        }
    }
}

/// Filter for `heal status --metric`. Distinct from [`MetricKind`]
/// because `complexity` here is an alias that selects both `ccn` and
/// `cognitive` findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum FindingMetric {
    Ccn,
    Cognitive,
    /// CCN + Cognitive together.
    Complexity,
    Duplication,
    /// `change_coupling` symmetric pairs.
    Coupling,
    Hotspot,
    /// `lcom` — class-level Lack of Cohesion of Methods.
    Lcom,
}

impl FindingMetric {
    /// Does a `Finding.metric` string belong to this filter? Used by
    /// the renderer when narrowing the displayed list.
    #[must_use]
    pub fn matches(self, metric: &str) -> bool {
        match self {
            Self::Ccn => metric == "ccn",
            Self::Cognitive => metric == "cognitive",
            Self::Complexity => matches!(metric, "ccn" | "cognitive"),
            Self::Duplication => metric == "duplication",
            Self::Coupling => matches!(metric, "change_coupling" | "change_coupling.symmetric"),
            Self::Hotspot => metric == "hotspot",
            Self::Lcom => metric == "lcom",
        }
    }
}

/// CLI-side mirror of [`crate::core::severity::Severity`] so clap's
/// `value_enum` can render the four labels without leaking SGR colour
/// codes into the help text.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum SeverityFilter {
    Critical,
    High,
    Medium,
    Ok,
}

impl SeverityFilter {
    #[must_use]
    pub fn into_severity(self) -> crate::core::severity::Severity {
        use crate::core::severity::Severity;
        match self {
            Self::Critical => Severity::Critical,
            Self::High => Severity::High,
            Self::Medium => Severity::Medium,
            Self::Ok => Severity::Ok,
        }
    }
}

#[derive(Debug, Clone, Copy, Subcommand)]
pub enum HookEvent {
    /// Post-commit hook (git).
    Commit,
    /// Claude Code PostToolUse(Edit|Write|MultiEdit) hook. No-op kept
    /// for back-compat with stale `settings.json` registrations.
    Edit,
    /// Claude Code Stop hook. No-op kept for back-compat with stale
    /// `settings.json` registrations.
    Stop,
}

#[derive(Debug, clap::Args)]
#[allow(clippy::struct_excessive_bools)] // every flag is independent CLI surface
pub struct StatusArgs {
    /// Restrict the rendered list to one metric (or one metric family —
    /// `complexity` covers both CCN and Cognitive).
    #[arg(long, value_enum)]
    pub metric: Option<FindingMetric>,
    /// Restrict to findings inside one declared
    /// `[[project.workspaces]]` entry. The value is the workspace's
    /// `path` (the same string `Finding.workspace` carries).
    #[arg(long, value_name = "PATH")]
    pub workspace: Option<String>,
    /// Restrict to findings under a path prefix (e.g.
    /// `--feature src/payments`). Matched against `Finding.location.file`.
    #[arg(long)]
    pub feature: Option<String>,
    /// Severity floor — show only this level. Combine with `--all` to
    /// also surface lower severities below it.
    #[arg(long, value_enum)]
    pub severity: Option<SeverityFilter>,
    /// Show every Severity tier (Medium / Ok included) plus the
    /// low-Severity hotspot section. Without this, only Critical /
    /// High render (with a "(N) hidden — pass `--all`" footer when
    /// there are more).
    #[arg(long)]
    pub all: bool,
    /// Emit the `FindingsRecord` payload as JSON on stdout. Same shape as
    /// `.heal/findings/latest.json` — stable contract for skills and CI.
    #[arg(long)]
    pub json: bool,
    /// Re-scan the project and overwrite `.heal/findings/latest.json`
    /// instead of reading the cached record. Without this, a present
    /// cache is reused as-is; only a missing cache triggers a scan.
    #[arg(long)]
    pub refresh: bool,
    /// Cap each Severity bucket at the N worst findings.
    #[arg(long, value_name = "N")]
    pub top: Option<usize>,
    /// Skip the pager and write directly to stdout. By default
    /// `heal status` pipes through `$PAGER` (or `less`) when stdout
    /// is a terminal — same convention as `git diff` / `git log`.
    /// Has no effect with `--json` or when stdout is not a terminal.
    #[arg(long)]
    pub no_pager: bool,
}

/// Args for `heal diff`. The positional `revspec` accepts anything
/// `git rev-parse` understands — `main`, `v0.2.1`, `HEAD~3`, or a
/// partial / full SHA. When omitted, defaults to the calibration
/// baseline SHA (recorded by `heal init` / `heal calibrate --force`),
/// falling back to `HEAD` when no baseline is recorded.
#[derive(Debug, clap::Args)]
pub struct DiffArgs {
    /// Git revision to diff against. Resolves against the local repo;
    /// the matching `FindingsRecord` must already exist in
    /// `.heal/findings/`. Omit to diff against the calibration
    /// baseline.
    #[arg(value_name = "GIT_REF")]
    pub revspec: Option<String>,
    /// Restrict to findings inside one declared
    /// `[[project.workspaces]]` entry. The value is the workspace's
    /// `path` (the same string `Finding.workspace` carries).
    #[arg(long, value_name = "PATH")]
    pub workspace: Option<String>,
    /// Show the Improved / Unchanged buckets in addition to Resolved /
    /// Regressed / New. (Distinct from `heal status --all`, which
    /// surfaces lower Severity tiers; this flag has no effect on
    /// Severity filtering.)
    #[arg(long)]
    pub all: bool,
    /// Emit the diff as JSON on stdout. Stable contract for skills.
    #[arg(long)]
    pub json: bool,
    /// Skip the pager and write directly to stdout. By default
    /// `heal diff` pipes through `$PAGER` (or `less`) when stdout is
    /// a terminal. Has no effect with `--json` or when stdout is not
    /// a terminal.
    #[arg(long)]
    pub no_pager: bool,
}

#[derive(Debug, Clone, Subcommand)]
pub enum MarkAction {
    /// Record a finding as resolved by a commit — used by
    /// `/heal-code-patch` after each fix commit so the next
    /// `heal status --refresh` either retires the entry (genuinely
    /// fixed) or moves it to `regressed.jsonl` (re-detected).
    Fix {
        /// `Finding.id` from `heal status --json` output.
        #[arg(long, value_name = "ID")]
        finding_id: String,
        /// SHA of the commit that resolved the finding.
        #[arg(long, value_name = "SHA")]
        commit_sha: String,
        /// Emit a JSON summary of the recorded fix entry.
        #[arg(long)]
        json: bool,
    },
    /// Record a finding as accepted (won't fix / acknowledged
    /// intrinsic) — used by `/heal-code-review` once the triage
    /// concludes the finding is intrinsic complexity / a cohesive
    /// procedural block / a load-bearing boundary. Snapshots the
    /// finding's severity, hotspot, `metric_value`, and summary at
    /// accept time so later auditors can revisit the decision.
    Accept {
        /// `Finding.id` from `heal status --json` output.
        #[arg(long, value_name = "ID")]
        finding_id: String,
        /// Free-form rationale. Empty string is allowed (the AI
        /// agent driving this command is expected to fill it).
        #[arg(long, value_name = "TEXT", default_value = "")]
        reason: String,
        /// Emit a JSON summary of the recorded accept entry.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Debug, Clone, Copy, Subcommand)]
pub enum SkillsAction {
    /// Extract the bundled skills into `<project>/.claude/skills/` and
    /// merge HEAL's hook commands into `<project>/.claude/settings.json`.
    Install {
        /// Overwrite existing skill files even if they were edited locally.
        #[arg(long)]
        force: bool,
        /// Emit a JSON summary of the install outcome.
        #[arg(long)]
        json: bool,
    },
    /// Refresh skill files after a binary upgrade. Skips files the user
    /// has edited locally; pass `--force` to overwrite them too.
    Update {
        #[arg(long)]
        force: bool,
        /// Emit a JSON summary of the update outcome.
        #[arg(long)]
        json: bool,
    },
    /// Show installed skill version, bundled version, and any drift.
    Status {
        /// Emit a JSON view of the install status (versions, drift list).
        #[arg(long)]
        json: bool,
    },
    /// Remove HEAL's skills from `.claude/skills/` and its hook
    /// commands from `.claude/settings.json`.
    Uninstall {
        /// Emit a JSON summary of what was removed.
        #[arg(long)]
        json: bool,
    },
}

impl Cli {
    pub fn run(self) -> Result<()> {
        let project = self
            .project
            .unwrap_or_else(|| std::env::current_dir().expect("cwd"));
        match self.command {
            Command::Init {
                force,
                yes,
                no_skills,
                json,
            } => commands::init::run(&project, force, yes, no_skills, json),
            Command::Hook { event } => commands::hook::run(&project, event),
            Command::Metrics {
                json,
                metric,
                workspace,
                no_pager,
            } => commands::metrics::run(&project, json, metric, workspace.as_deref(), no_pager),
            Command::Status(args) => commands::status::run(&project, &args),
            Command::Diff(args) => commands::diff::run(
                &project,
                args.revspec.as_deref(),
                args.workspace.as_deref(),
                args.all,
                args.json,
                args.no_pager,
            ),
            Command::Mark { action } => match action {
                MarkAction::Fix {
                    finding_id,
                    commit_sha,
                    json,
                } => commands::mark::run_fix(&project, &finding_id, &commit_sha, json),
                MarkAction::Accept {
                    finding_id,
                    reason,
                    json,
                } => commands::mark::run_accept(&project, &finding_id, &reason, json),
            },
            Command::MarkFixed {
                finding_id,
                commit_sha,
                json,
            } => commands::mark::run_fix_legacy(&project, &finding_id, &commit_sha, json),
            Command::Skills { action } => commands::skills::run(&project, action),
            Command::Calibrate { force, json } => commands::calibrate::run(&project, force, json),
        }
    }
}