@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmerterden/multi-agent-pipeline",
3
- "version": "20.41.0",
3
+ "version": "20.42.0",
4
4
  "description": "6-phase AI development pipeline with full orchestration on Claude Code, Copilot CLI and Codex CLI. Analysis, planning, TDD, CLI-aware parallel review with consensus surfacing + Fable triage, default-FAIL evidence gates, secret + intent guards, per-phase cost ledger, persistent learnings memory, wiki generation, commit automation. Token-preserving uninstall.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "scripts": {
22
22
  "start": "node index.js",
23
- "test": "npm run format:check && npm run lint && node --test test/*.test.mjs && node --test test/*.serial.mjs && node pipeline/scripts/run-smokes.mjs && node pipeline/scripts/lint-skills.mjs && node pipeline/scripts/gen-skills-index.mjs --check && node pipeline/scripts/build-skills-index.mjs --check && node pipeline/scripts/gen-free-llm-skill.mjs --check && node pipeline/scripts/gen-secret-patterns.mjs --check && node pipeline/scripts/gen-free-hosts.mjs --check && node pipeline/scripts/sync-skill-copies.mjs --check && node pipeline/scripts/gen-toolkit-path-params.mjs --check && node pipeline/scripts/gen-fact-marks.mjs --check && node pipeline/scripts/lint-personas.mjs && node pipeline/scripts/lint-mcp-refs.mjs && node pipeline/scripts/eval-triage.mjs && node pipeline/scripts/eval-golden-tasks.mjs && node pipeline/scripts/eval-intent.mjs && node pipeline/scripts/eval-recall.mjs && node pipeline/scripts/eval-persona-walk.mjs && node pipeline/scripts/eval-guard-robustness.mjs && node pipeline/scripts/validate-schemas.mjs && node pipeline/scripts/validate-prefs.mjs && node pipeline/scripts/scorecard.mjs",
23
+ "test": "npm run format:check && npm run lint && node --test test/*.test.mjs && node --test test/*.serial.mjs && node pipeline/scripts/run-smokes.mjs && node pipeline/scripts/lint-skills.mjs && node pipeline/scripts/gen-skills-index.mjs --check && node pipeline/scripts/build-skills-index.mjs --check && node pipeline/scripts/gen-free-llm-skill.mjs --check && node pipeline/scripts/gen-secret-patterns.mjs --check && node pipeline/scripts/gen-free-hosts.mjs --check && node pipeline/scripts/sync-skill-copies.mjs --check && node pipeline/scripts/gen-toolkit-path-params.mjs --check && node pipeline/scripts/gen-fact-marks.mjs --check && node pipeline/scripts/lint-personas.mjs && node pipeline/scripts/lint-mcp-refs.mjs && node pipeline/scripts/eval-triage.mjs && node pipeline/scripts/eval-golden-tasks.mjs && node pipeline/scripts/eval-intent.mjs && node pipeline/scripts/eval-recall.mjs && node pipeline/scripts/eval-persona-walk.mjs && node pipeline/scripts/eval-guard-robustness.mjs --fast && node pipeline/scripts/validate-schemas.mjs && node pipeline/scripts/validate-prefs.mjs && node pipeline/scripts/scorecard.mjs",
24
24
  "test:unit": "node --test test/*.test.mjs && node --test test/*.serial.mjs",
25
25
  "test:smoke": "node pipeline/scripts/run-smokes.mjs",
26
26
  "lint:skills": "node pipeline/scripts/lint-skills.mjs",
@@ -31,6 +31,7 @@
31
31
  "format": "prettier --write \"**/*.{js,mjs,json,yml}\" --ignore-path .gitignore --ignore-path .prettierignore",
32
32
  "format:check": "prettier --check \"**/*.{js,mjs,json,yml}\" --ignore-path .gitignore --ignore-path .prettierignore",
33
33
  "audit:refs": "node pipeline/scripts/ref-filler-audit.mjs",
34
+ "eval:guards": "node pipeline/scripts/eval-guard-robustness.mjs",
34
35
  "scorecard": "node pipeline/scripts/scorecard.mjs",
35
36
  "prepack": "node pipeline/contract/build.mjs --write && node pipeline/scripts/make-manifest.mjs",
36
37
  "gate": "bash pipeline/scripts/pre-push-check.sh --run"
