@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
@@ -0,0 +1,406 @@
1
+ /**
2
+ * @file _guard-probe.mjs - time, depth and size inputs thrown at every guard.
3
+ *
4
+ * eval-guard-robustness.mjs asks whether a disguised bad input is still
5
+ * caught. This asks whether a guard still answers at all, and in time, when
6
+ * the input is built to make a matcher slow or a parser give up:
7
+ *
8
+ * redos inputs that make a backtracking pattern or a character-at-a-time
9
+ * tokenizer go quadratic: long runs of quotes, backslashes,
10
+ * spaces, repeated words, unclosed `$(`, heredoc openers, flag
11
+ * clusters, URL-shaped and base64-shaped runs;
12
+ * size a 1 MB string;
13
+ * depth 5000 levels of nesting, as JSON in the tool input and as
14
+ * brackets in the text.
15
+ *
16
+ * Targets are of two kinds. Hook guards are read from
17
+ * install/templates/claude-hooks.json, every PreToolUse entry, with one tool
18
+ * per matcher alternative family, so a guard added to the template is probed
19
+ * without editing this file. Each runs as the hook runs: bash, the payload on
20
+ * stdin, a throwaway HOME. Library matchers (the outbound scan, the redactor,
21
+ * the folds, the fence, the narrowed-run reader) run in a child node process.
22
+ *
23
+ * Every probe has a timeout and runs in its own process, so a hang costs one
24
+ * probe, not the eval. A probe fails when it times out, when a hook exits
25
+ * with anything but 0 or 2, when a library call throws, or when its median
26
+ * time is over the limit: the hook's own template timeout, or LIB_FAIL_MS for
27
+ * a library call. A median over the advisory mark is reported, not failed.
28
+ * One run decides unless it is over the advisory mark; then two more runs
29
+ * give a median of three.
30
+ *
31
+ * A failure listed in guard-probe-known-holes.json, with a reason and an
32
+ * expiry date, is reported as known and does not fail the eval until the
33
+ * date passes. A listed hole that no longer fails is reported so the entry
34
+ * can go.
35
+ *
36
+ * @module pipeline/scripts/_guard-probe
37
+ */
38
+
39
+ import { spawn } from "node:child_process";
40
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
41
+ import { tmpdir } from "node:os";
42
+ import { join } from "node:path";
43
+
44
+ import { PREFS_ENV } from "../lib/prefs-value.mjs";
45
+
46
+ const ROOT = join(import.meta.dirname, "..", "..");
47
+ export const TEMPLATE = join(ROOT, "install", "templates", "claude-hooks.json");
48
+ export const KNOWN_HOLES = join(import.meta.dirname, "guard-probe-known-holes.json");
49
+
50
+ export const LIB_FAIL_MS = 1000;
51
+ export const LIB_ADVISORY_MS = 250;
52
+ export const HOOK_ADVISORY_EXTRA_MS = 2000;
53
+ const DEFAULT_HOOK_TIMEOUT_S = 10;
54
+ const CONCURRENCY = 4;
55
+
56
+ const MB = 1024 * 1024;
57
+ const DEPTH = 5000;
58
+
59
+ /** Input shapes, by name. Each builds its string on demand. */
60
+ export const SHAPES = {
61
+ "redos-quotes": { cls: "redos", build: () => `"${'\\"'.repeat(20000)}` },
62
+ "redos-backslash": { cls: "redos", build: () => `${"\\".repeat(50000)}x` },
63
+ "redos-spaces": { cls: "redos", build: () => `a${" ".repeat(100000)}!` },
64
+ "redos-repeated-word": { cls: "redos", build: () => `${"git ".repeat(20000)}commit -m x` },
65
+ "redos-trailer": { cls: "redos", build: () => `co-authored-by:${" ".repeat(50000)}x` },
66
+ "redos-heredoc": { cls: "redos", build: () => "cat <<EOF\n".repeat(5000) },
67
+ "redos-substitution": { cls: "redos", build: () => "$(".repeat(10000) },
68
+ "redos-flags": { cls: "redos", build: () => `rm ${"-rf ".repeat(30000)}/` },
69
+ "redos-url": { cls: "redos", build: () => `https://${"a.".repeat(50000)}` },
70
+ "redos-base64": { cls: "redos", build: () => "QUFB".repeat(65536) },
71
+ "size-1mb": { cls: "size", build: () => "a".repeat(MB) },
72
+ "depth-brackets": { cls: "depth", build: () => `${"(".repeat(DEPTH)}${")".repeat(DEPTH)}` },
73
+ "depth-json": { cls: "depth", json: true, build: () => "x" },
74
+ };
75
+
76
+ export const FAST_SHAPES = ["redos-quotes", "redos-backslash", "size-1mb", "depth-json"];
77
+
78
+ /** One concrete tool per matcher alternative the guards care about. */
79
+ const TOOL_FOR = [
80
+ [/^Bash$/, "Bash"],
81
+ [/^Edit$/, "Edit"],
82
+ [/^Write$/, "Write"],
83
+ [/^NotebookEdit$/, "NotebookEdit"],
84
+ [/^WebFetch$/, "WebFetch"],
85
+ [/^AskUserQuestion$/, "AskUserQuestion"],
86
+ [/^Read$/, "Read"],
87
+ [/^Grep$/, "Grep"],
88
+ [/^Glob$/, "Glob"],
89
+ [/^Agent$/, "Agent"],
90
+ [/^Task$/, "Task"],
91
+ [/multi-agent-toolkit/, "mcp__multi-agent-toolkit__web_goto"],
92
+ [/[Ff]igma/, "mcp__figma__get_design_context"],
93
+ ];
94
+
95
+ /**
96
+ * Hook targets from the template: every PreToolUse command, once per tool its
97
+ * matcher names.
98
+ *
99
+ * @param {string} [template]
100
+ * @returns {{id: string, script: string, tool: string, timeoutMs: number}[]}
101
+ */
102
+ export function hookTargets(template = TEMPLATE) {
103
+ const t = JSON.parse(readFileSync(template, "utf8"));
104
+ const out = [];
105
+ const seen = new Set();
106
+ for (const group of t.hooks?.PreToolUse ?? []) {
107
+ const alternatives = String(group.matcher || "").split("|");
108
+ for (const h of group.hooks ?? []) {
109
+ const m = /\/\.claude\/scripts\/([\w.-]+\.sh)/.exec(h.command || "");
110
+ if (!m) continue;
111
+ for (const alt of alternatives) {
112
+ const hit = TOOL_FOR.find(([re]) => re.test(alt));
113
+ if (!hit) continue;
114
+ const id = `${m[1]}[${hit[1]}]`;
115
+ if (seen.has(id)) continue;
116
+ seen.add(id);
117
+ out.push({
118
+ id,
119
+ script: m[1],
120
+ tool: hit[1],
121
+ timeoutMs: (Number(h.timeout) || DEFAULT_HOOK_TIMEOUT_S) * 1000,
122
+ });
123
+ }
124
+ }
125
+ }
126
+ return out;
127
+ }
128
+
129
+ /** A tool input for `tool` carrying `value` where that tool carries text. */
130
+ export function toolInput(tool, value, cwd) {
131
+ const file = join(cwd, "probe.txt");
132
+ switch (tool) {
133
+ case "Bash":
134
+ return { command: value };
135
+ case "Edit":
136
+ return { file_path: file, old_string: value, new_string: value };
137
+ case "Write":
138
+ return { file_path: file, content: value };
139
+ case "NotebookEdit":
140
+ return { notebook_path: join(cwd, "probe.ipynb"), new_source: value };
141
+ case "WebFetch":
142
+ return { url: "https://example.invalid/", prompt: value };
143
+ case "AskUserQuestion":
144
+ return { questions: [{ question: value, options: [{ label: "a" }, { label: "b" }] }] };
145
+ case "Read":
146
+ return { file_path: value.length > 4096 ? file : value };
147
+ case "Grep":
148
+ case "Glob":
149
+ return { pattern: value, path: cwd };
150
+ case "Agent":
151
+ case "Task":
152
+ return { description: "probe", prompt: value, subagent_type: "general-purpose" };
153
+ default:
154
+ return { url: "https://example.invalid/", text: value };
155
+ }
156
+ }
157
+
158
+ /** The PreToolUse payload as text; the depth shape nests tool_input 5000 deep. */
159
+ export function payloadText(tool, shape, cwd) {
160
+ const s = SHAPES[shape];
161
+ const base = { tool_name: tool, cwd, session_id: "probe", hook_event_name: "PreToolUse" };
162
+ if (!s.json) return JSON.stringify({ ...base, tool_input: toolInput(tool, s.build(), cwd) });
163
+ const nested = `${'{"a":'.repeat(DEPTH)}1${"}".repeat(DEPTH)}`;
164
+ const input = JSON.stringify(toolInput(tool, "probe", cwd)).replace(/}$/, `,"nested":${nested}}`);
165
+ return `${JSON.stringify(base).replace(/}$/, "")},"tool_input":${input}}`;
166
+ }
167
+
168
+ /** Library matchers, each called on the shape's text in a child process. */
169
+ export const LIBRARY = [
170
+ { id: "outbound-gate.scan", module: "pipeline/lib/outbound-gate.mjs", fn: "scan" },
171
+ { id: "redact", module: "pipeline/lib/redact.mjs", fn: "redact" },
172
+ { id: "normalizeForMatch", module: "pipeline/lib/normalize-text.mjs", fn: "normalizeForMatch" },
173
+ { id: "decodedVariants", module: "pipeline/lib/normalize-text.mjs", fn: "decodedVariants" },
174
+ { id: "suspiciousKinds", module: "pipeline/lib/untrusted-fence.mjs", fn: "suspiciousKinds" },
175
+ { id: "narrowedRun", module: "pipeline/scripts/_test-gaming.mjs", fn: "narrowedRun" },
176
+ { id: "narrowedLog", module: "pipeline/scripts/_test-gaming.mjs", fn: "narrowedLog" },
177
+ {
178
+ id: "scanTestGaming",
179
+ module: "pipeline/scripts/_test-gaming.mjs",
180
+ fn: "scanTestGaming",
181
+ diff: true,
182
+ },
183
+ ];
184
+
185
+ const CHILD = `
186
+ import { pathToFileURL } from "node:url";
187
+ const [modPath, fn, runs, diff] = process.argv.slice(1);
188
+ let text = "";
189
+ process.stdin.setEncoding("utf8");
190
+ for await (const c of process.stdin) text += c;
191
+ if (diff === "1") text = "diff --git a/x.js b/x.js\\n--- a/x.js\\n+++ b/x.js\\n@@ -1 +1 @@\\n+" + text + "\\n";
192
+ const mod = await import(pathToFileURL(modPath).href);
193
+ const times = [];
194
+ for (let i = 0; i < Number(runs); i++) {
195
+ const t = performance.now();
196
+ mod[fn](text);
197
+ times.push(performance.now() - t);
198
+ }
199
+ process.stdout.write(JSON.stringify(times));
200
+ `;
201
+
202
+ /**
203
+ * Run one probe in its own process group. On timeout the whole group is
204
+ * killed and the probe answers at once, so a hook's node or python child
205
+ * that keeps the pipes open cannot stretch the wait.
206
+ */
207
+ function run(cmd, args, { input, env, cwd, timeoutMs }) {
208
+ return new Promise((resolve) => {
209
+ const started = Date.now();
210
+ const child = spawn(cmd, args, { env, cwd, stdio: ["pipe", "pipe", "pipe"], detached: true });
211
+ let stdout = "";
212
+ let stderr = "";
213
+ let done = false;
214
+ const finish = (code, timedOut) => {
215
+ if (done) return;
216
+ done = true;
217
+ clearTimeout(timer);
218
+ resolve({ code, stdout, stderr, timedOut, ms: Date.now() - started });
219
+ };
220
+ const timer = setTimeout(() => {
221
+ try {
222
+ process.kill(-child.pid, "SIGKILL");
223
+ } catch {
224
+ child.kill("SIGKILL");
225
+ }
226
+ child.stdout.destroy();
227
+ child.stderr.destroy();
228
+ finish(null, true);
229
+ }, timeoutMs);
230
+ child.stdout.on("data", (d) => (stdout += d));
231
+ child.stderr.on("data", (d) => (stderr += d.toString().slice(0, 4096)));
232
+ child.on("close", (code) => finish(code, false));
233
+ child.stdin.on("error", () => {});
234
+ child.stdin.end(input);
235
+ });
236
+ }
237
+
238
+ const median = (xs) => [...xs].sort((a, b) => a - b)[Math.floor(xs.length / 2)];
239
+
240
+ async function probeHook(target, shape, ctx) {
241
+ const env = {
242
+ ...process.env,
243
+ HOME: ctx.home,
244
+ MULTI_AGENT_UNATTENDED: "",
245
+ [PREFS_ENV]: join(ctx.home, "none.json"),
246
+ LOGS_ROOT: join(ctx.home, "logs"),
247
+ };
248
+ const input = payloadText(target.tool, shape, ctx.cwd);
249
+ const script = join(ROOT, "pipeline", "scripts", target.script);
250
+ const once = () =>
251
+ run("bash", [script], { input, env, cwd: ctx.cwd, timeoutMs: target.timeoutMs + 2000 });
252
+ const first = await once();
253
+ if (first.timedOut) return { verdict: "fail", why: `timed out after ${first.ms} ms` };
254
+ if (first.code !== 0 && first.code !== 2) {
255
+ return { verdict: "fail", why: `exit ${first.code}: ${first.stderr.trim().split("\n")[0]}` };
256
+ }
257
+ const advisory = (ctx.baseline.get(target.id) ?? 0) + HOOK_ADVISORY_EXTRA_MS;
258
+ const times = [first.ms];
259
+ if (first.ms > advisory && !ctx.fast) {
260
+ for (let i = 0; i < 2; i++) times.push((await once()).ms);
261
+ }
262
+ const ms = median(times);
263
+ if (ms > target.timeoutMs)
264
+ return { verdict: "fail", why: `median ${ms} ms over the hook timeout` };
265
+ if (ms > advisory) return { verdict: "slow", why: `median ${ms} ms` };
266
+ return { verdict: "pass", ms };
267
+ }
268
+
269
+ async function probeLibrary(lib, shape, ctx) {
270
+ const s = SHAPES[shape];
271
+ const text = s.json ? `${'{"a":'.repeat(DEPTH)}1${"}".repeat(DEPTH)}` : s.build();
272
+ const call = (runs) =>
273
+ run(
274
+ process.execPath,
275
+ [
276
+ "--input-type=module",
277
+ "-e",
278
+ CHILD,
279
+ lib.module.startsWith("/") ? lib.module : join(ROOT, lib.module),
280
+ lib.fn,
281
+ String(runs),
282
+ lib.diff ? "1" : "0",
283
+ ],
284
+ { input: text, env: process.env, cwd: ctx.cwd, timeoutMs: ctx.libTimeoutMs },
285
+ );
286
+ let r = await call(1);
287
+ if (r.timedOut) return { verdict: "fail", why: `timed out after ${r.ms} ms` };
288
+ if (r.code !== 0) {
289
+ return { verdict: "fail", why: `threw: ${r.stderr.trim().split("\n").slice(-1)[0]}` };
290
+ }
291
+ let times = JSON.parse(r.stdout);
292
+ if (times[0] > LIB_ADVISORY_MS && !ctx.fast) {
293
+ r = await call(3);
294
+ if (r.code === 0 && !r.timedOut) times = JSON.parse(r.stdout);
295
+ }
296
+ const ms = Math.round(median(times));
297
+ if (ms > LIB_FAIL_MS) return { verdict: "fail", why: `median ${ms} ms` };
298
+ if (ms > LIB_ADVISORY_MS) return { verdict: "slow", why: `median ${ms} ms` };
299
+ return { verdict: "pass", ms };
300
+ }
301
+
302
+ async function pool(jobs, limit) {
303
+ const results = new Array(jobs.length);
304
+ let next = 0;
305
+ const worker = async () => {
306
+ while (next < jobs.length) {
307
+ const i = next++;
308
+ results[i] = await jobs[i]();
309
+ }
310
+ };
311
+ await Promise.all(Array.from({ length: Math.min(limit, jobs.length) }, worker));
312
+ return results;
313
+ }
314
+
315
+ /** Known holes: {id, reason, added, expires}; an entry past its date is not honoured. */
316
+ export function readKnownHoles(path = KNOWN_HOLES) {
317
+ try {
318
+ return JSON.parse(readFileSync(path, "utf8")).holes ?? [];
319
+ } catch {
320
+ return [];
321
+ }
322
+ }
323
+
324
+ /**
325
+ * Sort probe results against the known holes: a failure listed with an
326
+ * expiry on or after `date` is known, any other failure (a listed one past
327
+ * its date included) fails; a listed hole that was probed and did not fail is
328
+ * fixed.
329
+ *
330
+ * @param {object[]} results
331
+ * @param {{id: string, expires: string}[]} holes
332
+ * @param {string} date YYYY-MM-DD
333
+ */
334
+ export function classify(results, holes, date) {
335
+ const byId = new Map(holes.map((h) => [h.id, h]));
336
+ const failures = [];
337
+ const known = [];
338
+ for (const r of results.filter((x) => x.verdict === "fail")) {
339
+ const hole = byId.get(r.id);
340
+ if (hole && String(hole.expires) >= date) known.push({ ...r, hole });
341
+ else failures.push({ ...r, expired: Boolean(hole) });
342
+ }
343
+ const failed = new Set(results.filter((x) => x.verdict === "fail").map((x) => x.id));
344
+ const probed = new Set(results.map((x) => x.id));
345
+ const fixed = holes.filter((h) => probed.has(h.id) && !failed.has(h.id));
346
+ const slow = results.filter((x) => x.verdict === "slow");
347
+ return { results, failures, known, slow, fixed };
348
+ }
349
+
350
+ /**
351
+ * Run the probe. `hooks`, `library` and `shapes` default to the template's
352
+ * hooks, LIBRARY and every shape (the fast subset with `fast`).
353
+ *
354
+ * @param {{fast?: boolean, today?: string, holes?: object[], hooks?: object[],
355
+ * library?: object[], shapes?: string[], libTimeoutMs?: number}} [opts]
356
+ * @returns {Promise<{results: object[], failures: object[], known: object[], slow: object[], fixed: object[]}>}
357
+ */
358
+ export async function runProbe({
359
+ fast = false,
360
+ today,
361
+ holes = readKnownHoles(),
362
+ hooks: givenHooks,
363
+ library = LIBRARY,
364
+ shapes: givenShapes,
365
+ libTimeoutMs = LIB_FAIL_MS * 10,
366
+ } = {}) {
367
+ const home = mkdtempSync(join(tmpdir(), "guard-probe-"));
368
+ const ctx = { fast, home, cwd: home, baseline: new Map(), libTimeoutMs };
369
+ const date = today ?? new Date().toISOString().slice(0, 10);
370
+ try {
371
+ let hooks = givenHooks ?? hookTargets();
372
+ if (fast && !givenHooks) hooks = hooks.filter((h) => h.id === "agent-guard.sh[Bash]");
373
+ const shapes = givenShapes ?? (fast ? FAST_SHAPES : Object.keys(SHAPES));
374
+ const env = { ...process.env, HOME: home, MULTI_AGENT_UNATTENDED: "" };
375
+ for (const h of hooks) {
376
+ const r = await run("bash", [join(ROOT, "pipeline", "scripts", h.script)], {
377
+ input: JSON.stringify({
378
+ tool_name: h.tool,
379
+ tool_input: toolInput(h.tool, "ls", home),
380
+ cwd: home,
381
+ }),
382
+ env,
383
+ cwd: home,
384
+ timeoutMs: h.timeoutMs + 2000,
385
+ });
386
+ ctx.baseline.set(h.id, r.ms);
387
+ }
388
+ const jobs = [];
389
+ for (const h of hooks) {
390
+ for (const shape of shapes) {
391
+ jobs.push(async () => ({ id: `${h.id}/${shape}`, ...(await probeHook(h, shape, ctx)) }));
392
+ }
393
+ }
394
+ for (const lib of library) {
395
+ for (const shape of shapes) {
396
+ jobs.push(async () => ({
397
+ id: `${lib.id}/${shape}`,
398
+ ...(await probeLibrary(lib, shape, ctx)),
399
+ }));
400
+ }
401
+ }
402
+ return classify(await pool(jobs, CONCURRENCY), holes, date);
403
+ } finally {
404
+ rmSync(home, { recursive: true, force: true });
405
+ }
406
+ }
@@ -25,6 +25,7 @@ a body is where a commit message usually is.
25
25
  read_only_* a commit, push or file write into a repository
