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,21 +4,25 @@
4
4
  Rules are the instruction and permission files coding agents load (AGENTS.md, CLAUDE.md, .cursor/rules/, skills,
5
5
  agent settings; the full list is rule-paths.json) plus `convention` records in the deepmodebot project memory.
6
6
  .deepmodebot/rules/ledger.json pins the approved SHA-256 of each rule, .deepmodebot/rules/approved/<sha256> keeps the
7
- approved bytes, and the history logs every decision. The ledger is signed with an Ed25519 key derived from a passphrase
8
- only the owner knows: agents can read, review and propose, but approving, rejecting and re-keying need the passphrase.
9
- Trust is anchored on the committed ledger at HEAD and at the merge-base with the remote default branch.
10
-
11
- python -B rule_ledger.py status [--root R] [--json]
12
- python -B rule_ledger.py review [--root R] [--json]
13
- python -B rule_ledger.py log [--root R] [--json]
14
- python -B rule_ledger.py propose --item AGENTS.md --file .scratch/AGENTS.draft.md --reason "why" [--by NAME] [--root R]
7
+ approved bytes, and the history logs every decision. Agents can read, review and propose; only the owner approves or
8
+ rejects, with a yes/no in their own terminal. The hooks block agents from running those commands and from writing the
9
+ ledger. Trust is anchored on the committed ledger at HEAD and at the merge-base with the remote default branch.
10
+
11
+ With `--user` the same ledger covers user-level agent rules: files under the home folder that every session of a
12
+ harness loads (`user` in rule-paths.json: ~/.omp/agent hooks and skills, ~/.claude settings, ~/.codex config, ...).
13
+ That ledger lives in ~/.deepmodebot/rules/, has no git anchor, and starts empty, so the owner reviews every current
14
+ user rule once. The hooks deny agent writes to those paths and `rules_watch.py` notifies the owner about drift.
15
+
16
+ python -B rule_ledger.py status [--root R | --user] [--json]
17
+ python -B rule_ledger.py review [--root R | --user] [--json]
18
+ python -B rule_ledger.py log [--root R | --user] [--json]
19
+ python -B rule_ledger.py propose --item AGENTS.md --file .scratch/AGENTS.draft.md --reason "why" [--by NAME] [--root R | --user]
15
20
  python -B rule_ledger.py check [--root R] [--staged] [--base REF] [--json]
16
21
  python -B rule_ledger.py guard (hook helper: JSON {"cwd", "paths", "command"} on stdin, JSON verdict out)
17
- Owner only; each asks for the owner passphrase on the terminal:
18
- python -B rule_ledger.py init [--root R] [--yes] [--reset]
19
- python -B rule_ledger.py approve (ID ... | --all) [--root R] [--yes]
20
- python -B rule_ledger.py reject (ID ... | --all) [--root R] [--yes]
21
- python -B rule_ledger.py rotate [--root R]
22
+ Owner only; each asks for a yes/no on the owner's own terminal:
23
+ python -B rule_ledger.py init [--root R | --user [--accept-current]]
24
+ python -B rule_ledger.py approve (ID ... | --all) [--root R | --user]
25
+ python -B rule_ledger.py reject (ID ... | --all) [--root R | --user]
22
26
  """
23
27
 
24
28
  from __future__ import annotations
@@ -27,7 +31,6 @@ import argparse
27
31
  import datetime
28
32
  import difflib
29
33
  import fnmatch
30
- import getpass
31
34
  import glob
32
35
  import hashlib
33
36
  import importlib.util
@@ -35,7 +38,6 @@ import json
35
38
  import os
36
39
  import posixpath
37
40
  import re
38
- import secrets
39
41
  import shlex
40
42
  import sqlite3
41
43
  import stat
@@ -53,14 +55,12 @@ STORE_REL = ".deepmodebot/rules"
53
55
  LEDGER_REL = STORE_REL + "/ledger.json"
54
56
  APPROVED_REL = STORE_REL + "/approved"
55
57
  PROPOSALS_REL = STORE_REL + "/proposals"
58
+ REGISTRY_REL = STORE_REL + "/repos.json"
59
+ USER_BLOB_MAX = 1 << 20
56
60
  MEMORY_PREFIX = "memory:"
57
- LEDGER_VERSION = 1
58
- KDF_ITERATIONS = 600_000
59
- MAX_KDF_ITERATIONS = 20_000_000
60
- MIN_PASSPHRASE = 8
61
- ROTATE_TAG = b"deepmodebot-rules-rotate:"
62
- SUBCOMMANDS = frozenset({"status", "review", "log", "propose", "check", "guard", "init", "approve", "reject", "rotate"})
63
- OWNER_COMMANDS = frozenset({"init", "approve", "reject", "rotate"})
61
+ LEDGER_VERSION = 2
62
+ SUBCOMMANDS = frozenset({"status", "review", "log", "propose", "check", "guard", "init", "approve", "reject"})
63
+ OWNER_COMMANDS = frozenset({"init", "approve", "reject"})
64
64
  SKIP_SEGMENTS = frozenset({".git", "node_modules", ".scratch", ".worktrees"})
65
65
  NO_WINDOW = getattr(subprocess, "CREATE_NO_WINDOW", 0)
66
66
  DIFF_LINES_SHOWN = 40
@@ -124,6 +124,28 @@ def norm_rel(raw: str) -> str:
124
124
  return s.rstrip("/")
125
125
 
126
126
 
127
+ def _load_user_spec() -> tuple[tuple, tuple]:
128
+ user = json.loads((HERE / "rule-paths.json").read_text(encoding="utf-8")).get("user") or {}
129
+ return (tuple(norm_rel(f) for f in user.get("files", [])),
130
+ tuple(norm_rel(d).strip("/") for d in user.get("dirs", [])))
131
+
132
+
133
+ USER_FILE_PATHS, USER_DIR_PATHS = _load_user_spec()
134
+ USER_FILES = frozenset(f.lower() for f in USER_FILE_PATHS)
135
+ USER_DIRS = tuple(d.lower() + "/" for d in USER_DIR_PATHS)
136
+
137
+
138
+ def user_home() -> Path:
139
+ return Path.home().resolve()
140
+
141
+
142
+ def is_user_root(root) -> bool:
143
+ try:
144
+ return Path(root).resolve() == user_home()
145
+ except (OSError, RuntimeError):
146
+ return False
147
+
148
+
127
149
  def is_store_path(rel: str) -> bool:
128
150
  low = norm_rel(rel).lower()
129
151
  return low == STORE_REL or low.startswith(STORE_REL + "/")
@@ -142,6 +164,21 @@ def is_rule_path(rel: str) -> bool:
142
164
  return any(d in padded for d in RULE_DIRS)
143
165
 
144
166
 
167
+ def is_user_rule_path(rel: str) -> bool:
168
+ """A home-relative path that a harness loads into every session (`user` in rule-paths.json)."""
169
+ low = norm_rel(rel).lower()
170
+ if not low or low.startswith("/") or is_store_path(low):
171
+ return False
172
+ parts = low.split("/")
173
+ if ".." in parts or any(p in SKIP_SEGMENTS for p in parts[:-1]):
174
+ return False
175
+ return low in USER_FILES or low.startswith(USER_DIRS)
176
+
177
+
178
+ def rule_path_in(root, rel: str) -> bool:
179
+ return is_user_rule_path(rel) if is_user_root(root) else is_rule_path(rel)
180
+
181
+
145
182
  def _rule_ish(rel: str) -> bool:
146
183
  """A rule path itself, or a folder that holds rule paths (a symlinked `.claude/skills`)."""
147
184
  return is_rule_path(rel) or is_rule_path(norm_rel(rel) + "/x")
@@ -213,11 +250,16 @@ def _cat_blobs(root: Path, specs: list[str]) -> dict[str, bytes | None]:
213
250
  class Source:
214
251
  """Rule bytes from the working tree ("work"), the git index ("index", pre-commit), or a commit ("ref").
