@mmerterden/multi-agent-pipeline 20.40.0 → 20.41.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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +4 -1
  3. package/README.tr.md +4 -1
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +9 -9
  7. package/docs/facts.json +4 -4
  8. package/docs/features.md +6 -0
  9. package/install/claude.mjs +12 -3
  10. package/install/templates/claude-hooks.json +12 -1
  11. package/manifest.json +79 -60
  12. package/package.json +2 -2
  13. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  14. package/pipeline/contract/types/index.d.ts +53 -49
  15. package/pipeline/lib/context-budget.mjs +5 -42
  16. package/pipeline/lib/hook-registration.mjs +5 -0
  17. package/pipeline/lib/md2confluence-v3.py +12 -4
  18. package/pipeline/lib/tiered-budget.mjs +87 -0
  19. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  20. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  21. package/pipeline/multi-agent-refs/features/doctor.md +32 -1
  22. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  23. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  24. package/pipeline/multi-agent-refs/features/usage-reporting.md +31 -0
  25. package/pipeline/multi-agent-refs/help/en.md +1 -0
  26. package/pipeline/multi-agent-refs/help/tr.md +1 -0
  27. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  28. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  29. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -0
  30. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  31. package/pipeline/office/index.html +13 -7
  32. package/pipeline/office/toolkit.json +1 -1
  33. package/pipeline/preferences-template.json +1 -0
  34. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  35. package/pipeline/schemas/office-archive.schema.json +225 -128
  36. package/pipeline/schemas/prefs.schema.json +83 -0
  37. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  38. package/pipeline/schemas/product-tree.schema.json +136 -0
  39. package/pipeline/schemas/toolkit-path-params.json +1 -1
  40. package/pipeline/scripts/_eval-stats.mjs +182 -0
  41. package/pipeline/scripts/_guard_rules.py +130 -1
  42. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  43. package/pipeline/scripts/_locate.mjs +539 -0
  44. package/pipeline/scripts/_memory-policy.mjs +213 -14
  45. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  46. package/pipeline/scripts/_product-tree.mjs +923 -0
  47. package/pipeline/scripts/_retrieval.mjs +13 -2
  48. package/pipeline/scripts/_stack-routing.mjs +1 -0
  49. package/pipeline/scripts/_user_guard_rules.py +744 -0
  50. package/pipeline/scripts/agent-guard.py +61 -5
  51. package/pipeline/scripts/agent-guard.sh +8 -1
  52. package/pipeline/scripts/doctor.mjs +157 -1
  53. package/pipeline/scripts/graph-query.mjs +257 -17
  54. package/pipeline/scripts/learnings-ledger.mjs +664 -43
  55. package/pipeline/scripts/note-mcp-failure.mjs +356 -0
  56. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  57. package/pipeline/scripts/note-skill-use.mjs +93 -23
  58. package/pipeline/scripts/office-archive.mjs +23 -10
  59. package/pipeline/scripts/office-memory.mjs +4 -1
  60. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  61. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  62. package/pipeline/scripts/product-tree.mjs +544 -0
  63. package/pipeline/skills/.skill-manifest.json +11 -7
  64. package/pipeline/skills/.skills-index.json +12 -1
  65. package/pipeline/skills/shared/README.md +4 -3
  66. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  67. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  68. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  69. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  70. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  71. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  72. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  73. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  74. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  75. package/pipeline/skills/skill-copies.json +5 -1
  76. package/pipeline/skills/skills-index.md +2 -1
