@mmerterden/multi-agent-pipeline 20.41.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 (103) hide show
  1. package/CHANGELOG.md +44 -0
  2. package/README.md +1 -1
  3. package/README.tr.md +1 -1
  4. package/docs/ecosystem.md +45 -8
  5. package/docs/facts.json +7 -7
  6. package/docs/features.md +9 -4
  7. package/install/claude.mjs +34 -1
  8. package/install/templates/claude-hooks.json +12 -1
  9. package/manifest.json +106 -86
  10. package/package.json +3 -2
  11. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  12. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  13. package/pipeline/lib/args.mjs +131 -4
  14. package/pipeline/lib/bg-launch.mjs +5 -2
  15. package/pipeline/lib/credential-store.sh +11 -1
  16. package/pipeline/lib/hook-once.mjs +134 -0
  17. package/pipeline/lib/isotonic.mjs +73 -0
  18. package/pipeline/lib/low-disk.mjs +153 -0
  19. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  20. package/pipeline/lib/md2confluence-v3.py +8 -7
  21. package/pipeline/lib/model-dispatch.sh +26 -2
  22. package/pipeline/lib/normalize-text.mjs +135 -0
  23. package/pipeline/lib/outbound-gate.mjs +21 -3
  24. package/pipeline/lib/plan-todos.sh +17 -4
  25. package/pipeline/lib/redact.mjs +12 -3
  26. package/pipeline/lib/risky-settings.mjs +198 -0
  27. package/pipeline/lib/route-state.sh +1 -0
  28. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  29. package/pipeline/lib/session-usage.mjs +232 -0
  30. package/pipeline/lib/source-digest.mjs +211 -0
  31. package/pipeline/lib/tdd-evidence.mjs +250 -17
  32. package/pipeline/lib/untrusted-fence.mjs +132 -1
  33. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  34. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  35. package/pipeline/multi-agent-refs/features/doctor.md +51 -4
  36. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  37. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  38. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  39. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  40. package/pipeline/multi-agent-refs/help/en.md +1 -1
  41. package/pipeline/multi-agent-refs/help/tr.md +1 -1
  42. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  43. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  44. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  45. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  46. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  47. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  48. package/pipeline/office/toolkit.json +1 -1
  49. package/pipeline/rules/outside-the-pipeline.md +1 -1
  50. package/pipeline/schemas/doctor-report.schema.json +47 -0
  51. package/pipeline/schemas/plan-todos.schema.json +29 -1
  52. package/pipeline/schemas/prefs.schema.json +63 -0
  53. package/pipeline/schemas/route-config.schema.json +51 -0
  54. package/pipeline/schemas/secret-patterns.json +17 -1
  55. package/pipeline/schemas/toolkit-path-params.json +15 -1
  56. package/pipeline/scripts/_cost-advise.mjs +357 -0
  57. package/pipeline/scripts/_cost-budget.mjs +78 -0
  58. package/pipeline/scripts/_cost.mjs +29 -0
  59. package/pipeline/scripts/_decode_text.py +107 -0
  60. package/pipeline/scripts/_guard-probe.mjs +406 -0
  61. package/pipeline/scripts/_guard_rules.py +206 -0
  62. package/pipeline/scripts/_memory-policy.mjs +1 -25
  63. package/pipeline/scripts/_retrieval.mjs +148 -2
  64. package/pipeline/scripts/_secret-scan.mjs +6 -1
  65. package/pipeline/scripts/_stack-routing.mjs +1 -0
  66. package/pipeline/scripts/_test-gaming.mjs +346 -0
  67. package/pipeline/scripts/agent-guard.py +8 -1
  68. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  69. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  70. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  71. package/pipeline/scripts/capture-resume.sh +9 -1
  72. package/pipeline/scripts/cost-analyze.mjs +66 -4
  73. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  74. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  75. package/pipeline/scripts/doctor.mjs +169 -44
  76. package/pipeline/scripts/evidence-gate.mjs +90 -0
  77. package/pipeline/scripts/gate-ledger.mjs +76 -21
  78. package/pipeline/scripts/gc-tmp.sh +5 -0
  79. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  80. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  81. package/pipeline/scripts/note-agent-event.mjs +2 -0
  82. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  83. package/pipeline/scripts/note-skill-use.mjs +4 -1
  84. package/pipeline/scripts/pre-commit-check.sh +2 -2
  85. package/pipeline/scripts/pre-push-check.sh +8 -1
  86. package/pipeline/scripts/publish-staged.mjs +324 -0
  87. package/pipeline/scripts/route-learn.mjs +628 -0
  88. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  89. package/pipeline/scripts/scan-agent-config.sh +1 -1
  90. package/pipeline/scripts/statusline.mjs +309 -0
  91. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  92. package/pipeline/scripts/triage-memory.mjs +12 -4
  93. package/pipeline/scripts/uninstall.mjs +1 -0
  94. package/pipeline/skills/.skill-manifest.json +8 -4
  95. package/pipeline/skills/.skills-index.json +14 -3
  96. package/pipeline/skills/shared/README.md +5 -4
  97. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  98. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  99. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  100. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  102. package/pipeline/skills/skill-copies.json +4 -0
  103. package/pipeline/skills/skills-index.md +3 -2
@@ -40,10 +40,25 @@
40
40
  * mode without the evidence). Phase 3 notes the unverified todos and the
41
41
  * exemptions a todo declared for itself (`--no-tests`, `selfDeclared`).
42
42
  *
