deepmodebot 0.10.0 → 0.11.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 (75) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.omp-plugin/marketplace.json +2 -2
  4. package/README.md +15 -6
  5. package/bin/deepmodebot.mjs +104 -10
  6. package/native/dmb-gate/Cargo.toml +1 -1
  7. package/native/dmb-gate/src/agents.rs +58 -25
  8. package/native/dmb-gate/src/ci.rs +530 -14
  9. package/native/dmb-gate/src/main.rs +215 -7
  10. package/native/dmb-gate/src/reward.rs +1895 -242
  11. package/native/dmb-gate/src/sim.rs +969 -0
  12. package/native/dmb-gate/src/slop.rs +1061 -295
  13. package/package.json +1 -1
  14. package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
  15. package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +1 -1
  16. package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
  17. package/plugins/deepmodebot/.codex-plugin/plugin.json +2 -2
  18. package/plugins/deepmodebot/agents/comment-sicko.md +29 -0
  19. package/plugins/deepmodebot/agents/researcher.md +29 -0
  20. package/plugins/deepmodebot/agents/reviewer.md +29 -0
  21. package/plugins/deepmodebot/agents/scout.md +28 -0
  22. package/plugins/deepmodebot/agents/security-reviewer.md +27 -0
  23. package/plugins/deepmodebot/commands/deep.md +3 -2
  24. package/plugins/deepmodebot/commands/tournament.md +1 -1
  25. package/plugins/deepmodebot/hooks/hooks.json +12 -2
  26. package/plugins/deepmodebot/hooks.json +1 -1
  27. package/plugins/deepmodebot/scripts/antigravity-guard.mjs +740 -37
  28. package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
  29. package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +19 -11
  30. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +51 -20
  31. package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +54 -49
  32. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +4 -0
  33. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +658 -21
  34. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/holdout_guard_cases.json +272 -0
  35. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +774 -23
  36. package/plugins/deepmodebot/skills/deepmodebot/assets/f2p-gate/f2p_gate.py +547 -0
  37. package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +5 -11
  38. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +4 -4
  39. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +53 -6
  40. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +48 -2
  41. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +262 -6
  42. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +529 -122
  43. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +747 -46
  44. package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +404 -5
  45. package/plugins/deepmodebot/skills/deepmodebot/assets/mutation/mutation_gate.py +798 -0
  46. package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +2050 -200
  47. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +44 -1
  48. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +278 -252
  49. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rules_watch.py +436 -0
  50. package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +594 -18
  51. package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +41 -5
  52. package/plugins/deepmodebot/skills/deepmodebot/assets/sim/sim.py +856 -0
  53. package/plugins/deepmodebot/skills/deepmodebot/assets/worker-gate/worker_gate.py +237 -0
  54. package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +3 -2
  55. package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +6 -2
  56. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +1 -1
  57. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +1 -0
  58. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +1 -1
  59. package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +6 -6
  60. package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +36 -16
  61. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +9 -8
  62. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +1 -0
  63. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +6 -2
  64. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +31 -9
  65. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +1 -1
  66. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +4 -4
  67. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sim.md +41 -0
  68. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +12 -0
  69. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +24 -13
  70. package/plugins/deepmodebot/skills/deepmodebot/worker.md +28 -16
  71. package/plugins/deepmodebot/agents/comment-sicko/agent.md +0 -35
  72. package/plugins/deepmodebot/agents/researcher/agent.md +0 -33
  73. package/plugins/deepmodebot/agents/reviewer/agent.md +0 -35
  74. package/plugins/deepmodebot/agents/scout/agent.md +0 -33
  75. package/plugins/deepmodebot/agents/security-reviewer/agent.md +0 -31
@@ -6,11 +6,16 @@
6
6
  // injectSteps (deduplicated across tool-loop invocations and subsequent turns). PreToolUse blocks
7
7
  // file writes outside the project root once active (or unconditionally when invoked with CLI
8
8
  // argument "enforce"). Rule approval (skills/deepmodebot/assets/rules/rule_ledger.py) applies in
9
- // every conversation: in a repo whose owner turned it on, file writes to agent rule files or the
10
- // ledger and shell commands that write them are denied, and the owner-only
11
- // `rules init|approve|reject|rotate` commands are denied everywhere. Other shell commands,
12
- // workflows (run_workflow), and MCP tools are not covered here. Always exits 0 because
13
- // Antigravity treats non-zero hook exits as execution errors and fails open.
9
+ // every conversation: in a repo whose owner turned it on, and for the user-level agent rules once
10
+ // the owner ran `deepmodebot rules init --user`, file writes to agent rule files or the ledger and
11
+ // shell commands that write them are denied (and the owner is notified), and the owner-only
12
+ // `rules init|approve|reject` commands are denied everywhere. The first PreInvocation of a
13
+ // conversation also injects a notice of agent rule changes the owner has not approved
14
+ // (rules/rules_watch.py). In active conversations and for registered workers, every tool call that reaches the
15
+ // hidden holdout store (~/.deepmodebot-holdout in any spelling) or mines git answers (cat-file --batch-all-objects,
16
+ // fsck, reflog recovery, raw .git/objects reads, sweeps of / ~ /tmp for tests) is denied. Workflows (run_workflow)
17
+ // and MCP tools are not otherwise covered here. Always exits 0 because Antigravity treats non-zero hook exits as
18
+ // execution errors and fails open.
14
19
 
15
20
  import { execFileSync } from "node:child_process";
16
21
  import * as fs from "node:fs";
