@mmerterden/multi-agent-pipeline 20.41.0 → 20.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +8 -6
  3. package/README.tr.md +8 -6
  4. package/docs/architecture.md +3 -3
  5. package/docs/ecosystem.md +50 -13
  6. package/docs/facts.json +9 -9
  7. package/docs/features.md +9 -4
  8. package/install/claude.mjs +34 -1
  9. package/install/templates/claude-hooks.json +12 -1
  10. package/manifest.json +117 -90
  11. package/package.json +3 -2
  12. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  13. package/pipeline/commands/multi-agent/clean-disk/SKILL.md +134 -0
  14. package/pipeline/commands/multi-agent/review-priority/SKILL.md +143 -0
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/commands/multi-agent/sync/SKILL.md +4 -4
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/credential-store.sh +11 -1
  20. package/pipeline/lib/hook-once.mjs +134 -0
  21. package/pipeline/lib/isotonic.mjs +73 -0
  22. package/pipeline/lib/low-disk.mjs +154 -0
  23. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  24. package/pipeline/lib/md2confluence-v3.py +8 -7
  25. package/pipeline/lib/model-dispatch.sh +26 -2
  26. package/pipeline/lib/normalize-text.mjs +135 -0
  27. package/pipeline/lib/outbound-gate.mjs +21 -3
  28. package/pipeline/lib/plan-todos.sh +17 -4
  29. package/pipeline/lib/redact.mjs +12 -3
  30. package/pipeline/lib/risky-settings.mjs +198 -0
  31. package/pipeline/lib/route-state.sh +1 -0
  32. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  33. package/pipeline/lib/session-usage.mjs +232 -0
  34. package/pipeline/lib/source-digest.mjs +211 -0
  35. package/pipeline/lib/tdd-evidence.mjs +250 -17
  36. package/pipeline/lib/untrusted-fence.mjs +132 -1
  37. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  38. package/pipeline/multi-agent-refs/cross-cli-contract.md +5 -5
  39. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  40. package/pipeline/multi-agent-refs/features/doctor.md +66 -4
  41. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  42. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  43. package/pipeline/multi-agent-refs/features/review-priority.md +123 -0
  44. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  45. package/pipeline/multi-agent-refs/features/usage-reporting.md +4 -2
  46. package/pipeline/multi-agent-refs/help/en.md +3 -1
  47. package/pipeline/multi-agent-refs/help/tr.md +3 -1
  48. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  49. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +1 -1
  50. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  51. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  52. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  53. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  54. package/pipeline/multi-agent-refs/review-priority/rules/example.md +137 -0
  55. package/pipeline/office/toolkit.json +1 -1
  56. package/pipeline/rules/outside-the-pipeline.md +1 -1
  57. package/pipeline/schemas/doctor-report.schema.json +47 -0
  58. package/pipeline/schemas/plan-todos.schema.json +29 -1
  59. package/pipeline/schemas/prefs.schema.json +81 -0
  60. package/pipeline/schemas/route-config.schema.json +51 -0
  61. package/pipeline/schemas/secret-patterns.json +17 -1
  62. package/pipeline/schemas/toolkit-path-params.json +15 -1
  63. package/pipeline/scripts/_cost-advise.mjs +357 -0
  64. package/pipeline/scripts/_cost-budget.mjs +78 -0
  65. package/pipeline/scripts/_cost.mjs +29 -0
  66. package/pipeline/scripts/_decode_text.py +107 -0
  67. package/pipeline/scripts/_guard-probe.mjs +406 -0
  68. package/pipeline/scripts/_guard_rules.py +206 -0
  69. package/pipeline/scripts/_memory-policy.mjs +1 -25
  70. package/pipeline/scripts/_retrieval.mjs +148 -2
  71. package/pipeline/scripts/_secret-scan.mjs +6 -1
  72. package/pipeline/scripts/_stack-routing.mjs +1 -0
  73. package/pipeline/scripts/_test-gaming.mjs +346 -0
  74. package/pipeline/scripts/agent-guard.py +8 -1
  75. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  76. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  77. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  78. package/pipeline/scripts/capture-resume.sh +9 -1
  79. package/pipeline/scripts/cost-analyze.mjs +66 -4
  80. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  81. package/pipeline/scripts/disk-cleaner.mjs +1432 -0
  82. package/pipeline/scripts/doctor.mjs +302 -47
  83. package/pipeline/scripts/evidence-gate.mjs +90 -0
  84. package/pipeline/scripts/gate-ledger.mjs +76 -21
  85. package/pipeline/scripts/gc-tmp.sh +5 -0
  86. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  87. package/pipeline/scripts/learnings-ledger.mjs +16 -12
  88. package/pipeline/scripts/note-agent-event.mjs +2 -0
  89. package/pipeline/scripts/note-mcp-failure.mjs +9 -2
  90. package/pipeline/scripts/note-skill-use.mjs +4 -1
  91. package/pipeline/scripts/pre-commit-check.sh +2 -2
  92. package/pipeline/scripts/pre-push-check.sh +8 -1
  93. package/pipeline/scripts/priority-review.mjs +912 -0
  94. package/pipeline/scripts/publish-staged.mjs +324 -0
  95. package/pipeline/scripts/route-learn.mjs +628 -0
  96. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  97. package/pipeline/scripts/scan-agent-config.sh +1 -1
  98. package/pipeline/scripts/statusline.mjs +309 -0
  99. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  100. package/pipeline/scripts/triage-memory.mjs +12 -4
  101. package/pipeline/scripts/uninstall.mjs +1 -0
  102. package/pipeline/skills/.skill-manifest.json +17 -5
  103. package/pipeline/skills/.skills-index.json +36 -3
  104. package/pipeline/skills/shared/README.md +9 -6
  105. package/pipeline/skills/shared/core/multi-agent-clean-disk/SKILL.md +34 -0
  106. package/pipeline/skills/shared/core/multi-agent-review-priority/SKILL.md +36 -0
  107. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +4 -4
  108. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  109. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +111 -0
  110. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  111. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1432 -0
  112. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  113. package/pipeline/skills/skill-copies.json +4 -0
  114. package/pipeline/skills/skills-index.md +5 -2
