@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,628 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * route-learn.mjs - learn which model rung to try first from how runs
4
+ * actually turned out, and change routing only after the learned policy has
5
+ * beaten the current one on runs it did not see.
6
+ *
7
+ * Off unless prefs.global.modelRouting.learned.enabled is true (and routing
8
+ * itself is on); model-dispatch.sh asks `choose` only then. The rest of the
9
+ * object tunes it: `learned.minSamples` (20), `learned.target` (0.8),
10
+ * `learned.halfLifeDays` (60), `learned.explore` (false), and for promote
11
+ * `learned.holdout` (0.25), `learned.minRows` (10) and `learned.margin`
12
+ * (0.005); route-config.schema.json says what each one changes.
13
+ *
14
+ * REWARD comes from objective signals the pipeline records, never from what a
15
+ * model says about its own work:
16
+ *
17
+ * gates the latest verdict per gate in the run's state.gates[]
18
+ * blockers blocking findings in the first review round
19
+ * stillPresent findings review-delta.mjs saw survive into the last round
20
+ * rework review rounds after the first
21
+ *
22
+ * reward = 0 when any gate's latest verdict is fail, else
23
+ * 1 / (1 + blockers + stillPresent + rework)
24
+ *
25
+ * A row with no gate verdict and no review count has no reward and is refused.
26
+ *
27
+ * POLICY. Per bucket (call site, task kind, complexity band) and rung, a
28
+ * Beta(1 + successes, 1 + failures) posterior over the reward, each outcome
29
+ * weighted 0.5^(age / halfLifeDays) so old evidence fades. `choose` draws one
30
+ * sample per rung (Thompson sampling, seeded so the same task gets the same
31
+ * answer and tests are deterministic) and orders the rungs: those whose draw
32
+ * clears `target` cheapest first, then the rest by draw. A rung whose last
33
+ * three outcomes all scored 0 goes last, except on one draw in ten, so a rung
34
+ * that recovered can earn its place back (a breaker that never re-closes
35
+ * would freeze the policy on its last bad streak). While any candidate has fewer than
36
+ * `minSamples` outcomes in the bucket the rule's own order stands, unless
37
+ * `explore` is on, in which case a cold rung is drawn from its prior.
38
+ *
39
+ * PROMOTION. `promote` splits the outcomes by time, fits a candidate on the
40
+ * older part, calibrates its posterior means against those outcomes with
41
+ * isotonic regression (lib/isotonic.mjs), and scores it on the newer part by
42
+ * Brier score against the current policy (or, with none, the training
43
+ * part's overall rate). Only a candidate better by `--margin` over at least
44
+ * `--min-rows` holdout rows is refitted on everything and written, atomically
45
+ * and under a lock, with the previous policy kept as policy.json.bak.
46
+ * `choose` reads only the promoted policy, never the raw outcomes.
47
+ *
48
+ * Usage:
49
+ * route-learn.mjs record --rung R [--state <agent-state.json>] [--task-id ID]
50
+ * [--call-site S] [--task-kind K] [--complexity N] [--files N]
51
+ * [--gate-pass N] [--gate-fail N] [--blockers N]
52
+ * [--still-present N] [--rework N]
53
+ * route-learn.mjs ingest --state <agent-state.json> [--metrics <metrics.jsonl>]
54
+ * [--complexity N] [--files N]
55
+ * route-learn.mjs train [--json]
56
+ * route-learn.mjs promote [--holdout 0.25] [--min-rows 10] [--margin 0.005] [--json]
57
+ * route-learn.mjs choose --candidates "a b c" [--bucket B | --call-site S
58
+ * --task-kind K --complexity N --files N]
59
+ * [--task-id ID] [--seed S] [--json]
60
+ * route-learn.mjs status [--json]
61
+ *
62
+ * `ingest` reads the model_routing.decision events model-dispatch.sh logged
63
+ * for the run's task id and writes one row per (call site, rung) it used,
64
+ * each with the run's reward; a row already recorded is not written twice.
65
+ *
66
+ * Files: $ROUTE_LEARN_DIR or ~/.claude/state/route-learn/ holding
67
+ * outcomes.jsonl, policy.json and policy.json.bak.
68
+ *
69
+ * Exit: 0 done (choose always exits 0 and prints a usable order);
70
+ * 10 promote kept the current policy; 2 usage error or no objective signal.
71
+ */
72
+
73
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
74
+ import { homedir } from "node:os";
75
+ import { join } from "node:path";
76
+
77
+ import { ArgsError, parseArgs, unknownSubcommand } from "../lib/args.mjs";
78
+ import { exitOnHelp } from "../lib/cli-help.mjs";
79
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
80
+ import { applyIsotonic, fitIsotonic } from "../lib/isotonic.mjs";
81
+ import { withFileLockSync, writeJsonAtomicSync } from "../lib/json-file-lock.mjs";
82
+ import { loadGlobalPrefs, prefsPath } from "../lib/prefs-value.mjs";
83
+ import { readRegularJson } from "../lib/regular-file.mjs";
84
+
85
+ exitOnHelp(import.meta.url);
86
+
87
+ const DAY_MS = 86_400_000;
88
+ const PASSING = new Set(["pass", "not-applicable"]);
89
+ const BREAKER = 3;
90
+ const HALF_OPEN = 0.1;
91
+ export const DEFAULTS = {
92
+ minSamples: 20,
93
+ target: 0.8,
94
+ halfLifeDays: 60,
95
+ explore: false,
96
+ holdout: 0.25,
97
+ minRows: 10,
98
+ margin: 0.005,
99
+ };
100
+
101
+ const count = (v) => {
102
+ const n = Number(v);
103
+ return Number.isFinite(n) && n >= 0 ? n : null;
104
+ };
105
+
106
+ /**
107
+ * The reward of one run, from objective signals; null when there are none.
108
+ *
109
+ * @param {{gatePass?: number, gateFail?: number, blockers?: number, stillPresent?: number, rework?: number}} s
110
+ * @returns {number|null}
111
+ */
112
+ export function rewardOf(s) {
113
+ const gates = (count(s.gatePass) ?? 0) + (count(s.gateFail) ?? 0);
114
+ const review = ["blockers", "stillPresent", "rework"].some((k) => count(s[k]) !== null);
115
+ if (!gates && !review) return null;
116
+ if ((count(s.gateFail) ?? 0) > 0) return 0;
117
+ return 1 / (1 + (count(s.blockers) ?? 0) + (count(s.stillPresent) ?? 0) + (count(s.rework) ?? 0));
118
+ }
119
+
120
+ /** The objective signals an agent-state.json carries. */
121
+ export function signalsFromState(state) {
122
+ const latest = new Map();
123
+ for (const g of Array.isArray(state?.gates) ? state.gates : []) {
124
+ if (!g || typeof g.gate !== "string") continue;
125
+ const prev = latest.get(g.gate);
126
+ if (!prev || (Date.parse(g.at) || 0) >= (Date.parse(prev.at) || 0)) latest.set(g.gate, g);
127
+ }
128
+ const verdicts = [...latest.values()].map((g) => g.verdict);
129
+ const rounds = Array.isArray(state?.reviewIterations) ? state.reviewIterations : [];
130
+ const out = {
131
+ gatePass: verdicts.filter((v) => PASSING.has(v)).length,
132
+ gateFail: verdicts.filter((v) => !PASSING.has(v)).length,
133
+ };
134
+ if (rounds.length) {
135
+ const last = rounds[rounds.length - 1];
136
+ out.blockers = count(rounds[0]?.blocking) ?? 0;
137
+ out.stillPresent = Array.isArray(last?.delta?.stillPresent)
138
+ ? last.delta.stillPresent.length
139
+ : 0;
140
+ out.rework = rounds.length - 1;
141
+ }
142
+ return out;
143
+ }
144
+
145
+ /** "<call site>:<task kind>:<band>", the band from complexity or file count. */
146
+ export function bucketOf({ callSite, taskKind, complexity, files } = {}) {
147
+ const c = Number(complexity);
148
+ const f = Number(files);
149
+ let band = "any";
150
+ if (complexity !== undefined && complexity !== null && Number.isFinite(c) && c > 0) {
151
+ band = c <= 3 ? "low" : c <= 6 ? "mid" : "high";
152
+ } else if (files !== undefined && files !== null && Number.isFinite(f) && f > 0) {
153
+ band = f <= 2 ? "low" : f <= 8 ? "mid" : "high";
154
+ }
155
+ return `${callSite || "any"}:${taskKind || "any"}:${band}`;
156
+ }
157
+
158
+ /** mulberry32 seeded from an FNV-1a hash of `seed`: uniform draws in [0, 1). */
159
+ export function makeRng(seed) {
160
+ let h = 0x811c9dc5;
161
+ for (const ch of String(seed)) h = Math.imul(h ^ ch.charCodeAt(0), 0x01000193) >>> 0;
162
+ let a = h || 1;
163
+ return () => {
164
+ a = (a + 0x6d2b79f5) >>> 0;
165
+ let t = a;
166
+ t = Math.imul(t ^ (t >>> 15), t | 1);
167
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
168
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
169
+ };
170
+ }
171
+
172
+ function normal(rng) {
173
+ const u = Math.max(rng(), Number.EPSILON);
174
+ return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rng());
175
+ }
176
+
177
+ /** Gamma(shape, 1) by Marsaglia and Tsang, boosted below shape 1. */
178
+ function sampleGamma(shape, rng) {
179
+ if (shape < 1)
180
+ return sampleGamma(shape + 1, rng) * Math.pow(Math.max(rng(), Number.EPSILON), 1 / shape);
181
+ const d = shape - 1 / 3;
182
+ const c = 1 / Math.sqrt(9 * d);
183
+ for (;;) {
184
+ let x;
185
+ let v;
186
+ do {
187
+ x = normal(rng);
188
+ v = 1 + c * x;
189
+ } while (v <= 0);
190
+ v = v * v * v;
191
+ const u = rng();
192
+ if (u < 1 - 0.0331 * x ** 4 || Math.log(u) < 0.5 * x * x + d * (1 - v + Math.log(v)))
193
+ return d * v;
194
+ }
195
+ }
196
+
197
+ /** One draw from Beta(alpha, beta). */
198
+ export function sampleBeta(alpha, beta, rng) {
199
+ const x = sampleGamma(alpha, rng);
200
+ const y = sampleGamma(beta, rng);
201
+ return x + y > 0 ? x / (x + y) : 0.5;
202
+ }
203
+
204
+ /**
205
+ * Posteriors per bucket and rung from outcome rows.
206
+ *
207
+ * @param {{ts: string, bucket: string, rung: string, reward: number}[]} rows
208
+ * @param {{halfLifeDays?: number, now?: number}} [opts]
209
+ */
210
+ export function fitPolicy(rows, { halfLifeDays = DEFAULTS.halfLifeDays, now = Date.now() } = {}) {
211
+ const buckets = {};
212
+ const sorted = [...rows].sort((a, b) => (Date.parse(a.ts) || 0) - (Date.parse(b.ts) || 0));
213
+ for (const r of sorted) {
214
+ if (typeof r?.bucket !== "string" || typeof r?.rung !== "string") continue;
215
+ const reward = Number(r.reward);
216
+ if (!Number.isFinite(reward) || reward < 0 || reward > 1) continue;
217
+ const age = Math.max(0, now - (Date.parse(r.ts) || now)) / DAY_MS;
218
+ const w = Math.pow(0.5, age / Math.max(1, halfLifeDays));
219
+ const b = (buckets[r.bucket] ??= Object.create(null));
220
+ const s = (b[r.rung] ??= { alpha: 1, beta: 1, n: 0, recentFails: 0 });
221
+ s.alpha += w * reward;
222
+ s.beta += w * (1 - reward);
223
+ s.n += 1;
224
+ s.recentFails = reward === 0 ? s.recentFails + 1 : 0;
225
+ }
226
+ for (const b of Object.values(buckets)) {
227
+ for (const s of Object.values(b)) {
228
+ s.alpha = Number(s.alpha.toFixed(6));
229
+ s.beta = Number(s.beta.toFixed(6));
230
+ s.mean = Number((s.alpha / (s.alpha + s.beta)).toFixed(6));
231
+ }
232
+ }
233
+ return { version: 1, fittedRows: sorted.length, buckets, calibration: null };
234
+ }
235
+
236
+ /**
237
+ * The rule's candidates, reordered by the policy.
238
+ *
239
+ * @param {{policy: object|null, bucket: string, candidates: string[], prices: Record<string, {inPerMtok?: number}>,
240
+ * seed: string, minSamples?: number, target?: number, explore?: boolean}} args
241
+ * @returns {{order: string[], reason: "no-policy"|"cold"|"learned", draws?: Record<string, number>}}
242
+ */
243
+ export function choose({
244
+ policy,
245
+ bucket,
246
+ candidates,
247
+ prices = {},
248
+ seed,
249
+ minSamples = DEFAULTS.minSamples,
250
+ target = DEFAULTS.target,
251
+ explore = DEFAULTS.explore,
252
+ }) {
253
+ const list = [...new Set(candidates)];
254
+ if (list.length < 2) return { order: list, reason: "learned" };
255
+ const stats = policy?.buckets?.[bucket];
256
+ if (!policy) return { order: list, reason: "no-policy" };
257
+ const warm = (r) => stats?.[r] && stats[r].n >= minSamples;
258
+ const ranked = explore ? list : list.filter(warm);
259
+ if (ranked.length < 2) return { order: list, reason: "cold" };
260
+ const rng = makeRng(`${seed}|${bucket}|${list.join(",")}`);
261
+ const draws = {};
262
+ for (const r of ranked) {
263
+ const s = stats?.[r] || { alpha: 1, beta: 1 };
264
+ draws[r] = applyIsotonic(policy.calibration, sampleBeta(s.alpha, s.beta, rng));
265
+ }
266
+ const price = (r) => Number(prices[r]?.inPerMtok ?? Infinity);
267
+ const tripped = new Set(
268
+ ranked.filter((r) => (stats?.[r]?.recentFails ?? 0) >= BREAKER && rng() >= HALF_OPEN),
269
+ );
270
+ const broken = (r) => tripped.has(r);
271
+ const live = ranked.filter((r) => !broken(r));
272
+ const clear = live.filter((r) => draws[r] >= target).sort((a, b) => price(a) - price(b));
273
+ const rest = live
274
+ .filter((r) => draws[r] < target)
275
+ .sort((a, b) => draws[b] - draws[a] || list.indexOf(a) - list.indexOf(b));
276
+ const order = [
277
+ ...clear,
278
+ ...rest,
279
+ ...ranked.filter(broken),
280
+ ...list.filter((r) => !ranked.includes(r)),
281
+ ];
282
+ return {
283
+ order,
284
+ reason: "learned",
285
+ draws: Object.fromEntries(Object.entries(draws).map(([k, v]) => [k, Number(v.toFixed(4))])),
286
+ };
287
+ }
288
+
289
+ function predictor(policy, fallback) {
290
+ return (row) => {
291
+ const s = policy?.buckets?.[row.bucket]?.[row.rung];
292
+ if (!s) return fallback;
293
+ return applyIsotonic(policy.calibration, s.alpha / (s.alpha + s.beta));
294
+ };
295
+ }
296
+
297
+ const brier = (rows, predict) =>
298
+ rows.reduce((a, r) => a + (predict(r) - Number(r.reward)) ** 2, 0) / (rows.length || 1);
299
+
300
+ function calibrated(policy, rows) {
301
+ const predict = predictor(policy, 0.5);
302
+ return {
303
+ ...policy,
304
+ calibration: fitIsotonic(
305
+ rows.map((r) => {
306
+ const s = policy.buckets[r.bucket]?.[r.rung];
307
+ return s ? s.alpha / (s.alpha + s.beta) : predict(r);
308
+ }),
309
+ rows.map((r) => Number(r.reward)),
310
+ ),
311
+ };
312
+ }
313
+
314
+ /**
315
+ * Whether a policy fitted on the outcomes should replace `current`.
316
+ *
317
+ * @returns {{promote: boolean, reason: string, metric?: object, policy?: object}}
318
+ */
319
+ export function decidePromotion(rows, current, opts = {}) {
320
+ const o = { ...DEFAULTS, now: Date.now(), ...opts };
321
+ const sorted = [...rows]
322
+ .filter((r) => Number.isFinite(Number(r?.reward)))
323
+ .sort((a, b) => (Date.parse(a.ts) || 0) - (Date.parse(b.ts) || 0));
324
+ const cut = Math.floor(sorted.length * (1 - o.holdout));
325
+ const train = sorted.slice(0, cut);
326
+ const holdout = sorted.slice(cut);
327
+ if (holdout.length < o.minRows || !train.length) {
328
+ return {
329
+ promote: false,
330
+ reason: `${holdout.length} holdout rows from ${sorted.length}; at least ${o.minRows} are needed`,
331
+ };
332
+ }
333
+ const fitOpts = { halfLifeDays: o.halfLifeDays, now: o.now };
334
+ const candidate = calibrated(fitPolicy(train, fitOpts), train);
335
+ const base = train.reduce((a, r) => a + Number(r.reward), 0) / train.length;
336
+ const candidateBrier = brier(holdout, predictor(candidate, base));
337
+ const currentBrier = brier(holdout, predictor(current, base));
338
+ const metric = {
339
+ trainRows: train.length,
340
+ holdoutRows: holdout.length,
341
+ candidateBrier: Number(candidateBrier.toFixed(6)),
342
+ currentBrier: Number(currentBrier.toFixed(6)),
343
+ against: current ? "current policy" : "training rate",
344
+ margin: o.margin,
345
+ };
346
+ if (candidateBrier > currentBrier - o.margin) {
347
+ return {
348
+ promote: false,
349
+ reason: `candidate Brier ${metric.candidateBrier} is not below ${metric.currentBrier} by the margin ${o.margin}`,
350
+ metric,
351
+ };
352
+ }
353
+ const policy = {
354
+ ...calibrated(fitPolicy(sorted, fitOpts), sorted),
355
+ promotedAt: new Date(o.now).toISOString(),
356
+ metric,
357
+ };
358
+ return { promote: true, reason: "candidate beat the holdout comparison", metric, policy };
359
+ }
360
+
361
+ // --- files -------------------------------------------------------------------
362
+
363
+ const storeDir = (env = process.env) =>
364
+ env.ROUTE_LEARN_DIR || join(env.HOME || homedir(), ".claude", "state", "route-learn");
365
+
366
+ function readRows(file) {
367
+ if (!existsSync(file)) return [];
368
+ const out = [];
369
+ for (const line of readFileSync(file, "utf8").split("\n")) {
370
+ if (!line.trim()) continue;
371
+ try {
372
+ out.push(JSON.parse(line));
373
+ } catch {
374
+ /* a torn line is skipped, never fatal */
375
+ }
376
+ }
377
+ return out;
378
+ }
379
+
380
+ function learnedPrefs(env) {
381
+ try {
382
+ return { ...DEFAULTS, ...(loadGlobalPrefs(prefsPath(env)).modelRouting?.learned || {}) };
383
+ } catch {
384
+ return { ...DEFAULTS };
385
+ }
386
+ }
387
+
388
+ function prices() {
389
+ return readRegularJson(join(import.meta.dirname, "cost-table.json"), null)?.prices || {};
390
+ }
391
+
392
+ // --- commands ----------------------------------------------------------------
393
+
394
+ const NUMERIC = ["gate-pass", "gate-fail", "blockers", "still-present", "rework"];
395
+
396
+ function cmdRecord(flags, env) {
397
+ if (!flags.rung)
398
+ throw new ArgsError("record needs --rung", { kind: "missing-value", token: "--rung" });
399
+ const state = flags.state ? readRegularJson(flags.state, null) : null;
400
+ if (flags.state && !state)
401
+ throw new ArgsError(`--state ${flags.state} is not readable JSON`, {
402
+ kind: "unexpected",
403
+ token: flags.state,
404
+ });
405
+ const signals = state ? signalsFromState(state) : {};
406
+ const keys = {
407
+ "gate-pass": "gatePass",
408
+ "gate-fail": "gateFail",
409
+ "still-present": "stillPresent",
410
+ };
411
+ for (const f of NUMERIC) if (flags[f] !== undefined) signals[keys[f] || f] = Number(flags[f]);
412
+ const reward = rewardOf(signals);
413
+ if (reward === null) {
414
+ throw new ArgsError(
415
+ "no objective signal: give --state with gates or review rounds, or gate and review counts",
416
+ {
417
+ kind: "unexpected",
418
+ token: "record",
419
+ },
420
+ );
421
+ }
422
+ const row = {
423
+ ts: new Date().toISOString(),
424
+ taskId: flags["task-id"] || state?.taskId || "unknown",
425
+ bucket: bucketOf({
426
+ callSite: flags["call-site"] || "subagent",
427
+ taskKind: flags["task-kind"] || state?.taskType,
428
+ complexity: flags.complexity,
429
+ files: flags.files,
430
+ }),
431
+ rung: flags.rung,
432
+ reward: Number(reward.toFixed(6)),
433
+ signals,
434
+ };
435
+ const dir = storeDir(env);
436
+ mkdirSync(dir, { recursive: true });
437
+ appendFileSync(join(dir, "outcomes.jsonl"), `${JSON.stringify(row)}\n`);
438
+ return `recorded ${row.bucket} ${row.rung} reward ${row.reward}\n`;
439
+ }
440
+
441
+ function cmdIngest(flags, env) {
442
+ const state = flags.state ? readRegularJson(flags.state, null) : null;
443
+ if (!state)
444
+ throw new ArgsError("ingest needs a readable --state", {
445
+ kind: "missing-value",
446
+ token: "--state",
447
+ });
448
+ const reward = rewardOf(signalsFromState(state));
449
+ if (reward === null) {
450
+ throw new ArgsError("no objective signal in the run's state", {
451
+ kind: "unexpected",
452
+ token: "ingest",
453
+ });
454
+ }
455
+ const metrics =
456
+ flags.metrics ||
457
+ env.METRICS_FILE ||
458
+ join(
459
+ env.LOGS_ROOT || join(env.HOME || homedir(), ".claude", "logs", "multi-agent"),
460
+ "metrics.jsonl",
461
+ );
462
+ const taskId = String(state.taskId || "");
463
+ const used = new Map();
464
+ for (const ev of readRows(metrics)) {
465
+ if (ev?.event !== "model_routing.decision" || String(ev.task_id) !== taskId) continue;
466
+ const cs = ev.details?.call_site;
467
+ const rung = ev.details?.rung;
468
+ if (typeof cs === "string" && typeof rung === "string") used.set(`${cs}|${rung}`, { cs, rung });
469
+ }
470
+ const dir = storeDir(env);
471
+ mkdirSync(dir, { recursive: true });
472
+ const file = join(dir, "outcomes.jsonl");
473
+ const seen = new Set(readRows(file).map((r) => `${r.taskId}|${r.bucket}|${r.rung}`));
474
+ let written = 0;
475
+ for (const { cs, rung } of used.values()) {
476
+ const bucket = bucketOf({
477
+ callSite: cs,
478
+ taskKind: state.taskType,
479
+ complexity: flags.complexity,
480
+ files: flags.files,
481
+ });
482
+ if (seen.has(`${taskId}|${bucket}|${rung}`)) continue;
483
+ appendFileSync(
484
+ file,
485
+ `${JSON.stringify({ ts: new Date().toISOString(), taskId, bucket, rung, reward: Number(reward.toFixed(6)), signals: signalsFromState(state) })}\n`,
486
+ );
487
+ written += 1;
488
+ }
489
+ return `ingested ${written} row(s) for ${taskId} from ${used.size} routing decision(s)\n`;
490
+ }
491
+
492
+ function cmdPromote(flags, env, json) {
493
+ const p = learnedPrefs(env);
494
+ const dir = storeDir(env);
495
+ const policyFile = join(dir, "policy.json");
496
+ const opts = {
497
+ halfLifeDays: p.halfLifeDays,
498
+ holdout: Number(flags.holdout ?? p.holdout),
499
+ minRows: Number(flags["min-rows"] ?? p.minRows),
500
+ margin: Number(flags.margin ?? p.margin),
501
+ };
502
+ if (!(opts.holdout > 0 && opts.holdout < 1))
503
+ throw new ArgsError("--holdout takes a fraction between 0 and 1", {
504
+ kind: "unexpected",
505
+ token: "--holdout",
506
+ });
507
+ mkdirSync(dir, { recursive: true });
508
+ const d = withFileLockSync(policyFile, () => {
509
+ const current = readRegularJson(policyFile, null);
510
+ const decision = decidePromotion(readRows(join(dir, "outcomes.jsonl")), current, opts);
511
+ if (decision.promote) {
512
+ if (current) copyFileSync(policyFile, `${policyFile}.bak`);
513
+ writeJsonAtomicSync(policyFile, decision.policy);
514
+ }
515
+ return decision;
516
+ });
517
+ const out = { promoted: d.promote, reason: d.reason, metric: d.metric ?? null };
518
+ return {
519
+ code: d.promote ? 0 : 10,
520
+ text: json
521
+ ? `${JSON.stringify(out, null, 2)}\n`
522
+ : `${d.promote ? "promoted" : "kept the current policy"}: ${d.reason}\n`,
523
+ };
524
+ }
525
+
526
+ function cmdChoose(flags, env, json) {
527
+ const candidates = String(flags.candidates || "")
528
+ .split(/[\s,]+/)
529
+ .filter(Boolean);
530
+ const bucket =
531
+ flags.bucket ||
532
+ bucketOf({
533
+ callSite: flags["call-site"],
534
+ taskKind: flags["task-kind"],
535
+ complexity: flags.complexity,
536
+ files: flags.files,
537
+ });
538
+ const p = learnedPrefs(env);
539
+ let out;
540
+ try {
541
+ out = choose({
542
+ policy: readRegularJson(join(storeDir(env), "policy.json"), null),
543
+ bucket,
544
+ candidates,
545
+ prices: prices(),
546
+ seed: flags.seed || env.ROUTE_LEARN_SEED || `${flags["task-id"] || "none"}`,
547
+ minSamples: Number(p.minSamples),
548
+ target: Number(p.target),
549
+ explore: p.explore === true,
550
+ });
551
+ } catch {
552
+ out = { order: candidates, reason: "error" };
553
+ }
554
+ return json ? `${JSON.stringify({ bucket, ...out }, null, 2)}\n` : `${out.order.join(" ")}\n`;
555
+ }
556
+
557
+ function cmdStatus(env, json, train) {
558
+ const dir = storeDir(env);
559
+ const rows = readRows(join(dir, "outcomes.jsonl"));
560
+ const policy = train
561
+ ? fitPolicy(rows, { halfLifeDays: learnedPrefs(env).halfLifeDays })
562
+ : readRegularJson(join(dir, "policy.json"), null);
563
+ if (json) return `${JSON.stringify({ outcomes: rows.length, policy }, null, 2)}\n`;
564
+ const lines = [
565
+ `outcomes: ${rows.length}`,
566
+ `policy: ${policy ? (train ? "candidate (not promoted)" : `promoted ${policy.promotedAt}`) : "none promoted"}`,
567
+ ];
568
+ for (const [b, rungs] of Object.entries(policy?.buckets || {})) {
569
+ for (const [r, s] of Object.entries(rungs)) lines.push(` ${b} ${r}: n=${s.n} mean=${s.mean}`);
570
+ }
571
+ return `${lines.join("\n")}\n`;
572
+ }
573
+
574
+ const SUBCOMMANDS = ["record", "ingest", "train", "promote", "choose", "status"];
575
+
576
+ function main(argv, env) {
577
+ const [sub, ...rest] = argv;
578
+ if (!SUBCOMMANDS.includes(sub)) throw unknownSubcommand(sub ?? "", SUBCOMMANDS);
579
+ const { flags } = parseArgs(rest, {
580
+ unknown: "error",
581
+ positionals: false,
582
+ booleans: ["json"],
583
+ strings: [
584
+ "rung",
585
+ "state",
586
+ "task-id",
587
+ "call-site",
588
+ "task-kind",
589
+ "complexity",
590
+ "files",
591
+ "metrics",
592
+ "holdout",
593
+ "min-rows",
594
+ "margin",
595
+ "candidates",
596
+ "bucket",
597
+ "seed",
598
+ ...NUMERIC,
599
+ ],
600
+ });
601
+ const json = flags.json === true;
602
+ switch (sub) {
603
+ case "record":
604
+ return { code: 0, text: cmdRecord(flags, env) };
605
+ case "ingest":
606
+ return { code: 0, text: cmdIngest(flags, env) };
607
+ case "promote":
608
+ return cmdPromote(flags, env, json);
609
+ case "choose":
610
+ return { code: 0, text: cmdChoose(flags, env, json) };
611
+ case "train":
612
+ return { code: 0, text: cmdStatus(env, json, true) };
613
+ default:
614
+ return { code: 0, text: cmdStatus(env, json, false) };
615
+ }
616
+ }
617
+
618
+ if (invokedDirectly(import.meta.url)) {
619
+ try {
620
+ const { code, text } = main(process.argv.slice(2), process.env);
621
+ process.stdout.write(text);
622
+ process.exitCode = code;
623
+ } catch (e) {
624
+ if (!(e instanceof ArgsError)) throw e;
625
+ process.stderr.write(`route-learn: ${e.message}\n`);
626
+ process.exitCode = 2;
627
+ }
628
+ }