@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.
Files changed (143) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/README.tr.md +5 -2
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +51 -14
  7. package/docs/facts.json +7 -7
  8. package/docs/features.md +15 -4
  9. package/install/claude.mjs +45 -3
  10. package/install/templates/claude-hooks.json +23 -1
  11. package/manifest.json +146 -107
  12. package/package.json +3 -2
  13. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  14. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/contract/types/index.d.ts +53 -49
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/context-budget.mjs +5 -42
  20. package/pipeline/lib/credential-store.sh +11 -1
  21. package/pipeline/lib/hook-once.mjs +134 -0
  22. package/pipeline/lib/hook-registration.mjs +5 -0
  23. package/pipeline/lib/isotonic.mjs +73 -0
  24. package/pipeline/lib/low-disk.mjs +153 -0
  25. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  26. package/pipeline/lib/md2confluence-v3.py +19 -10
  27. package/pipeline/lib/model-dispatch.sh +26 -2
  28. package/pipeline/lib/normalize-text.mjs +135 -0
  29. package/pipeline/lib/outbound-gate.mjs +21 -3
  30. package/pipeline/lib/plan-todos.sh +17 -4
  31. package/pipeline/lib/redact.mjs +12 -3
  32. package/pipeline/lib/risky-settings.mjs +198 -0
  33. package/pipeline/lib/route-state.sh +1 -0
  34. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  35. package/pipeline/lib/session-usage.mjs +232 -0
  36. package/pipeline/lib/source-digest.mjs +211 -0
  37. package/pipeline/lib/tdd-evidence.mjs +250 -17
  38. package/pipeline/lib/tiered-budget.mjs +87 -0
  39. package/pipeline/lib/untrusted-fence.mjs +132 -1
  40. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  41. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  42. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  43. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  44. package/pipeline/multi-agent-refs/features/doctor.md +82 -4
  45. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  46. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  47. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  48. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  49. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  50. package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
  51. package/pipeline/multi-agent-refs/help/en.md +2 -1
  52. package/pipeline/multi-agent-refs/help/tr.md +2 -1
  53. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  54. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  55. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  56. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
  57. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  58. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  59. package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
  60. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  61. package/pipeline/office/index.html +13 -7
  62. package/pipeline/office/toolkit.json +1 -1
  63. package/pipeline/preferences-template.json +1 -0
  64. package/pipeline/rules/outside-the-pipeline.md +1 -1
  65. package/pipeline/schemas/doctor-report.schema.json +47 -0
  66. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  67. package/pipeline/schemas/office-archive.schema.json +225 -128
  68. package/pipeline/schemas/plan-todos.schema.json +29 -1
  69. package/pipeline/schemas/prefs.schema.json +146 -0
  70. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  71. package/pipeline/schemas/product-tree.schema.json +136 -0
  72. package/pipeline/schemas/route-config.schema.json +51 -0
  73. package/pipeline/schemas/secret-patterns.json +17 -1
  74. package/pipeline/schemas/toolkit-path-params.json +15 -1
  75. package/pipeline/scripts/_cost-advise.mjs +357 -0
  76. package/pipeline/scripts/_cost-budget.mjs +78 -0
  77. package/pipeline/scripts/_cost.mjs +29 -0
  78. package/pipeline/scripts/_decode_text.py +107 -0
  79. package/pipeline/scripts/_eval-stats.mjs +182 -0
  80. package/pipeline/scripts/_guard-probe.mjs +406 -0
  81. package/pipeline/scripts/_guard_rules.py +336 -1
  82. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  83. package/pipeline/scripts/_locate.mjs +539 -0
  84. package/pipeline/scripts/_memory-policy.mjs +208 -33
  85. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  86. package/pipeline/scripts/_product-tree.mjs +923 -0
  87. package/pipeline/scripts/_retrieval.mjs +161 -4
  88. package/pipeline/scripts/_secret-scan.mjs +6 -1
  89. package/pipeline/scripts/_stack-routing.mjs +2 -0
  90. package/pipeline/scripts/_test-gaming.mjs +346 -0
  91. package/pipeline/scripts/_user_guard_rules.py +744 -0
  92. package/pipeline/scripts/agent-guard.py +69 -6
  93. package/pipeline/scripts/agent-guard.sh +8 -1
  94. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  95. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  96. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  97. package/pipeline/scripts/capture-resume.sh +9 -1
  98. package/pipeline/scripts/cost-analyze.mjs +66 -4
  99. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  100. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/scripts/doctor.mjs +324 -43
  102. package/pipeline/scripts/evidence-gate.mjs +90 -0
  103. package/pipeline/scripts/gate-ledger.mjs +76 -21
  104. package/pipeline/scripts/gc-tmp.sh +5 -0
  105. package/pipeline/scripts/graph-query.mjs +257 -17
  106. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  107. package/pipeline/scripts/learnings-ledger.mjs +680 -55
  108. package/pipeline/scripts/note-agent-event.mjs +2 -0
  109. package/pipeline/scripts/note-mcp-failure.mjs +363 -0
  110. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  111. package/pipeline/scripts/note-skill-use.mjs +96 -23
  112. package/pipeline/scripts/office-archive.mjs +23 -10
  113. package/pipeline/scripts/office-memory.mjs +4 -1
  114. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  115. package/pipeline/scripts/pre-commit-check.sh +2 -2
  116. package/pipeline/scripts/pre-push-check.sh +8 -1
  117. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  118. package/pipeline/scripts/product-tree.mjs +544 -0
  119. package/pipeline/scripts/publish-staged.mjs +324 -0
  120. package/pipeline/scripts/route-learn.mjs +628 -0
  121. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  122. package/pipeline/scripts/scan-agent-config.sh +1 -1
  123. package/pipeline/scripts/statusline.mjs +309 -0
  124. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  125. package/pipeline/scripts/triage-memory.mjs +12 -4
  126. package/pipeline/scripts/uninstall.mjs +1 -0
  127. package/pipeline/skills/.skill-manifest.json +15 -7
  128. package/pipeline/skills/.skills-index.json +25 -3
  129. package/pipeline/skills/shared/README.md +6 -4
  130. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  131. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  132. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  133. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  134. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  135. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  136. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  137. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  138. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  139. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  140. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  141. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  142. package/pipeline/skills/skill-copies.json +9 -1
  143. package/pipeline/skills/skills-index.md +4 -2
