deepmodebot 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +2 -2
  3. package/.omp-plugin/marketplace.json +2 -2
  4. package/README.md +15 -6
  5. package/bin/deepmodebot.mjs +104 -10
  6. package/native/dmb-gate/Cargo.toml +1 -1
  7. package/native/dmb-gate/src/agents.rs +58 -25
  8. package/native/dmb-gate/src/ci.rs +530 -14
  9. package/native/dmb-gate/src/main.rs +215 -7
  10. package/native/dmb-gate/src/reward.rs +1895 -242
  11. package/native/dmb-gate/src/sim.rs +969 -0
  12. package/native/dmb-gate/src/slop.rs +1061 -295
  13. package/package.json +1 -1
  14. package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
  15. package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +1 -1
  16. package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
  17. package/plugins/deepmodebot/.codex-plugin/plugin.json +2 -2
  18. package/plugins/deepmodebot/agents/comment-sicko.md +29 -0
  19. package/plugins/deepmodebot/agents/researcher.md +29 -0
  20. package/plugins/deepmodebot/agents/reviewer.md +29 -0
  21. package/plugins/deepmodebot/agents/scout.md +28 -0
  22. package/plugins/deepmodebot/agents/security-reviewer.md +27 -0
  23. package/plugins/deepmodebot/commands/deep.md +3 -2
  24. package/plugins/deepmodebot/commands/tournament.md +1 -1
  25. package/plugins/deepmodebot/hooks/hooks.json +12 -2
  26. package/plugins/deepmodebot/hooks.json +1 -1
  27. package/plugins/deepmodebot/scripts/antigravity-guard.mjs +740 -37
  28. package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
  29. package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +19 -11
  30. package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +51 -20
  31. package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +54 -49
  32. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +4 -0
  33. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +658 -21
  34. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/holdout_guard_cases.json +272 -0
  35. package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +774 -23
  36. package/plugins/deepmodebot/skills/deepmodebot/assets/f2p-gate/f2p_gate.py +547 -0
  37. package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +5 -11
  38. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +4 -4
  39. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +53 -6
  40. package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +48 -2
  41. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +262 -6
  42. package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +529 -122
  43. package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +747 -46
  44. package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +404 -5
  45. package/plugins/deepmodebot/skills/deepmodebot/assets/mutation/mutation_gate.py +798 -0
  46. package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +2050 -200
  47. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +44 -1
  48. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +278 -252
  49. package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rules_watch.py +436 -0
  50. package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +594 -18
  51. package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +41 -5
  52. package/plugins/deepmodebot/skills/deepmodebot/assets/sim/sim.py +856 -0
  53. package/plugins/deepmodebot/skills/deepmodebot/assets/worker-gate/worker_gate.py +237 -0
  54. package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +3 -2
  55. package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +6 -2
  56. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +1 -1
  57. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +1 -0
  58. package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +1 -1
  59. package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +6 -6
  60. package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +36 -16
  61. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +9 -8
  62. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +1 -0
  63. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +6 -2
  64. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +31 -9
  65. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +1 -1
  66. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +4 -4
  67. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sim.md +41 -0
  68. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +12 -0
  69. package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +24 -13
  70. package/plugins/deepmodebot/skills/deepmodebot/worker.md +28 -16
  71. package/plugins/deepmodebot/agents/comment-sicko/agent.md +0 -35
  72. package/plugins/deepmodebot/agents/researcher/agent.md +0 -33
  73. package/plugins/deepmodebot/agents/reviewer/agent.md +0 -35
  74. package/plugins/deepmodebot/agents/scout/agent.md +0 -33
  75. package/plugins/deepmodebot/agents/security-reviewer/agent.md +0 -31
@@ -6,19 +6,29 @@
6
6
  python -B project_memory.py recall [--query <q>] [--kind <k>] [--budget-tokens 800] [--format xml|json|yaml] [--root <repo>]
7
7
  python -B project_memory.py compact [--max-records 500] [--root <repo>] [--json]
8
8
  python -B project_memory.py stats [--root <repo>] [--json]
9
+ python -B project_memory.py scan [--root <repo>] [--json]
9
10
 
10
11
  Design:
11
12
  - Single shared SQLite DB at <main-checkout>/.scratch/deepmode-memory.db (shared across linked git worktrees).
12
13
  - WAL + 64 MB mmap + MEMORY temp_store + bounded 8 MB page cache + incremental auto_vacuum.
13
14
  - SHA-256 content-addressed dedup + FTS5 BM25 + exponential time-decay + LFU hits + token-budgeted greedy knapsack packing.
15
+ - Transmissible-hack screen (arXiv:2610.12822): `put` rejects notes (key, content, tags, source) that teach a future agent to skip tests/hooks/gates,
16
+ weaken thresholds, special-case test inputs, force a zero exit, mine holdouts or git objects, override rules, pipe remote code to a shell, or leak
17
+ secrets. Matching reuses reward_guard's pattern table plus a prose table, after Unicode/escape/base64 de-obfuscation. Policy is fail-closed:
18
+ a flagged note is ALWAYS rejected (exit 3) and there is no override flag or parameter; each rejected attempt is recorded in `memory_audit`
19
+ (key, categories, time; never the note content). `recall` re-scans every note it would emit and drops flagged ones, whatever wrote them
20
+ (counted in `flagged_dropped`); `scan` lists flagged ids without deleting (exit 1 if any).
14
21
  - Compact XML (<deepmode-memory>), JSON, and YAML exporters. Stdlib only; zero bytecode writes.