@@ -55,6 +55,17 @@ Run the task end-to-end with no confirmations.
55
55
  /multi-agent:autopilot resume #3
56
56
  ```
57
57
 
58
+ ## Loop mode (`--loop N`)
59
+
60
+ For mechanical batch work that takes several passes, `--loop N` does not run the task here. Start the bounded loop in the background and report its id:
61
+
62
+ ```bash
63
+ node "$HOME/.claude/scripts/autopilot-loop.mjs" start --task "<task>" --repo "$PWD" \
64
+ --max-iterations N [--max-minutes M] [--max-usd U] [--until "<command that exits 0 when done>"]
65
+ ```
66
+
67
+ Each iteration is one full autopilot run with every gate, launched unattended exactly as the queue runner launches an item (`install --unattended` must have run: without agent-guard registered and the sandbox profile in force the loop refuses to start, exit 4). The loop stops on a failed or missing gate, an incomplete run, two iterations that delivered nothing, a cap (iterations at most 25, minutes 120 by default, $20 by default) or `autopilot-loop.mjs stop <id>`. Only the loop declares it complete, after a gated iteration whose `--until` check exited 0; never write or claim completion yourself. Report `autopilot-loop.mjs status <id>` when asked.
68
+
58
69
  ## Steps
59
70
 
60
71
  1. **Parse input** - standard multi-agent input formats
@@ -91,7 +91,7 @@ From scratch: `npx @{npm-scope}/multi-agent-pipeline install`, `/multi-agent set
91
91
 
92
92
  ### Step 8 - Enforcement hooks (optional)
93
93
 
94
- Claude Code: offer (picker, default Yes) to merge `$HOME/.claude/templates/claude-hooks.json` into `~/.claude/settings.json`; deep-merge EVERY event, never duplicate a matcher. Read `$HOME/.claude/multi-agent-refs/setup/hooks-and-plugins.md` before Step 8. Codex: only the syntax gate, via `node "$HOME/.codex/scripts/host-hooks.mjs" install --host codex`. Copilot CLI: no hook.
94
+ Claude Code: offer (picker, default Yes) to merge `$HOME/.claude/templates/claude-hooks.json` into `~/.claude/settings.json`; deep-merge EVERY event, never duplicate a matcher. First run `node "$HOME/.claude/lib/risky-settings.mjs" --json`; for each HIGH finding (bypass with a broad allow, a hook that runs fetched code, a literal secret) ask Keep / Fix it myself, naming the rule and place, never the value. Never edit the setting for the user; under autopilot only report. Read `$HOME/.claude/multi-agent-refs/setup/hooks-and-plugins.md` before Step 8. Codex: only the syntax gate, via `node "$HOME/.codex/scripts/host-hooks.mjs" install --host codex`. Copilot CLI: no hook.
95
95
 
96
96
  ### Step 9 - Default stack plugin enablement
97
97
 
@@ -25,13 +25,19 @@
25
25
  * or a positional, at its place in argv: an error it throws for one argument
26
26
  * comes before any error a later argument would raise.
27
27
  *
28
+ * An "unknown" error names the nearest declared flag when one is close
29
+ * (`suggestions`, and a hint in the message in the output language), and
30
+ * `unknownSubcommand` builds the matching error for a script's subcommand.
31
+ *
28
32
  * @module pipeline/lib/args
29
33
  */
30
34
 
35
+ import { messages } from "./user-facing.mjs";
36
+
31
37
  export class ArgsError extends Error {
32
38
  /**
33
39
  * @param {string} message
34
- * @param {{kind: "missing-value"|"unknown"|"unexpected"|"duplicate"|"exclusive", token: string, flag?: string|null}} detail
40
+ * @param {{kind: "missing-value"|"unknown"|"unknown-subcommand"|"unexpected"|"duplicate"|"exclusive", token: string, flag?: string|null}} detail
35
41
  */
36
42
  constructor(message, { kind, token, flag = null }) {
37
43
  super(message);
@@ -39,6 +45,7 @@ export class ArgsError extends Error {
39
45
  this.kind = kind;
40
46
  this.token = token;
41
47
  this.flag = flag;
48
+ this.suggestions = [];
42
49
  }
43
50
  }
44
51
 
@@ -53,10 +60,129 @@ function put(flags, key, value, many) {
53
60
  });