215
252
 
216
- Symlinks read as their link text in every mode, the way git stores them.
253
+ Symlinks read as their link text in every mode, the way git stores them. A working-tree Source rooted at the home
254
+ folder is the user scope: it lists only the user rule paths, never the whole home folder.
217
255
  """
218
256
 
219
257
  def __init__(self, root: Path, mode: str = "work", ref: str = ""):
220
258
  self.root, self.mode, self.ref = Path(root), mode, ref
259
+ self.user = mode == "work" and is_user_root(root)
260
+
261
+ def is_rule(self, rel: str) -> bool:
262
+ return is_user_rule_path(rel) if self.user else is_rule_path(rel)
221
263
 
222
264
  def read_many(self, rels: list[str]) -> dict[str, bytes | None]:
223
265
  if self.mode != "work":
@@ -241,6 +283,8 @@ class Source:
241
283
 
242
284
  def paths(self) -> list[str]:
243
285
  """Every file git tracks or would track; gitignored files are personal and stay out of the ledger."""
286
+ if self.user:
287
+ return self._user_paths()
244
288
  if self.mode == "index":
245
289
  return self._git_list("ls-files", "-z", "--cached") or []
246
290
  if self.mode == "ref":
@@ -254,13 +298,35 @@ class Source:
254
298
  listed += [(base / n).as_posix() for n in filenames]
255
299
  return sorted({p for p in listed if os.path.lexists(self.root / p)})
256
300
 
301
+ def _user_paths(self) -> list[str]:
302
+ """User rule files, plus symlinked folders inside the rule folders (tracked as their link text)."""
303
+ found = [f for f in USER_FILE_PATHS if os.path.lexists(self.root / f) and not (self.root / f).is_dir()]
304
+ for top in USER_DIR_PATHS:
305
+ base = self.root / top
306
+ if base.is_symlink():
307
+ found.append(top)
308
+ continue
309
+ for folder, dirnames, filenames in os.walk(base):
310
+ rel_dir = Path(folder).relative_to(self.root).as_posix()
311
+ keep = []
312
+ for name in dirnames:
313
+ if name in SKIP_SEGMENTS:
314
+ continue
315
+ if os.path.islink(os.path.join(folder, name)):
316
+ found.append(f"{rel_dir}/{name}")
317
+ else:
318
+ keep.append(name)
319
+ dirnames[:] = keep
320
+ found += [f"{rel_dir}/{name}" for name in filenames]
321
+ return sorted(set(found))
322
+
257
323
  def links(self) -> dict[str, str]:
258
324
  """Symlinked rule paths and rule folders: {repo path: link target}."""
259
325
  if self.mode == "work":
260
326
  out = {}
261
327
  for rel in self.paths():
262
328
  path = self.root / rel
263
- if _rule_ish(rel) and path.is_symlink():
329
+ if (self.is_rule(rel) if self.user else _rule_ish(rel)) and path.is_symlink():
264
330
  out[rel] = os.readlink(path)
265
331
  return out
266
332
  args = ("ls-files", "-s", "-z") if self.mode == "index" else ("ls-tree", "-r", "-z", self.ref)
@@ -281,11 +347,16 @@ class Source:
281
347
 
282
348
 
283
349
  def rule_files(src: Source) -> list[str]:
284
- return sorted(p for p in src.paths() if is_rule_path(p))
350
+ return sorted(p for p in src.paths() if src.is_rule(p))
285
351
 
286
352
 
287
353
  def untracked_links(src: Source) -> list[tuple[str, str]]:
288
- """Symlinked rules whose target is not itself a rule path: the target's content could change unseen."""
354
+ """Symlinked rules whose target is not itself a rule path: the target's content could change unseen.
355
+
356
+ The user scope tracks a symlink by its link text (skills are often linked in from a checkout), so none count here.
357
+ """
358
+ if src.user:
359
+ return []
289
360
  bad = []
290
361
  for rel, target in sorted(src.links().items()):
291
362
  t = target.replace("\\", "/")
@@ -331,109 +402,29 @@ def _asset_module(name: str, rel: str):
331
402
  return _MODULES[name]
332
403
 
333
404
 
334
- def _ed():
335
- return _asset_module("dmb_reward_guard", "reward-guard/reward_guard.py")
336
-
337
-
338
- def _expand_seed(seed: bytes) -> tuple[int, bytes]:
339
- h = hashlib.sha512(seed).digest()
340
- scalar = int.from_bytes(h[:32], "little")
341
- scalar &= (1 << 254) - 8
342
- scalar |= 1 << 254
343
- return scalar, h[32:]
344
-
345
-
346
- def _encode_point(point) -> bytes:
347
- p = _ed()._ED_P
348
- x, y, z, _ = point
349
- zi = pow(z, p - 2, p)
350
- x, y = x * zi % p, y * zi % p
351
- return (y | ((x & 1) << 255)).to_bytes(32, "little")
352
-
353
-
354
- def public_key(seed: bytes) -> str:
355
- ed = _ed()
356
- scalar, _ = _expand_seed(seed)
357
- return _encode_point(ed._ed_mul(ed._ED_B, scalar)).hex()
358
-
359
-
360
- def sign(seed: bytes, msg: bytes) -> str:
361
- """RFC 8032 Ed25519 signature over msg with the 32-byte private seed."""
362
- ed = _ed()
363
- scalar, prefix = _expand_seed(seed)
364
- pub = _encode_point(ed._ed_mul(ed._ED_B, scalar))
365
- r = int.from_bytes(hashlib.sha512(prefix + msg).digest(), "little") % ed._ED_L
366
- big_r = _encode_point(ed._ed_mul(ed._ED_B, r))
367
- k = int.from_bytes(hashlib.sha512(big_r + pub + msg).digest(), "little") % ed._ED_L
368
- return (big_r + ((r + k * scalar) % ed._ED_L).to_bytes(32, "little")).hex()
369
-
370
-
371
- def verify(pubkey_hex: str, msg: bytes, sig_hex: str) -> bool:
372
- return bool(_ed().ed25519_verify(str(pubkey_hex), msg, str(sig_hex)))
373
-
374
-
375
- def derive_seed(passphrase: str, owner: dict) -> bytes:
376
- return hashlib.pbkdf2_hmac("sha256", passphrase.encode("utf-8"), bytes.fromhex(owner["salt"]),
377
- int(owner["iterations"]), dklen=32)
378
-
379
-
380
- def _new_owner(passphrase: str) -> tuple[dict, bytes]:
381
- if len(passphrase) < MIN_PASSPHRASE:
382
- raise RuleError(f"pick a passphrase of at least {MIN_PASSPHRASE} characters")
383
- owner = {"kdf": "pbkdf2-sha256", "salt": secrets.token_hex(16), "iterations": KDF_ITERATIONS}
384
- seed = derive_seed(passphrase, owner)
385
- owner["pubkey"] = public_key(seed)
386
- return owner, seed
387
-
388
-
389
- def _owner_seed(ledger: dict, passphrase: str) -> bytes:
390
- seed = derive_seed(passphrase, ledger["owner"])
391
- if public_key(seed) != ledger["owner"]["pubkey"]:
392
- raise RuleError("wrong passphrase: it does not match the owner key that signed this ledger")
393
- return seed
394
-
395
-
396
- def _canonical(ledger: dict) -> bytes:
397
- body = {k: v for k, v in ledger.items() if k != "signature"}
398
- return json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
399
-
400
-
401
405
  def parse_ledger(raw: bytes) -> dict:
406
+ """The ledger JSON. Ledgers written before approval dropped its passphrase still carry `owner` and `signature`;
407
+ those fields are ignored and removed on the next save."""
402
408
  try:
403
409
  data = json.loads(raw.decode("utf-8"))
404
410
  except (UnicodeDecodeError, ValueError) as exc:
405
411
  raise RuleError(f"{LEDGER_REL} is not valid JSON: {exc}") from None
406
- owner = data.get("owner") if isinstance(data, dict) else None
407
- if (not isinstance(owner, dict) or not isinstance(data.get("approved"), dict)
408
- or not isinstance(data.get("history"), list)
409
- or not all(isinstance(owner.get(k), str) for k in ("pubkey", "salt"))
410
- or not isinstance(owner.get("iterations"), int) or not 0 < owner["iterations"] <= MAX_KDF_ITERATIONS
411
- or not isinstance(data.get("links", []), list)):
412
+ if (not isinstance(data, dict) or not isinstance(data.get("approved"), dict)
413
+ or not isinstance(data.get("history"), list) or not isinstance(data.get("links", []), list)):
412
414
  raise RuleError(f"{LEDGER_REL} is malformed")
413
415
  return data
414
416
 
415
417
 
416
- def signature_ok(ledger: dict) -> bool:
417
- return verify(ledger["owner"]["pubkey"], _canonical(ledger), str(ledger.get("signature") or ""))
418
-
419
-
420
- def _key_chain_ok(start: str, entries: list, final: str) -> bool:
421
- key = start
422
- for entry in entries:
423
- if not isinstance(entry, dict) or entry.get("action") != "rotate" or entry.get("from") != key:
424
- continue
425
- nxt = str(entry.get("to") or "")
426
- if verify(key, ROTATE_TAG + nxt.encode("utf-8"), str(entry.get("sig") or "")):
427
- key = nxt
428
- return key == final
429
-
430
-
431
418
  def _resolves(root: Path, ref: str) -> bool:
432
419
  return _git_text(root, "rev-parse", "--verify", "--quiet", ref + "^{commit}") is not None
433
420
 
434
421
 
435
422
  def trust_bases(root: Path) -> list[str]:
436
- """Commits whose ledger the working one must extend: HEAD and the merge-base with the remote default branch."""
423
+ """Commits whose ledger the working one must extend: HEAD and the merge-base with the remote default branch.
424
+
425
+ The user ledger has none: it lives outside git, so the hooks are what protect it."""
426
+ if is_user_root(root):
427
+ return []
437
428
  bases = ["HEAD"] if _resolves(root, "HEAD") else []
438
429
  head = _git_text(root, "rev-parse", "HEAD") if bases else None
439
430
  default = _git_text(root, "symbolic-ref", "--quiet", "refs/remotes/origin/HEAD")
@@ -447,7 +438,10 @@ def trust_bases(root: Path) -> list[str]:
447
438
 
448
439
 
449
440
  def _trust_problem(ledger: dict, committed_raw: bytes | None, base: str) -> tuple[str, str] | None:
450
- """(rule, message) when a validly signed ledger does not extend the committed one at `base`, else None."""
441
+ """(rule, message) when the ledger does not extend the committed one at `base`, else None.
442
+
443
+ Every approval is recorded as a decision, so approvals that differ from `base` with no decision added were edited
444
+ into the ledger by hand."""
451
445
  try:
452
446
  committed = parse_ledger(committed_raw) if committed_raw is not None else None
453
447
  except RuleError:
@@ -455,12 +449,11 @@ def _trust_problem(ledger: dict, committed_raw: bytes | None, base: str) -> tupl
455
449
  if committed is None:
456
450
  return None
457
451
  n = len(committed["history"])
458
- extends = ledger["history"][:n] == committed["history"]
459
- if extends and _key_chain_ok(committed["owner"]["pubkey"], ledger["history"][n:], ledger["owner"]["pubkey"]):
460
- return None
461
- if ledger["owner"]["pubkey"] != committed["owner"]["pubkey"]:
462
- return "rules-owner-key-changed", f"The owner key differs from {base} with no rotation signed by the old key."
463
- return "rules-ledger-rollback", f"The rule ledger drops decisions recorded at {base} (an older ledger was restored)."
452
+ if ledger["history"][:n] != committed["history"]:
453
+ return "rules-ledger-rollback", f"The rule ledger drops decisions recorded at {base} (an older ledger was restored)."
454
+ if len(ledger["history"]) == n and ledger["approved"] != committed["approved"]:
455
+ return "rules-ledger-edited", f"The approvals differ from {base} with no decision recorded (the ledger was edited)."
456
+ return None
464
457
 
465
458
 
466
459
  def _committed(root: Path, bases: list[str]) -> list[tuple[str, bytes | None]]:
@@ -476,9 +469,9 @@ def _trust_warning(root: Path, ledger: dict) -> str:
476
469
 
477
470
 
478
471
  def trusted_approvals(root) -> dict | None:
479
- """Approved item hashes from a signed ledger that extends the committed ones; None when approval is off.
472
+ """Approved item hashes from a ledger that extends the committed ones; None when approval is off.
480
473
 