43
+ * The tests RED wrote are kept. RED records `red.testFiles[]`: every test file
44
+ * of the run's work tree (state.worktreePath, or --repo) committed since the
45
+ * run base (state.baseSha, else MA_RUN_BASE_SHA; HEAD when neither is set)
46
+ * or new or changed in the work tree, as {path, blob}, so a failing test
47
+ * committed before RED is kept too. The blob is written into that
48
+ * repository's object store so the bytes can come back. Under
49
+ * MULTI_AGENT_UNATTENDED=1 test-integrity-gate reports even a recorded edit
50
+ * as blocking. GREEN refuses (exit 1) when one of those files was
51
+ * modified or deleted since, because a suite made green by weakening its own
52
+ * new test proves nothing; `restore` writes the RED bytes back. A legitimate
53
+ * fix to the test passes with `--test-edit-reason <why>` and is kept as
54
+ * `green.testEdits[]`, which test-integrity-gate --state reports for review.
55
+ * Outside a git work tree no files are recorded and nothing is refused.
56
+ *
43
57
  * CLI (exit 0 ok, 1 the evidence does not hold, 2 usage or unreadable input):
44
58
  * tdd-evidence.mjs parse <results>
45
- * tdd-evidence.mjs red --state <f> --todo <id> --results <r> [--tests a,b] [--already-passing <reason>] [--mode off|warn|enforce]
46
- * tdd-evidence.mjs green --state <f> --todo <id> --results <r>
59
+ * tdd-evidence.mjs red --state <f> --todo <id> --results <r> [--tests a,b] [--already-passing <reason>] [--mode off|warn|enforce] [--repo <dir>]
60
+ * tdd-evidence.mjs green --state <f> --todo <id> --results <r> [--test-edit-reason <why>] [--repo <dir>]
61
+ * tdd-evidence.mjs restore --state <f> --todo <id> [--repo <dir>]
47
62
  * tdd-evidence.mjs check --state <f> --todo <id> --mode off|warn|enforce [--no-tests <reason>]
48
63
  * tdd-evidence.mjs unverified --state <f>
49
64
  *
@@ -56,10 +71,12 @@
56
71
  */
57
72
 
58
73
  import { spawnSync } from "node:child_process";
59
- import { readdirSync, readFileSync, statSync } from "node:fs";
60
- import { basename, join } from "node:path";
74
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";
75
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
61
76
 
77
+ import { isTestPath } from "../scripts/_handle-patterns.mjs";
62
78
  import { fromXcresultJson, summarize } from "../scripts/test-summary.mjs";
79
+ import { mkdirSafe, writeFileSafe } from "./safe-write.mjs";
63
80
  import { invokedDirectly } from "./invoked-directly.mjs";
64
81
  import { ArgsError, parseArgs } from "./args.mjs";
65
82
 
@@ -327,6 +344,191 @@ export function resultsFresh(path, startedAt) {
327
344
  }
328
345
  }
329
346
 
