@mmerterden/multi-agent-pipeline 20.41.0 → 20.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +8 -6
  3. package/README.tr.md +8 -6
  4. package/docs/architecture.md +3 -3
  5. package/docs/ecosystem.md +50 -13
  6. package/docs/facts.json +9 -9
  7. package/docs/features.md +9 -4
  8. package/install/claude.mjs +34 -1
  9. package/install/templates/claude-hooks.json +12 -1
  10. package/manifest.json +117 -90
  11. package/package.json +3 -2
  12. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  13. package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
  14. package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/credential-store.sh +11 -1
  20. package/pipeline/lib/hook-once.mjs +134 -0
  21. package/pipeline/lib/isotonic.mjs +73 -0
  22. package/pipeline/lib/low-disk.mjs +154 -0
  23. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  24. package/pipeline/lib/md2confluence-v3.py +8 -7
  25. package/pipeline/lib/model-dispatch.sh +26 -2
  26. package/pipeline/lib/normalize-text.mjs +135 -0
  27. package/pipeline/lib/outbound-gate.mjs +21 -3
  28. package/pipeline/lib/plan-todos.sh +17 -4
  29. package/pipeline/lib/redact.mjs +12 -3
  30. package/pipeline/lib/risky-settings.mjs +198 -0
  31. package/pipeline/lib/route-state.sh +1 -0
  32. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  33. package/pipeline/lib/session-usage.mjs +232 -0
  34. package/pipeline/lib/source-digest.mjs +211 -0
  35. package/pipeline/lib/tdd-evidence.mjs +250 -17
  36. package/pipeline/lib/untrusted-fence.mjs +132 -1
  37. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  38. package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
  39. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  40. package/pipeline/multi-agent-refs/features/doctor.md +66 -4
  41. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  42. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  43. package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
  44. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  45. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  46. package/pipeline/multi-agent-refs/help/en.md +3 -1
  47. package/pipeline/multi-agent-refs/help/tr.md +3 -1
  48. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  49. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  50. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  51. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  52. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  53. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  54. package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
  55. package/pipeline/office/toolkit.json +1 -1
  56. package/pipeline/rules/outside-the-pipeline.md +1 -1
  57. package/pipeline/schemas/doctor-report.schema.json +47 -0
  58. package/pipeline/schemas/plan-todos.schema.json +29 -1
  59. package/pipeline/schemas/prefs.schema.json +81 -0
  60. package/pipeline/schemas/route-config.schema.json +51 -0
  61. package/pipeline/schemas/secret-patterns.json +17 -1
  62. package/pipeline/schemas/toolkit-path-params.json +15 -1
  63. package/pipeline/scripts/_cost-advise.mjs +357 -0
  64. package/pipeline/scripts/_cost-budget.mjs +78 -0
  65. package/pipeline/scripts/_cost.mjs +29 -0
  66. package/pipeline/scripts/_decode_text.py +107 -0
  67. package/pipeline/scripts/_guard-probe.mjs +406 -0
  68. package/pipeline/scripts/_guard_rules.py +206 -0
  69. package/pipeline/scripts/_memory-policy.mjs +1 -25
  70. package/pipeline/scripts/_retrieval.mjs +148 -2
  71. package/pipeline/scripts/_secret-scan.mjs +6 -1
  72. package/pipeline/scripts/_stack-routing.mjs +1 -0
  73. package/pipeline/scripts/_test-gaming.mjs +346 -0
  74. package/pipeline/scripts/agent-guard.py +8 -1
  75. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  76. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  77. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  78. package/pipeline/scripts/capture-resume.sh +9 -1
  79. package/pipeline/scripts/cost-analyze.mjs +66 -4
  80. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  81. package/pipeline/scripts/disk-cleaner.mjs +1432 -0
  82. package/pipeline/scripts/doctor.mjs +302 -47
  83. package/pipeline/scripts/evidence-gate.mjs +90 -0
  84. package/pipeline/scripts/gate-ledger.mjs +76 -21
  85. package/pipeline/scripts/gc-tmp.sh +5 -0
  86. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  87. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  88. package/pipeline/scripts/note-agent-event.mjs +2 -0
  89. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  90. package/pipeline/scripts/note-skill-use.mjs +4 -1
  91. package/pipeline/scripts/pre-commit-check.sh +2 -2
  92. package/pipeline/scripts/pre-push-check.sh +8 -1
  93. package/pipeline/scripts/priority-review.mjs +912 -0
  94. package/pipeline/scripts/publish-staged.mjs +324 -0
  95. package/pipeline/scripts/route-learn.mjs +628 -0
  96. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  97. package/pipeline/scripts/scan-agent-config.sh +1 -1
  98. package/pipeline/scripts/statusline.mjs +309 -0
  99. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  100. package/pipeline/scripts/triage-memory.mjs +12 -4
  101. package/pipeline/scripts/uninstall.mjs +1 -0
  102. package/pipeline/skills/.skill-manifest.json +17 -5
  103. package/pipeline/skills/.skills-index.json +36 -3
  104. package/pipeline/skills/shared/README.md +9 -6
  105. package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
  106. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
  107. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
  108. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  109. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +111 -0
  110. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  111. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1432 -0
  112. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  113. package/pipeline/skills/skill-copies.json +4 -0
  114. package/pipeline/skills/skills-index.md +5 -2
@@ -28,6 +28,13 @@
28
28
  * worktree, a real-path prefix match; unattended, that policy and its