481
- A forged, rolled-back, re-keyed or deleted ledger yields {} so nothing it lists counts as approved.
474
+ A rolled-back or deleted ledger yields {} so nothing it lists counts as approved.
482
475
  """
483
476
  root = project_root(root)
484
477
  raw = Source(root).read(LEDGER_REL)
@@ -489,7 +482,7 @@ def trusted_approvals(root) -> dict | None:
489
482
  ledger = parse_ledger(raw)
490
483
  except RuleError:
491
484
  return {}
492
- if not signature_ok(ledger) or any(_trust_problem(ledger, c, b) for b, c in committed):
485
+ if any(_trust_problem(ledger, c, b) for b, c in committed):
493
486
  return {}
494
487
  return dict(ledger["approved"])
495
488
 
@@ -498,11 +491,7 @@ def _require_ledger(root: Path) -> dict:
498
491
  raw = Source(root).read(LEDGER_REL)
499
492
  if raw is None:
500
493
  raise RuleError("rule approval is off in this repo; the owner turns it on with `deepmodebot rules init`")
501
- ledger = parse_ledger(raw)
502
- if not signature_ok(ledger):
503
- raise RuleError(f"{LEDGER_REL} does not carry a valid owner signature. "
504
- f"Restore it from git (`git checkout HEAD -- {STORE_REL}`) before changing rules.")
505
- return ledger
494
+ return parse_ledger(raw)
506
495
 
507
496
 
508
497
  def _target(root: Path, rel: str, *, final_link_ok: bool = False) -> Path:
@@ -588,7 +577,7 @@ def _state(root: Path, src: Source, approved: dict, *, memory: bool) -> tuple[di
588
577
  approved = {i: s for i, s in approved.items() if memory or not i.startswith(MEMORY_PREFIX)}
589
578
  files = set(rule_files(src)) | {i for i in approved if not i.startswith(MEMORY_PREFIX)}
590
579
  current = src.read_many(sorted(files))
591
- if memory:
580
+ if memory and not src.user:
592
581
  mem = memory_rules(root)
593
582
  current.update(mem)
594
583
  current.update({i: None for i in approved if i.startswith(MEMORY_PREFIX) and i not in mem})
@@ -665,7 +654,7 @@ def load_proposals(root: Path) -> list[dict]:
665
654
  prop = json.loads(path.read_text(encoding="utf-8"))
666
655
  except (OSError, ValueError):
667
656
  continue
668
- if isinstance(prop, dict) and isinstance(prop.get("content"), str) and is_rule_path(str(prop.get("item", ""))):
657
+ if isinstance(prop, dict) and isinstance(prop.get("content"), str) and rule_path_in(root, str(prop.get("item", ""))):
669
658
  out.append({**prop, "file": f"{PROPOSALS_REL}/{path.name}"})
670
659
  return out
671
660
 
@@ -718,10 +707,14 @@ def _select(changes: list[dict], ids: list[str], select_all: bool) -> list[dict]
718
707
 
719
708
 
720
709
  def _approve_bytes(root: Path, ledger: dict, item: str, data: bytes, *, link: bool = False) -> None:
710
+ """Record `data` as the approved version of `item`, keeping a copy for diffs and rejects.
711
+
712
+ User-scope files over USER_BLOB_MAX (skill images, binaries) are pinned by hash only."""
721
713
  sha = _sha(data)
722
714
  blob = f"{APPROVED_REL}/{sha}"
723
715
  existing = _target(root, blob)
724
- if not (existing.is_file() and _sha(_eol(existing.read_bytes())) == sha):
716
+ big = is_user_root(root) and len(data) > USER_BLOB_MAX
717
+ if not big and not (existing.is_file() and _sha(_eol(existing.read_bytes())) == sha):
725
718
  _safe_write(root, blob, data)
726
719
  ledger["approved"][item] = sha
727
720
  links = set(ledger.get("links") or [])
@@ -744,10 +737,11 @@ def _forget(ledger: dict, item: str) -> None:
744
737
  ledger.pop("links", None)
745
738
 
746
739
 
747
- def _save(root: Path, ledger: dict, seed: bytes) -> None:
740
+ def _save(root: Path, ledger: dict) -> None:
748
741
  folder = _target(root, APPROVED_REL)
749
742
  ledger["version"] = LEDGER_VERSION
750
- ledger["signature"] = sign(seed, _canonical(ledger))
743
+ ledger.pop("owner", None)
744
+ ledger.pop("signature", None)
751
745
  _safe_write(root, LEDGER_REL, (json.dumps(ledger, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8"))
752
746
  keep = set(ledger["approved"].values())
753
747
  for blob in folder.iterdir() if folder.is_dir() else []:
@@ -787,6 +781,9 @@ def _decide_item(root: Path, ledger: dict, item: str, group: list[dict], current
787
781
  _approve_bytes(root, ledger, item, new, link=_is_link(root, item))
788
782
  else:
789
783
  if item in ledger["approved"] and old is None:
784
+ if is_user_root(root):
785
+ raise RuleError(f"{item} was approved by hash only (user files over {USER_BLOB_MAX >> 20} MB keep no "
786
+ "copy), so it cannot be restored here; restore it yourself or approve the new version")
790
787
  raise RuleError(f"the approved copy of {item} is missing, so it cannot be restored")
791
788
  _write_item(root, item, old, link=was_link)
792
789
  for prop in (c for c in group if c["kind"] == "proposal"):
@@ -797,11 +794,10 @@ def _decide_item(root: Path, ledger: dict, item: str, group: list[dict], current
797
794
  _safe_unlink(root, prop["file"])
798
795
 
799
796
 
800
- def decide(root: Path, ids: list[str], *, approve: bool, passphrase: str, select_all: bool = False) -> list[dict]:
797
+ def decide(root: Path, ids: list[str], *, approve: bool, select_all: bool = False) -> list[dict]:
801
798
  """Owner approves (or rejects) pending changes; rejecting puts the approved text back."""
802
799
  root = Path(root)
803
800
  ledger = _require_ledger(root)
804
- seed = _owner_seed(ledger, passphrase)
805
801
  src = Source(root)
806
802
  changes = pending_changes(root, src, ledger)
807
803
  chosen = _select(changes, ids, select_all)
@@ -820,60 +816,61 @@ def decide(root: Path, ids: list[str], *, approve: bool, passphrase: str, select
820
816
  for item, group in by_item.items():
821
817
  _decide_item(root, ledger, item, group, current, kept, approve)
822
818
  ledger["history"] += [_history(at, "approve" if approve else "reject", c) for c in group]
823
- _save(root, ledger, seed)
819
+ _save(root, ledger)
824
820
  return chosen
825
821
 
826
822
 
827
- def init_ledger(root: Path, passphrase: str, *, reset: bool = False) -> dict:
828
- """Owner turns rule approval on: every rule present now becomes the signed, approved baseline."""
823
+ def init_ledger(root: Path, *, accept_current: bool = True) -> dict:
824
+ """Owner turns rule approval on: every rule present now becomes the approved baseline.
825
+
826
+ With accept_current=False the baseline is empty, so every current rule waits for the owner's review."""
829
827
  root = Path(root)
830
828
  src = Source(root)
831
- raw = src.read(LEDGER_REL)
832
- history: list = []
833
- if raw is not None:
834
- if not reset:
835
- raise RuleError("rule approval is already on here; `rotate` changes the passphrase")
836
- try:
837
- history = list(parse_ledger(raw)["history"])
838
- except RuleError:
839
- history = []
829
+ if src.read(LEDGER_REL) is not None:
830
+ raise RuleError("rule approval is already on here")
840
831
  links = untracked_links(src)
841
832
  if links:
842
833
  listed = ", ".join(f"{rel} -> {target}" for rel, target in links)
843
834
  raise RuleError(f"these rule symlinks point at files that are not rule paths, so their content could change "
844
835
  f"unseen: {listed}. Replace each link with the real file (or link it to a rule path), then run init again.")
845
- owner, seed = _new_owner(passphrase)
846
- ledger = {"version": LEDGER_VERSION, "owner": owner, "approved": {}, "history": history}
836
+ ledger = {"version": LEDGER_VERSION, "approved": {}, "history": []}
847
837
  current, _ = _state(root, src, {}, memory=True)
848
- for item, data in sorted(current.items()):
838
+ for item, data in sorted(current.items()) if accept_current else ():
849
839
  if data is not None:
850
840
  _approve_bytes(root, ledger, item, data, link=_is_link(root, item))
851
- ledger["history"].append({"at": _now(), "action": "reset" if raw is not None else "init",
852
- "items": sorted(ledger["approved"])})
853
- _save(root, ledger, seed)
841
+ ledger["history"].append({"at": _now(), "action": "init", "items": sorted(ledger["approved"])})
842
+ _save(root, ledger)
843
+ if not is_user_root(root):
844
+ register_repo(root)
854
845
  return ledger
855
846
 
856
847
 
