@mmerterden/multi-agent-pipeline 20.40.0 → 20.42.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 (143) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/README.tr.md +5 -2
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +51 -14
  7. package/docs/facts.json +7 -7
  8. package/docs/features.md +15 -4
  9. package/install/claude.mjs +45 -3
  10. package/install/templates/claude-hooks.json +23 -1
  11. package/manifest.json +146 -107
  12. package/package.json +3 -2
  13. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  14. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/contract/types/index.d.ts +53 -49
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/context-budget.mjs +5 -42
  20. package/pipeline/lib/credential-store.sh +11 -1
  21. package/pipeline/lib/hook-once.mjs +134 -0
  22. package/pipeline/lib/hook-registration.mjs +5 -0
  23. package/pipeline/lib/isotonic.mjs +73 -0
  24. package/pipeline/lib/low-disk.mjs +153 -0
  25. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  26. package/pipeline/lib/md2confluence-v3.py +19 -10
  27. package/pipeline/lib/model-dispatch.sh +26 -2
  28. package/pipeline/lib/normalize-text.mjs +135 -0
  29. package/pipeline/lib/outbound-gate.mjs +21 -3
  30. package/pipeline/lib/plan-todos.sh +17 -4
  31. package/pipeline/lib/redact.mjs +12 -3
  32. package/pipeline/lib/risky-settings.mjs +198 -0
  33. package/pipeline/lib/route-state.sh +1 -0
  34. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  35. package/pipeline/lib/session-usage.mjs +232 -0
  36. package/pipeline/lib/source-digest.mjs +211 -0
  37. package/pipeline/lib/tdd-evidence.mjs +250 -17
  38. package/pipeline/lib/tiered-budget.mjs +87 -0
  39. package/pipeline/lib/untrusted-fence.mjs +132 -1
  40. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  41. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  42. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  43. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  44. package/pipeline/multi-agent-refs/features/doctor.md +82 -4
  45. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  46. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  47. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  48. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  49. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  50. package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
  51. package/pipeline/multi-agent-refs/help/en.md +2 -1
  52. package/pipeline/multi-agent-refs/help/tr.md +2 -1
  53. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  54. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  55. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  56. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
  57. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  58. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  59. package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
  60. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  61. package/pipeline/office/index.html +13 -7
  62. package/pipeline/office/toolkit.json +1 -1
  63. package/pipeline/preferences-template.json +1 -0
  64. package/pipeline/rules/outside-the-pipeline.md +1 -1
  65. package/pipeline/schemas/doctor-report.schema.json +47 -0
  66. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  67. package/pipeline/schemas/office-archive.schema.json +225 -128
  68. package/pipeline/schemas/plan-todos.schema.json +29 -1
  69. package/pipeline/schemas/prefs.schema.json +146 -0
  70. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  71. package/pipeline/schemas/product-tree.schema.json +136 -0
  72. package/pipeline/schemas/route-config.schema.json +51 -0
  73. package/pipeline/schemas/secret-patterns.json +17 -1
  74. package/pipeline/schemas/toolkit-path-params.json +15 -1
  75. package/pipeline/scripts/_cost-advise.mjs +357 -0
  76. package/pipeline/scripts/_cost-budget.mjs +78 -0
  77. package/pipeline/scripts/_cost.mjs +29 -0
  78. package/pipeline/scripts/_decode_text.py +107 -0
  79. package/pipeline/scripts/_eval-stats.mjs +182 -0
  80. package/pipeline/scripts/_guard-probe.mjs +406 -0
  81. package/pipeline/scripts/_guard_rules.py +336 -1
  82. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  83. package/pipeline/scripts/_locate.mjs +539 -0
  84. package/pipeline/scripts/_memory-policy.mjs +208 -33
  85. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  86. package/pipeline/scripts/_product-tree.mjs +923 -0
  87. package/pipeline/scripts/_retrieval.mjs +161 -4
  88. package/pipeline/scripts/_secret-scan.mjs +6 -1
  89. package/pipeline/scripts/_stack-routing.mjs +2 -0
  90. package/pipeline/scripts/_test-gaming.mjs +346 -0
  91. package/pipeline/scripts/_user_guard_rules.py +744 -0
  92. package/pipeline/scripts/agent-guard.py +69 -6
  93. package/pipeline/scripts/agent-guard.sh +8 -1
  94. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  95. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  96. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  97. package/pipeline/scripts/capture-resume.sh +9 -1
  98. package/pipeline/scripts/cost-analyze.mjs +66 -4
  99. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  100. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/scripts/doctor.mjs +324 -43
  102. package/pipeline/scripts/evidence-gate.mjs +90 -0
  103. package/pipeline/scripts/gate-ledger.mjs +76 -21
  104. package/pipeline/scripts/gc-tmp.sh +5 -0
  105. package/pipeline/scripts/graph-query.mjs +257 -17
  106. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  107. package/pipeline/scripts/learnings-ledger.mjs +680 -55
  108. package/pipeline/scripts/note-agent-event.mjs +2 -0
  109. package/pipeline/scripts/note-mcp-failure.mjs +363 -0
  110. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  111. package/pipeline/scripts/note-skill-use.mjs +96 -23
  112. package/pipeline/scripts/office-archive.mjs +23 -10
  113. package/pipeline/scripts/office-memory.mjs +4 -1
  114. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  115. package/pipeline/scripts/pre-commit-check.sh +2 -2
  116. package/pipeline/scripts/pre-push-check.sh +8 -1
  117. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  118. package/pipeline/scripts/product-tree.mjs +544 -0
  119. package/pipeline/scripts/publish-staged.mjs +324 -0
  120. package/pipeline/scripts/route-learn.mjs +628 -0
  121. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  122. package/pipeline/scripts/scan-agent-config.sh +1 -1
  123. package/pipeline/scripts/statusline.mjs +309 -0
  124. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  125. package/pipeline/scripts/triage-memory.mjs +12 -4
  126. package/pipeline/scripts/uninstall.mjs +1 -0
  127. package/pipeline/skills/.skill-manifest.json +15 -7
  128. package/pipeline/skills/.skills-index.json +25 -3
  129. package/pipeline/skills/shared/README.md +6 -4
  130. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  131. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  132. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  133. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  134. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  135. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  136. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  137. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  138. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  139. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  140. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  141. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  142. package/pipeline/skills/skill-copies.json +9 -1
  143. package/pipeline/skills/skills-index.md +4 -2
