@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,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 = "";
@@ -50,7 +50,7 @@
50
50
 
51
51
  import { readFileSync } from "node:fs";
52
52
  import { invokedDirectly } from "./invoked-directly.mjs";
53
- import { TABLE_LOADED, normalizeForMatch } from "./normalize-text.mjs";
53
+ import { TABLE_LOADED, decodedVariants, normalizeForMatch } from "./normalize-text.mjs";
54
54
  import { SECRET_PATTERNS } from "./secret-patterns.generated.mjs";
55
55
 
56
56
  /**
@@ -78,7 +78,7 @@ export const RULES = [
78
78
  {
79
79
  name: "email-address",
80
80
  certain: false,
81
- re: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
81
+ re: /\b[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,63}\b/g,
82
82
  },
83
83
  // An absolute path under /Users or /home names the operator.
84
84
  { name: "home-directory-path", certain: false, re: /\/(?:Users|home)\/[A-Za-z0-9_.-]+\//g },
@@ -120,8 +120,15 @@ export const SURFACES = [
120
120
  const NEEDS_FOLD = /[^\t -~]/;
121
121
 
122
122
  /**
123
+ * The certain rules also run over the bounded decode of each line
124
+ * (normalize-text.mjs decodedVariants): a token wrapped in base64, hex or
125
+ * rot13 is a token all the same, and the receiving end can undo the wrapping.
126
+ * Such a finding carries `encoding`, the decode path that revealed it. The
127
+ * uncertain rules do not: an email address inside a decoded blob is not worth
128
+ * a report.
129
+ *
123
130
  * @param {string} text
124
- * @returns {{rule: string, certain: boolean, line: number}[]}
131
+ * @returns {{rule: string, certain: boolean, line: number, encoding?: string}[]}
125
132
  */
126
133
  export function scan(text) {
127
134
  // Without the fold table a disguised credential would pass as clean text,
@@ -135,6 +142,7 @@ export function scan(text) {
135
142
  // A credential written with an invisible character or a look-alike letter
136
143
  // still matches: the certain rules also run on the folded line.
137
144
  const folded = NEEDS_FOLD.test(lines[i]) ? normalizeForMatch(lines[i]) : lines[i];
145
+ let decoded = null;
138
146
  for (const rule of RULES) {
139
147
  // `lastIndex` survives between calls on a /g regex and would make every
140
148
  // second line skip its start. Reset per line.
@@ -146,6 +154,16 @@ export function scan(text) {
146
154
  }
147
155
  if (hit) {
148
156
  findings.push({ rule: rule.name, certain: rule.certain, line: i + 1 });
157
+ continue;
158
+ }
159
+ if (!rule.certain) continue;
160
+ decoded ??= decodedVariants(folded);
161
+ const via = decoded.find((v) => {
162
+ rule.re.lastIndex = 0;
163
+ return rule.re.test(v.text);
164
+ });
165
+ if (via) {
166
+ findings.push({ rule: rule.name, certain: true, line: i + 1, encoding: via.kind });
149
167
  }
150
168
  }
151
169
  }
@@ -22,8 +22,12 @@
22
22
  # prefs.global.tddEvidence.mode (off | warn | enforce, default warn)
23
23
  # tdd-red <task-id> <todo-id> <results> [--tests a,b] [--already-passing <reason>]
24
24
  # Record the RED run (a named test fails) from JUnit XML / xcresult / log
25
- # (under enforce, --tests needs results that name failing tests)
26
- # tdd-green <task-id> <todo-id> <results> Record the GREEN run (no failures, RED's tests among them)
25
+ # (under enforce, --tests needs results that name failing tests);
26
+ # keeps the work tree's new and changed test files (red.testFiles)
27
+ # tdd-green <task-id> <todo-id> <results> [--test-edit-reason <why>]
28
+ # Record the GREEN run (no failures, RED's tests among them);
29
+ # refuses when a test file RED kept was changed, unless the reason is given
30
+ # tdd-restore <task-id> <todo-id> Write the RED bytes of the kept test files back
27
31
  # fail <task-id> <todo-id> <reason> Mark failed
28
32
  # skip <task-id> <todo-id> <reason> Mark skipped (counts as satisfied for dependents)
29
33
  # next <task-id> Print the next ready todo (deps-respecting, ranked by what it unblocks); empty if none, blocked todos named on stderr
@@ -275,10 +279,10 @@ do_tdd_run() {
275
279
  local extra=()
276
280
  while [ $# -gt 0 ]; do
277
281
  case "$1" in
278
- --tests|--already-passing)
282
+ --tests|--already-passing|--test-edit-reason)
279
283
  [ $# -ge 2 ] || { echo "tdd-$kind: $1 needs a value" >&2; exit 64; }
280
284
  extra+=("$1" "$2"); shift 2 ;;
281
- *) echo "tdd-$kind: unsupported flag '$1' (only --tests and --already-passing)" >&2; exit 64 ;;
285
+ *) echo "tdd-$kind: unsupported flag '$1' (only --tests, --already-passing and --test-edit-reason)" >&2; exit 64 ;;
282
286
  esac