857
- def rotate_key(root: Path, old_passphrase: str, new_passphrase: str) -> dict:
858
- root = Path(root)
859
- ledger = _require_ledger(root)
860
- old_seed = _owner_seed(ledger, old_passphrase)
861
- owner, seed = _new_owner(new_passphrase)
862
- ledger["history"].append({"at": _now(), "action": "rotate", "from": ledger["owner"]["pubkey"], "to": owner["pubkey"],
863
- "sig": sign(old_seed, ROTATE_TAG + owner["pubkey"].encode("utf-8"))})
864
- ledger["owner"] = owner
865
- _save(root, ledger, seed)
866
- return ledger
848
+ def registered_repos() -> list[Path]:
849
+ """Repos whose owner turned rule approval on from this machine; `rules_watch.py` checks them for drift."""
850
+ try:
851
+ data = json.loads((user_home() / REGISTRY_REL).read_text(encoding="utf-8"))
852
+ except (OSError, ValueError):
853
+ return []
854
+ return [Path(p) for p in data.get("repos", []) if isinstance(p, str)] if isinstance(data, dict) else []
855
+
856
+
857
+ def register_repo(root: Path) -> None:
858
+ repos = {str(p) for p in registered_repos() if p.is_dir()} | {str(Path(root).resolve())}
859
+ body = json.dumps({"repos": sorted(repos)}, indent=2) + "\n"
860
+ try:
861
+ _safe_write(user_home(), REGISTRY_REL, body.encode("utf-8"))
862
+ except (OSError, RuleError):
863
+ pass
867
864
 
868
865
 
869
866
  def propose(root: Path, item: str, content: bytes, reason: str, by: str = "agent") -> dict:
870
867
  """Agent-facing: park a full new version of a rule file for the owner to approve. The rule file is untouched."""
871
868
  root = Path(root)
872
869
  rel = norm_rel(item)
873
- if not is_rule_path(rel):
870
+ if not rule_path_in(root, rel):
874
871
  raise RuleError(f"{rel} is not an agent rule file (see rule-paths.json), so it needs no approval")
875
872
  if Source(root).read(LEDGER_REL) is None:
876
- raise RuleError("rule approval is off in this repo, so there is nothing to propose to")
873
+ raise RuleError("rule approval is off here, so there is nothing to propose to")
877
874
  text = _text(content)
878
875
  if text is None:
879
876
  raise RuleError("a proposal must be UTF-8 text")
@@ -892,7 +889,7 @@ def _finding(severity: str, rule: str, file: str, message: str, fix: str) -> dic
892
889
 
893
890
 
894
891
  def check(root: Path, *, staged: bool = False, base: str | None = None) -> dict:
895
- """Gate: fail on unapproved rules, a forged, rolled-back or deleted ledger, or a swapped owner key.
892
+ """Gate: fail on unapproved rules, or a malformed, rolled-back or deleted ledger.
896
893
 
897
894
  Without `base` the ledger must extend the committed ones at HEAD and at the merge-base with the remote default
898
895
  branch; a CI run passes the protected branch it merges into.
@@ -915,7 +912,7 @@ def check(root: Path, *, staged: bool = False, base: str | None = None) -> dict:
915
912
  for label, committed_raw in committed:
916
913
  if committed_raw is not None:
917
914
  findings.append(_finding("P0", "rules-ledger-removed", LEDGER_REL,
918
- f"The owner-signed rule ledger exists at {label[:12]} but is gone now.",
915
+ f"The rule ledger exists at {label[:12]} but is gone now.",
919
916
  f"Restore it: `git checkout {label} -- {STORE_REL}`."))
920
917
  break
921
918
  return result(bool(findings))
@@ -928,17 +925,12 @@ def check(root: Path, *, staged: bool = False, base: str | None = None) -> dict:
928
925
  try:
929
926
  ledger = parse_ledger(raw)
930
927
  except RuleError as exc:
931
- findings.append(_finding("P0", "rules-ledger-forged", LEDGER_REL, str(exc), restore))
932
- return result(True)
933
- if not signature_ok(ledger):
934
- findings.append(_finding("P0", "rules-ledger-forged", LEDGER_REL,
935
- "The rule ledger was edited without the owner's passphrase (bad signature).", restore))
928
+ findings.append(_finding("P0", "rules-ledger-malformed", LEDGER_REL, str(exc), restore))
936
929
  return result(True)
937
930
  for label, committed_raw in committed:
938
931
  problem = _trust_problem(ledger, committed_raw, label[:12])
939
932
  if problem:
940
- findings.append(_finding("P0", problem[0], LEDGER_REL, problem[1],
941
- f"{restore} Owners change the passphrase with `deepmodebot rules rotate`."))
933
+ findings.append(_finding("P0", problem[0], LEDGER_REL, problem[1], restore))
942
934
  break
943
935
  approved = {i: s for i, s in ledger["approved"].items() if not (staged and i.startswith(MEMORY_PREFIX))}
944
936
  _, kept = _state(root, src, approved, memory=False)
@@ -972,10 +964,14 @@ def ledger_enabled(root: Path) -> bool:
972
964
 
973
965
 
974
966
  def _owning_root(full: str) -> Path | None:
975
- """The repo (or ledger-holding folder) a path belongs to: nearest ancestor with .git or a rule ledger."""
967
+ """The repo (or ledger-holding folder) a path belongs to: nearest ancestor with .git or a rule ledger.
968
+
969
+ The home folder's user ledger does not make home a repo; `_locations` adds the user scope separately."""
970
+ home = os.path.normcase(str(user_home()))
976
971
  cur = full if os.path.isdir(full) else os.path.dirname(full)
977
972
  while True:
978
- if os.path.lexists(os.path.join(cur, ".git")) or os.path.lexists(os.path.join(cur, LEDGER_REL)):
973
+ repo_ledger = os.path.lexists(os.path.join(cur, LEDGER_REL)) and os.path.normcase(os.path.abspath(cur)) != home
974
+ if os.path.lexists(os.path.join(cur, ".git")) or repo_ledger:
979
975
  return Path(cur)
980
976
  parent = os.path.dirname(cur)
981
977
  if parent == cur:
@@ -994,14 +990,21 @@ def _locations(cwd: Path, raw: str, removes: bool) -> list[tuple[Path, str]]:
994
990
  if not removes:
995
991
  variants.append(os.path.realpath(joined))
996
992
  out = []
993
+ home = user_home()
994
+ user_on = os.path.lexists(home / LEDGER_REL)
997
995
  for full in dict.fromkeys(variants):
998
996
  root = _owning_root(full)
999
- if root is None:
1000
- continue
1001
- rel = os.path.relpath(full, str(root)).replace(os.sep, "/")
1002
- if rel == "..":
1003
- continue
1004
- out.append((root, "" if rel == "." else rel))
997
+ if root is not None:
998
+ rel = os.path.relpath(full, str(root)).replace(os.sep, "/")
999
+ if rel != "..":
1000
+ out.append((root, "" if rel == "." else rel))
1001
+ if user_on:
1002
+ try:
1003
+ rel = os.path.relpath(full, str(home)).replace(os.sep, "/")
1004
+ except ValueError:
1005
+ continue
1006
+ if rel != ".." and not rel.startswith("../"):
1007
+ out.append((home, "" if rel == "." else rel))
1005
1008
  return out
1006
1009
 
1007
1010
 