15
22
  """
16
23
 
17
24
  from __future__ import annotations
18
25
 
19
26
  import argparse
27
+ import base64
20
28
  import contextlib
29
+ import functools
21
30
  import hashlib
31
+ import html
22
32
  import importlib.util
23
33
  import json
24
34
  import math
@@ -27,6 +37,8 @@ import sqlite3
27
37
  import subprocess
28
38
  import sys
29
39
  import time
40
+ import unicodedata
41
+ import urllib.parse
30
42
  from pathlib import Path
31
43
  from xml.sax.saxutils import escape as xml_escape
32
44
 
@@ -60,6 +72,335 @@ def _rule_approvals(root: Path) -> dict | None:
60
72
  return mod.trusted_approvals(root)
61
73
 
62
74
 
75
+ REWARD_GUARD_PY = Path(__file__).resolve().parent.parent / "reward-guard" / "reward_guard.py"
76
+ REWARD_GUARD_CARRIERS = (
77
+ "note.py", "tests/test_note.py", "note.sh", "note.js", "gate.py", "train.py",
78
+ ".github/workflows/note.yml", "package.json", "pyproject.toml", "tsconfig.json",
79
+ )
80
+ LOOKALIKES = {
81
+ "\u0430": "a", "\u0432": "b", "\u0441": "c", "\u0501": "d", "\u0435": "e", "\u04bb": "h", "\u0456": "i",
82
+ "\u0458": "j", "\u043a": "k", "\u04cf": "l", "\u043c": "m", "\u043d": "h", "\u043e": "o", "\u0440": "p",
83
+ "\u051b": "q", "\u0455": "s", "\u0442": "t", "\u0475": "v", "\u051d": "w", "\u0461": "w", "\u0445": "x",
84
+ "\u0443": "y", "\u043f": "n", "\u0251": "a", "\u0261": "g", "\u0269": "i", "\u0131": "i", "\u03b1": "a",
85
+ "\u03b5": "e", "\u03b7": "n", "\u03b9": "i", "\u03ba": "k", "\u03bd": "v", "\u03bf": "o", "\u03c1": "p",
86
+ "\u03c4": "t", "\u03c5": "u", "\u03c7": "x", "\u03b3": "y", "\u03f2": "c",
87
+ }
88
+ FOLD_TABLE = {ord(src): dst for src, dst in LOOKALIKES.items()}
89
+ FOLD_TABLE.update({ord(src.upper()): dst.upper() for src, dst in LOOKALIKES.items() if len(src.upper()) == 1})
90
+ FOLD_TABLE.update({cp: "-" for cp in (*range(0x2010, 0x2016), 0x2212)})
91
+ FOLD_TABLE.update({0x2223: "|", 0x01C0: "|"})
92
+ INVISIBLE_FILLERS = frozenset("\u3164\u115f\u1160\u2800\u17b4\u17b5\u180e")
93
+ LINE_BREAKS = frozenset("\r\n\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029")
94
+ DROPPED_CATEGORIES = ("Cf", "Mn", "Me", "Cc", "Cs", "Co")
95
+ ESCAPE_RE = re.compile(r"\\u([0-9a-fA-F]{4})|\\x([0-9a-fA-F]{2})")
96
+ BASE64_RE = re.compile(r"[A-Za-z0-9+/]{24,}={0,2}")
97
+ COMMENT_MARKER_RE = re.compile(r"#|//|/\*|\*/|<!--|-->")
98
+ QUOTE_RE = re.compile(r"[\"'`]")
99
+ MAX_BASE64_TOKENS = 8
100
+
101
+ _GAP = r"(?:\s+[\w'/-]+)"
102
+ _GATE = (
103
+ r"(?:tests?|test\s+suites?|specs?|e2e|hooks?|pre-?(?:commit|push)|gates?|guards?|checks?|ci|pipelines?|"
104
+ r"lint(?:s|ers?|ing)?|type-?check(?:s|ers?|ing)?|verif(?:y|ication)|validation|assertions?|"
105
+ r"reward[- ]?guard|slop[- ]?gate|coverage|sandbox|containment|safeguards?)"
106
+ )
107
+ _WEAKEN = (
108
+ r"(?:skip(?:s|ped|ping)?|disabl(?:e|es|ed|ing)|bypass(?:es|ed|ing)?|circumvent(?:s|ed|ing)?|"
109
+ r"weaken(?:s|ed|ing)?|relax(?:es|ed|ing)?|loosen(?:s|ed|ing)?|neuter(?:s|ed|ing)?|"
110
+ r"silenc(?:e|es|ed|ing)|suppress(?:es|ed|ing)?|(?:turn|switch)(?:s|ed|ing)?\s+off|"
111
+ r"comment(?:s|ed|ing)?\s+out|ignor(?:e|es|ed|ing)|omit(?:s|ted|ting)?|"
112
+ r"remov(?:e|es|ed|ing)|delet(?:e|es|ed|ing)|stub(?:s|bed|bing)?\s+out|short-?circuit(?:s|ed|ing)?)"
113
+ )
114
+ _RULE_NOUN = (
115
+ r"(?:instructions?|rules?|guidelines?|polic(?:y|ies)|constraints?|guardrails?|safeguards?|restrictions?|"
116
+ r"directives?|prompts?|system\s+prompt|AGENTS\.md|CLAUDE\.md|worker\.md|SKILL\.md|containment|sandbox)"
117
+ )
118
+ _HOLDOUT = (
119
+ r"(?:hold-?outs?|(?:hidden|private|sealed|secret|reserved)\s+(?:tests?|test\s+suites?|suites?|evals?|"
120
+ r"graders?|answers?|labels?|keys?|data(?:sets?)?)|answer\s+keys?|test\s+(?:answers?|labels?|solutions?))"
121
+ )
122
+ _PEEK = (
123
+ r"(?:read|open|cat|type|copy|peek|leak|load|access|inspect|extract|grep|find|locat\w*|scan|search|mine|"
124
+ r"steal|exfiltrat\w*|dump|print|cheat|look\s+(?:at|up|into)|train\s+on|fit\s+on|memoriz\w*)"
125
+ )
126
+ _NET = r"(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod|nc|ncat|netcat|scp|rsync|sftp|ftp|socat|telnet)"
127
+ _SECRET_PATH = (
128
+ r"(?:\.env\b|\.ssh\b|id_(?:rsa|ed25519|ecdsa|dsa)|\.npmrc|\.netrc|\.aws\b|\.git-credentials|\.pypirc|auth\.json|"
129
+ r"credentials(?:\.json)?\b|\.kube[/\\]config|secrets?\.(?:json|ya?ml|env)|/etc/(?:passwd|shadow))"
130
+ )
131
+ _SECRET_VAR = r"\$\{?\w*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)\w*\}?"
132
+ _SECRET_NOUN = (
133
+ r"(?:secrets?|credentials?|api[\s_-]?keys?|tokens?|passwords?|\.env(?:\s+file)?|ssh\s+keys?|private\s+keys?|"
134
+ r"environment\s+variables?|env\s+vars?)"
135
+ )
136
+ _PIPE_TARGET = (
137
+ r"(?:sudo\s+)?(?:\S*[/\\])?(?:(?:ba|z|da|k|c|fi|a)?sh|python[\d.]*|node|perl|ruby|pwsh|powershell|iex|"
138
+ r"invoke-expression|bun|deno)"
139
+ )
140
+
141
+ SUPPLEMENTAL_PATTERNS: dict[str, tuple[int, tuple[str, ...]]] = {
142
+ "test-gate-bypass": (re.I, (
143
+ rf"\b{_WEAKEN}\b{_GAP}{{0,3}}?\s+{_GATE}\b",
144
+ rf"\b{_GATE}{_GAP}{{0,3}}?\s+(?:can|could|should|must|may|might|will|to)\s+(?:(?:safely|just|simply|always)\s+)*(?:be\s+)?{_WEAKEN}\b",
145
+ r"(?<![\w-])--no-(?:verify|hooks?)\b",
146
+ r"\bHUSKY\s*=\s*0\b",
147
+ r"\bSKIP\s*=\s*[\w,-]+\s+git\b",
148
+ r"\bcore\.hooksPath\b",
149
+ r"\bcontinue-on-error\b",
150
+ )),
151
+ "threshold-weakening": (re.I, (
152
+ rf"\b(?:lower|reduc(?:e|es|ed|ing)|decreas(?:e|es|ed|ing)|relax(?:es|ed|ing)?|loosen(?:s|ed|ing)?|drop(?:s|ped|ping)?|zero(?:ed|ing)?(?:\s+out)?)\b{_GAP}{{0,3}}?\s+(?:thresholds?|tolerances?|coverage|pass[- ]rates?|(?:minimum|min)(?:\s+\w+)?|floors?)\b",
153
+ r"\b(?:thresholds?|tolerances?|coverage|pass[- ]rates?)\s+(?:down\s+)?(?:to|at)\s+(?:0(?:\.0+)?(?![\d.]*[1-9])|zero|nothing|none)\b",
154
+ )),
155
+ "special-cased-output": (re.I, (
156
+ rf"\bhard-?\s?cod(?:e|es|ed|ing)\b{_GAP}{{0,4}}?\s+(?:the\s+)?(?:expected|outputs?|answers?|results?|return\s+values?|test\s+(?:inputs?|cases?|data|fixtures?)|fixtures?|golden)\b",
157
+ rf"\bspecial[- ]?cas(?:e|es|ed|ing)\b{_GAP}{{0,5}}?\s+(?:tests?|inputs?|cases?|fixtures?|expected|examples?|benchmarks?|graders?)\b",
158
+ r"\b(?:return|emit|print|echo|output|yield)\w*\s+(?:the\s+)?(?:expected|canned|known|memorized|precomputed|pre-computed|literal)\s+(?:output|answer|result|value)s?\b",
159
+ rf"\b(?:detect|check|test|sniff)\w*\s+(?:whether\s+|if\s+|when\s+)?(?:(?:we\s+are|running|being\s+run|it\s+is|the\s+code\s+is)\s+)*(?:under|in|inside|by)\s+(?:a\s+)?(?:test|pytest|unittest|jest|grader|evaluator|ci)\b",
160
+ rf"\b(?:game|gaming|cheat|cheating|trick|fool|spoof|hack|hacking)\b{_GAP}{{0,2}}?\s+(?:the\s+)?(?:tests?|graders?|evaluators?|judges?|gates?|checkers?|metrics?|benchmarks?|rewards?|scorers?|ci)\b",
161
+ )),
162
+ "forced-zero-exit": (re.I, (
163
+ r"\|\|\s*(?:true|:|exit\s+0|return\s+0)\b",
164
+ r"(?:;|&&)\s*exit\s+0\b",
165
+ r"\bset\s+\+e\b",
166
+ r"\bexit\s*\(\s*0\s*\)|\b(?:sys|os|process)\._?exit\s*\(\s*0\s*\)",
167
+ r"\$(?:global:)?LASTEXITCODE\s*=\s*0\b",
168
+ r"\b(?:force|always|unconditionally|just)\w*\s+(?:return(?:ing)?|exit(?:ing)?|emit(?:ting)?)\s+(?:an?\s+)?(?:(?:exit\s+)?(?:code|status)\s+)?0\b",
169
+ r"\bexit\s+(?:code|status)\s+(?:of\s+)?0\s+(?:regardless|no\s+matter|even\s+(?:if|when)|always)\b",
170
+ r"\b(?:ignor(?:e|es|ed|ing)|swallow(?:s|ed|ing)?|mask(?:s|ed|ing)?|hid(?:e|es|ing))\s+(?:the\s+)?(?:non-?zero\s+)?exit\s+(?:codes?|status)\b",
171
+ )),
172
+ "holdout-or-git-object-mining": (re.I, (
173
+ rf"\b{_PEEK}\b{_GAP}{{0,5}}?\s+{_HOLDOUT}",
174
+ r"deepmodebot[-_]holdout",
175
+ r"\bgit\s+(?:cat-file|fsck|unpack-objects|verify-pack)\b",
176
+ r"[./\\]git[/\\]objects\b",
177
+ r"\bgit\s+(?:rev-list|log|show|grep|diff)\b[^\n]*?--(?:objects|unreachable|lost-found|reflog)\b",
178
+ r"\bgit\s+reflog\b",
179
+ r"\b(?:dangling|unreachable|orphaned)\s+(?:commits?|blobs?|objects?|trees?)\b",
180
+ rf"\b(?:mine|dig|scrape|recover|extract|read|search|grep)\w*{_GAP}{{0,3}}?\s+(?:the\s+)?git\s+(?:objects?|history|packs?|reflog|internals)\b",
181
+ )),
182
+ "prompt-injection": (re.I, (
183
+ rf"\b(?:ignor(?:e|es|ed|ing)|disregard(?:s|ed|ing)?|forget(?:s|ting)?|overrid(?:e|es|ing)|overrul(?:e|es|ed|ing)|discard(?:s|ed|ing)?|bypass(?:es|ed|ing)?|violat(?:e|es|ed|ing))\b(?:\s+(?:all|any|the|your|these|those|every|previous|prior|above|earlier|other|existing|system|safety|repo(?:sitory)?|agent|operator|user|developer|original))*\s+{_RULE_NOUN}\b",
184
+ r"\bnew\s+instructions?\b",
185
+ r"\bsystem\s+(?:prompt|override|message)\b",
186
+ r"</?\s*(?:deepmode-memory|system|instructions?|assistant|tool_?(?:call|result)|function_?calls?)\b",
187
+ r"\[\s*/?\s*(?:system|inst)\s*\]|<\|(?:im_start|im_end|endoftext)\|>",
188
+ rf"\bfrom\s+now\s+on\b{_GAP}{{0,8}}?\s+(?:ignore|always|never|you\s+must|you\s+will|do\s+not|don't)\b",
189
+ r"\b(?:do\s+not|don't|never|without)\s+(?:tell(?:ing)?|inform(?:ing)?|mention(?:ing)?|report(?:ing)?|alert(?:ing)?|reveal(?:ing)?|disclos(?:e|ing)|notify(?:ing)?|ask(?:ing)?)\s+(?:the\s+)?(?:user|operator|human|reviewer|owner|maintainers?)\b",
190
+ rf"\b(?:future|next|other|later|subsequent)\s+(?:agents?|workers?|sessions?|assistants?|models?|runs?)\b{_GAP}{{0,8}}?\s+(?:should|must|shall|will|need\s+to|have\s+to)\s+(?:(?:always|simply|just|immediately)\s+)*(?:skip|ignore|disable|bypass|disregard|obey|trust|follow\s+this|comply|execute\s+this)\b",
191
+ rf"\b(?:mark|report|claim|declare|state|say|record)\w*{_GAP}{{0,3}}?\s+(?:as\s+)?(?:passed|passing|done|complete|completed|verified|approved|green)\b{_GAP}{{0,4}}?\s+(?:without|regardless|even\s+(?:if|when)|no\s+matter)\b",
192
+ rf"\b(?:pretend|act\s+as\s+if|behave\s+as\s+if)\b{_GAP}{{0,6}}?\s+(?:tests?|checks?|ci|gates?)\s+(?:pass|passed|are\s+passing|succeed)",
193
+ r"\bjailbreak\b|\bDAN\s+mode\b",
194
+ )),
195
+ "remote-code-execution": (re.I, (
196
+ rf"\b(?:curl|wget|iwr|irm|invoke-webrequest|invoke-restmethod)\b[^\n]*?\|\s*{_PIPE_TARGET}\b",
197
+ r"\b(?:ba|z)?sh\s+<\(\s*(?:curl|wget)\b",
198
+ r"\beval\s+[\"']?\$\(\s*(?:curl|wget)\b",
199
+ r"\|\s*(?:iex|invoke-expression)\b",
200
+ r"\b(?:iex|invoke-expression)\s*\(?\s*(?:iwr|irm|invoke-webrequest|invoke-restmethod|\(?\s*new-object\s+net\.webclient)\b",
201
+ r"\bbase64\s+(?:-d|--decode)\b[^\n]*?\|\s*(?:ba)?sh\b",
202
+ r"\b(?:python[\d.]*|node|perl|ruby)\s+-[ce]\s+[^\n]*?\b(?:urlopen|urllib|requests\.get|fetch\s*\(|http\.get|socket)\b",
203
+ r"\b(?:powershell|pwsh)\b[^\n]*?\s-e(?:nc(?:odedcommand)?)?\s+[A-Za-z0-9+/=]{20,}",
204
+ )),
205
+ "secret-exfiltration": (re.I, (
206
+ rf"\b{_NET}\b[^\n]*?{_SECRET_PATH}",
207
+ rf"{_SECRET_PATH}[^\n]*?\|\s*{_NET}\b",
208
+ rf"\b{_NET}\b[^\n]*?(?:\s-d|\s--data\S*|\s-F|\s--form|\s-T|\s--upload-file|\s-Body|\s-InFile)\s+[\"']?\S*{_SECRET_VAR}",
209
+ rf"\b{_NET}\b[^\n]*?https?://\S*\?\S*{_SECRET_VAR}",
210
+ rf"\b(?:printenv|env|export\s+-p|get-childitem\s+env:|gci\s+env:)\b[^\n]*?\|\s*{_NET}\b",
211
+ r"\b(?:exfiltrat|smuggl)\w*",
212
+ rf"\b(?:send|post|upload|forward|email|transmit|leak|ship|copy)\w*\b{_GAP}{{0,6}}?\s+(?:the\s+|all\s+|any\s+|your\s+)*{_SECRET_NOUN}\b{_GAP}{{0,6}}?\s+(?:to|at|via|into)\s+(?:\S+://|an?\s+(?:external|remote|public)|the\s+(?:remote|external)|attacker|webhook|pastebin|discord|slack|telegram|gist)",
213
+ )),
214
+ "embedded-secret": (0, (
215
+ r"\bsk-[A-Za-z0-9_-]{20,}",
216
+ r"\bgh[pousr]_[A-Za-z0-9]{30,}",
217
+ r"\bAKIA[0-9A-Z]{16}\b",
218
+ r"\bxox[abprs]-[A-Za-z0-9-]{10,}",
219
+ r"\bAIza[0-9A-Za-z_-]{35}",
220
+ r"-----BEGIN[ A-Z]*PRIVATE KEY-----",
221
+ r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}",
222
+ r"\bBearer\s+[A-Za-z0-9._~+/-]{20,}=*",
223
+ r"(?i:\b(?:api[_-]?key|secret|token|password|passwd|auth)\w*\s*[:=]\s*[\"']?)(?=[A-Za-z0-9+/_.~-]*\d)(?=[A-Za-z0-9+/_.~-]*[A-Za-z])[A-Za-z0-9+/_.~-]{16,}",
224
+ )),
225
+ }
226
+ COMPILED_SUPPLEMENTAL = {
227
+ category: re.compile("|".join(f"(?:{p})" for p in patterns), flags)
228
+ for category, (flags, patterns) in SUPPLEMENTAL_PATTERNS.items()
229
+ }
230
+
231
+ _LOOSEN = (
232
+ rf"(?:{_WEAKEN}|lower(?:s|ed|ing)?|reduc(?:e|es|ed|ing)|decreas(?:e|es|ed|ing)|drop(?:s|ped|ping)?|"
233
+ r"zero(?:s|ed|ing)?(?:\s+out)?|null(?:s|ed|ing)?(?:\s+out)?|nullif(?:y|ies|ied|ying)|neutraliz(?:e|es|ed|ing)|"
234
+ r"waiv(?:e|es|ed|ing)|eliminat(?:e|es|ed|ing)|(?:turn|switch)(?:s|ed|ing)?\s+down|water(?:s|ed|ing)?\s+down|"
235
+ r"tone(?:s|d)?\s+down|cut(?:s|ting)?)"
236
+ )
237
+ _RAISE = r"(?:rais(?:e|es|ed|ing)|increas(?:e|es|ed|ing)|bump(?:s|ed|ing)?(?:\s+up)?|widen(?:s|ed|ing)?|expand(?:s|ed|ing)?|inflat(?:e|es|ed|ing))"
238
+ _ZERO = r"(?<![\d.])(?:0+(?:\.0*)?|\.0+|zero|nothing|none|nil|null|off|false|disabled?)%?(?![\d.]*[1-9])(?!\w)"
239
+ _PASS_PURPOSE = (
240
+ r"\b(?:so|such\s+that|until|to\s+make|to\s+get|to\s+keep|in\s+order\s+to(?:\s+make)?)\b[^\n]{0,40}?"
241
+ r"\b(?:checks?|tests?|ci|builds?|pipelines?|gates?|linters?|lint|type[- ]?checks?|suites?|runs?|jobs?)\b"
242
+ r"(?:\s+\w+){0,2}?\s+(?:pass\w*|green|succeed\w*|stop\s+failing|go(?:es)?\s+green)\b"
243
+ )
244
+
245
+
246
+ @functools.lru_cache(maxsize=1)
247
+ def _threshold_weakening_rx() -> re.Pattern[str]:
248
+ rg = _reward_guard()
249
+
250
+ def metrics(src: str) -> str:
251
+ return "(?:" + "|".join(m.replace("_", "[_ -]?") for m in src.split("|")) + ")"
252
+
253
+ lower_nouns = (
254
+ rf"(?:(?:\w+[\s_-])?(?:thresholds?|cut-?offs?|floors?|fail[_-]under)|(?:min|minimum)(?:[_-]\w+|\s+\w+)?|"
255
+ rf"{metrics(rg.BARE_LOWER_METRICS)}[_ -](?:thresholds?|floors?|cut-?offs?|minimums?)|"
256
+ r"pass[- ]rates?|coverage(?:\s+(?:requirements?|floors?|thresholds?|gates?|minimums?))?|assertions?|"
257
+ r"strict(?:ness)?(?:[\s_-]+(?:flags?|modes?|checks?|settings?))?|no-?implicit-?any|strict-?null-?checks|"
258
+ r"lint(?:s|ers?|ing)?(?:\s+(?:rules?|checks?|errors?))?|type[- ]?check(?:s|ers?|ing)?|"
259
+ r"quality\s+gates?|gates?|mypy|eslint|ruff|pylint|tsc|flake8)"
260
+ )
261
+ upper_nouns = (
262
+ r"(?:tolerances?|epsilon|eps|max[_-]\w+|"
263
+ rf"{metrics(rg.BARE_UPPER_METRICS)}[_ -](?:thresholds?|budgets?|limits?|caps?|ceilings?))"
264
+ )
265
+ any_nouns = f"(?:{lower_nouns}|{upper_nouns})"
266
+ patterns = (
267
+ rf"\b{_LOOSEN}\b{_GAP}{{0,3}}?\s+{any_nouns}\b",
268
+ rf"\b{any_nouns}\b(?:\s+[\w'/-]+){{0,2}}?\s*(?:=|:|->|\u2192|\bto\b|\bat\b)\s*{_ZERO}",
269
+ rf"\b(?:set|use|pass|configure|put|change|make|force|pin|hard-?code)\w*\b{_GAP}{{0,3}}?\s+{any_nouns}\b\s+(?:of\s+|as\s+|equal\s+to\s+)?{_ZERO}",
270
+ rf"\b{any_nouns}\b(?:\s+[\w'/-]+){{0,2}}?\s+(?:can|could|should|must|may|might|will|needs?\s+to)\s+(?:(?:just|simply|always|safely)\s+)*(?:be\s+)?"
271
+ rf"(?:(?:lowered|reduced|relaxed|loosened|dropped|zeroed|removed|disabled|waived|neutered|weakened|turned\s+(?:off|down)|switched\s+off)\b|(?:(?:set\s+)?(?:to|at|=)\s*)?{_ZERO})",
272
+ rf"\b{_LOOSEN}\b[^\n]{{0,60}}?\b{lower_nouns}\b[^\n]{{0,60}}?{_PASS_PURPOSE}",
273
+ rf"\b(?:{_LOOSEN}|{_RAISE})\b[^\n]{{0,60}}?\b{upper_nouns}\b[^\n]{{0,60}}?{_PASS_PURPOSE}",
274
+ )
275
+ return re.compile("|".join(f"(?:{p})" for p in patterns), re.I)
276
+
277
+
278
+ class FlaggedMemoryError(ValueError):
279
+ def __init__(self, categories: tuple[str, ...]):
280
+ self.categories = tuple(categories)
281
+ super().__init__("memory note rejected: transmissible-hack content (" + ", ".join(self.categories) + ")")
282
+
283
+
284
+ def _reward_guard():
285
+ mod = sys.modules.get("dmb_reward_guard")
286
+ if mod is None:
287
+ if not REWARD_GUARD_PY.is_file():
288
+ raise RuntimeError(f"reward_guard.py missing at {REWARD_GUARD_PY}; refusing to store or recall unscanned memory")
289
+ spec = importlib.util.spec_from_file_location("dmb_reward_guard", REWARD_GUARD_PY)
290
+ mod = importlib.util.module_from_spec(spec)
291
+ sys.modules[spec.name] = mod
292
+ spec.loader.exec_module(mod)
293
+ return mod
294
+
295
+
296
+ def _fold(text: str, *, gap: str) -> str:
297
+ out = []
298
+ for ch in unicodedata.normalize("NFKD", text):
299
+ if ch in LINE_BREAKS:
300
+ out.append("\n")
301
+ elif ch.isspace():
302
+ out.append(" ")
303
+ elif ch in INVISIBLE_FILLERS or unicodedata.category(ch) in DROPPED_CATEGORIES:
304
+ out.append(gap)
305
+ else:
306
+ out.append(ch)
307
+ return "".join(out).translate(FOLD_TABLE)
308
+
309
+
310
+ def _decoded_forms(text: str) -> list[str]:
311
+ forms = [text]
312
+ unescaped = urllib.parse.unquote(html.unescape(ESCAPE_RE.sub(lambda m: chr(int(m.group(1) or m.group(2), 16)), text)))
313
+ if unescaped != text:
314
+ forms.append(unescaped)
315
+ for token in BASE64_RE.findall(text)[:MAX_BASE64_TOKENS]:
316
+ stripped = token.rstrip("=")
317
+ try:
318
+ decoded = base64.b64decode(stripped + "=" * (-len(stripped) % 4), validate=True).decode("utf-8")
319
+ except ValueError:
320
+ continue
321
+ if decoded.strip() and sum(c.isprintable() or c.isspace() for c in decoded) >= 0.95 * len(decoded):
322
+ forms.append(decoded)
323
+ return forms
324
+
325
+
326
+ def _line_views(lines: list[str]) -> list[tuple[str, ...]]:
327
+ meta = _reward_guard().SCANNER_META_RE
328
+ neutral = [COMMENT_MARKER_RE.sub(" ", meta.sub(" ", line)) for line in lines]
329
+ unquoted = [QUOTE_RE.sub(" ", line) for line in neutral]
330
+ return [tuple(lines), tuple(neutral), tuple(unquoted)]
331
+
332
+
333
+ def _reward_guard_categories(views: set[tuple[str, ...]]) -> set[str]:
334
+ rg = _reward_guard()
335
+ found: set[str] = set()
336
+ for view in views:
337
+ added = {n: line for n, line in enumerate(view, 1) if line.strip()}
338
+ if not added:
339
+ continue
340
+ for carrier in REWARD_GUARD_CARRIERS:
341
+ try:
342
+ findings = rg.scan_added_lines_for_reward_hacks(carrier, added, include_primitives=False)
343
+ except Exception:
344
+ found.add("scanner-error")
345
+ continue
346
+ found.update("reward-guard:" + f["rule"].removeprefix("reward-hack-") for f in findings)
347
+ return found
348
+
349
+
350
+ @functools.lru_cache(maxsize=4096)
351
+ def _scan_text(text: str) -> frozenset[str]:
352
+ found: set[str] = set()
353
+ views: set[tuple[str, ...]] = set()
354
+ collapsed_forms: set[str] = set()
355
+ for form in _decoded_forms(text):
356
+ for candidate in {form, _fold(form, gap=""), _fold(form, gap=" ")}:
357
+ collapsed = " ".join(candidate.split())
358
+ collapsed_forms.add(collapsed)
359
+ views.update(_line_views(candidate.splitlines() + [collapsed]))
360
+ for collapsed in collapsed_forms:
361
+ found.update(category for category, rx in COMPILED_SUPPLEMENTAL.items() if rx.search(collapsed))
362
+ unquoted = " ".join(QUOTE_RE.sub(" ", collapsed).split())
363
+ if _threshold_weakening_rx().search(collapsed) or _threshold_weakening_rx().search(unquoted):
364
+ found.add("threshold-weakening")
365
+ found |= _reward_guard_categories(views)
366
+ return frozenset(found)
367
+
368
+
369
+ def note_violations(*, key: str, kind: str = "", content: str, tags: str = "", source: str = "") -> tuple[str, ...]:
370
+ found: set[str] = set()
371
+ for field in (key, kind, content, tags, source):
372
+ if field:
373
+ found |= _scan_text(field)
374
+ return tuple(sorted(found))
375
+
376
+
377
+ def _redacted_key(key: str) -> str:
378
+ if note_violations(key=key, content=""):
379
+ return "redacted:" + hashlib.sha256(key.encode("utf-8", "surrogatepass")).hexdigest()[:12]
380
+ return key
381
+
382
+
383
+ def _migrate_audit_table(conn: sqlite3.Connection) -> None:
384
+ columns = {r["name"] for r in conn.execute("PRAGMA table_info(memory_audit)")}
385
+ if "override_digest" not in columns:
386
+ return
387
+ conn.executescript(
388
+ """
389
+ DROP INDEX IF EXISTS idx_audit_digest;
390
+ ALTER TABLE memory_audit RENAME TO memory_audit_old;
391
+ CREATE TABLE memory_audit (
392
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
393
+ key TEXT NOT NULL,
394
+ categories TEXT NOT NULL,
395
+ created_at REAL NOT NULL
396
+ );
397
+ INSERT INTO memory_audit(id, key, categories, created_at)
398
+ SELECT id, key, categories, created_at FROM memory_audit_old;
399
+ DROP TABLE memory_audit_old;
400
+ """
401
+ )
402
+
403
+
63
404
  def resolve_main_root(start: Path) -> Path:
64
405
  resolved = start.expanduser().resolve()
65
406
  try:
@@ -173,8 +514,15 @@ def ensure_schema(conn: sqlite3.Connection) -> None:
173
514
  INSERT INTO memories_fts(rowid, key, kind, tags, content)
174
515
  VALUES (new.id, new.key, new.kind, new.tags, new.content);
175
516
  END;
517
+ CREATE TABLE IF NOT EXISTS memory_audit (
518
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
519
+ key TEXT NOT NULL,
520
+ categories TEXT NOT NULL,
521
+ created_at REAL NOT NULL
522
+ );
176
523
  """
