@mmerterden/multi-agent-pipeline 20.42.0 → 20.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +7 -5
  3. package/README.tr.md +7 -5
  4. package/docs/architecture.md +3 -3
  5. package/docs/ecosystem.md +6 -6
  6. package/docs/facts.json +5 -5
  7. package/manifest.json +40 -33
  8. package/package.json +1 -1
  9. package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
  10. package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
  11. package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
  12. package/pipeline/lib/low-disk.mjs +6 -5
  13. package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
  14. package/pipeline/multi-agent-refs/features/doctor.md +17 -2
  15. package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
  16. package/pipeline/multi-agent-refs/features/usage-reporting.md +1 -1
  17. package/pipeline/multi-agent-refs/help/en.md +2 -0
  18. package/pipeline/multi-agent-refs/help/tr.md +2 -0
  19. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +1 -1
  20. package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
  21. package/pipeline/office/toolkit.json +1 -1
  22. package/pipeline/schemas/prefs.schema.json +19 -1
  23. package/pipeline/schemas/toolkit-path-params.json +1 -1
  24. package/pipeline/scripts/capture-resume.sh +1 -1
  25. package/pipeline/scripts/disk-cleaner.mjs +77 -63
  26. package/pipeline/scripts/doctor.mjs +140 -10
  27. package/pipeline/scripts/priority-review.mjs +912 -0
  28. package/pipeline/skills/.skill-manifest.json +12 -4
  29. package/pipeline/skills/.skills-index.json +24 -2
  30. package/pipeline/skills/shared/README.md +6 -4
  31. package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
  32. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
  33. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
  34. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +10 -4
  35. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +6 -6
  36. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +77 -63
  37. package/pipeline/skills/skills-index.md +4 -2