@@ -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,154 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * @file low-disk.mjs - one cheap free-space check, and the one line that
4
+ * names the clean-disk command when the disk is nearly full or a failure log
5
+ * says it ran out of space. The command is spelled the way this host types it.
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
+ import { hostCommand } from "./user-facing.mjs";
30
+
31
+ export const DEFAULT_LOW_GB = 10;
32
+ export const DEFAULT_LOW_PERCENT = 5;
33
+ const GB = 1e9;
34
+ const SCAN_MAX = 4 * 1024 * 1024;
35
+
36
+ /** Error text a full disk produces, across Node, the shell, git and Xcode. */
37
+ export const DISK_FULL =
38
+ /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;
39
+
40
+ /** The thresholds from prefs, falling back to the defaults. */
41
+ export function thresholds(env = process.env) {
42
+ const gb = Number(globalPref("diskCleaner.lowDiskGb", DEFAULT_LOW_GB, env));
43
+ const pct = Number(globalPref("diskCleaner.lowDiskPercent", DEFAULT_LOW_PERCENT, env));
44
+ return {
45
+ lowGb: Number.isFinite(gb) && gb >= 0 ? gb : DEFAULT_LOW_GB,
46
+ lowPercent: Number.isFinite(pct) && pct >= 0 ? pct : DEFAULT_LOW_PERCENT,
47
+ suggest: globalPref("diskCleaner.suggest", true, env) !== false,
48
+ };
49
+ }
50
+
51
+ /** Free and total bytes of the volume holding `path`, or nulls. */
52
+ export function measure(path) {
53
+ try {
54
+ const s = statfsSync(path);
55
+ return { freeBytes: s.bavail * s.bsize, totalBytes: s.blocks * s.bsize };
56
+ } catch {
57
+ return { freeBytes: null, totalBytes: null };
58
+ }
59
+ }
60
+
61
+ /** True when either threshold is crossed. Unknown sizes are never low. */
62
+ export function isLow(status, th) {
63
+ if (status.freeBytes == null || !status.totalBytes) return false;
64
+ const pct = (status.freeBytes / status.totalBytes) * 100;
65
+ return status.freeBytes < th.lowGb * GB || pct < th.lowPercent;
66
+ }
67
+
68
+ export function mentionsDiskFull(text) {
69
+ return DISK_FULL.test(String(text || ""));
70
+ }
71
+
72
+ /** The suggestion, one line, in the caller's output language. */
73
+ export function suggestion(status, { lang = "en", cause = "low" } = {}) {
74
+ const free =
75
+ status.freeBytes == null
76
+ ? "?"
77
+ : `${(status.freeBytes / GB).toFixed(1)} GB` +
78
+ (status.totalBytes
79
+ ? ` (${((status.freeBytes / status.totalBytes) * 100).toFixed(1)}%)`
80
+ : "");
81
+ const cmd = hostCommand("clean-disk", import.meta.dirname);
82
+ if (lang === "tr") {
83
+ const why = cause === "error" ? "Hata çıktısı diskin dolduğunu söylüyor" : "Disk dolmak üzere";
84
+ return `multi-agent: ${why}, boş alan ${free}. Neyin silinebileceğini görmek için ${cmd} çalıştır; onay vermeden hiçbir şey silinmez.`;
85
+ }
86
+ const why = cause === "error" ? "the failure output says the disk is full" : "disk nearly full";
87
+ return `multi-agent: ${why}, ${free} free. Run ${cmd} to see what can be freed; nothing is deleted until you confirm.`;
88
+ }
89
+
90
+ /**
91
+ * The line to print, or null. `scanText` is failure output to look for a
92
+ * disk-full error in; without it only the free space decides.
93
+ */
94
+ export function check({ path = homedir(), scanText = null, lang = "en", env = process.env } = {}) {
95
+ const th = thresholds(env);
96
+ const status = measure(path);
97
+ const low = isLow(status, th);
98
+ const errored = scanText != null && mentionsDiskFull(scanText);
99
+ const line =
100
+ th.suggest && (low || errored)
101
+ ? suggestion(status, { lang, cause: errored ? "error" : "low" })
102
+ : null;
103
+ return { ...status, ...th, low, errored, line };
104
+ }
105
+
106
+ function readScan(file) {
107
+ try {
108
+ const text = readFileSync(file, "utf8");
109
+ return text.length > SCAN_MAX ? text.slice(-SCAN_MAX) : text;
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ export function main(argv = process.argv.slice(2), env = process.env) {
116
+ const arg = (k) => {
117
+ const i = argv.indexOf(k);
118
+ if (i >= 0) return argv[i + 1];
119
+ const eq = argv.find((a) => a.startsWith(`${k}=`));
120
+ return eq ? eq.slice(k.length + 1) : undefined;
121
+ };
122
+ if (argv.includes("-h") || argv.includes("--help")) {
123
+ process.stdout.write(
124
+ "usage: low-disk.mjs [--path DIR] [--scan FILE] [--lang en|tr] [--json]\n",
125
+ );
126
+ return 0;
127
+ }
128
+ const scan = arg("--scan");
129
+ const r = check({
130
+ path: arg("--path") || env.HOME || homedir(),
131
+ scanText: scan ? readScan(scan) : null,
132
+ lang: arg("--lang") === "tr" ? "tr" : "en",
133
+ env,
134
+ });
135
+ if (argv.includes("--json")) process.stdout.write(JSON.stringify(r) + "\n");
136
+ else if (r.line) process.stdout.write(r.line + "\n");
137
+ return 0;
138
+ }
139
+
140
+ function invokedDirectly() {
141
+ try {
142
+ return import.meta.url === pathToFileURL(realpathSync(process.argv[1] ?? "")).href;
143
+ } catch {
144
+ return false;
145
+ }
146
+ }
147
+
148
+ if (invokedDirectly()) {
149
+ try {
150
+ process.exitCode = main();
151
+ } catch {
152
+ process.exitCode = 0;
153
+ }
154
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * mcp-schema-load.mjs - how much context an MCP server's tool list takes,
3
+ * per tool family.
4
+ *
5
+ * Every tool a server lists is sent with every turn: its name, description
6
+ * and input schema. The toolkit names its tools `<family>_<verb>` and
7
+ * MCP_TOOLKIT_CAPS narrows what it lists by family, so the useful number is
8
+ * the load per family: it says what each cap value would save.
9
+ *
10
+ * Tokens are an ESTIMATE, bytes / 4 of the JSON each entry is sent as. No
11
+ * tokenizer is bundled (ADR-0004) and the estimate is labelled as one
12
+ * wherever it is shown.
13
+ *
14
+ * @module pipeline/lib/mcp-schema-load
15
+ */
16
+
17
+ export const BYTES_PER_TOKEN = 4;
18
+
19
+ const tokensOf = (bytes) => Math.ceil(bytes / BYTES_PER_TOKEN);
20
+
21
+ /** The family a tool name belongs to: the part before the first underscore. */
22
+ export function familyOf(name) {
23
+ const s = String(name ?? "");
24
+ const i = s.indexOf("_");
25
+ return i > 0 ? s.slice(0, i) : s;
26
+ }
27
+
28
+ function summarize(families) {
29
+ families.sort((a, b) => b.bytes - a.bytes || (a.family < b.family ? -1 : 1));
30
+ return {
31
+ estimate: true,
32
+ bytesPerToken: BYTES_PER_TOKEN,
33
+ totalTools: families.reduce((a, f) => a + f.tools, 0),
34
+ totalBytes: families.reduce((a, f) => a + f.bytes, 0),
35
+ totalTokens: families.reduce((a, f) => a + f.tokens, 0),
36
+ families,
37
+ };
38
+ }
39
+
40
+ /**
41
+ * Load per family from a `tools/list` result.
42
+ *
43
+ * @param {object[]} tools the `result.tools` array as served
44
+ */
45
+ export function schemaLoadByFamily(tools) {
46
+ const by = new Map();
47
+ for (const t of Array.isArray(tools) ? tools : []) {
48
+ if (!t || typeof t.name !== "string") continue;
49
+ const family = familyOf(t.name);
50
+ const f = by.get(family) || { family, tools: 0, bytes: 0 };
51
+ f.tools += 1;
52
+ f.bytes += Buffer.byteLength(JSON.stringify(t));
53
+ by.set(family, f);
54
+ }
55
+ return summarize([...by.values()].map((f) => ({ ...f, tokens: tokensOf(f.bytes) })));
56
+ }
57
+
58
+ /**
59
+ * Load per family from a toolkit manifest that carries a `families` field,
60
+ * either a map (`{ios: {tools, bytes | tokens}}`) or a list
61
+ * (`[{family, tools, bytes | tokens}]`). Null when the field is absent or any
62
+ * entry lacks a tool count and a size.
63
+ *
64
+ * @param {object|null} manifest
65
+ */
66
+ export function loadFromManifest(manifest) {
67
+ const raw = manifest?.families;
68
+ if (!raw || typeof raw !== "object") return null;
69
+ const entries = Array.isArray(raw)
70
+ ? raw.map((e) => [e?.family ?? e?.name, e])
71
+ : Object.entries(raw);
72
+ const families = [];
73
+ for (const [family, e] of entries) {
74
+ const tools = Number(e?.tools);
75
+ const bytes = Number(e?.bytes);
76
+ const tokens = Number(e?.tokens ?? e?.estTokens);
77
+ if (typeof family !== "string" || !Number.isInteger(tools)) return null;
78
+ if (Number.isFinite(bytes)) families.push({ family, tools, bytes, tokens: tokensOf(bytes) });
79
+ else if (Number.isFinite(tokens))
80
+ families.push({ family, tools, bytes: tokens * BYTES_PER_TOKEN, tokens });
81
+ else return null;
82
+ }
83
+ return families.length ? summarize(families) : null;
84
+ }
85
+
86
+ /** "ios 31 tools ~9.8k tokens" for one family. */
87
+ export function familyLine(f) {
88
+ const k = f.tokens >= 1000 ? `${(f.tokens / 1000).toFixed(1)}k` : String(f.tokens);
89
+ return `${f.family}: ${f.tools} tools, ~${k} tokens (estimate)`;
90
+ }
@@ -270,11 +270,10 @@ class InlineContext:
270
270
  # Confluence renders an <ac:image> at its natural size, so one screenshot took two
271
271
  # screen heights on the page. Width is a display attribute only: the attachment
272
272
  # stays full resolution and a click still opens the original.
273
- # 720 is a desktop frame at half of a 2x export and a diagram at readable size;
274
- # a phone frame overrides itself down to 320 through the title syntax, which the
275
- # frame-gallery row writes because it is the only place that knows the frame width.
273
+ # 720 is a desktop frame at half of a 2x export and a diagram at readable size.
276
274
  # An image inside a table cell shares the row with text columns, so it renders
277
- # at TABLE_IMAGE_WIDTH unless its own title names a width.
275
+ # at TABLE_IMAGE_WIDTH; the frame gallery is a table, so its phone frames land
276
+ # there too. Any image can still name its own width through the title syntax.
278
277
  DEFAULT_IMAGE_WIDTH = 720
279
278
  TABLE_IMAGE_WIDTH = 240
280
279
 
@@ -1183,8 +1182,9 @@ def build_parser() -> argparse.ArgumentParser:
1183
1182
  "--image-width",
1184
1183
  type=int,
1185
1184
  default=DEFAULT_IMAGE_WIDTH,
1186
- help="Display width in px for embedded attachment images (0 = natural size). "
1187
- "Per-image override: ![alt](f.png \"width=320\").",
1185
+ help="Display width in px for embedded attachment images (0 = natural size; images in a table cell stay at %d). "
1186
+ % TABLE_IMAGE_WIDTH
1187
+ + "Per-image override: ![alt](f.png \"width=320\").",
1188
1188
  )
1189
1189
  create.add_argument("--dry-run", action="store_true")
1190
1190
  create.set_defaults(func=cmd_create)
@@ -1198,7 +1198,8 @@ def build_parser() -> argparse.ArgumentParser:
1198
1198
  "--image-width",
1199
1199
  type=int,
1200
1200
  default=DEFAULT_IMAGE_WIDTH,
1201
- help="Display width in px for embedded attachment images (0 = natural size).",
1201
+ help="Display width in px for embedded attachment images (0 = natural size; images in a table cell stay at %d)."
1202
+ % TABLE_IMAGE_WIDTH,
1202
1203
  )
1203
1204
  update.add_argument("--mermaid-fallback", action="store_true")
1204
1205
  update.add_argument("--dry-run", action="store_true")
@@ -7,7 +7,7 @@
7
7
  #
8
8
  # Usage:
9
9
  # model-dispatch.sh <call-site> [--persona P] [--phase N] [--task-kind K]
10
- # [--default RUNG] [--task-id ID]
10
+ # [--default RUNG] [--task-id ID] [--complexity N]
11
11
  #
12
12
  # <call-site> is one of the `scope` members: subagent | bulk-read | delegate |
13
13
  # research. stdout is a single rung NAME. Rung names are the contract; the model
@@ -34,13 +34,21 @@
34
34
  # Strategies: manual keeps the rule's order; task-fit tries the cheapest rung
35
35
  # first; cost-ceiling keeps the order until cost-budget-check.mjs reports the run
36
36
  # at its warn threshold of budgetCeilingUsd, then tries the cheapest first.
37
+ #
38
+ # Learned order: with modelRouting.learned.enabled (ships false), the order the
39
+ # strategy produced is handed to route-learn.mjs choose, which reorders it from
40
+ # the PROMOTED policy for this call site, task kind and complexity band. Only
41
+ # a permutation of the rule's own candidates is taken, so learning can change
42
+ # which allowed rung is tried first and never adds one; the fable switch and
43
+ # the provider checks below still apply to whatever order comes back. No
44
+ # promoted policy, too few outcomes, or any failure leaves the order as it was.
37
45
 
38
46
  set -uo pipefail
39
47
 
40
48
  CALL_SITE="${1:-}"
41
49
  shift || true
42
50
 
43
- PERSONA=""; PHASE=""; TASK_KIND=""; DEFAULT_RUNG=""; TASK_ID="${MULTI_AGENT_TASK_ID:-unknown}"
51
+ PERSONA=""; PHASE=""; TASK_KIND=""; DEFAULT_RUNG=""; COMPLEXITY=""; TASK_ID="${MULTI_AGENT_TASK_ID:-unknown}"
44
52
  while [ $# -gt 0 ]; do
45
53
  case "$1" in
46
54
  --persona) PERSONA="${2:-}"; shift 2 ;;
@@ -48,6 +56,7 @@ while [ $# -gt 0 ]; do
48
56
  --task-kind) TASK_KIND="${2:-}"; shift 2 ;;
49
57
  --default) DEFAULT_RUNG="${2:-}"; shift 2 ;;