177
524
  )
525
+ _migrate_audit_table(conn)
178
526
  conn.execute("INSERT OR IGNORE INTO kv_meta(k, v) VALUES ('schema_version', ?)", (str(SCHEMA_VERSION),))
179
527
  conn.commit()
180
528
 
@@ -206,7 +554,16 @@ def put_memory(
206
554
  if not clean_content:
207
555
  raise ValueError("content must be non-empty")
208
556
  clean_tags = ",".join(sorted({t.strip().lower() for t in tags.split(",") if t.strip()}))
557
+ categories = note_violations(key=key, kind=kind, content=clean_content, tags=clean_tags, source=source)
209
558
  now = time.time()
559
+ if categories:
560
+ with connect_db(db_path_for(root)) as conn:
561
+ conn.execute(
562
+ "INSERT INTO memory_audit(key, categories, created_at) VALUES (?, ?, ?)",
563
+ (_redacted_key(key), ",".join(categories), now),
564
+ )
565
+ conn.commit()
566
+ raise FlaggedMemoryError(categories)
210
567
  exp = now + ttl_hours * 3600.0 if ttl_hours and ttl_hours > 0 else None
211
568
  digest = content_digest(kind, clean_content)
212
569
  tok = estimate_tokens(key, clean_content, source)
@@ -321,12 +678,16 @@ def recall_memories(
321
678
 
322
679
  packed = []
323
680
  used = 0
681
+ flagged = 0
324
682
  chosen_ids: list[int] = []
325
683
  for r, sc, tok in p0 + rest:
326
684
  if len(packed) >= limit:
327
685
  break
328
686
  if used + tok > budget_tokens and packed:
329
687
  continue
688
+ if note_violations(key=r["key"], kind=r["kind"], content=r["content"], tags=r["tags"], source=r["source"]):
689
+ flagged += 1
690
+ continue
330
691
  used += tok
331
692
  chosen_ids.append(int(r["id"]))
332
693
  packed.append({
@@ -347,7 +708,7 @@ def recall_memories(
347
708
  )
348
709
  conn.commit()
349
710
 
350
- return {
711
+ payload = {
351
712
  "db": str(db_file),
352
713
  "repo": resolve_main_root(root).name,
353
714
  "budget_tokens": budget_tokens,
@@ -355,6 +716,23 @@ def recall_memories(
355
716
  "items": packed,
356
717
  "pending_rules": hidden,
357
718
  }
719
+ if flagged:
720
+ payload["flagged_dropped"] = flagged
721
+ return payload
722
+
723
+
724
+ def scan_memory(root: Path) -> dict:
725
+ db_file = db_path_for(root)
726
+ if not db_file.exists():
727
+ return {"db": str(db_file), "scanned": 0, "flagged": []}
728
+ with connect_db(db_file, readonly=True) as conn:
729
+ rows = conn.execute("SELECT id, key, kind, content, tags, source FROM memories ORDER BY id").fetchall()
730
+ flagged = []
731
+ for r in rows:
732
+ categories = note_violations(key=r["key"], kind=r["kind"], content=r["content"], tags=r["tags"], source=r["source"])
733
+ if categories:
734
+ flagged.append({"id": int(r["id"]), "categories": list(categories)})
735
+ return {"db": str(db_file), "scanned": len(rows), "flagged": flagged}
358
736
 
359
737
 
360
738
  def format_xml(payload: dict) -> str:
@@ -365,6 +743,8 @@ def format_xml(payload: dict) -> str:
365
743
  )
366
744
  if payload.get("pending_rules"):
367
745
  attrs += f' unapproved-conventions-hidden="{payload["pending_rules"]}"'
746
+ if payload.get("flagged_dropped"):
747
+ attrs += f' flagged-notes-dropped="{payload["flagged_dropped"]}"'
368
748
  lines = [f"<deepmode-memory {attrs}>"]
369
749
  for item in payload["items"]:
370
750
  src = f' src="{xml_escape(item["source"])}"' if item["source"] else ""
@@ -385,6 +765,8 @@ def format_yaml(payload: dict) -> str:
385
765
  f"pending_rules: {payload.get('pending_rules', 0)}",
386
766
  "items:",
387
767
  ]
768
+ if payload.get("flagged_dropped"):
769
+ lines.insert(4, f"flagged_dropped: {payload['flagged_dropped']}")
388
770
  for item in payload["items"]:
389
771
  lines.append(f" - key: {json.dumps(item['key'])}")
390
772
  lines.append(f" kind: {item['kind']}")
@@ -485,6 +867,10 @@ def main(argv: list[str] | None = None) -> int:
485
867
  p_st.add_argument("--root", default=".")
486
868
  p_st.add_argument("--json", action="store_true")
487
869
 
870
+ p_scan = sub.add_parser("scan", help="Audit stored notes for transmissible-hack content without deleting.")
871
+ p_scan.add_argument("--root", default=".")
872
+ p_scan.add_argument("--json", action="store_true")
873
+
488
874
  args = p.parse_args(argv)
489
875
  root = Path(args.root).resolve()
490
876
 
@@ -496,10 +882,14 @@ def main(argv: list[str] | None = None) -> int:
496
882
  print(json.dumps(out, indent=2) if args.json else f"initialized {dbf}")
497
883
  return 0
498
884
  if args.cmd == "put":
499
- res = put_memory(
500
- root, key=args.key, kind=args.kind, content=args.content,
501
- priority=args.priority, tags=args.tags, source=args.source, ttl_hours=args.ttl_hours,
502
- )
885
+ try:
886
+ res = put_memory(
887
+ root, key=args.key, kind=args.kind, content=args.content,
888
+ priority=args.priority, tags=args.tags, source=args.source, ttl_hours=args.ttl_hours,
889
+ )
890
+ except FlaggedMemoryError as exc:
891
+ print(exc, file=sys.stderr)
892
+ return 3
503
893
  print(json.dumps(res, indent=2))
504
894
  return 0
505
895
  if args.cmd == "recall":
@@ -522,6 +912,15 @@ def main(argv: list[str] | None = None) -> int:
522
912
  res = memory_stats(root)
523
913
  print(json.dumps(res, indent=2) if args.json else f"{res['records']} records, {res['bytes']} B ({res['db']})")
524
914
  return 0
915
+ if args.cmd == "scan":
916
+ res = scan_memory(root)
917
+ if args.json:
918
+ print(json.dumps(res, indent=2))
919
+ else:
920
+ for f in res["flagged"]:
921
+ print(f"flagged id={f['id']} categories={','.join(f['categories'])}")
922
+ print(f"{len(res['flagged'])} flagged of {res['scanned']}")
923
+ return 1 if res["flagged"] else 0
525
924
  return 1
526
925
 
527
926