@@ -1012,7 +1015,18 @@ def _rule_reason(rel: str) -> str:
1012
1015
  "`deepmodebot rules review`.")
1013
1016
 
1014
1017
 
1015
- STORE_REASON = (f"deepmodebot rule approval: {STORE_REL}/ holds the owner-signed rule ledger; agents may not write, "
1018
+ def _user_reason(rel: str) -> str:
1019
+ return (f"deepmodebot rule approval: `~/{_clean(rel)}` is a user-level agent rule (it loads into every agent "
1020
+ "session), and only the owner approves those. Write your draft under .scratch/, run "
1021
+ f"`\"{sys.executable or 'python3'}\" -B \"{SCRIPT}\" propose --user --item {_clean(rel)} --file <draft> "
1022
+ "--reason \"<why>\"`, and tell the owner to review it with `deepmodebot rules review --user`.")
1023
+
1024
+
1025
+ def _scope_reason(root: Path, rel: str) -> str:
1026
+ return _user_reason(rel) if is_user_root(root) else _rule_reason(rel)
1027
+
1028
+
1029
+ STORE_REASON = (f"deepmodebot rule approval: {STORE_REL}/ holds the owner's rule ledger; agents may not write, "
1016
1030
  "move or delete anything in it.")
1017
1031
  HOOK_REASON = ("deepmodebot rule approval: skipping git hooks (`--no-verify`, `commit -n`, `core.hooksPath`) is blocked "
1018
1032
  "in a repo with owner rule approval, because those hooks run the rule gate.")
@@ -1022,13 +1036,13 @@ UNSEEN_REASON = ("deepmodebot rule approval: this command changes files chosen b
1022
1036
 
1023
1037
  def _owner_reason(sub: str) -> str:
1024
1038
  return (f"deepmodebot rule approval: `rules {sub}` is owner-only. Ask the owner to run `deepmodebot rules {sub}` in "
1025
- "their own terminal. Never ask for, store or type the owner's passphrase.")
1039
+ "their own terminal.")
1026
1040
 
1027
1041
 
1028
- def _path_reason(rel: str) -> str | None:
1042
+ def _path_reason(root: Path, rel: str) -> str | None:
1029
1043
  if is_store_path(rel):
1030
1044
  return STORE_REASON
1031
- return _rule_reason(rel) if is_rule_path(rel) else None
1045
+ return _scope_reason(root, rel) if rule_path_in(root, rel) else None
1032
1046
 
1033
1047
 
1034
1048
  def _dir_has_rules(root: Path, rel: str) -> bool:
@@ -1040,10 +1054,10 @@ def _dir_has_rules(root: Path, rel: str) -> bool:
1040
1054
 
1041
1055
  def _literal_reason(cwd: Path, raw: str, removes: bool) -> str | None:
1042
1056
  for root, rel in _locations(cwd, raw, removes):
1043
- reason = _path_reason(rel) if rel else None
1057
+ reason = _path_reason(root, rel) if rel else None
1044
1058
  if reason is None and removes and (root / rel).is_dir() and not (root / rel).is_symlink():
1045
1059
  if ledger_enabled(root) and _dir_has_rules(root, rel):
1046
- return STORE_REASON if (STORE_REL + "/").startswith(rel.lower().strip("/") + "/") else _rule_reason(rel or ".")
1060
+ return STORE_REASON if (STORE_REL + "/").startswith(rel.lower().strip("/") + "/") else _scope_reason(root, rel or ".")
1047
1061
  if reason and ledger_enabled(root):
1048
1062
  return reason
1049
1063
  return None
@@ -1193,7 +1207,7 @@ def _find_reason(cwd: Path, args: list[str]) -> str | None:
1193
1207
  continue
1194
1208
  if paths and not any(fnmatch.fnmatchcase(shown, p) for p in paths):
1195
1209
  continue
1196
- return _rule_reason(item)
1210
+ return _scope_reason(root, item)
1197
1211
  return None
1198
1212
 
1199
1213
 
@@ -1385,9 +1399,6 @@ def status(root: Path) -> dict:
1385
1399
  return {"enabled": True, "root": str(root), "problem": "the committed rule ledger was deleted from the working tree",
1386
1400
  "items": [], "pending": 0, "proposals": []}
1387
1401
  ledger = parse_ledger(raw)
1388
- if not signature_ok(ledger):
1389
- return {"enabled": True, "root": str(root), "items": [], "pending": 0, "proposals": [],
1390
- "problem": "the ledger was edited without the owner passphrase (bad signature)"}
1391
1402
  problem = next((p[1] for p in (_trust_problem(ledger, c, b[:12]) for b, c in committed) if p), "")
1392
1403
  links = untracked_links(src)
1393
1404
  if links and not problem:
@@ -1404,8 +1415,9 @@ def status(root: Path) -> dict:
1404
1415
  for item in sorted(set(ledger["approved"]) | {c["item"] for c in drift}):
1405
1416
  mine = [c for c in drift if c["item"] == item]
1406
1417
  state = mine[0]["kind"] if mine and mine[0]["kind"] in ("new", "removed") else ("changed" if mine else "approved")
1407
- rows.append({"item": item, "state": state, "pending": len(mine), "approved_at": last.get(item, "")})
1408
- return {"enabled": True, "root": str(root), "problem": problem, "owner_key": ledger["owner"]["pubkey"],
1418
+ rows.append({"item": item, "state": state, "pending": len(mine), "approved_at": last.get(item, ""),
1419
+ "ids": [c["id"] for c in mine]})
1420
+ return {"enabled": True, "root": str(root), "problem": problem,
1409
1421
  "items": rows, "pending": len(changes), "proposals": [c for c in changes if c["kind"] == "proposal"]}
1410
1422
 
1411
1423
 
@@ -1420,22 +1432,16 @@ def _print_changes(changes: list[dict]) -> None:
1420
1432
  print(f" ... {len(c['diff']) - DIFF_LINES_SHOWN} more lines")
1421
1433
 
1422
1434
 
1423
- def _confirm(question: str, yes: bool) -> bool:
1424
- if yes:
1425
- return True
1435
+ def _confirm(question: str) -> bool:
1436
+ """The owner's yes/no. Only an interactive terminal can answer, so a piped `y` from a script does not count."""
1437
+ if not sys.stdin.isatty():
1438
+ raise RuleError("this asks the owner to confirm with y/N, so run it in your own terminal")
1426
1439
  try:
1427
1440
  return input(f"{question} [y/N] ").strip().lower() in ("y", "yes")
1428
1441
  except EOFError:
1429
1442
  return False
1430
1443
 
1431
1444
 
1432
- def _ask_new_passphrase() -> str:
1433
- first = getpass.getpass("New owner passphrase (8+ characters; never give it to an AI agent): ")
1434
- if getpass.getpass("Repeat the passphrase: ") != first:
1435
- raise RuleError("the two passphrases differ")
1436
- return first
1437
-
1438
-
1439
1445
  def _warn_untrusted(root: Path, ledger: dict) -> None:
1440
1446
  warning = _trust_warning(root, ledger)
1441
1447
  if warning:
@@ -1443,16 +1449,21 @@ def _warn_untrusted(root: Path, ledger: dict) -> None:
1443
1449
  f"Restore it with `git checkout HEAD -- {STORE_REL}`.")
1444
1450
 
1445
1451
 
1452
+ def _flag(root: Path) -> str:
1453
+ return " --user" if is_user_root(root) else ""
1454
+
1455
+
1446
1456
  def _cmd_status(root: Path, as_json: bool) -> int:
1447
1457
  res = status(root)
1448
1458
  if as_json:
1449
1459
  print(json.dumps(res, indent=2))
1450
1460
  return 0
1461
+ flag = _flag(root)
1451
1462
  if not res["enabled"]:
1452
1463
  print(f"Rule approval is off in {root}. Rule files agents load here ({len(res['rule_files'])}):")
1453
1464
  for item in res["rule_files"]:
1454
1465
  print(f" {_clean(item)}")
1455
- print("The owner turns approval on with `deepmodebot rules init`.")
1466
+ print(f"The owner turns approval on with `deepmodebot rules init{flag}`.")
1456
1467
  return 0
1457
1468
  if res["problem"]:
1458
1469
  print(f"WARNING: {LEDGER_REL} cannot be trusted: {_clean(res['problem']).rstrip('.')}. "
@@ -1460,7 +1471,7 @@ def _cmd_status(root: Path, as_json: bool) -> int:
1460
1471
  if not res["items"]:
1461
1472
  return 1
1462
1473
  approved = sum(1 for r in res["items"] if r["state"] == "approved")
1463
- print(f"Rule ledger for {root}: {approved} approved, {res['pending']} pending (owner key {res['owner_key'][:16]})")
1474
+ print(f"Rule ledger for {root}: {approved} approved, {res['pending']} pending")
1464
1475
  for row in res["items"]:
1465
1476
  note = f" {row['pending']} unapproved change(s)" if row["state"] == "changed" else ""
1466
1477
  when = f" approved {row['approved_at']}" if row["state"] == "approved" and row["approved_at"] else ""
@@ -1468,7 +1479,8 @@ def _cmd_status(root: Path, as_json: bool) -> int:
1468
1479
  for prop in res["proposals"]:
1469
1480
  print(f" PROPOSAL {_clean(prop['item'])} [{prop['id']}] by {prop['by']}: {prop['reason']}")
1470
1481
  if res["pending"]:
1471
- print("Review with `deepmodebot rules review`; decide with `deepmodebot rules approve <id>` or `reject <id>`.")
1482
+ print(f"Review with `deepmodebot rules review{flag}`; decide with `deepmodebot rules approve{flag} <id>` "
1483
+ f"or `reject{flag} <id>`.")
1472
1484
  return 0
1473
1485
 
1474
1486
 
@@ -1483,8 +1495,9 @@ def _cmd_review(root: Path, as_json: bool) -> int:
1483
1495
  print("No pending rule changes.")
1484
1496
  else:
1485
1497
  _print_changes(changes)
1486
- print(f"{len(changes)} pending. Owner: `deepmodebot rules approve <id> ...` or `deepmodebot rules reject <id> ...` "
1487
- "(`--all` for everything).")
1498
+ flag = _flag(root)
1499
+ print(f"{len(changes)} pending. Owner: `deepmodebot rules approve{flag} <id> ...` or "
1500
+ f"`deepmodebot rules reject{flag} <id> ...` (`--all` for everything).")
1488
1501
  return 0
1489
1502
 
1490
1503
 
@@ -1498,7 +1511,7 @@ def _cmd_log(root: Path, as_json: bool) -> int:
1498
1511
  for e in history:
1499
1512
  if e.get("action") in ("init", "reset"):
1500
1513
  print(f"{e.get('at')} {e['action']:7} baseline of {len(e.get('items', []))} rule(s)")
1501
- elif e.get("action") == "rotate":
1514
+ elif e.get("action") == "rotate": # written by ledgers from before approval dropped its passphrase
1502
1515
  print(f"{e.get('at')} rotate owner key {str(e.get('from'))[:16]} -> {str(e.get('to'))[:16]}")
1503
1516
  else:
1504
1517
  by = f" (proposed by {e.get('by', 'agent')})" if e.get("kind") == "proposal" else ""
@@ -1507,7 +1520,7 @@ def _cmd_log(root: Path, as_json: bool) -> int:
1507
1520
  return 0
1508
1521
 
1509
1522
 
1510
- def _cmd_decide(root: Path, ids: list[str], select_all: bool, approve: bool, yes: bool) -> int:
1523
+ def _cmd_decide(root: Path, ids: list[str], select_all: bool, approve: bool) -> int:
1511
1524
  ledger = _require_ledger(root)
1512
1525
  changes = pending_changes(root, Source(root), ledger)
1513
1526
  if select_all and not changes:
@@ -1517,36 +1530,40 @@ def _cmd_decide(root: Path, ids: list[str], select_all: bool, approve: bool, yes
1517
1530
  _warn_untrusted(root, ledger)
1518
1531
  _print_changes(chosen)
1519
1532
  verb = "Approve" if approve else "Reject"
1520
- if not _confirm(f"{verb} these {len(chosen)} change(s)?", yes):
1533
+ if not _confirm(f"{verb} these {len(chosen)} change(s)?"):
1521
1534
  print("Nothing changed.")
1522
1535
  return 1
1523
- done = decide(root, [c["id"] for c in chosen], approve=approve, passphrase=getpass.getpass("Owner passphrase: "))
1536
+ done = decide(root, [c["id"] for c in chosen], approve=approve)
1537
+ record = (f"Recorded in {root / STORE_REL}." if is_user_root(root)
1538
+ else f"Commit {STORE_REL}/ with the rule files to record it.")
1524
1539
  if approve:
1525
- print(f"Approved {len(done)} change(s). Commit {STORE_REL}/ with the rule files to record it.")
1540
+ print(f"Approved {len(done)} change(s). {record}")
1526
1541
  else:
1527
- print(f"Rejected {len(done)} change(s); the rules are back to their approved text. Commit {STORE_REL}/ to record it.")
1542
+ print(f"Rejected {len(done)} change(s); the rules are back to their approved text. {record}")
1528
1543
  return 0
1529
1544
 
1530
1545
 
1531
- def _cmd_init(root: Path, yes: bool, reset: bool) -> int:
1546
+ def _cmd_init(root: Path, accept_current: bool) -> int:
1532
1547
  src = Source(root)
1533
1548
  items = [i for i, d in _state(root, src, {}, memory=True)[0].items() if d is not None]
1534
- print(f"Turning on rule approval in {root}. These {len(items)} rules become the approved baseline:")
1549
+ if is_user_root(root) and not accept_current:
1550
+ print(f"Turning on approval for the user-level agent rules in {root}. Nothing is approved yet: these "
1551
+ f"{len(items)} files will each wait for your review (`deepmodebot rules review --user`):")
1552
+ question = "Turn it on and review them next?"
1553
+ else:
1554
+ print(f"Turning on rule approval in {root}. These {len(items)} rules become the approved baseline:")
1555
+ question = "Approve all of them exactly as they are now?"
1535
1556
  for item in sorted(items):
1536
1557
  print(f" {_clean(item)}")
1537
- if not _confirm("Approve all of them exactly as they are now?", yes):
1558
+ if not _confirm(question):
1538
1559
  print("Nothing changed. Fix or remove unwanted rules first, then run init again.")
1539
1560
  return 1
1540
- init_ledger(root, _ask_new_passphrase(), reset=reset)
1541
- print(f"Rule approval is on. Commit {STORE_REL}/ so every clone and CI run enforces it.")
1542
- return 0
1543
-
1544
-
1545
- def _cmd_rotate(root: Path) -> int:
1546
- old = getpass.getpass("Current owner passphrase: ")
1547
- _owner_seed(_require_ledger(root), old)
1548
- rotate_key(root, old, _ask_new_passphrase())
1549
- print(f"Owner key rotated. Commit {STORE_REL}/ to record it.")
1561
+ init_ledger(root, accept_current=accept_current or not is_user_root(root))
1562
+ if is_user_root(root):
1563
+ print("User rule approval is on. Agents can no longer change these files; review the pending ones with "
1564
+ "`deepmodebot rules review --user`.")
1565
+ else:
1566
+ print(f"Rule approval is on. Commit {STORE_REL}/ so every clone and CI run enforces it.")
1550
1567
  return 0
1551
1568
 
1552
1569
 
@@ -1572,22 +1589,38 @@ def _cmd_guard() -> int:
1572
1589
  cwd = req.get("cwd") or os.getcwd()
1573
1590
  paths = [p for p in req.get("paths") or [] if isinstance(p, str)]
1574
1591
  reason = guard(cwd, paths=paths, command=str(req.get("command") or ""))
1592
+ if reason:
1593
+ notify_blocked(reason, str(cwd))
1575
1594
  print(json.dumps({"block": bool(reason), "reason": reason or ""}))
1576
1595
  return 0
1577
1596
 
1578
1597
 
1598
+ def notify_blocked(reason: str, cwd: str) -> None:
1599
+ """Tell the owner a guard just denied an agent's rule write (rules_watch.py: log + desktop notification)."""
1600
+ try:
1601
+ spec = importlib.util.spec_from_file_location("dmb_rules_watch", HERE / "rules_watch.py")
1602
+ mod = importlib.util.module_from_spec(spec)
1603
+ spec.loader.exec_module(mod)
1604
+ mod.notify_blocked(reason, cwd)
1605
+ except (OSError, ImportError, ValueError):
1606
+ pass
1607
+
1608
+
1579
1609
  def build_parser() -> argparse.ArgumentParser:
1580
- p = argparse.ArgumentParser(description="Owner-approved agent rules: track, review and sign off every rule AI agents load.")
1610
+ p = argparse.ArgumentParser(description="Owner-approved agent rules: track, review and approve every rule AI agents load.")
1581
1611
  sub = p.add_subparsers(dest="cmd", required=True)
1612
+ def scoped(sp):
1613
+ sp.add_argument("--root", default=".")
1614
+ sp.add_argument("--user", action="store_true", help="The user-level agent rules in your home folder.")
1582
1615
  for name, text in (("status", "List tracked rules and what waits for approval."),
1583
1616
  ("review", "Show every pending rule change with its id and diff."),
1584
- ("log", "Show the signed decision history.")):
1617
+ ("log", "Show the decision history.")):
1585
1618
  sp = sub.add_parser(name, help=text)
1586
- sp.add_argument("--root", default=".")
1619
+ scoped(sp)
1587
1620
  sp.add_argument("--json", action="store_true")
1588
1621
  sp = sub.add_parser("propose", help="Agents: park a new version of a rule file for the owner.")
1589
- sp.add_argument("--root", default=".")
1590
- sp.add_argument("--item", required=True, help="Repo-relative rule file, e.g. AGENTS.md.")
1622
+ scoped(sp)
1623
+ sp.add_argument("--item", required=True, help="Rule file relative to the repo (or home with --user), e.g. AGENTS.md.")
1591
1624
  sp.add_argument("--file", required=True, help="Draft holding the full new file text.")
1592
1625
  sp.add_argument("--reason", required=True)
1593
1626
  sp.add_argument("--by", default="agent", help="Who proposes (harness or agent name).")
@@ -1598,18 +1631,15 @@ def build_parser() -> argparse.ArgumentParser:
1598
1631
  help="Commit whose ledger this one must extend (default: HEAD and the merge-base with origin's default branch).")
1599
1632
  sp.add_argument("--json", action="store_true")
1600
1633
  sub.add_parser("guard", help="Hook helper: JSON request on stdin, JSON verdict on stdout.")
1601
- sp = sub.add_parser("init", help="Owner: turn approval on; current rules become the signed baseline.")
1602
- sp.add_argument("--root", default=".")
1603
- sp.add_argument("--yes", action="store_true")
1604
- sp.add_argument("--reset", action="store_true", help="Replace a ledger whose passphrase is lost (history kept).")
1634
+ sp = sub.add_parser("init", help="Owner: turn approval on; current rules become the approved baseline.")
1635
+ scoped(sp)
1636
+ sp.add_argument("--accept-current", action="store_true",
1637
+ help="With --user: approve every current user rule instead of reviewing each one.")
1605
1638
  for name in ("approve", "reject"):
1606
1639
  sp = sub.add_parser(name, help=f"Owner: {name} pending changes by id.")
1607
1640
  sp.add_argument("ids", nargs="*")
1608
1641
  sp.add_argument("--all", action="store_true")
1609
- sp.add_argument("--root", default=".")
1610
- sp.add_argument("--yes", action="store_true")
1611
- sp = sub.add_parser("rotate", help="Owner: change the passphrase (signed by the old key).")
1612
- sp.add_argument("--root", default=".")
1642
+ scoped(sp)
1613
1643
  return p
1614
1644
 
1615
1645
 
@@ -1617,28 +1647,24 @@ def main(argv: list[str] | None = None) -> int:
1617
1647
  args = build_parser().parse_args(argv)
1618
1648
  if args.cmd == "guard":
1619
1649
  return _cmd_guard()
1620
- root = project_root(args.root)
1650
+ root = user_home() if getattr(args, "user", False) else project_root(args.root)
1621
1651
  try:
1622
1652
  if args.cmd in ("status", "review", "log"):
1623
1653
  return {"status": _cmd_status, "review": _cmd_review, "log": _cmd_log}[args.cmd](root, args.json)
1624
1654
  if args.cmd == "propose":
1625
1655
  prop = propose(root, args.item, Path(args.file).read_bytes(), args.reason, args.by)
1656
+ flag = _flag(root)
1626
1657
  print(f"Proposed [{prop['id']}] for {prop['item']}. The rule file is unchanged until the owner runs "
1627
- f"`deepmodebot rules review` and `deepmodebot rules approve {prop['id']}`.")
1658
+ f"`deepmodebot rules review{flag}` and `deepmodebot rules approve{flag} {prop['id']}`.")
1628
1659
  return 0
1629
1660
  if args.cmd == "check":
1630
1661
  return _cmd_check(root, args.staged, args.base, args.json)
1631
1662
  if args.cmd == "init":
1632
- return _cmd_init(root, args.yes, args.reset)
1633
- if args.cmd in ("approve", "reject"):
1634
- return _cmd_decide(root, args.ids, args.all, args.cmd == "approve", args.yes)
1635
- return _cmd_rotate(root)
1663
+ return _cmd_init(root, args.accept_current)
1664
+ return _cmd_decide(root, args.ids, args.all, args.cmd == "approve")
1636
1665
  except (RuleError, OSError) as exc:
1637
1666
  print(f"rules: {exc}", file=sys.stderr)
1638
1667
  return 1
1639
- except EOFError:
1640
- print("rules: the owner passphrase must be typed on a terminal", file=sys.stderr)
1641
- return 1
1642
1668
 
1643
1669
 
1644
1670
  if __name__ == "__main__":