29
29
  * protected paths decide instead, so this rule stays silent there.
30
30
  *
31
+ * Subagent spawn (matcher `Agent|Task`): when prefs.global.costBudget.enabled
32
+ * is true and the bound live run's tracker prices above the budget
33
+ * (_cost-budget.mjs), a new subagent asks the user first, and is refused with
34
+ * `onExceed: halt`; from warnPct up to the ceiling the model gets a note and
35
+ * the call proceeds. The phase-end check catches spend between phases; this
36
+ * catches it where it grows fastest, at the spawn.
37
+ *
31
38
  * No run bound to the session: no output, the call proceeds. Any internal
32
39
  * error: no output, a line in <log root>/hook-failures.log.
33
40
  *
@@ -42,8 +49,11 @@ import { homedir, tmpdir } from "node:os";
42
49
  import { basename, dirname, isAbsolute, join, resolve, sep } from "node:path";
43
50
 
44
51
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
52
+ import { globalPref } from "../lib/prefs-value.mjs";
53
+ import { readRegularJson } from "../lib/regular-file.mjs";
45
54
  import { isUnattended } from "../lib/unattended.mjs";
46
55
  import { findActiveRun, logHookFailure, modeOf, phaseContract } from "./_active-run.mjs";
56
+ import { budgetConfig, budgetLevel, rateFor, trackerSpend } from "./_cost-budget.mjs";
47
57
  import { logsRoot } from "./_run-paths.mjs";
48
58
  import { exitOnHelp } from "../lib/cli-help.mjs";
49
59
 