@@ -0,0 +1,744 @@
1
+ """User-defined guard rules: prefs.global.guardRules, applied by agent-guard.py.
2
+
3
+ A rule names a tool, a regular expression and an action:
4
+
5
+ {"id": "no-prod-db", "tool": "Bash", "match": "psql\\s+.*prod",
6
+ "action": "block", "reason": "production database"}
7
+
8
+ tool Bash, Edit (also NotebookEdit, and MultiEdit on a host that has it
9
+ and runs the guard on it), Write, Read, or a glob over a toolkit
10
+ tool name (mcp__multi-agent-toolkit__web_*)
11
+ match searched (re.search) in the command for Bash, the target path for
12
+ the file tools (as given, made absolute, and real-pathed), and the
13
+ tool input as compact sorted JSON for a toolkit tool; a step of
14
+ agent_run_steps is judged as a call of its own tool
15
+ action warn: the call proceeds and a note names the rule
16
+ ask: the user confirms, as with the built-in confirmations
17
+ block: the call is refused
18
+
19
+ Rules only add restrictions. The built-in verdict is reached first and a rule
20
+ is applied over it: a built-in block or deny is final, a rule block outranks a
21
+ built-in ask, and nothing a rule says turns a refusal or an ask into an allow.
22
+ Unattended, ask is block, because nobody is there to answer.
23
+
24
+ The regex is bounded three ways. A pattern is at most MAX_PATTERN_CHARS long,
25
+ and one with a back-reference or one that does not compile is invalid. Every
26
+ other pattern runs under a wall-clock budget (MATCH_DEADLINE_SECONDS,
27
+ run_matches): Python's re has no timeout of its own, but it checks for
28
+ pending signals while it backtracks, so a timer signal ends a runaway match
29
+ in place, and a rule that ran out of time fails closed (below). The shape
30
+ check (pattern_shape) names the shapes whose matching time can grow
31
+ exponentially or with a high power of the input: a variable quantifier
32
+ inside a group repeated more than SMALL_REPEAT times whose repetitions can
33
+ split the same text more than one way, and three or more adjacent
34
+ open-ended quantifiers whose characters overlap. Such a pattern still runs;
35
+ doctor names it so its author can tighten it. A bounded repeat with a small
36
+ maximum ((\d{1,3}\.){3}) and a group whose quantified items cannot match
37
+ each other's characters ((\s+\S+)*) are not slow shapes. Rules run block first, then
38
+ ask, then warn, and each gets an even share of the budget left, so a slow
39
+ rule cannot use up the time of the rules after it. That costs nothing per
40
+ call, where a child interpreter per call would add a process start to every
41
+ guarded tool call. Matched text is capped at MAX_SUBJECT_CHARS: past it, the
42
+ head and the tail are matched.
43
+
44
+ An invalid rule is treated as absent and doctor's guard-rules check reports
45
+ it. The exception is an invalid block rule whose tool is readable: unattended,
46
+ it refuses every call of that tool, because the rule exists to stop something
47
+ and nobody is watching to notice that it is not running. A rule that ran out
48
+ of time, never got its turn, or found nothing in the head and tail of input
49
+ past the cap gave no answer: unattended an ask or block rule then refuses;
50
+ attended an ask or block rule asks, so input the agent controls cannot switch
51
+ a refusing rule off, and a warn rule leaves a note. A preferences file that
52
+ does not parse, or a guardRules that is not a list, applies no rule. Unattended
53
+ it refuses every call a rule could govern when the file names guardRules (or
54
+ cannot be read at all), since the rules it holds cannot be read; attended each
55
+ such call carries a note saying the guard rules could not be read.
56
+
57
+ Messages name the rule id and its reason, never the matched text or the
58
+ pattern.
59
+
60
+ python3 _user_guard_rules.py --report JSON summary for doctor
61
+ """
62
+ import fnmatch
63
+ import json
64
+ import os
65
+ import re
66
+ import signal
67
+ import sys
68
+ import time
69
+
70
+ try:
71
+ from re import _constants as _sre_constants
72
+ from re import _parser as _sre_parser
73
+ except ImportError: # Python before 3.11
74
+ import sre_constants as _sre_constants
75
+ import sre_parse as _sre_parser
76
+
77
+ MAX_RULES = 64
78
+ MAX_PATTERN_CHARS = 512
79
+ MAX_REASON_CHARS = 300
80
+ MAX_SUBJECT_CHARS = 65536
81
+ MATCH_DEADLINE_SECONDS = 1.0
82
+ SMALL_REPEAT = 16
83
+ MAX_PREFS_SCAN = 4 * 1024 * 1024
84
+ MAX_STEP_DEPTH = 2
85
+ MAX_LISTED = 3
86
+
87
+ ACTIONS = ("warn", "ask", "block")
88
+ SEVERITY = {"warn": 1, "ask": 2, "block": 3}
89
+ KEYS = {"id", "tool", "match", "action", "reason"}
90
+ ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")
91
+ TOOLKIT_PREFIX = "mcp__multi-agent-toolkit__"
92
+ TOOL_RE = re.compile(r"^(?:Bash|Edit|Write|Read|mcp__multi-agent-toolkit__[A-Za-z0-9_*?]{1,80})$")
93
+ CONTROL = re.compile(r"[\x00-\x1f\x7f]")
94
+ NAMED_TOOLS = {
95
+ "Bash": {"Bash"},
96
+ "Edit": {"Edit", "MultiEdit", "NotebookEdit"},
97
+ "Write": {"Write"},
98
+ "Read": {"Read"},
99
+ }
100
+ PATH_TOOLS = {"Edit", "MultiEdit", "NotebookEdit", "Write", "Read"}
101
+
102
+ REPEATS = {
103
+ getattr(_sre_constants, name)
104
+ for name in ("MAX_REPEAT", "MIN_REPEAT", "POSSESSIVE_REPEAT")
105
+ if hasattr(_sre_constants, name)
106
+ }
107
+ BACKREFS = {
108
+ getattr(_sre_constants, name) for name in ("GROUPREF", "GROUPREF_EXISTS") if hasattr(_sre_constants, name)
109
+ }
110
+
111
+ ALL_BYTES = frozenset(range(256))
112
+ CATEGORY_RX = {
113
+ "CATEGORY_DIGIT": r"\d",
114
+ "CATEGORY_NOT_DIGIT": r"\D",
115
+ "CATEGORY_SPACE": r"\s",
116
+ "CATEGORY_NOT_SPACE": r"\S",
117
+ "CATEGORY_WORD": r"\w",
118
+ "CATEGORY_NOT_WORD": r"\W",
119
+ }
120
+
121
+ ERROR = "error"
122
+ NOT_RUN = "not-run"
123
+ MIN_SLICE_SECONDS = 0.005
124
+
125
+
126
+ # --- validation -----------------------------------------------------------------
127
+
128
+
129
+ def _subpatterns(value):
130
+ if isinstance(value, _sre_parser.SubPattern):
131
+ yield value
132
+ elif isinstance(value, (list, tuple)):
133
+ for item in value:
134
+ yield from _subpatterns(item)
135
+
136
+
137
+ def _charset(body):
138
+ """The bytes (0-255, both cases) one repetition of body can start with,
139
+ or None when body is more than one single-character item."""
140
+ items = list(body)
141
+ if len(items) != 1:
142
+ return None
143
+ op, av = items[0]
144
+ if op == _sre_constants.IN:
145
+ out, negate = set(), False
146
+ for iop, iav in av:
147
+ if iop == _sre_constants.NEGATE:
148
+ negate = True
149
+ continue
150
+ part = _single(iop, iav)
151
+ if part is None:
152
+ return None
153
+ out |= part
154
+ chars = ALL_BYTES - out if negate else out
155
+ else:
156
+ chars = _single(op, av)
157
+ if chars is None:
158
+ return None
159
+ swapped = (chr(c).swapcase() for c in chars)
160
+ return chars | {ord(s) for s in swapped if len(s) == 1 and ord(s) < 256}
161
+
162
+
163
+ def _single(op, av):
164
+ if op == _sre_constants.LITERAL:
165
+ return {av} if av < 256 else set()
166
+ if op == _sre_constants.NOT_LITERAL:
167
+ return ALL_BYTES - {av}
168
+ if op == _sre_constants.ANY:
169
+ return set(ALL_BYTES)
170
+ if op == _sre_constants.RANGE:
171
+ return set(range(av[0], min(av[1], 255) + 1))
172
+ if op == _sre_constants.CATEGORY and str(av) in CATEGORY_RX:
173
+ rx = re.compile(CATEGORY_RX[str(av)])
174
+ return {c for c in ALL_BYTES if rx.match(chr(c))}
175
+ return None
176
+
177
+
178
+ def _adjacent_problem(items):
179
+ """Three or more unbounded quantifiers in a row whose neighbours can match
180
+ the same character: the match time grows with a power of the input length."""
181
+ run, previous = 0, None
182
+ for op, av in items:
183
+ if op in REPEATS and av[1] == _sre_constants.MAXREPEAT:
184
+ chars = _charset(av[2])
185
+ if chars is None:
186
+ chars = ALL_BYTES
187
+ run = run + 1 if previous is not None and chars & previous else 1
188
+ previous = chars
189
+ if run >= 3:
190
+ return "the pattern has three or more adjacent open-ended quantifiers that overlap"
191
+ else:
192
+ run, previous = 0, None
193
+ return None
194
+
195
+
196
+ def _items(body):
197
+ """A group's items, with any wrapping group taken off."""
198
+ items = list(body)
199
+ while len(items) == 1 and items[0][0] == _sre_constants.SUBPATTERN:
200
+ items = list(items[0][1][-1])
201
+ return items
202
+
203
+
204
+ def _unambiguous(body):
205
+ """True when consecutive repetitions of body can split a text only one
206
+ way: every item matches one character (or a repeat of one), and the
207
+ characters a variable item matches cannot start whatever may follow it,
208
+ up to and including the next item that cannot be empty, wrapping around
209
+ into the body's own first items for the next repetition."""
210
+ items = _items(body)
211
+ if not items:
212
+ return False
213
+ sets, low, variable = [], [], []
214
+ for op, av in items:
215
+ if op in REPEATS:
216
+ chars = _charset(av[2])
217
+ low.append(av[0])
218
+ variable.append(av[0] != av[1])
219
+ else:
220
+ chars = _charset([(op, av)])
221
+ low.append(1)
222
+ variable.append(False)
223
+ if chars is None:
224
+ return False
225
+ sets.append(chars)
226
+ n = len(items)
227
+ for i in range(n):
228
+ if not variable[i]:
229
+ continue
230
+ follow = set()
231
+ for step in range(1, n + 1):
232
+ k = (i + step) % n
233
+ follow |= sets[k]
234
+ if low[k] >= 1:
235
+ break
236
+ if follow & sets[i]:
237
+ return False
238
+ return True
239
+
240
+
241
+ def _has_variable(sub):
242
+ for op, av in sub:
243
+ if op in REPEATS and av[0] != av[1]:
244
+ return True
245
+ children = [av[2]] if op in REPEATS else list(_subpatterns(av))
246
+ if any(_has_variable(child) for child in children):
247
+ return True
248
+ return False
249
+
250
+
251
+ def _has_backref(sub):
252
+ for op, av in sub:
253
+ if op in BACKREFS:
254
+ return True
255
+ children = [av[2]] if op in REPEATS else list(_subpatterns(av))
256
+ if any(_has_backref(child) for child in children):
257
+ return True
258
+ return False
259
+
260
+
261
+ def _shape_problem(sub):
262
+ problem = _adjacent_problem(list(sub))
263
+ if problem:
264
+ return problem
265
+ for op, av in sub:
266
+ if op in REPEATS:
267
+ low, high, body = av
268
+ large = high == _sre_constants.MAXREPEAT or high > SMALL_REPEAT
269
+ if large and _has_variable(body) and not _unambiguous(body):
270
+ return "the pattern has a variable quantifier inside a repeated group"
271
+ problem = _shape_problem(body)
272
+ else:
273
+ problem = None
274
+ for child in _subpatterns(av):
275
+ problem = problem or _shape_problem(child)
276
+ if problem:
277
+ return problem
278
+ return None
279
+
280
+
281
+ def pattern_problem(pattern):
282
+ """None for a pattern the guard may run, else a reason that never quotes it."""
283
+ if not isinstance(pattern, str) or not pattern:
284
+ return "match is not a non-empty string"
285
+ if len(pattern) > MAX_PATTERN_CHARS:
286
+ return f"the pattern is longer than {MAX_PATTERN_CHARS} characters"
287
+ try:
288
+ tree = _sre_parser.parse(pattern)
289
+ re.compile(pattern)
290
+ except (re.error, RecursionError, OverflowError, ValueError):
291
+ return "the pattern does not compile"
292
+ try:
293
+ return "the pattern refers back to a group" if _has_backref(tree) else None
294
+ except RecursionError:
295
+ return "the pattern nests too deeply"
296
+
297
+
298
+ def pattern_shape(pattern):
299
+ """A slow shape a valid pattern has, or None. It runs under the matching
300
+ budget either way; this names it for doctor."""
301
+ try:
302
+ return _shape_problem(_sre_parser.parse(pattern))
303
+ except (re.error, RecursionError, OverflowError, ValueError, TypeError):
304
+ return None
305
+
306
+
307
+ def _label(raw, index, seen):
308
+ rid = raw.get("id") if isinstance(raw, dict) else None
309
+ if not isinstance(rid, str) or not ID_RE.match(rid):
310
+ return f"#{index + 1}"
311
+ return f"{rid} (#{index + 1})" if seen.get(rid, index) != index else rid
312
+
313
+
314
+ def _rule_problem(raw, seen, index):
315
+ if not isinstance(raw, dict):
316
+ return "the rule is not an object"
317
+ if set(raw) - KEYS:
318
+ return "the rule carries a key the schema does not define"
319
+ rid = raw.get("id")
320
+ if not isinstance(rid, str) or not ID_RE.match(rid):
321
+ return "id is missing or not 1-64 letters, digits, dot, dash or underscore"
322
+ if seen.get(rid, index) != index:
323
+ return f"rules {seen[rid] + 1} and {index + 1} share the id {rid}; only rule {seen[rid] + 1} is kept"
324
+ if not isinstance(raw.get("tool"), str) or not TOOL_RE.match(raw["tool"]):
325
+ return "tool is not Bash, Edit, Write, Read or a mcp__multi-agent-toolkit__ glob"
326
+ if raw.get("action") not in ACTIONS:
327
+ return "action is not warn, ask or block"
328
+ reason = raw.get("reason")
329
+ if not isinstance(reason, str) or not reason.strip() or len(reason) > MAX_REASON_CHARS or CONTROL.search(reason):
330
+ return f"reason is not one line of 1-{MAX_REASON_CHARS} characters"
331
+ return pattern_problem(raw.get("match"))
332
+
333
+
334
+ def parse_rules(raw):
335
+ """One entry per rule: label, tool, action, reason, match, problem.
336
+ tool and action are kept when readable even if the rule is invalid."""
337
+ if raw is None:
338
+ return []
339
+ if not isinstance(raw, list):
340
+ return [{"label": "guardRules", "tool": None, "action": None, "reason": None, "match": None,
341
+ "problem": "guardRules is not a list"}]
342
+ out, seen = [], {}
343
+ for index, item in enumerate(raw):
344
+ d = item if isinstance(item, dict) else {}
345
+ if isinstance(d.get("id"), str):
346
+ seen.setdefault(d["id"], index)
347
+ problem = _rule_problem(item, seen, index)
348
+ if not problem and index >= MAX_RULES:
349
+ problem = f"the list is longer than {MAX_RULES} rules"
350
+ tool = d.get("tool") if isinstance(d.get("tool"), str) and TOOL_RE.match(d["tool"]) else None
351
+ action = d.get("action") if d.get("action") in ACTIONS else None
352
+ out.append({
353
+ "label": _label(d, index, seen),
354
+ "tool": tool,
355
+ "action": action,
356
+ "reason": d.get("reason") if not problem else None,
357
+ "match": d.get("match") if not problem else None,
358
+ "problem": problem,
359
+ "shape": pattern_shape(d.get("match")) if not problem else None,
360
+ })
361
+ return out
362
+
363
+
364
+ def _prefs_candidates(env):
365
+ home = env.get("HOME") or os.path.expanduser("~")
366
+ return [
367
+ p
368
+ for p in (
369
+ env.get("MULTI_AGENT_PREFS"),
370
+ os.path.join(home, ".claude", "multi-agent-preferences.json"),
371
+ os.path.join(home, ".config", "multi-agent-pipeline", "multi-agent-preferences.json"),
372
+ )
373
+ if p
374
+ ]
375
+
376
+
377
+ def _names_rules(path):
378
+ """Whether an unparsable preferences file mentions guardRules; True when
379
+ it cannot be read at all, since then nobody can tell."""
380
+ try:
381
+ with open(path, "rb") as fh:
382
+ return b'"guardRules"' in fh.read(MAX_PREFS_SCAN)
383
+ except OSError:
384
+ return True
385
+
386
+
387
+ def load(env=None):
388
+ """(entries, source, error, holds) from the first preferences file that
389
+ exists, in the order the other guard preferences are read. A file that
390
+ does not parse, or a guardRules that is not a list, yields no rules and an
391
+ error; holds says whether the file names guardRules (or could not be read
392
+ to tell), which is when evaluate refuses unattended."""
393
+ env = os.environ if env is None else env
394
+ for path in _prefs_candidates(env):
395
+ if not os.path.isfile(path):
396
+ continue
397
+ try:
398
+ with open(path, encoding="utf-8") as fh:
399
+ doc = json.load(fh)
400
+ raw = (doc.get("global") or {}).get("guardRules")
401
+ except (OSError, ValueError, AttributeError):
402
+ return [], path, "the preferences file does not parse", _names_rules(path)
403
+ if raw is not None and not isinstance(raw, list):
404
+ return [], path, "guardRules is not a list", True
405
+ return parse_rules(raw), path, None, False
406
+ return [], None, None, False
407
+
408
+
409
+ # --- what a rule is matched against ----------------------------------------------
410
+
411
+
412
+ def tool_matches(rule_tool, name):
413
+ if rule_tool in NAMED_TOOLS:
414
+ return name in NAMED_TOOLS[rule_tool]
415
+ return fnmatch.fnmatchcase(name, rule_tool)
416
+
417
+
418
+ def _path_subjects(path, cwd):
419
+ out = [path]
420
+ absolute = os.path.normpath(os.path.join(cwd, os.path.expanduser(path)))
421
+ out.append(absolute)
422
+ try:
423
+ out.append(os.path.realpath(absolute))
424
+ except (OSError, ValueError):
425
+ pass
426
+ return list(dict.fromkeys(out))
427
+
428
+
429
+ def calls(tool, ti, cwd, depth=0):
430
+ """(tool name, [texts]) for the call and, for agent_run_steps, each step."""
431
+ if not isinstance(tool, str) or not isinstance(ti, dict):
432
+ return []
433
+ if tool == "Bash":
434
+ cmd = ti.get("command")
435
+ return [("Bash", [cmd])] if isinstance(cmd, str) and cmd else []
436
+ if tool in PATH_TOOLS:
437
+ path = ti.get("file_path") or ti.get("notebook_path")
438
+ return [(tool, _path_subjects(path, cwd))] if isinstance(path, str) and path else []
439
+ if not tool.startswith(TOOLKIT_PREFIX):
440
+ return []
441
+ try:
442
+ text = json.dumps(ti, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
443
+ except (TypeError, ValueError):
444
+ text = str(ti)
445
+ out = [(tool, [text])]
446
+ steps = ti.get("steps")
447
+ if tool == TOOLKIT_PREFIX + "agent_run_steps" and depth < MAX_STEP_DEPTH and isinstance(steps, list):
448
+ for step in steps:
449
+ if not isinstance(step, dict) or not isinstance(step.get("tool"), str):
450
+ continue
451
+ sub = step["tool"] if step["tool"].startswith(TOOLKIT_PREFIX) else TOOLKIT_PREFIX + step["tool"]
452
+ args = step.get("args") if isinstance(step.get("args"), dict) else {}
453
+ out.extend(calls(sub, args, cwd, depth + 1))
454
+ return out
455
+
456
+
457
+ def cap(text):
458
+ """(text matched, whether the original was longer than the cap)."""
459
+ if len(text) <= MAX_SUBJECT_CHARS:
460
+ return text, False
461
+ half = MAX_SUBJECT_CHARS // 2
462
+ return text[:half] + "\n" + text[-half:], True
463
+
464
+
465
+ # --- matching under a deadline ---------------------------------------------------
466
+
467
+
468
+ def match_deadline(env=None):
469
+ """MATCH_DEADLINE_SECONDS, or a lower MA_GUARD_RULES_DEADLINE_SECONDS."""
470
+ env = os.environ if env is None else env
471
+ try:
472
+ v = float(env.get("MA_GUARD_RULES_DEADLINE_SECONDS", ""))
473
+ except ValueError:
474
+ return MATCH_DEADLINE_SECONDS
475
+ return v if 0 < v < MATCH_DEADLINE_SECONDS else MATCH_DEADLINE_SECONDS
476
+
477
+
478
+ class _Expired(Exception):
479
+ pass
480
+
481
+
482
+ def _expire(_signum, _frame):
483
+ raise _Expired()
484
+
485
+
486
+ def _search(pattern, texts):
487
+ try:
488
+ rx = re.compile(pattern)
489
+ except re.error:
490
+ return None
491
+ return any(rx.search(text) for text in texts)
492
+
493
+
494
+ def run_matches(jobs, deadline, slices=None):
495
+ """For each (pattern, texts): True on a hit, False on none, None when its
496
+ slice ran out first, NOT_RUN when the budget was spent before its turn
497
+ (or the timer could not be armed). slices, when a list, receives the
498
+ seconds each job was given (None for a job that never ran).
499
+
500
+ deadline is the total budget, in wall-clock time on ITIMER_REAL. Each job
501
+ gets an even share of what is left, so a job that finishes early leaves its
502
+ time to the ones after it and a runaway one cannot take the others' time.
503
+ The regex engine checks for pending signals while it backtracks, so the
504
+ handler's exception ends a runaway match in place. agent-guard.py keeps its
505
+ own deadline on the same timer, so that timer is saved, the budget ends no
506
+ later than it, and the guard's is re-armed with what is left (at once when
507
+ it is already due), so its fail-closed verdict still fires on time."""
508
+ results = [NOT_RUN] * len(jobs)
509
+ given = [None] * len(jobs)
510
+ if slices is not None:
511
+ slices[:] = given
512
+ if not jobs:
513
+ return results
514
+ started = time.monotonic()
515
+ try:
516
+ outer_left, outer_interval = signal.getitimer(signal.ITIMER_REAL)
517
+ previous = signal.signal(signal.SIGALRM, _expire)
518
+ except (ValueError, AttributeError, OSError):
519
+ return results
520
+ stop_at = started + (min(deadline, outer_left) if outer_left else deadline)
521
+ try:
522
+ for i, (pattern, texts) in enumerate(jobs):
523
+ share = (stop_at - time.monotonic()) / (len(jobs) - i)
524
+ if share < MIN_SLICE_SECONDS:
525
+ break
526
+ given[i] = share
527
+ try:
528
+ try:
529
+ signal.setitimer(signal.ITIMER_REAL, share)
530
+ results[i] = _search(pattern, texts)
531
+ finally:
532
+ signal.setitimer(signal.ITIMER_REAL, 0)
533
+ except _Expired:
534
+ results[i] = None
535
+ except (ValueError, OSError):
536
+ pass
537
+ finally:
538
+ if slices is not None:
539
+ slices[:] = given
540
+ try:
541
+ signal.setitimer(signal.ITIMER_REAL, 0)
542
+ except (ValueError, OSError):
543
+ pass
544
+ signal.signal(signal.SIGALRM, previous)
545
+ if outer_left:
546
+ left = outer_left - (time.monotonic() - started)
547
+ signal.setitimer(signal.ITIMER_REAL, max(left, 0.001), outer_interval)
548
+ return results
549
+
550
+
551
+ # --- the decision ----------------------------------------------------------------
552
+
553
+
554
+ def _subjects(texts, fold):
555
+ out = []
556
+ for text in texts:
557
+ variants = [text]
558
+ if fold is not None:
559
+ try:
560
+ folded = fold(text)
561
+ except Exception:
562
+ folded = text
563
+ if folded != text:
564
+ variants.append(folded)
565
+ out.extend(cap(v) for v in variants)
566
+ return out
567
+
568
+
569
+ def ordered(entries):
570
+ """Block rules first, then ask, then warn, each kept in list order, so the
571
+ rules that refuse are matched before a slow warn rule can use the budget."""
572
+ return sorted(entries, key=lambda e: -SEVERITY.get(e["action"], 0))
573
+
574
+
575
+ def governed(tool):
576
+ """Whether a guard rule could apply to this tool at all."""
577
+ return isinstance(tool, str) and (tool == "Bash" or tool in PATH_TOOLS or tool.startswith(TOOLKIT_PREFIX))
578
+
579
+
580
+ def _unmatched(e, what, strict, guarded):
581
+ """The hit for a rule that did not give an answer: refused unattended,
582
+ asked attended for a block or ask rule (agent-controlled input must not
583
+ be able to switch a refusing rule off), a note for a warn rule."""
584
+ if strict and guarded:
585
+ return ("block", f"guard rule {e['label']} {what}, so the call is refused unattended")
586
+ if guarded:
587
+ return ("ask", f"guard rule {e['label']} {what}, so the call needs your confirmation")
588
+ if strict:
589
+ return None
590
+ return ("warn", f"guard rule {e['label']} {what} and was not applied")
591
+
592
+
593
+ def evaluate(data, strict, fold=None, env=None, entries=None, error=None, holds=True):
594
+ """{"action", "message"} for the strictest rule that applies, or None."""
595
+ tool = data.get("tool_name")
596
+ if entries is None:
597
+ entries, _, error, holds = load(env)
598
+ if error:
599
+ if not governed(tool):
600
+ return None
601
+ if strict:
602
+ if not holds:
603
+ return None
604
+ return {"action": "block", "message": f"the guard rules cannot be read ({error}), so every call "
605
+ "they could govern is refused unattended"}
606
+ return {"action": "warn", "message": f"the guard rules could not be read ({error}); none of them ran"}
607
+ if not entries:
608
+ return None
609
+ cwd = data.get("cwd") if isinstance(data.get("cwd"), str) and data.get("cwd") else os.getcwd()
610
+ targets = calls(tool, data.get("tool_input") or {}, cwd)
611
+ if not targets:
612
+ return None
613
+ seconds = match_deadline(env)
614
+ hits, jobs = [], []
615
+ for e in ordered(entries):
616
+ texts = [t for name, ts in targets if e["tool"] and tool_matches(e["tool"], name) for t in ts]
617
+ if not texts:
618
+ continue
619
+ if e["problem"]:
620
+ if strict and e["action"] == "block":
621
+ hits.append(("block", f"guard rule {e['label']} is invalid ({e['problem']}); "
622
+ "an invalid block rule refuses its tool unattended"))
623
+ continue
624
+ jobs.append((e, _subjects(texts, fold)))
625
+ slices = []
626
+ results = run_matches([(e["match"], [s for s, _ in subj]) for e, subj in jobs], seconds, slices)
627
+ for (e, subj), hit, given in zip(jobs, results, slices):
628
+ guarded = e["action"] in ("ask", "block")
629
+ if hit is True:
630
+ hits.append((e["action"], f"guard rule {e['label']}: {e['reason']}"))
631
+ continue
632
+ if hit is NOT_RUN:
633
+ what = f"was not checked: the {seconds:g}s matching budget ran out before its turn"
634
+ elif hit is None:
635
+ what = f"did not finish matching within {given:.2g}s"
636
+ elif any(over for _, over in subj):
637
+ what = (f"matched only the first and last {MAX_SUBJECT_CHARS // 2} characters of input "
638
+ f"longer than {MAX_SUBJECT_CHARS} characters")
639
+ else:
640
+ continue
641
+ found = _unmatched(e, what, strict, guarded)
642
+ if found:
643
+ hits.append(found)
644
+ if not hits:
645
+ return None
646
+ top = max(SEVERITY[a] for a, _ in hits)
647
+ action = next(a for a in ACTIONS if SEVERITY[a] == top)
648
+ messages = [m for a, m in hits if a == action]
649
+ message = "; ".join(messages[:MAX_LISTED])
650
+ if len(messages) > MAX_LISTED:
651
+ message += f"; and {len(messages) - MAX_LISTED} more"
652
+ return {"action": action, "message": message}
653
+
654
+
655
+ def note(message):
656
+ """Hook JSON that lets the call proceed and shows the note to both sides."""
657
+ text = "agent-guard: " + message
658
+ return json.dumps({
659
+ "systemMessage": text,
660
+ "hookSpecificOutput": {"hookEventName": "PreToolUse", "additionalContext": text},
661
+ })
662
+
663
+
664
+ def before_ask(verdict, data, strict, fold=None, env=None):
665
+ """First hook-in, before agent-guard turns an ask into a prompt.
666
+
667
+ Returns (verdict, decision). Attended, a rule ask on an otherwise allowed
668
+ call becomes the guard's own ask, so one confirmation covers it. Never
669
+ raises: an error is carried to after_policy as ERROR."""
670
+ try:
671
+ decision = evaluate(data, strict, fold, env)
672
+ except Exception:
673
+ return verdict, ERROR
674
+ if decision and decision["action"] == "ask" and not strict and verdict == "OK":
675
+ return "ASK\t" + decision["message"], decision
676
+ return verdict, decision
677
+
678
+
679
+ def after_policy(verdict, decision, strict):
680
+ """Second hook-in, after the built-in rules and the unattended policy.
681
+ A built-in block or deny is returned unchanged."""
682
+ if not decision or verdict.startswith(("BLOCK", "DENY")):
683
+ return verdict
684
+ if decision == ERROR:
685
+ return "BLOCK_UNATTENDED\tthe guard rules could not be evaluated" if strict else verdict
686
+ action, message = decision["action"], decision["message"]
687
+ if action == "block" or (action == "ask" and strict):
688
+ if strict:
689
+ suffix = " (ask is a block unattended: nobody is there to answer)" if action == "ask" else ""
690
+ return "BLOCK_UNATTENDED\t" + message + suffix
691
+ return "DENY\t" + message
692
+ if action == "warn" and verdict == "OK":
693
+ return "NOTE\t" + note(message)
694
+ if verdict.startswith("ASK\t"):
695
+ return _with_reason(verdict, message)
696
+ return verdict
697
+
698
+
699
+ def _with_reason(verdict, message):
700
+ """The guard's ask with a rule's message added to the reason the user
701
+ reads, once."""
702
+ try:
703
+ out = json.loads(verdict.split("\t", 1)[1])
704
+ spec = out["hookSpecificOutput"]
705
+ reason = spec.get("permissionDecisionReason") or "agent-guard"
706
+ except (ValueError, KeyError, TypeError, AttributeError):
707
+ return verdict
708
+ if message in reason:
709
+ return verdict
710
+ spec["permissionDecisionReason"] = f"{reason}; {message}"
711
+ return "ASK\t" + json.dumps(out)
712
+
713
+
714
+ # --- doctor ----------------------------------------------------------------------
715
+
716
+
717
+ def report(env=None):
718
+ entries, source, error, holds = load(env)
719
+ return {
720
+ "source": source,
721
+ "error": error,
722
+ "holdsRules": holds,
723
+ "rules": len(entries),
724
+ "valid": sum(1 for e in entries if not e["problem"]),
725
+ "invalid": [
726
+ {"label": e["label"], "tool": e["tool"], "action": e["action"], "problem": e["problem"]}
727
+ for e in entries
728
+ if e["problem"]
729
+ ],
730
+ "tools": sorted({e["tool"] for e in entries if e["tool"]}),
731
+ "slow": [
732
+ {"label": e["label"], "tool": e["tool"], "action": e["action"], "shape": e["shape"]}
733
+ for e in entries
734
+ if not e["problem"] and e.get("shape")
735
+ ],
736
+ }
737
+
738
+
739
+ if __name__ == "__main__":
740
+ if len(sys.argv) > 1 and sys.argv[1] == "--report":
741
+ print(json.dumps(report()))
742
+ else:
743
+ sys.stderr.write("usage: _user_guard_rules.py --report\n")
744
+ sys.exit(2)