@@ -0,0 +1,137 @@
1
+ ---
2
+ team: Example Team
3
+ slug: example
4
+ ---
5
+
6
+ # Example Team - priority rules
7
+
8
+ <!-- toc -->
9
+ - [Jira selection](#jira-selection)
10
+ - [Priority scale](#priority-scale)
11
+ - [Rules](#rules)
12
+ <!-- /toc -->
13
+
14
+ A starting point for `/multi-agent:review-priority`. Copy this file into the
15
+ rules directory as `<your-slug>.md`, set `team` and `slug`, and replace the
16
+ Jira selection with your own. The rules below describe an impact-based
17
+ priority model and can be kept as they are. The file format is described in
18
+ `multi-agent-refs/features/review-priority.md`.
19
+
20
+ ## Jira selection
21
+
22
+ The presets below use placeholder values: a project key `EXAMPLE` and a
23
+ component `Example Component`. `environment` is a standard Jira field; add the
24
+ fields your team records evidence in (environment, root cause, application)
25
+ to `evidenceFields`, keyed by field id.
26
+
27
+ ```json jira-selection
28
+ {
29
+ "base": "issuetype = Bug",
30
+ "default": "open",
31
+ "presets": [
32
+ {"id": "open", "label": "Example Team, open bugs",
33
+ "jql": "project = EXAMPLE AND statusCategory != Done"},
34
+ {"id": "component-open", "label": "Example Component only, open bugs",
35
+ "jql": "project = EXAMPLE AND component = \"Example Component\" AND statusCategory != Done"}
36
+ ],
37
+ "order": "priority DESC, created DESC",
38
+ "evidenceFields": {
39
+ "environment": "Environment"
40
+ }
41
+ }
42
+ ```
43
+
44
+ ## Priority scale
45
+
46
+ Critical > High > Medium > Low. Priority states how much damage the defect
47
+ does to the system, a workflow, the integrity of data and the people using
48
+ it. How soon it must be fixed is urgency, a separate question answered in the
49
+ description, a label or the release plan. A value outside these four is
50
+ reported as off the scale.
51
+
52
+ ## Rules
53
+
54
+ Each row: a rule id, what it implies for the level, what to look for in the
55
+ issue, and why.
56
+
57
+ ### Principles
58
+
59
+ | Id | Implies | Look for | Why |
60
+ |---|---|---|---|
61
+ | PRI-001 | Judge technical impact only | How badly the defect hurts the system, a workflow, data or users | Impact and urgency are separate axes |
62
+ | PRI-002 | Out of scope -> `insufficient` | The record is a task, a change request, an incident or a question rather than a defect found in testing | The model grades defects, nothing else |
63
+ | PRI-003 | Never raises the level | The text argues from a close release date, management attention, visibility to end users, a large fix, a team asking to go first, or a sprint goal | These change the order of work, not the damage |
64
+ | PRI-004 | Never raises the level | A release-blocker label or the words "release blocker" | Blocking a release is recorded separately; a Medium may block a release |
65
+ | PRI-005 | Never raises the level alone | The defect was seen in production | Where it was seen does not measure how much it hurts |
66
+ | PRI-006 | High or Critical possible | A single user is affected and cannot finish the action at all | Spread is one input; a complete stop for one user still counts |
67
+ | PRI-007 | One band lower | A workaround that people can actually keep using | A workaround that only works on paper does not lower the level |
68
+ | PRI-008 | Medium or High possible | A UI defect that misleads the user into a wrong action or breaks the main flow | A visual defect is not Low by default |
69
+ | PRI-009 | Judge by the data | A small symptom on screen while the data written, shown or sent is wrong | The data impact decides, not the size of the symptom |
70
+
71
+ ### Critical
72
+
73
+ | Id | Implies | Look for | Why |
74
+ |---|---|---|---|
75
+ | PRI-010 | Critical | The system or a core flow cannot be used; the main path stops or keeps failing | Nothing of value can be done |
76
+ | PRI-011 | Critical | A core business function cannot complete: taking a payment, signing in or authenticating, creating an order or a booking | These functions are what the product exists for |
77
+ | PRI-012 | Critical | A crash, errors that do not stop, or corrupted data (wrong amounts, wrong records) | Damage spreads beyond the screen |
78
+ | PRI-013 | Critical | A security, legal or reputational exposure (a required check skipped, personal data visible) | The risk is outside the product's own walls |
79
+ | PRI-014 | Needed for Critical | No workaround that is workable and lasting, and no other way through | With a workable route the damage is contained |
80
+ | PRI-015 | Not Critical on its own | One secondary area is wrong while the product works; the user can finish another way; a narrow group with little spread | Real, but contained |
81
+
82
+ ### High
83
+
84
+ | Id | Implies | Look for | Why |
85
+ |---|---|---|---|
86
+ | PRI-020 | High | The main function can be reached but works badly; a step inside the main flow is seriously broken | The flow exists but cannot be relied on |
87
+ | PRI-021 | High | The flow completes but adds operational work, delay or a clearly worse experience | The cost is paid on every use |
88
+ | PRI-022 | High | It happens often and to many people | Frequency and reach multiply the impact |
89
+ | PRI-023 | High | A workaround exists but it is manual, complicated or cannot be kept up; an action succeeds only on a retry or by another route | The user carries the cost of the defect |
90
+ | PRI-024 | Not High on its own | Only a text or an icon is wrong; a rare validation mismatch with little effect | Too small to degrade the function |
91
+
92
+ ### Medium
93
+
94
+ | Id | Implies | Look for | Why |
95
+ |---|---|---|---|
96
+ | PRI-030 | Medium | The function works but departs from the business rules in a way that matters (a wrong message while the action continues, results in the wrong order) | Correctness suffers while the work gets done |
97
+ | PRI-031 | Medium | The flow continues with a workaround (an action that fails once and succeeds when repeated) | Annoying, recoverable |
98
+ | PRI-032 | Medium | Only under specific conditions (a region, a device, a sequence of steps) and with limited effect | Narrow and contained |
99
+ | PRI-033 | Medium | A functional effect while the system as a whole keeps working | Real impact, no breakdown |
100
+ | PRI-034 | Not Medium on its own | A spelling mistake with no functional effect | Cosmetic |
101
+
102
+ ### Low
103
+
104
+ | Id | Implies | Look for | Why |
105
+ |---|---|---|---|
106
+ | PRI-040 | Low | A visual, wording or usability finding while the action completes | The outcome is right |
107
+ | PRI-041 | Low | Design, alignment or labelling work that does not change the functional result | An improvement, not a failure |
108
+ | PRI-042 | Never Low | The user cannot complete the action, or needs a workaround to do so | That is a functional failure |
109
+
110
+ ### Decision order and evidence
111
+
112
+ | Id | Implies | Look for | Why |
113
+ |---|---|---|---|
114
+ | PRI-050 | Order of evaluation | 1. Is it really a defect, not missing data, misuse or the environment? 2. Which flow: the main one, a side one, one segment? 3. Can the flow complete? 4. Is there a workaround, and does it hold up in practice? 5. Is there data loss, money, security, regulatory or operational risk? 6. Choose the level; note urgency and release impact separately | Each answer narrows the next |
115
+ | PRI-060 | Missing items -> `insufficient` | The record should state the affected flow, the spread (everyone, a segment, a device, a channel), the real impact, the workaround if any, and the release or production risk as its own note | Without them the steps above cannot run |
116
+ | PRI-061 | Consistency | Similar earlier records were given the same level | One defect, one level, whoever files it |
117
+
118
+ ### Triage checklist
119
+
120
+ | Id | Implies | Look for | Why |
121
+ |---|---|---|---|
122
+ | PRI-080 | Ask before settling | Is it a defect? Which flow? Does it complete? Is the workaround real? What is at risk? Does a similar record exist? Is urgency written apart from the level? | The same questions every time keep levels comparable |
123
+
124
+ ### Decision matrix
125
+
126
+ | Id | Situation | Spread | Workaround | Implies |
127
+ |---|---|---|---|---|
128
+ | PRI-070 | Nobody can sign in | Everyone | None | Critical |
129
+ | PRI-071 | A payment fails on the first attempt and goes through on a retry | Wide | Yes | High |
130
+ | PRI-072 | A field is validated wrongly on some devices; the flow still completes | Limited | Not needed | Medium |
131
+ | PRI-073 | A typo or an alignment problem; the flow completes | Any | Not needed | Low |
132
+
133
+ ### Roles
134
+
135
+ | Id | Implies | Why |
136
+ |---|---|---|
137
+ | PRI-090 | The review proposes; people decide | The tester sets the first level from impact, a developer does not change it alone, product and analysis add business context, and triage keeps levels consistent. The review is input to that triage |
@@ -1,3 +1,3 @@
1
1
  {
2
- "toolkitVersion": "3.32.0"
2
+ "toolkitVersion": "3.32.1"
3
3
  }
@@ -1518,7 +1518,7 @@
1518
1518
  "diskCleaner": {
1519
1519
  "type": "object",
1520
1520
  "additionalProperties": false,
1521
- "description": "When the ecosystem suggests the disk-cleaner skill. lib/low-disk.mjs reads these with one statfs call from doctor's disk-space check, the SessionStart banner and the pre-push gate's failure path, and prints one line naming the skill. The suggestion never deletes anything.",
1521
+ "description": "When the ecosystem suggests /multi-agent:clean-disk. lib/low-disk.mjs reads these with one statfs call from doctor's disk-space check, the SessionStart banner and the pre-push gate's failure path, and prints one line naming the command. The suggestion never deletes anything.",
1522
1522
  "properties": {
1523
1523
  "lowDiskGb": {
1524
1524
  "type": "number",
@@ -1537,6 +1537,24 @@
1537
1537
  "type": "boolean",
1538
1538
  "default": true,
1539
1539
  "description": "false silences the suggestion everywhere, including after a disk-full failure."
1540
+ },
1541
+ "reclaimableGb": {
1542
+ "type": "number",
1543
+ "minimum": 0,
1544
+ "default": 10,
1545
+ "description": "doctor's disk-space check names /multi-agent:clean-disk when the newest disk-cleaner dry run (under a day old) found at least this many gigabytes to free, even with enough free space."
1546
+ }
1547
+ }
1548
+ },
1549
+ "reviewPriority": {
1550
+ "type": "object",
1551
+ "additionalProperties": false,
1552
+ "description": "Where /multi-agent:review-priority reads team rule files. scripts/priority-review.mjs reads it; run data goes to runs/ beside the rules directory.",
1553
+ "properties": {
1554
+ "rulesDir": {
1555
+ "type": "string",
1556
+ "default": "~/.claude/routine-assets/review-priority/rules",
1557
+ "description": "Directory holding one <slug>.md rule file per team. A leading ~ is the home directory. Unset means the default."
1540
1558
  }
1541
1559
  }
1542
1560
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "$comment": "Generated by pipeline/scripts/gen-toolkit-path-params.mjs from multi-agent-toolkit-mcp tool-manifest.json; do not edit. Per toolkit tool: the parameters it writes to and the filesystem paths it reads, both confined by scripts/unattended_policy.py.",
3
- "toolkitVersion": "3.32.0",
3
+ "toolkitVersion": "3.32.1",
4
4
  "tools": {
5
5
  "agent_query_output": {
6
6
  "writes": [],
@@ -18,7 +18,7 @@
18
18
  # last review, with at least one open observation.) Offer one line. The
19
19
  # user's own work is never made to wait on it.
20
20
  # - Is the disk nearly full? lib/low-disk.mjs answers with one statfs call
21
- # and, when it is, one line naming the disk-cleaner skill. Nothing is
21
+ # and, when it is, one line naming /multi-agent:clean-disk. Nothing is
22
22
  # deleted from here.
23
23
  #
24
24
  # Usage: ./capture-resume.sh [--json]
@@ -21,11 +21,13 @@
21
21
  * - never a file the user does not own, and never a path an open file
22
22
  * handle or a running command line points into
23
23
  *
24
- * Transcripts and the Trash are opt-in (--transcripts, --trash). Orphaned
25
- * session children are only reported unless --apply --processes is given.
26
- * Unattended runs (--unattended or MULTI_AGENT_UNATTENDED=1) keep to
27
- * UNATTENDED_SAFE and never touch the Trash, transcripts, processes,
28
- * worktrees, archives or device support.
24
+ * The Trash and old session transcripts are opt-in (--trash, --transcripts):
25
+ * the Trash holds the user's own files, and resume and past-session search
26
+ * read the transcripts. Processes are never stopped: orphaned children of
27
+ * ended sessions are listed in the report under `orphans` as information, and
28
+ * nothing here can signal a process. Unattended runs (--unattended or
29
+ * MULTI_AGENT_UNATTENDED=1) keep to UNATTENDED_SAFE and never touch the Trash,
30
+ * transcripts, worktrees, archives or device support.
29
31
  *
30
32
  * Deletion uses fs.rmSync, which unlinks a symlink instead of entering it.
31
33
  * Pipeline scratch under /tmp and per-task pipeline logs are delegated to
@@ -34,11 +36,18 @@
34
36
  *
35
37
  * Usage:
36
38
  * disk-cleaner.mjs [--dry-run] [--apply] [--only=a,b] [--skip=a,b]
37
- * [--trash] [--transcripts] [--processes] [--unattended]
39
+ * [--trash] [--transcripts] [--unattended]
38
40
  * [--log-days=N] [--archive-days=N] [--transcript-days=N]
39
41
  * [--scratch-hours=N] [--build-hours=N] [--orphan-minutes=N]
40
42
  * [--root=DIR]... [--tmp-root=DIR]... [--home=DIR]
41
- * [--report=FILE] [--json] [--list]
43
+ * [--report=FILE] [--json] [--list] [--top=N]
44
+ *
45
+ * Every category in the JSON report carries `top` (its largest items, real
46
+ * paths and sizes, 5 unless --top says otherwise), `more` (how many items
47
+ * `top` leaves out) and `kept` (how many items were kept, per reason). The
48
+ * report also carries `reclaimableBytes` (categories whose tool is running
49
+ * are measured but left out) and `disk.expectedFreeBytes`. --top=N also lists
50
+ * the top items under each row of the text table.
42
51
  *
43
52
  * Exit: 0 done, 1 one or more deletions failed, 2 usage error.
44
53
  *
@@ -61,11 +70,12 @@ import { homedir, tmpdir } from "node:os";
61
70
  import { basename, dirname, join, sep } from "node:path";
62
71
  import { fileURLToPath, pathToFileURL } from "node:url";
63
72
 
64
- export const VERSION = "1.0.0";
73
+ export const VERSION = "1.1.0";
65
74
  const DAY_MS = 86_400_000;
66
75
  const HOUR_MS = 3_600_000;
67
76
  const MAX_WALK_DEPTH = 8;
68
77
  const KEEP_REPORTS = 20;
78
+ const DEFAULT_TOP = 5;
69
79
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
70
80
 
71
81
  /** Folders under $HOME that hold the user's own files or secrets. */
@@ -280,7 +290,6 @@ export function makeContext(o = {}) {
280
290
  tmpGraceMinutes: o.tmpGraceMinutes ?? 120,
281
291
  orphanMinutes: o.orphanMinutes ?? 30,
282
292
  run: o.run || realRun,
283
- kill: o.kill || ((pid) => process.kill(pid, "SIGTERM")),
284
293
  du: o.du || duBytes,
285
294
  ps: () => (psCache ??= (o.ps || realPs)()),
286
295
  openPaths: () =>
@@ -706,6 +715,16 @@ function transcriptCandidates(ctx, out) {
706
715
  }
707
716
  }
708
717
 
718
+ /** Orphaned session children, for the report only: pid and command, nothing to act on. */
719
+ export function listOrphans(ctx) {
720
+ const rows = ctx.ps();
721
+ return findOrphans(rows, {
722
+ uid: ctx.uid,
723
+ minAgeSec: ctx.orphanMinutes * 60,
724
+ selfChain: selfChain(rows),
725
+ }).map((r) => ({ pid: r.pid, command: r.command }));
726
+ }
727
+
709
728
  function selfChain(rows) {
710
729
  const parent = new Map(rows.map((r) => [r.pid, r.ppid]));
711
730
  const chain = new Set();
@@ -985,27 +1004,6 @@ export const CATEGORIES = [
985
1004
  optIn: "transcripts",
986
1005
  discover: transcriptCandidates,
987
1006
  },
988
- {
989
- id: "processes",
990
- label: "orphaned children of ended Claude or Codex sessions",
991
- unattended: false,
992
- discover(ctx, out) {
993
- const rows = ctx.ps();
994
- for (const r of findOrphans(rows, {
995
- uid: ctx.uid,
996
- minAgeSec: ctx.orphanMinutes * 60,
997
- selfChain: selfChain(rows),
998
- })) {
999
- out.candidates.push({
1000
- kind: "process",
1001
- pid: r.pid,
1002
- path: `pid ${r.pid}: ${r.command}`,
1003
- command: r.command,
1004
- bytes: 0,
1005
- });
1006
- }
1007
- },
1008
- },
1009
1007
  ];
1010
1008
 
1011
1009
  export const UNATTENDED_SAFE = new Set(CATEGORIES.filter((c) => c.unattended).map((c) => c.id));
@@ -1073,19 +1071,6 @@ function removeWorktree(ctx, c) {
1073
1071
  return r.status === 0 ? { ok: true } : { ok: false, reason: r.stderr.trim() || "git refused" };
1074
1072
  }
1075
1073
 
1076
- function stopProcess(ctx, c) {
1077
- const now = ctx.ps().find((r) => r.pid === c.pid);
1078
- if (!now || now.ppid !== 1 || now.command !== c.command) {
1079
- return { ok: false, reason: "process changed or exited" };
1080
- }
1081
- try {
1082
- ctx.kill(c.pid);
1083
- return { ok: true };
1084
- } catch (e) {
1085
- return { ok: false, reason: e.code || "kill failed" };
1086
- }
1087
- }
1088
-
1089
1074
  function runDelegate(ctx, tool, items) {
1090
1075
  const listFile = join(tmpdir(), `disk-cleaner-${tool}-${process.pid}-${Date.now()}.txt`);
1091
1076
  try {
@@ -1113,12 +1098,11 @@ function runDelegate(ctx, tool, items) {
1113
1098
 
1114
1099
  /**
1115
1100
  * Delete what `planned` lists. Every path passes the guard again first, a
1116
- * worktree is re-checked for changes, and a process is re-read before it is
1117
- * signalled.
1101
+ * worktree is re-checked for changes.
1118
1102
  */
1119
- export function applyPlan(ctx, planned, opts = {}) {
1103
+ export function applyPlan(ctx, planned) {
1120
1104
  ctx.resetProbes?.();
1121
- const result = { removed: 0, failed: 0, stopped: 0, failures: [], held: [] };
1105
+ const result = { removed: 0, failed: 0, failures: [], held: [] };
1122
1106
  for (const cat of planned.categories) {
1123
1107
  const def = CATEGORIES.find((c) => c.id === cat.id);
1124
1108
  if (cat.blocked || (def?.blocker && processRunning(ctx, def.blocker[0]))) {
@@ -1133,13 +1117,6 @@ export function applyPlan(ctx, planned, opts = {}) {
1133
1117
  else if (c.kind === "command") {
1134
1118
  const x = ctx.run(c.cmd, c.args, { timeout: 600_000 });
1135
1119
  r = x.status === 0 ? { ok: true } : { ok: false, reason: `${c.cmd} exited ${x.status}` };
1136
- } else if (c.kind === "process") {
1137
- if (!opts.processes) continue;
1138
- r = stopProcess(ctx, c);
1139
- if (r.ok) {
1140
- result.stopped++;
1141
- continue;
1142
- }
1143
1120
  } else if (c.kind === "delegate") {
1144
1121
  if (!delegates.has(c.tool)) delegates.set(c.tool, []);
1145
1122
  delegates.get(c.tool).push(c);
@@ -1183,7 +1160,6 @@ function parseCli(argv) {
1183
1160
  break;
1184
1161
  case "--trash":
1185
1162
  case "--transcripts":
1186
- case "--processes":
1187
1163
  case "--unattended":
1188
1164
  case "--json":
1189
1165
  case "--list":
@@ -1211,18 +1187,21 @@ function parseCli(argv) {
1211
1187
  case "--archive-days":
1212
1188
  o.archiveDays = num(k, v);
1213
1189
  break;
1214
- case "--transcript-days":
1215
- o.transcriptDays = num(k, v);
1216
- break;
1217
1190
  case "--scratch-hours":
1218
1191
  o.scratchHours = num(k, v);
1219
1192
  break;
1220
1193
  case "--build-hours":
1221
1194
  o.buildHours = num(k, v);
1222
1195
  break;
1196
+ case "--transcript-days":
1197
+ o.transcriptDays = num(k, v);
1198
+ break;
1223
1199
  case "--orphan-minutes":
1224
1200
  o.orphanMinutes = num(k, v);
1225
1201
  break;
1202
+ case "--top":
1203
+ o.top = num(k, v);
1204
+ break;
1226
1205
  case "-h":
1227
1206
  case "--help":
1228
1207
  o.help = true;
@@ -1259,7 +1238,24 @@ function writeReport(file, data) {
1259
1238
  for (const p of old) rmSync(p, { force: true });
1260
1239
  }
1261
1240
 
1262
- function printPlan(p, mode, disk) {
1241
+ /** The largest items of a category, how many are left out, and why items were kept. */
1242
+ export function categorySummary(c, top = DEFAULT_TOP) {
1243
+ const sorted = [...c.candidates].sort((a, b) => (b.bytes || 0) - (a.bytes || 0));
1244
+ const kept = {};
1245
+ for (const k of c.skipped) kept[k.reason] = (kept[k.reason] || 0) + 1;
1246
+ return {
1247
+ top: sorted.slice(0, top).map((x) => ({ path: x.path, bytes: x.bytes, kind: x.kind })),
1248
+ more: Math.max(0, sorted.length - top),
1249
+ kept,
1250
+ };
1251
+ }
1252
+
1253
+ /** What an apply of this plan would free: blocked categories are not applied. */
1254
+ export function reclaimable(p) {
1255
+ return p.categories.filter((c) => !c.blocked).reduce((s, c) => s + c.bytes, 0);
1256
+ }
1257
+
1258
+ function printPlan(p, mode, disk, top = 0) {
1263
1259
  const lines = [];
1264
1260
  const pct = disk.totalBytes ? ((disk.freeBytes / disk.totalBytes) * 100).toFixed(1) : "?";
1265
1261
  lines.push(
@@ -1274,6 +1270,12 @@ function printPlan(p, mode, disk) {
1274
1270
  lines.push(
1275
1271
  `${c.id.padEnd(18)} ${String(c.candidates.length).padStart(6)} ${human(c.bytes).padStart(9)} ${note}`,
1276
1272
  );
1273
+ if (top > 0) {
1274
+ const s = categorySummary(c, top);
1275
+ for (const x of s.top)
1276
+ lines.push(`${"".padEnd(18)} ${human(x.bytes).padStart(16)} ${x.path}`);
1277
+ if (s.more) lines.push(`${"".padEnd(18)} ${"".padStart(16)} + ${s.more} more`);
1278
+ }
1277
1279
  }
1278
1280
  lines.push(`${"total".padEnd(18)} ${"".padStart(6)} ${human(p.totalBytes).padStart(9)}`);
1279
1281
  return lines.join("\n");
@@ -1348,8 +1350,12 @@ export function main(argv, env = process.env) {
1348
1350
  mode,
1349
1351
  unattended,
1350
1352
  startedAt: new Date(ctx.now).toISOString(),
1351
- disk: { before },
1353
+ disk: {
1354
+ before,
1355
+ expectedFreeBytes: before.freeBytes == null ? null : before.freeBytes + reclaimable(planned),
1356
+ },
1352
1357
  totalBytes: planned.totalBytes,
1358
+ reclaimableBytes: reclaimable(planned),
1353
1359
  categories: planned.categories.map((c) => ({
1354
1360
  id: c.id,
1355
1361
  label: c.label,
@@ -1357,11 +1363,14 @@ export function main(argv, env = process.env) {
1357
1363
  note: c.note,
1358
1364
  candidates: c.candidates.map((x) => ({ path: x.path, bytes: x.bytes, kind: x.kind })),
1359
1365
  skipped: c.skipped,
1366
+ blocked: c.blocked || null,
1367
+ ...categorySummary(c, o.top ?? DEFAULT_TOP),
1360
1368
  })),
1369
+ orphans: listOrphans(ctx),
1361
1370
  };
1362
1371
  let applied = null;
1363
1372
  if (o.apply) {
1364
- applied = applyPlan(ctx, planned, { processes: Boolean(o.processes) && !unattended });
1373
+ applied = applyPlan(ctx, planned);
1365
1374
  const after = diskStatus(ctx.home);
1366
1375
  report.disk.after = after;
1367
1376
  report.applied = {
@@ -1389,10 +1398,15 @@ export function main(argv, env = process.env) {
1389
1398
  if (o.json) {
1390
1399
  process.stdout.write(JSON.stringify(report, null, 2) + "\n");
1391
1400
  } else {
1392
- const lines = [printPlan(planned, mode, before), ...summarizeSkips(planned)];
1401
+ const lines = [printPlan(planned, mode, before, o.top || 0), ...summarizeSkips(planned)];
1402
+ if (report.orphans.length) {
1403
+ lines.push(
1404
+ `orphaned session processes: ${report.orphans.length} (information only; never stopped)`,
1405
+ );
1406
+ }
1393
1407
  if (applied) {
1394
1408
  lines.push(
1395
- `removed ${applied.removed}, failed ${applied.failed}, processes stopped ${applied.stopped}; freed ${human(report.applied.freedBytes)} (df before ${human(before.freeBytes)}, after ${human(report.disk.after.freeBytes)})`,
1409
+ `removed ${applied.removed}, failed ${applied.failed}; freed ${human(report.applied.freedBytes)} (df before ${human(before.freeBytes)}, after ${human(report.disk.after.freeBytes)})`,
1396
1410
  );
1397
1411
  for (const f of applied.failures.slice(0, 10)) {
1398
1412
  lines.push(` failed ${f.category}: ${f.path} (${f.reason})`);
@@ -58,7 +58,7 @@ import {
58
58
  } from "node:fs";
59
59
  import { basename, join, dirname } from "node:path";
60
60
  import { homedir } from "node:os";
61
- import { execFileSync } from "node:child_process";
61
+ import { execFileSync, spawnSync } from "node:child_process";
62
62
  import { fileURLToPath, pathToFileURL } from "node:url";
63
63
  import { runMain } from "../lib/fatal.mjs";
64
64
  import { hostCommand } from "../lib/user-facing.mjs";
@@ -69,7 +69,7 @@ import {
69
69
  import { prefsHosts, profileGaps } from "../lib/unattended-profile-check.mjs";
70
70
  import { xcodeSkillsStatus } from "../lib/xcode-plugin.mjs";
71
71
  import { hookReport, registrationGaps } from "../lib/hook-registration.mjs";
72
- import { PREFS_ENV, prefsFileIn } from "../lib/prefs-value.mjs";
72
+ import { PREFS_ENV, globalPref, prefsFileIn } from "../lib/prefs-value.mjs";
73
73
  import { check as lowDiskCheck } from "../lib/low-disk.mjs";
74
74
  import { exitOnHelp } from "../lib/cli-help.mjs";
75
75
  import { didYouMean } from "../lib/args.mjs";
@@ -1197,7 +1197,7 @@ function checkMcpFailures() {
1197
1197
  "mcp-failures",
1198
1198
  "INFO",
1199
1199
  `${n} MCP call(s) failed with disk-full in the last ${summary.hours} hours (${diskFull.map((s) => s.server).join(", ")})`,
1200
- "run the disk-cleaner skill: node ~/.claude/scripts/disk-cleaner.mjs --dry-run, then --apply for the categories you choose",
1200
+ `run ${hostCommand("clean-disk", HERE)}: it measures every category first and deletes only the ones you choose`,
1201
1201
  diskFull.map((s) => ({ server: s.server, diskFull: s.classes["disk-full"] })),
1202
1202
  );
1203
1203
  return;
@@ -1454,25 +1454,154 @@ function checkXcodeSkills() {
1454
1454
 
1455
1455
  // One statfs call against the volume holding $HOME. Low means below
1456
1456
  // prefs.global.diskCleaner.lowDiskGb or lowDiskPercent (lib/low-disk.mjs owns
1457
- // both defaults); the step names the disk-cleaner skill, which measures before
1458
- // it deletes anything.
1457
+ // both defaults). What could be freed comes from the newest disk-cleaner dry
1458
+ // run under ~/.claude/logs/disk-cleaner, never from a fresh measurement: a
1459
+ // full measurement walks every cache and would make doctor slow. --probe runs
1460
+ // one under a time cap; a timeout is reported, never a failure. Nothing here
1461
+ // deletes anything.
1462
+ const DISK_REPORT_MAX_AGE_MS = 24 * 3_600_000;
1463
+ const DISK_PROBE_TIMEOUT_MS = 60_000;
1464
+ const DISK_TOP = 3;
1465
+ const GB = 1e9;
1466
+ const gb = (bytes) => `${(bytes / GB).toFixed(1)} GB`;
1467
+
1468
+ function newestDiskReport(dir) {
1469
+ let names;
1470
+ try {
1471
+ names = readdirSync(dir)
1472
+ .filter((n) => /^report-.*\.json$/.test(n))
1473
+ .sort()
1474
+ .reverse();
1475
+ } catch {
1476
+ return null;
1477
+ }
1478
+ for (const n of names) {
1479
+ const data = readJson(join(dir, n));
1480
+ if (data && data.mode === "dry-run" && Array.isArray(data.categories)) {
1481
+ return { file: join(dir, n), data };
1482
+ }
1483
+ }
1484
+ return null;
1485
+ }
1486
+
1487
+ function probeDiskReport() {
1488
+ const timeout = Number(process.env.DOCTOR_DISK_PROBE_TIMEOUT_MS) || DISK_PROBE_TIMEOUT_MS;
1489
+ const r = spawnSync(
1490
+ process.execPath,
1491
+ [join(HERE, "disk-cleaner.mjs"), "--dry-run", "--json", `--top=${DISK_TOP}`],
1492
+ { encoding: "utf8", timeout, maxBuffer: 256 * 1024 * 1024 },
1493
+ );
1494
+ if (r.error?.code === "ETIMEDOUT" || r.signal) {
1495
+ return { timedOut: true, seconds: Math.round(timeout / 1000) };
1496
+ }
1497
+ try {
1498
+ return { data: JSON.parse(r.stdout) };
1499
+ } catch {
1500
+ return { error: (r.stderr || "no JSON on stdout").trim().split("\n")[0] };
1501
+ }
1502
+ }
1503
+
1504
+ function reclaimSummary(data, source, file) {
1505
+ const measuredAt = Date.parse(data.startedAt);
1506
+ const ageMs = Number.isFinite(measuredAt) ? Date.now() - measuredAt : null;
1507
+ const top = [...data.categories]
1508
+ .filter((c) => c.bytes > 0)
1509
+ .sort((a, b) => b.bytes - a.bytes)
1510
+ .slice(0, DISK_TOP)
1511
+ .map((c) => ({ id: c.id, bytes: c.bytes }));
1512
+ return {
1513
+ source,
1514
+ file,
1515
+ measuredAt: data.startedAt || null,
1516
+ ageHours: ageMs == null ? null : Math.round((ageMs / 3_600_000) * 10) / 10,
1517
+ stale: ageMs == null || ageMs > DISK_REPORT_MAX_AGE_MS,
1518
+ totalBytes: data.reclaimableBytes ?? data.totalBytes ?? 0,
1519
+ top,
1520
+ };
1521
+ }
1522
+
1523
+ function ageText(hours) {
1524
+ if (hours == null) return "at an unknown time";
1525
+ if (hours < 1) return `${Math.max(1, Math.round(hours * 60))} min ago`;
1526
+ if (hours < 48) return `${Math.round(hours)} h ago`;
1527
+ return `${Math.round(hours / 24)} days ago`;
1528
+ }
1529
+
1459
1530
  function checkDiskSpace() {
1460
1531
  const r = lowDiskCheck({ path: HOME });
1461
1532
  if (r.freeBytes == null) {
1462
1533
  skip("disk-space", "statfs did not report a usable figure on this host");
1463
1534
  return;
1464
1535
  }
1536
+ const cmd = hostCommand("clean-disk", HERE);
1537
+ const pct = r.totalBytes ? (r.freeBytes / r.totalBytes) * 100 : null;
1538
+ const freeText = `${gb(r.freeBytes)} (${pct == null ? "?" : pct.toFixed(1)}%) free on the volume holding $HOME`;
1539
+ const threshold = Number(globalPref("diskCleaner.reclaimableGb", 10));
1540
+ const reclaimGb = Number.isFinite(threshold) && threshold >= 0 ? threshold : 10;
1541
+
1542
+ let reclaim = null;
1543
+ let probe = null;
1544
+ if (PROBE) {
1545
+ const p = probeDiskReport();
1546
+ probe = p.data
1547
+ ? { ok: true }
1548
+ : p.timedOut
1549
+ ? { timedOut: true, seconds: p.seconds }
1550
+ : { error: p.error };
1551
+ if (p.data) reclaim = reclaimSummary(p.data, "probe", null);
1552
+ }
1553
+ if (!reclaim) {
1554
+ const found = newestDiskReport(join(CLAUDE, "logs", "disk-cleaner"));
1555
+ if (found) reclaim = reclaimSummary(found.data, "report", found.file);
1556
+ }
1557
+
1558
+ let measured;
1559
+ if (probe?.timedOut) {
1560
+ measured = `the measurement timed out after ${probe.seconds} s`;
1561
+ if (reclaim && !reclaim.stale) measured += `; the last one, ${ageText(reclaim.ageHours)}`;
1562
+ } else if (probe?.error) {
1563
+ measured = `the measurement failed (${probe.error})`;
1564
+ } else if (!reclaim) {
1565
+ measured = `nothing measured yet; ${cmd} measures what can be freed`;
1566
+ } else if (reclaim.stale) {
1567
+ measured = `the last measurement is ${ageText(reclaim.ageHours).replace(/ ago$/, " old")}; ${cmd} measures again`;
1568
+ } else {
1569
+ measured = `measured ${ageText(reclaim.ageHours)}`;
1570
+ }
1571
+ const fresh = reclaim && !reclaim.stale;
1572
+ const reclaimText = fresh
1573
+ ? `${gb(reclaim.totalBytes)} can be freed${reclaim.top.length ? ` (${reclaim.top.map((c) => `${c.id} ${gb(c.bytes)}`).join(", ")})` : ""}, ${measured}`
1574
+ : measured;
1575
+ const detail = {
1576
+ freeBytes: r.freeBytes,
1577
+ totalBytes: r.totalBytes,
1578
+ freePercent: pct == null ? null : Math.round(pct * 10) / 10,
1579
+ lowGb: r.lowGb,
1580
+ lowPercent: r.lowPercent,
1581
+ reclaimableGb: reclaimGb,
1582
+ reclaimable: reclaim,
1583
+ probe,
1584
+ summary: `${freeText}; ${reclaimText}`,
1585
+ };
1586
+ const freeStep = fresh
1587
+ ? `run ${cmd}: ${gb(reclaim.totalBytes)} can be freed`
1588
+ : `run ${cmd} to measure what can be freed; it deletes only what you choose`;
1589
+
1465
1590
  if (r.low) {
1466
- const pct = r.totalBytes ? ((r.freeBytes / r.totalBytes) * 100).toFixed(1) : "?";
1467
1591
  report(
1468
1592
  "disk-space",
1469
1593
  "WARN",
1470
- `${(r.freeBytes / 1e9).toFixed(1)} GB (${pct}%) free on the volume holding $HOME, under the ${r.lowGb} GB / ${r.lowPercent}% floor; a worktree plus a build needs more`,
1471
- "run the disk-cleaner skill: node ~/.claude/scripts/disk-cleaner.mjs --dry-run, then --apply for the categories you choose",
1594
+ `${freeText}, under the ${r.lowGb} GB / ${r.lowPercent}% floor; a worktree plus a build needs more; ${reclaimText}`,
1595
+ freeStep,
1596
+ detail,
1472
1597
  );
1473
1598
  return;
1474
1599
  }
1475
- ok("disk-space");
1600
+ if (fresh && reclaim.totalBytes >= reclaimGb * GB) {
1601
+ report("disk-space", "INFO", `${freeText}; ${reclaimText}`, freeStep, detail);
1602
+ return;
1603
+ }
1604
+ report("disk-space", "OK", null, null, detail);
1476
1605
  }
1477
1606
 
1478
1607
  // A finished task removes its own worktree at PR time, but a run that dies
@@ -1806,7 +1935,8 @@ function main() {
1806
1935
  const r = results.find((x) => x.id === id);
1807
1936
  if (!r) continue;
1808
1937
  if (r.severity === "OK") {
1809
- process.stdout.write(`OK ${id}\n`);
1938
+ const note = typeof r.detail?.summary === "string" ? ` - ${r.detail.summary}` : "";
1939
+ process.stdout.write(`OK ${id}${note}\n`);
1810
1940
  } else if (r.severity === "SKIP") {
1811
1941
  process.stdout.write(`SKIP ${id} - ${r.problem}\n`);
1812
1942
  } else {