@@ -61,6 +71,8 @@ const FIGMA_URL = /\bhttps?:\/\/(?:[\w-]+\.)*figma\.com(?=[/:?#\s'"]|$)/i;
61
71
  const ADD_ALL = /\bgit\s+(?:-C\s+\S+\s+)?add\s+(?:[^;&|\n]*\s)?(?:-A|--all|\.)(?=$|[\s;&|])/;
62
72
  const HTTP_CLIENT = /(?:^|[\s;&|(])(?:curl|wget|http|https|xh)\s/;
63
73
 
74
+ const SPAWN_TOOLS = new Set(["Agent", "Task"]);
75
+
64
76
  const deny = (reason) => ({
65
77
  hookSpecificOutput: {
66
78
  hookEventName: "PreToolUse",
@@ -69,6 +81,44 @@ const deny = (reason) => ({
69
81
  },
70
82
  });
71
83
 
84
+ const ask = (reason) => ({
85
+ hookSpecificOutput: {
86
+ hookEventName: "PreToolUse",
87
+ permissionDecision: "ask",
88
+ permissionDecisionReason: `run-scope-guard: ${reason}`,
89
+ },
90
+ });
91
+
92
+ /** A subagent spawn against the bound run's cost budget, or null. */
93
+ function spawnDecision(run, env) {
94
+ const s = run.state;
95
+ if (!LIVE.has(s.status)) return null;
96
+ const cfg = budgetConfig(globalPref("costBudget", null, env));
97
+ if (!cfg.enabled) return null;
98
+ const rate = rateFor(cfg.pricingModel);
99
+ const tracker = readRegularJson(join(dirname(run.statePath), "tracker-state.json"), null);
100
+ if (!rate || !tracker) return null;
101
+ const { usd } = trackerSpend(tracker, rate);
102
+ const level = budgetLevel(usd, cfg);
103
+ if (level === "ok") return null;
104
+ const pct = Math.round((usd / cfg.maxUsd) * 100);
105
+ const spent = `run ${s.taskId || run.statePath} has spent an estimated $${usd.toFixed(2)} of its $${cfg.maxUsd.toFixed(2)} budget (${pct}%, priced at ${cfg.pricingModel})`;
106
+ if (level === "warn") {
107
+ return {
108
+ hookSpecificOutput: {
109
+ hookEventName: "PreToolUse",
110
+ additionalContext: `run-scope-guard: ${spent}; a new subagent adds to it, so start only the ones the phase needs.`,
111
+ },
112
+ };
113
+ }
114
+ if (cfg.onExceed === "halt") {
115
+ return deny(
116
+ `${spent}, over the ceiling, and costBudget.onExceed is halt: no new subagent starts. Record the halt; the user resumes with a higher maxUsd or accepts the overage.`,
117
+ );
118
+ }
119
+ return ask(`${spent}, over the ceiling. Another subagent spends more; confirm to go on.`);
120
+ }
121
+
72
122
  /** The last phase a Figma call is allowed in outside an analysis run. */
73
123
  export function figmaThroughPhase() {
74
124
  const n = Number(phaseContract().thresholds?.mcpAllowedThroughPhase);
@@ -202,7 +252,10 @@ export async function decide(payload, env = process.env) {
202
252
  tool === "Bash" &&
203
253
  typeof payload.tool_input?.command === "string" &&
204
254
  ADD_ALL.test(payload.tool_input.command);
205
- if (!figma && !figmaHttp && !asking && !addAll && !FILE_TOOLS.has(tool)) return null;
255
+ const spawning = SPAWN_TOOLS.has(tool);
256
+ if (!figma && !figmaHttp && !asking && !addAll && !spawning && !FILE_TOOLS.has(tool)) {
257
+ return null;
258
+ }
206
259
  const run = findActiveRun({
207
260
  sessionId: typeof payload.session_id === "string" ? payload.session_id : null,
208
261
  cwd: typeof payload.cwd === "string" ? payload.cwd : null,
@@ -212,6 +265,7 @@ export async function decide(payload, env = process.env) {
212
265
  // worktree (the project root) must not govern every later session there.
213
266
  if (!run || !SESSION_BOUND.has(run.matchedBy)) return null;
214
267
  if (asking) return askDecision(run);
268
+ if (spawning) return spawnDecision(run, env);
215
269
  if (addAll) {
216
270
  return LIVE.has(run.state.status)
217
271
  ? deny(
@@ -20,7 +20,7 @@ set -uo pipefail
20
20
  # BEGIN GENERATED: secret-patterns
21
21
  # Written by pipeline/scripts/gen-secret-patterns.mjs from
22
22
  # pipeline/schemas/secret-patterns.json; edit the JSON and regenerate.
23
- SECRET_PATTERNS_ERE='((^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{36,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{50,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xox[abprs]-[A-Za-z0-9-]{10,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])(AKIA|ASIA)[0-9A-Z]{16})|((^|[^A-Za-z0-9_])AIza[0-9A-Za-z_-]{35}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-(proj-)?[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-ant-[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])fig[a-z]_[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])npm_[A-Za-z0-9]{36}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])glpat-[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])[sr]k_live_[A-Za-z0-9]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])pplx-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])hf_[A-Za-z0-9]{30,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])gsk_[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-or-v1-[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xapp-[0-9]+-[A-Za-z0-9]{8,}-[0-9]{8,}-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}([^A-Za-z0-9_-]|$))|((^|[^A-Za-z0-9_])SK[0-9a-f]{32}([^A-Za-z0-9_]|$))|("type"[[:space:]]*:[[:space:]]*"service_account")|((^|[^A-Za-z0-9_])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}([^A-Za-z0-9_]|$))|(-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----)|((^|[^A-Za-z0-9_])[a-z][a-z0-9+.-]*://[^[:space:]/:@]+:[^[:space:]/@]+@)'
23
+ SECRET_PATTERNS_ERE='((^|[^A-Za-z0-9_])gh[pousr]_[A-Za-z0-9]{36,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])github_pat_[A-Za-z0-9_]{50,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xox[abprs]-[A-Za-z0-9-]{10,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])(AKIA|ASIA)[0-9A-Z]{16})|((^|[^A-Za-z0-9_])AIza[0-9A-Za-z_-]{35}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-(proj-)?[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-ant-[A-Za-z0-9_-]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])fig[a-z]_[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])npm_[A-Za-z0-9]{36}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])glpat-[A-Za-z0-9_-]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])[sr]k_live_[A-Za-z0-9]{20,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])pplx-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])hf_[A-Za-z0-9]{30,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])gsk_[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])sk-or-v1-[A-Za-z0-9]{40,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])xapp-[0-9]+-[A-Za-z0-9]{8,}-[0-9]{8,}-[A-Za-z0-9]{32,}([^A-Za-z0-9_]|$))|((^|[^A-Za-z0-9_])SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}([^A-Za-z0-9_-]|$))|((^|[^A-Za-z0-9_])SK[0-9a-f]{32}([^A-Za-z0-9_]|$))|("type"[[:space:]]*:[[:space:]]*"service_account")|((^|[^A-Za-z0-9_])eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}([^A-Za-z0-9_]|$))|(-----BEGIN [A-Z0-9 ]*PRIVATE KEY( BLOCK)?-----)|((^|[^A-Za-z0-9_])[a-z][a-z0-9+.-]{0,31}://[^[:space:]/:@]{1,255}:[^[:space:]/@]+@)'
24
24
  SECRET_PATTERNS_ERE_ICASE='(aws_?secret_?access_?key["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9/+=]{40}([^A-Za-z0-9/+=]|$))|(aws_?session_?token["'\'']?[[:space:]]*[:=][[:space:]]*["'\'']?[A-Za-z0-9/+=]{100,})|((^|[^A-Za-z0-9_])Authorization:[[:space:]]*(Bearer|Basic)[[:space:]]+[A-Za-z0-9._~+/=-]{16,})'
25
25
  # END GENERATED: secret-patterns
26
26
 
@@ -0,0 +1,309 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * statusline.mjs - one line for Claude Code's status bar: the run this
4
+ * session is driving, its phase, its cost against the budget, its gates, and
5
+ * whether it waits for an answer.
6
+ *
7
+ * MA PROJ-12 | P3 Review | $1.23/$5.00 | gates 4/5 !plan-coverage | answer needed
8
+ *
9
+ * Opt-in. Nothing installs it but `statusline.mjs install`, which writes
10
+ * `statusLine` into ~/.claude/settings.json only when that key is absent: a
11
+ * status line someone already set is theirs and is never replaced.
12
+ * `uninstall` removes the key only when it points here.
13
+ *
14
+ * Local files only, no network: the run's agent-state.json and
15
+ * tracker-state.json under the log root, priced from cost-table.json, and the
16
+ * budget from prefs.global.costBudget when it is enabled. The run is the one
17
+ * whose `sessionId` is the session Claude Code names on stdin, else the
18
+ * running one whose worktree holds the session's directory. The match is
19
+ * cached per session for 30 seconds, so a refresh does not read every run
20
+ * each time, in a 0700 directory of this user's own under the temp directory
21
+ * that is never a link and never open to others, the file read and written
22
+ * without following a link. No run, or input that does not parse, prints
23
+ * nothing and exits 0: a status bar is not the place for an error.
24
+ *
25
+ * Usage:
26
+ * statusline.mjs read the host's JSON on stdin, print the line
27
+ * statusline.mjs install add statusLine to ~/.claude/settings.json
28
+ * statusline.mjs uninstall remove it, if it is this one
29
+ *
30
+ * Exit: 0 printed (or nothing to print) / installed / removed; 1 install or
31
+ * uninstall refused; 2 usage error.
32
+ */
33
+
34
+ import {
35
+ chmodSync,
36
+ existsSync,
37
+ readFileSync,
38
+ readSync,
39
+ realpathSync,
40
+ renameSync,
41
+ rmSync,
42
+ statSync,
43
+ writeFileSync,
44
+ } from "node:fs";
45
+ import { homedir, tmpdir } from "node:os";
46
+ import { dirname, join, sep } from "node:path";
47
+
48
+ import { ArgsError, unknownSubcommand } from "../lib/args.mjs";
49
+ import { exitOnHelp } from "../lib/cli-help.mjs";
50
+ import { privateDir } from "../lib/hook-once.mjs";
51
+ import { readFileSafe, writeFileSafe } from "../lib/safe-write.mjs";
52
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
53
+ import { loadGlobalPrefs, prefsPath } from "../lib/prefs-value.mjs";
54
+ import { readRegularJson } from "../lib/regular-file.mjs";
55
+ import { phaseName } from "../lib/run-completion.mjs";
56
+ import { trackerUsd } from "./_cost.mjs";
57
+ import { ARTIFACTS_SUBDIR, listRuns } from "./_run-paths.mjs";
58
+
59
+ exitOnHelp(import.meta.url);
60
+
61
+ const HERE = import.meta.dirname;
62
+ const COMMAND = 'node "$HOME/.claude/scripts/statusline.mjs"';
63
+ const MARK = "statusline.mjs";
64
+ const CACHE_TTL_MS = 30_000;
65
+ const MAX_STDIN = 64 * 1024;
66
+ const MAX_CACHE = 256 * 1024;
67
+ const PASSING = new Set(["pass", "not-applicable"]);
68
+ const DONE = new Set(["complete", "completed", "failed", "killed", "stopped"]);
69
+
70
+ /**
71
+ * What the line shows, from a run's state and its measured cost.
72
+ *
73
+ * @param {{state: object, usd?: number|null, budgetUsd?: number|null}} input
74
+ */
75
+ export function statusOf({ state, usd = null, budgetUsd = null }) {
76
+ const latest = new Map();
77
+ for (const g of Array.isArray(state?.gates) ? state.gates : []) {
78
+ if (!g || typeof g.gate !== "string") continue;
79
+ const prev = latest.get(g.gate);
80
+ if (!prev || (Date.parse(g.at) || 0) >= (Date.parse(prev.at) || 0)) latest.set(g.gate, g);
81
+ }
82
+ const failing = [...latest.values()]
83
+ .filter((g) => !PASSING.has(g.verdict))
84
+ .map((g) => g.gate)
85
+ .sort();
86
+ const phase = Number.isInteger(Number(state?.currentPhase)) ? Number(state.currentPhase) : null;
87
+ return {
88
+ taskId: String(state?.taskId ?? "?"),
89
+ phase,
90
+ phaseName: phase === null ? null : phaseName(phase),
91
+ usd,
92
+ budgetUsd,
93
+ gates: { passed: latest.size - failing.length, total: latest.size, failing },
94
+ waiting: Boolean(state?.pendingQuestion),
95
+ };
96
+ }
97
+
98
+ /** The line itself. Unmeasured cost is `$?`, never `$0.00`. */
99
+ export function renderLine(s) {
100
+ const money = (n) => `$${n.toFixed(2)}`;
101
+ const cost = `${s.usd === null ? "$?" : money(s.usd)}${s.budgetUsd ? `/${money(s.budgetUsd)}` : ""}`;
102
+ const parts = [`MA ${s.taskId}`];
103
+ if (s.phase !== null) parts.push(`P${s.phase} ${s.phaseName}`);
104
+ parts.push(cost);
105
+ if (s.gates.total) {
106
+ parts.push(
107
+ `gates ${s.gates.passed}/${s.gates.total}${s.gates.failing.length ? ` !${s.gates.failing[0]}` : ""}`,
108
+ );
109
+ }
110
+ if (s.waiting) parts.push("answer needed");
111
+ return parts.join(" | ");
112
+ }
113
+
114
+ function readStdin() {
115
+ const buf = Buffer.alloc(MAX_STDIN);
116
+ let n = 0;
117
+ try {
118
+ for (;;) {
119
+ const got = readSync(0, buf, n, MAX_STDIN - n, null);
120
+ if (got <= 0) break;
121
+ n += got;
122
+ if (n >= MAX_STDIN) break;
123
+ }
124
+ } catch {
125
+ /* no stdin, or a closed one */
126
+ }
127
+ return buf.toString("utf8", 0, n);
128
+ }
129
+
130
+ const inside = (dir, root) =>
131
+ dir === root || dir.startsWith(root.endsWith(sep) ? root : root + sep);
132
+
133
+ /**
134
+ * The cache file, in a 0700 directory of this user's own under the temp
135
+ * directory (lib/hook-once.mjs privateDir), or null when that directory is a
136
+ * link, someone else's, or open to others: then nothing is cached.
137
+ */
138
+ function cachePath() {
139
+ const uid = typeof process.getuid === "function" ? process.getuid() : "user";
140
+ const dir = privateDir(join(tmpdir(), `multi-agent-statusline-${uid}`));
141
+ return dir ? join(dir, "cache.json") : null;
142
+ }
143
+
144
+ /** The cache, read without following a link, or null. */
145
+ function readCache(p) {
146
+ if (!p) return null;
147
+ try {
148
+ const doc = JSON.parse(
149
+ readFileSafe(p, { anchors: [dirname(p)], maxBytes: MAX_CACHE })?.toString("utf8"),
150
+ );
151
+ return doc && typeof doc === "object" && !Array.isArray(doc) ? doc : null;
152
+ } catch {
153
+ return null;
154
+ }
155
+ }
156
+
157
+ function findRun(sessionId, cwd) {
158
+ const at = cachePath();
159
+ const cache = readCache(at);
160
+ const hit = cache?.[sessionId];
161
+ if (hit && Date.now() - hit.at < CACHE_TTL_MS && existsSync(hit.statePath)) {
162
+ const state = readRegularJson(hit.statePath, null);
163
+ if (state && state.sessionId === sessionId) return { statePath: hit.statePath, state };
164
+ }
165
+ let byCwd = null;
166
+ for (const run of listRuns()) {
167
+ const statePath = join(run.dir, "agent-state.json");
168
+ const state = readRegularJson(statePath, null);
169
+ if (!state || typeof state !== "object") continue;
170
+ if (sessionId && state.sessionId === sessionId) {
171
+ try {
172
+ if (at)
173
+ writeFileSafe(
174
+ at,
175
+ JSON.stringify({ ...(cache || {}), [sessionId]: { statePath, at: Date.now() } }),
176
+ { mode: 0o600, anchors: [dirname(at)] },
177
+ );
178
+ } catch {
179
+ /* the cache is an optimisation */
180
+ }
181
+ return { statePath, state };
182
+ }
183
+ const wt = typeof state.worktreePath === "string" ? state.worktreePath : null;
184
+ if (!wt || !cwd || !inside(cwd, wt) || DONE.has(state.status)) continue;
185
+ let mtime;
186
+ try {
187
+ mtime = statSync(statePath).mtimeMs;
188
+ } catch {
189
+ continue;
190
+ }
191
+ if (!byCwd || mtime > byCwd.mtime) byCwd = { statePath, state, mtime };
192
+ }
193
+ return byCwd;
194
+ }
195
+
196
+ function runCost(statePath) {
197
+ const dir = dirname(statePath);
198
+ const prices = readRegularJson(join(HERE, "cost-table.json"), null)?.prices;
199
+ for (const base of [dir, join(dir, ARTIFACTS_SUBDIR)]) {
200
+ const tracker = readRegularJson(join(base, "tracker-state.json"), null);
201
+ if (tracker) return trackerUsd(tracker, prices);
202
+ }
203
+ return null;
204
+ }
205
+
206
+ function budget() {
207
+ try {
208
+ const b = loadGlobalPrefs(prefsPath()).costBudget;
209
+ return b?.enabled === true && Number(b.maxUsd) > 0 ? Number(b.maxUsd) : null;
210
+ } catch {
211
+ return null;
212
+ }
213
+ }
214
+
215
+ function render() {
216
+ let input;
217
+ try {
218
+ input = JSON.parse(readStdin());
219
+ } catch {
220
+ return "";
221
+ }
222
+ const sessionId = typeof input?.session_id === "string" ? input.session_id : "";
223
+ const cwd = input?.workspace?.current_dir || input?.cwd || "";
224
+ const found = findRun(sessionId, typeof cwd === "string" ? cwd : "");
225
+ if (!found) return "";
226
+ const line = renderLine(
227
+ statusOf({ state: found.state, usd: runCost(found.statePath), budgetUsd: budget() }),
228
+ );
229
+ return `${line}\n`;
230
+ }
231
+
232
+ const settingsPath = () => join(process.env.HOME || homedir(), ".claude", "settings.json");
233
+
234
+ function readSettings() {
235
+ const p = settingsPath();
236
+ if (!existsSync(p)) return { p, doc: {} };
237
+ const doc = JSON.parse(readFileSync(p, "utf8"));
238
+ if (!doc || typeof doc !== "object" || Array.isArray(doc)) throw new Error("not a JSON object");
239
+ return { p, doc };
240
+ }
241
+
242
+ /**
243
+ * Replace the settings file, keeping what it is: a settings.json that is a
244
+ * link (to a dotfiles checkout, say) stays a link and its target is the file
245
+ * replaced, and the file keeps its mode. The temp file is created exclusive
246
+ * beside the file it replaces, so the rename never crosses a filesystem.
247
+ */
248
+ function writeSettings(p, doc) {
249
+ const target = existsSync(p) ? realpathSync(p) : p;
250
+ const mode = existsSync(target) ? statSync(target).mode & 0o777 : 0o600;
251
+ const tmp = `${target}.statusline-${process.pid}.tmp`;
252
+ try {
253
+ writeFileSync(tmp, `${JSON.stringify(doc, null, 2)}\n`, { flag: "wx", mode });
254
+ chmodSync(tmp, mode);
255
+ renameSync(tmp, target);
256
+ } finally {
257
+ rmSync(tmp, { force: true });
258
+ }
259
+ }
260
+
261
+ const ours = (line) => typeof line?.command === "string" && line.command.includes(MARK);
262
+
263
+ function install() {
264
+ let settings;
265
+ try {
266
+ settings = readSettings();
267
+ } catch (e) {
268
+ return [1, `statusline: ${settingsPath()} does not parse (${e.message}); nothing written`];
269
+ }
270
+ const { p, doc } = settings;
271
+ if (doc.statusLine !== undefined) {
272
+ return ours(doc.statusLine)
273
+ ? [0, "statusline: already installed"]
274
+ : [1, `statusline: a statusLine is already set in ${p}; left as it is`];
275
+ }
276
+ writeSettings(p, { ...doc, statusLine: { type: "command", command: COMMAND, padding: 0 } });
277
+ return [0, `statusline: installed in ${p}`];
278
+ }
279
+
280
+ function uninstall() {
281
+ let settings;
282
+ try {
283
+ settings = readSettings();
284
+ } catch (e) {
285
+ return [1, `statusline: ${settingsPath()} does not parse (${e.message}); nothing written`];
286
+ }
287
+ const { p, doc } = settings;
288
+ if (doc.statusLine === undefined) return [0, "statusline: not installed"];
289
+ if (!ours(doc.statusLine))
290
+ return [1, `statusline: the statusLine in ${p} is not this one; left as it is`];
291
+ const { statusLine: _drop, ...rest } = doc;
292
+ writeSettings(p, rest);
293
+ return [0, `statusline: removed from ${p}`];
294
+ }
295
+
296
+ if (invokedDirectly(import.meta.url)) {
297
+ const sub = process.argv[2];
298
+ if (sub === undefined) {
299
+ process.stdout.write(render());
300
+ } else if (sub === "install" || sub === "uninstall") {
301
+ const [code, message] = sub === "install" ? install() : uninstall();
302
+ (code === 0 ? process.stdout : process.stderr).write(`${message}\n`);
303
+ process.exitCode = code;
304
+ } else {
305
+ const e = unknownSubcommand(sub, ["install", "uninstall"]);
306
+ process.stderr.write(`statusline: ${e instanceof ArgsError ? e.message : sub}\n`);
307
+ process.exitCode = 2;
308
+ }
309
+ }
@@ -31,9 +31,25 @@
31
31
  * unknown ref, a failed git call, a missing file), or a scan that throws, is
32
32
  * reported as `gaming.scanned: false` with the reason, never as a clean scan.
33
33
  *
34
+ * With --state <agent-state.json> it also reads the tests Phase 2 wrote in RED
35
+ * (`plan.todos[].tdd.red.testFiles`, lib/tdd-evidence.mjs): a GREEN that
36
+ * changed one with a recorded reason (`green.testEdits[]`) is an important
37
+ * finding (`signal: "test_edited_in_green"`) carrying the reason, and a RED
38
+ * test that no longer holds its RED bytes with no reason recorded for it is
39
+ * blocking (`signal: "test_edited_after_red"`). Under MULTI_AGENT_UNATTENDED=1
40
+ * the recorded edit is blocking too: nobody read the reason the agent gave.
41
+ *
42
+ * With --test-command-file <path> it reads the command the tests ran with and
43
+ * reports a narrowed run (_test-gaming.mjs narrowedRun) as a blocking
44
+ * `narrowed-run` finding.
45
+ *
46
+ * A --state or --test-command-file that cannot be read or parsed is a
47
+ * blocking `evidence_unreadable` finding, never an empty result.
48
+ *
34
49
  * Usage:
35
50
  * node diff-risk-score.mjs --base B --head H | node test-integrity-gate.mjs
36
51
  * node test-integrity-gate.mjs --file risk.json [--diff <unified.diff> | --diff-base <ref> [--repo <path>]]
52
+ * [--state <agent-state.json>] [--test-command-file <path>]
37
53
  * [--json] [--out <path>]
38
54
  *
39
55
  * --out writes the JSON to <path> (parent directories created) instead of
@@ -67,7 +83,8 @@ import {
67
83
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
68
84
  import { runMain } from "../lib/fatal.mjs";
69
85
  import { workingTreeReader } from "./_lint-suppression.mjs";
70
- import { safeScanTestGaming, scanTestGaming } from "./_test-gaming.mjs";
86
+ import { narrowedRunFinding, safeScanTestGaming, scanTestGaming } from "./_test-gaming.mjs";
87
+ import { testFileChanges } from "../lib/tdd-evidence.mjs";
71
88
  import { GitError, diffFromMergeBase } from "./_worktree-snapshot.mjs";
72
89
  import { exitOnHelp } from "../lib/cli-help.mjs";
73
90
 
@@ -163,6 +180,82 @@ if (OUT) {
163
180
  const FILE = flagValue("--file");
164
181
  const DIFF = flagValue("--diff");
165
182
  const DIFF_BASE = flagValue("--diff-base");
183
+ const STATE = flagValue("--state");
184
+ const TEST_COMMAND_FILE = flagValue("--test-command-file");
185
+
186
+ /**
187
+ * A flag named an evidence file the gate cannot read or parse. Blocking, like
188
+ * evidence-gate.mjs testCommand(): a gate asked to check evidence it cannot
189
+ * see has not checked it.
190
+ */
191
+ function unreadableFinding(flag, file, err) {
192
+ return {
193
+ file,
194
+ severity: "blocking",
195
+ tag: "test_integrity",
196
+ signal: "evidence_unreadable",
197
+ message: `${flag} ${file} cannot be read or parsed (${err.message}), so the check it feeds did not run. Fix the path or the file and run the gate again.`,
198
+ };
199
+ }
200
+
201
+ // An unattended run certifies its own --test-edit-reason with nobody to read
202
+ // it, so there an edit to a RED test blocks until a person accepts the reason.
203
+ const UNATTENDED = process.env.MULTI_AGENT_UNATTENDED === "1";
204
+
205
+ /** Findings for the tests RED wrote: edits recorded with a reason, and edits without one. */
206
+ function redTestFindings() {
207
+ if (STATE === null) return [];
208
+ let state;
209
+ try {
210
+ state = JSON.parse(readFileSync(STATE, "utf8"));
211
+ } catch (err) {
212
+ return [unreadableFinding("--state", STATE, err)];
213
+ }
214
+ const out = [];
215
+ for (const todo of state?.plan?.todos ?? []) {
216
+ const tdd = todo?.tdd;
217
+ const kept = Array.isArray(tdd?.red?.testFiles) ? tdd.red.testFiles : [];
218
+ const edits = Array.isArray(tdd?.green?.testEdits) ? tdd.green.testEdits : [];
219
+ const explained = new Set();
220
+ for (const e of edits) {
221
+ if (typeof e?.path !== "string") continue;
222
+ explained.add(e.path);
223
+ out.push({
224
+ file: e.path,
225
+ severity: UNATTENDED ? "blocking" : "important",
226
+ tag: "test_integrity",
227
+ signal: "test_edited_in_green",
228
+ todo: todo.id ?? null,
229
+ message: `Test '${e.path}' written in RED for todo ${todo.id} was ${e.change || "changed"} before GREEN, with the reason: ${e.reason || "(none)"}. Check the reason holds: the immutable-test rule (refs/rules.md) lets a test change only when it was wrong.${UNATTENDED ? " The run was unattended, so the reason is the agent's own and a person has to accept it." : ""}`,
230
+ });
231
+ }
232
+ for (const c of testFileChanges(REPO, kept)) {
233
+ if (explained.has(c.path)) continue;
234
+ out.push({
235
+ file: c.path,
236
+ severity: "blocking",
237
+ tag: "test_integrity",
238
+ signal: "test_edited_after_red",
239
+ todo: todo.id ?? null,
240
+ message: `Test '${c.path}' written in RED for todo ${todo.id} was ${c.change} afterwards with no reason recorded. Restore it (tdd-evidence.mjs restore) or record why the test itself was wrong.`,
241
+ });
242
+ }
243
+ }
244
+ return out;
245
+ }
246
+
247
+ /** A blocking finding when the test command was narrowed. */
248
+ function commandFindings() {
249
+ if (TEST_COMMAND_FILE === null) return [];
250
+ let command;
251
+ try {
252
+ command = readFileSync(TEST_COMMAND_FILE, "utf8");
253
+ } catch (err) {
254
+ return [unreadableFinding("--test-command-file", TEST_COMMAND_FILE, err)];
255
+ }
256
+ const f = narrowedRunFinding(command, TEST_COMMAND_FILE);
257
+ return f ? [f] : [];
258
+ }
166
259
 
167
260
  function emit(text) {
168
261
  if (!OUT) {
@@ -217,7 +310,9 @@ function gamingScan() {
217
310
 
218
311
  function main() {
219
312
  const raw = readInput();
220
- const { findings: gamingFindings, gaming } = gamingScan();
313
+ const scanned = gamingScan();
314
+ const gaming = scanned.gaming;
315
+ const gamingFindings = [...scanned.findings, ...commandFindings(), ...redTestFindings()];
221
316
  let report;
222
317
  try {
223
318
  report = JSON.parse(raw);
@@ -62,6 +62,8 @@ import { checkedSlug, repoName } from "../lib/slug.mjs";
62
62
  import { openScanner, stripPrivate } from "./_secret-scan.mjs";
63
63
  import {
64
64
  bm25,
65
+ mmr,
66
+ multiQuery,
65
67
  recencyRank,
66
68
  rrf,
67
69
  tokens,
@@ -386,14 +388,20 @@ function rank(corpus, issueText, fileGlob, topN, cfg) {
386
388
  file: r.file || "",
387
389
  reason: r.reason || "",
388
390
  }));
389
- const relevance = bm25(qTerms, docs, {
390
- fieldWeights: { issue: 3, fix: 2, file: 2, reason: 1 },
391
- });
391
+ // A task naming two things gets a sub-query per clause (multiQuery), and
392
+ // the head of the answer is re-picked for diversity (mmr), so five copies
393
+ // of one finding cannot take every place.
394
+ const fieldWeights = { issue: 3, fix: 2, file: 2, reason: 1 };
395
+ const relevance = cfg.multiQuery
396
+ ? multiQuery(issueText, docs, { fieldWeights })
397
+ : bm25(qTerms, docs, { fieldWeights });
392
398
  const fresh = recencyRank(filtered, { halfLifeDays: cfg.halfLifeDays });
393
399
  const matched = new Set(relevance.filter((x) => x.score > 0).map((x) => x.index));
394
- ordered = rrf([relevance, fresh], { k: [10, 60], weights: [3, 1] }).filter((x) =>
400
+ const fused = rrf([relevance, fresh], { k: [10, 60], weights: [3, 1] }).filter((x) =>
395
401
  matched.has(x.index),
396
402
  );
403
+ const terms = docs.map((d) => tokens(`${d.issue} ${d.fix} ${d.file} ${d.reason}`));
404
+ ordered = mmr(fused, terms, { lambda: cfg.mmrLambda, limit: topN });
397
405
  }
398
406
 
399
407
  const top = repoTop();
@@ -1108,6 +1108,7 @@ export async function main() {
1108
1108
  }
1109
1109
  rmIfExists(join(CLAUDE, ".pipeline-version"));
1110
1110
  rmIfExists(join(CLAUDE, "multi-agent-hook-manifest.json"));
1111
+ rmIfExists(join(CLAUDE, "multi-agent-risky-settings.json"));
1111
1112
  // NOTE: ~/.claude/rules/ is USER-OWNED. install lays baseline rules down
1112
1113
  // write-if-missing and NEVER overwrites them (install/claude.mjs
1113
1114
  // installRules, skipExisting) so users can evolve their global rules
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": "1.0.0",
3
- "generatedAt": "2026-11-03T17:11:02Z",
4
- "skillCount": 241,
3
+ "generatedAt": "2026-11-04T09:26:45Z",
4
+ "skillCount": 244,
5
5
  "entries": [
6
6
  {
7
7
  "path": "shared/core/apple-archive-compliance/SKILL.md",
@@ -51,6 +51,10 @@
51
51
  "path": "shared/core/multi-agent-channels/SKILL.md",
52
52
  "sha256": "f3706a2b87e6ebffb6e10c7829751177cad1495bae14abadf163fbc4d416b969"
53
53
  },
54
+ {
55
+ "path": "shared/core/multi-agent-clean-disk/SKILL.md",
56
+ "sha256": "469496a9548fb954738948692776010a9c080a9bcfbed44cce5d4e290ab198db"
57
+ },
54
58
  {
55
59
  "path": "shared/core/multi-agent-complaint-analysis/SKILL.md",
56
60
  "sha256": "3641e061247b16a505fa4e96e5893dc6d1de25f6d50c9eeb2ff83e3034e34889"
@@ -187,6 +191,10 @@
187
191
  "path": "shared/core/multi-agent-review-jira/SKILL.md",
188
192
  "sha256": "a17a1f11fcf6c75640452e53ddddaaf906ff9e3ebfeda73e333f44db02515352"
189
193
  },
194
+ {
195
+ "path": "shared/core/multi-agent-review-priority/SKILL.md",
196
+ "sha256": "c1cb3a693f7ccfb6d6298ba61fff9f78cc9dcb001f8db4d6b84adcbb636b3804"
197
+ },
190
198
  {
191
199
  "path": "shared/core/multi-agent-review/SKILL.md",
192
200
  "sha256": "385ef6f54374731c0c915217e01c69f7985da4f50c066d02cd29c28fecd7c1e3"
@@ -257,7 +265,7 @@
257
265
  },
258
266
  {
259
267
  "path": "shared/core/multi-agent-sync/SKILL.md",
260
- "sha256": "628b6398f8c609795b73bcaa0d326ffa4e00ac88d3e10b8b0967d338797baf7d"
268
+ "sha256": "feb25fa07a4c1a4bee4e116528116e9c7b3ef4d375fcde91e6f81e198a5eadad"
261
269
  },
262
270
  {
263
271
  "path": "shared/core/multi-agent-test-accessibility/SKILL.md",
@@ -393,7 +401,7 @@
393
401
  },
394
402
  {
395
403
  "path": "shared/external/backlog/SKILL.md",
396
- "sha256": "c4cfaf37afbc746d563d96626a3afd51ac39816a32db7957f31d537b6aa0bfe2"
404
+ "sha256": "1cfd3dea451fecb0e10757d5b64a394973d23cffde7498150ac7f5058353b231"
397
405
  },
398
406
  {
399
407
  "path": "shared/external/build-settings-audit/SKILL.md",
@@ -495,6 +503,10 @@
495
503
  "path": "shared/external/device-integrity/SKILL.md",
496
504
  "sha256": "9d8c39c65f7b5918c25c7ef3dd438fe62901e61ecc6fa2d7ecbd7c9a0fcfa4c0"
497
505
  },
506
+ {
507
+ "path": "shared/external/disk-cleaner/SKILL.md",
508
+ "sha256": "91028e79c5acd8aa76f899e80eb2b0a3605efaacdb102b13222651855df53fce"
509
+ },
498
510
  {
499
511
  "path": "shared/external/docker-expert/SKILL.md",
500
512
  "sha256": "b3db936caa89a2c249ae64896cfb4c0a72ac45064cc081d6f99c78efe6a1f9e9"
@@ -661,7 +673,7 @@
661
673
  },
662
674
  {
663
675
  "path": "shared/external/localization-reuse-map/SKILL.md",
664
- "sha256": "5eb944595439370298fbdee29127846e4dc1ed59fb38d50a612a995df0337a94"
676
+ "sha256": "f93eb09a9d1a91f7ab9475c770f54e09d8da38cc4d30a9a6db2edb4abe26bc77"
665
677
  },
666
678
  {
667
679
  "path": "shared/external/macos-app-distribution/SKILL.md",