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
@@ -0,0 +1,436 @@
1
+ #!/usr/bin/env python3
2
+ """Tell the owner when agent rules changed without their approval.
3
+
4
+ python -B rules_watch.py check [--cwd DIR] [--notify toast,orca] [--format text|json|claude|omp|agy]
5
+ python -B rules_watch.py blocked --reason TEXT [--cwd DIR]
6
+
7
+ Sources: the user rule ledger (~/.deepmodebot/rules, `deepmodebot rules init --user`), every repo registered by
8
+ `deepmodebot rules init`, and the repo holding --cwd. A change is any rule file that is new, changed or removed
9
+ against the owner's ledger, plus agent proposals waiting for a decision.
10
+
11
+ Channels:
12
+ - `--format claude|omp|agy` prints the notice for a harness session-start hook (Claude Code SessionStart,
13
+ omp session_start, Antigravity PreInvocation); `text` and `json` are for people and scripts.
14
+ - `--notify toast` shows a desktop notification (Windows toast, macOS osascript, Linux notify-send), again only when
15
+ the set of changes differs from the last toast or a day has passed. `--notify orca` puts the notice in the Orca
16
+ workspace comment and marks the workspace unread; it clears that comment once nothing is pending.
17
+ - `blocked` is the hook helper for a denied rule write: it toasts at once and logs the attempt.
18
+ Every notice and block is appended to ~/.deepmodebot/rules-watch.log. DEEPMODEBOT_NOTIFY_SINK=<file> writes each
19
+ toast and Orca update to that file as a JSON line instead of the OS and Orca (tests).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import hashlib
26
+ import importlib.util
27
+ import json
28
+ import os
29
+ import shutil
30
+ import subprocess
31
+ import sys
32
+ import time
33
+ from pathlib import Path
34
+
35
+ sys.dont_write_bytecode = True
36
+
37
+ HERE = Path(__file__).resolve().parent
38
+ NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
39
+ ORCA_PREFIX = "⚠ deepmodebot rules:"
40
+ TOAST_REPEAT_SECONDS = 24 * 3600
41
+ BLOCK_REPEAT_SECONDS = 60
42
+ SHOWN_ITEMS = 6
43
+ WIN_TOAST_APP = r"{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}\WindowsPowerShell\v1.0\powershell.exe"
44
+ WIN_TOAST_SCRIPT = r"""
45
+ $ErrorActionPreference = 'Stop'
46
+ [Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
47
+ [Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] > $null
48
+ $t = [Security.SecurityElement]::Escape($env:DMB_TOAST_TITLE)
49
+ $b = [Security.SecurityElement]::Escape($env:DMB_TOAST_BODY)
50
+ $x = New-Object Windows.Data.Xml.Dom.XmlDocument
51
+ $x.LoadXml("<toast><visual><binding template='ToastGeneric'><text>$t</text><text>$b</text></binding></visual></toast>")
52
+ [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier($env:DMB_TOAST_APP).Show(
53
+ [Windows.UI.Notifications.ToastNotification]::new($x))
54
+ """
55
+
56
+
57
+ def _ledger():
58
+ mod = sys.modules.get("dmb_rule_ledger")
59
+ if mod is None:
60
+ spec = importlib.util.spec_from_file_location("dmb_rule_ledger", HERE / "rule_ledger.py")
61
+ mod = importlib.util.module_from_spec(spec)
62
+ sys.modules[spec.name] = mod
63
+ spec.loader.exec_module(mod)
64
+ return mod
65
+
66
+
67
+ def _state_dir() -> Path:
68
+ return _ledger().user_home() / ".deepmodebot"
69
+
70
+
71
+ def _log(event: str, **fields) -> None:
72
+ entry = {"at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "event": event, **fields}
73
+ try:
74
+ _state_dir().mkdir(parents=True, exist_ok=True)
75
+ with open(_state_dir() / "rules-watch.log", "a", encoding="utf-8") as handle:
76
+ handle.write(json.dumps(entry, ensure_ascii=False) + "\n")
77
+ except OSError:
78
+ pass
79
+
80
+
81
+ def _load_json(path: Path) -> dict:
82
+ try:
83
+ data = json.loads(path.read_text(encoding="utf-8"))
84
+ except (OSError, ValueError):
85
+ return {}
86
+ return data if isinstance(data, dict) else {}
87
+
88
+
89
+ def _save_json(path: Path, data: dict) -> None:
90
+ try:
91
+ path.parent.mkdir(parents=True, exist_ok=True)
92
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
93
+ tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
94
+ os.replace(tmp, path)
95
+ except OSError:
96
+ pass
97
+
98
+
99
+ def _file_sha(path: Path, cache: dict, rel: str) -> str | None:
100
+ """SHA-256 the way the ledger hashes a rule (link text for symlinks, CRLF as LF), cached by size and mtime."""
101
+ rl = _ledger()
102
+ try:
103
+ st = os.lstat(path)
104
+ except OSError:
105
+ return None
106
+ key = [st.st_size, st.st_mtime_ns]
107
+ hit = cache.get(rel)
108
+ if isinstance(hit, list) and len(hit) == 3 and hit[:2] == key:
109
+ return hit[2]
110
+ try:
111
+ if path.is_symlink():
112
+ data = os.readlink(path).encode("utf-8", "surrogateescape")
113
+ elif path.is_file():
114
+ data = rl._eol(path.read_bytes())
115
+ else:
116
+ return None
117
+ except OSError:
118
+ return None
119
+ sha = rl._sha(data)
120
+ cache[rel] = key + [sha]
121
+ return sha
122
+
123
+
124
+ def _user_entry() -> dict:
125
+ """Pending user-level rule changes. Only approved files are hashed (through a size/mtime cache); a file the
126
+ owner never approved is pending whatever its content, so its size and mtime stand in for the hash."""
127
+ rl = _ledger()
128
+ home = rl.user_home()
129
+ entry = {"scope": "user", "root": str(home), "label": "~", "changes": [], "problem": "", "initialized": False,
130
+ "files": 0}
131
+ src = rl.Source(home)
132
+ raw = src.read(rl.LEDGER_REL)
133
+ if raw is None:
134
+ entry["files"] = len(rl.rule_files(src))
135
+ return entry
136
+ entry["initialized"] = True
137
+ try:
138
+ ledger = rl.parse_ledger(raw)
139
+ except rl.RuleError as exc:
140
+ entry["problem"] = str(exc)
141
+ return entry
142
+ cache_path = home / rl.STORE_REL / "hash-cache.json"
143
+ cache = _load_json(cache_path)
144
+ approved = ledger["approved"]
145
+ present = set()
146
+ for rel in rl.rule_files(src):
147
+ path = home / rel
148
+ if rel in approved:
149
+ sha = _file_sha(path, cache, rel)
150
+ if sha is not None:
151
+ present.add(rel)
152
+ if sha != approved[rel]:
153
+ entry["changes"].append({"kind": "changed", "item": rel, "sha": sha})
154
+ continue
155
+ try:
156
+ st = os.lstat(path)
157
+ except OSError:
158
+ continue
159
+ present.add(rel)
160
+ entry["changes"].append({"kind": "new", "item": rel, "sha": f"{st.st_size}:{st.st_mtime_ns}"})
161
+ _save_json(cache_path, {rel: v for rel, v in cache.items() if rel in approved})
162
+ for rel in sorted(set(approved) - present):
163
+ entry["changes"].append({"kind": "removed", "item": rel, "sha": ""})
164
+ entry["changes"].sort(key=lambda c: (c["item"], c["kind"]))
165
+ for prop in rl.load_proposals(home):
166
+ entry["changes"].append({"kind": "proposal", "item": prop["item"], "sha": str(prop.get("id", ""))})
167
+ return entry
168
+
169
+
170
+ def _repo_entry(root: Path) -> dict | None:
171
+ rl = _ledger()
172
+ try:
173
+ st = rl.status(root)
174
+ except (rl.RuleError, OSError, ValueError):
175
+ return None
176
+ if not st.get("enabled"):
177
+ return None
178
+ changes = [{"kind": row["state"], "item": row["item"], "sha": ",".join(row.get("ids") or [])}
179
+ for row in st.get("items", []) if row.get("state") != "approved"]
180
+ changes += [{"kind": "proposal", "item": p["item"], "sha": str(p.get("id", ""))} for p in st.get("proposals", [])]
181
+ return {"scope": "repo", "root": str(root), "label": str(root), "changes": changes,
182
+ "problem": st.get("problem") or "", "initialized": True, "files": len(st.get("items", []))}
183
+
184
+
185
+ def collect(cwd: str | None = None) -> list[dict]:
186
+ rl = _ledger()
187
+ entries = [_user_entry()]
188
+ roots = {os.path.normcase(str(p)): p for p in rl.registered_repos()}
189
+ if cwd:
190
+ here = rl.project_root(cwd)
191
+ if not rl.is_user_root(here) and rl.ledger_enabled(here):
192
+ roots.setdefault(os.path.normcase(str(here)), here)
193
+ for root in roots.values():
194
+ if Path(root).is_dir():
195
+ entry = _repo_entry(Path(root))
196
+ if entry:
197
+ entries.append(entry)
198
+ return entries
199
+
200
+
201
+ def _shown(entry: dict, change: dict) -> str:
202
+ return f"~/{change['item']}" if entry["scope"] == "user" else f"{entry['label']}: {change['item']}"
203
+
204
+
205
+ def summary(entries: list[dict]) -> dict:
206
+ """Notice text for people (message), for the agent (agent_note), a one-line status, and a change fingerprint."""
207
+ changes = [(e, c) for e in entries for c in e["changes"]]
208
+ problems = [e for e in entries if e["problem"]]
209
+ uninit = next((e for e in entries if e["scope"] == "user" and not e["initialized"]), None)
210
+ lines, review = [], []
211
+ if changes:
212
+ lines.append(f"{len(changes)} agent rule change(s) you have not approved:")
213
+ lines += [f" {c['kind']:8} {_shown(e, c)}" for e, c in changes[:SHOWN_ITEMS]]
214
+ if len(changes) > SHOWN_ITEMS:
215
+ lines.append(f" ... and {len(changes) - SHOWN_ITEMS} more")
216
+ if any(e["scope"] == "user" for e, _ in changes):
217
+ review.append("deepmodebot rules review --user")
218
+ review += [f"deepmodebot rules review --root \"{e['root']}\"" for e in entries if e["scope"] == "repo" and e["changes"]]
219
+ for e in problems:
220
+ lines.append(f"Rule ledger problem in {e['label']}: {e['problem']}")
221
+ if uninit is not None:
222
+ lines.append(f"Your {uninit['files']} user-level agent rules (~/.omp, ~/.claude, ~/.codex, ~/.gemini, ~/.agents) are "
223
+ "not under review yet, so changes to them go unnoticed.")
224
+ review.append("deepmodebot rules init --user")
225
+ if not lines:
226
+ return {"pending": 0, "message": "", "agent_note": "", "status": "", "fingerprint": ""}
227
+ message = "deepmodebot: " + "\n".join(lines)
228
+ if review:
229
+ message += "\nIn your own terminal: " + " ; ".join(dict.fromkeys(review))
230
+ count = len(changes)
231
+ status = (f"⚠ {count} unapproved agent rule change(s)" if count else
232
+ "⚠ agent rule ledger problem" if problems else "⚠ user agent rules not reviewed")
233
+ agent_note = (message + "\nAgents never change agent rule files themselves. Tell the user about this notice, and "
234
+ "propose rule changes with `rule_ledger.py propose` instead of writing them.")
235
+ blob = "\n".join(sorted(f"{e['root']}|{c['kind']}|{c['item']}|{c['sha']}" for e, c in changes)
236
+ + [f"problem|{e['root']}|{e['problem']}" for e in problems]
237
+ + (["uninitialized"] if uninit is not None else []))
238
+ return {"pending": count, "message": message, "agent_note": agent_note, "status": status,
239
+ "fingerprint": hashlib.sha256(blob.encode("utf-8")).hexdigest()}
240
+
241
+
242
+ def _sink(kind: str, **fields) -> bool:
243
+ path = os.environ.get("DEEPMODEBOT_NOTIFY_SINK")
244
+ if not path:
245
+ return False
246
+ with open(path, "a", encoding="utf-8") as handle:
247
+ handle.write(json.dumps({"channel": kind, **fields}, ensure_ascii=False) + "\n")
248
+ return True
249
+
250
+
251
+ def toast(title: str, body: str, *, wait: bool = True) -> bool:
252
+ if _sink("toast", title=title, body=body):
253
+ return True
254
+ body = body[:400]
255
+ if sys.platform == "win32":
256
+ exe = shutil.which("powershell.exe") or shutil.which("powershell")
257
+ if not exe:
258
+ return False
259
+ cmd = [exe, "-NoProfile", "-NonInteractive", "-WindowStyle", "Hidden", "-Command", WIN_TOAST_SCRIPT]
260
+ env = {**os.environ, "DMB_TOAST_TITLE": title, "DMB_TOAST_BODY": body, "DMB_TOAST_APP": WIN_TOAST_APP}
261
+ elif sys.platform == "darwin":
262
+ cmd = ["osascript", "-e", "on run argv\ndisplay notification (item 2 of argv) with title (item 1 of argv)\nend run",
263
+ title, body]
264
+ env = None
265
+ elif shutil.which("notify-send"):
266
+ cmd, env = ["notify-send", title, body], None
267
+ else:
268
+ return False
269
+ try:
270
+ if wait:
271
+ return subprocess.run(cmd, env=env, capture_output=True, timeout=30, creationflags=NO_WINDOW).returncode == 0
272
+ subprocess.Popen(cmd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
273
+ creationflags=NO_WINDOW)
274
+ return True
275
+ except (OSError, subprocess.SubprocessError):
276
+ return False
277
+
278
+
279
+ def _orca(*args: str) -> dict | None:
280
+ exe = shutil.which("orca")
281
+ if not exe:
282
+ return None
283
+ try:
284
+ out = subprocess.run([exe, *args, "--json"], capture_output=True, text=True, encoding="utf-8", errors="replace",
285
+ timeout=30, creationflags=NO_WINDOW)
286
+ except (OSError, subprocess.SubprocessError):
287
+ return None
288
+ try:
289
+ data = json.loads(out.stdout)
290
+ except ValueError:
291
+ return None
292
+ return data if isinstance(data, dict) else None
293
+
294
+
295
+ def _orca_worktrees() -> list[dict]:
296
+ data = _orca("worktree", "list") or {}
297
+ result = data.get("result", data)
298
+ rows = result.get("worktrees") if isinstance(result, dict) else result
299
+ return [w for w in rows or [] if isinstance(w, dict) and w.get("path") and not w.get("isArchived")]
300
+
301
+
302
+ def _same(a: str, b: str) -> bool:
303
+ return os.path.normcase(os.path.abspath(a)) == os.path.normcase(os.path.abspath(b))
304
+
305
+
306
+ def _inside(path: str, root: str) -> bool:
307
+ try:
308
+ return os.path.commonpath([os.path.normcase(os.path.abspath(path)), os.path.normcase(os.path.abspath(root))]) \
309
+ == os.path.normcase(os.path.abspath(root))
310
+ except ValueError:
311
+ return False
312
+
313
+
314
+ def orca_notify(entries: list[dict], notice: dict, cwd: str | None, fresh: bool) -> list[str]:
315
+ """Comment on the Orca workspaces the changes belong to (marked unread when the change set is new); clear our
316
+ comment where nothing is pending. Comments someone else wrote are left alone."""
317
+ short = notice["status"].lstrip("⚠ ").strip()
318
+ comment = f"{ORCA_PREFIX} {short}. Run `deepmodebot rules review --user` (or in the repo) to decide." if notice["message"] else ""
319
+ if os.environ.get("DEEPMODEBOT_NOTIFY_SINK"):
320
+ _sink("orca", comment=comment, cwd=cwd or "", unread=fresh and bool(comment))
321
+ return []
322
+ rows = _orca_worktrees()
323
+ targets: set[str] = set()
324
+ if notice["message"]:
325
+ for e in entries:
326
+ if not (e["changes"] or e["problem"] or not e["initialized"]):
327
+ continue
328
+ if e["scope"] == "repo":
329
+ targets |= {w["id"] for w in rows if _same(w["path"], e["root"])}
330
+ else:
331
+ here = [w for w in rows if cwd and _inside(cwd, w["path"])]
332
+ latest = sorted(rows, key=lambda w: w.get("lastActivityAt") or 0)[-1:]
333
+ targets |= {w["id"] for w in here or latest}
334
+ marked = []
335
+ for w in rows:
336
+ current = str(w.get("comment") or "")
337
+ ours = current.startswith(ORCA_PREFIX)
338
+ selector = f"id:{w['id']}"
339
+ if w["id"] in targets:
340
+ args = ["worktree", "set", "--worktree", selector]
341
+ if fresh:
342
+ args.append("--unread")
343
+ if (not current or ours) and current != comment:
344
+ args += ["--comment", comment]
345
+ if len(args) > 4:
346
+ _orca(*args)
347
+ marked.append(w["path"])
348
+ elif ours:
349
+ _orca("worktree", "set", "--worktree", selector, "--comment", "")
350
+ return marked
351
+
352
+
353
+ def check(cwd: str | None, channels: set[str]) -> dict:
354
+ entries = collect(cwd)
355
+ notice = summary(entries)
356
+ notice["entries"] = entries
357
+ state_path = _state_dir() / "rules-watch-state.json"
358
+ state = _load_json(state_path)
359
+ fingerprint = notice["fingerprint"]
360
+ if "toast" in channels:
361
+ due = fingerprint and (state.get("fingerprint") != fingerprint
362
+ or time.time() - float(state.get("toasted_at") or 0) > TOAST_REPEAT_SECONDS)
363
+ if due and toast("deepmodebot: agent rules need your review", notice["message"][len("deepmodebot: "):]):
364
+ state.update(fingerprint=fingerprint, toasted_at=time.time())
365
+ notice["toasted"] = True
366
+ elif not fingerprint:
367
+ state.pop("fingerprint", None)
368
+ state.pop("toasted_at", None)
369
+ if "orca" in channels:
370
+ notice["orca"] = orca_notify(entries, notice, cwd, fresh=state.get("orca_fingerprint") != fingerprint)
371
+ state["orca_fingerprint"] = fingerprint
372
+ if channels:
373
+ _save_json(state_path, state)
374
+ if notice["message"] and channels:
375
+ _log("notice", pending=notice["pending"], fingerprint=notice["fingerprint"], channels=sorted(channels))
376
+ return notice
377
+
378
+
379
+ def notify_blocked(reason: str, cwd: str = "") -> None:
380
+ """A guard denied an agent's rule write: log it and toast the owner (at most once a minute per reason)."""
381
+ _log("blocked", reason=reason, cwd=cwd)
382
+ state_path = _state_dir() / "rules-watch-state.json"
383
+ state = _load_json(state_path)
384
+ key = hashlib.sha256(reason.encode("utf-8")).hexdigest()[:16]
385
+ last = state.get("blocked") if isinstance(state.get("blocked"), dict) else {}
386
+ if time.time() - float(last.get(key) or 0) < BLOCK_REPEAT_SECONDS:
387
+ return
388
+ head = reason.split(". ", 1)[0].replace("deepmodebot rule approval: ", "", 1)
389
+ toast("deepmodebot blocked an agent rule change", head, wait=False)
390
+ last = {k: v for k, v in last.items() if time.time() - float(v) < BLOCK_REPEAT_SECONDS}
391
+ state["blocked"] = {**last, key: time.time()}
392
+ _save_json(state_path, state)
393
+
394
+
395
+ def render(notice: dict, fmt: str) -> str:
396
+ if fmt == "json":
397
+ return json.dumps(notice, indent=2, ensure_ascii=False)
398
+ if not notice["message"]:
399
+ return "" if fmt in ("claude", "agy") else ("{}" if fmt == "omp" else "deepmodebot rules: nothing pending.")
400
+ if fmt == "claude":
401
+ return json.dumps({"systemMessage": notice["message"],
402
+ "hookSpecificOutput": {"hookEventName": "SessionStart", "additionalContext": notice["agent_note"]}},
403
+ ensure_ascii=False)
404
+ if fmt == "omp":
405
+ return json.dumps({"message": notice["message"], "status": notice["status"]}, ensure_ascii=False)
406
+ if fmt == "agy":
407
+ return json.dumps({"systemMessage": notice["agent_note"]}, ensure_ascii=False)
408
+ return notice["message"]
409
+
410
+
411
+ def main(argv: list[str] | None = None) -> int:
412
+ p = argparse.ArgumentParser(description="Notify the owner about agent rules changed without approval.")
413
+ sub = p.add_subparsers(dest="cmd", required=True)
414
+ sp = sub.add_parser("check", help="Collect unapproved rule changes and notify.")
415
+ sp.add_argument("--cwd", default=None, help="Also check the repo holding this folder.")
416
+ sp.add_argument("--notify", default="", help="Comma-separated channels: toast, orca.")
417
+ sp.add_argument("--format", default="text", choices=("text", "json", "claude", "omp", "agy"))
418
+ sp = sub.add_parser("blocked", help="Hook helper: a guard denied an agent rule write.")
419
+ sp.add_argument("--reason", required=True)
420
+ sp.add_argument("--cwd", default="")
421
+ args = p.parse_args(argv)
422
+ if args.cmd == "blocked":
423
+ notify_blocked(args.reason, args.cwd)
424
+ return 0
425
+ channels = {c.strip() for c in args.notify.split(",") if c.strip()}
426
+ unknown = channels - {"toast", "orca"}
427
+ if unknown:
428
+ p.error(f"unknown channel(s): {', '.join(sorted(unknown))}")
429
+ out = render(check(args.cwd, channels), args.format)
430
+ if out:
431
+ print(out)
432
+ return 0
433
+
434
+
435
+ if __name__ == "__main__":
436
+ raise SystemExit(main())