50
58
  --task-id) TASK_ID="${2:-}"; shift 2 ;;
59
+ --complexity) COMPLEXITY="${2:-}"; shift 2 ;;
51
60
  *) shift ;;
52
61
  esac
53
62
  done
@@ -144,6 +153,21 @@ if [ "$CHEAPEST_FIRST" = "true" ] && [ -f "$COST_TABLE" ]; then
144
153
  | map(.value) | join(" ")' "$COST_TABLE" 2>/dev/null || printf '%s' "$CANDIDATES")
145
154
  fi
146
155
 
156
+ words() { tr -s ' ' <<< "$1" | sed 's/^ //; s/ $//'; }
157
+ sorted_words() { tr ' ' '\n' <<< "$1" | grep -v '^$' | sort | tr '\n' ' '; }
158
+
159
+ LEARNED_ON=$(jq -r '.global.modelRouting.learned.enabled // false' "$PREFS" 2>/dev/null)
160
+ if [ "$LEARNED_ON" = "true" ] && command -v node >/dev/null 2>&1 \
161
+ && [ -f "$HERE/../scripts/route-learn.mjs" ]; then
162
+ LEARNED=$(node "$HERE/../scripts/route-learn.mjs" choose --call-site "$CALL_SITE" \
163
+ --task-kind "$TASK_KIND" --complexity "$COMPLEXITY" --task-id "$TASK_ID" \
164
+ --candidates "$CANDIDATES" 2>/dev/null) || LEARNED=""
165
+ if [ -n "$LEARNED" ] && [ "$(sorted_words "$LEARNED")" = "$(sorted_words "$CANDIDATES")" ]; then
166
+ [ "$(words "$LEARNED")" != "$(words "$CANDIDATES")" ] && STRATEGY_NOTE="learned"
167
+ CANDIDATES="$LEARNED"
168
+ fi
169
+ fi
170
+
147
171
  # The fable rung answers only when the fable switch is on (FABLE_ON, read