54
61
  }
55
62
 
63
+ /**
64
+ * Optimal string alignment distance: insertions, deletions, substitutions and
65
+ * a swap of two adjacent characters each cost one, so the commonest typo
66
+ * (`--josn`) is one edit away rather than two.
67
+ *
68
+ * @param {string} a
69
+ * @param {string} b
70
+ * @returns {number}
71
+ */
72
+ export function editDistance(a, b) {
73
+ const s = String(a);
74
+ const t = String(b);
75
+ const d = Array.from({ length: s.length + 1 }, (_, i) => [i, ...new Array(t.length).fill(0)]);
76
+ for (let j = 1; j <= t.length; j++) d[0][j] = j;
77
+ for (let i = 1; i <= s.length; i++) {
78
+ for (let j = 1; j <= t.length; j++) {
79
+ const cost = s[i - 1] === t[j - 1] ? 0 : 1;
80
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
81
+ if (i > 1 && j > 1 && s[i - 1] === t[j - 2] && s[i - 2] === t[j - 1]) {
82
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
83
+ }
84
+ }
85
+ }
86
+ return d[s.length][t.length];
87
+ }
88
+
89
+ /**
90
+ * The candidates a mistyped word most likely meant: those at the smallest
91
+ * edit distance, when that distance is within reach of the word's length
92
+ * (one edit up to three characters, two beyond), else the single candidate
93
+ * the word is a prefix of. Case is ignored and an exact match is no
94
+ * suggestion. A threshold that grew with length would start proposing
95
+ * unrelated words of similar size, which is worse than proposing nothing.
96
+ *
97
+ * @param {string} input
98
+ * @param {Iterable<string>} candidates
99
+ * @returns {string[]} sorted, possibly empty
100
+ */
101
+ export function suggest(input, candidates) {
102
+ const word = String(input ?? "").toLowerCase();
103
+ if (!word) return [];
104
+ const pool = [...new Set(Array.from(candidates ?? [], String))].filter(
105
+ (c) => c && c.toLowerCase() !== word,
106
+ );
107
+ const reach = word.length <= 3 ? 1 : 2;
108
+ let best = Infinity;
109
+ let near = [];
110
+ for (const c of pool) {
111
+ const dist = editDistance(word, c.toLowerCase());
112
+ if (dist > reach || dist > best) continue;
113
+ if (dist < best) {
114
+ best = dist;
115
+ near = [];
116
+ }
117
+ near.push(c);
118
+ }
119
+ if (near.length) return near.sort();
120
+ if (word.length < 3) return [];
121
+ const prefixed = pool.filter((c) => c.toLowerCase().startsWith(word));
122
+ return prefixed.length === 1 ? prefixed : [];
123
+ }
124
+
125
+ const HINT = {
126
+ en: {
127
+ meant: (names) => `did you mean ${names}?`,
128
+ known: (names) => `known: ${names}`,
129
+ or: " or ",
130
+ },
131
+ tr: {
132
+ meant: (names) => `${names} mi demek istediniz?`,
133
+ known: (names) => `bilinenler: ${names}`,
134
+ or: " ya da ",
135
+ },
136
+ };
137
+
138
+ /**
139
+ * " (did you mean --json?)" for a mistyped word, in the output language, or
140
+ * "" when no candidate is close. `prefix` is put in front of every name, so a
141
+ * flag reads as it is typed.
142
+ *
143
+ * @param {string} input
144
+ * @param {Iterable<string>} candidates
145
+ * @param {{prefix?: string}} [opts]
146
+ * @returns {string}
147
+ */
148
+ export function didYouMean(input, candidates, { prefix = "" } = {}) {
149
+ const names = suggest(input, candidates);
150
+ if (!names.length) return "";
151
+ const say = messages(HINT);
152
+ return ` (${say.meant(names.map((n) => `${prefix}${n}`).join(say.or))})`;
153
+ }
154
+
155
+ /**
156
+ * The error for a subcommand a script does not have: the nearest one when a
157
+ * name is close, else the whole list, since a subcommand set is short enough
158
+ * to read.
159
+ *
160
+ * @param {string} sub
161
+ * @param {Iterable<string>} known
162
+ * @returns {ArgsError}
163
+ */
164
+ export function unknownSubcommand(sub, known) {
165
+ const list = [...known];
166
+ const hint = didYouMean(sub, list) || ` (${messages(HINT).known(list.join(", "))})`;
167
+ const token = String(sub ?? "");
168
+ return new ArgsError(`unknown subcommand ${token}${hint}`, {
169
+ kind: "unknown-subcommand",
170
+ token,
171
+ });
172
+ }
173
+
56
174
  const missing = (token, flag) =>
