@mmerterden/multi-agent-pipeline 20.41.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 (114) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +8 -6
  3. package/README.tr.md +8 -6
  4. package/docs/architecture.md +3 -3
  5. package/docs/ecosystem.md +50 -13
  6. package/docs/facts.json +9 -9
  7. package/docs/features.md +9 -4
  8. package/install/claude.mjs +34 -1
  9. package/install/templates/claude-hooks.json +12 -1
  10. package/manifest.json +117 -90
  11. package/package.json +3 -2
  12. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  13. package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
  14. package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/credential-store.sh +11 -1
  20. package/pipeline/lib/hook-once.mjs +134 -0
  21. package/pipeline/lib/isotonic.mjs +73 -0
  22. package/pipeline/lib/low-disk.mjs +154 -0
  23. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  24. package/pipeline/lib/md2confluence-v3.py +8 -7
  25. package/pipeline/lib/model-dispatch.sh +26 -2
  26. package/pipeline/lib/normalize-text.mjs +135 -0
  27. package/pipeline/lib/outbound-gate.mjs +21 -3
  28. package/pipeline/lib/plan-todos.sh +17 -4
  29. package/pipeline/lib/redact.mjs +12 -3
  30. package/pipeline/lib/risky-settings.mjs +198 -0
  31. package/pipeline/lib/route-state.sh +1 -0
  32. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  33. package/pipeline/lib/session-usage.mjs +232 -0
  34. package/pipeline/lib/source-digest.mjs +211 -0
  35. package/pipeline/lib/tdd-evidence.mjs +250 -17
  36. package/pipeline/lib/untrusted-fence.mjs +132 -1
  37. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  38. package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
  39. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  40. package/pipeline/multi-agent-refs/features/doctor.md +66 -4
  41. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  42. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  43. package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
  44. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  45. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  46. package/pipeline/multi-agent-refs/help/en.md +3 -1
  47. package/pipeline/multi-agent-refs/help/tr.md +3 -1
  48. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  49. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  50. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  51. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  52. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  53. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  54. package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
  55. package/pipeline/office/toolkit.json +1 -1
  56. package/pipeline/rules/outside-the-pipeline.md +1 -1
  57. package/pipeline/schemas/doctor-report.schema.json +47 -0
  58. package/pipeline/schemas/plan-todos.schema.json +29 -1
  59. package/pipeline/schemas/prefs.schema.json +81 -0
  60. package/pipeline/schemas/route-config.schema.json +51 -0
  61. package/pipeline/schemas/secret-patterns.json +17 -1
  62. package/pipeline/schemas/toolkit-path-params.json +15 -1
  63. package/pipeline/scripts/_cost-advise.mjs +357 -0
  64. package/pipeline/scripts/_cost-budget.mjs +78 -0
  65. package/pipeline/scripts/_cost.mjs +29 -0
  66. package/pipeline/scripts/_decode_text.py +107 -0
  67. package/pipeline/scripts/_guard-probe.mjs +406 -0
  68. package/pipeline/scripts/_guard_rules.py +206 -0
  69. package/pipeline/scripts/_memory-policy.mjs +1 -25
  70. package/pipeline/scripts/_retrieval.mjs +148 -2
  71. package/pipeline/scripts/_secret-scan.mjs +6 -1
  72. package/pipeline/scripts/_stack-routing.mjs +1 -0
  73. package/pipeline/scripts/_test-gaming.mjs +346 -0
  74. package/pipeline/scripts/agent-guard.py +8 -1
  75. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  76. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  77. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  78. package/pipeline/scripts/capture-resume.sh +9 -1
  79. package/pipeline/scripts/cost-analyze.mjs +66 -4
  80. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  81. package/pipeline/scripts/disk-cleaner.mjs +1432 -0
  82. package/pipeline/scripts/doctor.mjs +302 -47
  83. package/pipeline/scripts/evidence-gate.mjs +90 -0
  84. package/pipeline/scripts/gate-ledger.mjs +76 -21
  85. package/pipeline/scripts/gc-tmp.sh +5 -0
  86. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  87. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  88. package/pipeline/scripts/note-agent-event.mjs +2 -0
  89. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  90. package/pipeline/scripts/note-skill-use.mjs +4 -1
  91. package/pipeline/scripts/pre-commit-check.sh +2 -2
  92. package/pipeline/scripts/pre-push-check.sh +8 -1
  93. package/pipeline/scripts/priority-review.mjs +912 -0
  94. package/pipeline/scripts/publish-staged.mjs +324 -0
  95. package/pipeline/scripts/route-learn.mjs +628 -0
  96. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  97. package/pipeline/scripts/scan-agent-config.sh +1 -1
  98. package/pipeline/scripts/statusline.mjs +309 -0
  99. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  100. package/pipeline/scripts/triage-memory.mjs +12 -4
  101. package/pipeline/scripts/uninstall.mjs +1 -0
  102. package/pipeline/skills/.skill-manifest.json +17 -5
  103. package/pipeline/skills/.skills-index.json +36 -3
  104. package/pipeline/skills/shared/README.md +9 -6
  105. package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
  106. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
  107. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
  108. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  109. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +111 -0
  110. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  111. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1432 -0
  112. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  113. package/pipeline/skills/skill-copies.json +4 -0
  114. package/pipeline/skills/skills-index.md +5 -2