283
287
  done
284
288
  local state_path; state_path=$(resolve_state "$task_id")
@@ -289,6 +293,14 @@ do_tdd_run() {
289
293
  write_tdd "$state_path" "$todo_id" "$record"
290
294
  }
291
295
 
296
+ do_tdd_restore() {
297
+ local task_id="${1:-}"; local todo_id="${2:-}"
298
+ [ -z "$task_id" ] || [ -z "$todo_id" ] && { echo "usage: tdd-restore <task-id> <todo-id>" >&2; exit 64; }
299
+ local state_path; state_path=$(resolve_state "$task_id")
300
+ require_todo "$state_path" "$todo_id"
301
+ node "$TDD_EVIDENCE" restore --state "$state_path" --todo "$todo_id" || exit 2
302
+ }
303
+
292
304
  do_complete() {
293
305
  local task_id="${1:-}"; local todo_id="${2:-}"; local notes="" no_tests=""
294
306
  [ -z "$task_id" ] || [ -z "$todo_id" ] && { echo "usage: complete <task-id> <todo-id> [notes] [--no-tests <reason>]" >&2; exit 64; }
@@ -470,6 +482,7 @@ case "$CMD" in
470
482
  complete) do_complete "$@" ;;
471
483
  tdd-red) do_tdd_run red "$@" ;;
472
484
  tdd-green) do_tdd_run green "$@" ;;
485
+ tdd-restore) do_tdd_restore "$@" ;;
473
486
  fail) do_fail "$@" ;;
474
487
  skip) do_skip "$@" ;;
475
488
  next) do_next "$@" ;;
@@ -26,6 +26,11 @@ import { foldWithIndex, normalizeForMatch } from "./normalize-text.mjs";
26
26
 
27
27
  const CERTAIN = RULES.filter((r) => r.certain);
28
28
 
29
+ // Printable ASCII, tab and line breaks fold to themselves, so text made only
30
+ // of them skips the fold and its per-character index.
31
+ const NEEDS_FOLD = /[^\t\n\r -~]/;
32
+ const folds = (text) => NEEDS_FOLD.test(text);
33
+
29
34
  const globalCopy = (re) =>
30
35
  new RegExp(re.source, re.flags.includes("g") ? re.flags : `${re.flags}g`);
31
36
  const marker = (name) =>
@@ -60,7 +65,9 @@ function findSpans(text) {
60
65
  if (m[0]) spans.push([m.index, m.index + m[0].length, rule.name]);
61
66
  }
62
67
  }
