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
@@ -4,10 +4,15 @@
4
4
  // Roots = the worktree holding the session cwd plus its main checkout (they differ in a linked worktree, e.g. one
5
5
  // under <root>/.worktrees/ or an Orca workspace), or the cwd outside git. Also allowed: omp session resources
6
6
  // (local://, artifact://, agent://, proc://, xd://, out://, conflict://, cfg://) and `extraWriteRoots` in a root's
7
- // .deepmodebot.json (only paths the user named). eval is not covered.
8
- // Rule approval (../rules/rule_ledger.py): in a repo whose owner turned it on, write/edit/ast_edit on agent rule
9
- // files or the ledger are blocked, and so are bash commands that write them; the owner-only
10
- // `rules init|approve|reject|rotate` commands are blocked everywhere. Other bash commands pass.
7
+ // .deepmodebot.json (only paths the user named). Shell and eval get reward-hacking checks, not path containment.
8
+ // Every tool call (read, grep, glob, find, shell, eval, writes) that reaches the hidden holdout store (~/.deepmodebot-holdout
9
+ // in any spelling) or mines git answers (cat-file --batch-all-objects, fsck, reflog recovery, raw .git/objects reads,
10
+ // sweeps of / ~ /tmp for tests) is blocked with the anti-reward-hacking message.
11
+ // Rule approval (../rules/rule_ledger.py): in a repo whose owner turned it on, and for the user-level agent rules
12
+ // (~/.omp/agent hooks and skills, ~/.claude settings, ...) once the owner ran `deepmodebot rules init --user`,
13
+ // write/edit/ast_edit on agent rule files or the ledger are blocked, and so are bash commands that write them; the
14
+ // owner-only `rules init|approve|reject` commands are blocked everywhere. Rule approval blocks notify the owner;
15
+ // session_start shows the owner any rule changes they have not approved (../rules/rules_watch.py).
11
16
  import { execFileSync } from "node:child_process";
12
17
  import * as fs from "node:fs";
13
18
  import * as os from "node:os";
@@ -22,22 +27,102 @@ const ANY_URL = /^[a-z][a-z0-9+.-]*:\/\//i;
22
27
  const caseless = process.platform === "win32" || process.platform === "darwin";
23
28
  const RULES_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "rules");
24
29
  const RULE_LEDGER = path.join(RULES_DIR, "rule_ledger.py");
30
+ const RULES_WATCH = path.join(RULES_DIR, "rules_watch.py");
25
31
  const LEDGER_REL = path.join(".deepmodebot", "rules", "ledger.json");
26
32
  const PYTHONS: [string, string[]][] =
27
33
  process.platform === "win32"
28
34
  ? [["py", ["-3", "-B"]], ["python3", ["-B"]], ["python", ["-B"]]]
29
35
  : [["python3", ["-B"]], ["python", ["-B"]]];
30
36
  const RULES = loadRuleSpec();
