@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
@@ -136,14 +136,25 @@ function splitIdentifier(w) {
136
136
  * BM25 needs term frequency, so this returns an array; callers that only need
137
137
  * membership use tokenSet().
138
138
  *
139
+ * `unicode` reads a word of any script whole ("Kullanıcı" stays one term
140
+ * instead of stopping at "Kullan"). The memory policy's duplicate and
141
+ * promotion measures pass it; ranking keeps the ASCII words its evaluation
142
+ * corpus was measured on.
143
+ *
139
144
  * @param {string} text
145
+ * @param {{unicode?: boolean}} [opts]
140
146
  * @returns {string[]} stemmed lower-cased terms of 3+ chars, stop words
141
147
  * removed, identifiers indexed both whole and split
142
148
  */
143
- export function tokens(text) {
149
+ export function tokens(text, { unicode = false } = {}) {
144
150
  if (!text) return [];
145
151
  const out = [];
146
- for (const m of String(text).matchAll(/[A-Za-z][A-Za-z0-9_]{2,}/g)) {
152
+ const words = unicode
153
+ ? String(text)
154
+ .normalize("NFC")
155
+ .matchAll(/\p{L}[\p{L}\p{N}_]{2,}/gu)
156
+ : String(text).matchAll(/[A-Za-z][A-Za-z0-9_]{2,}/g);
157
+ for (const m of words) {
147
158
  const whole = m[0].toLowerCase();
148
159
  if (!STOP.has(whole)) out.push(stem(whole));
149
160
  const parts = splitIdentifier(m[0]);
@@ -316,6 +327,137 @@ export function rrf(rankings, opts = {}) {
316
327
  return sortStable([...fused].map(([index, score]) => ({ index, score })));
317
328
  }
318
329
 
330
+ /**
331
+ * Inverse document frequency over a corpus of token lists, smoothed so a term
332
+ * in every document still weighs something: log(1 + n / df).
333
+ *
334
+ * @param {string[][]} corpus
335
+ * @returns {(term: string) => number}
336
+ */
337
+ export function idfWeights(corpus) {
338
+ const df = new Map();
339
+ for (const doc of corpus) for (const t of new Set(doc)) df.set(t, (df.get(t) || 0) + 1);
340
+ const n = corpus.length;
341
+ return (t) => Math.log(1 + n / (df.get(t) || 1));
342
+ }
343
+
344
+ /**
345
+ * Term frequency times IDF, as a sparse vector.
346
+ *
347
+ * @param {string[]} doc
348
+ * @param {(term: string) => number} weight
349
+ * @returns {Map<string, number>}
350
+ */
351
+ export function tfidfVector(doc, weight) {
352
+ const tf = new Map();
353
+ for (const t of doc) tf.set(t, (tf.get(t) || 0) + 1);
354
+ const v = new Map();
355
+ for (const [t, c] of tf) v.set(t, c * weight(t));
356
+ return v;
357
+ }
358
+
359
+ /**
360
+ * Cosine of two sparse vectors; 0 when either is empty.
361
+ *
362
+ * @param {Map<string, number>} va
363
+ * @param {Map<string, number>} vb
364
+ * @returns {number}
365
+ */
366
+ export function cosine(va, vb) {
367
+ let dot = 0;
368
+ for (const [t, w] of va) dot += w * (vb.get(t) || 0);
369
+ const norm = (v) => Math.sqrt([...v.values()].reduce((s, w) => s + w * w, 0));
370
+ const d = norm(va) * norm(vb);
371
+ return d ? dot / d : 0;
372
+ }
373
+
374
+ /**
375
+ * Maximal Marginal Relevance: re-pick the head of a ranking so each next
376
+ * entry trades its relevance against its similarity to what is already
377
+ * picked, `lambda * relevance - (1 - lambda) * max similarity`.
378
+ *
379
+ * The stores inject a handful of rows. Without this, five rows recording the
380
+ * same finding take all five places and the second thing the task needs is
381
+ * not injected at all. Relevance is the ranking's own score scaled to the
382
+ * best one; similarity is TF-IDF cosine over the entries' terms, the same
383
+ * measure the memory policy uses for near-duplicates. Only the first `limit`
384
+ * places are re-picked and the rest keep their order, so nothing is dropped
385
+ * and lambda 1 is the input order. Ties go to the earlier entry.
386
+ *
387
+ * @param {Array<{index:number, score:number}>} ranked best first
388
+ * @param {string[][]} terms token list per document index
389
+ * @param {{lambda?: number, limit?: number}} [opts]
390
+ * @returns {Array<{index:number, score:number}>}
391
+ */
392
+ export function mmr(ranked, terms, { lambda = 0.7, limit = ranked.length } = {}) {
393
+ if (!ranked.length || lambda >= 1) return ranked.slice();
394
+ const top = Math.max(...ranked.map((x) => x.score), 0) || 1;
395
+ const weight = idfWeights(ranked.map((x) => terms[x.index] || []));
396
+ const vectors = new Map(ranked.map((x) => [x.index, tfidfVector(terms[x.index] || [], weight)]));
397
+ const left = ranked.slice();
398
+ const picked = [];
399
+ while (left.length && picked.length < limit) {
400
+ let best = 0;
401
+ let bestValue = -Infinity;
402
+ for (let i = 0; i < left.length; i++) {
403
+ const v = vectors.get(left[i].index);
404
+ let sim = 0;
405
+ for (const p of picked) sim = Math.max(sim, cosine(v, vectors.get(p.index)));
406
+ const value = lambda * (left[i].score / top) - (1 - lambda) * sim;
407
+ if (value > bestValue) {
408
+ bestValue = value;
409
+ best = i;
410
+ }
411
+ }
412
+ picked.push(left.splice(best, 1)[0]);
413
+ }
414
+ return [...picked, ...left];
415
+ }
416
+
417
+ const CLAUSE = /[.;\n]|,\s*|\s+(?:and|or|then|also|plus)\s+/i;
418
+ const MAX_SUBQUERIES = 4;
419
+
420
+ /**
421
+ * The query as given, plus one sub-query per clause when the text names
422
+ * several things ("fix the formatter crash and the checkout button"). A task
423
+ * that asks for two things is badly served by one query: the clause with the
424
+ * rarer terms decides the ranking and the other topic falls below the cut.
425
+ * At most four clauses are added; a one-clause text is the single query.
426
+ *
427
+ * @param {string} text
428
+ * @returns {string[][]} term lists, the whole query first
429
+ */
430
+ export function expandQuery(text) {
431
+ const whole = tokens(text);
432
+ const clauses = String(text || "")
433
+ .split(CLAUSE)
434
+ .map((c) => tokens(c))
435
+ .filter((t) => t.length > 0);
436
+ if (clauses.length < 2) return [whole];
437
+ return [whole, ...clauses.slice(0, MAX_SUBQUERIES)];
438
+ }
439
+
440
+ /**
441
+ * BM25 per query from expandQuery, fused by RRF with the whole query
442
+ * leading. Every term of every clause is in the whole query, so the rows it
443
+ * returns with a score are exactly the rows BM25 matches. A one-clause query
444
+ * is plain bm25.
445
+ *
446
+ * @param {string} text
447
+ * @param {Array<Record<string,string>>} docs
448
+ * @param {object} [opts] passed to bm25
449
+ * @returns {Array<{index:number, score:number}>}
450
+ */
451
+ export function multiQuery(text, docs, opts = {}) {
452
+ const queries = expandQuery(text);
453
+ if (queries.length === 1) return bm25(queries[0], docs, opts);
454
+ const rankings = queries.map((q) => bm25(q, docs, opts));
455
+ return rrf(rankings, {
456
+ k: queries.map((_, i) => (i === 0 ? 10 : 60)),
457
+ weights: queries.map((_, i) => (i === 0 ? 2 : 1)),
458
+ });
459
+ }
460
+
319
461
  /**
320
462
  * Stable descending sort by score, ties resolved by original index.
321
463
  *
@@ -362,18 +504,33 @@ export function shortId(prefix, ...parts) {
362
504
  * the ledger brief), which is the one-flag rollback if a ranking change ever
363
505
  * makes a run worse.
364
506
  *
507
+ * `memoryRecall.mmrLambda` (default 0.7, 1 turns it off) and
508
+ * `memoryRecall.multiQuery` (default on) are the diversity half: see mmr() and
509
+ * multiQuery().
510
+ *
365
511
  * @param {NodeJS.ProcessEnv} [env]
366
- * @returns {{strategy:string, maxResults:number, maxChars:number, halfLifeDays:number}}
512
+ * @returns {{strategy:string, maxResults:number, maxChars:number, halfLifeDays:number, mmrLambda:number, multiQuery:boolean}}
367
513
  */
368
514
  export function recallConfig(env = process.env) {
369
- const defaults = { strategy: "bm25", maxResults: 5, maxChars: 0, halfLifeDays: 30 };
515
+ const defaults = {
516
+ strategy: "bm25",
517
+ maxResults: 5,
518
+ maxChars: 0,
519
+ halfLifeDays: 30,
520
+ mmrLambda: 0.7,
521
+ multiQuery: true,
522
+ };
370
523
  try {
371
524
  const cfg = loadGlobalPrefs(prefsPath(env)).memoryRecall || {};
525
+ const lambda = Number(cfg.mmrLambda);
372
526
  return {
373
527
  strategy: cfg.strategy === "legacy" ? "legacy" : defaults.strategy,
374
528
  maxResults: Number.isFinite(cfg.maxResults) ? cfg.maxResults : defaults.maxResults,
375
529
  maxChars: Number.isFinite(cfg.maxChars) ? cfg.maxChars : defaults.maxChars,
376
530
  halfLifeDays: Number.isFinite(cfg.halfLifeDays) ? cfg.halfLifeDays : defaults.halfLifeDays,
531
+ mmrLambda:
532
+ cfg.mmrLambda !== undefined && lambda >= 0 && lambda <= 1 ? lambda : defaults.mmrLambda,
533
+ multiQuery: cfg.multiQuery === false ? false : defaults.multiQuery,
377
534
  };
378
535
  } catch {
379
536
  // No prefs file, unreadable, or malformed: ranking is a local improvement,
@@ -16,7 +16,9 @@
16
16
  * them also rejoins a token split by one. A run that starts with a known token
17
17
  * prefix is scanned a second time with its inner whitespace removed, so a token
18
18
  * hard-wrapped by a space or a line break is still caught; prose without such
19
- * a prefix is scanned once, as written.
19
+ * a prefix is scanned once, as written. Text that holds base64, hex or rot13
20
+ * runs is scanned once more as their bounded decode (lib/normalize-text.mjs
21
+ * decodedVariants), so a token wrapped in an encoding is still refused.
20
22
  *
21
23
  * @module pipeline/scripts/_secret-scan
22
24
  */
@@ -26,6 +28,7 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
26
28
  import { homedir, tmpdir } from "node:os";
27
29
  import { dirname, join } from "node:path";
28
30
  import { fileURLToPath } from "node:url";
31
+ import { decodedVariants } from "../lib/normalize-text.mjs";
29
32
  import { SECRET_PATTERNS } from "../lib/secret-patterns.generated.mjs";
30
33
 
31
34
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -75,6 +78,8 @@ export function openScanner() {
75
78
  const copies = [plain];
76
79
  const joined = rejoined(plain);
77
80
  if (joined !== plain) copies.push(joined);
81
+ const decoded = decodedVariants(plain);
82
+ if (decoded.length) copies.push(decoded.map((v) => v.text).join("\n"));
78
83
  return copies.every((copy) => {
79
84
  writeFileSync(file, `${copy}\n`, { mode: 0o600 });
80
85
  try {
@@ -36,6 +36,8 @@ export const COMMON_SKILLS = [
36
36
  "handle-request",
37
37
  "fix-review-verdicts",
38
38
  "free-llm-apis",
39
+ "spec-persona-walk",
40
+ "disk-cleaner",
39
41
  ];
40
42
 
41
43
  // The analyst plugin is the second always-enabled toolkit. It carries outside
@@ -42,6 +42,17 @@
42
42
  * _lint-suppression.mjs, which also covers lint config
43
43
  * files and comment lines.
44
44
  *
45
+ * narrowed-run read from the test command line, not the diff
46
+ * (narrowedRun): the run was a subset of the suite. A
47
+ * name filter or skip list (`-only-testing`,
48
+ * `--filter`, `--tests`, `-t`, `-k`, `--grep`, `-run`),
49
+ * a single test file or test id, or a flag that lets an
50
+ * empty run pass (`--passWithNoTests`). A green subset
51
+ * says nothing about the tests it left out, so
52
+ * evidence-gate refuses it as a pass. Blocking.
53
+ * narrowedLog reads the same from a runner's own output
54
+ * where it prints the filter (jest, pytest).
55
+ *
45
56
  * The other shapes read source files only, and skip comment lines. Configuration
46
57
  * (`*.config.*`, CI workflows, YAML) and documentation are out of scope:
47
58
  * `retries: process.env.CI ? 2 : 0` in a Playwright config tunes the runner,
@@ -299,3 +310,338 @@ export function scanTestGaming(diffText, options = {}) {
299
310
  }
300
311
  return findings;
301
312
  }
313
+
314
+ // ---------------------------------------------------------------------------
315
+ // narrowed-run: the test command ran a subset of the suite
316
+
317
+ const MAX_COMMAND_CHARS = 64 * 1024;
318
+
319
+ /**
320
+ * Shell words of a command line, split into the simple commands that `&&`,
321
+ * `||`, `;`, `|`, `&` and line breaks separate. Quotes are removed and a
322
+ * backslash escapes the next character. Redirections and their targets are
323
+ * dropped. One pass over the text, so a long command costs linear time.
324
+ */
325
+ function shellSegments(command) {
326
+ const text = String(command ?? "").slice(0, MAX_COMMAND_CHARS);
327
+ const segments = [[]];
328
+ let word = null;
329
+ let quote = null;
330
+ const end = () => {
331
+ if (word !== null) segments[segments.length - 1].push(word);
332
+ word = null;
333
+ };
334
+ for (let i = 0; i < text.length; i++) {
335
+ const c = text[i];
336
+ if (quote) {
337
+ if (c === quote) quote = null;
338
+ else if (c === "\\" && quote === '"' && i + 1 < text.length) word += text[++i];
339
+ else word += c;
340
+ continue;
341
+ }
342
+ if (c === "'" || c === '"') {
343
+ quote = c;
344
+ word ??= "";
345
+ } else if (c === "\\" && i + 1 < text.length) {
346
+ word = (word ?? "") + text[++i];
347
+ } else if (c === " " || c === "\t") {
348
+ end();
349
+ } else if (c === "\n" || c === ";" || c === "|" || c === "&") {
350
+ if (c === "&" && (text[i - 1] === ">" || text[i + 1] === ">")) {
351
+ word = (word ?? "") + c;
352
+ continue;
353
+ }
354
+ end();
355
+ if (segments[segments.length - 1].length) segments.push([]);
356
+ } else {
357
+ word = (word ?? "") + c;
358
+ }
359
+ }
360
+ end();
361
+ return segments.filter((s) => s.length).map(dropRedirections);
362
+ }
363
+
364
+ function dropRedirections(tokens) {
365
+ const out = [];
366
+ for (let i = 0; i < tokens.length; i++) {
367
+ const t = tokens[i];
368
+ if (/^\d*(?:>>?|<)(?:&\d*)?$/.test(t)) {
369
+ i++;
370
+ continue;
371
+ }
372
+ if (/^\d*(?:>>?|<)/.test(t)) continue;
373
+ out.push(t);
374
+ }
375
+ return out;
376
+ }
377
+
378
+ const base = (t) => String(t ?? "").replace(/^.*\//, "");
379
+
380
+ const WRAPPERS = new Set([
381
+ "env",
382
+ "time",
383
+ "nice",
384
+ "nohup",
385
+ "sudo",
386
+ "command",
387
+ "exec",
388
+ "npx",
389
+ "bunx",
390
+ "pnpx",
391
+ "xcrun",
392
+ ]);
393
+ const PACKAGE_MANAGERS = new Set(["npm", "yarn", "pnpm", "bun"]);
394
+ const RUNNER_NAMES = new Set(["jest", "vitest", "mocha", "playwright", "pytest", "rspec"]);
395
+
396
+ /** Index of the program a simple command runs, past assignments and wrappers. */
397
+ function programIndex(tokens) {
398
+ let i = 0;
399
+ for (let guard = 0; guard <= tokens.length; guard++) {
400
+ while (i < tokens.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[i])) i++;
401
+ const p = base(tokens[i]);
402
+ const next = tokens[i + 1];
403
+ if (WRAPPERS.has(p)) {
404
+ i++;
405
+ while (i < tokens.length && tokens[i].startsWith("-")) i++;
406
+ continue;
407
+ }
408
+ if (["bundle", "uv", "poetry", "pipenv"].includes(p) && (next === "exec" || next === "run")) {
409
+ i += 2;
410
+ continue;
411
+ }
412
+ if ((p === "pnpm" || p === "yarn") && (next === "exec" || next === "dlx")) {
413
+ i += 2;
414
+ continue;
415
+ }
416
+ if (PACKAGE_MANAGERS.has(p) && RUNNER_NAMES.has(base(next))) {
417
+ i++;
418
+ continue;
419
+ }
420
+ if (/^(?:python[0-9.]*|py)$/.test(p) && next === "-m") {
421
+ i += 2;
422
+ continue;
423
+ }
424
+ return i;
425
+ }
426
+ return i;
427
+ }
428
+
429
+ const TEST_FILE =
430
+ /(?:\.(?:test|spec)\.[A-Za-z0-9]+|_spec\.rb|(?:^|\/)test_[^/]*\.py|_test\.(?:py|go|rs)|Tests?\.(?:swift|kt|java))(?::\d+)?$|::/;
431
+
432
+ const isTestFileArg = (t) => !t.startsWith("-") && !t.includes("*") && TEST_FILE.test(t);
433
+
434
+ const CARGO_VALUE_FLAGS = new Set([
435
+ "-p",
436
+ "--package",
437
+ "--features",
438
+ "-F",
439
+ "--target",
440
+ "-j",
441
+ "--jobs",
442
+ "--manifest-path",
443
+ "--profile",
444
+ "--bin",
445
+ "--example",
446
+ "--bench",
447
+ "--color",
448
+ "--message-format",
449
+ "-Z",
450
+ "--target-dir",
451
+ "--config",
452
+ ]);
453
+
454
+ const GENERIC_FLAGS =
455
+ /^(?:-t|--testNamePattern|--test-name-pattern|--testPathPattern|--grep|-g|--passWithNoTests|--filter|--tests|-k|-only-testing)(?:[:=]|$)/;
456
+
457
+ const SUBCOMMANDS = new Set(["test", "run", "watch", "nextest", "exec", "--test"]);
458
+
459
+ /**
460
+ * Runners and what narrows each. `flag` is a test-selection or weakening flag;
461
+ * `positional` says how an argument selects tests: `testfile` when a test
462
+ * file or test id does (a directory or a glob does not), `any` when every
463
+ * argument is a name filter.
464
+ */
465
+ const RUNNERS = [
466
+ {
467
+ id: "xcodebuild",
468
+ is: (p) => p === "xcodebuild",
469
+ flag: /^-(?:only-testing|skip-testing|only-test-configuration|skip-test-configuration)(?:[:=]|$)/,
470
+ },
471
+ {
472
+ id: "swift",
473
+ is: (p, rest) => p === "swift" && rest[0] === "test",
474
+ flag: /^--(?:filter|skip)(?:=|$)/,
475
+ },
476
+ {
477
+ id: "gradle",
478
+ is: (p) => p === "gradlew" || p === "gradle",
479
+ flag: /^(?:--tests(?:=|$)|-Dtest\.single=|-Pandroid\.testInstrumentationRunnerArguments\.(?:class|package)=)/,
480
+ excludeTask: true,
481
+ },
482
+ {
483
+ id: "maven",
484
+ is: (p) => p === "mvn" || p === "mvnw",
485
+ flag: /^-D(?:test|it\.test|skipTests|maven\.test\.skip|skipITs)(?:=|$)/,
486
+ },
487
+ {
488
+ id: "jest",
489
+ is: (p) => p === "jest",
490
+ flag: /^(?:-t|--testNamePattern|--testPathPatterns?|--testPathIgnorePatterns|--passWithNoTests|-o|--onlyChanged|--onlyFailures|-f|--findRelatedTests|--changedSince|--lastCommit|--shard|--selectProjects|--testRegex)(?:=|$)/,
491
+ positional: "testfile",
492
+ },
493
+ {
494
+ id: "vitest",
495
+ is: (p) => p === "vitest",
496
+ flag: /^(?:-t|--testNamePattern|--passWithNoTests|--changed|--related|--shard|--project|--exclude)(?:=|$)/,
497
+ positional: "testfile",
498
+ subcommandNarrows: new Set(["related"]),
499
+ },
500
+ {
501
+ id: "pytest",
502
+ is: (p) => p === "pytest" || p === "py.test",
503
+ flag: /^(?:-k|--deselect|-m|--lf|--last-failed|--sw|--stepwise|--ignore|--ignore-glob)(?:=|$)/,
504
+ positional: "testfile",
505
+ },
506
+ {
507
+ id: "go",
508
+ is: (p, rest) => p === "go" && rest[0] === "test",
509
+ flag: /^--?(?:run|skip)(?:=|$)/,
510
+ },
511
+ {
512
+ id: "cargo",
513
+ is: (p, rest) => p === "cargo" && (rest[0] === "test" || rest[0] === "nextest"),
514
+ flag: /^--(?:skip|exact)(?:=|$)/,
515
+ positional: "any",
516
+ valueFlags: CARGO_VALUE_FLAGS,
517
+ },
518
+ {
519
+ id: "mocha",
520
+ is: (p) => p === "mocha",
521
+ flag: /^(?:-g|--grep|-f|--fgrep|-i|--invert)(?:=|$)/,
522
+ positional: "testfile",
523
+ },
524
+ {
525
+ id: "playwright",
526
+ is: (p, rest) => p === "playwright" && rest[0] === "test",
527
+ flag: /^(?:-g|--grep|--grep-invert|--last-failed|--only-changed|--shard)(?:=|$)/,
528
+ positional: "testfile",
529
+ },
530
+ {
531
+ id: "node",
532
+ is: (p, rest) => p === "node" && rest.includes("--test"),
533
+ flag: /^--test-(?:name-pattern|skip-pattern|only)(?:=|$)/,
534
+ positional: "testfile",
535
+ },
536
+ {
537
+ id: "dotnet",
538
+ is: (p, rest) => p === "dotnet" && rest[0] === "test",
539
+ flag: /^--filter(?:=|$)/,
540
+ },
541
+ {
542
+ id: "rspec",
543
+ is: (p) => p === "rspec",
544
+ flag: /^(?:-e|--example|--tag|--only-failures|--next-failure)(?:=|$)/,
545
+ positional: "testfile",
546
+ },
547
+ {
548
+ id: "package-script",
549
+ is: (p, rest) =>
550
+ PACKAGE_MANAGERS.has(p) &&
551
+ (rest[0] === "test" || (rest[0] === "run" && /^test/.test(rest[1] ?? ""))),
552
+ flag: GENERIC_FLAGS,
553
+ },
554
+ ];
555
+
556
+ /** What narrows one simple command, or null when it runs no known test runner. */
557
+ function narrowingIn(tokens) {
558
+ const at = programIndex(tokens);
559
+ const p = base(tokens[at]);
560
+ const rest = tokens.slice(at + 1);
561
+ const runner = RUNNERS.find((r) => r.is(p, rest));
562
+ if (!runner) return null;
563
+ const id = runner.id === "package-script" ? p : runner.id;
564
+ const reasons = [];
565
+ for (let i = 0; i < rest.length; i++) {
566
+ const t = rest[i];
567
+ if (runner.flag.test(t)) {
568
+ reasons.push(t.replace(/[:=].*$/, ""));
569
+ continue;
570
+ }
571
+ if (
572
+ runner.excludeTask &&
573
+ (t === "-x" || t === "--exclude-task") &&
574
+ /test/i.test(rest[i + 1] ?? "")
575
+ ) {
576
+ reasons.push(`${t} ${rest[i + 1]}`);
577
+ i++;
578
+ continue;
579
+ }
580
+ if (i === 0 && runner.subcommandNarrows?.has(t)) {
581
+ reasons.push(t);
582
+ continue;
583
+ }
584
+ if (runner.valueFlags?.has(t)) {
585
+ i++;
586
+ continue;
587
+ }
588
+ if (t.startsWith("-") || (i < 2 && SUBCOMMANDS.has(t))) continue;
589
+ if (runner.positional === "testfile" && isTestFileArg(t)) reasons.push(t);
590
+ else if (runner.positional === "any" && !t.includes("*")) reasons.push(t);
591
+ }
592
+ return { runner: id, reasons };
593
+ }
594
+
595
+ /**
596
+ * Did this test command run a subset of the suite?
597
+ *
598
+ * @param {string} command the command line as typed
599
+ * @returns {{narrowed: boolean, runner: string|null, reasons: string[]}}
600
+ */
601
+ export function narrowedRun(command) {
602
+ let first = null;
603
+ for (const tokens of shellSegments(command)) {
604
+ const n = narrowingIn(tokens);
605
+ if (!n) continue;
606
+ if (n.reasons.length) return { narrowed: true, runner: n.runner, reasons: n.reasons };
607
+ first ??= n.runner;
608
+ }
609
+ return { narrowed: false, runner: first, reasons: [] };
610
+ }
611
+
612
+ const LOG_NARROWING = [
613
+ { re: /Ran all test suites (?:with tests )?matching/, reason: "jest name or path filter" },
614
+ { re: /\b[1-9]\d* deselected\b/, reason: "pytest deselected tests" },
615
+ ];
616
+
617
+ /**
618
+ * Does a runner's own output say it ran a filtered subset? Reads only the
619
+ * lines a runner prints for a filter, so a full run is never flagged by it.
620
+ *
621
+ * @param {string} log
622
+ * @returns {{narrowed: boolean, reasons: string[]}}
623
+ */
624
+ export function narrowedLog(log) {
625
+ const text = String(log ?? "");
626
+ const reasons = LOG_NARROWING.filter(({ re }) => re.test(text)).map((x) => x.reason);
627
+ return { narrowed: reasons.length > 0, reasons };
628
+ }
629
+
630
+ /**
631
+ * The reviewer-shaped finding for a narrowed test command, or null.
632
+ *
633
+ * @param {string} command
634
+ * @param {string} file where the command was read from
635
+ */
636
+ export function narrowedRunFinding(command, file) {
637
+ const r = narrowedRun(command);
638
+ if (!r.narrowed) return null;
639
+ return finding(
640
+ file,
641
+ 1,
642
+ "narrowed-run",
643
+ "blocking",
644
+ String(command),
645
+ `The test run behind the pass was narrowed (${r.runner}: ${r.reasons.join(", ")}). A green subset says nothing about the tests it left out; run the whole suite.`,
646
+ );
647
+ }