26
26
  listed in prefs.global.readOnlyRepos
27
27
  """
28
+ import fnmatch
28
29
  import hashlib
29
30
  import json
30
31
  import os
@@ -731,6 +732,187 @@ def _learnings_ask(argv):
731
732
  return None
732
733
 
733
734
 
735
+ HOME_VAR = re.compile(r"^(?:\$HOME|\$\{HOME\})(?=/|$)")
736
+ ROOT_DELETE = (
737
+ "rm -r on the filesystem root deletes everything this account can write; "
738
+ "the user confirms it"
739
+ )
740
+ HOME_DELETE = (
741
+ "rm -r on $HOME or a directory above it deletes every project, credential and setting "
742
+ "under home; the user confirms it"
743
+ )
744
+
745
+
746
+ def _rm_recursive(args):
747
+ for a in args:
748
+ if a == "--":
749
+ return False
750
+ if a == "--recursive" or (
751
+ a.startswith("-") and not a.startswith("--") and ("r" in a[1:] or "R" in a[1:])
752
+ ):
753
+ return True
754
+ return False
755
+
756
+
757
+ def _rm_operands(args):
758
+ out, ended = [], False
759
+ for a in args:
760
+ if not ended and a == "--":
761
+ ended = True
762
+ elif ended or not a.startswith("-"):
763
+ out.append(a)
764
+ return out
765
+
766
+
767
+ HOME_BRACED = re.compile(r"^\$\{HOME(?:(?P<op>:?[-=?+]|%%?|##?)(?P<word>[^}]*))?\}(?=/|$)")
768
+ TILDE_USER = re.compile(r"^~(?P<user>[A-Za-z0-9_][A-Za-z0-9_.-]*)(?=/|$)")
769
+
770
+
771
+ def _user_home(user):
772
+ """The home directory ~user names, or None when no such account exists
773
+ (the shell then leaves ~user as a literal relative name)."""
774
+ try:
775
+ import pwd
776
+ except ImportError:
777
+ return None
778
+ try:
779
+ return pwd.getpwnam(user).pw_dir or None
780
+ except KeyError:
781
+ return None
782
+
783
+
784
+ def _trim(value, pattern, op):
785
+ """${HOME%pat}, ${HOME%%pat}, ${HOME#pat} and ${HOME##pat} on value, the
786
+ pattern matched as a shell glob."""
787
+ n = len(value)
788
+ if op in ("%", "%%"):
789
+ cuts = range(n, -1, -1) if op == "%" else range(0, n + 1)
790
+ for i in cuts:
791
+ if fnmatch.fnmatchcase(value[i:], pattern):
792
+ return value[:i]
793
+ else:
794
+ cuts = range(0, n + 1) if op == "#" else range(n, -1, -1)
795
+ for i in cuts:
796
+ if fnmatch.fnmatchcase(value[:i], pattern):
797
+ return value[i:]
798
+ return value
799
+
800
+
801
+ def _home_expansion(tok, home):
802
+ """tok with a leading $HOME form replaced by what the shell expands it to:
803
+ $HOME, ${HOME}, ${HOME:?..}, ${HOME:-..}, ${HOME:=..} (home is set, so
804
+ each is home), ${HOME:+word} (the word), the trims ${HOME%pat} and the
805
+ like, ~ and ~user. Anything else comes back unchanged."""
806
+ if tok == "~" or tok.startswith("~/"):
807
+ return home + tok[1:]
808
+ m = TILDE_USER.match(tok)
809
+ if m:
810
+ user_home = _user_home(m.group("user"))
811
+ return tok if user_home is None else user_home + tok[m.end():]
812
+ m = HOME_VAR.match(tok)
813
+ if m:
814
+ return home + tok[m.end():]
815
+ m = HOME_BRACED.match(tok)
816
+ if not m:
817
+ return tok
818
+ op, word, rest = m.group("op"), m.group("word") or "", tok[m.end():]
819
+ if not op:
820
+ return home + rest
821
+ if op.endswith("+"):
822
+ return word + rest
823
+ if op[0] in "%#":
824
+ if "$" in word or "`" in word:
825
+ return tok
826
+ return _trim(home, word, op) + rest
827
+ return home + rest
828
+
829
+
830
+ def _rm_target(tok, cwd):
831
+ """The absolute, normalised path an rm operand names, or None when it
832
+ depends on something other than $HOME (another variable, a substitution)
833
+ or is relative with no known working directory. A trailing `*` or `.*`
834
+ component stands for the directory it lists."""
835
+ t = _home_expansion(tok, os.path.expanduser("~"))
836
+ if "$" in t or "`" in t:
837
+ return None
838
+ parts = t.rstrip("/").split("/") if t.rstrip("/") else [""]
839
+ while len(parts) > 1 and parts[-1] in ("*", ".*"):
840
+ parts.pop()
841
+ t = "/".join(parts) or "/"
842
+ if t in ("*", ".*"):
843
+ t = "."
844
+ if not os.path.isabs(t):
845
+ if not cwd:
846
+ return None
847
+ t = os.path.join(cwd, t)
848
+ return re.sub(r"^/+", "/", os.path.normpath(t))
849
+
850
+
851
+ def _destructive_rm_ask(argv, cwd):
852
+ """rm -r on the filesystem root, on $HOME, or on a directory above it.
853
+ Anything inside home or inside the project is an ordinary delete."""
854
+ if not argv or os.path.basename(argv[0]) != "rm":
855
+ return None
856
+ args = argv[1:]
857
+ if "--no-preserve-root" in args:
858
+ return ROOT_DELETE
859
+ if not _rm_recursive(args):
860
+ return None
861
+ homes = {
862
+ os.path.normpath(os.path.expanduser("~")),
863
+ os.path.realpath(os.path.expanduser("~")),
864
+ }
865
+ for tok in _rm_operands(args):
866
+ p = _rm_target(tok, cwd)
867
+ if p is None:
868
+ continue
869
+ if p == "/":
870
+ return ROOT_DELETE
871
+ named = TILDE_USER.match(tok)
872
+ owner = _user_home(named.group("user")) if named else None
873
+ for h in homes | ({os.path.normpath(owner)} if owner else set()):
874
+ if p == h or h.startswith(p.rstrip("/") + "/"):
875
+ return HOME_DELETE
876
+ return None
877
+
878
+
879
+ FORK_HEAD = re.compile(r"\(\s*\)\s*\{")
880
+ FORK_NAME_MAX = 64
881
+ FORK_NAME_STOP = set(" \t\n(){}|&;<>")
882
+ PERL_FORK_BOMB = re.compile(r"\bfork\s+while\s+fork\b")
883
+ FORK_BOMB = (
884
+ "a fork bomb: a function that starts two copies of itself in the background "
885
+ "exhausts the process table; the user confirms it"
886
+ )
887
+
888
+
889
+ def fork_bomb_reason(cmd):
890
+ """A shell function whose body pipes itself into itself in the background,
891
+ then is called (`:(){ :|:& };:`), or perl's `fork while fork`. Each
892
+ `(){` head is examined once with a bounded name, so the scan is linear."""
893
+ if not isinstance(cmd, str):
894
+ return None
895
+ if PERL_FORK_BOMB.search(cmd):
896
+ return FORK_BOMB
897
+ for m in FORK_HEAD.finditer(cmd):
898
+ end = m.start()
899
+ while end > 0 and cmd[end - 1] in " \t":
900
+ end -= 1
901
+ start = end
902
+ while start > 0 and end - start < FORK_NAME_MAX and cmd[start - 1] not in FORK_NAME_STOP:
903
+ start -= 1
904
+ name = cmd[start:end]
905
+ if not name:
906
+ continue
907
+ n = re.escape(name)
908
+ tail = re.compile(
909
+ r"\s*" + n + r"\s*\|\s*" + n + r"\s*&\s*;?\s*\}\s*;?\s*" + n + r"(?![^\s;&|])"
910
+ )
911
+ if tail.match(cmd, m.end()):
912
+ return FORK_BOMB
913
+ return None
914
+
915
+
734
916
  def ask_reason(toks, seg, cwd=None):
735
917
  """Why a person should confirm this segment, or None."""
736
918
  _, argv = command_word(toks)
@@ -741,6 +923,7 @@ def ask_reason(toks, seg, cwd=None):
741
923
  or _cleanup_ask(argv)
742
924
  or _product_tree_ask(argv, seg, cwd)
743
925
  or _learnings_ask(argv)
926
+ or _destructive_rm_ask(argv, cwd)
744
927
  )
745
928
 
746
929
 
@@ -805,6 +988,29 @@ def secret_echo_reason(cmd):
805
988
  return None
806
989
 
807
990
 
991
+ # The guard answers inside its own deadline, so it decodes less than the
992
+ # outbound gate: a command line longer than this is not a hiding place a
993
+ # reviewer would miss anyway.
994
+ GUARD_DECODE_LIMITS = {"maxInputChars": 64 * 1024, "maxDecodedChars": 64 * 1024}
995
+
996
+
997
+ def encoded_secret_read_reason(cmd):
998
+ """A stored-secret read hidden inside base64, hex or rot13 text
999
+ (_decode_text.py, bounded). Reading a secret has a plain spelling; an
1000
+ encoded one only hides it from review."""
1001
+ import _decode_text
1002
+
1003
+ if not isinstance(cmd, str) or not cmd:
1004
+ return None
1005
+ for v in _decode_text.decoded_variants(cmd, GUARD_DECODE_LIMITS):
1006
+ if SECRET_READ.search(v["text"]):
1007
+ return (
1008
+ "the command carries a stored-secret read hidden in " + v["kind"]
1009
+ + " text; run the read in plain text, where it can be judged"
1010
+ )
1011
+ return None
1012
+
1013
+
808
1014
  # --- the run this session drives ----------------------------------------------
809
1015
 
810
1016
 
@@ -41,7 +41,7 @@
41
41
  * @module pipeline/scripts/_memory-policy
42
42
  */
43
43
 
44
- import { shortId, tokens } from "./_retrieval.mjs";
44
+ import { cosine, idfWeights as idf, shortId, tfidfVector as tfidf, tokens } from "./_retrieval.mjs";
45
45
  import { prefsPath, readPrefsFile } from "../lib/prefs-value.mjs";
46
46
 
47
47
  const CORROBORATION = 2;
@@ -307,30 +307,6 @@ const claimShape = (text) => ({
307
307
  plain: plainWords(text),
308
308
  });
309
309
 
310
- /** Inverse document frequencies over a corpus of token lists. */
311
- function idf(corpus) {
312
- const df = new Map();
313
- for (const doc of corpus) for (const t of new Set(doc)) df.set(t, (df.get(t) || 0) + 1);
314
- const n = corpus.length;
315
- return (t) => Math.log(1 + n / (df.get(t) || 1));
316
- }
317
-
318
- function tfidf(doc, weight) {
319
- const tf = new Map();
320
- for (const t of doc) tf.set(t, (tf.get(t) || 0) + 1);
321
- const v = new Map();
322
- for (const [t, c] of tf) v.set(t, c * weight(t));
323
- return v;
324
- }
325
-
326
- function cosine(va, vb) {
327
- let dot = 0;
328
- for (const [t, w] of va) dot += w * (vb.get(t) || 0);
329
- const norm = (v) => Math.sqrt([...v.values()].reduce((s, w) => s + w * w, 0));
330
- const d = norm(va) * norm(vb);
331
- return d ? dot / d : 0;
332
- }
333
-
334
310
  /** Jaccard overlap of adjacent token pairs: low when the same words come in another order. */
335
311
  function orderOverlap(a, b) {
336
312
  const pairs = (doc) => new Set(doc.slice(1).map((t, i) => `${doc[i]} ${t}`));