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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
use std::path::PathBuf;
use anyhow::Result;
use clap::{Parser, Subcommand};
use crate::commands;
use crate::core::finding::Finding;
use crate::skill_assets::TargetFilter;
#[derive(Debug, Parser)]
#[command(name = "heal", version, about = "Code health hook-driven harness", long_about = None)]
pub struct Cli {
/// Project root. Defaults to the nearest ancestor of the current
/// directory containing a `.heal/config.toml`, falling back to the
/// current directory when none qualifies (so `heal init` on a
/// fresh project still creates `.heal/` in place).
#[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-setup` skill.
#[arg(long)]
json: bool,
/// Write every config key — including the defaults the
/// loader would have applied anyway — to `.heal/config.toml`.
/// Helpful for discoverability ("which knobs exist?") at the
/// cost of a much longer file. Without this flag, `heal init`
/// emits the minimal form that contains only the values the
/// team has customized.
#[arg(long)]
explicit: 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 output to one metric family (`code` / `test` /
/// `docs`). Used by `/heal-code-review`,
/// `/heal-test-review`, and `/heal-doc-review` to scope each
/// review to its own family without enumerating every metric
/// inside it. Combine with `--metric` to narrow further.
#[arg(long, value_enum)]
feature: Option<FamilyFilter>,
/// 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 skill set across every agent target
/// (Claude → `.claude/skills/`, Codex → `.agents/skills/`). Each
/// subcommand takes `--target <detected|claude|codex|all>`.
Skills {
#[command(subcommand)]
action: SkillsAction,
},
/// Calibrate codebase-relative Severity thresholds. Default
/// behavior:
/// * `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-setup`
/// 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-setup` 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,
/// `[features.docs]` — src commits since paired doc last changed.
DocFreshness,
/// `[features.docs]` — Type 1 dangling identifier mentions in
/// docs whose paired src no longer defines them.
DocDrift,
/// `[features.docs]` — pairs whose `doc` no longer exists on disk.
DocCoverage,
/// `[features.docs]` — broken internal links across docs.
DocLinkHealth,
/// `[features.docs]` — Layer B docs not linked from anywhere.
OrphanPages,
/// `[features.docs]` — TODO/FIXME/XXX marker density per doc.
TodoDensity,
/// `[features.test.coverage]` — line coverage per source file,
/// ingested from an externally-generated lcov.info file.
CoveragePct,
/// `[features.test]` — skipped-test ratio per test file. Detected
/// via tree-sitter walking of language-specific markers
/// (`#[ignore]`, `it.skip`, `t.Skip()`, `@pytest.mark.skip`,
/// `ScalaTest` `ignore`).
SkipRatio,
/// `[features.test]` — per-src-file `commits × uncov_pct`
/// composite. Test-family analogue of code Hotspot.
TestHotspot,
/// `[features.docs]` — per-pair `paired_src_churn × debt`
/// composite. Docs-family analogue of code Hotspot.
DocHotspot,
}
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",
Self::DocFreshness => "doc_freshness",
Self::DocDrift => "doc_drift",
Self::DocCoverage => "doc_coverage",
Self::DocLinkHealth => "doc_link_health",
Self::OrphanPages => "orphan_pages",
Self::TodoDensity => "todo_density",
Self::CoveragePct => "coverage_pct",
Self::SkipRatio => Finding::METRIC_SKIP_RATIO,
Self::TestHotspot => Finding::METRIC_TEST_HOTSPOT,
Self::DocHotspot => Finding::METRIC_DOC_HOTSPOT,
}
}
}
/// 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,
/// `[features.docs]` — src commits past the paired doc.
DocFreshness,
/// `[features.docs]` — dangling identifier mentions.
DocDrift,
/// `[features.docs]` — paired docs missing from disk.
DocCoverage,
/// `[features.docs]` — broken internal links.
DocLinkHealth,
/// `[features.docs]` — orphan Layer B docs.
OrphanPages,
/// `[features.docs]` — TODO marker density per doc.
TodoDensity,
/// `[features.test.coverage]` — line coverage per source file.
CoveragePct,
/// `[features.test]` — skipped-test ratio per test file.
SkipRatio,
/// `[features.test]` — per-src-file `commits × uncov_pct`
/// composite. Test-family analogue of code Hotspot.
TestHotspot,
/// `[features.docs]` — per-pair `paired_src_churn × debt`
/// composite. Docs-family analogue of code Hotspot.
DocHotspot,
}
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,
Finding::METRIC_CHANGE_COUPLING
| Finding::METRIC_CHANGE_COUPLING_SYMMETRIC
| Finding::METRIC_CHANGE_COUPLING_DRIFT
),
Self::Hotspot => metric == "hotspot",
Self::Lcom => metric == "lcom",
Self::DocFreshness => metric == "doc_freshness",
Self::DocDrift => metric == "doc_drift",
Self::DocCoverage => metric == "doc_coverage",
Self::DocLinkHealth => metric == "doc_link_health",
Self::OrphanPages => metric == "orphan_pages",
Self::TodoDensity => metric == "todo_density",
Self::CoveragePct => metric == "coverage_pct",
Self::SkipRatio => metric == Finding::METRIC_SKIP_RATIO,
Self::TestHotspot => metric == Finding::METRIC_TEST_HOTSPOT,
Self::DocHotspot => metric == Finding::METRIC_DOC_HOTSPOT,
}
}
}
/// CLI-side mirror of [`crate::core::severity::Severity`] so clap's
/// `value_enum` can render the four labels without leaking SGR color
/// 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,
}
}
}
/// CLI-side mirror of [`crate::feature::Family`]. clap renders these
/// in kebab-case (`code` / `test` / `docs`) for `--feature`. Lives
/// here rather than on `Family` itself so the lib stays clap-free.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum FamilyFilter {
Code,
Test,
Docs,
}
impl FamilyFilter {
#[must_use]
pub fn as_family(self) -> crate::feature::Family {
use crate::feature::Family;
match self {
Self::Code => Family::Code,
Self::Test => Family::Test,
Self::Docs => Family::Docs,
}
}
}
#[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.
/// `--path src/payments`). Matched against `Finding.location.file`.
/// Renamed from `--feature` in v0.4 — that flag now selects a
/// metric family (`code` / `test` / `docs`).
#[arg(long)]
pub path: Option<String>,
/// Restrict to findings in one metric family. `code` covers the
/// always-on observers (`ccn`, `cognitive`, `change_coupling`,
/// `duplication`, `hotspot`, `lcom`); `test` covers `[features.test]`
/// (`coverage_pct`, `skip_ratio`, `test_hotspot`); `docs` covers
/// `[features.docs]` (`doc_freshness`, `doc_drift`, `doc_coverage`,
/// `doc_link_health`, `orphan_pages`, `todo_density`,
/// `doc_hotspot`).
#[arg(long, value_enum)]
pub feature: Option<FamilyFilter>,
/// 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, and surface entries whose `from`/`to` sit
/// below High. Without this, the human renderer hides entries
/// where neither side is Critical or High and prints a "(N)
/// hidden — pass --all" footer; the JSON output is unaffected.
#[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 each target's discovery path
/// (Claude → `.claude/skills/`, Codex → `.agents/skills/`) and
/// sweep legacy hook entries from `.claude/settings.json` if the
/// Claude target is in scope.
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,
/// Which agent target(s) to operate on. Default `detected`
/// matches `heal init` (every CLI on `PATH`); `all` operates
/// on every known target regardless of detection.
#[arg(long, value_enum, default_value_t = TargetFilter::Detected)]
target: TargetFilter,
},
/// 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,
#[arg(long, value_enum, default_value_t = TargetFilter::Detected)]
target: TargetFilter,
},
/// Show installed skill version, bundled version, and any drift —
/// per agent target.
Status {
/// Emit a JSON view of the install status (versions, drift list).
#[arg(long)]
json: bool,
#[arg(long, value_enum, default_value_t = TargetFilter::Detected)]
target: TargetFilter,
},
/// Remove HEAL's skills from each target's tree (and Claude
/// settings when the Claude target is in scope).
Uninstall {
/// Emit a JSON summary of what was removed.
#[arg(long)]
json: bool,
#[arg(long, value_enum, default_value_t = TargetFilter::Detected)]
target: TargetFilter,
},
}
impl Cli {
pub fn run(self) -> Result<()> {
let project = self.project.unwrap_or_else(|| {
let cwd = std::env::current_dir().expect("cwd");
crate::core::paths::find_project_root(&cwd)
});
match self.command {
Command::Init {
force,
yes,
no_skills,
json,
explicit,
} => commands::init::run(&project, force, yes, no_skills, json, explicit),
Command::Hook { event } => commands::hook::run(&project, event),
Command::Metrics {
json,
metric,
feature,
workspace,
no_pager,
} => commands::metrics::run(
&project,
json,
metric,
feature.map(FamilyFilter::as_family),
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),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use clap::CommandFactory;
fn parse(args: &[&str]) -> Cli {
Cli::try_parse_from(args).unwrap_or_else(|e| panic!("parse failed for {args:?}: {e}"))
}
#[test]
fn clap_derive_is_internally_consistent() {
// clap's debug_assert path catches arg-name collisions, missing
// value names, and conflicting flag definitions at startup.
// Run it here so a derive regression surfaces in unit tests
// instead of at first user invocation.
Cli::command().debug_assert();
}
#[test]
fn parses_init_with_every_flag() {
let cli = parse(&["heal", "init", "--force", "--yes", "--json", "--explicit"]);
match cli.command {
Command::Init {
force,
yes,
no_skills,
json,
explicit,
} => {
assert!(force);
assert!(yes);
assert!(!no_skills);
assert!(json);
assert!(explicit);
}
other => panic!("expected Init, got {other:?}"),
}
}
#[test]
fn init_yes_and_no_skills_conflict() {
let err =
Cli::try_parse_from(["heal", "init", "--yes", "--no-skills"]).expect_err("conflict");
assert!(
err.to_string().contains("cannot be used with"),
"expected conflict error, got: {err}",
);
}
#[test]
fn parses_global_project_flag_before_subcommand() {
let cli = parse(&["heal", "--project", "/tmp/foo", "metrics"]);
assert_eq!(
cli.project.as_deref(),
Some(std::path::Path::new("/tmp/foo"))
);
assert!(matches!(cli.command, Command::Metrics { .. }));
}
#[test]
fn parses_metrics_with_kebab_metric_and_feature() {
let cli = parse(&[
"heal",
"metrics",
"--json",
"--metric",
"change-coupling",
"--feature",
"code",
"--workspace",
"crates/cli",
"--no-pager",
]);
match cli.command {
Command::Metrics {
json,
metric,
feature,
workspace,
no_pager,
} => {
assert!(json);
assert_eq!(metric, Some(MetricKind::ChangeCoupling));
assert_eq!(feature, Some(FamilyFilter::Code));
assert_eq!(
workspace.as_deref(),
Some(std::path::Path::new("crates/cli"))
);
assert!(no_pager);
}
other => panic!("expected Metrics, got {other:?}"),
}
}
#[test]
fn metric_kebab_to_json_key_round_trip() {
// Every CLI-facing kebab form must map to its JSON snake_case
// counterpart via `MetricKind::json_key`. This is the contract
// skills rely on for `payload[payload.metric]`.
let cases = [
("loc", "loc"),
("complexity", "complexity"),
("churn", "churn"),
("change-coupling", "change_coupling"),
("duplication", "duplication"),
("hotspot", "hotspot"),
("lcom", "lcom"),
("doc-freshness", "doc_freshness"),
("doc-drift", "doc_drift"),
("doc-coverage", "doc_coverage"),
("doc-link-health", "doc_link_health"),
("orphan-pages", "orphan_pages"),
("todo-density", "todo_density"),
("coverage-pct", "coverage_pct"),
("skip-ratio", "skip_ratio"),
("test-hotspot", "test_hotspot"),
("doc-hotspot", "doc_hotspot"),
];
for (kebab, json_key) in cases {
let cli = parse(&["heal", "metrics", "--metric", kebab]);
let parsed_metric = match cli.command {
Command::Metrics { metric, .. } => metric.expect("metric flag set"),
other => panic!("expected Metrics, got {other:?}"),
};
assert_eq!(
parsed_metric.json_key(),
json_key,
"`--metric {kebab}` must round-trip to JSON key `{json_key}`",
);
}
}
#[test]
fn family_filter_round_trips_through_as_family() {
// The CLI mirrors `crate::feature::Family` via `FamilyFilter` so
// the lib stays clap-free. Both layers must agree on each name.
for (kebab, expected) in [
("code", crate::feature::Family::Code),
("test", crate::feature::Family::Test),
("docs", crate::feature::Family::Docs),
] {
let cli = parse(&["heal", "metrics", "--feature", kebab]);
let parsed_feature = match cli.command {
Command::Metrics { feature, .. } => feature.expect("feature flag set"),
other => panic!("expected Metrics, got {other:?}"),
};
assert_eq!(parsed_feature.as_family(), expected);
}
}
#[test]
fn parses_status_with_every_flag() {
let cli = parse(&[
"heal",
"status",
"--metric",
"ccn",
"--workspace",
"crates/foo",
"--path",
"src/payments",
"--feature",
"code",
"--severity",
"critical",
"--all",
"--json",
"--refresh",
"--top",
"5",
"--no-pager",
]);
match cli.command {
Command::Status(args) => {
assert_eq!(args.metric, Some(FindingMetric::Ccn));
assert_eq!(args.workspace.as_deref(), Some("crates/foo"));
assert_eq!(args.path.as_deref(), Some("src/payments"));
assert_eq!(args.feature, Some(FamilyFilter::Code));
assert_eq!(args.severity, Some(SeverityFilter::Critical));
assert!(args.all);
assert!(args.json);
assert!(args.refresh);
assert_eq!(args.top, Some(5));
assert!(args.no_pager);
}
other => panic!("expected Status, got {other:?}"),
}
}
#[test]
fn parses_diff_with_revspec_and_flags() {
let cli = parse(&[
"heal",
"diff",
"v0.3.0",
"--workspace",
"crates/cli",
"--all",
"--json",
"--no-pager",
]);
match cli.command {
Command::Diff(args) => {
assert_eq!(args.revspec.as_deref(), Some("v0.3.0"));
assert_eq!(args.workspace.as_deref(), Some("crates/cli"));
assert!(args.all);
assert!(args.json);
assert!(args.no_pager);
}
other => panic!("expected Diff, got {other:?}"),
}
}
#[test]
fn diff_revspec_is_optional() {
let cli = parse(&["heal", "diff"]);
match cli.command {
Command::Diff(args) => assert!(args.revspec.is_none()),
other => panic!("expected Diff, got {other:?}"),
}
}
#[test]
fn parses_hook_subcommands() {
for (arg, expected) in [
("commit", HookEvent::Commit),
("edit", HookEvent::Edit),
("stop", HookEvent::Stop),
] {
let cli = parse(&["heal", "hook", arg]);
match cli.command {
Command::Hook { event } => assert_eq!(
std::mem::discriminant(&event),
std::mem::discriminant(&expected),
"`heal hook {arg}` must dispatch to {expected:?}",
),
other => panic!("expected Hook, got {other:?}"),
}
}
}
#[test]
fn parses_mark_fix_and_accept() {
let cli = parse(&[
"heal",
"mark",
"fix",
"--finding-id",
"abc",
"--commit-sha",
"def",
"--json",
]);
match cli.command {
Command::Mark {
action:
MarkAction::Fix {
finding_id,
commit_sha,
json,
},
} => {
assert_eq!(finding_id, "abc");
assert_eq!(commit_sha, "def");
assert!(json);
}
other => panic!("expected Mark::Fix, got {other:?}"),
}
let cli = parse(&[
"heal",
"mark",
"accept",
"--finding-id",
"abc",
"--reason",
"intrinsic complexity",
]);
match cli.command {
Command::Mark {
action:
MarkAction::Accept {
finding_id,
reason,
json,
},
} => {
assert_eq!(finding_id, "abc");
assert_eq!(reason, "intrinsic complexity");
assert!(!json);
}
other => panic!("expected Mark::Accept, got {other:?}"),
}
}
#[test]
fn mark_fix_requires_finding_id_and_commit_sha() {
Cli::try_parse_from(["heal", "mark", "fix"]).expect_err("missing required args");
Cli::try_parse_from(["heal", "mark", "fix", "--finding-id", "x"])
.expect_err("missing commit-sha");
}
#[test]
fn mark_accept_reason_defaults_to_empty_string() {
let cli = parse(&["heal", "mark", "accept", "--finding-id", "abc"]);
match cli.command {
Command::Mark {
action: MarkAction::Accept { reason, .. },
} => assert_eq!(reason, ""),
other => panic!("expected Mark::Accept, got {other:?}"),
}
}
#[test]
fn parses_legacy_mark_fixed_alias() {
// The hidden `mark-fixed` alias keeps older skill bundles
// working after the rename to `mark fix`. If this regresses,
// shipped skills break silently — guard it explicitly.
let cli = parse(&[
"heal",
"mark-fixed",
"--finding-id",
"abc",
"--commit-sha",
"def",
]);
match cli.command {
Command::MarkFixed {
finding_id,
commit_sha,
json,
} => {
assert_eq!(finding_id, "abc");
assert_eq!(commit_sha, "def");
assert!(!json);
}
other => panic!("expected MarkFixed, got {other:?}"),
}
}
#[test]
fn parses_skills_subcommands() {
for action in ["install", "update", "status", "uninstall"] {
let cli = parse(&["heal", "skills", action]);
assert!(matches!(cli.command, Command::Skills { .. }));
}
// `--force` only valid on install / update; default `--target`
// resolves to `Detected`; explicit `--target` overrides.
let cli = parse(&["heal", "skills", "install", "--force", "--json"]);
match cli.command {
Command::Skills {
action:
SkillsAction::Install {
force,
json,
target,
},
} => {
assert!(force);
assert!(json);
assert_eq!(target, TargetFilter::Detected);
}
other => panic!("expected Skills::Install, got {other:?}"),
}
let cli = parse(&["heal", "skills", "install", "--target", "all"]);
match cli.command {
Command::Skills {
action: SkillsAction::Install { target, .. },
} => assert_eq!(target, TargetFilter::All),
other => panic!("expected Skills::Install, got {other:?}"),
}
let cli = parse(&["heal", "skills", "uninstall", "--target", "codex"]);
match cli.command {
Command::Skills {
action: SkillsAction::Uninstall { target, .. },
} => assert_eq!(target, TargetFilter::Codex),
other => panic!("expected Skills::Uninstall, got {other:?}"),
}
Cli::try_parse_from(["heal", "skills", "uninstall", "--force"])
.expect_err("--force not on uninstall");
}
#[test]
fn parses_calibrate_with_force_and_json() {
let cli = parse(&["heal", "calibrate", "--force", "--json"]);
match cli.command {
Command::Calibrate { force, json } => {
assert!(force);
assert!(json);
}
other => panic!("expected Calibrate, got {other:?}"),
}
}
#[test]
fn rejects_unknown_subcommand() {
Cli::try_parse_from(["heal", "do-the-thing"]).expect_err("unknown subcommand");
}
#[test]
fn rejects_unknown_metric_value() {
Cli::try_parse_from(["heal", "metrics", "--metric", "not-a-metric"])
.expect_err("unknown metric value");
}
}