@@ -0,0 +1,407 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * autopilot-loop.mjs - run one task as a bounded series of autopilot runs,
4
+ * for mechanical batch work that takes more than one pass.
5
+ *
6
+ * Each iteration is one whole `/multi-agent <task> autopilot` run, so every
7
+ * gate the pipeline has runs every time. What happens between iterations is
8
+ * decided here, from files, never from what a model wrote:
9
+ *
10
+ * judged the iteration's own agent-state.json must show a complete run
11
+ * (lib/run-completion.mjs completionGaps is empty) with at least
12
+ * one gate recorded and the latest verdict of every gate passing.
13
+ * Anything else stops the loop: gates-failed, gates-missing,
14
+ * incomplete, no-state.
15
+ * complete only after a judged iteration, and only when `--until "<cmd>"`
16
+ * exits 0, run here. The loop then writes complete.json itself,
17
+ * carrying a nonce kept in its own state, and `status` trusts a
18
+ * marker only with that nonce. There is no phrase a model can
19
+ * print to end it.
20
+ * no-progress two iterations in a row that delivered nothing (no commit
21
+ * and no pull request) end the loop.
22
+ *
23
+ * Hard caps, checked before every iteration: the iteration count (required,
24
+ * at most 25), wall time (default 120 minutes, at most 720; each launch is
25
+ * given only the time left) and cost (default $20, at most $200). The cost
26
+ * cap is checked against the spend so far plus the last iteration's cost, so
27
+ * an iteration that cannot be paid for is not started. An iteration whose
28
+ * cost cannot be measured stops the loop: a cap that cannot be checked is not
29
+ * a cap. A STOP file in the loop directory stops it before the next iteration.
30
+ *
31
+ * Every iteration is launched the way autopilot-runner launches an item, by
32
+ * the runner's own launch(), launchArgv() and launchEnv(): no permission
33
+ * prompts, the run's own launch settings file, MULTI_AGENT_UNATTENDED=1, the
34
+ * strict toolkit URL policy and index deny list, the unattended LOGS_ROOT,
35
+ * the checkout's HEAD as MA_RUN_BASE_SHA and the run's own Gradle home, with
36
+ * the sandbox precondition judging that exact argv and environment. Before
37
+ * the first iteration the runner's guard registration and sandbox checks run
38
+ * against the repository, and a failing one refuses the start. A launch the
39
+ * precondition refuses later stops the loop (launch-refused).
40
+ *
41
+ * The loop directory is ~/.claude/state/autopilot-loops/<id>/: state.json,
42
+ * written after every iteration, complete.json and STOP.
43
+ *
44
+ * Usage:
45
+ * autopilot-loop.mjs start --task <ref> --repo <dir> --max-iterations N
46
+ * [--max-minutes M] [--max-usd U] [--until "<cmd>"]
47
+ * [--dry-run] [--json]
48
+ * autopilot-loop.mjs status [<id>] [--json]
49
+ * autopilot-loop.mjs stop <id>
50
+ *
51
+ * Exit: 0 started and stopped normally (any stop reason) or a status / stop
52
+ * answered; 2 usage error; 3 no such loop; 4 the unattended preconditions
53
+ * refused the start.
54
+ */
55
+
56
+ import { spawnSync } from "node:child_process";
57
+ import { randomUUID } from "node:crypto";
58
+ import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from "node:fs";
59
+ import { homedir } from "node:os";
60
+ import { join } from "node:path";
61
+
62
+ import { ArgsError, parseArgs, unknownSubcommand } from "../lib/args.mjs";
63
+ import { exitOnHelp } from "../lib/cli-help.mjs";
64
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
65
+ import { writeJsonAtomicSync } from "../lib/json-file-lock.mjs";
66
+ import { readRegularJson } from "../lib/regular-file.mjs";
67
+ import { completionGaps, phase4Evidence } from "../lib/run-completion.mjs";
68
+ import { unattendedLogsRoot } from "../lib/pr-request-location.mjs";
69
+ import { unattendedSettingsPath } from "../lib/unattended-settings-location.mjs";
70
+ import {
71
+ endRunHome,
72
+ findRunState,
73
+ guardRegistration,
74
+ headSha,
75
+ launch as unattendedLaunch,
76
+ launchArgv,
77
+ runUsd,
78
+ sandboxPrecondition,
79
+ } from "./autopilot-runner.mjs";
80
+
81
+ exitOnHelp(import.meta.url);
82
+
83
+ export const CEILINGS = { iterations: 25, minutes: 720, usd: 200 };
84
+ const DEFAULT_MINUTES = 120;
85
+ const DEFAULT_USD = 20;
86
+ const EMPTY_STREAK = 2;
87
+ const PASSING = new Set(["pass", "not-applicable"]);
88
+
89
+ const usage = (message) => new ArgsError(message, { kind: "unexpected", token: "start" });
90
+
91
+ /**
92
+ * The loop's caps from what was asked, each held under its ceiling.
93
+ *
94
+ * @param {{task?: string, maxIterations?: number, maxMinutes?: number, maxUsd?: number, until?: string|null}} ask
95
+ */
96
+ export function resolveCaps(ask) {
97
+ if (!ask.task) throw usage("start needs --task");
98
+ const n = Number(ask.maxIterations);
99
+ if (!Number.isInteger(n) || n < 1)
100
+ throw usage("start needs --max-iterations, a whole number of at least 1");
101
+ const minutes = ask.maxMinutes === undefined ? DEFAULT_MINUTES : Number(ask.maxMinutes);
102
+ const usd = ask.maxUsd === undefined ? DEFAULT_USD : Number(ask.maxUsd);
103
+ if (n > CEILINGS.iterations) throw usage(`--max-iterations is at most ${CEILINGS.iterations}`);
104
+ if (!(minutes > 0) || minutes > CEILINGS.minutes)
105
+ throw usage(`--max-minutes is above 0 and at most ${CEILINGS.minutes}`);
106
+ if (!(usd > 0) || usd > CEILINGS.usd)
107
+ throw usage(`--max-usd is above 0 and at most ${CEILINGS.usd}`);
108
+ if (ask.until !== undefined && ask.until !== null && !String(ask.until).trim())
109
+ throw usage("--until needs a command");
110
+ return {
111
+ task: ask.task,
112
+ maxIterations: n,
113
+ maxMinutes: minutes,
114
+ maxUsd: usd,
115
+ until: ask.until ?? null,
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Whether one iteration's run may count: complete, gated, every gate passing.
121
+ *
122
+ * @param {object|null} state the run's agent-state.json
123
+ */
124
+ export function judgeIteration(state) {
125
+ if (!state || typeof state !== "object") return { ok: false, reason: "no-state" };
126
+ const latest = new Map();
127
+ for (const g of Array.isArray(state.gates) ? state.gates : []) {
128
+ if (!g || typeof g.gate !== "string") continue;
129
+ const prev = latest.get(g.gate);
130
+ if (!prev || (Date.parse(g.at) || 0) >= (Date.parse(prev.at) || 0)) latest.set(g.gate, g);
131
+ }
132
+ const total = latest.size;
133
+ const passed = [...latest.values()].filter((g) => PASSING.has(g.verdict)).length;
134
+ if (!total) return { ok: false, reason: "gates-missing", gates: { passed, total } };
135
+ if (passed < total) return { ok: false, reason: "gates-failed", gates: { passed, total } };
136
+ if (completionGaps(state).length)
137
+ return { ok: false, reason: "incomplete", gates: { passed, total } };
138
+ const p4 = state.phases?.["4"];
139
+ const decidedNothing = p4?.status === "skipped";
140
+ return {
141
+ ok: true,
142
+ delivered: phase4Evidence(state) && !decidedNothing,
143
+ gates: { passed, total },
144
+ };
145
+ }
146
+
147
+ /**
148
+ * The loop itself, with every effect injected.
149
+ *
150
+ * @param {ReturnType<typeof resolveCaps>} caps
151
+ * @param {{now: () => number, launch: Function, inspect: Function, measure: Function,
152
+ * check: Function, stopRequested: () => boolean, save: Function, writeMarker: Function,
153
+ * id?: string}} deps
154
+ */
155
+ export function runLoop(caps, deps) {
156
+ const startedAt = deps.now();
157
+ const s = {
158
+ id: deps.id ?? randomUUID(),
159
+ nonce: randomUUID(),
160
+ task: caps.task,
161
+ caps,
162
+ startedAt: new Date(startedAt).toISOString(),
163
+ status: "running",
164
+ iterations: [],
165
+ spentUsd: 0,
166
+ completed: false,
167
+ stopReason: null,
168
+ };
169
+ const stop = (reason) => {
170
+ s.status = reason === "complete" ? "complete" : "stopped";
171
+ s.stopReason = reason;
172
+ s.stoppedAt = new Date(deps.now()).toISOString();
173
+ deps.save(s);
174
+ return s;
175
+ };
176
+ const maxMs = caps.maxMinutes * 60_000;
177
+ let empty = 0;
178
+ for (let i = 1; ; i++) {
179
+ if (deps.stopRequested()) return stop("stop-requested");
180
+ if (i > caps.maxIterations) return stop("cap-iterations");
181
+ const remainingMs = maxMs - (deps.now() - startedAt);
182
+ if (remainingMs <= 0) return stop("cap-time");
183
+ const last = s.iterations.at(-1);
184
+ if (s.spentUsd >= caps.maxUsd || (last && s.spentUsd + last.usd > caps.maxUsd))
185
+ return stop("cap-cost");
186
+
187
+ const run = deps.launch({ iteration: i, remainingMs });
188
+ if (run.blocked) {
189
+ s.refusal = run.blocked;
190
+ return stop("launch-refused");
191
+ }
192
+ const found = deps.inspect(run);
193
+ const verdict = judgeIteration(found?.state ?? null);
194
+ const usd = found ? deps.measure(found) : null;
195
+ const row = {
196
+ iteration: i,
197
+ sessionId: run.sessionId,
198
+ taskId: found?.state?.taskId ?? null,
199
+ usd,
200
+ gates: verdict.gates ?? null,
201
+ delivered: verdict.delivered ?? false,
202
+ verdict: verdict.ok ? "pass" : verdict.reason,
203
+ at: new Date(deps.now()).toISOString(),
204
+ };
205
+ s.iterations.push(row);
206
+ if (Number.isFinite(usd)) s.spentUsd = Number((s.spentUsd + usd).toFixed(4));
207
+ deps.save(s);
208
+ if (run.timedOut) return stop("cap-time");
209
+ if (!verdict.ok) return stop(verdict.reason);
210
+ if (!Number.isFinite(usd)) return stop("cost-unmeasured");
211
+ if (caps.until) {
212
+ const r = deps.check(caps.until);
213
+ row.until = r.code;
214
+ if (r.ok) {
215
+ s.completed = true;
216
+ deps.writeMarker({
217
+ loopId: s.id,
218
+ nonce: s.nonce,
219
+ iteration: i,
220
+ until: caps.until,
221
+ completedAt: new Date(deps.now()).toISOString(),
222
+ });
223
+ return stop("complete");
224
+ }
225
+ }
226
+ empty = row.delivered ? 0 : empty + 1;
227
+ if (empty >= EMPTY_STREAK) return stop("no-progress");
228
+ }
229
+ }
230
+
231
+ /** One iteration: the runner's unattended launch of the task, in print mode, waited for. */
232
+ export function iterationArgv(task, sessionId, settingsFile = unattendedSettingsPath()) {
233
+ return launchArgv({ ref: task }, sessionId, settingsFile, { print: true });
234
+ }
235
+
236
+ /**
237
+ * The runner's tick-level checks, against the repository the loop works in:
238
+ * agent-guard registered with the unattended permission profile installed,
239
+ * and the profile's OS sandbox in force and not widened by the checkout.
240
+ *
241
+ * @returns {{ok: boolean, reason?: string}}
242
+ */
243
+ export function startPreconditions(repo, env = process.env) {
244
+ const guard = guardRegistration({ cwd: repo, env });
245
+ if (!guard.ok) return { ok: false, reason: guard.reason };
246
+ const sandbox = sandboxPrecondition({ cwd: repo });
247
+ if (!sandbox.ok) return { ok: false, reason: sandbox.reason };
248
+ return { ok: true };
249
+ }
250
+
251
+ // --- CLI ---------------------------------------------------------------------
252
+
253
+ const loopsDir = (env = process.env) =>
254
+ join(env.HOME || homedir(), ".claude", "state", "autopilot-loops");
255
+
256
+ function realDeps(caps, repo, dir, id) {
257
+ // Each run writes its state under the unattended LOGS_ROOT (launchEnv), so
258
+ // that is where findRunState has to look. An operator's own LOGS_ROOT is kept.
259
+ if (!process.env.LOGS_ROOT) process.env.LOGS_ROOT = unattendedLogsRoot();
260
+ return {
261
+ id,
262
+ now: Date.now,
263
+ launch: ({ remainingMs }) => {
264
+ const sessionId = randomUUID();
265
+ const r = unattendedLaunch(
266
+ (settingsFile) => iterationArgv(caps.task, sessionId, settingsFile),
267
+ repo,
268
+ sessionId,
269
+ headSha(repo),
270
+ { timeoutMs: remainingMs, stdio: "ignore" },
271
+ );
272
+ if (r.blocked) return { sessionId, blocked: r.blocked };
273
+ const timedOut = r.error?.code === "ETIMEDOUT" || r.signal === "SIGTERM";
274
+ if (r.status === 0 || timedOut) endRunHome(r.gradleHome, { reason: "finished" });
275
+ return { sessionId, timedOut };
276
+ },
277
+ inspect: ({ sessionId }) => {
278
+ const found = findRunState({ sessionId });
279
+ return found ? { ...found, state: readRegularJson(found.statePath, null) } : null;
280
+ },
281
+ measure: (found) => runUsd(found.runTaskId, found.statePath),
282
+ check: (cmd) => {
283
+ const r = spawnSync("/bin/sh", ["-c", cmd], {
284
+ cwd: repo,
285
+ stdio: "ignore",
286
+ timeout: 10 * 60_000,
287
+ });
288
+ return { ok: r.status === 0, code: r.status };
289
+ },
290
+ stopRequested: () => existsSync(join(dir, "STOP")),
291
+ save: (s) => writeJsonAtomicSync(join(dir, "state.json"), s),
292
+ writeMarker: (m) => writeJsonAtomicSync(join(dir, "complete.json"), m),
293
+ };
294
+ }
295
+
296
+ function statusOf(dir) {
297
+ const s = readRegularJson(join(dir, "state.json"), null);
298
+ if (!s) return null;
299
+ const marker = readRegularJson(join(dir, "complete.json"), null);
300
+ const markerOk = Boolean(marker && marker.nonce === s.nonce);
301
+ return {
302
+ id: s.id,
303
+ task: s.task,
304
+ status: s.status,
305
+ stopReason: s.stopReason,
306
+ iterations: s.iterations?.length ?? 0,
307
+ spentUsd: s.spentUsd ?? null,
308
+ caps: s.caps ?? null,
309
+ complete: Boolean(s.completed && markerOk),
310
+ note:
311
+ marker && !markerOk
312
+ ? "complete.json is present but not written by this loop; ignored"
313
+ : s.completed && !markerOk
314
+ ? "the loop recorded completion but its marker is missing"
315
+ : null,
316
+ };
317
+ }
318
+
319
+ function latestLoop(env) {
320
+ const root = loopsDir(env);
321
+ let best = null;
322
+ for (const e of existsSync(root) ? readdirSync(root, { withFileTypes: true }) : []) {
323
+ if (!e.isDirectory()) continue;
324
+ const m = statSync(join(root, e.name)).mtimeMs;
325
+ if (!best || m > best.m) best = { id: e.name, m };
326
+ }
327
+ return best?.id ?? null;
328
+ }
329
+
330
+ const SUBCOMMANDS = ["start", "status", "stop"];
331
+
332
+ async function main(argv, env) {
333
+ const [sub, ...rest] = argv;
334
+ if (!SUBCOMMANDS.includes(sub)) throw unknownSubcommand(sub ?? "", SUBCOMMANDS);
335
+ const { flags, positionals } = parseArgs(rest, {
336
+ unknown: "error",
337
+ booleans: ["json", "dry-run"],
338
+ strings: ["task", "repo", "max-iterations", "max-minutes", "max-usd", "until"],
339
+ });
340
+ const json = flags.json === true;
341
+ if (sub === "start") {
342
+ const caps = resolveCaps({
343
+ task: flags.task,
344
+ maxIterations: flags["max-iterations"],
345
+ maxMinutes: flags["max-minutes"],
346
+ maxUsd: flags["max-usd"],
347
+ until: flags.until,
348
+ });
349
+ const repo = flags.repo || process.cwd();
350
+ if (!existsSync(repo)) throw usage(`--repo ${repo} does not exist`);
351
+ if (flags["dry-run"]) {
352
+ const plan = { caps, repo, argv: iterationArgv(caps.task, "<session-id>"), launched: false };
353
+ return {
354
+ code: 0,
355
+ text: json ? `${JSON.stringify(plan, null, 2)}\n` : `${JSON.stringify(plan)}\n`,
356
+ };
357
+ }
358
+ const pre = startPreconditions(repo, env);
359
+ if (!pre.ok)
360
+ return {
361
+ code: 4,
362
+ text: "",
363
+ err: `autopilot-loop: not starting: ${pre.reason} (see features/unattended-security.md)\n`,
364
+ };
365
+ const id = randomUUID();
366
+ const dir = join(loopsDir(env), id);
367
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
368
+ process.stdout.write(`loop ${id}\n`);
369
+ const s = runLoop(caps, realDeps(caps, repo, dir, id));
370
+ const st = statusOf(dir);
371
+ return {
372
+ code: 0,
373
+ text: json
374
+ ? `${JSON.stringify(st, null, 2)}\n`
375
+ : `${s.status}: ${s.stopReason} after ${s.iterations.length} iteration(s), $${s.spentUsd}\n`,
376
+ };
377
+ }
378
+ const id = positionals[0] || (sub === "status" ? latestLoop(env) : null);
379
+ if (!id || !/^[A-Za-z0-9-]+$/.test(id)) throw usage(`${sub} needs a loop id`);
380
+ const dir = join(loopsDir(env), id);
381
+ if (!existsSync(join(dir, "state.json")))
382
+ return { code: 3, text: "", err: `autopilot-loop: no loop ${id}\n` };
383
+ if (sub === "stop") {
384
+ writeFileSync(join(dir, "STOP"), `${new Date().toISOString()}\n`);
385
+ return { code: 0, text: `loop ${id} stops before its next iteration\n` };
386
+ }
387
+ const st = statusOf(dir);
388
+ return {
389
+ code: 0,
390
+ text: json
391
+ ? `${JSON.stringify(st, null, 2)}\n`
392
+ : `${st.id} ${st.status}${st.stopReason ? ` (${st.stopReason})` : ""}: ${st.iterations} iteration(s), $${st.spentUsd}${st.complete ? ", complete" : ""}${st.note ? `\n ${st.note}` : ""}\n`,
393
+ };
394
+ }
395
+
396
+ if (invokedDirectly(import.meta.url)) {
397
+ try {
398
+ const { code, text, err } = await main(process.argv.slice(2), process.env);
399
+ process.stdout.write(text);
400
+ if (err) process.stderr.write(err);
401
+ process.exitCode = code;
402
+ } catch (e) {
403
+ if (!(e instanceof ArgsError)) throw e;
404
+ process.stderr.write(`autopilot-loop: ${e.message}\n`);
405
+ process.exitCode = 2;
406
+ }
407
+ }
@@ -100,7 +100,7 @@ import {
100
100
  resolveRunFile,
101
101
  runDirCandidates,
102
102
  } from "./_run-paths.mjs";
103
- import { costUsd } from "./_cost.mjs";
103
+ import { trackerUsd } from "./_cost.mjs";
104
104
  import { configRefusal } from "./_autopilot-config.mjs";
105
105
  import {
106
106
  OUTCOME,
@@ -762,18 +762,7 @@ export function runUsd(runTaskId, statePath) {
762
762
  if (!trackerPath) return null;
763
763
  const tracker = readJson(trackerPath, null);
764
764
  const prices = readJson(join(import.meta.dirname, "cost-table.json"), null)?.prices;
765
- if (!tracker || !prices) return null;
766
- let usd = 0;
767
- let tokens = 0;
768
- for (const ph of Object.values(tracker.phases || {})) {
769
- const tin = Number(ph?.tokens_in || 0);
770
- const tout = Number(ph?.tokens_out || 0);
771
- const tcached = Number(ph?.tokens_cached || 0);
772
- if (!(tin + tout + tcached > 0)) continue;
773
- tokens += tin + tout + tcached;
774
- usd += costUsd(prices[ph?.model] || prices[CONSERVATIVE_PRICE], tin, tout, tcached) ?? 0;
775
- }
776
- return tokens > 0 ? Math.round(usd * 10000) / 10000 : null;
765
+ return trackerUsd(tracker, prices, CONSERVATIVE_PRICE);
777
766
  }
778
767
 
779
768
  /**
@@ -1197,11 +1186,18 @@ export function outcomeFor(supervised, state, prUrl) {
1197
1186
  * positional prompt (`--bg` refuses `--print`: the prompt is the positional,
1198
1187
  * and the CLI prints the session id and returns) - is pending a live launch
1199
1188
  * trial; everything that launches or describes a launch derives from here so
1200
- * a correction is one edit.
1189
+ * a correction is one edit. `print` starts the same launch in print mode,
1190
+ * which waits for the run to end: autopilot-loop judges each iteration from
1191
+ * the state the finished run left.
1201
1192
  */
1202
- export function launchArgv(item, sessionId, settingsFile = unattendedSettingsPath()) {
1193
+ export function launchArgv(
1194
+ item,
1195
+ sessionId,
1196
+ settingsFile = unattendedSettingsPath(),
1197
+ { print = false } = {},
1198
+ ) {
1203
1199
  return [
1204
- "--bg",
1200
+ print ? "-p" : "--bg",
1205
1201
  "--session-id",
1206
1202
  sessionId,
1207
1203
  "--permission-prompts",
@@ -1451,7 +1447,7 @@ export function sandboxPrecondition({
1451
1447
  }
1452
1448
 
1453
1449
  /** The checkout's HEAD commit, or null when it has none. */
1454
- function headSha(cwd) {
1450
+ export function headSha(cwd) {
1455
1451
  const r = spawnSync("git", ["-C", cwd, "rev-parse", "--verify", "--quiet", "HEAD^{commit}"], {
1456
1452
  encoding: "utf-8",
1457
1453
  stdio: ["ignore", "pipe", "ignore"],
@@ -1663,20 +1659,36 @@ function rebindSession(claim, item, sessionId) {
1663
1659
  * settings file it is launched with; the precondition then accepts the
1664
1660
  * child's argv and environment only with exactly those. A launch that starts
1665
1661
  * nothing removes both at once; otherwise `gradleHome` is returned for
1666
- * endRunHome.
1662
+ * endRunHome. `blocked` carries the reason whenever nothing was started.
1663
+ * timeoutMs and stdio serve a caller that waits for the whole run
1664
+ * (autopilot-loop launches in print mode); the defaults suit `--bg`.
1665
+ *
1666
+ * @param {(settingsFile: string) => string[]} argvFor
1667
+ * @param {string} cwd
1668
+ * @param {string} sessionId
1669
+ * @param {string|null} baseSha
1670
+ * @param {{timeoutMs?: number, stdio?: import("node:child_process").StdioOptions}} [opts]
1667
1671
  */
1668
- function launch(argvFor, cwd, sessionId, baseSha) {
1672
+ export function launch(
1673
+ argvFor,
1674
+ cwd,
1675
+ sessionId,
1676
+ baseSha,
1677
+ { timeoutMs = LAUNCH_TIMEOUT_MS, stdio } = {},
1678
+ ) {
1669
1679
  const sandbox = sandboxPrecondition({ cwd });
1670
1680
  if (!sandbox.ok)
1671
- return { status: 1, stderr: `${OUTCOME.BLOCKED_SANDBOX_UNAVAILABLE}: ${sandbox.reason}` };
1681
+ return {
1682
+ status: 1,
1683
+ stderr: `${OUTCOME.BLOCKED_SANDBOX_UNAVAILABLE}: ${sandbox.reason}`,
1684
+ blocked: sandbox.reason,
1685
+ };
1672
1686
  let prepared;
1673
1687
  try {
1674
1688
  prepared = prepareLaunch(sessionId, process.env, { sessions: () => listSessions(process.env) });
1675
1689
  } catch (err) {
1676
- return {
1677
- status: 1,
1678
- stderr: `the run's Gradle home could not be made: ${err.code || err.message}`,
1679
- };
1690
+ const reason = `the run's Gradle home could not be made: ${err.code || err.message}`;
1691
+ return { status: 1, stderr: reason, blocked: reason };
1680
1692
  }
1681
1693
  const r = startBackground({
1682
1694
  argv: argvFor(prepared.settingsFile || unattendedSettingsPath()),
@@ -1684,7 +1696,8 @@ function launch(argvFor, cwd, sessionId, baseSha) {
1684
1696
  env: launchEnv(sessionId, process.env, { baseSha, gradleEnv: prepared.gradleEnv }),
1685
1697
  precondition: (o) => sandboxPrecondition({ ...o, gradleHome: prepared.gradleHome }),
1686
1698
  bin: CLAUDE_BIN,
1687
- timeoutMs: LAUNCH_TIMEOUT_MS,
1699
+ timeoutMs,
1700
+ ...(stdio ? { stdio } : {}),
1688
1701
  });
1689
1702
  // A launcher that timed out may have left its session running.
1690
1703
  if (r.status !== 0 && r.error?.code !== "ETIMEDOUT")
@@ -10,13 +10,16 @@
10
10
  # 3. It prints at most a few lines. A session banner that scrolls is a banner
11
11
  # the user learns to skip, which costs more than it saves.
12
12
  #
13
- # It answers two questions:
13
+ # It answers three questions:
14
14
  # - Is there a pipeline run that stopped before Phase 5? Name it and the resume
15
15
  # command, because that run's work is recoverable and its findings are not
16
16
  # yet in the durable stores until it flushes.
17
17
  # - Is the pipeline's own observation queue stale? (>= REVIEW_DAYS since the
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
+ # - Is the disk nearly full? lib/low-disk.mjs answers with one statfs call
21
+ # and, when it is, one line naming /multi-agent:clean-disk. Nothing is
22
+ # deleted from here.
20
23
  #
21
24
  # Usage: ./capture-resume.sh [--json]
22
25
 
@@ -165,6 +168,11 @@ if [ "$REVIEW_DUE" -eq 1 ]; then
165
168
  "$OPEN_OBS" "$REVIEW_DAYS" "$(ma_command refactor)"
166
169
  fi
167
170
  fi
171
+ LOW_DISK="$_MA_CR_HERE/../lib/low-disk.mjs"
172
+ [ -f "$LOW_DISK" ] || LOW_DISK="$HOME/.claude/lib/low-disk.mjs"
173
+ if [ -f "$LOW_DISK" ] && command -v node >/dev/null 2>&1; then
174
+ node "$LOW_DISK" --lang "$LANG_CODE" 2>/dev/null || true
175
+ fi
168
176
  }
169
177
 
170
178
  # The host replaces SessionStart output past 10,000 characters with a stub, and
@@ -17,6 +17,10 @@
17
17
  * huge day inflates both and then hides itself)
18
18
  * burn - is the last 24h accelerating against the preceding week
19
19
  * diff - two saved snapshots, metric by metric
20
+ * advise - which lever to pull: cache-read ratio, 1-hour cache TTL
21
+ * payback, sub-agent rung, context size, unpriced models;
22
+ * each finding with its numbers and their source
23
+ * (_cost-advise.mjs)
20
24
  *
21
25
  * WHERE THE NUMBERS COME FROM, and what that makes them worth: the per-run
22
26
  * token accumulators in tracker-state.json are the pipeline's own ledger, but
@@ -35,14 +39,15 @@
35
39
  * cost-analyze.mjs anomaly [--days N] [--by day|session] [--threshold N]
36
40
  * cost-analyze.mjs burn [--factor N]
37
41
  * cost-analyze.mjs diff [a.json b.json]
42
+ * cost-analyze.mjs advise [--days N]
38
43
  * cost-analyze.mjs --save store a snapshot
39
44
  * cost-analyze.mjs --list what is stored
40
45
  * any subcommand plus --json
41
46
  *
42
47
  * Exit codes:
43
48
  * 0 nothing to report, or UNMEASURED (no series to read)
44
- * 10 a finding: an anomaly, an accelerating burn, or a budget that the
45
- * current rate exhausts inside the projection window
49
+ * 10 a finding: an anomaly, an accelerating burn, a budget that the
50
+ * current rate exhausts inside the projection window, or advice
46
51
  * 2 usage error
47
52
  */
48
53
 
@@ -54,7 +59,8 @@ import { modelRateLookup, priceUsage as priceRecord } from "./_cost.mjs";
54
59
  import { readJsonl } from "./_jsonl.mjs";
55
60
  import { runMain } from "../lib/fatal.mjs";
56
61
  import { messages, outputLanguage } from "../lib/user-facing.mjs";
57
- import { parseArgs } from "../lib/args.mjs";
62
+ import { parseArgs, unknownSubcommand } from "../lib/args.mjs";
63
+ import { advise, collectRows, personaTiers } from "./_cost-advise.mjs";
58
64
  import { exitOnHelp } from "../lib/cli-help.mjs";
59
65
 
60
66
  exitOnHelp(import.meta.url);
@@ -97,6 +103,13 @@ const REPORT = {
97
103
  perDayDiff: (from, to, delta) => ` a day ${from} -> ${to} (${delta})`,
98
104
  windowsDiffer: (a, b) =>
99
105
  ` ! different windows (${a} / ${b} days) - the daily rate compares, the total does not`,
106
+ adviceHead: (days, records, files) =>
107
+ `cost advice, last ${days} days: ${records} priced turns from ${files} transcripts`,
108
+ noAdvice: " nothing crosses a threshold",
109
+ saving: (v) => (v === null ? "saving n/a" : `up to ${v} over the window`),
110
+ evidence: "evidence",
111
+ action: "do",
112
+ whatIf: " savings reprice the same tokens at another rate; they do not predict quality",
100
113
  },
101
114
  tr: {
102
115
  rate: (days, total, observedDays, perDay) =>
@@ -125,6 +138,13 @@ const REPORT = {
125
138
  perDayDiff: (from, to, delta) => ` gunluk ${from} -> ${to} (${delta})`,
126
139
  windowsDiffer: (a, b) =>
127
140
  ` ! pencereler farkli (${a} / ${b} gun) - gunluk oran karsilastirilabilir, toplam degil`,
141
+ adviceHead: (days, records, files) =>
142
+ `maliyet tavsiyesi, son ${days} gun: ${files} transkriptten ${records} fiyatli tur`,
143
+ noAdvice: " esigi asan bulgu yok",
144
+ saving: (v) => (v === null ? "tasarruf hesaplanamaz" : `pencerede en fazla ${v}`),
145
+ evidence: "kanit",
146
+ action: "yapilacak",
147
+ whatIf: " tasarruf ayni tokenlarin baska fiyattan hesabidir; kaliteyi ongormez",
128
148
  },
129
149
  };
130
150
 
@@ -553,10 +573,46 @@ function cmdDiff(json) {
553
573
  }
554
574
  }
555
575
 
576
+ async function cmdAdvise(json) {
577
+ const days = asNumber(flags.days, 7);
578
+ const sinceMs = Date.now() - days * 86_400_000;
579
+ const data = await collectRows(TRANSCRIPT_ROOT, { sinceMs });
580
+ if (!data.records.length)
581
+ return unmeasured(`no usage records in the last ${days} days under ${TRANSCRIPT_ROOT}`, json);
582
+ const source = {
583
+ transcripts: TRANSCRIPT_ROOT,
584
+ files: data.files,
585
+ records: data.records.length,
586
+ windowDays: days,
587
+ priceTable: join(HERE, "cost-table.json"),
588
+ };
589
+ const findings = advise(data.records, {
590
+ table: TABLE,
591
+ personas: personaTiers(join(HERE, "..", "agents")),
592
+ source,
593
+ });
594
+ if (json) {
595
+ process.stdout.write(`${JSON.stringify({ kind: "advise", source, findings }, null, 2)}\n`);
596
+ } else {
597
+ process.stdout.write(`${say.adviceHead(days, data.records.length, data.files)}\n`);
598
+ if (!findings.length) process.stdout.write(`${say.noAdvice}\n`);
599
+ findings.forEach((f, i) => {
600
+ process.stdout.write(
601
+ `${i + 1}. ${f.title} - ${say.saving(f.savingUsd === null ? null : usd(f.savingUsd))}\n` +
602
+ ` ${say.evidence}: ${JSON.stringify(f.numbers)}\n` +
603
+ ` ${say.action}: ${f.action}\n`,
604
+ );
605
+ });
606
+ process.stdout.write(`${say.whatIf}\n`);
607
+ }
608
+ if (findings.length) process.exitCode = 10;
609
+ }
610
+
556
611
  // --- main --------------------------------------------------------------------
557
612
 
558
613
  const json = flags.json === true || flags.json === "true";
559
614
  const sub = positional[0];
615
+ const SUBCOMMANDS = ["projection", "anomaly", "burn", "diff", "advise"];
560
616
 
561
617
  const run = async () => {
562
618
  if (flags.save) return cmdSave(json);
@@ -570,8 +626,14 @@ const run = async () => {
570
626
  return cmdBurn(json);
571
627
  case "diff":
572
628
  return cmdDiff(json);
629
+ case "advise":
630
+ return cmdAdvise(json);
631
+ case undefined:
632
+ return die(
633
+ "usage: cost-analyze.mjs projection|anomaly|burn|diff|advise [--json] | --save | --list",
634
+ );
573
635
  default:
574
- return die("usage: cost-analyze.mjs projection|anomaly|burn|diff [--json] | --save | --list");
636
+ return die(unknownSubcommand(sub, SUBCOMMANDS).message);
575
637
  }
576
638
  };
577
639