@@ -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 the disk-cleaner skill. 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
 
@@ -37,7 +37,7 @@
37
37
  import { readFileSync, existsSync } from "fs";
38
38
  import { dirname, join } from "path";
39
39
  import { fileURLToPath } from "url";
40
- import { costUsd } from "./_cost.mjs";
40
+ import { budgetLevel, trackerSpend } from "./_cost-budget.mjs";
41
41
  import { resolveRunFile } from "./_run-paths.mjs";
42
42
  import { parseArgs } from "../lib/args.mjs";
43
43
  import { helpRequested } from "../lib/cli-help.mjs";
@@ -117,16 +117,8 @@ const costTable = JSON.parse(readFileSync(join(__dirname, "cost-table.json"), "u
117
117
  const rate = costTable.prices?.[cfg.pricingModel];
118
118
  if (!rate) die(`no price for model "${cfg.pricingModel}" in cost-table.json`);
119
119
 
120
- let tokensIn = 0;
121
- let tokensOut = 0;
122
- let tokensCached = 0;
123
- for (const p of Object.values(tracker.phases || {})) {
124
- tokensIn += Number(p?.tokens_in || 0);
125
- tokensOut += Number(p?.tokens_out || 0);
126
- tokensCached += Number(p?.tokens_cached || 0);
127
- }
128
-
129
- const usd = costUsd(rate, tokensIn, tokensOut, tokensCached);
120
+ const { usd, tokensIn, tokensOut, tokensCached } = trackerSpend(tracker, rate);
121
+ const level = budgetLevel(usd, cfg);
130
122
  const pctOfMax = (usd / cfg.maxUsd) * 100;
131
123
  const usdStr = `$${usd.toFixed(2)}`;
132
124
  const totalTok = tokensIn + tokensOut + tokensCached;
@@ -135,13 +127,13 @@ const base =
135
127
  `cost-budget: ${usdStr} of $${cfg.maxUsd.toFixed(2)} ` +
136
128
  `(${pctOfMax.toFixed(0)}%, ${totalTok.toLocaleString("en-US")} tok @ ${cfg.pricingModel})`;
137
129
 
138
- if (usd > cfg.maxUsd) {
130
+ if (level === "exceeded") {
139
131
  const action =
140
132
  cfg.onExceed === "halt" ? "HALT - run multi-agent:resume to continue" : "over budget";
141
133
  process.stdout.write(`EXCEEDED: ${base} - ${action}\n`);
142
134
  process.exit(11);
143
135
  }
144
- if (pctOfMax >= cfg.warnPct) {
136
+ if (level === "warn") {
145
137
  process.stdout.write(`WARN: ${base} - approaching ceiling\n`);
146
138
  process.exit(10);
147
139
  }