148
172
  # above). Routing is a policy over what is available; it is not a second way to
149
173
  # turn a rung on, or `/multi-agent:model off` would stop meaning anything the
@@ -100,6 +100,141 @@ export function foldWithIndex(text) {
100
100
  return { folded, start, end };
101
101
  }
102
102
 
103
+ // ---------------------------------------------------------------------------
104
+ // Bounded decode: what a run of base64, hex or rot13 text says once decoded
105
+
106
+ /**
107
+ * The work decodedVariants does is capped: `maxDepth` decode steps on top of
108
+ * one another, the first `maxInputChars` of the text, `maxVariants` decoded
109
+ * copies and `maxDecodedChars` decoded characters in all. A decoded run is kept
110
+ * only when it is at least `minBytes` long and `minPrintable` of its bytes are
111
+ * printable ASCII, so random bytes (a hash, an image) are dropped.
112
+ */
113
+ export const DECODE_LIMITS = Object.freeze({
114
+ maxDepth: 2,
115
+ maxInputChars: 256 * 1024,
116
+ maxVariants: 32,
117
+ maxDecodedChars: 256 * 1024,
118
+ minBytes: 8,
119
+ minPrintable: 0.9,
120
+ });
121
+
122
+ const B64_RUN = /[A-Za-z0-9+/_-]{16,}={0,2}/g;
123
+ const HEX_RUN = /(?:[0-9a-fA-F]{2}){8,}/g;
124
+
125
+ const B64_VALUE = (() => {
126
+ const v = new Int16Array(128).fill(-1);
127
+ for (let i = 0; i < 26; i++) {
128
+ v[65 + i] = i;
129
+ v[97 + i] = 26 + i;
130
+ }
131
+ for (let i = 0; i < 10; i++) v[48 + i] = 52 + i;
132
+ v[43] = 62;
133
+ v[45] = 62;
134
+ v[47] = 63;
135
+ v[95] = 63;
136
+ return v;
137
+ })();
138
+
139
+ /** Standard or URL-safe base64, padding optional, as one byte per char. */
140
+ export function decodeBase64(run) {
141
+ const s = run.replace(/=+$/, "");
142
+ let out = "";
143
+ let acc = 0;
144
+ let bits = 0;
145
+ for (let i = 0; i < s.length; i++) {
146
+ const v = B64_VALUE[s.charCodeAt(i)];
147
+ if (v === undefined || v < 0) return null;
148
+ acc = ((acc << 6) | v) & 0xffffff;
149
+ bits += 6;
150
+ if (bits >= 8) {
151
+ bits -= 8;
152
+ out += String.fromCharCode((acc >> bits) & 0xff);
153
+ }
154
+ }
155
+ return out;
156
+ }
157
+
158
+ /** Pairs of hex digits as one byte per char. */
159
+ export function decodeHex(run) {
160
+ let out = "";
161
+ for (let i = 0; i + 1 < run.length; i += 2) {
162
+ out += String.fromCharCode(parseInt(run.slice(i, i + 2), 16));
163
+ }
164
+ return out;
165
+ }
166
+
167
+ /** Letters rotated by 13; everything else unchanged. */
168
+ export function rot13(text) {
169
+ let out = "";
170
+ for (let i = 0; i < text.length; i++) {
171
+ const c = text.charCodeAt(i);
172
+ if (c >= 65 && c <= 90) out += String.fromCharCode(((c - 65 + 13) % 26) + 65);
173
+ else if (c >= 97 && c <= 122) out += String.fromCharCode(((c - 97 + 13) % 26) + 97);
174
+ else out += text[i];
175
+ }
176
+ return out;
177
+ }
178
+
179
+ function printable(bytes, minBytes, minPrintable) {
180
+ if (bytes.length < minBytes) return false;
181
+ let ok = 0;
182
+ for (let i = 0; i < bytes.length; i++) {
183
+ const c = bytes.charCodeAt(i);
184
+ if ((c >= 0x20 && c <= 0x7e) || c === 9 || c === 10 || c === 13) ok++;
185
+ }
186
+ return ok / bytes.length >= minPrintable;
187
+ }
188
+
189
+ /**
190
+ * Decoded copies of the base64, hex and rot13 text inside `text`, for a
191
+ * matcher to run over next to the text itself. Deterministic: base64 runs in
192
+ * order of position, then hex runs, then the rot13 of the whole text (first
193
+ * step only); each later step decodes the copies of the step before. Every
194
+ * copy names how it was reached (`base64`, `hex`, `rot13`, `base64>hex`).
195
+ *
196
+ * @param {string} text
197
+ * @param {Partial<typeof DECODE_LIMITS>} [limits]
198
+ * @returns {{kind: string, text: string}[]}
199
+ */
200
+ export function decodedVariants(text, limits = {}) {
201
+ const L = { ...DECODE_LIMITS, ...limits };
202
+ const out = [];
203
+ const seen = new Set();
204
+ let budget = L.maxDecodedChars;
205
+ const keep = (kind, decoded, next) => {
206
+ if (out.length >= L.maxVariants || decoded.length > budget || seen.has(decoded)) return;
207
+ seen.add(decoded);
208
+ budget -= decoded.length;
209
+ out.push({ kind, text: decoded });
210
+ next.push({ kind, text: decoded });
211
+ };
212
+ let frontier = [{ kind: "", text: String(text ?? "").slice(0, L.maxInputChars) }];
213
+ for (let depth = 1; depth <= L.maxDepth && frontier.length; depth++) {
214
+ const next = [];
215
+ for (const item of frontier) {
216
+ const prefix = item.kind ? `${item.kind}>` : "";
217
+ for (const [kind, re, decode, ratio] of [
218
+ ["base64", B64_RUN, decodeBase64, 0.75],
219
+ ["hex", HEX_RUN, decodeHex, 0.5],
220
+ ]) {
221
+ re.lastIndex = 0;
222
+ for (const m of item.text.matchAll(re)) {
223
+ if (out.length >= L.maxVariants) break;
224
+ if (m[0].length * ratio > budget) continue;
225
+ const bytes = decode(m[0]);
226
+ if (bytes !== null && printable(bytes, L.minBytes, L.minPrintable)) {
227
+ keep(prefix + kind, bytes, next);
228
+ }
229
+ }
230
+ }
231
+ if (depth === 1 && /[A-Za-z]/.test(item.text)) keep("rot13", rot13(item.text), []);
232
+ }
233
+ frontier = next;
234
+ }
235
+ return out;
236
+ }
237
+
103
238
  if (invokedDirectly(import.meta.url)) {
104
239
  const nul = process.argv.includes("--nul");
105
240
  let input = "";