63
- const { folded, start, end } = foldWithIndex(text);
68
+ const { folded, start, end } = folds(text)
69
+ ? foldWithIndex(text)
70
+ : { folded: text, start: [], end: [] };
64
71
  if (folded !== text) {
65
72
  for (const rule of CERTAIN) {
66
73
  for (const m of folded.matchAll(globalCopy(rule.re))) {
@@ -84,8 +91,10 @@ function findSpans(text) {
84
91
  }
85
92
 
86
93
  function stillMatches(text) {
87
- const folded = normalizeForMatch(text);
88
- return CERTAIN.find((r) => globalCopy(r.re).test(text) || globalCopy(r.re).test(folded));
94
+ const folded = folds(text) ? normalizeForMatch(text) : text;
95
+ return CERTAIN.find(
96
+ (r) => globalCopy(r.re).test(text) || (folded !== text && globalCopy(r.re).test(folded)),
97
+ );
89
98
  }
90
99
 
91
100
  /** @param {string} text */
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * risky-settings.mjs - what in a Claude Code settings.json lets things run
4
+ * that nobody approved.
5
+ *
6
+ * The installer runs this on ~/.claude/settings.json before it merges its own
7
+ * hooks into it (install/claude.mjs configureSettings). It reports and never
8
+ * edits: removing a person's setting is their decision, which
9
+ * /multi-agent:setup asks about from the report the installer leaves at
10
+ * ~/.claude/multi-agent-risky-settings.json. A clean scan removes that report.
11
+ *
12
+ * HIGH bypass-with-broad-allow permission prompts off (bypassPermissions)
13
+ * together with a blanket Bash allow or every
14
+ * project MCP server enabled: any command
15
+ * and any server runs without a question
16
+ * hook-remote-exec a hook command that runs fetched or
17
+ * decoded code (curl or wget piped into a
18
+ * shell, /dev/tcp, base64 -d into a shell,
19
+ * nc -e)
20
+ * literal-secret a credential shape in env, in a hook
21
+ * command or in an MCP server entry
22
+ * MEDIUM bypass-mode bypassPermissions, or the dangerous-mode
23
+ * prompt skipped
24
+ * blanket-bash-allow Bash, Bash(*), Bash(:*) in the allow list
25
+ * all-project-mcp enableAllProjectMcpServers
26
+ * mcp-floating / mcp-mutable / mcp-insecure-transport
27
+ * an MCP launch whose code can change
28
+ * between two starts, or a plain-http
29
+ * server (lib/mcp-config-audit.mjs)
30
+ *
31
+ * A finding names the rule and where it is, never the value.
32
+ *
33
+ * CLI: risky-settings.mjs [--settings <path>] [--json]
34
+ * exit 0 no HIGH finding, 1 a HIGH finding, 2 the file is not JSON.
35
+ *
36
+ * @module pipeline/lib/risky-settings
37
+ */
38
+
39
+ import { readFileSync } from "node:fs";
40
+ import { homedir } from "node:os";
41
+ import { join } from "node:path";
42
+
43
+ import { parseArgs } from "./args.mjs";
44
+ import { invokedDirectly } from "./invoked-directly.mjs";
45
+ import { auditMcpConfig } from "./mcp-config-audit.mjs";
46
+ import { scan } from "./outbound-gate.mjs";
47
+ import { SECRET_PATTERNS } from "./secret-patterns.generated.mjs";
48
+
49
+ export const RISKY_REPORT = "multi-agent-risky-settings.json";
50
+
51
+ const BLANKET_BASH = new Set(["Bash", "Bash(*)", "Bash(:*)", "Bash(*:*)"]);
52
+ const REMOTE_EXEC =
53
+ /\b(?:curl|wget)\b[^|\n]{0,500}\|\s*(?:sudo\s+)?(?:ba|z|da|k)?sh\b|\/dev\/(?:tcp|udp)\/|\bbase64\s+(?:-d|--decode)\b[^|\n]{0,200}\|\s*(?:ba|z|da|k)?sh\b|\bnc\b[^|\n]{0,100}\s-e\s/;
54
+ const SECRET_MCP_KINDS = new Set([
55
+ "env-secret",
56
+ "header-secret",
57
+ "arg-secret",
58
+ "url-credentials",
59
+ "url-secret-param",
60
+ ]);
61
+
62
+ const finding = (level, rule, where, message) => ({ level, rule, where, message });
63
+
64
+ function hookCommands(settings) {
65
+ const out = [];
66
+ for (const [event, groups] of Object.entries(settings?.hooks ?? {})) {
67
+ if (!Array.isArray(groups)) continue;
68
+ groups.forEach((g, i) => {
69
+ for (const h of Array.isArray(g?.hooks) ? g.hooks : []) {
70
+ if (typeof h?.command === "string")
71
+ out.push({ where: `hooks.${event}[${i}]`, command: h.command });
72
+ }
73
+ });
74
+ }
75
+ return out;
76
+ }
77
+
78
+ const hasSecret = (text) => scan(String(text)).some((f) => f.certain);
79
+
80
+ /**
81
+ * Findings for one parsed settings document.
82
+ *
83
+ * @param {object} settings
84
+ * @returns {{level: "HIGH"|"MEDIUM", rule: string, where: string, message: string}[]}
85
+ */
86
+ export function scanRiskySettings(settings) {
87
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) return [];
88
+ const out = [];
89
+ const perms =
90
+ settings.permissions && typeof settings.permissions === "object" ? settings.permissions : {};
91
+ const bypass = perms.defaultMode === "bypassPermissions";
92
+ const allow = Array.isArray(perms.allow) ? perms.allow : [];
93
+ const blanket = allow.filter((a) => BLANKET_BASH.has(String(a).trim()));
94
+ const allMcp = settings.enableAllProjectMcpServers === true;
95
+
96
+ if (bypass && (blanket.length || allMcp)) {
97
+ out.push(
98
+ finding(
99
+ "HIGH",
100
+ "bypass-with-broad-allow",
101
+ "permissions.defaultMode",
102
+ `permission prompts are off and ${blanket.length ? "every Bash command is allowed" : "every project MCP server is enabled"}, so anything runs without a question`,
103
+ ),
104
+ );
105
+ }
106
+ if (bypass || settings.skipDangerousModePermissionPrompt === true) {
107
+ out.push(
108
+ finding(
109
+ "MEDIUM",
110
+ "bypass-mode",
111
+ bypass ? "permissions.defaultMode" : "skipDangerousModePermissionPrompt",
112
+ "permission prompts are switched off",
113
+ ),
114
+ );
115
+ }
116
+ if (blanket.length) {
117
+ out.push(
118
+ finding("MEDIUM", "blanket-bash-allow", "permissions.allow", "every Bash command is allowed"),
119
+ );
120
+ }
121
+ if (allMcp) {
122
+ out.push(
123
+ finding(
124
+ "MEDIUM",
125
+ "all-project-mcp",
126
+ "enableAllProjectMcpServers",
127
+ "every MCP server a project's .mcp.json names starts without approval",
128
+ ),
129
+ );
130
+ }
131
+ for (const { where, command } of hookCommands(settings)) {
132
+ if (REMOTE_EXEC.test(command)) {
133
+ out.push(finding("HIGH", "hook-remote-exec", where, "a hook runs fetched or decoded code"));
134
+ }
135
+ if (hasSecret(command)) {
136
+ out.push(finding("HIGH", "literal-secret", where, "a hook command carries a credential"));
137
+ }
138
+ }
139
+ for (const [key, value] of Object.entries(settings.env ?? {})) {
140
+ if (typeof value === "string" && hasSecret(`${key}=${value}`)) {
141
+ out.push(finding("HIGH", "literal-secret", `env.${key}`, "an env value is a credential"));
142
+ }
143
+ }
144
+ if (settings.mcpServers && typeof settings.mcpServers === "object") {
145
+ const audit = auditMcpConfig(
146
+ { mcpServers: settings.mcpServers },
147
+ { secretPatterns: SECRET_PATTERNS },
148
+ );
149
+ for (const s of audit.servers ?? []) {
150
+ const where = `mcpServers.${s.name}`;
151
+ if (s.verdict === "floating" || s.verdict === "mutable") {
152
+ out.push(finding("MEDIUM", `mcp-${s.verdict}`, where, s.reason));
153
+ }
154
+ for (const i of s.issues ?? []) {
155
+ if (SECRET_MCP_KINDS.has(i.kind)) {
156
+ out.push(finding("HIGH", "literal-secret", where, i.detail));
157
+ } else if (i.kind === "insecure-transport") {
158
+ out.push(finding("MEDIUM", "mcp-insecure-transport", where, i.detail));
159
+ }
160
+ }
161
+ }
162
+ }
163
+ return out;
164
+ }
165
+
166
+ /** The report the installer leaves for setup. */
167
+ export function riskyReport(findings, settingsPath) {
168
+ return {
169
+ settings: settingsPath,
170
+ at: new Date().toISOString(),
171
+ high: findings.filter((f) => f.level === "HIGH").length,
172
+ medium: findings.filter((f) => f.level === "MEDIUM").length,
173
+ findings,
174
+ };
175
+ }
176
+
177
+ if (invokedDirectly(import.meta.url)) {
178
+ const { flags } = parseArgs(process.argv.slice(2), { booleans: ["json"] });
179
+ const path =
180
+ typeof flags.settings === "string"
181
+ ? flags.settings
182
+ : join(homedir(), ".claude", "settings.json");
183
+ let settings;
184
+ try {
185
+ settings = JSON.parse(readFileSync(path, "utf8"));
186
+ } catch (err) {
187
+ process.stderr.write(`risky-settings: cannot read ${path}: ${err.message}\n`);
188
+ process.exit(2);
189
+ }
190
+ const report = riskyReport(scanRiskySettings(settings), path);
191
+ if (flags.json) process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
192
+ else {
193
+ for (const f of report.findings) {
194
+ process.stdout.write(`[${f.level}] ${f.rule} (${f.where}): ${f.message}\n`);
195
+ }
196
+ }
197
+ process.exit(report.high ? 1 : 0);
198
+ }