@@ -28,6 +33,11 @@ const WORKSPACE_MAP_SCRIPT = path.resolve(
28
33
  const caseless = process.platform === "win32" || process.platform === "darwin";
29
34
  const RULES_DIR = path.resolve(SCRIPT_DIR, "../skills/deepmodebot/assets/rules");
30
35
  const RULE_LEDGER = path.join(RULES_DIR, "rule_ledger.py");
36
+ const RULES_WATCH = path.join(RULES_DIR, "rules_watch.py");
37
+ const WORKER_GATE = path.resolve(RULES_DIR, "../worker-gate/worker_gate.py");
38
+ const WORKER_BRIEF = path.resolve(SCRIPT_DIR, "../skills/deepmodebot/worker.md").split(path.sep).join("/");
39
+ const OVERHEAD_AGENTS = { scout: true, researcher: true, reviewer: true, "security-reviewer": true, "comment-sicko": true };
40
+ const NESTED_REASON = "deepmodebot anti-stacking guard: nested subagent spawning is blocked (max_subagents=0); execute inline or include ALLOW_NESTED_SUBAGENTS when explicitly authorized.";
31
41
  const LEDGER_REL = path.join(".deepmodebot", "rules", "ledger.json");
32
42
  const PYTHONS =
33
43
  process.platform === "win32"
@@ -43,8 +53,44 @@ const WRITE_TOOLS = new Set([
43
53
  "multi_replace_file_content",
44
54
  ]);
45
55
  const SHELL_TOOLS = new Set(["run_command", "execute_command", "bash"]);
46
- const REWARD_HACK_CMD_RE =
47
- /(?:^|[ ;&|(])--(?:gate-)?min-(?:iou|ssim|psnr|clip|clip-score|dice|f1|score|fidelity|similarity|coverage|accuracy|protrusion)(?:\s+|=)['"]?(?:-\d+(?:\.\d+)?|0+(?:\.0+)?|\d+(?:\.\d+)?e-[6-9]\d*)['"]?(?=$|[ ;&|)])|(?:^|[ ;&|(])--(?:skip-reference|skip-fidelity|skip-gates?|bypass-gate)(?=$|[ ;&|)])|(?:^|[ ;&|(])(?:--require-spark-receipt(?:\s+|=)['"]?false|--gate-mode(?:\s+|=)['"]?off)['"]?(?=$|[ ;&|)])|\bgit\b[^\n;&|]*\bcommit\b[^\n;&|]*\s(?:-n|--no-verify)(?=$|[ ;&|)])|\bsqlite3\b[^\n;&|]*reward-guard\.db\b|\b(?:rm|del|unlink|Remove-Item)\b[^\n;&|]*(?:contract-lock\.json|reward-guard\.db)\b|\breward_guard\.py\b[^\n;&|]*\brecord-judge\b/i;
56
+ const METRIC_FLOORS = {
57
+ iou: 0.5, ssim: 0.5, dice: 0.5, f1: 0.5, auc: 0.5,
58
+ accuracy: 0.5, acc: 0.5, precision: 0.5, recall: 0.5,
59
+ fidelity: 0.5, similarity: 0.5, coverage: 0.5, "pass-rate": 0.5, "win-rate": 0.5,
60
+ clip: 0.15, "clip-score": 0.15, ap: 0.15, map: 0.15, bleu: 0.15, rouge: 0.15,
61
+ psnr: 10.0, protrusion: 0.02, score: 0.05, confidence: 0.05, symmetry: 0.05,
62
+ "cov-fail-under": 50.0,
63
+ };
64
+ const MIN_FLAG_VAL_RE =
65
+ /(?:^|[\s;&|(])(['"]?--(?:(?:gate-)?mi(?:n(?:-([a-z0-9_-]*))?)?|(cov-fail-under))['"]?(?:\s+|=)['"]?\s*([-+]?(?:inf(?:inity)?|nan|(?:\d[\d_]*\.?[\d_]*|\.[\d_]+)(?:e[-+]?[\d_]+)?))\s*['"]?)(?=$|[\s;&|)])/gi;
66
+ const REWARD_HACK_CMD_RE = new RegExp(
67
+ [
68
+ String.raw`(?:^|[\s;&|(])['"]?--(?:skip-reference|skip-fidelity|skip-gates?|skip-verify|skip-validation|bypass-gate|pass-if-no-tests|passWithNoTests|no-cov|(?:update-snapshots|snapshot-update|overwrite-snapshots|updateSnapshot)(?:=[^\s;&|)'"]+)?)['"]?(?=$|[\s;&|)])`,
69
+ String.raw`(?:^|[\s;&|(])['"]?(?:--require-spark-receipt(?:\s+|=)['"]?false|--gate-mode(?:\s+|=)['"]?off|--measured-gates(?:\s+|=)['"]?off|--check-360(?:\s+|=)['"]?(?:false|0))['"]?(?=$|[\s;&|)])`,
70
+ String.raw`(?:^|[\s;&|(])(?:(?:jest|vitest|playwright\s+test)\b[^\n;&|]*\s['"]?(?:-u|--update)['"]?|cargo\b[^\n;&|]*\sinsta\s+accept|(?:UPDATE_SNAPSHOTS|SNAPSHOT_UPDATE|INSTA_UPDATE)=['"]?(?:1|true|always|all)['"]?|go\s+test\b[^\n;&|]*\s-run(?:=|\s+)['"]?\^\$['"]?)(?=$|[\s;&|)])`,
71
+ String.raw`\bgit\b[^\n;&|]*\bcommit\b[^\n;&|]*\s['"]?(?:-n|--no-verify)['"]?(?=$|[\s;&|)])`,
72
+ String.raw`\b(?:reward-guard\.db|contract-lock\.json|judge_verdicts)\b`,
73
+ String.raw`\breward_guard\.py\b[^\n;&|]*\brecord-judge\b`,
74
+ ].join("|"),
75
+ "i",
76
+ );
77
+
78
+ function minFlagFloor(rawTok) {
79
+ const tok = (rawTok ?? "").toLowerCase().replace(/_/g, "-");
80
+ if (!tok) return 0.5;
81
+ if (tok === "p" || tok === "k" || tok === "port" || tok === "ports") return null;
82
+ if (Object.hasOwn(METRIC_FLOORS, tok)) return METRIC_FLOORS[tok];
83
+ const matches = Object.entries(METRIC_FLOORS)
84
+ .filter(([k]) => k.startsWith(tok))
85
+ .map(([, v]) => v);
86
+ return matches.length ? Math.max(...matches) : null;
87
+ }
88
+ function parseGuardFloat(raw) {
89
+ const c = String(raw).trim().replace(/_/g, "");
90
+ if (/^[-+]?inf(?:inity)?$/i.test(c)) return c.startsWith("-") ? -Infinity : Infinity;
91
+ if (/^[-+]?nan$/i.test(c)) return NaN;
92
+ return Number(c);
93
+ }
48
94
 
49
95
  // rule-paths.json, lowercased, for the cheap pre-check that decides whether rule_ledger.py needs to run at all.
50
96
  function loadRuleSpec() {
@@ -54,17 +100,33 @@ function loadRuleSpec() {
54
100
  const names = low(spec.names);
55
101
  const dirs = low(spec.dirs);
56
102
  const files = low(spec.files);
103
+ const userFiles = low(spec.user?.files);
104
+ const userDirs = low(spec.user?.dirs);
57
105
  return {
58
106
  names: new Set(names),
59
107
  dirs: dirs.map(d => `/${d}/`),
60
108
  files: files.map(f => `/${f}`),
61
- hints: [...names, ...files, ...dirs, ...dirs.map(d => d.split("/")[0]), "deepmodebot", "rule_ledger"],
109
+ userFiles: new Set(userFiles),
110
+ userDirs: userDirs.map(d => `${d}/`),
111
+ hints: [
112
+ ...names, ...files, ...dirs, ...dirs.map(d => d.split("/")[0]),
113
+ ...userFiles, ...userDirs, "deepmodebot", "rule_ledger",
114
+ ],
62
115
  };
63
116
  } catch {
64
117
  return undefined;
65
118
  }
66
119
  }
67
120
 
121
+ // A user-level agent rule: a `user` path of rule-paths.json under the home folder.
122
+ function isUserRulePath(abs) {
123
+ const home = real(homeDirectory()).replace(/\\/g, "/").toLowerCase();
124
+ const p = abs.replace(/\\/g, "/").toLowerCase();
125
+ if (!RULES || !p.startsWith(`${home}/`)) return false;
126
+ const rel = p.slice(home.length + 1);
127
+ return RULES.userFiles.has(rel) || RULES.userDirs.some(d => rel.startsWith(d));
128
+ }
129
+
68
130
  function mayBeRulePath(abs) {
69
131
  if (!RULES) return false;
70
132
  const p = abs.toLowerCase().replace(/\\/g, "/");
@@ -72,7 +134,8 @@ function mayBeRulePath(abs) {
72
134
  RULES.names.has(p.slice(p.lastIndexOf("/") + 1)) ||
73
135
  p.includes("/.deepmodebot/rules") ||
74
136
  RULES.dirs.some(d => p.includes(d)) ||
75
- RULES.files.some(f => p.endsWith(f))
137
+ RULES.files.some(f => p.endsWith(f)) ||
138
+ isUserRulePath(abs)
76
139
  );
77
140
  }
78
141
 
@@ -88,20 +151,18 @@ function ledgerNear(abs) {
88
151
  }
89
152
  }
90
153
 
91
- // rule_ledger.py guard verdict: a deny reason, "" to allow, or null when no Python could run it.
92
- function pythonGuard(request) {
154
+ // Output of a Python helper, "" when it failed, or null when no Python could run it.
155
+ function runPython(script, args, input, timeout) {
93
156
  for (const [exe, prefix] of PYTHONS) {
94
157
  try {
95
- const out = execFileSync(exe, [...prefix, RULE_LEDGER, "guard"], {
96
- input: JSON.stringify(request),
158
+ return execFileSync(exe, [...prefix, script, ...args], {
159
+ input,
97
160
  encoding: "utf8",
98
- timeout: 8_000,
161
+ timeout,
99
162
  stdio: ["pipe", "pipe", "ignore"],
100
163
  windowsHide: true,
101
164
  env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" },
102
165
  });
103
- const verdict = JSON.parse(out);
104
- return verdict && verdict.block ? String(verdict.reason) : "";
105
166
  } catch (err) {
106
167
  if (err && err.code === "ENOENT") continue;
107
168
  return "";
@@ -110,6 +171,31 @@ function pythonGuard(request) {
110
171
  return null;
111
172
  }
112
173
 
174
+ // rule_ledger.py guard verdict: a deny reason, "" to allow, or null when no Python could run it.
175
+ function pythonGuard(request) {
176
+ const out = runPython(RULE_LEDGER, ["guard"], JSON.stringify(request), 8_000);
177
+ if (out === null) return null;
178
+ try {
179
+ const verdict = JSON.parse(out);
180
+ return verdict && verdict.block ? String(verdict.reason) : "";
181
+ } catch {
182
+ return "";
183
+ }
184
+ }
185
+
186
+ // The unapproved-rules notice for this conversation as an injectSteps entry, or null when nothing is pending.
187
+ function rulesNoticeStep(cwd) {
188
+ const out = runPython(RULES_WATCH, ["check", "--format", "agy", "--cwd", cwd], "", 8_000);
189
+ let notice;
190
+ try {
191
+ notice = out ? JSON.parse(out) : null;
192
+ } catch {
193
+ notice = { systemMessage: "deepmodebot: the agent rule check returned unreadable output; tell the user to run `deepmodebot rules watch`." };
194
+ }
195
+ if (!notice || !notice.systemMessage) return null;
196
+ return { systemMessage: { systemMessage: notice.systemMessage, metadata: { source: "deepmodebot", kind: "rules-notice" } } };
197
+ }
198
+
113
199
  // Python runs only for shell commands in a ledger repo or naming a rule path or owner command, and for writes whose
114
200
  // target (or resolved target) looks like a rule path.
115
201
  function ruleDenyReason(cwd, paths, command) {
@@ -120,7 +206,8 @@ function ruleDenyReason(cwd, paths, command) {
120
206
  if (candidates.length === 0 && !shell) return "";
121
207
  const verdict = pythonGuard({ cwd, paths: candidates, command: shell ? command : "" });
122
208
  if (verdict !== null) return verdict;
123
- return candidates.some(p => ledgerNear(absolute(p, cwd)))
209
+ const userOn = fs.existsSync(path.join(homeDirectory(), LEDGER_REL));
210
+ return candidates.some(p => ledgerNear(absolute(p, cwd)) || (userOn && isUserRulePath(absolute(p, cwd))))
124
211
  ? "deepmodebot rule approval needs Python 3 on PATH to check rule files; install it, then retry."
125
212
  : "";
126
213
  }
@@ -129,13 +216,51 @@ function findShellRewardHack(rawCmd) {
129
216
  const cleaned = String(rawCmd ?? "").replace(/(-m|--message)(=|\s+)("[^"]*"|'[^']*')/g, '$1 ""');
130
217
  for (const rawLine of cleaned.replace(/\\\r?\n/g, " ").split(/\r?\n/)) {
131
218
  const line = rawLine.trim();
132
- if (!line || /^(?:grep|rg)\s+[^;&|`$]*$/.test(line)) continue;
219
+ if (!line || /^(?:grep|rg|echo|printf)\s+[^;&|<>()`$]*$/.test(line)) continue;
220
+ MIN_FLAG_VAL_RE.lastIndex = 0;
221
+ let fm;
222
+ while ((fm = MIN_FLAG_VAL_RE.exec(line)) !== null) {
223
+ const floor = minFlagFloor(fm[3] || fm[2]);
224
+ const val = parseGuardFloat(fm[4]);
225
+ if (floor !== null && (!Number.isFinite(val) || val < floor)) return fm[1].trim();
226
+ }
133
227
  const m = REWARD_HACK_CMD_RE.exec(line);
134
228
  if (m) return m[0].trim();
135
229
  }
136
230
  return null;
137
231
  }
138
232
 
233
+ function spawnVerdict(args) {
234
+ const env = process.env;
235
+ const depth = env.DEEPMODEBOT_SUBAGENT_DEPTH;
236
+ const nested = env.TEAMWORK_RUN_ID || env.SWARM_ID || env.AGY_PARENT_CONVERSATION_ID ||
237
+ (depth && depth !== "0") || env.DEEPMODEBOT_MAX_SUBAGENTS === "0";
238
+ const promptKey = "Prompt" in args || !("prompt" in args) ? "Prompt" : "prompt";
239
+ const prompt = String(args[promptKey] ?? "");
240
+ if (nested && env.ALLOW_NESTED_SUBAGENTS !== "1" && !prompt.includes("ALLOW_NESTED_SUBAGENTS")) {
241
+ return { decision: "deny", reason: NESTED_REASON };
242
+ }
243
+ const overwrite = {};
244
+ const agent = args.TypeName;
245
+ if (typeof agent === "string" && Object.hasOwn(OVERHEAD_AGENTS, agent) && (!args.Model || args.Model === "inherit")) {
246
+ overwrite.Model = agent === "scout" ? "flash_lite" : "flash";
247
+ }
248
+ if (!prompt.includes("worker.md")) overwrite[promptKey] = `Read ${WORKER_BRIEF} before anything else.\n${prompt}`;
249
+ return Object.keys(overwrite).length ? { decision: "allow", overwrite } : { decision: "allow" };
250
+ }
251
+
252
+ function sliceDenyReason(root, target) {
253
+ const worker = process.env.DEEPMODEBOT_WORKER_ID;
254
+ if (!worker) return "";
255
+ if (!/^[A-Za-z0-9._-]+(?![\s\S])/.test(worker)) return "deepmodebot: invalid worker ID";
256
+ if (!fs.existsSync(path.join(root, ".scratch", "slices", `${worker}.json`))) return "";
257
+ const out = runPython(WORKER_GATE, ["check-write", "--root", root, "--worker", worker, "--path", target, "--json"], "", 5_000);
258
+ try {
259
+ if (out && JSON.parse(out).ok === true) return "";
260
+ } catch { return `deepmodebot: ${target} is outside the owned slice for ${worker}, or the slice could not be checked`; }
261
+ return `deepmodebot: ${target} is outside the owned slice for ${worker}, or the slice could not be checked`;
262
+ }
263
+
139
264
  // Kept as explicit slash tokens so scripts/whitelabel.py rebrands both /deepmodebot: and /deep.
140
265
  const SLASH_PREFIX = "/deepmodebot:";
141
266
  const SLASH_COMMANDS = [
@@ -323,13 +448,38 @@ function allowedRoots(roots, event) {
323
448
  return allowed.map(real);
324
449
  }
325
450
 
451
+ function guardDataDir() {
452
+ return process.env.PLUGIN_DATA || path.join(homeDirectory(), ".gemini", "antigravity", "deepmodebot-guard");
453
+ }
454
+
455
+ function conversationId(event) {
456
+ return String(event.conversationId ?? event.session_id ?? "").replace(/[^A-Za-z0-9_-]/g, "");
457
+ }
458
+
326
459
  function sessionMarkPath(event) {
327
- const dataDir =
328
- process.env.PLUGIN_DATA ||
329
- path.join(homeDirectory(), ".gemini", "antigravity", "deepmodebot-guard");
330
- const rawId = String(event.conversationId ?? event.session_id ?? "");
331
- const cleanId = rawId.replace(/[^A-Za-z0-9_-]/g, "");
332
- return cleanId ? path.join(dataDir, "active-sessions", cleanId) : null;
460
+ const id = conversationId(event);
461
+ return id ? path.join(guardDataDir(), "active-sessions", id) : null;
462
+ }
463
+
464
+ // Whether this conversation still needs its rules notice; marks it shown (marks older than 30 days are pruned).
465
+ function claimRulesNotice(event) {
466
+ const id = conversationId(event);
467
+ if (!id) return typeof event.invocationNum !== "number" || event.invocationNum <= 1;
468
+ const folder = path.join(guardDataDir(), "rules-notice");
469
+ const mark = path.join(folder, id);
470
+ if (fs.existsSync(mark)) return false;
471
+ try {
472
+ fs.mkdirSync(folder, { recursive: true });
473
+ const now = Date.now();
474
+ for (const entry of fs.readdirSync(folder)) {
475
+ const old = path.join(folder, entry);
476
+ if (now - fs.statSync(old).mtimeMs > MARK_MAX_AGE_MS) fs.unlinkSync(old);
477
+ }
478
+ fs.writeFileSync(mark, "");
479
+ } catch {
480
+ // Without a mark the notice may repeat; that is better than never showing it.
481
+ }
482
+ return true;
333
483
  }
334
484
 
335
485
  function readMarkState(markPath) {
@@ -402,6 +552,537 @@ function writeJsonAndExit(payload) {
402
552
  process.exit(0);
403
553
  }
404
554
 
555
+
556
+ const HOLDOUT_DIR = ".deepmodebot-holdout";
557
+ const HOLDOUT_FALLBACK = "deepmodebot-holdout";
558
+ const onWindows = process.platform === "win32";
559
+ const TMP_ROOTS = ["/tmp", "/var/tmp", "/private/tmp", "/var/folders", "/private/var/folders", "c:/windows/temp"];
560
+ const HOME_SPELLING_RE =
561
+ /^(?:~|\$\{?(?:home|userprofile)\}?|%(?:home|userprofile)%|\$\{?env:(?:home|userprofile)\}?|%homedrive%%homepath%|\$\{?(?:env:)?homedrive\}?\$\{?(?:env:)?homepath\}?)(?=\/|$)/i;
562
+ const LOCAL_SPELLING_RE = /^(?:\$\{?(?:env:)?localappdata\}?|%localappdata%)(?=\/|$)/i;
563
+ const GIT_RAW_RE = /(?:^|\/)[^/]*\.git\/(?:objects|logs|lost-found)(?:\/|$)|(?:^|\/)objects\/(?:pack|info|[0-9a-f]{2})(?:\/|$)/i;
564
+ const GLOB_RE = /[*?[]/;
565
+ const TEST_RE = /(?:^|[^a-z0-9])(?:tests?|specs?|holdouts?|hidden|golden|graders?|solutions?|answers?|expected|fixtures?)(?:[^a-z0-9]|$)/i;
566
+ const INTERPRETER_RE = /^(?:python|py|node|bun|deno|perl|ruby|php|pwsh|powershell|bash|sh|zsh|dash|ksh|cmd|lua|tsx|ts-node|osascript|rscript)[0-9.]*$/;
567
+ const LOOP_RE = /(?:^|[\s;&|(])(?:for|while|until|read|xargs)(?=$|[\s;&|)])/;
568
+ const COMMAND_PREFIXES = new Set(["sudo", "time", "command", "env", "nohup", "exec", "builtin", "nice", "then", "do", "else", "{"]);
569
+ const CD_COMMANDS = new Set(["cd", "pushd", "chdir", "sl", "set-location"]);
570
+ const GREP_FAMILY = new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "sls", "select-string"]);
571
+ const ENUMERATORS = new Set(["find", "fd", "fdfind", "ls", "dir", "tree", "gci", "get-childitem", "locate", "mlocate"]);
572
+ const CONTENT_READERS = new Set([
573
+ "cat", "type", "head", "tail", "less", "more", "xargs", "strings", "bat", "tac", "nl", "od", "xxd", "hexdump",
574
+ "get-content", "gc", "select-string", "sls", "findstr",
575
+ ]);
576
+ const ALWAYS_RECURSIVE = new Set(["rg", "ag", "ack", "zip", "7z", "7za", "rsync", "robocopy", "xcopy"]);
577
+ const GREP_ARG_FLAGS = new Set([
578
+ "-e", "-f", "-m", "-A", "-B", "-C", "-g", "-t", "-T", "-j", "-M", "-d", "-D", "--regexp", "--file", "--max-count",
579
+ "--after-context", "--before-context", "--context", "--glob", "--iglob", "--type", "--type-not", "--include",
580
+ "--exclude", "--exclude-dir", "--include-dir", "--max-depth", "--threads", "-pattern", "-path", "-literalpath",
581
+ ]);
582
+ const GIT_GLOBAL_ARG_FLAGS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env"]);
583
+ const GIT_DENIED_SUBCOMMANDS = new Set(["unpack-file", "prune", "show-index", "verify-pack", "lost-found"]);
584
+ const GIT_REFLOG_SUBCOMMANDS = new Set(["log", "show", "rev-list", "whatchanged", "shortlog", "format-patch", "diff", "archive", "grep"]);
585
+ const GIT_CONTENT_SUBCOMMANDS = new Set(["show", "diff", "format-patch", "archive", "grep"]);
586
+ const GIT_RECOVER_SUBCOMMANDS = new Set([
587
+ "show", "cat-file", "checkout", "restore", "switch", "cherry-pick", "archive", "diff", "format-patch", "read-tree",
588
+ "reset", "merge", "branch", "tag", "update-ref", "worktree", "apply",
589
+ ]);
590
+ const GIT_CONTENT_FLAGS = [
591
+ "--patch", "--patch-with-stat", "--patch-with-raw", "--cc", "--stat", "--numstat", "--shortstat", "--raw", "--name-only",
592
+ "--name-status", "--full-diff", "--pickaxe-regex", "--pickaxe-all", "--word-diff", "--textconv", "--objects",
593
+ "--summary", "--dirstat",
594
+ ];
595
+ const TOOL_PATH_KEYS = new Set([
596
+ "path", "paths", "filepath", "file", "files", "notebookpath", "directory", "dir", "cwd", "root", "targetfile",
597
+ "searchpath", "searchdirectory", "directorypath", "absolutepath", "abspath", "workdir", "filename",
598
+ ]);
599
+ const TOOL_PATTERN_KEYS = new Set(["glob", "include", "pattern"]);
600
+ const SEARCH_TOOL_RE = /grep|glob|find|^ls$|list|tree|walk|^dir$|^rg$/i;
601
+
602
+ function holdoutReason(hit) {
603
+ return `deepmodebot anti-reward-hacking guard blocked "${hit}": builders may not read the hidden holdout store or mine git objects, reflogs, or other agents' temp files for hidden answers.`;
604
+ }
605
+
606
+ function homeDirs() {
607
+ const env = process.env;
608
+ const found = [];
609
+ for (const home of [env.HOME, env.USERPROFILE, `${env.HOMEDRIVE ?? ""}${env.HOMEPATH ?? ""}`, os.homedir()]) {
610
+ if (home && home !== "~" && !found.includes(home)) found.push(home);
611
+ }
612
+ return found;
613
+ }
614
+
615
+ function prepPath(p) {
616
+ let text = p.replace(/\\/g, "/");
617
+ text = text.replace(/^file:\/{2,3}(?:localhost\/)?/i, "/");
618
+ if (/^\/[A-Za-z]:/.test(text)) text = text.slice(1);
619
+ text = text.replace(/^\/\/[?.]\//, "");
620
+ text = text.replace(/^\/\/(?:localhost|127\.0\.0\.1)\/([A-Za-z])\$(?=\/|$)/i, "$1:");
621
+ if (onWindows) {
622
+ text = text.replace(/^\/(?:mnt|cygdrive)\/([A-Za-z])(?=\/|$)/, "$1:");
623
+ text = text.replace(/^\/([A-Za-z])(?=\/)/, "$1:");
624
+ }
625
+ return text;
626
+ }
627
+
628
+ function toSegs(p) {
629
+ const text = prepPath(p);
630
+ const drive = /^[A-Za-z]:(?=\/|$)/.exec(text);
631
+ let root;
632
+ let rest;
633
+ if (drive) {
634
+ root = drive[0];
635
+ rest = text.slice(drive[0].length);
636
+ } else if (text.startsWith("/")) {
637
+ root = onWindows ? process.cwd().slice(0, 2) : "/";
638
+ rest = text;
639
+ } else {
640
+ return null;
641
+ }
642
+ const out = [];
643
+ for (let part of rest.split("/")) {
644
+ if (part === "" || part === ".") continue;
645
+ if (part === "..") {
646
+ out.pop();
647
+ continue;
648
+ }
649
+ if (onWindows) {
650
+ part = part.split(":")[0].replace(/[. ]+$/, "");
651
+ if (!part) continue;
652
+ }
653
+ out.push(part);
654
+ }
655
+ return caseless ? [root.toLowerCase(), ...out.map(part => part.toLowerCase())] : [root, ...out];
656
+ }
657
+
658
+ function joinSegs(segs) {
659
+ return (segs[0] !== "/" ? segs[0] : "") + "/" + segs.slice(1).join("/");
660
+ }
661
+
662
+ function toAbs(text, cwd) {
663
+ return toSegs(text) ?? toSegs(joinSegs(cwd) + "/" + prepPath(text)) ?? cwd;
664
+ }
665
+
666
+ function realpathLoose(p) {
667
+ try {
668
+ return fs.realpathSync.native(p);
669
+ } catch {
670
+ const parent = path.dirname(p);
671
+ return parent === p ? p : path.join(realpathLoose(parent), path.basename(p));
672
+ }
673
+ }
674
+
675
+ function realSegs(text, cwd) {
676
+ const raw = prepPath(text);
677
+ return toSegs(realpathLoose(toSegs(raw) ? raw : joinSegs(cwd) + "/" + raw));
678
+ }
679
+
680
+ function sameSegs(a, b) {
681
+ return a.length === b.length && a.every((part, i) => part === b[i]);
682
+ }
683
+
684
+ function startsWithSegs(segs, prefix) {
685
+ return segs.length >= prefix.length && prefix.every((part, i) => part === segs[i]);
686
+ }
687
+
688
+ function uniqueSegs(paths) {
689
+ const found = [];
690
+ for (const p of paths) {
691
+ for (const segs of [toSegs(p), toSegs(realpathLoose(p))]) {
692
+ if (segs && !found.some(f => sameSegs(f, segs))) found.push(segs);
693
+ }
694
+ }
695
+ return found;
696
+ }
697
+
698
+ function expandBraces(text, cap = 64) {
699
+ const match = /\{([^{}]*,[^{}]*)\}/.exec(text);
700
+ if (!match) return [text];
701
+ const out = [];
702
+ for (const alt of match[1].split(",")) {
703
+ out.push(...expandBraces(text.slice(0, match.index) + alt + text.slice(match.index + match[0].length), cap));
704
+ if (out.length >= cap) break;
705
+ }
706
+ return out.slice(0, cap);
707
+ }
708
+
709
+ function wordVariants(word) {
710
+ const out = [word];
711
+ for (let i = word.indexOf("="); i !== -1; i = word.indexOf("=", i + 1)) out.push(word.slice(i + 1));
712
+ for (const match of word.matchAll(/:(?=[~$%/\\])/g)) out.push(word.slice((match.index ?? 0) + 1));
713
+ return out.filter((v, i) => v !== "" && !out.slice(0, i).includes(v));
714
+ }
715
+
716
+ function segMatch(glob, name) {
717
+ if (!GLOB_RE.test(glob)) return glob === name;
718
+ if ("*?[".includes(glob[0]) && name.startsWith(".")) return false;
719
+ let out = "";
720
+ for (let i = 0; i < glob.length; i++) {
721
+ const ch = glob[i];
722
+ const close = ch === "[" ? glob.indexOf("]", i + 2) : -1;
723
+ if (ch === "*") {
724
+ out += "[^/]*";
725
+ } else if (ch === "?") {
726
+ out += "[^/]";
727
+ } else if (close !== -1) {
728
+ const body = glob.slice(i + 1, close);
729
+ out += "[" + (body[0] === "!" || body[0] === "^" ? "^" + body.slice(1) : body).replace(/\\/g, "\\\\") + "]";
730
+ i = close;
731
+ } else {
732
+ out += escapeRegex(ch);
733
+ }
734
+ }
735
+ try {
736
+ return new RegExp("^" + out + "$").test(name);
737
+ } catch {
738
+ return true;
739
+ }
740
+ }
741
+
742
+ function namedLiteral(seg) {
743
+ return !GLOB_RE.test(seg) || seg.replace(/[.*?[\]!^-]/g, "") !== "";
744
+ }
745
+
746
+ function globMatch(glob, i, root, j) {
747
+ if (j === root.length) return i < glob.length || (i > 0 && namedLiteral(glob[i - 1]));
748
+ if (i === glob.length) return false;
749
+ if (glob[i] === "**") return globMatch(glob, i + 1, root, j) || globMatch(glob, i, root, j + 1);
750
+ return segMatch(glob[i], root[j]) && globMatch(glob, i + 1, root, j + 1);
751
+ }
752
+
753
+ function wordBase(word) {
754
+ const name = (word.replace(/\\/g, "/").split("/").pop() ?? "").toLowerCase();
755
+ return name.endsWith(".exe") ? name.slice(0, -4) : name;
756
+ }
757
+
758
+ function leadIndex(words) {
759
+ let prefixed = false;
760
+ for (let i = 0; i < words.length; i++) {
761
+ if (/^[A-Za-z_]\w*=/.test(words[i]) || COMMAND_PREFIXES.has(wordBase(words[i]))) prefixed = true;
762
+ else if (!(prefixed && words[i].startsWith("-"))) return i;
763
+ }
764
+ return words.length;
765
+ }
766
+
767
+ function optIs(token, full, minLen) {
768
+ const name = token.split("=")[0];
769
+ return name.startsWith("--") && name.length >= minLen && full.startsWith(name);
770
+ }
771
+
772
+ class HoldoutScan {
773
+ homes = homeDirs();
774
+ cwd;
775
+ roots;
776
+ tmp;
777
+ realBudget = 200;
778
+
779
+ constructor(cwd) {
780
+ this.cwd = toSegs(cwd) ?? toSegs(process.cwd()) ?? ["/"];
781
+ const stores = this.homes.map(home => path.join(home, HOLDOUT_DIR));
782
+ const local = process.env.LOCALAPPDATA;
783
+ if (local) stores.push(path.join(local, HOLDOUT_FALLBACK));
784
+ stores.push("/tmp/" + HOLDOUT_FALLBACK);
785
+ this.roots = uniqueSegs(stores);
786
+ this.tmp = uniqueSegs([...TMP_ROOTS, ...this.homes.map(home => path.join(home, "AppData", "Local", "Temp"))]);
787
+ }
788
+
789
+ expand(item) {
790
+ const match = HOME_SPELLING_RE.exec(item);
791
+ if (match) return this.homes.length ? this.homes.map(home => home + item.slice(match[0].length)) : [item];
792
+ const local = process.env.LOCALAPPDATA;
793
+ const localMatch = LOCAL_SPELLING_RE.exec(item);
794
+ return localMatch && local ? [local + item.slice(localMatch[0].length)] : [item];
795
+ }
796
+
797
+ candidates(word, cwd) {
798
+ const found = [];
799
+ for (const variant of wordVariants(word.replace(/\\/g, "/"))) {
800
+ for (const item of expandBraces(variant)) {
801
+ for (const text of this.expand(item)) {
802
+ found.push(toAbs(text, cwd));
803
+ if (this.realBudget > 0 && prepPath(text).includes("/") && !GLOB_RE.test(text)) {
804
+ this.realBudget -= 1;
805
+ const real = realSegs(text, cwd);
806
+ if (real) found.push(real);
807
+ }
808
+ }
809
+ }
810
+ }
811
+ return found;
812
+ }
813
+
814
+ reaches(cands) {
815
+ return cands.some(c => this.roots.some(r => globMatch(c, 0, r, 0)));
816
+ }
817
+
818
+ above(cands, widen = false) {
819
+ return cands.map(c => (widen ? literalHead(c) : c))
820
+ .some(h => !h.some(s => GLOB_RE.test(s)) && this.roots.some(r => startsWithSegs(r, h)));
821
+ }
822
+
823
+ inTmp(segs) {
824
+ return this.tmp.some(t => startsWithSegs(segs, t)) && !startsWithSegs(segs, this.cwd);
825
+ }
826
+ }
827
+
828
+ function literalHead(segs) {
829
+ const i = segs.findIndex(seg => GLOB_RE.test(seg));
830
+ return i === -1 ? segs : segs.slice(0, i);
831
+ }
832
+
833
+ function computedHome(word) {
834
+ for (const variant of wordVariants(word)) {
835
+ const match = HOME_SPELLING_RE.exec(variant);
836
+ const first = match ? variant.slice(match[0].length).replace(/^\/+/, "").split("/")[0] : "";
837
+ if (first && /\$|%[A-Za-z_]\w*%/.test(first)) return true;
838
+ }
839
+ return false;
840
+ }
841
+
842
+ function grepSkips(words) {
843
+ const skips = new Set();
844
+ for (let i = 0; i < words.length; i++) {
845
+ const name = wordBase(words[i]);
846
+ if (!GREP_FAMILY.has(name)) continue;
847
+ let k = i + 1;
848
+ let havePattern = false;
849
+ while (k < words.length && words[k].startsWith("-") && words[k] !== "-" && words[k] !== "--") {
850
+ const flag = words[k].length <= 2 ? words[k] : words[k].toLowerCase();
851
+ if (flag.startsWith("--regexp=")) {
852
+ skips.add(k);
853
+ havePattern = true;
854
+ }
855
+ if (flag === "-e" || flag === "--regexp" || flag === "-pattern") {
856
+ havePattern = true;
857
+ skips.add(k + 1);
858
+ }
859
+ k += GREP_ARG_FLAGS.has(flag) || (name === "rg" && flag === "-r") ? 2 : 1;
860
+ }
861
+ if (k < words.length && words[k] === "--") k += 1;
862
+ if (!havePattern && k < words.length) skips.add(k);
863
+ }
864
+ return skips;
865
+ }
866
+
867
+ function contentFlag(token) {
868
+ return GIT_CONTENT_FLAGS.some(full => optIs(token, full, 4)) || /^-\d*[pu]$/.test(token)
869
+ || token.startsWith("-S") || token.startsWith("-G");
870
+ }
871
+
872
+ function gitCalls(words) {
873
+ const calls = [];
874
+ for (let i = 0; i < words.length; i++) {
875
+ const name = wordBase(words[i]);
876
+ const dashed = /^git-([a-z-]+)$/.exec(name);
877
+ if (dashed) {
878
+ calls.push([dashed[1], words.slice(i + 1)]);
879
+ } else if (name === "git") {
880
+ let k = i + 1;
881
+ while (k < words.length && words[k].startsWith("-")) k += GIT_GLOBAL_ARG_FLAGS.has(words[k]) ? 2 : 1;
882
+ if (k < words.length) calls.push([words[k].toLowerCase(), words.slice(k + 1)]);
883
+ }
884
+ }
885
+ return calls;
886
+ }
887
+
888
+ function reflogFlagged(sub, args) {
889
+ return GIT_REFLOG_SUBCOMMANDS.has(sub)
890
+ && args.some(a => a === "-g" || optIs(a, "--reflog", 6) || optIs(a, "--walk-reflogs", 7));
891
+ }
892
+
893
+ function gitHit(sub, args) {
894
+ if (sub === "cat-file" && args.some(a => optIs(a, "--batch-all-objects", 9))) return "git cat-file --batch-all-objects";
895
+ if (sub === "fsck" || sub === "fsck-objects") {
896
+ const bad = args.some(a => optIs(a, "--lost-found", 4) || optIs(a, "--unreachable", 4) || optIs(a, "--dangling", 3)
897
+ || optIs(a, "--no-reflogs", 6));
898
+ if (bad || !args.some(a => optIs(a, "--no-dangling", 8))) return "git fsck";
899
+ }
900
+ if (GIT_DENIED_SUBCOMMANDS.has(sub)) return "git " + sub;
901
+ const content = args.some(contentFlag);
902
+ if ((reflogFlagged(sub, args) && (GIT_CONTENT_SUBCOMMANDS.has(sub) || content)) || (sub === "reflog" && content)) {
903
+ return "git " + sub + " reflog content";
904
+ }
905
+ return null;
906
+ }
907
+
908
+ function gitRole(sub, args) {
909
+ const feeder = sub === "reflog" || reflogFlagged(sub, args) || (
910
+ sub === "rev-list" && args.some(a => optIs(a, "--objects", 5))
911
+ && args.some(a => a === "--all" || optIs(a, "--reflog", 6)));
912
+ const sink = GIT_RECOVER_SUBCOMMANDS.has(sub) || (sub === "cat-file" && args.some(a => a.startsWith("--batch")));
913
+ return [feeder, sink];
914
+ }
915
+
916
+ function isRecursive(name, args) {
917
+ const low = args.map(a => a.toLowerCase());
918
+ if (ALWAYS_RECURSIVE.has(name)) return true;
919
+ if (GREP_FAMILY.has(name)) {
920
+ return args.some(a => /^-[a-zA-Z]*[rR][a-zA-Z]*$/.test(a) || a === "--recursive" || a === "--dereference-recursive")
921
+ || low.includes("-recurse") || (args.includes("-d") && args.includes("recurse"));
922
+ }
923
+ if (name === "cp" || name === "scp" || name === "copy-item" || name === "cpi") {
924
+ return args.some(a => /^-[a-zA-Z]*[rRa][a-zA-Z]*$/.test(a) || a === "--recursive") || low.includes("-recurse");
925
+ }
926
+ if (name === "tar") return args.length > 0 && (args[0] === "--create" || /^-?[a-zA-Z]*c[a-zA-Z]*$/.test(args[0]));
927
+ return name === "findstr" && low.includes("/s");
928
+ }
929
+
930
+ function isContentReader(words) {
931
+ const consumes = words.some(w => GREP_FAMILY.has(wordBase(w)) || wordBase(w) === "sed" || wordBase(w) === "awk");
932
+ return words.some(w => CONTENT_READERS.has(wordBase(w)) || /^-(?:exec|execdir|ok|okdir)$/.test(w) || (w === "$" && consumes));
933
+ }
934
+
935
+ function sweepHit(scan, stages, content) {
936
+ const hasTest = TEST_RE.test(stages.flatMap(st => (st ? st.words : [])).join(" "));
937
+ for (const st of stages) {
938
+ if (!st) continue;
939
+ for (let i = 0; i < st.words.length; i++) {
940
+ const name = wordBase(st.words[i]);
941
+ const rec = isRecursive(name, st.words.slice(i + 1));
942
+ const enumerates = ENUMERATORS.has(name);
943
+ if ((rec || (enumerates && content)) && scan.above([...st.ops, st.start], rec)) {
944
+ return name + " over a directory holding the holdout store";
945
+ }
946
+ if (!hasTest) continue;
947
+ for (const op of st.ops) {
948
+ const broad = rec || (enumerates && content) || (CONTENT_READERS.has(name) && op.some(s => GLOB_RE.test(s)));
949
+ if (broad && scan.inTmp(op)) return name + " sweeping temp directories for tests";
950
+ }
951
+ }
952
+ }
953
+ return null;
954
+ }
955
+
956
+ function scanStage(scan, words, cur) {
957
+ const lead = leadIndex(words);
958
+ const skips = grepSkips(words);
959
+ const ops = [];
960
+ for (let i = 0; i < words.length; i++) {
961
+ const token = words[i].replace(/^\d*[<>]+/, "");
962
+ if (skips.has(i) || !token) continue;
963
+ if (GIT_RAW_RE.test(token.replace(/\\/g, "/"))) return { hit: token, stage: null };
964
+ if (token.startsWith("-") && !token.includes("=")) continue;
965
+ const cands = scan.candidates(token, cur);
966
+ if (computedHome(token) || scan.reaches(cands)) return { hit: token, stage: null };
967
+ if (i > lead) ops.push(...cands);
968
+ }
969
+ const gwords = words.flatMap(w => w.split(/[,[\]]+/).filter(Boolean));
970
+ const calls = [];
971
+ for (const [sub, args] of gitCalls(gwords)) {
972
+ const hit = gitHit(sub, args);
973
+ if (hit) return { hit, stage: null };
974
+ calls.push([sub, args]);
975
+ }
976
+ return { hit: null, stage: { words, ops, start: cur, git: calls, lead } };
977
+ }
978
+
979
+ function nextCwd(scan, st, cur) {
980
+ const { words, lead } = st;
981
+ if (lead >= words.length || !CD_COMMANDS.has(wordBase(words[lead])) || words.slice(lead + 1).includes("-")) return cur;
982
+ const args = words.slice(lead + 1).filter(w => !w.startsWith("-") && !/^\/[A-Za-z]$/.test(w));
983
+ const first = scan.candidates(args.length ? args[0] : "~", cur)[0];
984
+ return first.some(s => GLOB_RE.test(s)) ? cur : first;
985
+ }
986
+
987
+ function gitLinkHit(stages, ci, links) {
988
+ const feeders = [];
989
+ const sinks = [];
990
+ stages.forEach((st, si) => {
991
+ if (!st) return;
992
+ for (const [sub, args] of st.git) {
993
+ const [feeder, sink] = gitRole(sub, args);
994
+ if (feeder) feeders.push(si);
995
+ if (sink) sinks.push(si);
996
+ }
997
+ if (st.words.some(w => wordBase(w) === "xargs")) sinks.push(si);
998
+ });
999
+ links.feeders.push(...feeders.map((f) => [ci, f]));
1000
+ links.sinks.push(...sinks.map((s) => [ci, s]));
1001
+ return feeders.some(f => sinks.some(s => f !== s)) ? "git history listing piped into content recovery" : null;
1002
+ }
1003
+
1004
+ function scanText(scan, source) {
1005
+ const text = source.replace(/`([^`]*)`/g, "$$($1)");
1006
+ let cur = scan.cwd;
1007
+ const links = { feeders: [], sinks: [] };
1008
+ const chains = text.split(/\|\||&&|[;&\r\n]/);
1009
+ for (let ci = 0; ci < chains.length; ci++) {
1010
+ const stages = [];
1011
+ for (const part of chains[ci].split(/[|()]/)) {
1012
+ const words = part.split(/\s+/).filter(Boolean);
1013
+ const scanned = words.length ? scanStage(scan, words, cur) : { hit: null, stage: null };
1014
+ if (scanned.hit) return scanned.hit;
1015
+ stages.push(scanned.stage);
1016
+ if (scanned.stage) cur = nextCwd(scan, scanned.stage, cur);
1017
+ }
1018
+ const content = stages.some(st => st !== null && isContentReader(st.words));
1019
+ const hit = gitLinkHit(stages, ci, links) ?? sweepHit(scan, stages, content);
1020
+ if (hit) return hit;
1021
+ }
1022
+ const crossed = links.feeders.some(([fc, fs]) => links.sinks.some(([sc, ss]) => fc !== sc || fs !== ss));
1023
+ return LOOP_RE.test(text) && crossed ? "git history listing piped into content recovery" : null;
1024
+ }
1025
+
1026
+ function inlineNameHit(text, evalMode) {
1027
+ const reduced = text.toLowerCase().replace(/[\s'"+,()[\]`\\^$\/]/g, "");
1028
+ if (!reduced.includes("deepmodebot-holdout")) return null;
1029
+ const interpreted = text.split(/[\s;&|()'"`]+/).some(w => w !== "" && INTERPRETER_RE.test(wordBase(w)));
1030
+ return evalMode || interpreted ? HOLDOUT_DIR : null;
1031
+ }
1032
+
1033
+ function holdoutCommandHit(command, cwd, evalMode = false) {
1034
+ const stripped = String(command ?? "").replace(/(-m|--message)(=|\s+)("[^"]*"|'[^']*')/g, '$1 ""');
1035
+ const text = stripped.replace(/\\\r?\n/g, " ");
1036
+ const scan = new HoldoutScan(cwd);
1037
+ const inline = inlineNameHit(text, evalMode);
1038
+ if (inline) return inline;
1039
+ const flat = text.replace(/\$(?=['"])/g, "").replace(/['"]/g, "");
1040
+ for (const view of [flat.replace(/\\/g, "/"), flat.replace(/[\\^`]/g, "")]) {
1041
+ const hit = scanText(scan, view);
1042
+ if (hit) return hit;
1043
+ }
1044
+ return null;
1045
+ }
1046
+
1047
+ function toolVariants(value) {
1048
+ const out = [value, value.replace(/#[0-9A-Za-z]{4}$/, ""), value.replace(/:\d+(?:-\d+)?(?:,.*)?$/, "")];
1049
+ for (const pattern of [/^\[(.+)#[0-9A-Za-z]+\]$/, /^(.{2,}?):[^/\\]/]) {
1050
+ const match = pattern.exec(value);
1051
+ if (match) out.push(match[1]);
1052
+ }
1053
+ return out.filter((v, i) => v !== "" && !out.slice(0, i).includes(v));
1054
+ }
1055
+
1056
+ function toolStrings(value) {
1057
+ if (typeof value === "string") return [value];
1058
+ return Array.isArray(value) ? value.filter(v => typeof v === "string") : [];
1059
+ }
1060
+
1061
+ function holdoutToolHit(toolName, input, cwd) {
1062
+ const search = SEARCH_TOOL_RE.test(toolName);
1063
+ const patternOk = search && !toolName.toLowerCase().includes("grep");
1064
+ const bases = [];
1065
+ const patterns = [];
1066
+ for (const [key, value] of Object.entries(input)) {
1067
+ const norm = key.replace(/[_\-\s]/g, "").toLowerCase();
1068
+ if (TOOL_PATTERN_KEYS.has(norm) && (norm !== "pattern" || patternOk)) patterns.push(...toolStrings(value));
1069
+ if (TOOL_PATH_KEYS.has(norm)) bases.push(...toolStrings(value));
1070
+ }
1071
+ if (!search && bases.length === 0 && patterns.length === 0) return null;
1072
+ const scan = new HoldoutScan(cwd);
1073
+ const texts = [...bases, ...patterns].flatMap(value => value.split(";"));
1074
+ for (const base of bases.length ? bases : [joinSegs(scan.cwd)]) {
1075
+ for (const pattern of patterns) texts.push(base.replace(/[/\\]+$/, "") + "/" + pattern);
1076
+ }
1077
+ for (const text of texts) {
1078
+ for (const variant of toolVariants(text.trim())) {
1079
+ const cands = scan.candidates(variant, scan.cwd);
1080
+ if (GIT_RAW_RE.test(variant.replace(/\\/g, "/")) || scan.reaches(cands) || (search && scan.above(cands, true))) return variant;
1081
+ }
1082
+ }
1083
+ return search && bases.length === 0 && scan.above([scan.cwd]) ? joinSegs(scan.cwd) : null;
1084
+ }
1085
+
405
1086
  function main() {
406
1087
  const mode = process.argv[2] === "enforce" ? "enforce" : "session";
407
1088
  const raw = readStdinText();
@@ -425,6 +1106,11 @@ function main() {
425
1106
  (event.hookEventName == null && event.toolCall != null);
426
1107
 
427
1108
  if (!isPreToolUse) {
1109
+ const steps = [];
1110
+ if (claimRulesNotice(event)) {
1111
+ const notice = rulesNoticeStep(resolveSessionCwd(event));
1112
+ if (notice) steps.push(notice);
1113
+ }
428
1114
  if (ACTIVATION_RE.test(promptText)) {
429
1115
  const prevState = markPath ? readMarkState(markPath) : null;
430
1116
  if (markPath) {
@@ -448,24 +1134,19 @@ function main() {
448
1134
  // Non-fatal: still return the overview for this invocation.
449
1135
  }
450
1136
  }
451
- writeJsonAndExit({
452
- injectSteps: [
453
- {
454
- systemMessage: {
455
- systemMessage: `deepmodebot workspace-map (auto-injected):\n${overview}`,
456
- metadata: { source: "deepmodebot", kind: "workspace-map" },
457
- },
458
- },
459
- ],
1137
+ steps.push({
1138
+ systemMessage: {
1139
+ systemMessage: `deepmodebot workspace-map (auto-injected):\n${overview}`,
1140
+ metadata: { source: "deepmodebot", kind: "workspace-map" },
1141
+ },
460
1142
  });
461
- return;
462
1143
  }
463
1144
  } catch {
464
1145
  // Fail open cleanly if workspace-map overview cannot be generated.
465
1146
  }
466
1147
  }
467
1148
  }
468
- writeJsonAndExit({});
1149
+ writeJsonAndExit(steps.length ? { injectSteps: steps } : {});
469
1150
  return;
470
1151
  }
471
1152
 
@@ -487,11 +1168,27 @@ function main() {
487
1168
  return;
488
1169
  }
489
1170
 
490
- if (mode !== "enforce" && !(markPath && fs.existsSync(markPath))) {
1171
+ const parentMark = sessionMarkPath({ conversationId: process.env.AGY_PARENT_CONVERSATION_ID });
1172
+ const active = mode === "enforce" || [markPath, parentMark].some(p => p && fs.existsSync(p));
1173
+ if (active || process.env.DEEPMODEBOT_WORKER_ID) {
1174
+ const holdoutHit = SHELL_TOOLS.has(toolName)
1175
+ ? holdoutCommandHit(String(args.CommandLine ?? args.command ?? args.cmd ?? ""), ruleCwd)
1176
+ : holdoutToolHit(toolName, args, sessionCwd);
1177
+ if (holdoutHit) {
1178
+ writeJsonAndExit({ decision: "deny", reason: holdoutReason(holdoutHit) });
1179
+ return;
1180
+ }
1181
+ }
1182
+ if (!active) {
491
1183
  writeJsonAndExit({ decision: "allow" });
492
1184
  return;
493
1185
  }
494
1186
 
1187
+ if (toolName === "invoke_subagent") {
1188
+ writeJsonAndExit(spawnVerdict(args));
1189
+ return;
1190
+ }
1191
+
495
1192
  if (SHELL_TOOLS.has(toolName)) {
496
1193
  const cmdStr = args.CommandLine ?? args.command ?? args.cmd ?? "";
497
1194
  const hit = findShellRewardHack(cmdStr);
@@ -527,7 +1224,13 @@ function main() {
527
1224
  }
528
1225
  }
529
1226
 
530
- const resolvedTarget = real(absolute(target.trim(), cwd));
1227
+ const absTarget = absolute(target.trim(), cwd);
1228
+ const sliceReason = sliceDenyReason(roots[0], absTarget);
1229
+ if (sliceReason) {
1230
+ writeJsonAndExit({ decision: "deny", reason: sliceReason });
1231
+ return;
1232
+ }
1233
+ const resolvedTarget = real(absTarget);
531
1234
  const allowed = allowedRoots(roots, event);
532
1235
  if (allowed.some(r => inside(resolvedTarget, r))) {
533
1236
  writeJsonAndExit({ decision: "allow" });