@mmerterden/multi-agent-pipeline 20.40.0 → 20.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +94 -0
- package/README.md +5 -2
- package/README.tr.md +5 -2
- package/docs/adr/0019-product-tree.md +143 -0
- package/docs/adr/README.md +1 -0
- package/docs/ecosystem.md +51 -14
- package/docs/facts.json +7 -7
- package/docs/features.md +15 -4
- package/install/claude.mjs +45 -3
- package/install/templates/claude-hooks.json +23 -1
- package/manifest.json +146 -107
- package/package.json +3 -2
- package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
- package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
- package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
- package/pipeline/contract/types/index.d.ts +53 -49
- package/pipeline/lib/args.mjs +131 -4
- package/pipeline/lib/bg-launch.mjs +5 -2
- package/pipeline/lib/context-budget.mjs +5 -42
- package/pipeline/lib/credential-store.sh +11 -1
- package/pipeline/lib/hook-once.mjs +134 -0
- package/pipeline/lib/hook-registration.mjs +5 -0
- package/pipeline/lib/isotonic.mjs +73 -0
- package/pipeline/lib/low-disk.mjs +153 -0
- package/pipeline/lib/mcp-schema-load.mjs +90 -0
- package/pipeline/lib/md2confluence-v3.py +19 -10
- package/pipeline/lib/model-dispatch.sh +26 -2
- package/pipeline/lib/normalize-text.mjs +135 -0
- package/pipeline/lib/outbound-gate.mjs +21 -3
- package/pipeline/lib/plan-todos.sh +17 -4
- package/pipeline/lib/redact.mjs +12 -3
- package/pipeline/lib/risky-settings.mjs +198 -0
- package/pipeline/lib/route-state.sh +1 -0
- package/pipeline/lib/secret-patterns.generated.mjs +6 -2
- package/pipeline/lib/session-usage.mjs +232 -0
- package/pipeline/lib/source-digest.mjs +211 -0
- package/pipeline/lib/tdd-evidence.mjs +250 -17
- package/pipeline/lib/tiered-budget.mjs +87 -0
- package/pipeline/lib/untrusted-fence.mjs +132 -1
- package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
- package/pipeline/multi-agent-refs/analysis/review.md +23 -1
- package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
- package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
- package/pipeline/multi-agent-refs/features/doctor.md +82 -4
- package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
- package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
- package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
- package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
- package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
- package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
- package/pipeline/multi-agent-refs/help/en.md +2 -1
- package/pipeline/multi-agent-refs/help/tr.md +2 -1
- package/pipeline/multi-agent-refs/knowledge.md +58 -0
- package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
- package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
- package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
- package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
- package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
- package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
- package/pipeline/multi-agent-refs/progress-contract.md +3 -1
- package/pipeline/office/index.html +13 -7
- package/pipeline/office/toolkit.json +1 -1
- package/pipeline/preferences-template.json +1 -0
- package/pipeline/rules/outside-the-pipeline.md +1 -1
- package/pipeline/schemas/doctor-report.schema.json +47 -0
- package/pipeline/schemas/learnings-ledger.schema.json +35 -2
- package/pipeline/schemas/office-archive.schema.json +225 -128
- package/pipeline/schemas/plan-todos.schema.json +29 -1
- package/pipeline/schemas/prefs.schema.json +146 -0
- package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
- package/pipeline/schemas/product-tree.schema.json +136 -0
- package/pipeline/schemas/route-config.schema.json +51 -0
- package/pipeline/schemas/secret-patterns.json +17 -1
- package/pipeline/schemas/toolkit-path-params.json +15 -1
- package/pipeline/scripts/_cost-advise.mjs +357 -0
- package/pipeline/scripts/_cost-budget.mjs +78 -0
- package/pipeline/scripts/_cost.mjs +29 -0
- package/pipeline/scripts/_decode_text.py +107 -0
- package/pipeline/scripts/_eval-stats.mjs +182 -0
- package/pipeline/scripts/_guard-probe.mjs +406 -0
- package/pipeline/scripts/_guard_rules.py +336 -1
- package/pipeline/scripts/_learnings-promotion.mjs +229 -0
- package/pipeline/scripts/_locate.mjs +539 -0
- package/pipeline/scripts/_memory-policy.mjs +208 -33
- package/pipeline/scripts/_product-tree-extract.mjs +761 -0
- package/pipeline/scripts/_product-tree.mjs +923 -0
- package/pipeline/scripts/_retrieval.mjs +161 -4
- package/pipeline/scripts/_secret-scan.mjs +6 -1
- package/pipeline/scripts/_stack-routing.mjs +2 -0
- package/pipeline/scripts/_test-gaming.mjs +346 -0
- package/pipeline/scripts/_user_guard_rules.py +744 -0
- package/pipeline/scripts/agent-guard.py +69 -6
- package/pipeline/scripts/agent-guard.sh +8 -1
- package/pipeline/scripts/argv-secret-scan.mjs +2 -1
- package/pipeline/scripts/autopilot-loop.mjs +407 -0
- package/pipeline/scripts/autopilot-runner.mjs +38 -25
- package/pipeline/scripts/capture-resume.sh +9 -1
- package/pipeline/scripts/cost-analyze.mjs +66 -4
- package/pipeline/scripts/cost-budget-check.mjs +5 -13
- package/pipeline/scripts/disk-cleaner.mjs +1418 -0
- package/pipeline/scripts/doctor.mjs +324 -43
- package/pipeline/scripts/evidence-gate.mjs +90 -0
- package/pipeline/scripts/gate-ledger.mjs +76 -21
- package/pipeline/scripts/gc-tmp.sh +5 -0
- package/pipeline/scripts/graph-query.mjs +257 -17
- package/pipeline/scripts/guard-probe-known-holes.json +3 -0
- package/pipeline/scripts/learnings-ledger.mjs +680 -55
- package/pipeline/scripts/note-agent-event.mjs +2 -0
- package/pipeline/scripts/note-mcp-failure.mjs +363 -0
- package/pipeline/scripts/note-mcp-failure.sh +19 -0
- package/pipeline/scripts/note-skill-use.mjs +96 -23
- package/pipeline/scripts/office-archive.mjs +23 -10
- package/pipeline/scripts/office-memory.mjs +4 -1
- package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
- package/pipeline/scripts/pre-commit-check.sh +2 -2
- package/pipeline/scripts/pre-push-check.sh +8 -1
- package/pipeline/scripts/product-tree-eval.mjs +685 -0
- package/pipeline/scripts/product-tree.mjs +544 -0
- package/pipeline/scripts/publish-staged.mjs +324 -0
- package/pipeline/scripts/route-learn.mjs +628 -0
- package/pipeline/scripts/run-scope-guard.mjs +55 -1
- package/pipeline/scripts/scan-agent-config.sh +1 -1
- package/pipeline/scripts/statusline.mjs +309 -0
- package/pipeline/scripts/test-integrity-gate.mjs +97 -2
- package/pipeline/scripts/triage-memory.mjs +12 -4
- package/pipeline/scripts/uninstall.mjs +1 -0
- package/pipeline/skills/.skill-manifest.json +15 -7
- package/pipeline/skills/.skills-index.json +25 -3
- package/pipeline/skills/shared/README.md +6 -4
- package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
- package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
- package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
- package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
- package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
- package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
- package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
- package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
- package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
- package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
- package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
- package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
- package/pipeline/skills/skill-copies.json +9 -1
- package/pipeline/skills/skills-index.md +4 -2
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file _eval-stats.mjs - ranking metrics and paired significance tests for
|
|
3
|
+
* product-tree-eval.mjs.
|
|
4
|
+
*
|
|
5
|
+
* Two arms answer the same bugs, so every comparison here is paired: McNemar's
|
|
6
|
+
* exact test on the per-bug hit / miss outcome, and a bootstrap that resamples
|
|
7
|
+
* bugs (not arms) for the confidence interval of the difference. The exact
|
|
8
|
+
* test is used rather than the chi-square approximation because a repo
|
|
9
|
+
* contributes tens of bugs, and the approximation is poor when the discordant
|
|
10
|
+
* count is small.
|
|
11
|
+
*
|
|
12
|
+
* The bootstrap takes a seed, so a report reproduces byte for byte.
|
|
13
|
+
*
|
|
14
|
+
* Zero dependencies.
|
|
15
|
+
*
|
|
16
|
+
* @module pipeline/scripts/_eval-stats
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* n choose k, exact for the sizes an evaluation reaches.
|
|
21
|
+
*
|
|
22
|
+
* @param {number} n
|
|
23
|
+
* @param {number} k
|
|
24
|
+
* @returns {number}
|
|
25
|
+
*/
|
|
26
|
+
export function binomial(n, k) {
|
|
27
|
+
if (k < 0 || k > n) return 0;
|
|
28
|
+
const m = Math.min(k, n - k);
|
|
29
|
+
let r = 1;
|
|
30
|
+
for (let i = 1; i <= m; i++) r = (r * (n - m + i)) / i;
|
|
31
|
+
return Math.round(r);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Two-sided exact McNemar p-value.
|
|
36
|
+
*
|
|
37
|
+
* The binomial tail is summed in log space: 2^n and n choose k overflow a
|
|
38
|
+
* double past about 1023 discordant pairs.
|
|
39
|
+
*
|
|
40
|
+
* @param {number} b bugs the first arm hit and the second missed
|
|
41
|
+
* @param {number} c bugs the second arm hit and the first missed
|
|
42
|
+
* @returns {number} p in [0, 1]
|
|
43
|
+
*/
|
|
44
|
+
export function mcnemarExact(b, c) {
|
|
45
|
+
const n = b + c;
|
|
46
|
+
if (n === 0) return 1;
|
|
47
|
+
const lo = Math.min(b, c);
|
|
48
|
+
const logs = [0];
|
|
49
|
+
for (let i = 1; i <= lo; i++) logs.push(logs[i - 1] + Math.log(n - i + 1) - Math.log(i));
|
|
50
|
+
const top = Math.max(...logs);
|
|
51
|
+
const sum = logs.reduce((s, l) => s + Math.exp(l - top), 0);
|
|
52
|
+
const logP = Math.log(2) + top + Math.log(sum) - n * Math.log(2);
|
|
53
|
+
return Math.min(1, Math.exp(logP));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Deterministic uniform generator (mulberry32).
|
|
58
|
+
*
|
|
59
|
+
* @param {number} seed
|
|
60
|
+
* @returns {() => number} values in [0, 1)
|
|
61
|
+
*/
|
|
62
|
+
export function seededRandom(seed) {
|
|
63
|
+
let a = seed >>> 0;
|
|
64
|
+
return () => {
|
|
65
|
+
a = (a + 0x6d2b79f5) >>> 0;
|
|
66
|
+
let t = a;
|
|
67
|
+
t = Math.imul(t ^ (t >>> 15), t | 1);
|
|
68
|
+
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
|
69
|
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const mean = (xs) => xs.reduce((s, x) => s + x, 0) / xs.length;
|
|
74
|
+
|
|
75
|
+
function percentile(sorted, q) {
|
|
76
|
+
const i = Math.min(sorted.length - 1, Math.max(0, Math.floor(q * sorted.length)));
|
|
77
|
+
return sorted[i];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Percentile bootstrap interval of the mean.
|
|
82
|
+
*
|
|
83
|
+
* @param {number[]} values
|
|
84
|
+
* @param {{iterations?: number, seed?: number, alpha?: number}} [opts]
|
|
85
|
+
* @returns {{mean: number|null, low: number|null, high: number|null}}
|
|
86
|
+
*/
|
|
87
|
+
export function bootstrapCI(values, { iterations = 2000, seed = 1, alpha = 0.05 } = {}) {
|
|
88
|
+
if (!values.length) return { mean: null, low: null, high: null };
|
|
89
|
+
const rand = seededRandom(seed);
|
|
90
|
+
const n = values.length;
|
|
91
|
+
const means = new Array(iterations);
|
|
92
|
+
for (let it = 0; it < iterations; it++) {
|
|
93
|
+
let s = 0;
|
|
94
|
+
for (let i = 0; i < n; i++) s += values[Math.floor(rand() * n)];
|
|
95
|
+
means[it] = s / n;
|
|
96
|
+
}
|
|
97
|
+
means.sort((x, y) => x - y);
|
|
98
|
+
return {
|
|
99
|
+
mean: mean(values),
|
|
100
|
+
low: percentile(means, alpha / 2),
|
|
101
|
+
high: percentile(means, 1 - alpha / 2),
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Bootstrap interval of mean(b - a) over paired observations.
|
|
107
|
+
*
|
|
108
|
+
* @param {number[]} a
|
|
109
|
+
* @param {number[]} b same length as a, same bugs in the same order
|
|
110
|
+
* @param {{iterations?: number, seed?: number, alpha?: number}} [opts]
|
|
111
|
+
*/
|
|
112
|
+
export function pairedBootstrapDiff(a, b, opts = {}) {
|
|
113
|
+
if (a.length !== b.length) throw new Error("paired samples differ in length");
|
|
114
|
+
return bootstrapCI(
|
|
115
|
+
a.map((x, i) => b[i] - x),
|
|
116
|
+
opts,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Per-bug ranking metrics.
|
|
122
|
+
*
|
|
123
|
+
* hit@k is 1 when any changed file is in the top k (Acc@k once averaged);
|
|
124
|
+
* recall@k is the share of changed files in the top k; rr is 1 / rank of the
|
|
125
|
+
* first changed file, 0 when none is ranked.
|
|
126
|
+
*
|
|
127
|
+
* @param {string[]} ranked candidate files, best first
|
|
128
|
+
* @param {string[]} truth files the fix changed
|
|
129
|
+
* @param {number[]} ks
|
|
130
|
+
*/
|
|
131
|
+
export function rankingMetrics(ranked, truth, ks) {
|
|
132
|
+
const want = new Set(truth);
|
|
133
|
+
const hit = {};
|
|
134
|
+
const recall = {};
|
|
135
|
+
let first = 0;
|
|
136
|
+
for (let i = 0; i < ranked.length; i++) {
|
|
137
|
+
if (want.has(ranked[i])) {
|
|
138
|
+
first = i + 1;
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (const k of ks) {
|
|
143
|
+
const top = ranked.slice(0, k);
|
|
144
|
+
const found = top.filter((f) => want.has(f)).length;
|
|
145
|
+
hit[k] = found > 0 ? 1 : 0;
|
|
146
|
+
recall[k] = want.size ? found / want.size : 0;
|
|
147
|
+
}
|
|
148
|
+
return { hit, recall, rr: first ? 1 / first : 0 };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Mean of per-bug metrics.
|
|
153
|
+
*
|
|
154
|
+
* @param {Array<ReturnType<typeof rankingMetrics>>} rows
|
|
155
|
+
* @param {number[]} ks
|
|
156
|
+
*/
|
|
157
|
+
export function aggregateMetrics(rows, ks) {
|
|
158
|
+
const acc = {};
|
|
159
|
+
const recall = {};
|
|
160
|
+
for (const k of ks) {
|
|
161
|
+
acc[k] = rows.length ? mean(rows.map((r) => r.hit[k])) : null;
|
|
162
|
+
recall[k] = rows.length ? mean(rows.map((r) => r.recall[k])) : null;
|
|
163
|
+
}
|
|
164
|
+
return { n: rows.length, acc, recall, mrr: rows.length ? mean(rows.map((r) => r.rr)) : null };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The go / no-go rule: the lift is large enough, it is significant, and no
|
|
169
|
+
* repository got worse.
|
|
170
|
+
*
|
|
171
|
+
* @param {{liftPoints: number, p: number, regressedRepos: string[], minLiftPoints: number, alpha: number}} r
|
|
172
|
+
* @returns {{go: boolean, reasons: string[]}}
|
|
173
|
+
*/
|
|
174
|
+
export function verdict({ liftPoints, p, regressedRepos, minLiftPoints, alpha }) {
|
|
175
|
+
const reasons = [];
|
|
176
|
+
if (!(liftPoints >= minLiftPoints)) {
|
|
177
|
+
reasons.push(`recall@10 lift ${liftPoints.toFixed(1)} points is below ${minLiftPoints}`);
|
|
178
|
+
}
|
|
179
|
+
if (!(p < alpha)) reasons.push(`McNemar p=${p.toFixed(4)} is not below ${alpha}`);
|
|
180
|
+
if (regressedRepos.length) reasons.push(`regressed: ${regressedRepos.join(", ")}`);
|
|
181
|
+
return { go: reasons.length === 0, reasons };
|
|
182
|
+
}
|
|
@@ -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
|
+
}
|