@@ -0,0 +1,685 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * @file product-tree-eval.mjs - does the screen layer find bug locations the
5
+ * code graph alone does not?
6
+ *
7
+ * Mines bug-fix commits from local git history and, for each one, rebuilds
8
+ * the code graph and the product tree from the fix commit's PARENT (read
9
+ * straight from git objects, no checkout), ranks files for the commit's
10
+ * subject line under three arms, and scores them against the files the fix
11
+ * modified:
12
+ *
13
+ * bm25 BM25F over file names, symbols and directories
14
+ * graph bm25 + UI-string expansion and boost + personalized PageRank +
15
+ * Turkish-aware normalisation + identifier splitting
16
+ * tree graph + screens, routes and the files each screen owns
17
+ *
18
+ * The parent's files are read as `product-tree build` reads a working tree:
19
+ * regular files up to MAX_INPUT_BYTES, no symlinks, the same decoding, and
20
+ * every git call through safeGit. The arm measured is the arm the pipeline
21
+ * runs.
22
+ *
23
+ * Every arm's output is rendered and cut to the same character budget before
24
+ * it is scored, so a gain cannot come from injecting more text.
25
+ *
26
+ * Bugs are split by time: the older half is the development set, the newer
27
+ * half the held-out test set the verdict is read from, so no parameter is
28
+ * tuned on the bugs it is judged on. A bug whose text already names a file,
29
+ * a symbol or a stack frame is reported separately: grep answers those, and
30
+ * the tree is meant for the rest.
31
+ *
32
+ * Metrics: Acc@k (any changed file in the top k), recall@k (share of the
33
+ * changed files in the top k), MRR. Statistics: exact McNemar on hit@10,
34
+ * tree against graph, and a seeded bootstrap interval of the recall@10
35
+ * difference; per repository and pooled.
36
+ *
37
+ * GO needs all three: recall@10 lift of at least --min-lift points on
38
+ * domain-text test bugs, McNemar p below --alpha, and no repository whose
39
+ * recall@10 under the tree arm is below the graph arm.
40
+ *
41
+ * Inputs:
42
+ * --repos <dir,dir,...> Local git repositories. Required.
43
+ * --max-bugs N Most recent qualifying fixes per repo. Default 60.
44
+ * --max-files N Skip fixes that modify more files. Default 8.
45
+ * --budget N Characters each arm may inject. Default 6000.
46
+ * --ks 1,5,10 Cut-offs. Default 1,5,10.
47
+ * --seed N Bootstrap seed. Default 1.
48
+ * --iterations N Bootstrap resamples. Default 2000.
49
+ * --min-lift N Points of recall@10 for GO. Default 15.
50
+ * --alpha X Significance level. Default 0.05.
51
+ * --out-dir <dir> Default ~/.claude/knowledge/_eval
52
+ * --issue-text-arm Add the memorization control: the bug text
53
+ * alone, no repository, sent to --llm-cmd. Off by
54
+ * default because it needs a model.
55
+ * --llm-cmd "<command>" Shell command that reads a prompt on stdin and
56
+ * prints file paths, one per line.
57
+ * --tune Build only the development half and grid-search
58
+ * the ranking settings on it; prints the chosen
59
+ * settings and writes no report. The held-out half
60
+ * is never read.
61
+ * --json Print the report as JSON.
62
+ *
63
+ * Output: the full report (per-bug rows included) is written 0600 to
64
+ * <out-dir>/product-tree-eval-<timestamp>.json. It names repositories and
65
+ * files, so it stays on this machine; anything published quotes only the
66
+ * pooled numbers and repository kinds.
67
+ *
68
+ * Exit codes: 0 report written, 1 a repository could not be read, 64 usage.
69
+ *
70
+ * @module pipeline/scripts/product-tree-eval
71
+ */
72
+
73
+ import { spawnSync } from "node:child_process";
74
+ import { chmodSync, mkdirSync, writeFileSync } from "node:fs";
75
+ import { basename, join, resolve } from "node:path";
76
+ import { homedir } from "node:os";
77
+ import {
78
+ buildProductTree,
79
+ isTreeInput,
80
+ stackOf,
81
+ detectStacks,
82
+ decodeText,
83
+ safeGit,
84
+ MAX_INPUT_BYTES,
85
+ } from "./_product-tree.mjs";
86
+ import { loadRules, isTestPath } from "./_code-graph.mjs";
87
+ import { isExcludedBy } from "./_path-match.mjs";
88
+ import { buildLocateIndex, rankArms, locateInput, cutToBudget } from "./_locate.mjs";
89
+ import {
90
+ rankingMetrics,
91
+ aggregateMetrics,
92
+ mcnemarExact,
93
+ bootstrapCI,
94
+ pairedBootstrapDiff,
95
+ verdict,
96
+ } from "./_eval-stats.mjs";
97
+ import { parseArgs } from "../lib/args.mjs";
98
+ import { exitOnHelp } from "../lib/cli-help.mjs";
99
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
100
+
101
+ exitOnHelp(import.meta.url);
102
+
103
+ const ARMS = ["bm25", "graph", "tree"];
104
+ const RULES_FOR = { ios: "ios", android: "android", web: "node" };
105
+
106
+ const FIX_RE = /\b(fix(?:e[sd])?|bug(?:fix)?|hotfix)\b/i;
107
+ const NOT_A_BUG_RE = /^(docs|doc|ci|test|tests|chore|build|style|refactor|perf|deps|release)\b/i;
108
+
109
+ /** Whether a commit subject reads as a bug fix rather than maintenance. */
110
+ export function isFixSubject(subject) {
111
+ const s = String(subject || "").trim();
112
+ if (/^(merge|revert)\b/i.test(s)) return false;
113
+ if (NOT_A_BUG_RE.test(s)) return false;
114
+ if (/\b(typo|lint|bump|version|changelog)\b/i.test(s)) return false;
115
+ return FIX_RE.test(s);
116
+ }
117
+
118
+ /** The subject without its conventional-commit prefix or PR number. */
119
+ export function bugText(subject) {
120
+ return String(subject || "")
121
+ .replace(/^\s*[A-Za-z]+(?:\([^)]*\))?!?\s*:\s*/, "")
122
+ .replace(/\s*\((?:#|PR\s*#?)\d+\)\s*$/i, "")
123
+ .replace(/\s*#\d+\s*$/, "")
124
+ .trim();
125
+ }
126
+
127
+ const FRAME_RE = /\b[\w./-]+\.(?:swift|kt|java|tsx?|jsx?|mjs|py|go|m|mm):\d+|\bat\s+\S+\s+\(/;
128
+
129
+ /**
130
+ * "frame", "file" or "symbol" when the text names code directly, else null.
131
+ *
132
+ * @param {string} text
133
+ * @param {string[]} files repo paths
134
+ * @param {Set<string>} symbols declared names
135
+ */
136
+ export function namesCode(text, files, symbols) {
137
+ if (FRAME_RE.test(text)) return "frame";
138
+ const words = String(text).match(/`?[A-Za-z_$][\w$.-]*`?(?:\(\))?/g) || [];
139
+ const bases = new Set();
140
+ const withExt = new Set();
141
+ for (const f of files) {
142
+ const b = basename(f);
143
+ withExt.add(b);
144
+ const stem = b.replace(/\.[^.]+$/, "");
145
+ if (/[a-z][A-Z]|_|-/.test(stem)) bases.add(stem);
146
+ }
147
+ for (const raw of words) {
148
+ const w = raw.replace(/^`|`$/g, "").replace(/\(\)$/, "");
149
+ if (withExt.has(w) || bases.has(w)) return "file";
150
+ }
151
+ for (const raw of words) {
152
+ const quoted = raw.startsWith("`") || raw.endsWith("()");
153
+ const w = raw.replace(/^`|`$/g, "").replace(/\(\)$/, "");
154
+ const compound = /[a-z][A-Z]|_/.test(w);
155
+ if ((compound || quoted) && symbols.has(w)) return "symbol";
156
+ }
157
+ return null;
158
+ }
159
+
160
+ /** Older half is the development set, newer half the test set. */
161
+ export function splitByTime(bugs) {
162
+ const sorted = [...bugs].sort((a, b) => a.ts - b.ts);
163
+ const half = Math.floor(sorted.length / 2);
164
+ return { dev: sorted.slice(0, half), test: sorted.slice(half) };
165
+ }
166
+
167
+ const git = (repo, args, opts = {}) =>
168
+ safeGit(repo, args, { maxBuffer: 1024 * 1024 * 1024, ...opts });
169
+
170
+ /** Paths a `diff-tree -z --name-status` output lists with status M. */
171
+ function modifiedPaths(raw) {
172
+ const parts = raw.split("\0");
173
+ const out = [];
174
+ for (let i = 0; i < parts.length - 1;) {
175
+ const status = parts[i];
176
+ if (!status) {
177
+ i++;
178
+ continue;
179
+ }
180
+ const paths = /^[RC]/.test(status) ? 2 : 1;
181
+ if (status === "M") out.push(parts[i + 1]);
182
+ i += 1 + paths;
183
+ }
184
+ return out;
185
+ }
186
+
187
+ /** Qualifying fix commits, newest first. */
188
+ export function mineFixes(repo, { maxBugs = 60, maxFiles = 8 } = {}) {
189
+ const log = git(repo, [
190
+ "log",
191
+ "--no-merges",
192
+ "--no-show-signature",
193
+ "--format=%H%x1f%P%x1f%ct%x1f%s%x1e",
194
+ ]);
195
+ const out = [];
196
+ for (const rec of log.split("\x1e")) {
197
+ const [sha, parents, ts, subject] = rec.trim().split("\x1f");
198
+ if (!sha || !parents || !isFixSubject(subject)) continue;
199
+ const parent = parents.split(" ")[0];
200
+ const status = git(repo, [
201
+ "diff-tree",
202
+ "-z",
203
+ "--no-commit-id",
204
+ "--no-ext-diff",
205
+ "--no-textconv",
206
+ "-r",
207
+ "--name-status",
208
+ parent,
209
+ sha,
210
+ ]);
211
+ const modified = modifiedPaths(status).filter((p) => stackOf(p));
212
+ out.push({ sha, parent, ts: Number(ts), subject, modified });
213
+ if (out.length >= maxBugs * 6) break;
214
+ }
215
+ return out.filter((c) => c.modified.length && c.modified.length <= maxFiles);
216
+ }
217
+
218
+ /**
219
+ * Path -> {text, id} for the tree inputs at a commit, sharing blob texts
220
+ * across calls. It reads what readRepoFiles reads: regular files up to
221
+ * MAX_INPUT_BYTES, never a symlink, decoded the same way.
222
+ */
223
+ export function snapshotAt(repo, commit, blobs) {
224
+ const raw = git(repo, ["ls-tree", "-r", "-z", "-l", commit]);
225
+ const entries = [];
226
+ for (const rec of raw.split("\0")) {
227
+ const m = rec.match(/^100(?:644|755) blob ([0-9a-f]+)\s+(\d+)\t(.+)$/);
228
+ if (!m || !isTreeInput(m[3]) || Number(m[2]) > MAX_INPUT_BYTES) continue;
229
+ entries.push({ sha: m[1], path: m[3] });
230
+ }
231
+ const missing = [...new Set(entries.map((e) => e.sha).filter((s) => !blobs.has(s)))];
232
+ if (missing.length) {
233
+ const buf = git(repo, ["cat-file", "--batch"], {
234
+ input: missing.join("\n") + "\n",
235
+ encoding: null,
236
+ maxBuffer: 2 * 1024 * 1024 * 1024,
237
+ });
238
+ let at = 0;
239
+ while (at < buf.length) {
240
+ const nl = buf.indexOf(10, at);
241
+ const header = buf.toString("utf8", at, nl).split(" ");
242
+ const size = Number(header[2]);
243
+ blobs.set(header[0], decodeText(buf.subarray(nl + 1, nl + 1 + size)));
244
+ at = nl + 1 + size + 1;
245
+ }
246
+ }
247
+ return new Map(entries.map((e) => [e.path, { text: blobs.get(e.sha) ?? "", id: e.sha }]));
248
+ }
249
+
250
+ function mergedGraph(tree) {
251
+ const graphs = Object.values(tree.graphs || {});
252
+ return { nodes: graphs.flatMap((g) => g.nodes), edges: graphs.flatMap((g) => g.edges) };
253
+ }
254
+
255
+ /** The lines an arm injects, and the files that survive the budget, in order. */
256
+ export function renderArm(arm, result, budget) {
257
+ const files = result[arm];
258
+ const lines = [];
259
+ const fileAt = [];
260
+ if (arm === "tree") {
261
+ for (const s of result.screens.slice(0, 3)) {
262
+ lines.push(
263
+ `screen ${s.name}${s.routes.length ? ` [${s.routes.slice(0, 2).join(", ")}]` : ""}`,
264
+ );
265
+ fileAt.push(null);
266
+ }
267
+ }
268
+ for (const f of files) {
269
+ lines.push(f);
270
+ fileAt.push(f);
271
+ }
272
+ const kept = cutToBudget(lines, budget);
273
+ return {
274
+ files: fileAt.slice(0, kept.length).filter(Boolean),
275
+ chars: kept.join("\n").length,
276
+ };
277
+ }
278
+
279
+ function repoKind(stacks, screens) {
280
+ if (!screens) return stacks.includes("web") || !stacks.length ? "tooling-repo" : "library-repo";
281
+ return `${stacks.join("+")}-app`;
282
+ }
283
+
284
+ /**
285
+ * The most recent qualifying fixes, each with the production files it
286
+ * modified that existed at its parent. Reads only file names, so it is cheap
287
+ * next to building a tree.
288
+ */
289
+ export function selectBugs(repo, { maxBugs = 60, maxFiles = 8 } = {}) {
290
+ const rulesByStack = new Map();
291
+ const selected = [];
292
+ for (const c of mineFixes(repo, { maxBugs, maxFiles })) {
293
+ if (selected.length >= maxBugs) break;
294
+ const text = bugText(c.subject);
295
+ if (text.length < 8) continue;
296
+ const paths = new Set(git(repo, ["ls-tree", "-r", "--name-only", "-z", c.parent]).split("\0"));
297
+ const stacks = detectStacks([...paths]);
298
+ const truth = c.modified.filter((p) => {
299
+ const st = stackOf(p);
300
+ if (!paths.has(p) || !st || !stacks.includes(st)) return false;
301
+ if (!rulesByStack.has(st)) rulesByStack.set(st, loadRules(RULES_FOR[st]));
302
+ const rules = rulesByStack.get(st);
303
+ return !isTestPath(p, rules) && !isExcludedBy(p, rules.excludePathGlobs);
304
+ });
305
+ if (truth.length) selected.push({ ...c, text, truth });
306
+ }
307
+ return selected;
308
+ }
309
+
310
+ /**
311
+ * Evaluate qualifying fixes in one repository.
312
+ *
313
+ * @param {string} repo
314
+ * @param {object} opts
315
+ * @param {"all"|"dev"} [opts.only] "dev" builds only the older half, for --tune
316
+ * @param {boolean} [opts.keepIndex] keep each bug's locate index on the row
317
+ */
318
+ export function evaluateRepo(repo, opts = {}) {
319
+ const {
320
+ maxBugs = 60,
321
+ maxFiles = 8,
322
+ budget = 6000,
323
+ ks = [1, 5, 10],
324
+ llmCmd = null,
325
+ only = "all",
326
+ keepIndex = false,
327
+ rank = {},
328
+ } = opts;
329
+ const blobs = new Map();
330
+ const cache = new Map();
331
+ const selected = selectBugs(repo, { maxBugs, maxFiles });
332
+ const chosen = only === "dev" ? splitByTime(selected).dev : selected;
333
+ const bugs = [];
334
+ let stacksSeen = null;
335
+ let screenTotal = 0;
336
+ let coverage = null;
337
+ for (const c of [...chosen].sort((x, y) => y.ts - x.ts)) {
338
+ const files = snapshotAt(repo, c.parent, blobs);
339
+ const tree = buildProductTree({
340
+ files,
341
+ project: "eval",
342
+ baseCommit: c.parent,
343
+ generatedAt: "1970-01-01T00:00:00Z",
344
+ cache,
345
+ });
346
+ const graph = mergedGraph(tree);
347
+ const input = locateInput(tree, graph);
348
+ const index = buildLocateIndex(input);
349
+ const result = rankArms(index, c.text, { rank });
350
+ const symbols = new Set(graph.nodes.filter((n) => n.kind === "symbol").map((n) => n.name));
351
+ const row = {
352
+ sha: c.sha,
353
+ ts: c.ts,
354
+ text: c.text,
355
+ truth: c.truth,
356
+ named: namesCode(
357
+ c.text,
358
+ input.files.map((f) => f.path),
359
+ symbols,
360
+ ),
361
+ arms: {},
362
+ chars: {},
363
+ };
364
+ for (const arm of ARMS) {
365
+ const r = renderArm(arm, result, budget);
366
+ row.arms[arm] = rankingMetrics(r.files, c.truth, ks);
367
+ row.chars[arm] = r.chars;
368
+ }
369
+ if (llmCmd) {
370
+ const guess = askModel(llmCmd, c.text);
371
+ row.arms.issueText = rankingMetrics(guess, c.truth, ks);
372
+ row.chars.issueText = 0;
373
+ }
374
+ if (keepIndex) Object.defineProperty(row, "index", { value: index, enumerable: false });
375
+ bugs.push(row);
376
+ if (!stacksSeen) {
377
+ stacksSeen = tree.stacks;
378
+ screenTotal = tree.stats.screens;
379
+ coverage = tree.coverage;
380
+ }
381
+ }
382
+ return {
383
+ repo,
384
+ kind: repoKind(stacksSeen || [], screenTotal),
385
+ stacks: stacksSeen || [],
386
+ screens: screenTotal,
387
+ coverage,
388
+ bugs,
389
+ };
390
+ }
391
+
392
+ /** Candidate settings for --tune. */
393
+ export function tuneGrid() {
394
+ const grid = [];
395
+ for (const keyCoverage of [0.5, 0.6, 0.8]) {
396
+ for (const ui of [0.3, 0.6, 1]) {
397
+ for (const ppr of [0, 0.3, 0.6]) {
398
+ for (const tree of [0.25, 0.5, 1]) {
399
+ for (const treeK of [10, 30, 60]) {
400
+ grid.push({
401
+ keyCoverage,
402
+ graphWeights: [1, ui, ui, ppr],
403
+ treeWeights: [1, tree],
404
+ treeK: [10, treeK],
405
+ });
406
+ }
407
+ }
408
+ }
409
+ }
410
+ }
411
+ return grid;
412
+ }
413
+
414
+ /**
415
+ * Pick ranking settings on development bugs only: the graph arm's settings
416
+ * by its own recall@10, then the tree arm's on top of them.
417
+ */
418
+ export function tune(results, { budget = 6000, ks = [1, 5, 10] } = {}) {
419
+ const rows = results.flatMap((r) => r.bugs.filter((b) => !b.named && b.index));
420
+ const score = (cfg, arm) => {
421
+ let sum = 0;
422
+ for (const b of rows) {
423
+ const r = rankArms(b.index, b.text, { rank: cfg });
424
+ sum += rankingMetrics(renderArm(arm, r, budget).files, b.truth, ks).recall[10];
425
+ }
426
+ return rows.length ? sum / rows.length : 0;
427
+ };
428
+ const grid = tuneGrid();
429
+ const graphOnly = new Map();
430
+ for (const cfg of grid) {
431
+ const k = JSON.stringify([cfg.keyCoverage, cfg.graphWeights]);
432
+ if (!graphOnly.has(k)) graphOnly.set(k, cfg);
433
+ }
434
+ let bestGraph = null;
435
+ for (const cfg of graphOnly.values()) {
436
+ const s = score(cfg, "graph");
437
+ if (!bestGraph || s > bestGraph.score) bestGraph = { cfg, score: s };
438
+ }
439
+ let bestTree = null;
440
+ for (const cfg of grid) {
441
+ if (cfg.keyCoverage !== bestGraph.cfg.keyCoverage) continue;
442
+ if (JSON.stringify(cfg.graphWeights) !== JSON.stringify(bestGraph.cfg.graphWeights)) continue;
443
+ const s = score(cfg, "tree");
444
+ if (!bestTree || s > bestTree.score) bestTree = { cfg, score: s };
445
+ }
446
+ return { devBugs: rows.length, bm25: score({}, "bm25"), graph: bestGraph, tree: bestTree };
447
+ }
448
+
449
+ function askModel(cmd, text) {
450
+ const prompt =
451
+ "A bug was fixed in a software repository you cannot see. From the bug text alone, " +
452
+ "list up to 10 repository-relative file paths the fix most likely changed, one per " +
453
+ `line, nothing else.\n\nBug: ${text}\n`;
454
+ const r = spawnSync("sh", ["-c", cmd], { input: prompt, encoding: "utf8", timeout: 120000 });
455
+ return String(r.stdout || "")
456
+ .split("\n")
457
+ .map((l) => l.trim().replace(/^[-*\d.)\s]+/, ""))
458
+ .filter(Boolean)
459
+ .slice(0, 10);
460
+ }
461
+
462
+ /** Aggregate one bug set: per-arm metrics, McNemar and bootstrap, tree vs graph. */
463
+ export function summarize(bugs, { ks, seed, iterations }) {
464
+ const arms = Object.keys(bugs[0]?.arms || {});
465
+ const out = { n: bugs.length, arms: {}, chars: {} };
466
+ for (const arm of arms) {
467
+ out.arms[arm] = aggregateMetrics(
468
+ bugs.map((b) => b.arms[arm]),
469
+ ks,
470
+ );
471
+ out.arms[arm].recall10CI = bootstrapCI(
472
+ bugs.map((b) => b.arms[arm].recall[10] ?? 0),
473
+ { seed, iterations },
474
+ );
475
+ out.chars[arm] = bugs.length
476
+ ? Math.round(bugs.reduce((s, b) => s + b.chars[arm], 0) / bugs.length)
477
+ : 0;
478
+ }
479
+ if (bugs.length && arms.includes("tree") && arms.includes("graph")) {
480
+ let b = 0;
481
+ let c = 0;
482
+ for (const bug of bugs) {
483
+ const g = bug.arms.graph.hit[10];
484
+ const t = bug.arms.tree.hit[10];
485
+ if (g && !t) b++;
486
+ if (t && !g) c++;
487
+ }
488
+ out.mcnemar = { graphOnly: b, treeOnly: c, p: mcnemarExact(b, c) };
489
+ out.recall10Diff = pairedBootstrapDiff(
490
+ bugs.map((x) => x.arms.graph.recall[10]),
491
+ bugs.map((x) => x.arms.tree.recall[10]),
492
+ { seed, iterations },
493
+ );
494
+ }
495
+ return out;
496
+ }
497
+
498
+ /** Full report over several repositories. */
499
+ export function report(results, opts) {
500
+ const { ks = [1, 5, 10], seed = 1, iterations = 2000, minLift = 15, alpha = 0.05 } = opts;
501
+ const per = [];
502
+ const pooledTest = [];
503
+ const pooledAll = [];
504
+ for (const r of results) {
505
+ const { dev, test } = splitByTime(r.bugs);
506
+ const domainTest = test.filter((b) => !b.named);
507
+ pooledTest.push(...domainTest);
508
+ pooledAll.push(...r.bugs);
509
+ per.push({
510
+ repo: r.repo,
511
+ kind: r.kind,
512
+ stacks: r.stacks,
513
+ screens: r.screens,
514
+ coverage: r.coverage,
515
+ bugs: r.bugs.length,
516
+ named: r.bugs.filter((b) => b.named).length,
517
+ dev: summarize(
518
+ dev.filter((b) => !b.named),
519
+ { ks, seed, iterations },
520
+ ),
521
+ test: summarize(domainTest, { ks, seed, iterations }),
522
+ namedTest: summarize(
523
+ test.filter((b) => b.named),
524
+ { ks, seed, iterations },
525
+ ),
526
+ });
527
+ }
528
+ const pooled = summarize(pooledTest, { ks, seed, iterations });
529
+ const pooledEverything = summarize(pooledAll, { ks, seed, iterations });
530
+ const lift =
531
+ pooled.n && pooled.arms.tree
532
+ ? (pooled.arms.tree.recall[10] - pooled.arms.graph.recall[10]) * 100
533
+ : 0;
534
+ const regressed = per
535
+ .filter((p) => p.test.n && p.test.arms.tree.recall[10] < p.test.arms.graph.recall[10])
536
+ .map((p) => p.kind);
537
+ const v = verdict({
538
+ liftPoints: lift,
539
+ p: pooled.mcnemar ? pooled.mcnemar.p : 1,
540
+ regressedRepos: regressed,
541
+ minLiftPoints: minLift,
542
+ alpha,
543
+ });
544
+ return {
545
+ generatedAt: new Date().toISOString(),
546
+ ks,
547
+ seed,
548
+ iterations,
549
+ per,
550
+ pooled,
551
+ pooledEverything,
552
+ liftPoints: lift,
553
+ verdict: v,
554
+ };
555
+ }
556
+
557
+ const pct = (x) => (x == null ? " - " : `${(x * 100).toFixed(1)}`);
558
+
559
+ function printReport(rep) {
560
+ const lines = [];
561
+ const row = (label, s) => {
562
+ if (!s.n) return lines.push(` ${label}: no bugs`);
563
+ for (const arm of Object.keys(s.arms)) {
564
+ const a = s.arms[arm];
565
+ lines.push(
566
+ ` ${label} ${arm.padEnd(9)} n=${s.n} Acc@1 ${pct(a.acc[1])} Acc@5 ${pct(a.acc[5])} ` +
567
+ `Acc@10 ${pct(a.acc[10])} R@1 ${pct(a.recall[1])} R@5 ${pct(a.recall[5])} ` +
568
+ `R@10 ${pct(a.recall[10])} [${pct(a.recall10CI.low)}, ${pct(a.recall10CI.high)}] ` +
569
+ `MRR ${a.mrr.toFixed(3)} chars ${s.chars[arm]}`,
570
+ );
571
+ }
572
+ if (s.mcnemar) {
573
+ lines.push(
574
+ ` ${label} tree vs graph: hit@10 graph-only ${s.mcnemar.graphOnly}, tree-only ` +
575
+ `${s.mcnemar.treeOnly}, McNemar p=${s.mcnemar.p.toFixed(4)}, R@10 diff ` +
576
+ `${pct(s.recall10Diff.mean)} [${pct(s.recall10Diff.low)}, ${pct(s.recall10Diff.high)}]`,
577
+ );
578
+ }
579
+ };
580
+ for (const p of rep.per) {
581
+ const cov = Object.entries(p.coverage || {})
582
+ .map(
583
+ ([s, c]) =>
584
+ `${s} ${c.reachable}/${c.screens} reachable, ${c.programmatic.resolved}/${c.programmatic.total} programmatic`,
585
+ )
586
+ .join("; ");
587
+ lines.push(
588
+ `${p.kind} (${basename(p.repo)}): ${p.bugs} bugs, ${p.named} name code; ${cov || "no screens"}`,
589
+ );
590
+ row("test", p.test);
591
+ row("named", p.namedTest);
592
+ }
593
+ lines.push("pooled, domain-text test bugs:");
594
+ row("pooled", rep.pooled);
595
+ lines.push(
596
+ `verdict: ${rep.verdict.go ? "GO" : "NO-GO"} (lift ${rep.liftPoints.toFixed(1)} points)` +
597
+ (rep.verdict.reasons.length ? `: ${rep.verdict.reasons.join("; ")}` : ""),
598
+ );
599
+ return lines.join("\n");
600
+ }
601
+
602
+ function main() {
603
+ let parsed;
604
+ try {
605
+ parsed = parseArgs(process.argv.slice(2), {
606
+ booleans: ["json", "issue-text-arm", "tune"],
607
+ strings: [
608
+ "repos",
609
+ "max-bugs",
610
+ "max-files",
611
+ "budget",
612
+ "ks",
613
+ "seed",
614
+ "iterations",
615
+ "min-lift",
616
+ "alpha",
617
+ "out-dir",
618
+ "llm-cmd",
619
+ ],
620
+ unknown: "error",
621
+ positionals: false,
622
+ });
623
+ } catch (e) {
624
+ process.stderr.write(`product-tree-eval: ${e.message}\n`);
625
+ process.exit(64);
626
+ }
627
+ const f = parsed.flags;
628
+ if (typeof f.repos !== "string") {
629
+ process.stderr.write("product-tree-eval: --repos <dir,dir,...> is required\n");
630
+ process.exit(64);
631
+ }
632
+ if (f["issue-text-arm"] && typeof f["llm-cmd"] !== "string") {
633
+ process.stderr.write("product-tree-eval: --issue-text-arm needs --llm-cmd\n");
634
+ process.exit(64);
635
+ }
636
+ const num = (v, d) => (v !== undefined && Number.isFinite(Number(v)) ? Number(v) : d);
637
+ const opts = {
638
+ maxBugs: num(f["max-bugs"], 60),
639
+ maxFiles: num(f["max-files"], 8),
640
+ budget: num(f.budget, 6000),
641
+ ks: typeof f.ks === "string" ? f.ks.split(",").map(Number) : [1, 5, 10],
642
+ seed: num(f.seed, 1),
643
+ iterations: num(f.iterations, 2000),
644
+ minLift: num(f["min-lift"], 15),
645
+ alpha: num(f.alpha, 0.05),
646
+ llmCmd: f["issue-text-arm"] ? f["llm-cmd"] : null,
647
+ };
648
+ if (!opts.ks.includes(10)) opts.ks.push(10);
649
+ const results = [];
650
+ if (f.tune === true) {
651
+ opts.only = "dev";
652
+ opts.keepIndex = true;
653
+ }
654
+ for (const repo of f.repos.split(",").map((r) => resolve(r.trim()))) {
655
+ try {
656
+ const started = Date.now();
657
+ const r = evaluateRepo(repo, opts);
658
+ process.stderr.write(
659
+ `product-tree-eval: ${basename(repo)} ${r.bugs.length} bugs in ${Date.now() - started}ms\n`,
660
+ );
661
+ results.push(r);
662
+ } catch (e) {
663
+ process.stderr.write(`product-tree-eval: cannot evaluate ${repo}: ${e.message}\n`);
664
+ process.exit(1);
665
+ }
666
+ }
667
+ if (f.tune === true) {
668
+ const t = tune(results, opts);
669
+ process.stdout.write(JSON.stringify(t, null, 2) + "\n");
670
+ return;
671
+ }
672
+ const rep = report(results, opts);
673
+ const outDir =
674
+ typeof f["out-dir"] === "string"
675
+ ? resolve(f["out-dir"])
676
+ : join(homedir(), ".claude", "knowledge", "_eval");
677
+ mkdirSync(outDir, { recursive: true });
678
+ const out = join(outDir, `product-tree-eval-${rep.generatedAt.replace(/[:.]/g, "-")}.json`);
679
+ writeFileSync(out, JSON.stringify({ ...rep, results }, null, 2), { mode: 0o600 });
680
+ chmodSync(out, 0o600);
681
+ if (f.json === true) process.stdout.write(JSON.stringify(rep, null, 2) + "\n");
682
+ else process.stdout.write(`${printReport(rep)}\nreport: ${out}\n`);
683
+ }
684
+
685
+ if (invokedDirectly(import.meta.url)) main();