37
+ const OVERHEAD_AGENTS: Record<string, true> = {
38
+ scout: true, researcher: true, reviewer: true, "security-reviewer": true, "comment-sicko": true,
39
+ };
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.";
41
+ const METRIC_FLOORS: Record<string, number> = {
42
+ iou: 0.5, ssim: 0.5, dice: 0.5, f1: 0.5, auc: 0.5,
43
+ accuracy: 0.5, acc: 0.5, precision: 0.5, recall: 0.5,
44
+ fidelity: 0.5, similarity: 0.5, coverage: 0.5, "pass-rate": 0.5, "win-rate": 0.5,
45
+ clip: 0.15, "clip-score": 0.15, ap: 0.15, map: 0.15, bleu: 0.15, rouge: 0.15,
46
+ psnr: 10.0, protrusion: 0.02, score: 0.05, confidence: 0.05, symmetry: 0.05,
47
+ "cov-fail-under": 50.0,
48
+ };
49
+ const MIN_FLAG_VAL_RE =
50
+ /(?:^|[\s;&|(])(['"]?--(?:(?:gate-)?mi(?:n(?:-([a-z0-9_-]*))?)?|(cov-fail-under))['"]?(?:\s+|=)['"]?\s*([-+]?(?:inf(?:inity)?|nan|(?:\d[\d_]*\.?[\d_]*|\.[\d_]+)(?:e[-+]?[\d_]+)?))\s*['"]?)(?=$|[\s;&|)])/gi;
51
+ const REWARD_HACK_CMD_RE = new RegExp(
52
+ [
53
+ 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;&|)])`,
54
+ String.raw`(?:^|[\s;&|(])['"]?(?:--require-spark-receipt(?:\s+|=)['"]?false|--gate-mode(?:\s+|=)['"]?off|--measured-gates(?:\s+|=)['"]?off|--check-360(?:\s+|=)['"]?(?:false|0))['"]?(?=$|[\s;&|)])`,
55
+ 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;&|)])`,
56
+ String.raw`\bgit\b[^\n;&|]*\bcommit\b[^\n;&|]*\s['"]?(?:-n|--no-verify)['"]?(?=$|[\s;&|)])`,
57
+ String.raw`\b(?:reward-guard\.db|contract-lock\.json|judge_verdicts)\b`,
58
+ String.raw`\breward_guard\.py\b[^\n;&|]*\brecord-judge\b`,
59
+ ].join("|"),
60
+ "i",
61
+ );
62
+
63
+ function minFlagFloor(rawTok: string | undefined): number | null {
64
+ const tok = (rawTok ?? "").toLowerCase().replace(/_/g, "-");
65
+ if (!tok) return 0.5;
66
+ if (tok === "p" || tok === "k" || tok === "port" || tok === "ports") return null;
67
+ if (Object.hasOwn(METRIC_FLOORS, tok)) return METRIC_FLOORS[tok];
68
+ const matches = Object.entries(METRIC_FLOORS)
69
+ .filter(([k]) => k.startsWith(tok))
70
+ .map(([, v]) => v);
71
+ return matches.length ? Math.max(...matches) : null;
72
+ }
73
+
74
+ function parseGuardFloat(raw: string): number {
75
+ const c = String(raw).trim().replace(/_/g, "");
76
+ if (/^[-+]?inf(?:inity)?$/i.test(c)) return c.startsWith("-") ? -Infinity : Infinity;
77
+ if (/^[-+]?nan$/i.test(c)) return NaN;
78
+ return Number(c);
79
+ }
80
+
81
+ function findShellRewardHack(rawCmd: unknown): string | null {
82
+ const cleaned = String(rawCmd ?? "").replace(/(-m|--message)(=|\s+)("[^"]*"|'[^']*')/g, '$1 ""');
83
+ for (const rawLine of cleaned.replace(/\\\r?\n/g, " ").split(/\r?\n/)) {
84
+ const line = rawLine.trim();
85
+ if (!line || /^(?:grep|rg|echo|printf)\s+[^;&|<>()`$]*$/.test(line)) continue;
86
+ MIN_FLAG_VAL_RE.lastIndex = 0;
87
+ let fm: RegExpExecArray | null;
88
+ while ((fm = MIN_FLAG_VAL_RE.exec(line)) !== null) {
89
+ const floor = minFlagFloor(fm[3] || fm[2]);
90
+ const val = parseGuardFloat(fm[4]);
91
+ if (floor !== null && (!Number.isFinite(val) || val < floor)) return fm[1].trim();
92
+ }
93
+ const m = REWARD_HACK_CMD_RE.exec(line);
94
+ if (m) return m[0].trim();
95
+ }
96
+ return null;
97
+ }
98
+
99
+ function nestedSpawn(): boolean {
100
+ const { TEAMWORK_RUN_ID, SWARM_ID, DEEPMODEBOT_SUBAGENT_DEPTH, DEEPMODEBOT_MAX_SUBAGENTS } = process.env;
101
+ return Boolean(TEAMWORK_RUN_ID || SWARM_ID || (DEEPMODEBOT_SUBAGENT_DEPTH && DEEPMODEBOT_SUBAGENT_DEPTH !== "0")
102
+ || DEEPMODEBOT_MAX_SUBAGENTS === "0");
103
+ }
31
104
 
32
105
  interface ToolCallEvent {
33
106
  toolName: string;
34
107
  input?: Record<string, unknown>;
35
108
  }
36
109
 
37
- type ToolCallResult = { block: true; reason: string } | undefined;
110
+ type Block = { block: true; reason: string };
111
+ type ToolCallResult = Block | { input: Record<string, unknown> } | undefined;
112
+
113
+ interface HookContext {
114
+ cwd?: string;
115
+ ui?: { notify?(message: string, type?: string): void; setStatus?(key: string, text: string | undefined): void };
116
+ }
38
117
 
39
118
  interface HookApi {
40
119
  on(event: "tool_call", handler: (event: ToolCallEvent, ctx: { cwd?: string }) => Promise<ToolCallResult>): void;
120
+ on(event: "session_start", handler: (event: unknown, ctx: HookContext) => Promise<void>): void;
121
+ on(
122
+ event: "before_subagent_spawn",
123
+ handler: (event: { agent: string; modelRole?: string; patterns?: string[] }) =>
124
+ Promise<{ model?: string | string[]; block?: boolean; reason?: string; note?: string } | undefined>,
125
+ ): void;
41
126
  }
42
127
 
43
128
  // Absolute form of a path as omp would open it: `~` is the home folder, anything relative hangs off cwd.
@@ -46,16 +131,16 @@ function absolute(p: string, cwd: string): string {
46
131
  return path.resolve(cwd, expanded);
47
132
  }
48
133
 
49
- function real(p: string): string {
134
+ function real(p: string, fold = caseless): string {
50
135
  let resolved = path.resolve(p);
51
136
  try {
52
137
  resolved = fs.realpathSync.native(resolved);
53
138
  } catch {
54
139
  // Target may not exist yet; resolve its nearest existing parent so symlinked parents still count.
55
140
  const parent = path.dirname(resolved);
56
- if (parent !== resolved) resolved = path.join(real(parent), path.basename(resolved));
141
+ if (parent !== resolved) resolved = path.join(real(parent, fold), path.basename(resolved));
57
142
  }
58
- return caseless ? resolved.toLowerCase() : resolved;
143
+ return fold ? resolved.toLowerCase() : resolved;
59
144
  }
60
145
 
61
146
  function inside(p: string, root: string): boolean {
@@ -65,6 +150,62 @@ function inside(p: string, root: string): boolean {
65
150
  return !path.isAbsolute(rel);
66
151
  }
67
152
 
153
+ function escapeRegex(text: string): string {
154
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
155
+ }
156
+
157
+ function compileOwnedGlob(value: unknown): RegExp {
158
+ if (typeof value !== "string") throw new Error("owned_globs entries must be strings");
159
+ const glob = value.trim().replace(/\\/g, "/").replace(/\/+$/, "");
160
+ const parts = glob.split("/");
161
+ if (/^[a-z]:/i.test(glob) || glob.includes("\0") || parts.some(p => !p || p === "." || p === "..")) {
162
+ throw new Error("owned_globs must contain only repo-relative glob patterns");
163
+ }
164
+ const expr = /[*?]/.test(glob)
165
+ ? parts.map(part => part === "**" ? "(?:/[^/]+)*"
166
+ : "/" + Array.from(part, c => c === "*" ? "[^/]*" : c === "?" ? "[^/]" : escapeRegex(c)).join("")).join("")
167
+ : "/" + escapeRegex(glob) + "(?:/[\\s\\S]*)?";
168
+ return new RegExp("^" + expr + "(?![\\s\\S])", process.platform === "win32" ? "iu" : "u");
169
+ }
170
+
171
+ function sliceWriteBlock(root: string, cwd: string, paths: string[]): Block | undefined {
172
+ const worker = process.env.DEEPMODEBOT_WORKER_ID;
173
+ if (!worker) return;
174
+ if (!/^[A-Za-z0-9._-]+(?![\s\S])/.test(worker)) return { block: true, reason: "deepmodebot: invalid worker ID" };
175
+ const slicePath = path.join(root, ".scratch", "slices", `${worker}.json`);
176
+ let manifest: unknown;
177
+ try {
178
+ manifest = JSON.parse(fs.readFileSync(slicePath, "utf8"));
179
+ } catch (error) {
180
+ if (error && typeof error === "object" && "code" in error && error.code === "ENOENT") return;
181
+ return { block: true, reason: `deepmodebot: cannot read slice manifest ${slicePath}: ${String(error)}` };
182
+ }
183
+ try {
184
+ if (!manifest || typeof manifest !== "object" || !("schema_version" in manifest) || manifest.schema_version !== 1
185
+ || !("worker_id" in manifest) || manifest.worker_id !== worker
186
+ || !("build_owner" in manifest) || typeof manifest.build_owner !== "boolean"
187
+ || !("owned_globs" in manifest) || !Array.isArray(manifest.owned_globs) || !manifest.owned_globs.length) {
188
+ throw new Error("invalid slice manifest");
189
+ }
190
+ const globs = manifest.owned_globs.map(compileOwnedGlob);
191
+ const permits = (base: string, candidate: string) => {
192
+ if (!inside(candidate, base)) return false;
193
+ const rel = path.relative(base, candidate).split(path.sep).join("/");
194
+ const scratch = process.platform === "win32" ? rel.toLowerCase() : rel;
195
+ return scratch === ".scratch" || scratch.startsWith(".scratch/") || globs.some(glob => glob.test("/" + rel));
196
+ };
197
+ const realRoot = real(root, false);
198
+ for (const target of paths) {
199
+ const abs = absolute(target, cwd);
200
+ if (ANY_URL.test(target) || !permits(root, abs) || !permits(realRoot, real(abs, false))) {
201
+ return { block: true, reason: `deepmodebot: ${target} is outside the owned slice for ${worker}` };
202
+ }
203
+ }
204
+ } catch (error) {
205
+ return { block: true, reason: `deepmodebot: invalid slice manifest ${slicePath}: ${String(error)}` };
206
+ }
207
+ }
208
+
68
209
  // The worktree holding cwd first, then the main checkout.
69
210
  function projectRoots(cwd: string): string[] {
70
211
  try {
@@ -115,17 +256,33 @@ function loadRuleSpec() {
115
256
  const names = low(spec.names);
116
257
  const dirs = low(spec.dirs);
117
258
  const files = low(spec.files);
259
+ const userFiles = low(spec.user?.files);
260
+ const userDirs = low(spec.user?.dirs);
118
261
  return {
119
262
  names: new Set(names),
120
263
  dirs: dirs.map(d => `/${d}/`),
121
264
  files: files.map(f => `/${f}`),
122
- hints: [...names, ...files, ...dirs, ...dirs.map(d => d.split("/")[0]), "deepmodebot", "rule_ledger"],
265
+ userFiles: new Set(userFiles),
266
+ userDirs: userDirs.map(d => `${d}/`),
267
+ hints: [
268
+ ...names, ...files, ...dirs, ...dirs.map(d => d.split("/")[0]),
269
+ ...userFiles, ...userDirs, "deepmodebot", "rule_ledger",
270
+ ],
123
271
  };
124
272
  } catch {
125
273
  return undefined;
126
274
  }
127
275
  }
128
276
 
277
+ // A user-level agent rule: a `user` path of rule-paths.json under the home folder.
278
+ function isUserRulePath(abs: string): boolean {
279
+ const home = real(os.homedir()).replace(/\\/g, "/").toLowerCase();
280
+ const p = abs.replace(/\\/g, "/").toLowerCase();
281
+ if (!RULES || !p.startsWith(`${home}/`)) return false;
282
+ const rel = p.slice(home.length + 1);
283
+ return RULES.userFiles.has(rel) || RULES.userDirs.some(d => rel.startsWith(d));
284
+ }
285
+
129
286
  function mayBeRulePath(abs: string): boolean {
130
287
  if (!RULES) return false;
131
288
  const p = abs.toLowerCase().replace(/\\/g, "/");
@@ -133,7 +290,8 @@ function mayBeRulePath(abs: string): boolean {
133
290
  RULES.names.has(p.slice(p.lastIndexOf("/") + 1)) ||
134
291
  p.includes("/.deepmodebot/rules") ||
135
292
  RULES.dirs.some(d => p.includes(d)) ||
136
- RULES.files.some(f => p.endsWith(f))
293
+ RULES.files.some(f => p.endsWith(f)) ||
294
+ isUserRulePath(abs)
137
295
  );
138
296
  }
139
297
 
@@ -149,20 +307,18 @@ function ledgerNear(abs: string): boolean {
149
307
  }
150
308
  }
151
309
 
152
- // rule_ledger.py guard verdict: a deny reason, "" to allow, or null when no Python could run it.
153
- function pythonGuard(request: { cwd: string; paths: string[]; command: string }): string | null {
310
+ // Output of a Python helper, "" when it failed, or null when no Python could run it.
311
+ function runPython(script: string, args: string[], input: string, timeout: number): string | null {
154
312
  for (const [exe, prefix] of PYTHONS) {
155
313
  try {
156
- const out = execFileSync(exe, [...prefix, RULE_LEDGER, "guard"], {
157
- input: JSON.stringify(request),
314
+ return execFileSync(exe, [...prefix, script, ...args], {
315
+ input,
158
316
  encoding: "utf8",
159
- timeout: 15_000,
317
+ timeout,
160
318
  stdio: ["pipe", "pipe", "ignore"],
161
319
  windowsHide: true,
162
320
  env: { ...process.env, PYTHONDONTWRITEBYTECODE: "1" },
163
321
  });
164
- const verdict = JSON.parse(out);
165
- return verdict && verdict.block ? String(verdict.reason) : "";
166
322
  } catch (err) {
167
323
  if (err && typeof err === "object" && "code" in err && err.code === "ENOENT") continue;
168
324
  return "";
@@ -171,9 +327,21 @@ function pythonGuard(request: { cwd: string; paths: string[]; command: string })
171
327
  return null;
172
328
  }
173
329
 
330
+ // rule_ledger.py guard verdict: a deny reason, "" to allow, or null when no Python could run it.
331
+ function pythonGuard(request: { cwd: string; paths: string[]; command: string }): string | null {
332
+ const out = runPython(RULE_LEDGER, ["guard"], JSON.stringify(request), 15_000);
333
+ if (out === null) return null;
334
+ try {
335
+ const verdict = JSON.parse(out);
336
+ return verdict && verdict.block ? String(verdict.reason) : "";
337
+ } catch {
338
+ return "";
339
+ }
340
+ }
341
+
174
342
  // Python runs only for shell commands in a ledger repo or naming a rule path or owner command, and for writes whose
175
343
  // target (or resolved target) looks like a rule path.
176
- function ruleBlock(cwd: string, paths: string[], command: string): ToolCallResult {
344
+ function ruleBlock(cwd: string, paths: string[], command: string): Block | undefined {
177
345
  const candidates = paths.filter(p => mayBeRulePath(absolute(p, cwd)) || mayBeRulePath(real(absolute(p, cwd))));
178
346
  const lowered = command.toLowerCase().replace(/\\/g, "/");
179
347
  const shell =
@@ -181,25 +349,608 @@ function ruleBlock(cwd: string, paths: string[], command: string): ToolCallResul
181
349
  if (candidates.length === 0 && !shell) return undefined;
182
350
  const verdict = pythonGuard({ cwd, paths: candidates, command: shell ? command : "" });
183
351
  if (verdict === null) {
184
- if (!candidates.some(p => ledgerNear(absolute(p, cwd)))) return undefined;
352
+ const userOn = fs.existsSync(path.join(os.homedir(), LEDGER_REL));
353
+ if (!candidates.some(p => ledgerNear(absolute(p, cwd)) || (userOn && isUserRulePath(absolute(p, cwd))))) return undefined;
185
354
  return { block: true, reason: "deepmodebot rule approval needs Python 3 on PATH to check rule files; install it, then retry." };
186
355
  }
187
356
  return verdict ? { block: true, reason: verdict } : undefined;
188
357
  }
189
358
 
359
+ type Segs = string[];
360
+ type GitCall = [string, string[]];
361
+ type Stage = { words: string[]; ops: Segs[]; start: Segs; git: GitCall[]; lead: number };
362
+ type Links = { feeders: [number, number][]; sinks: [number, number][] };
363
+
364
+ const HOLDOUT_DIR = ".deepmodebot-holdout";
365
+ const HOLDOUT_FALLBACK = "deepmodebot-holdout";
366
+ const onWindows = process.platform === "win32";
367
+ const TMP_ROOTS = ["/tmp", "/var/tmp", "/private/tmp", "/var/folders", "/private/var/folders", "c:/windows/temp"];
368
+ const HOME_SPELLING_RE =
369
+ /^(?:~|\$\{?(?:home|userprofile)\}?|%(?:home|userprofile)%|\$\{?env:(?:home|userprofile)\}?|%homedrive%%homepath%|\$\{?(?:env:)?homedrive\}?\$\{?(?:env:)?homepath\}?)(?=\/|$)/i;
370
+ const LOCAL_SPELLING_RE = /^(?:\$\{?(?:env:)?localappdata\}?|%localappdata%)(?=\/|$)/i;
371
+ const GIT_RAW_RE = /(?:^|\/)[^/]*\.git\/(?:objects|logs|lost-found)(?:\/|$)|(?:^|\/)objects\/(?:pack|info|[0-9a-f]{2})(?:\/|$)/i;
372
+ const GLOB_RE = /[*?[]/;
373
+ const TEST_RE = /(?:^|[^a-z0-9])(?:tests?|specs?|holdouts?|hidden|golden|graders?|solutions?|answers?|expected|fixtures?)(?:[^a-z0-9]|$)/i;
374
+ 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.]*$/;
375
+ const LOOP_RE = /(?:^|[\s;&|(])(?:for|while|until|read|xargs)(?=$|[\s;&|)])/;
376
+ const COMMAND_PREFIXES = new Set(["sudo", "time", "command", "env", "nohup", "exec", "builtin", "nice", "then", "do", "else", "{"]);
377
+ const CD_COMMANDS = new Set(["cd", "pushd", "chdir", "sl", "set-location"]);
378
+ const GREP_FAMILY = new Set(["grep", "egrep", "fgrep", "rg", "ag", "ack", "sls", "select-string"]);
379
+ const ENUMERATORS = new Set(["find", "fd", "fdfind", "ls", "dir", "tree", "gci", "get-childitem", "locate", "mlocate"]);
380
+ const CONTENT_READERS = new Set([
381
+ "cat", "type", "head", "tail", "less", "more", "xargs", "strings", "bat", "tac", "nl", "od", "xxd", "hexdump",
382
+ "get-content", "gc", "select-string", "sls", "findstr",
383
+ ]);
384
+ const ALWAYS_RECURSIVE = new Set(["rg", "ag", "ack", "zip", "7z", "7za", "rsync", "robocopy", "xcopy"]);
385
+ const GREP_ARG_FLAGS = new Set([
386
+ "-e", "-f", "-m", "-A", "-B", "-C", "-g", "-t", "-T", "-j", "-M", "-d", "-D", "--regexp", "--file", "--max-count",
387
+ "--after-context", "--before-context", "--context", "--glob", "--iglob", "--type", "--type-not", "--include",
388
+ "--exclude", "--exclude-dir", "--include-dir", "--max-depth", "--threads", "-pattern", "-path", "-literalpath",
389
+ ]);
390
+ const GIT_GLOBAL_ARG_FLAGS = new Set(["-C", "-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env"]);
391
+ const GIT_DENIED_SUBCOMMANDS = new Set(["unpack-file", "prune", "show-index", "verify-pack", "lost-found"]);
392
+ const GIT_REFLOG_SUBCOMMANDS = new Set(["log", "show", "rev-list", "whatchanged", "shortlog", "format-patch", "diff", "archive", "grep"]);
393
+ const GIT_CONTENT_SUBCOMMANDS = new Set(["show", "diff", "format-patch", "archive", "grep"]);
394
+ const GIT_RECOVER_SUBCOMMANDS = new Set([
395
+ "show", "cat-file", "checkout", "restore", "switch", "cherry-pick", "archive", "diff", "format-patch", "read-tree",
396
+ "reset", "merge", "branch", "tag", "update-ref", "worktree", "apply",
397
+ ]);
398
+ const GIT_CONTENT_FLAGS = [
399
+ "--patch", "--patch-with-stat", "--patch-with-raw", "--cc", "--stat", "--numstat", "--shortstat", "--raw", "--name-only",
400
+ "--name-status", "--full-diff", "--pickaxe-regex", "--pickaxe-all", "--word-diff", "--textconv", "--objects",
401
+ "--summary", "--dirstat",
402
+ ];
403
+ const TOOL_PATH_KEYS = new Set([
404
+ "path", "paths", "filepath", "file", "files", "notebookpath", "directory", "dir", "cwd", "root", "targetfile",
405
+ "searchpath", "searchdirectory", "directorypath", "absolutepath", "abspath", "workdir", "filename",
406
+ ]);
407
+ const TOOL_PATTERN_KEYS = new Set(["glob", "include", "pattern"]);
408
+ const SEARCH_TOOL_RE = /grep|glob|find|^ls$|list|tree|walk|^dir$|^rg$/i;
409
+
410
+ function holdoutReason(hit: string): string {
411
+ 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.`;
412
+ }
413
+
414
+ function homeDirs(): string[] {
415
+ const env = process.env;
416
+ const found: string[] = [];
417
+ for (const home of [env.HOME, env.USERPROFILE, `${env.HOMEDRIVE ?? ""}${env.HOMEPATH ?? ""}`, os.homedir()]) {
418
+ if (home && home !== "~" && !found.includes(home)) found.push(home);
419
+ }
420
+ return found;
421
+ }
422
+
423
+ function prepPath(p: string): string {
424
+ let text = p.replace(/\\/g, "/");
425
+ text = text.replace(/^file:\/{2,3}(?:localhost\/)?/i, "/");
426
+ if (/^\/[A-Za-z]:/.test(text)) text = text.slice(1);
427
+ text = text.replace(/^\/\/[?.]\//, "");
428
+ text = text.replace(/^\/\/(?:localhost|127\.0\.0\.1)\/([A-Za-z])\$(?=\/|$)/i, "$1:");
429
+ if (onWindows) {
430
+ text = text.replace(/^\/(?:mnt|cygdrive)\/([A-Za-z])(?=\/|$)/, "$1:");
431
+ text = text.replace(/^\/([A-Za-z])(?=\/)/, "$1:");
432
+ }
433
+ return text;
434
+ }
435
+
436
+ function toSegs(p: string): Segs | null {
437
+ const text = prepPath(p);
438
+ const drive = /^[A-Za-z]:(?=\/|$)/.exec(text);
439
+ let root: string;
440
+ let rest: string;
441
+ if (drive) {
442
+ root = drive[0];
443
+ rest = text.slice(drive[0].length);
444
+ } else if (text.startsWith("/")) {
445
+ root = onWindows ? process.cwd().slice(0, 2) : "/";
446
+ rest = text;
447
+ } else {
448
+ return null;
449
+ }
450
+ const out: string[] = [];
451
+ for (let part of rest.split("/")) {
452
+ if (part === "" || part === ".") continue;
453
+ if (part === "..") {
454
+ out.pop();
455
+ continue;
456
+ }
457
+ if (onWindows) {
458
+ part = part.split(":")[0].replace(/[. ]+$/, "");
459
+ if (!part) continue;
460
+ }
461
+ out.push(part);
462
+ }
463
+ return caseless ? [root.toLowerCase(), ...out.map(part => part.toLowerCase())] : [root, ...out];
464
+ }
465
+
466
+ function joinSegs(segs: Segs): string {
467
+ return (segs[0] !== "/" ? segs[0] : "") + "/" + segs.slice(1).join("/");
468
+ }
469
+
470
+ function toAbs(text: string, cwd: Segs): Segs {
471
+ return toSegs(text) ?? toSegs(joinSegs(cwd) + "/" + prepPath(text)) ?? cwd;
472
+ }
473
+
474
+ function realpathLoose(p: string): string {
475
+ try {
476
+ return fs.realpathSync.native(p);
477
+ } catch {
478
+ const parent = path.dirname(p);
479
+ return parent === p ? p : path.join(realpathLoose(parent), path.basename(p));
480
+ }
481
+ }
482
+
483
+ function realSegs(text: string, cwd: Segs): Segs | null {
484
+ const raw = prepPath(text);
485
+ return toSegs(realpathLoose(toSegs(raw) ? raw : joinSegs(cwd) + "/" + raw));
486
+ }
487
+
488
+ function sameSegs(a: Segs, b: Segs): boolean {
489
+ return a.length === b.length && a.every((part, i) => part === b[i]);
490
+ }
491
+
492
+ function startsWithSegs(segs: Segs, prefix: Segs): boolean {
493
+ return segs.length >= prefix.length && prefix.every((part, i) => part === segs[i]);
494
+ }
495
+
496
+ function uniqueSegs(paths: string[]): Segs[] {
497
+ const found: Segs[] = [];
498
+ for (const p of paths) {
499
+ for (const segs of [toSegs(p), toSegs(realpathLoose(p))]) {
500
+ if (segs && !found.some(f => sameSegs(f, segs))) found.push(segs);
501
+ }
502
+ }
503
+ return found;
504
+ }
505
+
506
+ function expandBraces(text: string, cap = 64): string[] {
507
+ const match = /\{([^{}]*,[^{}]*)\}/.exec(text);
508
+ if (!match) return [text];
509
+ const out: string[] = [];
510
+ for (const alt of match[1].split(",")) {
511
+ out.push(...expandBraces(text.slice(0, match.index) + alt + text.slice(match.index + match[0].length), cap));
512
+ if (out.length >= cap) break;
513
+ }
514
+ return out.slice(0, cap);
515
+ }
516
+
517
+ function wordVariants(word: string): string[] {
518
+ const out = [word];
519
+ for (let i = word.indexOf("="); i !== -1; i = word.indexOf("=", i + 1)) out.push(word.slice(i + 1));
520
+ for (const match of word.matchAll(/:(?=[~$%/\\])/g)) out.push(word.slice((match.index ?? 0) + 1));
521
+ return out.filter((v, i) => v !== "" && !out.slice(0, i).includes(v));
522
+ }
523
+
524
+ function segMatch(glob: string, name: string): boolean {
525
+ if (!GLOB_RE.test(glob)) return glob === name;
526
+ if ("*?[".includes(glob[0]) && name.startsWith(".")) return false;
527
+ let out = "";
528
+ for (let i = 0; i < glob.length; i++) {
529
+ const ch = glob[i];
530
+ const close = ch === "[" ? glob.indexOf("]", i + 2) : -1;
531
+ if (ch === "*") {
532
+ out += "[^/]*";
533
+ } else if (ch === "?") {
534
+ out += "[^/]";
535
+ } else if (close !== -1) {
536
+ const body = glob.slice(i + 1, close);
537
+ out += "[" + (body[0] === "!" || body[0] === "^" ? "^" + body.slice(1) : body).replace(/\\/g, "\\\\") + "]";
538
+ i = close;
539
+ } else {
540
+ out += escapeRegex(ch);
541
+ }
542
+ }
543
+ try {
544
+ return new RegExp("^" + out + "$").test(name);
545
+ } catch {
546
+ return true;
547
+ }
548
+ }
549
+
550
+ function namedLiteral(seg: string): boolean {
551
+ return !GLOB_RE.test(seg) || seg.replace(/[.*?[\]!^-]/g, "") !== "";
552
+ }
553
+
554
+ function globMatch(glob: Segs, i: number, root: Segs, j: number): boolean {
555
+ if (j === root.length) return i < glob.length || (i > 0 && namedLiteral(glob[i - 1]));
556
+ if (i === glob.length) return false;
557
+ if (glob[i] === "**") return globMatch(glob, i + 1, root, j) || globMatch(glob, i, root, j + 1);
558
+ return segMatch(glob[i], root[j]) && globMatch(glob, i + 1, root, j + 1);
559
+ }
560
+
561
+ function wordBase(word: string): string {
562
+ const name = (word.replace(/\\/g, "/").split("/").pop() ?? "").toLowerCase();
563
+ return name.endsWith(".exe") ? name.slice(0, -4) : name;
564
+ }
565
+
566
+ function leadIndex(words: string[]): number {
567
+ let prefixed = false;
568
+ for (let i = 0; i < words.length; i++) {
569
+ if (/^[A-Za-z_]\w*=/.test(words[i]) || COMMAND_PREFIXES.has(wordBase(words[i]))) prefixed = true;
570
+ else if (!(prefixed && words[i].startsWith("-"))) return i;
571
+ }
572
+ return words.length;
573
+ }
574
+
575
+ function optIs(token: string, full: string, minLen: number): boolean {
576
+ const name = token.split("=")[0];
577
+ return name.startsWith("--") && name.length >= minLen && full.startsWith(name);
578
+ }
579
+
580
+ class HoldoutScan {
581
+ homes = homeDirs();
582
+ cwd: Segs;
583
+ roots: Segs[];
584
+ tmp: Segs[];
585
+ realBudget = 200;
586
+
587
+ constructor(cwd: string) {
588
+ this.cwd = toSegs(cwd) ?? toSegs(process.cwd()) ?? ["/"];
589
+ const stores = this.homes.map(home => path.join(home, HOLDOUT_DIR));
590
+ const local = process.env.LOCALAPPDATA;
591
+ if (local) stores.push(path.join(local, HOLDOUT_FALLBACK));
592
+ stores.push("/tmp/" + HOLDOUT_FALLBACK);
593
+ this.roots = uniqueSegs(stores);
594
+ this.tmp = uniqueSegs([...TMP_ROOTS, ...this.homes.map(home => path.join(home, "AppData", "Local", "Temp"))]);
595
+ }
596
+
597
+ expand(item: string): string[] {
598
+ const match = HOME_SPELLING_RE.exec(item);
599
+ if (match) return this.homes.length ? this.homes.map(home => home + item.slice(match[0].length)) : [item];
600
+ const local = process.env.LOCALAPPDATA;
601
+ const localMatch = LOCAL_SPELLING_RE.exec(item);
602
+ return localMatch && local ? [local + item.slice(localMatch[0].length)] : [item];
603
+ }
604
+
605
+ candidates(word: string, cwd: Segs): Segs[] {
606
+ const found: Segs[] = [];
607
+ for (const variant of wordVariants(word.replace(/\\/g, "/"))) {
608
+ for (const item of expandBraces(variant)) {
609
+ for (const text of this.expand(item)) {
610
+ found.push(toAbs(text, cwd));
611
+ if (this.realBudget > 0 && prepPath(text).includes("/") && !GLOB_RE.test(text)) {
612
+ this.realBudget -= 1;
613
+ const real = realSegs(text, cwd);
614
+ if (real) found.push(real);
615
+ }
616
+ }
617
+ }
618
+ }
619
+ return found;
620
+ }
621
+
622
+ reaches(cands: Segs[]): boolean {
623
+ return cands.some(c => this.roots.some(r => globMatch(c, 0, r, 0)));
624
+ }
625
+
626
+ above(cands: Segs[], widen = false): boolean {
627
+ return cands.map(c => (widen ? literalHead(c) : c))
628
+ .some(h => !h.some(s => GLOB_RE.test(s)) && this.roots.some(r => startsWithSegs(r, h)));
629
+ }
630
+
631
+ inTmp(segs: Segs): boolean {
632
+ return this.tmp.some(t => startsWithSegs(segs, t)) && !startsWithSegs(segs, this.cwd);
633
+ }
634
+ }
635
+
636
+ function literalHead(segs: Segs): Segs {
637
+ const i = segs.findIndex(seg => GLOB_RE.test(seg));
638
+ return i === -1 ? segs : segs.slice(0, i);
639
+ }
640
+
641
+ function computedHome(word: string): boolean {
642
+ for (const variant of wordVariants(word)) {
643
+ const match = HOME_SPELLING_RE.exec(variant);
644
+ const first = match ? variant.slice(match[0].length).replace(/^\/+/, "").split("/")[0] : "";
645
+ if (first && /\$|%[A-Za-z_]\w*%/.test(first)) return true;
646
+ }
647
+ return false;
648
+ }
649
+
650
+ function grepSkips(words: string[]): Set<number> {
651
+ const skips = new Set<number>();
652
+ for (let i = 0; i < words.length; i++) {
653
+ const name = wordBase(words[i]);
654
+ if (!GREP_FAMILY.has(name)) continue;
655
+ let k = i + 1;
656
+ let havePattern = false;
657
+ while (k < words.length && words[k].startsWith("-") && words[k] !== "-" && words[k] !== "--") {
658
+ const flag = words[k].length <= 2 ? words[k] : words[k].toLowerCase();
659
+ if (flag.startsWith("--regexp=")) {
660
+ skips.add(k);
661
+ havePattern = true;
662
+ }
663
+ if (flag === "-e" || flag === "--regexp" || flag === "-pattern") {
664
+ havePattern = true;
665
+ skips.add(k + 1);
666
+ }
667
+ k += GREP_ARG_FLAGS.has(flag) || (name === "rg" && flag === "-r") ? 2 : 1;
668
+ }
669
+ if (k < words.length && words[k] === "--") k += 1;
670
+ if (!havePattern && k < words.length) skips.add(k);
671
+ }
672
+ return skips;
673
+ }
674
+
675
+ function contentFlag(token: string): boolean {
676
+ return GIT_CONTENT_FLAGS.some(full => optIs(token, full, 4)) || /^-\d*[pu]$/.test(token)
677
+ || token.startsWith("-S") || token.startsWith("-G");
678
+ }
679
+
680
+ function gitCalls(words: string[]): GitCall[] {
681
+ const calls: GitCall[] = [];
682
+ for (let i = 0; i < words.length; i++) {
683
+ const name = wordBase(words[i]);
684
+ const dashed = /^git-([a-z-]+)$/.exec(name);
685
+ if (dashed) {
686
+ calls.push([dashed[1], words.slice(i + 1)]);
687
+ } else if (name === "git") {
688
+ let k = i + 1;
689
+ while (k < words.length && words[k].startsWith("-")) k += GIT_GLOBAL_ARG_FLAGS.has(words[k]) ? 2 : 1;
690
+ if (k < words.length) calls.push([words[k].toLowerCase(), words.slice(k + 1)]);
691
+ }
692
+ }
693
+ return calls;
694
+ }
695
+
696
+ function reflogFlagged(sub: string, args: string[]): boolean {
697
+ return GIT_REFLOG_SUBCOMMANDS.has(sub)
698
+ && args.some(a => a === "-g" || optIs(a, "--reflog", 6) || optIs(a, "--walk-reflogs", 7));
699
+ }
700
+
701
+ function gitHit(sub: string, args: string[]): string | null {
702
+ if (sub === "cat-file" && args.some(a => optIs(a, "--batch-all-objects", 9))) return "git cat-file --batch-all-objects";
703
+ if (sub === "fsck" || sub === "fsck-objects") {
704
+ const bad = args.some(a => optIs(a, "--lost-found", 4) || optIs(a, "--unreachable", 4) || optIs(a, "--dangling", 3)
705
+ || optIs(a, "--no-reflogs", 6));
706
+ if (bad || !args.some(a => optIs(a, "--no-dangling", 8))) return "git fsck";
707
+ }
708
+ if (GIT_DENIED_SUBCOMMANDS.has(sub)) return "git " + sub;
709
+ const content = args.some(contentFlag);
710
+ if ((reflogFlagged(sub, args) && (GIT_CONTENT_SUBCOMMANDS.has(sub) || content)) || (sub === "reflog" && content)) {
711
+ return "git " + sub + " reflog content";
712
+ }
713
+ return null;
714
+ }
715
+
716
+ function gitRole(sub: string, args: string[]): [boolean, boolean] {
717
+ const feeder = sub === "reflog" || reflogFlagged(sub, args) || (
718
+ sub === "rev-list" && args.some(a => optIs(a, "--objects", 5))
719
+ && args.some(a => a === "--all" || optIs(a, "--reflog", 6)));
720
+ const sink = GIT_RECOVER_SUBCOMMANDS.has(sub) || (sub === "cat-file" && args.some(a => a.startsWith("--batch")));
721
+ return [feeder, sink];
722
+ }
723
+
724
+ function isRecursive(name: string, args: string[]): boolean {
725
+ const low = args.map(a => a.toLowerCase());
726
+ if (ALWAYS_RECURSIVE.has(name)) return true;
727
+ if (GREP_FAMILY.has(name)) {
728
+ return args.some(a => /^-[a-zA-Z]*[rR][a-zA-Z]*$/.test(a) || a === "--recursive" || a === "--dereference-recursive")
729
+ || low.includes("-recurse") || (args.includes("-d") && args.includes("recurse"));
730
+ }
731
+ if (name === "cp" || name === "scp" || name === "copy-item" || name === "cpi") {
732
+ return args.some(a => /^-[a-zA-Z]*[rRa][a-zA-Z]*$/.test(a) || a === "--recursive") || low.includes("-recurse");
733
+ }
734
+ if (name === "tar") return args.length > 0 && (args[0] === "--create" || /^-?[a-zA-Z]*c[a-zA-Z]*$/.test(args[0]));
735
+ return name === "findstr" && low.includes("/s");
736
+ }
737
+
738
+ function isContentReader(words: string[]): boolean {
739
+ const consumes = words.some(w => GREP_FAMILY.has(wordBase(w)) || wordBase(w) === "sed" || wordBase(w) === "awk");
740
+ return words.some(w => CONTENT_READERS.has(wordBase(w)) || /^-(?:exec|execdir|ok|okdir)$/.test(w) || (w === "$" && consumes));
741
+ }
742
+
743
+ function sweepHit(scan: HoldoutScan, stages: (Stage | null)[], content: boolean): string | null {
744
+ const hasTest = TEST_RE.test(stages.flatMap(st => (st ? st.words : [])).join(" "));
745
+ for (const st of stages) {
746
+ if (!st) continue;
747
+ for (let i = 0; i < st.words.length; i++) {
748
+ const name = wordBase(st.words[i]);
749
+ const rec = isRecursive(name, st.words.slice(i + 1));
750
+ const enumerates = ENUMERATORS.has(name);
751
+ if ((rec || (enumerates && content)) && scan.above([...st.ops, st.start], rec)) {
752
+ return name + " over a directory holding the holdout store";
753
+ }
754
+ if (!hasTest) continue;
755
+ for (const op of st.ops) {
756
+ const broad = rec || (enumerates && content) || (CONTENT_READERS.has(name) && op.some(s => GLOB_RE.test(s)));
757
+ if (broad && scan.inTmp(op)) return name + " sweeping temp directories for tests";
758
+ }
759
+ }
760
+ }
761
+ return null;
762
+ }
763
+
764
+ function scanStage(scan: HoldoutScan, words: string[], cur: Segs): { hit: string | null; stage: Stage | null } {
765
+ const lead = leadIndex(words);
766
+ const skips = grepSkips(words);
767
+ const ops: Segs[] = [];
768
+ for (let i = 0; i < words.length; i++) {
769
+ const token = words[i].replace(/^\d*[<>]+/, "");
770
+ if (skips.has(i) || !token) continue;
771
+ if (GIT_RAW_RE.test(token.replace(/\\/g, "/"))) return { hit: token, stage: null };
772
+ if (token.startsWith("-") && !token.includes("=")) continue;
773
+ const cands = scan.candidates(token, cur);
774
+ if (computedHome(token) || scan.reaches(cands)) return { hit: token, stage: null };
775
+ if (i > lead) ops.push(...cands);
776
+ }
777
+ const gwords = words.flatMap(w => w.split(/[,[\]]+/).filter(Boolean));
778
+ const calls: GitCall[] = [];
779
+ for (const [sub, args] of gitCalls(gwords)) {
780
+ const hit = gitHit(sub, args);
781
+ if (hit) return { hit, stage: null };
782
+ calls.push([sub, args]);
783
+ }
784
+ return { hit: null, stage: { words, ops, start: cur, git: calls, lead } };
785
+ }
786
+
787
+ function nextCwd(scan: HoldoutScan, st: Stage, cur: Segs): Segs {
788
+ const { words, lead } = st;
789
+ if (lead >= words.length || !CD_COMMANDS.has(wordBase(words[lead])) || words.slice(lead + 1).includes("-")) return cur;
790
+ const args = words.slice(lead + 1).filter(w => !w.startsWith("-") && !/^\/[A-Za-z]$/.test(w));
791
+ const first = scan.candidates(args.length ? args[0] : "~", cur)[0];
792
+ return first.some(s => GLOB_RE.test(s)) ? cur : first;
793
+ }
794
+
795
+ function gitLinkHit(stages: (Stage | null)[], ci: number, links: Links): string | null {
796
+ const feeders: number[] = [];
797
+ const sinks: number[] = [];
798
+ stages.forEach((st, si) => {
799
+ if (!st) return;
800
+ for (const [sub, args] of st.git) {
801
+ const [feeder, sink] = gitRole(sub, args);
802
+ if (feeder) feeders.push(si);
803
+ if (sink) sinks.push(si);
804
+ }
805
+ if (st.words.some(w => wordBase(w) === "xargs")) sinks.push(si);
806
+ });
807
+ links.feeders.push(...feeders.map((f): [number, number] => [ci, f]));
808
+ links.sinks.push(...sinks.map((s): [number, number] => [ci, s]));
809
+ return feeders.some(f => sinks.some(s => f !== s)) ? "git history listing piped into content recovery" : null;
810
+ }
811
+
812
+ function scanText(scan: HoldoutScan, source: string): string | null {
813
+ const text = source.replace(/`([^`]*)`/g, "$$($1)");
814
+ let cur = scan.cwd;
815
+ const links: Links = { feeders: [], sinks: [] };
816
+ const chains = text.split(/\|\||&&|[;&\r\n]/);
817
+ for (let ci = 0; ci < chains.length; ci++) {
818
+ const stages: (Stage | null)[] = [];
819
+ for (const part of chains[ci].split(/[|()]/)) {
820
+ const words = part.split(/\s+/).filter(Boolean);
821
+ const scanned = words.length ? scanStage(scan, words, cur) : { hit: null, stage: null };
822
+ if (scanned.hit) return scanned.hit;
823
+ stages.push(scanned.stage);
824
+ if (scanned.stage) cur = nextCwd(scan, scanned.stage, cur);
825
+ }
826
+ const content = stages.some(st => st !== null && isContentReader(st.words));
827
+ const hit = gitLinkHit(stages, ci, links) ?? sweepHit(scan, stages, content);
828
+ if (hit) return hit;
829
+ }
830
+ const crossed = links.feeders.some(([fc, fs]) => links.sinks.some(([sc, ss]) => fc !== sc || fs !== ss));
831
+ return LOOP_RE.test(text) && crossed ? "git history listing piped into content recovery" : null;
832
+ }
833
+
834
+ function inlineNameHit(text: string, evalMode: boolean): string | null {
835
+ const reduced = text.toLowerCase().replace(/[\s'"+,()[\]`\\^$\/]/g, "");
836
+ if (!reduced.includes("deepmodebot-holdout")) return null;
837
+ const interpreted = text.split(/[\s;&|()'"`]+/).some(w => w !== "" && INTERPRETER_RE.test(wordBase(w)));
838
+ return evalMode || interpreted ? HOLDOUT_DIR : null;
839
+ }
840
+
841
+ function holdoutCommandHit(command: unknown, cwd: string, evalMode = false): string | null {
842
+ const stripped = String(command ?? "").replace(/(-m|--message)(=|\s+)("[^"]*"|'[^']*')/g, '$1 ""');
843
+ const text = stripped.replace(/\\\r?\n/g, " ");
844
+ const scan = new HoldoutScan(cwd);
845
+ const inline = inlineNameHit(text, evalMode);
846
+ if (inline) return inline;
847
+ const flat = text.replace(/\$(?=['"])/g, "").replace(/['"]/g, "");
848
+ for (const view of [flat.replace(/\\/g, "/"), flat.replace(/[\\^`]/g, "")]) {
849
+ const hit = scanText(scan, view);
850
+ if (hit) return hit;
851
+ }
852
+ return null;
853
+ }
854
+
855
+ function toolVariants(value: string): string[] {
856
+ const out = [value, value.replace(/#[0-9A-Za-z]{4}$/, ""), value.replace(/:\d+(?:-\d+)?(?:,.*)?$/, "")];
857
+ for (const pattern of [/^\[(.+)#[0-9A-Za-z]+\]$/, /^(.{2,}?):[^/\\]/]) {
858
+ const match = pattern.exec(value);
859
+ if (match) out.push(match[1]);
860
+ }
861
+ return out.filter((v, i) => v !== "" && !out.slice(0, i).includes(v));
862
+ }
863
+
864
+ function toolStrings(value: unknown): string[] {
865
+ if (typeof value === "string") return [value];
866
+ return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
867
+ }
868
+
869
+ function holdoutToolHit(toolName: string, input: Record<string, unknown>, cwd: string): string | null {
870
+ const search = SEARCH_TOOL_RE.test(toolName);
871
+ const patternOk = search && !toolName.toLowerCase().includes("grep");
872
+ const bases: string[] = [];
873
+ const patterns: string[] = [];
874
+ for (const [key, value] of Object.entries(input)) {
875
+ const norm = key.replace(/[_\-\s]/g, "").toLowerCase();
876
+ if (TOOL_PATTERN_KEYS.has(norm) && (norm !== "pattern" || patternOk)) patterns.push(...toolStrings(value));
877
+ if (TOOL_PATH_KEYS.has(norm)) bases.push(...toolStrings(value));
878
+ }
879
+ if (!search && bases.length === 0 && patterns.length === 0) return null;
880
+ const scan = new HoldoutScan(cwd);
881
+ const texts = [...bases, ...patterns].flatMap(value => value.split(";"));
882
+ for (const base of bases.length ? bases : [joinSegs(scan.cwd)]) {
883
+ for (const pattern of patterns) texts.push(base.replace(/[/\\]+$/, "") + "/" + pattern);
884
+ }
885
+ for (const text of texts) {
886
+ for (const variant of toolVariants(text.trim())) {
887
+ const cands = scan.candidates(variant, scan.cwd);
888
+ if (GIT_RAW_RE.test(variant.replace(/\\/g, "/")) || scan.reaches(cands) || (search && scan.above(cands, true))) return variant;
889
+ }
890
+ }
891
+ return search && bases.length === 0 && scan.above([scan.cwd]) ? joinSegs(scan.cwd) : null;
892
+ }
893
+
190
894
  export default function (pi: HookApi): void {
895
+ // Show the owner, once per session, any agent rule changes they have not approved (rules_watch.py).
896
+ pi.on("session_start", async (_event, ctx) => {
897
+ const out = runPython(RULES_WATCH, ["check", "--format", "omp", "--cwd", ctx?.cwd ?? process.cwd()], "", 30_000);
898
+ let notice: { message?: string; status?: string };
899
+ try {
900
+ notice = out ? JSON.parse(out) : {};
901
+ } catch {
902
+ notice = { message: "deepmodebot: the agent rule check returned unreadable output; run `deepmodebot rules watch`." };
903
+ }
904
+ ctx?.ui?.setStatus?.("deepmodebot-rules", notice.status || undefined);
905
+ if (notice.message) ctx?.ui?.notify?.(notice.message, "warning");
906
+ });
907
+ pi.on("before_subagent_spawn", async event => {
908
+ if (nestedSpawn() && process.env.ALLOW_NESTED_SUBAGENTS !== "1") return { block: true, reason: NESTED_REASON };
909
+ if (!event.modelRole && Object.hasOwn(OVERHEAD_AGENTS, event.agent) && event.patterns?.[0] !== "@smol") {
910
+ return { model: ["@smol", ...(event.patterns ?? [])], note: "deepmodebot: pinned overhead specialist to @smol" };
911
+ }
912
+ });
191
913
  pi.on("tool_call", async (event, ctx) => {
192
914
  const cwd = ctx?.cwd ?? process.cwd();
193
915
  const input = event.input ?? {};
194
- if (event.toolName === "bash") {
916
+ if (event.toolName === "task") {
917
+ const context = String(input.context ?? "");
918
+ if (nestedSpawn() && process.env.ALLOW_NESTED_SUBAGENTS !== "1" && !context.includes("ALLOW_NESTED_SUBAGENTS")) {
919
+ return { block: true, reason: NESTED_REASON };
920
+ }
921
+ if (context.includes("worker.md")) return;
922
+ const [root] = projectRoots(cwd);
923
+ const nextContext = `Read skill://deepmodebot/worker.md before anything else.\nProject root: ${root} | Scratch & TMPDIR: ${path.join(root, ".scratch", "tmp")}\n${context}`;
924
+ return { input: { ...input, context: nextContext } };
925
+ }
926
+ if (event.toolName === "bash" || event.toolName === "eval") {
927
+ const command = event.toolName === "bash" ? input.command : input.code;
928
+ const hit = findShellRewardHack(event.toolName === "eval" && typeof command === "string"
929
+ ? command.replace(/[`}\]]/g, " ") : command);
930
+ if (hit) return {
931
+ block: true,
932
+ reason: `deepmodebot anti-reward-hacking guard blocked "${hit}": builders may not zero thresholds, skip reference/verification gates, or tamper with provenance ledgers.`,
933
+ };
195
934
  const runDir = typeof input.cwd === "string" && input.cwd.trim() ? absolute(input.cwd.trim(), cwd) : cwd;
196
- return ruleBlock(runDir, [], typeof input.command === "string" ? input.command : "");
935
+ const holdout = holdoutCommandHit(
936
+ event.toolName === "eval" && typeof command === "string" ? command.replace(/[`}\]]/g, " ") : command,
937
+ runDir,
938
+ event.toolName === "eval",
939
+ );
940
+ if (holdout) return { block: true, reason: holdoutReason(holdout) };
941
+ if (event.toolName === "eval") return;
942
+ return ruleBlock(runDir, [], typeof command === "string" ? command : "");
197
943
  }
944
+ const holdoutTool = holdoutToolHit(event.toolName, input, cwd);
945
+ if (holdoutTool) return { block: true, reason: holdoutReason(holdoutTool) };
198
946
  if (!WRITE_TOOLS[event.toolName]) return;
199
947
  const roots = projectRoots(cwd);
200
948
  const root = roots[0];
949
+ const files = targets(input);
950
+ const sliceBlock = sliceWriteBlock(root, cwd, files);
951
+ if (sliceBlock) return sliceBlock;
201
952
  const allowed = allowedRoots(roots);
202
- for (const target of targets(input)) {
953
+ for (const target of files) {
203
954
  // skill://, vault://, ssh:// and other non-session URLs resolve outside the root. A selector suffix
204
955
  // (archive.zip:member, db.sqlite:table) stays on the path: `..` in it must count against the target.
205
956
  if (!ANY_URL.test(target) && allowed.some(r => inside(real(absolute(target, cwd)), r))) continue;
@@ -211,6 +962,6 @@ export default function (pi: HookApi): void {
211
962
  `If the user explicitly named this path, add it to extraWriteRoots in ${path.join(root, ".deepmodebot.json")}.`,
212
963
  };
213
964
  }
214
- return ruleBlock(cwd, targets(input).filter(t => !ANY_URL.test(t)), "");
965
+ return ruleBlock(cwd, files.filter(t => !ANY_URL.test(t)), "");
215
966
  });
216
967
  }