57
175
  new ArgsError(`${token} needs a value`, { kind: "missing-value", token, flag });
58
- const unknownFlag = (token, flag) =>
59
- new ArgsError(`unknown option ${token}`, { kind: "unknown", token, flag });
176
+ const unknownFlag = (token, flag, known) => {
177
+ const suggestions = suggest(flag, known);
178
+ const e = new ArgsError(`unknown option ${token}${didYouMean(flag, known, { prefix: "--" })}`, {
179
+ kind: "unknown",
180
+ token,
181
+ flag,
182
+ });
183
+ e.suggestions = suggestions;
184
+ return e;
185
+ };
60
186
  const duplicate = (token, flag) =>
61
187
  new ArgsError(`${token} given more than once`, { kind: "duplicate", token, flag });
62
188
  const exclusive = (token, flag, group) =>
@@ -149,7 +275,8 @@ export function parseArgs(argv, opts = {}) {
149
275
  const body = a.slice(2);
150
276
  const eq = equals ? body.indexOf("=") : -1;
151
277
  const key = eq === -1 ? body : body.slice(0, eq);
152
- if (unknown === "error" && !known(key)) throw unknownFlag(a, key);
278
+ if (unknown === "error" && !known(key))
279
+ throw unknownFlag(a, key, [...booleans, ...strings, ...values, ...multiple]);
153
280
  if (unknown === "positional" && !known(key)) {
154
281
  if (!allowPositionals) throw unexpected(a);
155
282
  positionals.push(a);
@@ -20,7 +20,9 @@ export const LAUNCH_TIMEOUT_MS = 2 * 60 * 1000;
20
20
  /**
21
21
  * @param {{argv: string[], cwd: string, env: Record<string,string|undefined>,
22
22
  * precondition?: (o: {cwd: string, argv: string[], env: Record<string,string|undefined>}) => {ok: boolean, reason?: string},
23
- * bin?: string, timeoutMs?: number}} args
23
+ * bin?: string, timeoutMs?: number, stdio?: import("node:child_process").StdioOptions}} args
24
+ * stdio: a launch that runs to its end, rather than returning once the
25
+ * session exists, passes "ignore" so its output never fills a buffer.
24
26
  * @returns {{status: number|null, stdout?: string, stderr?: string, error?: Error, blocked?: string}}
25
27
  */
26
28
  export function startBackground({
@@ -30,6 +32,7 @@ export function startBackground({
30
32
  precondition,
31
33
  bin = resolveClaudeBin(env),
32
34
  timeoutMs = LAUNCH_TIMEOUT_MS,
35
+ stdio = ["ignore", "pipe", "pipe"],
33
36
  }) {
34
37
  if (!Array.isArray(argv) || !argv.every((a) => typeof a === "string")) {
35
38
  throw new TypeError("argv is a list of strings");
@@ -42,7 +45,7 @@ export function startBackground({
42
45
  cwd,
43
46
  env,
44
47
  encoding: "utf-8",
45
- stdio: ["ignore", "pipe", "pipe"],
48
+ stdio,
46
49
  timeout: timeoutMs,
47
50
  shell: false,
48
51
  });
@@ -178,10 +178,20 @@ do_set() {
178
178
  [ -z "$key" ] && { echo "usage: $0 set <key> <value|->" >&2; exit 3; }
179
179
  # Resolve through the same mapping as do_get so set/get stay symmetric.
180
180
  key=$(resolve_key "$key")
181
- # "-" means: read the secret from stdin (keeps it off argv).
181
+ # "-" or no value: read the secret from stdin (keeps it off argv); on a
182
+ # terminal the prompt is hidden and the trailing newline is dropped.
182
183
  if [ "$val" = "-" ]; then
183
184
  val=$(cat)
185
+ elif [ $# -lt 2 ]; then
186
+ if [ -t 0 ]; then
187
+ printf 'Secret for %s (input hidden): ' "$key" >&2
188
+ IFS= read -rs val || true
189
+ printf '\n' >&2
190
+ else
191
+ val=$(cat)
192
+ fi
184
193
  fi
194
+ [ -z "$val" ] && { echo "usage: $0 set <key> [<value>|-] (empty secret refused; pipe it in or type it at the prompt)" >&2; exit 3; }
185
195
  # The delegate receives the secret on stdin and hands it to `security -i` on
186
196
  # stdin as well, so no argv ever carries it, and it writes both the -l and -s
187
197
  # attributes that lookups by either convention expect.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * hook-once.mjs - run a hook's side effect once per event.
3
+ *
4
+ * The same event can reach a hook twice: a plugin and the user's settings
5
+ * register the same script on one matcher, or the host delivers again after
6
+ * a timeout. A hook that appends a row or mirrors a task would then write it
7
+ * twice. Before its side effect a hook claims the event; the claim is a file
8
+ * created with O_CREAT|O_EXCL|O_NOFOLLOW (safe-write.mjs createExclusive), so
9
+ * of any number of deliveries, concurrent ones included, exactly one wins.
10
+ *
11
+ * The event key is a sha256 of the hook name, the event name and the
12
+ * payload's tool_use_id, the one identity the host gives every tool event. A
13
+ * payload without one is not claimed and its side effect runs: two identical
14
+ * payloads without an id may be two real events, and a guess that folds them
15
+ * into one drops a row that should exist. The claim file is named by the
16
+ * digest and holds nothing from the payload.
17
+ *
18
+ * Claims live in MA_HOOK_ONCE_DIR, else /tmp/multi-agent-hook-once-<uid>
19
+ * (gc-tmp.sh sweeps the multi-agent-* prefix there), else the OS temp
20
+ * directory. The directory must be a real directory owned by this user with
21
+ * no access for others; anything else, a link included, is not used. Claims
22
+ * older than the TTL (ten minutes) are pruned at most once a TTL, by the hook
23
+ * that claims next.
24
+ *
25
+ * Failing open: when the claim cannot be made for any reason but "already
26
+ * claimed", the answer is true and the side effect runs. Writing a row twice
27
+ * is the smaller harm next to never writing it.
28
+ *
29
+ * @module pipeline/lib/hook-once
30
+ */
31
+
32
+ import { createHash } from "node:crypto";
33
+ import { existsSync, lstatSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
34
+ import { tmpdir } from "node:os";
35
+ import { join } from "node:path";
36
+
37
+ import { createExclusive, writeFileSafe } from "./safe-write.mjs";
38
+
39
+ export const HOOK_ONCE_TTL_MS = 10 * 60 * 1000;
40
+ const PRUNE_MARK = ".pruned";
41
+
42
+ const sha = (s) => createHash("sha256").update(s).digest("hex");
43
+
44
+ /** Where claims are kept. */
45
+ export function claimDir(env = process.env) {
46
+ if (env.MA_HOOK_ONCE_DIR) return env.MA_HOOK_ONCE_DIR;
47
+ const uid = typeof process.getuid === "function" ? process.getuid() : "user";
48
+ const base = existsSync("/tmp") ? "/tmp" : tmpdir();
49
+ return join(base, `multi-agent-hook-once-${uid}`);
50
+ }
51
+
52
+ /**
53
+ * The key one event has for one hook, or null when the payload carries no
54
+ * tool_use_id.
55
+ *
56
+ * @param {string} hook
57
+ * @param {object} payload
58
+ */
59
+ export function eventKey(hook, payload) {
60
+ if (!payload || typeof payload !== "object") return null;
61
+ const id = payload.tool_use_id;
62
+ if (typeof id !== "string" || !id) return null;
63
+ return sha(`${hook}\0${payload.hook_event_name ?? ""}\0${id}`);
64
+ }
65
+
66
+ /**
67
+ * dir, made 0700 if missing, or null when it is not safe to use: not a plain
68
+ * directory (a link included), not owned by this user, or open to others.
69
+ * The statusline cache keeps its file in such a directory too.
70
+ */
71
+ export function privateDir(dir) {
72
+ try {
73
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
74
+ const st = lstatSync(dir);
75
+ if (!st.isDirectory() || st.isSymbolicLink()) return null;
76
+ if (typeof process.getuid === "function" && st.uid !== process.getuid()) return null;
77
+ if ((st.mode & 0o077) !== 0) return null;
78
+ return dir;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ function prune(dir, ttlMs, now) {
85
+ const mark = join(dir, PRUNE_MARK);
86
+ try {
87
+ if (existsSync(mark) && now - statSync(mark).mtimeMs < ttlMs) return;
88
+ writeFileSafe(mark, "", { anchors: [dir] });
89
+ for (const name of readdirSync(dir)) {
90
+ if (name === PRUNE_MARK) continue;
91
+ const p = join(dir, name);
92
+ const st = lstatSync(p);
93
+ if (st.isFile() && now - st.mtimeMs > ttlMs) unlinkSync(p);
94
+ }
95
+ } catch {
96
+ return;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Claim `key`. True when this call is the first claim (run the side effect),
102
+ * false when the key was already claimed.
103
+ *
104
+ * @param {string} key
105
+ * @param {{dir?: string, ttlMs?: number, now?: number}} [opts]
106
+ */
107
+ export function claimOnce(
108
+ key,
109
+ { dir = claimDir(), ttlMs = HOOK_ONCE_TTL_MS, now = Date.now() } = {},
110
+ ) {
111
+ if (typeof key !== "string" || !/^[0-9a-z]{1,128}$/i.test(key)) return true;
112
+ const at = privateDir(dir);
113
+ if (!at) return true;
114
+ prune(at, ttlMs, now);
115
+ try {
116
+ createExclusive(join(at, key), "", { anchors: [at] });
117
+ return true;
118
+ } catch (err) {
119
+ return err?.code !== "EEXIST";
120
+ }
121
+ }
122
+
123
+ /**
124
+ * claimOnce for a hook payload: true when this delivery should run the side
125
+ * effect.
126
+ *
127
+ * @param {string} hook
128
+ * @param {object} payload
129
+ * @param {{dir?: string, ttlMs?: number, now?: number}} [opts]
130
+ */
131
+ export function claimHookEvent(hook, payload, opts = {}) {
132
+ const key = eventKey(hook, payload);
133
+ return key === null ? true : claimOnce(key, opts);
134
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * isotonic.mjs - isotonic regression by pool adjacent violators, for
3
+ * calibrating a score that should be monotone in a probability.
4
+ *
5
+ * A Beta posterior mean is a probability only in name until it is checked
6
+ * against what happened: with few rows it is overconfident at the ends. The
7
+ * fit maps a predicted value to the observed rate of the block it falls in,
8
+ * with the constraint that a higher prediction never maps lower. Zero
9
+ * dependencies (ADR-0004).
10
+ *
11
+ * @module pipeline/lib/isotonic
12
+ */
13
+
14
+ /**
15
+ * Fit a non-decreasing step function of `xs` to `ys` (each 0..1).
16
+ *
17
+ * @param {number[]} xs predictions
18
+ * @param {number[]} ys outcomes
19
+ * @returns {{x: number[], y: number[]}|null} one point per block: the mean
20
+ * prediction and the mean outcome; null for no data
21
+ */
22
+ export function fitIsotonic(xs, ys) {
23
+ const pairs = xs
24
+ .map((x, i) => [Number(x), Number(ys[i])])
25
+ .filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y))
26
+ .sort((a, b) => a[0] - b[0]);
27
+ if (!pairs.length) return null;
28
+ const blocks = [];
29
+ for (const [x, y] of pairs) {
30
+ const last = blocks[blocks.length - 1];
31
+ if (last && last.x === x) {
32
+ last.sy += y;
33
+ last.n += 1;
34
+ last.sx += x;
35
+ } else {
36
+ blocks.push({ x, sx: x, sy: y, n: 1 });
37
+ }
38
+ while (blocks.length > 1) {
39
+ const b = blocks[blocks.length - 1];
40
+ const a = blocks[blocks.length - 2];
41
+ if (a.sy / a.n <= b.sy / b.n) break;
42
+ blocks.splice(-2, 2, { x: a.x, sx: a.sx + b.sx, sy: a.sy + b.sy, n: a.n + b.n });
43
+ }
44
+ }
45
+ return {
46
+ x: blocks.map((b) => Number((b.sx / b.n).toFixed(6))),
47
+ y: blocks.map((b) => Number((b.sy / b.n).toFixed(6))),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * The calibrated value of `p`: linear between block points, clamped outside
53
+ * them. Without a model, `p` itself.
54
+ *
55
+ * @param {{x: number[], y: number[]}|null} model
56
+ * @param {number} p
57
+ * @returns {number}
58
+ */
59
+ export function applyIsotonic(model, p) {
60
+ if (!model || !model.x?.length) return p;
61
+ const { x, y } = model;
62
+ if (p <= x[0]) return y[0];
63
+ if (p >= x[x.length - 1]) return y[y.length - 1];
64
+ let lo = 0;
65
+ let hi = x.length - 1;
66
+ while (hi - lo > 1) {
67
+ const mid = (lo + hi) >> 1;
68
+ if (x[mid] <= p) lo = mid;
69
+ else hi = mid;
70
+ }
71
+ const t = (p - x[lo]) / (x[hi] - x[lo]);
72
+ return y[lo] + t * (y[hi] - y[lo]);
73
+ }
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file low-disk.mjs - one cheap free-space check, and the one line that
4
+ * suggests the disk-cleaner skill when the disk is nearly full or a failure
5
+ * log says it ran out of space.
6
+ *
7
+ * The check is a single statfs call. It never deletes anything and never
8
+ * asks; callers decide whether to ask. Low means below
9
+ * prefs.global.diskCleaner.lowDiskGb (default 10) gigabytes free OR below
10
+ * prefs.global.diskCleaner.lowDiskPercent (default 5) percent free.
11
+ * prefs.global.diskCleaner.suggest false silences the line everywhere.
12
+ *
13
+ * Usage:
14
+ * low-disk.mjs [--path DIR] [--scan FILE] [--lang en|tr] [--json]
15
+ *
16
+ * --scan reads a failure log and prints the line when it names ENOSPC or a
17
+ * low-disk error, whatever the free space is now. Without output the disk
18
+ * is fine. Exit is always 0, so a hook or a gate's failure path can call it
19
+ * without changing its own result.
20
+ *
21
+ * @module pipeline/lib/low-disk
22
+ */
23
+
24
+ import { readFileSync, realpathSync, statfsSync } from "node:fs";
25
+ import { homedir } from "node:os";
26
+ import { pathToFileURL } from "node:url";
27
+
28
+ import { globalPref } from "./prefs-value.mjs";
29
+
30
+ export const DEFAULT_LOW_GB = 10;
31
+ export const DEFAULT_LOW_PERCENT = 5;
32
+ const GB = 1e9;
33
+ const SCAN_MAX = 4 * 1024 * 1024;
34
+
35
+ /** Error text a full disk produces, across Node, the shell, git and Xcode. */
36
+ export const DISK_FULL =
37
+ /ENOSPC|No space left on device|disk (?:is )?full|not enough (?:free )?(?:disk )?space|insufficient (?:free )?(?:disk )?space|low disk space|out of disk space/i;
38
+
39
+ /** The thresholds from prefs, falling back to the defaults. */
40
+ export function thresholds(env = process.env) {
41
+ const gb = Number(globalPref("diskCleaner.lowDiskGb", DEFAULT_LOW_GB, env));
42
+ const pct = Number(globalPref("diskCleaner.lowDiskPercent", DEFAULT_LOW_PERCENT, env));
43
+ return {
44
+ lowGb: Number.isFinite(gb) && gb >= 0 ? gb : DEFAULT_LOW_GB,
45
+ lowPercent: Number.isFinite(pct) && pct >= 0 ? pct : DEFAULT_LOW_PERCENT,
46
+ suggest: globalPref("diskCleaner.suggest", true, env) !== false,
47
+ };
48
+ }
49
+
50
+ /** Free and total bytes of the volume holding `path`, or nulls. */
51
+ export function measure(path) {
52
+ try {
53
+ const s = statfsSync(path);
54
+ return { freeBytes: s.bavail * s.bsize, totalBytes: s.blocks * s.bsize };
55
+ } catch {
56
+ return { freeBytes: null, totalBytes: null };
57
+ }
58
+ }
59
+
60
+ /** True when either threshold is crossed. Unknown sizes are never low. */
61
+ export function isLow(status, th) {
62
+ if (status.freeBytes == null || !status.totalBytes) return false;
63
+ const pct = (status.freeBytes / status.totalBytes) * 100;
64
+ return status.freeBytes < th.lowGb * GB || pct < th.lowPercent;
65
+ }
66
+
67
+ export function mentionsDiskFull(text) {
68
+ return DISK_FULL.test(String(text || ""));
69
+ }
70
+
71
+ /** The suggestion, one line, in the caller's output language. */
72
+ export function suggestion(status, { lang = "en", cause = "low" } = {}) {
73
+ const free =
74
+ status.freeBytes == null
75
+ ? "?"
76
+ : `${(status.freeBytes / GB).toFixed(1)} GB` +
77
+ (status.totalBytes
78
+ ? ` (${((status.freeBytes / status.totalBytes) * 100).toFixed(1)}%)`
79
+ : "");
80
+ const cmd = "node ~/.claude/scripts/disk-cleaner.mjs --dry-run";
81
+ if (lang === "tr") {
82
+ const why = cause === "error" ? "Hata çıktısı diskin dolduğunu söylüyor" : "Disk dolmak üzere";
83
+ return `multi-agent: ${why}, boş alan ${free}. Neyin silinebileceğini görmek için disk-cleaner skill'ini çalıştır (\`${cmd}\`); onay vermeden hiçbir şey silinmez.`;
84
+ }
85
+ const why = cause === "error" ? "the failure output says the disk is full" : "disk nearly full";
86
+ return `multi-agent: ${why}, ${free} free. Run the disk-cleaner skill (\`${cmd}\`) to see what can be freed; nothing is deleted until you confirm.`;
87
+ }
88
+
89
+ /**
90
+ * The line to print, or null. `scanText` is failure output to look for a
91
+ * disk-full error in; without it only the free space decides.
92
+ */
93
+ export function check({ path = homedir(), scanText = null, lang = "en", env = process.env } = {}) {
94
+ const th = thresholds(env);
95
+ const status = measure(path);
96
+ const low = isLow(status, th);
97
+ const errored = scanText != null && mentionsDiskFull(scanText);
98
+ const line =
99
+ th.suggest && (low || errored)
100
+ ? suggestion(status, { lang, cause: errored ? "error" : "low" })
101
+ : null;
102
+ return { ...status, ...th, low, errored, line };
103
+ }
104
+
105
+ function readScan(file) {
106
+ try {
107
+ const text = readFileSync(file, "utf8");
108
+ return text.length > SCAN_MAX ? text.slice(-SCAN_MAX) : text;
109
+ } catch {
110
+ return null;
111
+ }
112
+ }
113
+
114
+ export function main(argv = process.argv.slice(2), env = process.env) {
115
+ const arg = (k) => {
116
+ const i = argv.indexOf(k);
117
+ if (i >= 0) return argv[i + 1];
118
+ const eq = argv.find((a) => a.startsWith(`${k}=`));
119
+ return eq ? eq.slice(k.length + 1) : undefined;
120
+ };
121
+ if (argv.includes("-h") || argv.includes("--help")) {
122
+ process.stdout.write(
123
+ "usage: low-disk.mjs [--path DIR] [--scan FILE] [--lang en|tr] [--json]\n",
124
+ );
125
+ return 0;
126
+ }
127
+ const scan = arg("--scan");
128
+ const r = check({
129
+ path: arg("--path") || env.HOME || homedir(),
130
+ scanText: scan ? readScan(scan) : null,
131
+ lang: arg("--lang") === "tr" ? "tr" : "en",
132
+ env,
133
+ });
134
+ if (argv.includes("--json")) process.stdout.write(JSON.stringify(r) + "\n");
135
+ else if (r.line) process.stdout.write(r.line + "\n");
136
+ return 0;
137
+ }
138
+
139
+ function invokedDirectly() {
140
+ try {
141
+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1] ?? "")).href;
142
+ } catch {
143
+ return false;
144
+ }
145
+ }
146
+
147
+ if (invokedDirectly()) {
148
+ try {
149
+ process.exitCode = main();
150
+ } catch {
151
+ process.exitCode = 0;
152
+ }
153
+ }