347
+ // ---------------------------------------------------------------------------
348
+ // Test files written in RED
349
+
350
+ const MAX_TEST_FILES = 200;
351
+ const GIT_TIMEOUT_MS = 20000;
352
+
353
+ function gitRun(dir, args, { input, buffer = false } = {}) {
354
+ const r = spawnSync("git", ["-C", dir, ...args], {
355
+ encoding: buffer ? null : "utf8",
356
+ timeout: GIT_TIMEOUT_MS,
357
+ maxBuffer: 256 * 1024 * 1024,
358
+ input,
359
+ });
360
+ return r.status === 0 && !r.error ? r.stdout : null;
361
+ }
362
+
363
+ /** The root of the git work tree `dir` is in, or null. */
364
+ export function workTreeRoot(dir) {
365
+ if (!dir || !existsSync(dir)) return null;
366
+ const out = gitRun(dir, ["rev-parse", "--show-toplevel"]);
367
+ return out ? out.trim() : null;
368
+ }
369
+
370
+ /** A repository-relative path that stays inside the work tree. */
371
+ function insideRoot(root, path) {
372
+ if (typeof path !== "string" || !path || isAbsolute(path) || path.includes("\0")) return null;
373
+ const abs = resolve(root, path);
374
+ const rel = relative(root, abs);
375
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) return null;
376
+ return abs;
377
+ }
378
+
379
+ /** The commit `ref` names in the work tree at root, or null. */
380
+ function commitOf(root, ref) {
381
+ if (typeof ref !== "string" || !/^[0-9a-f]{7,64}$/i.test(ref)) return null;
382
+ const out = gitRun(root, [
383
+ "rev-parse",
384
+ "--verify",
385
+ "--quiet",
386
+ "--end-of-options",
387
+ `${ref}^{commit}`,
388
+ ]);
389
+ return out ? out.trim() || null : null;
390
+ }
391
+
392
+ /**
393
+ * The test files the run wrote: those committed since the run base
394
+ * (`git diff <base>...HEAD`, deletions left out), and the work tree's new,
395
+ * changed and renamed-to ones, untracked included. Without a base, or with
396
+ * one that names no commit here, the run starts at HEAD and only the work
397
+ * tree counts.
398
+ */
399
+ function changedTestFiles(root, base = null) {
400
+ const paths = [];
401
+ const since = commitOf(root, base);
402
+ if (since) {
403
+ const committed = gitRun(root, [
404
+ "diff",
405
+ "--name-only",
406
+ "-z",
407
+ "--diff-filter=d",
408
+ `${since}...HEAD`,
409
+ ]);
410
+ for (const path of (committed ?? "").split("\0"))
411
+ if (path && isTestPath(path)) paths.push(path);
412
+ }
413
+ const out = gitRun(root, ["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
414
+ if (out === null) return paths;
415
+ const recs = out.split("\0");
416
+ for (let i = 0; i < recs.length; i++) {
417
+ const rec = recs[i];
418
+ if (rec.length < 4) continue;
419
+ const xy = rec.slice(0, 2);
420
+ if (xy[0] === "R" || xy[0] === "C") i++;
421
+ if (xy.includes("D")) continue;
422
+ const path = rec.slice(3);
423
+ if (isTestPath(path)) paths.push(path);
424
+ }
425
+ return paths;
426
+ }
427
+
428
+ /** The run base: the state's baseSha, else MA_RUN_BASE_SHA, else none (HEAD). */
429
+ export function runBase(state, env = process.env) {
430
+ const fromState = typeof state?.baseSha === "string" ? state.baseSha.trim() : "";
431
+ return fromState || String(env.MA_RUN_BASE_SHA || "").trim() || null;
432
+ }
433
+
434
+ function hashFiles(root, paths, write) {
435
+ if (!paths.length) return [];
436
+ const args = write ? ["hash-object", "-w", "--stdin-paths"] : ["hash-object", "--stdin-paths"];
437
+ const out = gitRun(root, args, { input: `${paths.join("\n")}\n` });
438
+ const shas = out ? out.trim().split("\n") : [];
439
+ if (shas.length !== paths.length) throw new Unreadable(`git could not hash ${paths.join(", ")}`);
440
+ return shas;
441
+ }
442
+
443
+ /**
444
+ * Keep the test files a RED run stands on: each file's bytes go into the
445
+ * repository's object store and its blob id is returned. `paths` defaults to
446
+ * the test files the run wrote since `base` (changedTestFiles).
447
+ *
448
+ * @param {string} repo
449
+ * @param {string[]|null} [paths]
450
+ * @param {{base?: string|null}} [opts]
451
+ * @returns {{path: string, blob: string}[]}
452
+ */
453
+ export function snapshotTestFiles(repo, paths = null, { base = null } = {}) {
454
+ const root = workTreeRoot(repo);
455
+ if (!root) return [];
456
+ const wanted = [...new Set(paths ?? changedTestFiles(root, base))]
457
+ .filter((p) => {
458
+ const abs = insideRoot(root, p);
459
+ return abs && !p.includes("\n") && existsSync(abs) && lstatSync(abs).isFile();
460
+ })
461
+ .sort()
462
+ .slice(0, MAX_TEST_FILES);
463
+ const blobs = hashFiles(root, wanted, true);
464
+ return wanted.map((path, i) => ({ path, blob: blobs[i] }));
465
+ }
466
+
467
+ /**
468
+ * Which kept test files no longer hold their RED bytes.
469
+ *
470
+ * @param {string} repo
471
+ * @param {{path: string, blob: string}[]} testFiles
472
+ * @returns {{path: string, change: "modified"|"deleted"}[]}
473
+ */
474
+ export function testFileChanges(repo, testFiles) {
475
+ const root = workTreeRoot(repo);
476
+ if (!root || !Array.isArray(testFiles) || !testFiles.length) return [];
477
+ const present = [];
478
+ const changes = [];
479
+ for (const f of testFiles) {
480
+ const abs = insideRoot(root, f?.path);
481
+ if (!abs) continue;
482
+ if (!existsSync(abs)) changes.push({ path: f.path, change: "deleted" });
483
+ else present.push(f);
484
+ }
485
+ const now = hashFiles(
486
+ root,
487
+ present.map((f) => f.path),
488
+ false,
489
+ );
490
+ present.forEach((f, i) => {
491
+ if (now[i] !== f.blob) changes.push({ path: f.path, change: "modified" });
492
+ });
493
+ return changes.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
494
+ }
495
+
496
+ /**
497
+ * Write the RED bytes of every kept test file that changed back into the work
498
+ * tree. A path that leaves the work tree, or a link on the way, is refused.
499
+ *
500
+ * @param {string} repo
501
+ * @param {{path: string, blob: string}[]} testFiles
502
+ * @returns {string[]} the restored paths
503
+ */
504
+ export function restoreTestFiles(repo, testFiles) {
505
+ const root = workTreeRoot(repo);
506
+ if (!root) throw new Unreadable(`${repo} is not in a git work tree`);
507
+ for (const f of testFiles ?? []) {
508
+ if (!insideRoot(root, f?.path)) {
509
+ throw new Refused(`refusing to restore ${f?.path}: outside the work tree`);
510
+ }
511
+ }
512
+ const changed = new Set(testFileChanges(root, testFiles).map((c) => c.path));
513
+ const restored = [];
514
+ for (const f of testFiles ?? []) {
515
+ if (!changed.has(f.path)) continue;
516
+ const bytes = gitRun(root, ["cat-file", "blob", f.blob], { buffer: true });
517
+ if (bytes === null) throw new Unreadable(`blob ${f.blob} for ${f.path} is gone`);
518
+ const abs = insideRoot(root, f.path);
519
+ try {
520
+ mkdirSafe(dirname(abs), { mode: 0o755, anchors: [root] });
521
+ writeFileSafe(abs, bytes, { mode: 0o644, anchors: [root] });
522
+ } catch (err) {
523
+ if (err?.code === "ELINKED")
524
+ throw new Refused(`refusing to restore ${f.path}: ${err.message}`);
525
+ throw err;
526
+ }
527
+ restored.push(f.path);
528
+ }
529
+ return restored;
530
+ }
531
+
330
532
  // ---------------------------------------------------------------------------
331
533
  // Decisions
332
534
 
@@ -407,9 +609,19 @@ export function redRecord(summary, { tests = [], alreadyPassing = "", mode = "wa
407
609
  * The GREEN record, on top of the todo's RED record.
408
610
  *
409
611
  * @param {object} summary
410
- * @param {{prior: object|null, testPolicy?: string, now: string}} opts
612
+ * @param {{prior: object|null, testPolicy?: string, now: string,
613
+ * testChanges?: {path: string, change: string}[], testEditReason?: string}} opts
411
614
  */
412
- export function greenRecord(summary, { prior, testPolicy, now }) {
615
+ export function greenRecord(
616
+ summary,
617
+ { prior, testPolicy, now, testChanges = [], testEditReason = "" },
618
+ ) {
619
+ if (testChanges.length && !testEditReason) {
620
+ const list = testChanges.map((c) => `${c.path} (${c.change})`).join(", ");
621
+ throw new Refused(
622
+ `test file(s) written in RED changed before GREEN: ${list}. A suite made green by weakening its own new test proves nothing: restore them (tdd-evidence.mjs restore, plan-todos.sh tdd-restore), or, when the test itself was wrong, record why with --test-edit-reason <why>`,
623
+ );
624
+ }
413
625
  if (!prior?.red && testPolicy !== "tests-after") {
414
626
  throw new Refused("no RED run recorded for this todo; record RED first");
415
627
  }
@@ -436,7 +648,10 @@ export function greenRecord(summary, { prior, testPolicy, now }) {
436
648
  base.outcome = "verified";
437
649
  delete base.reason;
438
650
  }
439
- return { ...base, green: { at: now, failed: 0, total: summary.total } };
651
+ const green = { at: now, failed: 0, total: summary.total };
652
+ if (testChanges.length)
653
+ green.testEdits = testChanges.map((c) => ({ ...c, reason: testEditReason }));
654
+ return { ...base, green };
440
655
  }
441
656
 
442
657
  function exemption(todo, { taskType, testPolicy, noTests }) {
@@ -532,21 +747,39 @@ function main(argv) {
532
747
  if (!f.results) throw new Unreadable("--results is required");
533
748
  const summary = parseResults(f.results);
534
749
  resultsFresh(f.results, todo.startedAt);
535
- const record =
536
- cmd === "red"
537
- ? redRecord(summary, {
538
- tests: (f.tests ?? "").split(",").filter(Boolean),
539
- alreadyPassing: f["already-passing"] ?? "",
540
- mode: f.mode,
541
- now,
542
- })
543
- : greenRecord(summary, { prior: todo.tdd ?? null, testPolicy: state.testPolicy, now });
750
+ const repo = typeof f.repo === "string" ? f.repo : state.worktreePath;
751
+ let record;
752
+ if (cmd === "red") {
753
+ record = redRecord(summary, {
754
+ tests: (f.tests ?? "").split(",").filter(Boolean),
755
+ alreadyPassing: f["already-passing"] ?? "",
756
+ mode: f.mode,
757
+ now,
758
+ });
759
+ const testFiles =
760
+ record.outcome === "red"
761
+ ? snapshotTestFiles(repo, null, { base: runBase(state, process.env) })
762
+ : [];
763
+ if (testFiles.length) record.red.testFiles = testFiles;
764
+ } else {
765
+ record = greenRecord(summary, {
766
+ prior: todo.tdd ?? null,
767
+ testPolicy: state.testPolicy,
768
+ now,
769
+ testChanges: testFileChanges(repo, todo.tdd?.red?.testFiles),
770
+ testEditReason: typeof f["test-edit-reason"] === "string" ? f["test-edit-reason"] : "",
771
+ });
772
+ }
544
773
  if (record.red?.testsUnverifiable) {
545
774
  process.stderr.write(
546
775
  `tdd-evidence: warning: ${f.results} names no failing test, so --tests ${f.tests} is recorded unchecked (red.testsUnverifiable); JUnit XML names them\n`,
547
776
  );
548
777
  }
549
778
  print(record);
779
+ } else if (cmd === "restore") {
780
+ const { state, todo } = loadTodo(f);
781
+ const repo = typeof f.repo === "string" ? f.repo : state.worktreePath;
782
+ print({ restored: restoreTestFiles(repo, todo.tdd?.red?.testFiles ?? []) });
550
783
  } else if (cmd === "check") {
551
784
  const { state, todo } = loadTodo(f);
552
785
  print(
@@ -566,7 +799,7 @@ function main(argv) {
566
799
  }
567
800
  } else {
568
801
  throw new Unreadable(
569
- `unknown subcommand '${cmd ?? ""}' (parse | red | green | check | unverified)`,
802
+ `unknown subcommand '${cmd ?? ""}' (parse | red | green | restore | check | unverified)`,
570
803
  );
571
804
  }
572
805
  return 0;
@@ -22,6 +22,17 @@
22
22
  * Extra attributes follow `source` in the order given; a value loses `"`, `<`,
23
23
  * `>` and line breaks, and an empty one is left out.
24
24
  *
25
+ * Text that reads like instructions to the model is marked, never changed or
26
+ * refused: wrapUntrusted adds `suspicious="<classes>"` last, naming the
27
+ * SUSPICIOUS_CLASSES its rules matched, in that list's order. The text
28
+ * patterns run on the text and on a fold of it (NFKC, format characters such
29
+ * as zero-width ones removed), over the head and tail of a long text, with
30
+ * bounded gaps only. Hidden or look-alike characters hide text rather than
31
+ * instruct, so they are not marked. A caller that passes its own `suspicious`
32
+ * value, or the toolkit's `injection-flags`, keeps it and gets no second mark.
33
+ * Blocking stays with the guards; the mark is a signal for the model and for
34
+ * review.
35
+ *
25
36
  * This file imports nothing, so the vendored copy runs on its own.
26
37
  *
27
38
  * @module untrusted-fence
@@ -47,14 +58,134 @@ export function hasFenceMarker(text) {
47
58
  return MARKER.test(String(text ?? ""));
48
59
  }
49
60
 
61
+ export const SUSPICIOUS_SCAN_HEAD = 196_608;
62
+ export const SUSPICIOUS_SCAN_TAIL = 65_536;
63
+
64
+ /** The classes a mark can name, in the order it lists them (the toolkit's suspiciousOf order). */
65
+ export const SUSPICIOUS_CLASSES = Object.freeze([
66
+ "instruction-override",
67
+ "role-tag",
68
+ "tool-invocation",
69
+ "exfiltration",
70
+ "fence-escape",
71
+ ]);
72
+
73
+ /**
74
+ * Instruction-shaped text by family, each folded into one class. The family
75
+ * ids and patterns are the toolkit's injection-scan families, so a fenced
76
+ * tool result and a fenced ticket carry the same names. Every pattern has
77
+ * bounded gaps only, so the cost is linear in the scanned text.
78
+ */
79
+ export const SUSPICIOUS_RULES = Object.freeze([
80
+ {
81
+ id: "instruction-override",
82
+ cls: "instruction-override",
83
+ re: /\b(ignore|disregard|forget|override)\b[^.\n]{0,40}\b(previous|prior|above|earlier|all|your|the)\b[^.\n]{0,30}\b(instructions?|prompts?|rules|directions|guidelines)\b/i,
84
+ },
85
+ {
86
+ id: "role-reassignment",
87
+ cls: "instruction-override",
88
+ re: /\b(you are now (a|an|the|in) [^.\n]{0,30}\b(ai|assistant|model|agent|bot|mode|persona|character)\b|you are (actually|secretly) (a|an|the)\b|from now on,? you (are|will|must|should)\b|act as (an?|the) (unrestricted|jailbroken|developer mode)|developer mode enabled|do anything now|jailbreak mode)/i,
89
+ },
90
+ {
91
+ id: "directive-injection",
92
+ cls: "instruction-override",
93
+ re: /(^|\n)[ \t#>*-]*(new|updated|revised|real|actual|additional|hidden)\s+(instructions?|directives?|task|system prompt|orders)\s*:|\b(the (assistant|ai|model|agent)|you) (must|should) (not|never) (tell|inform|mention|reveal|show)\b[^.\n]{0,20}\b(the )?user\b|\b(do not|don't|never) (tell|inform|mention (this|it) to|show (this|it) to) the user\b/i,
94
+ },
95
+ {
96
+ id: "system-prompt-probe",
97
+ cls: "instruction-override",
98
+ re: /\b(reveal|print|show|repeat|output)\b[^.\n]{0,30}\b(system prompt|hidden instructions|initial instructions)\b/i,
99
+ },
100
+ {
101
+ id: "chat-template-token",
102
+ cls: "role-tag",
103
+ re: /<\|(im_start|im_end|system|endoftext|start_header_id|end_header_id|eot_id)\|>|\[\/?INST\]|<<\/?SYS>>|<\/?(system|assistant)>|\n\n(Human|Assistant):/i,
104
+ },
105
+ { id: "forged-turns", cls: "role-tag", turns: true },
106
+ {
107
+ id: "tool-call-mimicry",
108
+ cls: "tool-invocation",
109
+ re: /<\/?(function_calls|invoke|tool_use|tool_call|tool_code)\b|"(tool_use|function_call)"\s*:|"tool_calls"\s*:\s*\[|"method"\s*:\s*"tools\/call"/i,
110
+ },
111
+ {
112
+ id: "exfiltration-request",
113
+ cls: "exfiltration",
114
+ re: /\b(send|post|upload|forward|exfiltrate|leak)\b[^.\n]{0,60}\b(api[_ -]?keys?|tokens?|secrets?|credentials?|passwords?|env(ironment)? variables?|\.env|ssh keys?)\b/i,
115
+ },
116
+ {
117
+ id: "covert-link-action",
118
+ cls: "exfiltration",
119
+ re: /\b(open|visit|navigate to|fetch|curl|click)\b[^.\n]{0,20}https?:\/\/\S+[^.\n]{0,40}\b(silently|without telling|do not mention|don't mention|secretly)\b/i,
120
+ },
121
+ { id: "fence-marker", cls: "fence-escape", raw: MARKER },
122
+ ]);
123
+
124
+ const ROLE_LINE = /^[ \t]*(system|assistant|user|human)[ \t]*:/gim;
125
+ const MAX_ROLE_LINES = 64;
126
+
127
+ /**
128
+ * A forged conversation: line-start role markers for at least two different
129
+ * roles, one of them system or assistant. A single "System: macOS 14" line is
130
+ * a spec sheet, not a turn.
131
+ */
132
+ function forgedTurns(text) {
133
+ const roles = new Set();
134
+ let seen = 0;
135
+ for (const m of text.matchAll(ROLE_LINE)) {
136
+ roles.add(m[1].toLowerCase());
137
+ if (++seen >= MAX_ROLE_LINES) break;
138
+ }
139
+ return roles.size >= 2 && (roles.has("system") || roles.has("assistant"));
140
+ }
141
+
142
+ /** The part of a text the rules read: all of it, or its head and tail joined by a newline. */
143
+ function scanWindow(text) {
144
+ if (text.length <= SUSPICIOUS_SCAN_HEAD + SUSPICIOUS_SCAN_TAIL) return text;
145
+ return `${text.slice(0, SUSPICIOUS_SCAN_HEAD)}\n${text.slice(text.length - SUSPICIOUS_SCAN_TAIL)}`;
146
+ }
147
+
148
+ /** The fold the text patterns also run on: NFKC, format characters removed. */
149
+ function foldForRules(text) {
150
+ return text.normalize("NFKC").replace(/\p{Cf}/gu, "");
151
+ }
152
+
153
+ /**
154
+ * The SUSPICIOUS_CLASSES the text falls into, in class order, each once.
155
+ *
156
+ * @param {string} text
157
+ * @returns {string[]}
158
+ */
159
+ export function suspiciousKinds(text) {
160
+ const raw = scanWindow(String(text ?? ""));
161
+ if (!raw) return [];
162
+ const folded = foldForRules(raw);
163
+ const hit = new Set();
164
+ for (const r of SUSPICIOUS_RULES) {
165
+ if (hit.has(r.cls)) continue;
166
+ const matched = r.raw
167
+ ? r.raw.test(raw)
168
+ : r.turns
169
+ ? forgedTurns(raw) || (folded !== raw && forgedTurns(folded))
170
+ : r.re.test(raw) || (folded !== raw && r.re.test(folded));
171
+ if (matched) hit.add(r.cls);
172
+ }
173
+ return SUSPICIOUS_CLASSES.filter((c) => hit.has(c));
174
+ }
175
+
50
176
  /**
51
177
  * @param {string} source where the text came from, e.g. `jira:PROJ-12`
52
178
  * @param {string} text
53
179
  * @param {Record<string, unknown>} [attrs] extra attributes after source
54
180
  */
55
181
  export function wrapUntrusted(source, text, attrs = {}) {
182
+ const own = (k) => Object.prototype.hasOwnProperty.call(attrs, k);
183
+ const all =
184
+ own("suspicious") || own("injection-flags")
185
+ ? attrs
186
+ : { ...attrs, suspicious: suspiciousKinds(text).join(",") };
56
187
  let head = `${UNTRUSTED_OPEN} source="${clean(source || "unknown")}"`;
57
- for (const [name, value] of Object.entries(attrs)) {
188
+ for (const [name, value] of Object.entries(all)) {
58
189
  if (!ATTR_NAME.test(name) || name === "source") {
59
190
  throw new Error(`untrusted-fence: bad attribute name ${JSON.stringify(name)}`);
60
191
  }
@@ -62,7 +62,7 @@ behind.
62
62
  15. **New assets default to SVG.** Section 8 entries marked `new` are SVG unless a documented exception is captured in the rationale column (Lottie for motion design, optimized PNG for raster-only icons). PDF, JPG, and unoptimized PNG are rejected.
63
63
  16. **Files-to-Add tag required.** Every row in Section 14 carries one tag from `Reuse | Add new | Modify`. Untagged rows fail the dispatch gate.
64
64
  17. **API response variants exhaustive.** Section 9 lists every HTTP status code returned by the endpoint with at least one example body and the matching UI outcome. Phrases like "other errors" or "various 4xx" are rejected.
65
- 18. **Screenshots embedded, not linked, and every inventory row gets one.** Section 5 frame galleries reference local PNG files. Dispatch uploads them as Confluence multipart attachments and injects `<ac:image><ri:attachment ri:filename="..." /></ac:image>` into the page body. The gallery is generated from the inventory, never hand-picked: one row, one embedded image, ordered by node id and titled `<nodeId> <frame name>`. A bare filename in a table cell is text to the reader, not a picture: an attachment that is uploaded but not embedded is invisible on the page. Narrowing to a canonical subset for page weight is not a call the run makes on its own; the display-width cap (`md2confluence-v3.py --image-width`, phone frames overriding to 320) already solves readability without dropping evidence. Dispatch reports the embedded-over-inventory ratio and warns below 1. URL-only Figma references in Section 5 are a review finding, not a validator ERROR: the check belongs to the Confluence dispatch step, which is the only place that knows whether an attachment upload succeeded.
65
+ 18. **Screenshots embedded, not linked, and every inventory row gets one.** Section 5 frame galleries reference local PNG files. Dispatch uploads them as Confluence multipart attachments and injects `<ac:image><ri:attachment ri:filename="..." /></ac:image>` into the page body. The gallery is generated from the inventory, never hand-picked: one row, one embedded image, ordered by node id and titled `<nodeId> <frame name>`. A bare filename in a table cell is text to the reader, not a picture: an attachment that is uploaded but not embedded is invisible on the page. Narrowing to a canonical subset for page weight is not a call the run makes on its own; the display-width cap (`md2confluence-v3.py --image-width`, with every gallery frame at the 240 px table-cell width) already solves readability without dropping evidence. Dispatch reports the embedded-over-inventory ratio and warns below 1. URL-only Figma references in Section 5 are a review finding, not a validator ERROR: the check belongs to the Confluence dispatch step, which is the only place that knows whether an attachment upload succeeded.
66
66
  19. **All Figma variants drilled, and drilled means read.** When a Figma section URL is supplied, all child frames are drilled, not just the canonical default. The renderer enumerates child frames via `mcp__claude_ai_Figma__get_metadata` (Tier 1) or `figma-screenshot.sh --section` (Tier 2) and produces one Section 5.1 row per child frame. Counting them is not drilling them: extract the visible `TEXT` layers inside each frame's own bounds, dropping hidden layers and component-instance boilerplate that overflows the frame (default card and widget filler can outnumber the real text several times over). A frame may be called out of scope only by quoting its own extracted text; "the name looked unrelated" is not a reason. Opening a Section 20 question about a frame requires that its text was extracted first, and asking about a frame nobody read fails the dispatch gate: a frame whose name looks ambiguous can spell out a whole step in its text.
67
67
  20. **Localization mode (ownership-aware).** Section 10's shape is driven by the project `figma-config` `localization.ownership` (default `in-repo`). The locale set comes from `localization.locales` (default `tr, en, ar, de, es, fr, it, ru`); do not hardcode a locale list in the render.
68
68
  - **`in-repo`** (default, historical behavior): new keys carry filled cells for every configured locale. Placeholder values `[bekleniyor: çeviri ekibi]` / `[pending: translation team]` are a soft state and the dispatch report flags `i18n_pending: <count>` as a blocker. Empty cells are rejected outright.
@@ -1,4 +1,12 @@
1
- # cost analysis - projection, anomaly, burn, diff
1
+ # cost analysis - projection, anomaly, burn, diff, advise
2
+
3
+ <!-- toc -->
4
+ - [Where the numbers come from, and what that makes them worth](#where-the-numbers-come-from-and-what-that-makes-them-worth)
5
+ - [Why the median and the MAD, not the mean](#why-the-median-and-the-mad-not-the-mean)
6
+ - [Why projection divides by the calendar window](#why-projection-divides-by-the-calendar-window)
7
+ - [Snapshots](#snapshots)
8
+ - [Advice](#advice)
9
+ <!-- /toc -->
2
10
 
3
11
  `cost-budget-check.mjs` answers one question, live, for one run: is THIS task
4
12
  about to cross its ceiling. Two ways a budget actually empties are invisible to
@@ -6,7 +14,7 @@ it. A slow drift never trips any single run's ceiling. And one pathological
6
14
  session can burn a week's worth in an hour while every individual run stays
7
15
  comfortably under its cap.
8
16
 
9
- `cost-analyze.mjs` answers the other four questions off one series.
17
+ `cost-analyze.mjs` answers the other questions off one series.
10
18
 
11
19
  | Sub-command | Question |
12
20
  |---|---|
@@ -14,6 +22,7 @@ comfortably under its cap.
14
22
  | `anomaly` | which day or session is out of family |
15
23
  | `burn` | is the last day accelerating against the preceding week |
16
24
  | `diff` | two saved snapshots, side by side |
25
+ | `advise` | which lever to pull, each finding with its numbers and their source |
17
26
 
18
27
  ```bash
19
28
  node "$HOME/.claude/scripts/cost-analyze.mjs" projection --days 14 [--monthly-usd 200]
@@ -21,6 +30,7 @@ node "$HOME/.claude/scripts/cost-analyze.mjs" anomaly --days 30 [--by day|sessio
21
30
  node "$HOME/.claude/scripts/cost-analyze.mjs" burn [--factor 3]
22
31
  node "$HOME/.claude/scripts/cost-analyze.mjs" --save [--days 30]
23
32
  node "$HOME/.claude/scripts/cost-analyze.mjs" diff [a.json b.json]
33
+ node "$HOME/.claude/scripts/cost-analyze.mjs" advise [--days 7]
24
34
  ```
25
35
 
26
36
  Exit 0 means nothing to report, 10 means a finding, 2 is a usage error. Every
@@ -95,3 +105,28 @@ budget to compare against would produce a number that looks measured.
95
105
  per-day rate and the per-day breakdown. `diff` compares two, by path or the last
96
106
  two by default, and says when the windows differ - the per-day rate is
97
107
  comparable across different windows, the total is not.
108
+
109
+ ## Advice
110
+
111
+ `advise` reads the same transcripts, sub-agent files under
112
+ `<session>/subagents/` included, and reports only what crosses a threshold.
113
+ Every finding carries `numbers` (the measured values), `source` (the
114
+ transcript root, file and record counts, the window and the price table) and
115
+ `savingUsd`: the same tokens repriced at another rate, or `null` where no
116
+ defensible figure exists.
117
+
118
+ | Finding | Fires when | Saving |
119
+ |---|---|---|
120
+ | `cache-read-ratio` | under 80% of input came from cache reads, over at least 1M input tokens | null |
121
+ | `ttl-1h-payback` | the 1-hour write surcharge (0.75x input over a 5-minute write) exceeds the value of the reads that came more than five minutes after the session's previous turn, by at least $0.50 | surcharge minus that value |
122
+ | `subagent-tier-<rung>` | sub-agent turns on fable or opus would cost at least $1 less one rung down | the difference |
123
+ | `context-bloat` | a session of 20 or more turns averaged 150k context tokens a turn | null |
124
+ | `unpriced` | a model id is not in `cost-table.json` | null |
125
+
126
+ A 1-hour write pays off only for a read a 5-minute entry would have missed,
127
+ which is a read after a pause of more than five minutes; reads in quick
128
+ succession were served as well by the cheaper TTL. The sub-agent finding names
129
+ the personas pinned to that rung by their frontmatter. For fable it points at
130
+ the fable switch, since `agent-model-sync.mjs` rewrites those installed
131
+ personas to opus when the switch is off. Quality is not measured here, so the
132
+ action asks for a comparison before a persona moves down.
@@ -6,6 +6,7 @@
6
6
  - [Who calls it, and what they do with the code](#who-calls-it-and-what-they-do-with-the-code)
7
7
  - [The four severities](#the-four-severities)
8
8
  - [The line shape](#the-line-shape)
9
+ - [The JSON report](#the-json-report)
9
10
  - [It recommends, it never fixes](#it-recommends-it-never-fixes)
10
11
  - [Checks](#checks)
11
12
  - [The server profile (`--profile=server`)](#the-server-profile---profileserver)
@@ -86,6 +87,35 @@ The third field is one step, and its first word comes from a closed list:
86
87
  `record`, `re-run`. `consider`, `may want` and `should probably` are refused by
87
88
  the gate. One problem, one step: a reader with five suggestions does nothing.
88
89
 
90
+ ## The JSON report
91
+
92
+ `--json` prints one document whose shape `schemas/doctor-report.schema.json`
93
+ fixes and `test/doctor-json-contract.test.mjs` holds against real output and a
94
+ golden file:
95
+
96
+ ```json
97
+ {
98
+ "schemaVersion": 1,
99
+ "exit": 1,
100
+ "selection": null,
101
+ "checks": [{ "id": "identity", "severity": "WARN", "problem": "...", "step": "set ...", "detail": null }]
102
+ }
103
+ ```
104
+
105
+ - `schemaVersion` changes only when an existing field changes meaning or
106
+ shape. A new check id, or a new optional field, does not change it, so a
107
+ reader keys on `id` and ignores ids it does not know.
108
+ - `exit` equals the process exit code (0, 1, 2 or 4).
109
+ - `selection` is the `--only` list in the order given, or null for a full run,
110
+ so a filtered report is never mistaken for a complete one.
111
+ - `checks` holds one entry per check that ran, in registry order. `problem` and
112
+ `step` are null for OK; `step` is null for SKIP.
113
+
114
+ `--only <id,...>` (or `--only=<id,...>`) runs and reports only the named
115
+ checks; the layout checks still run first, since nothing resolves without
116
+ them, and a run whose layout does not resolve is still exit 4. An unknown id
117
+ is exit 3 with the nearest known id named.
118
+
89
119
  ## It recommends, it never fixes
90
120
 
91
121
  Nothing here rewrites a remote URL, edits `settings.json` or touches a token.
@@ -295,6 +325,18 @@ many servers are worth their context is the user's call, not a health failure.
295
325
  The threshold is judgement, which is why it is a pref instead of a constant in
296
326
  the script - a number nobody can see is a number nobody can argue with.
297
327
 
328
+ ### mcp-schema-load
329
+
330
+ How much of every turn the toolkit's tool list takes, per tool family, and
331
+ what each `MCP_TOOLKIT_CAPS` family would save. With `--probe` it is measured
332
+ from the `tools/list` the registration probe served; without it, a
333
+ `families` field in the `tool-manifest.json` beside a toolkit registered by
334
+ path is read; otherwise SKIP. Tokens are bytes / 4 of the JSON each entry is
335
+ sent as: an estimate, and the problem line says so. INFO once the total
336
+ reaches `prefs.global.mcpSurface.schemaInfoAboveTokens` (default 8000), naming
337
+ the three largest families; `--explain` lists every family. Like
338
+ `mcp-surface` it only reports: which families a repo needs is the user's call.
339
+
298
340
  ### mcp-failures
299
341
 
300
342
  A server whose MCP tool calls keep failing, read from the local log
@@ -304,7 +346,9 @@ the arguments, the output or the error text. INFO when one server failed five
304
346
  times or more in the last 24 hours; `--explain` lists each such server with its
305
347
  failures per tool and per class. Invalid input, a denied call and an
306
348
  interrupted one are the caller's or the user's, so they never count toward the
307
- light. SKIP when `mcpFailures.enabled` is false or `usageLog.optOut` is true.
349
+ light. A single `disk-full` failure (ENOSPC, no space left on device) in the
350
+ window lights INFO on its own, with the disk-cleaner skill as the step. SKIP
351
+ when `mcpFailures.enabled` is false or `usageLog.optOut` is true.
308
352
 
309
353
  Nothing is probed: the light only reflects calls the sessions already made.
310
354
  INFO and never WARN, because a flaky third-party server makes a session worse
@@ -312,9 +356,12 @@ without making this install unhealthy.
312
356
 
313
357
  ### disk-space
314
358
 
315
- Free space on the volume holding `$HOME`. WARN under 2 GB: a worktree plus a
316
- build is the largest thing a run writes, and ENOSPC mid-run corrupts the state
317
- file it was writing at the time.
359
+ Free space on the volume holding `$HOME`, from one statfs call in
360
+ `lib/low-disk.mjs`. WARN under `diskCleaner.lowDiskGb` (default 10 GB) or
361
+ `diskCleaner.lowDiskPercent` (default 5%) free: a worktree plus a build is the
362
+ largest thing a run writes, and ENOSPC mid-run corrupts the state file it was
363
+ writing at the time. The step names the disk-cleaner skill, which measures
364
+ before it deletes anything; doctor itself deletes nothing.
318
365
 
319
366
  ### worktree-residue
320
367