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.
- package/.agents/plugins/marketplace.json +1 -1
- package/.claude-plugin/marketplace.json +2 -2
- package/.omp-plugin/marketplace.json +2 -2
- package/README.md +15 -6
- package/bin/deepmodebot.mjs +104 -10
- package/native/dmb-gate/Cargo.toml +1 -1
- package/native/dmb-gate/src/agents.rs +58 -25
- package/native/dmb-gate/src/ci.rs +530 -14
- package/native/dmb-gate/src/main.rs +215 -7
- package/native/dmb-gate/src/reward.rs +1895 -242
- package/native/dmb-gate/src/sim.rs +969 -0
- package/native/dmb-gate/src/slop.rs +1061 -295
- package/package.json +1 -1
- package/plugins/deepmodebot/.antigravity-plugin/plugin.json +1 -1
- package/plugins/deepmodebot/.antigravity-plugin/skills/deep/SKILL.md +1 -1
- package/plugins/deepmodebot/.claude-plugin/plugin.json +1 -1
- package/plugins/deepmodebot/.codex-plugin/plugin.json +2 -2
- package/plugins/deepmodebot/agents/comment-sicko.md +29 -0
- package/plugins/deepmodebot/agents/researcher.md +29 -0
- package/plugins/deepmodebot/agents/reviewer.md +29 -0
- package/plugins/deepmodebot/agents/scout.md +28 -0
- package/plugins/deepmodebot/agents/security-reviewer.md +27 -0
- package/plugins/deepmodebot/commands/deep.md +3 -2
- package/plugins/deepmodebot/commands/tournament.md +1 -1
- package/plugins/deepmodebot/hooks/hooks.json +12 -2
- package/plugins/deepmodebot/hooks.json +1 -1
- package/plugins/deepmodebot/scripts/antigravity-guard.mjs +740 -37
- package/plugins/deepmodebot/skills/agent-harnesses/references/antigravity.md +2 -2
- package/plugins/deepmodebot/skills/deepmodebot/SKILL.md +19 -11
- package/plugins/deepmodebot/skills/deepmodebot/assets/agents-md/agents_md.py +51 -20
- package/plugins/deepmodebot/skills/deepmodebot/assets/autoroute/autoroute.py +54 -49
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude-guard.sh +4 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/claude_guard.py +658 -21
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/holdout_guard_cases.json +272 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/contain/omp-contain.ts +774 -23
- package/plugins/deepmodebot/skills/deepmodebot/assets/f2p-gate/f2p_gate.py +547 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/gap-audit/gap_audit.py +5 -11
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard-patterns.txt +4 -4
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.sh +53 -6
- package/plugins/deepmodebot/skills/deepmodebot/assets/git-guardrails/git-guard.ts +48 -2
- package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/local_ci.py +262 -6
- package/plugins/deepmodebot/skills/deepmodebot/assets/local-ci/slop_gate.py +529 -122
- package/plugins/deepmodebot/skills/deepmodebot/assets/loop/loop.py +747 -46
- package/plugins/deepmodebot/skills/deepmodebot/assets/memory/project_memory.py +404 -5
- package/plugins/deepmodebot/skills/deepmodebot/assets/mutation/mutation_gate.py +798 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/reward-guard/reward_guard.py +2050 -200
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule-paths.json +44 -1
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rule_ledger.py +278 -252
- package/plugins/deepmodebot/skills/deepmodebot/assets/rules/rules_watch.py +436 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/self-grill/self_grill.py +594 -18
- package/plugins/deepmodebot/skills/deepmodebot/assets/setup/project_setup.py +41 -5
- package/plugins/deepmodebot/skills/deepmodebot/assets/sim/sim.py +856 -0
- package/plugins/deepmodebot/skills/deepmodebot/assets/worker-gate/worker_gate.py +237 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/catalog.md +3 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/delegation.md +6 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/authoring-a-skill.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/hillclimb.md +1 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/playbooks/self-authoring.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/principles/no-reward-hacking.md +6 -6
- package/plugins/deepmodebot/skills/deepmodebot/references/rule-approval.md +36 -16
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/autoroute.md +9 -8
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/correct.md +1 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/inner-loop.md +6 -2
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/mutation-testing.md +31 -9
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/no-comments.md +1 -1
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/panel.md +4 -4
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/sim.md +41 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tdd.md +12 -0
- package/plugins/deepmodebot/skills/deepmodebot/references/techniques/tournament.md +24 -13
- package/plugins/deepmodebot/skills/deepmodebot/worker.md +28 -16
- package/plugins/deepmodebot/agents/comment-sicko/agent.md +0 -35
- package/plugins/deepmodebot/agents/researcher/agent.md +0 -33
- package/plugins/deepmodebot/agents/reviewer/agent.md +0 -35
- package/plugins/deepmodebot/agents/scout/agent.md +0 -33
- package/plugins/deepmodebot/agents/security-reviewer/agent.md +0 -31
|
@@ -8,52 +8,621 @@ Modes (first argument):
|
|
|
8
8
|
activate <data-dir> UserPromptSubmit: mark the session active when the prompt runs a /deepmodebot: command.
|
|
9
9
|
The mark outlives the process, so a resumed session (same session id) stays guarded;
|
|
10
10
|
marks older than 30 days are pruned here.
|
|
11
|
+
session-notice SessionStart: show the owner any agent rule changes they have not approved
|
|
12
|
+
(../rules/rules_watch.py), as a systemMessage plus context for the agent.
|
|
11
13
|
|
|
12
14
|
The allowed roots are the worktree holding the session's cwd and its main checkout (they differ in a linked
|
|
13
15
|
worktree, e.g. one under <root>/.worktrees/ or an Orca workspace), or the cwd itself outside git. Also allowed:
|
|
14
16
|
Claude Code's own plan and project-memory dirs, and any `extraWriteRoots` listed in a root's .deepmodebot.json
|
|
15
17
|
(only paths the user named).
|
|
16
18
|
Rule approval (../rules/rule_ledger.py) runs in every PreToolUse mode, active session or not: in a repo whose owner
|
|
17
|
-
turned it on,
|
|
18
|
-
|
|
19
|
+
turned it on, and for the user-level rules once `deepmodebot rules init --user` ran, Write/Edit/NotebookEdit on agent
|
|
20
|
+
rule files or the ledger are denied, and so are Bash commands that write them; the owner-only
|
|
21
|
+
`rules init|approve|reject` commands are denied everywhere. Each denial also notifies the owner.
|
|
22
|
+
In active sessions and for registered workers, every tool call (Bash included) that reaches the hidden holdout store
|
|
23
|
+
(~/.deepmodebot-holdout in any spelling) or mines git answers (cat-file --batch-all-objects, fsck, reflog recovery,
|
|
24
|
+
raw .git/objects reads, sweeps of / ~ /tmp for tests) is denied with the anti-reward-hacking message.
|
|
19
25
|
Other Bash, MCP tools and hook programs are not covered here.
|
|
20
26
|
"""
|
|
21
27
|
import importlib.util
|
|
22
28
|
import json
|
|
23
29
|
import os
|
|
30
|
+
import math
|
|
24
31
|
import re
|
|
25
32
|
import subprocess
|
|
33
|
+
from pathlib import Path
|
|
26
34
|
import sys
|
|
27
35
|
import time
|
|
28
36
|
|
|
29
37
|
sys.dont_write_bytecode = True
|
|
30
38
|
|
|
31
39
|
MARK_MAX_AGE_SECONDS = 30 * 24 * 3600
|
|
40
|
+
METRIC_FLOORS = {
|
|
41
|
+
"iou": 0.50, "ssim": 0.50, "dice": 0.50, "f1": 0.50, "auc": 0.50,
|
|
42
|
+
"accuracy": 0.50, "acc": 0.50, "precision": 0.50, "recall": 0.50,
|
|
43
|
+
"fidelity": 0.50, "similarity": 0.50, "coverage": 0.50, "pass-rate": 0.50, "win-rate": 0.50,
|
|
44
|
+
"clip": 0.15, "clip-score": 0.15, "ap": 0.15, "map": 0.15, "bleu": 0.15, "rouge": 0.15,
|
|
45
|
+
"psnr": 10.0, "protrusion": 0.02, "score": 0.05, "confidence": 0.05, "symmetry": 0.05,
|
|
46
|
+
"cov-fail-under": 50.0,
|
|
47
|
+
}
|
|
48
|
+
MIN_FLAG_VAL_RE = re.compile(
|
|
49
|
+
r"(?:^|[\s;&|(])(['\"]?--(?:(?:gate-)?mi(?:n(?:-([a-z0-9_-]*))?)?|(cov-fail-under))['\"]?(?:\s+|=)['\"]?\s*([-+]?(?:inf(?:inity)?|nan|(?:\d[\d_]*\.?[\d_]*|\.[\d_]+)(?:[eE][-+]?[\d_]+)?))\s*['\"]?)(?=$|[\s;&|)])",
|
|
50
|
+
re.I,
|
|
51
|
+
)
|
|
32
52
|
RULE_LEDGER = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "rules", "rule_ledger.py")
|
|
53
|
+
WORKER_GATE = os.path.join(os.path.dirname(RULE_LEDGER), "..", "worker-gate", "worker_gate.py")
|
|
54
|
+
NESTED_REASON = ("deepmodebot anti-stacking guard: nested subagent spawning is blocked (max_subagents=0); "
|
|
55
|
+
"execute inline or include ALLOW_NESTED_SUBAGENTS when explicitly authorized.")
|
|
33
56
|
REWARD_HACK_CMD_RE = re.compile(
|
|
34
|
-
r"(?:^|[
|
|
35
|
-
r"|(?:^|[
|
|
36
|
-
r"|(?:^|[
|
|
37
|
-
r"|\bgit\b[^\n;&|]*\bcommit\b[^\n;&|]*\s(?:-n|--no-verify)(?=$|[
|
|
38
|
-
r"|\
|
|
39
|
-
r"|\b(?:rm|del|unlink|Remove-Item)\b[^\n;&|]*(?:contract-lock\.json|reward-guard\.db)\b"
|
|
57
|
+
r"(?:^|[\s;&|(])['\"]?--(?:skip-reference|skip-fidelity|skip-gates?|skip-verify|skip-validation|bypass-gate|pass-if-no-tests|passWithNoTests|no-cov|(?:update-snapshots|snapshot-update|overwrite-snapshots|updateSnapshot)(?:=[^\s;&|)'\"]+)?)['\"]?(?=$|[\s;&|)])"
|
|
58
|
+
r"|(?:^|[\s;&|(])['\"]?(?:--require-spark-receipt(?:\s+|=)['\"]?false|--gate-mode(?:\s+|=)['\"]?off|--measured-gates(?:\s+|=)['\"]?off|--check-360(?:\s+|=)['\"]?(?:false|0))['\"]?(?=$|[\s;&|)])"
|
|
59
|
+
r"|(?:^|[\s;&|(])(?:(?:jest|vitest|playwright\s+test)\b[^\n;&|]*\s['\"]?(?:-u|--update)['\"]?|cargo\b[^\n;&|]*\sinsta\s+accept|(?:UPDATE_SNAPSHOTS|SNAPSHOT_UPDATE|INSTA_UPDATE)=['\"]?(?:1|true|always|all)['\"]?|go\s+test\b[^\n;&|]*\s-run(?:=|\s+)['\"]?\^\$['\"]?)(?=$|[\s;&|)])"
|
|
60
|
+
r"|\bgit\b[^\n;&|]*\bcommit\b[^\n;&|]*\s['\"]?(?:-n|--no-verify)['\"]?(?=$|[\s;&|)])"
|
|
61
|
+
r"|\b(?:reward-guard\.db|contract-lock\.json|judge_verdicts)\b"
|
|
40
62
|
r"|\breward_guard\.py\b[^\n;&|]*\brecord-judge\b",
|
|
41
63
|
re.I,
|
|
42
64
|
)
|
|
43
65
|
|
|
44
66
|
|
|
67
|
+
def _min_flag_floor(tok):
|
|
68
|
+
norm = (tok or "").lower().replace("_", "-")
|
|
69
|
+
if not norm:
|
|
70
|
+
return 0.50
|
|
71
|
+
if norm in ("p", "k", "port", "ports"):
|
|
72
|
+
return None
|
|
73
|
+
if norm in METRIC_FLOORS:
|
|
74
|
+
return METRIC_FLOORS[norm]
|
|
75
|
+
matches = [v for k, v in METRIC_FLOORS.items() if k.startswith(norm)]
|
|
76
|
+
return max(matches) if matches else None
|
|
77
|
+
|
|
45
78
|
def check_bash_reward_hack(cmd_text):
|
|
46
79
|
cleaned = re.sub(r"(-m|--message)(=|\s+)(\"[^\"]*\"|'[^']*')", r'\1 ""', str(cmd_text or ""))
|
|
47
80
|
for raw_ln in cleaned.replace("\\\r\n", " ").replace("\\\n", " ").splitlines():
|
|
48
81
|
ln = raw_ln.strip()
|
|
49
|
-
if not ln or re.match(r"^(?:grep|rg)\s+[
|
|
82
|
+
if not ln or re.match(r"^(?:grep|rg|echo|printf)\s+[^;&|<>()`$]*$", ln):
|
|
50
83
|
continue
|
|
84
|
+
for fm in MIN_FLAG_VAL_RE.finditer(ln):
|
|
85
|
+
floor = _min_flag_floor(fm.group(3) or fm.group(2))
|
|
86
|
+
if floor is not None:
|
|
87
|
+
try:
|
|
88
|
+
val = float(fm.group(4))
|
|
89
|
+
if not math.isfinite(val) or val < floor:
|
|
90
|
+
return fm.group(1).strip()
|
|
91
|
+
except ValueError:
|
|
92
|
+
pass
|
|
51
93
|
m = REWARD_HACK_CMD_RE.search(ln)
|
|
52
94
|
if m:
|
|
53
95
|
return m.group(0).strip()
|
|
54
96
|
return None
|
|
55
97
|
|
|
56
98
|
|
|
99
|
+
HOLDOUT_DIR = ".deepmodebot-holdout"
|
|
100
|
+
HOLDOUT_FALLBACK = "deepmodebot-holdout"
|
|
101
|
+
HOLDOUT_REASON = ("deepmodebot anti-reward-hacking guard blocked `{hit}`: builders may not read the hidden holdout store "
|
|
102
|
+
"or mine git objects, reflogs, or other agents' temp files for hidden answers.")
|
|
103
|
+
WINDOWS = sys.platform == "win32"
|
|
104
|
+
CASELESS = sys.platform in ("win32", "darwin")
|
|
105
|
+
TMP_ROOTS = ("/tmp", "/var/tmp", "/private/tmp", "/var/folders", "/private/var/folders", "c:/windows/temp")
|
|
106
|
+
HOME_SPELLING_RE = re.compile(
|
|
107
|
+
r"^(?:~|\$\{?(?:home|userprofile)\}?|%(?:home|userprofile)%|\$\{?env:(?:home|userprofile)\}?"
|
|
108
|
+
r"|%homedrive%%homepath%|\$\{?(?:env:)?homedrive\}?\$\{?(?:env:)?homepath\}?)(?=/|$)", re.I)
|
|
109
|
+
LOCAL_SPELLING_RE = re.compile(r"^(?:\$\{?(?:env:)?localappdata\}?|%localappdata%)(?=/|$)", re.I)
|
|
110
|
+
GIT_RAW_RE = re.compile(
|
|
111
|
+
r"(?:^|/)[^/]*\.git/(?:objects|logs|lost-found)(?:/|$)|(?:^|/)objects/(?:pack|info|[0-9a-f]{2})(?:/|$)", re.I)
|
|
112
|
+
GLOB_RE = re.compile(r"[*?\[]")
|
|
113
|
+
TEST_RE = re.compile(
|
|
114
|
+
r"(?:^|[^a-z0-9])(?:tests?|specs?|holdouts?|hidden|golden|graders?|solutions?|answers?|expected|fixtures?)(?:[^a-z0-9]|$)", re.I)
|
|
115
|
+
INTERPRETER_RE = re.compile(
|
|
116
|
+
r"^(?:python|py|node|bun|deno|perl|ruby|php|pwsh|powershell|bash|sh|zsh|dash|ksh|cmd|lua|tsx|ts-node|osascript|rscript)[0-9.]*$")
|
|
117
|
+
LOOP_RE = re.compile(r"(?:^|[\s;&|(])(?:for|while|until|read|xargs)(?=$|[\s;&|)])")
|
|
118
|
+
COMMAND_PREFIXES = frozenset(("sudo", "time", "command", "env", "nohup", "exec", "builtin", "nice", "then", "do", "else", "{"))
|
|
119
|
+
CD_COMMANDS = frozenset(("cd", "pushd", "chdir", "sl", "set-location"))
|
|
120
|
+
GREP_FAMILY = frozenset(("grep", "egrep", "fgrep", "rg", "ag", "ack", "sls", "select-string"))
|
|
121
|
+
ENUMERATORS = frozenset(("find", "fd", "fdfind", "ls", "dir", "tree", "gci", "get-childitem", "locate", "mlocate"))
|
|
122
|
+
CONTENT_READERS = frozenset((
|
|
123
|
+
"cat", "type", "head", "tail", "less", "more", "xargs", "strings", "bat", "tac", "nl", "od", "xxd", "hexdump",
|
|
124
|
+
"get-content", "gc", "select-string", "sls", "findstr"))
|
|
125
|
+
ALWAYS_RECURSIVE = frozenset(("rg", "ag", "ack", "zip", "7z", "7za", "rsync", "robocopy", "xcopy"))
|
|
126
|
+
GREP_ARG_FLAGS = frozenset((
|
|
127
|
+
"-e", "-f", "-m", "-A", "-B", "-C", "-g", "-t", "-T", "-j", "-M", "-d", "-D", "--regexp", "--file", "--max-count",
|
|
128
|
+
"--after-context", "--before-context", "--context", "--glob", "--iglob", "--type", "--type-not", "--include",
|
|
129
|
+
"--exclude", "--exclude-dir", "--include-dir", "--max-depth", "--threads", "-pattern", "-path", "-literalpath"))
|
|
130
|
+
GIT_GLOBAL_ARG_FLAGS = frozenset(("-C", "-c", "--git-dir", "--work-tree", "--namespace", "--super-prefix", "--config-env"))
|
|
131
|
+
GIT_DENIED_SUBCOMMANDS = frozenset(("unpack-file", "prune", "show-index", "verify-pack", "lost-found"))
|
|
132
|
+
GIT_REFLOG_SUBCOMMANDS = frozenset(("log", "show", "rev-list", "whatchanged", "shortlog", "format-patch", "diff", "archive", "grep"))
|
|
133
|
+
GIT_CONTENT_SUBCOMMANDS = frozenset(("show", "diff", "format-patch", "archive", "grep"))
|
|
134
|
+
GIT_RECOVER_SUBCOMMANDS = frozenset((
|
|
135
|
+
"show", "cat-file", "checkout", "restore", "switch", "cherry-pick", "archive", "diff", "format-patch", "read-tree",
|
|
136
|
+
"reset", "merge", "branch", "tag", "update-ref", "worktree", "apply"))
|
|
137
|
+
GIT_CONTENT_FLAGS = (
|
|
138
|
+
"--patch", "--patch-with-stat", "--patch-with-raw", "--cc", "--stat", "--numstat", "--shortstat", "--raw", "--name-only",
|
|
139
|
+
"--name-status", "--full-diff", "--pickaxe-regex", "--pickaxe-all", "--word-diff", "--textconv", "--objects",
|
|
140
|
+
"--summary", "--dirstat")
|
|
141
|
+
TOOL_PATH_KEYS = frozenset((
|
|
142
|
+
"path", "paths", "filepath", "file", "files", "notebookpath", "directory", "dir", "cwd", "root", "targetfile", "searchpath", "searchdirectory", "directorypath", "absolutepath", "abspath", "workdir", "filename"))
|
|
143
|
+
TOOL_PATTERN_KEYS = frozenset(("glob", "include", "pattern"))
|
|
144
|
+
SEARCH_TOOL_RE = re.compile(r"grep|glob|find|^ls$|list|tree|walk|^dir$|^rg$", re.I)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _homes():
|
|
148
|
+
env = os.environ
|
|
149
|
+
homes = []
|
|
150
|
+
for home in (env.get("HOME"), env.get("USERPROFILE"), (env.get("HOMEDRIVE") or "") + (env.get("HOMEPATH") or ""),
|
|
151
|
+
os.path.expanduser("~")):
|
|
152
|
+
if home and home != "~" and home not in homes:
|
|
153
|
+
homes.append(home)
|
|
154
|
+
return homes
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _prep(path):
|
|
158
|
+
text = path.replace("\\", "/")
|
|
159
|
+
text = re.sub(r"^file:/{2,3}(?:localhost/)?", "/", text, flags=re.I)
|
|
160
|
+
if re.match(r"^/[A-Za-z]:", text):
|
|
161
|
+
text = text[1:]
|
|
162
|
+
text = re.sub(r"^//[?.]/", "", text)
|
|
163
|
+
text = re.sub(r"^//(?:localhost|127\.0\.0\.1)/([A-Za-z])\$(?=/|$)", r"\1:", text, flags=re.I)
|
|
164
|
+
if WINDOWS:
|
|
165
|
+
text = re.sub(r"^/(?:mnt|cygdrive)/([A-Za-z])(?=/|$)", r"\1:", text)
|
|
166
|
+
text = re.sub(r"^/([A-Za-z])(?=/)", r"\1:", text)
|
|
167
|
+
return text
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _segs(path):
|
|
171
|
+
text = _prep(path)
|
|
172
|
+
drive = re.match(r"^[A-Za-z]:(?=/|$)", text)
|
|
173
|
+
if drive:
|
|
174
|
+
root, rest = drive.group(0), text[drive.end():]
|
|
175
|
+
elif text.startswith("/"):
|
|
176
|
+
root, rest = (os.getcwd()[:2] if WINDOWS else "/"), text
|
|
177
|
+
else:
|
|
178
|
+
return None
|
|
179
|
+
out = []
|
|
180
|
+
for part in rest.split("/"):
|
|
181
|
+
if part in ("", "."):
|
|
182
|
+
continue
|
|
183
|
+
if part == "..":
|
|
184
|
+
if out:
|
|
185
|
+
out.pop()
|
|
186
|
+
continue
|
|
187
|
+
if WINDOWS:
|
|
188
|
+
part = re.sub(r"[. ]+$", "", part.split(":", 1)[0])
|
|
189
|
+
if not part:
|
|
190
|
+
continue
|
|
191
|
+
out.append(part)
|
|
192
|
+
if CASELESS:
|
|
193
|
+
root, out = root.lower(), [part.lower() for part in out]
|
|
194
|
+
return [root] + out
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _unsegs(segs):
|
|
198
|
+
return (segs[0] if segs[0] != "/" else "") + "/" + "/".join(segs[1:])
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _abs(text, cwd):
|
|
202
|
+
return _segs(text) or _segs(_unsegs(cwd) + "/" + _prep(text))
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _real_segs(text, cwd):
|
|
206
|
+
raw = _prep(text)
|
|
207
|
+
try:
|
|
208
|
+
return _segs(os.path.realpath(raw if _segs(raw) else _unsegs(cwd) + "/" + raw))
|
|
209
|
+
except (OSError, ValueError):
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _unique_segs(paths):
|
|
214
|
+
found = []
|
|
215
|
+
for path in paths:
|
|
216
|
+
try:
|
|
217
|
+
real = os.path.realpath(path)
|
|
218
|
+
except (OSError, ValueError):
|
|
219
|
+
real = path
|
|
220
|
+
for segs in (_segs(path), _segs(real)):
|
|
221
|
+
if segs and segs not in found:
|
|
222
|
+
found.append(segs)
|
|
223
|
+
return found
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _braces(text, cap=64):
|
|
227
|
+
match = re.search(r"\{([^{}]*,[^{}]*)\}", text)
|
|
228
|
+
if not match:
|
|
229
|
+
return [text]
|
|
230
|
+
out = []
|
|
231
|
+
for alt in match.group(1).split(","):
|
|
232
|
+
out.extend(_braces(text[:match.start()] + alt + text[match.end():], cap))
|
|
233
|
+
if len(out) >= cap:
|
|
234
|
+
break
|
|
235
|
+
return out[:cap]
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _variants(word):
|
|
239
|
+
out = [word]
|
|
240
|
+
for match in re.finditer(r"=", word):
|
|
241
|
+
out.append(word[match.end():])
|
|
242
|
+
for match in re.finditer(r":(?=[~$%/\\])", word):
|
|
243
|
+
out.append(word[match.end():])
|
|
244
|
+
return [v for i, v in enumerate(out) if v and v not in out[:i]]
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def _seg_match(glob, name):
|
|
248
|
+
if not GLOB_RE.search(glob):
|
|
249
|
+
return glob == name
|
|
250
|
+
if glob[0] in "*?[" and name.startswith("."):
|
|
251
|
+
return False
|
|
252
|
+
out, i = [], 0
|
|
253
|
+
while i < len(glob):
|
|
254
|
+
ch = glob[i]
|
|
255
|
+
close = glob.find("]", i + 2) if ch == "[" else -1
|
|
256
|
+
if ch == "*":
|
|
257
|
+
out.append("[^/]*")
|
|
258
|
+
elif ch == "?":
|
|
259
|
+
out.append("[^/]")
|
|
260
|
+
elif close != -1:
|
|
261
|
+
body = glob[i + 1:close]
|
|
262
|
+
out.append("[" + ("^" + body[1:] if body[:1] in ("!", "^") else body).replace("\\", "\\\\") + "]")
|
|
263
|
+
i = close
|
|
264
|
+
else:
|
|
265
|
+
out.append(re.escape(ch))
|
|
266
|
+
i += 1
|
|
267
|
+
try:
|
|
268
|
+
return re.match("^" + "".join(out) + "$", name) is not None
|
|
269
|
+
except re.error:
|
|
270
|
+
return True
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _named_literal(seg):
|
|
274
|
+
return not GLOB_RE.search(seg) or re.sub(r"[.*?\[\]!^\-]", "", seg) != ""
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _gmatch(glob, i, root, j):
|
|
278
|
+
if j == len(root):
|
|
279
|
+
return i < len(glob) or (i > 0 and _named_literal(glob[i - 1]))
|
|
280
|
+
if i == len(glob):
|
|
281
|
+
return False
|
|
282
|
+
if glob[i] == "**":
|
|
283
|
+
return _gmatch(glob, i + 1, root, j) or _gmatch(glob, i, root, j + 1)
|
|
284
|
+
return _seg_match(glob[i], root[j]) and _gmatch(glob, i + 1, root, j + 1)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _base(word):
|
|
288
|
+
name = word.replace("\\", "/").split("/")[-1].lower()
|
|
289
|
+
return name[:-4] if name.endswith(".exe") else name
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _lead(words):
|
|
293
|
+
prefixed = False
|
|
294
|
+
for i, word in enumerate(words):
|
|
295
|
+
if re.match(r"^[A-Za-z_]\w*=", word) or _base(word) in COMMAND_PREFIXES:
|
|
296
|
+
prefixed = True
|
|
297
|
+
elif not (prefixed and word.startswith("-")):
|
|
298
|
+
return i
|
|
299
|
+
return len(words)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
def _opt(token, full, minlen):
|
|
303
|
+
name = token.split("=", 1)[0]
|
|
304
|
+
return name.startswith("--") and len(name) >= minlen and full.startswith(name)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
class HoldoutScan:
|
|
308
|
+
def __init__(self, cwd):
|
|
309
|
+
self.homes = _homes()
|
|
310
|
+
self.cwd = _segs(cwd) or _segs(os.getcwd()) or ["/"]
|
|
311
|
+
stores = [os.path.join(home, HOLDOUT_DIR) for home in self.homes]
|
|
312
|
+
local = os.environ.get("LOCALAPPDATA")
|
|
313
|
+
if local:
|
|
314
|
+
stores.append(os.path.join(local, HOLDOUT_FALLBACK))
|
|
315
|
+
stores.append("/tmp/" + HOLDOUT_FALLBACK)
|
|
316
|
+
self.roots = _unique_segs(stores)
|
|
317
|
+
self.tmp = _unique_segs(list(TMP_ROOTS) + [os.path.join(home, "AppData", "Local", "Temp") for home in self.homes])
|
|
318
|
+
self.real_budget = 200
|
|
319
|
+
|
|
320
|
+
def expand(self, item):
|
|
321
|
+
match = HOME_SPELLING_RE.match(item)
|
|
322
|
+
if match:
|
|
323
|
+
return [home + item[match.end():] for home in self.homes] or [item]
|
|
324
|
+
local = os.environ.get("LOCALAPPDATA")
|
|
325
|
+
match = LOCAL_SPELLING_RE.match(item)
|
|
326
|
+
return [local + item[match.end():]] if match and local else [item]
|
|
327
|
+
|
|
328
|
+
def candidates(self, word, cwd):
|
|
329
|
+
found = []
|
|
330
|
+
for variant in _variants(word.replace("\\", "/")):
|
|
331
|
+
for item in _braces(variant):
|
|
332
|
+
for text in self.expand(item):
|
|
333
|
+
found.append(_abs(text, cwd))
|
|
334
|
+
if self.real_budget > 0 and "/" in _prep(text) and not GLOB_RE.search(text):
|
|
335
|
+
self.real_budget -= 1
|
|
336
|
+
real = _real_segs(text, cwd)
|
|
337
|
+
if real:
|
|
338
|
+
found.append(real)
|
|
339
|
+
return found
|
|
340
|
+
|
|
341
|
+
def reaches(self, cands):
|
|
342
|
+
return any(_gmatch(c, 0, r, 0) for c in cands for r in self.roots)
|
|
343
|
+
|
|
344
|
+
def above(self, cands, widen=False):
|
|
345
|
+
heads = [_literal_head(c) if widen else c for c in cands]
|
|
346
|
+
return any(not any(GLOB_RE.search(s) for s in h) and len(h) <= len(r) and r[:len(h)] == h
|
|
347
|
+
for h in heads for r in self.roots)
|
|
348
|
+
|
|
349
|
+
def in_tmp(self, segs):
|
|
350
|
+
return any(len(segs) >= len(t) and segs[:len(t)] == t for t in self.tmp) and not (
|
|
351
|
+
len(segs) >= len(self.cwd) and segs[:len(self.cwd)] == self.cwd)
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _literal_head(segs):
|
|
355
|
+
for i, seg in enumerate(segs):
|
|
356
|
+
if GLOB_RE.search(seg):
|
|
357
|
+
return segs[:i]
|
|
358
|
+
return segs
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
def _computed_home(word):
|
|
362
|
+
for variant in _variants(word):
|
|
363
|
+
match = HOME_SPELLING_RE.match(variant)
|
|
364
|
+
first = variant[match.end():].lstrip("/").split("/", 1)[0] if match else ""
|
|
365
|
+
if first and re.search(r"\$|%[A-Za-z_]\w*%", first):
|
|
366
|
+
return True
|
|
367
|
+
return False
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _grep_skips(words):
|
|
371
|
+
skips = set()
|
|
372
|
+
for i, word in enumerate(words):
|
|
373
|
+
name = _base(word)
|
|
374
|
+
if name not in GREP_FAMILY:
|
|
375
|
+
continue
|
|
376
|
+
k, have_pattern = i + 1, False
|
|
377
|
+
while k < len(words) and words[k].startswith("-") and words[k] != "-" and words[k] != "--":
|
|
378
|
+
flag = words[k] if len(words[k]) <= 2 else words[k].lower()
|
|
379
|
+
if flag.startswith("--regexp="):
|
|
380
|
+
skips.add(k)
|
|
381
|
+
have_pattern = True
|
|
382
|
+
if flag in ("-e", "--regexp", "-pattern"):
|
|
383
|
+
have_pattern = True
|
|
384
|
+
skips.add(k + 1)
|
|
385
|
+
k += 2 if flag in GREP_ARG_FLAGS or (name == "rg" and flag == "-r") else 1
|
|
386
|
+
if k < len(words) and words[k] == "--":
|
|
387
|
+
k += 1
|
|
388
|
+
if not have_pattern and k < len(words):
|
|
389
|
+
skips.add(k)
|
|
390
|
+
return skips
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _content_flag(token):
|
|
394
|
+
return (any(_opt(token, full, 4) for full in GIT_CONTENT_FLAGS) or re.fullmatch(r"-\d*[pu]", token) is not None
|
|
395
|
+
or token.startswith(("-S", "-G")))
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _git_calls(words):
|
|
399
|
+
calls = []
|
|
400
|
+
for i, word in enumerate(words):
|
|
401
|
+
name = _base(word)
|
|
402
|
+
dashed = re.fullmatch(r"git-([a-z-]+)", name)
|
|
403
|
+
if dashed:
|
|
404
|
+
calls.append((dashed.group(1), words[i + 1:]))
|
|
405
|
+
elif name == "git":
|
|
406
|
+
k = i + 1
|
|
407
|
+
while k < len(words) and words[k].startswith("-"):
|
|
408
|
+
k += 2 if words[k] in GIT_GLOBAL_ARG_FLAGS else 1
|
|
409
|
+
if k < len(words):
|
|
410
|
+
calls.append((words[k].lower(), words[k + 1:]))
|
|
411
|
+
return calls
|
|
412
|
+
|
|
413
|
+
|
|
414
|
+
def _reflog_flagged(sub, args):
|
|
415
|
+
return sub in GIT_REFLOG_SUBCOMMANDS and any(
|
|
416
|
+
a == "-g" or _opt(a, "--reflog", 6) or _opt(a, "--walk-reflogs", 7) for a in args)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def _git_hit(sub, args):
|
|
420
|
+
if sub == "cat-file" and any(_opt(a, "--batch-all-objects", 9) for a in args):
|
|
421
|
+
return "git cat-file --batch-all-objects"
|
|
422
|
+
if sub in ("fsck", "fsck-objects"):
|
|
423
|
+
bad = any(_opt(a, "--lost-found", 4) or _opt(a, "--unreachable", 4) or _opt(a, "--dangling", 3)
|
|
424
|
+
or _opt(a, "--no-reflogs", 6) for a in args)
|
|
425
|
+
if bad or not any(_opt(a, "--no-dangling", 8) for a in args):
|
|
426
|
+
return "git fsck"
|
|
427
|
+
if sub in GIT_DENIED_SUBCOMMANDS:
|
|
428
|
+
return "git " + sub
|
|
429
|
+
content = any(_content_flag(a) for a in args)
|
|
430
|
+
if (_reflog_flagged(sub, args) and (sub in GIT_CONTENT_SUBCOMMANDS or content)) or (sub == "reflog" and content):
|
|
431
|
+
return "git " + sub + " reflog content"
|
|
432
|
+
return None
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _git_role(sub, args):
|
|
436
|
+
feeder = sub == "reflog" or _reflog_flagged(sub, args) or (
|
|
437
|
+
sub == "rev-list" and any(_opt(a, "--objects", 5) for a in args)
|
|
438
|
+
and any(a == "--all" or _opt(a, "--reflog", 6) for a in args))
|
|
439
|
+
sink = sub in GIT_RECOVER_SUBCOMMANDS or (sub == "cat-file" and any(a.startswith("--batch") for a in args))
|
|
440
|
+
return feeder, sink
|
|
441
|
+
|
|
442
|
+
|
|
443
|
+
def _recursive(name, args):
|
|
444
|
+
low = [a.lower() for a in args]
|
|
445
|
+
if name in ALWAYS_RECURSIVE:
|
|
446
|
+
return True
|
|
447
|
+
if name in GREP_FAMILY:
|
|
448
|
+
return (any(re.fullmatch(r"-[a-zA-Z]*[rR][a-zA-Z]*", a) or a in ("--recursive", "--dereference-recursive")
|
|
449
|
+
for a in args) or "-recurse" in low or ("-d" in args and "recurse" in args))
|
|
450
|
+
if name in ("cp", "scp", "copy-item", "cpi"):
|
|
451
|
+
return any(re.fullmatch(r"-[a-zA-Z]*[rRa][a-zA-Z]*", a) or a == "--recursive" for a in args) or "-recurse" in low
|
|
452
|
+
if name == "tar":
|
|
453
|
+
return bool(args) and (args[0] == "--create" or re.fullmatch(r"-?[a-zA-Z]*c[a-zA-Z]*", args[0]) is not None)
|
|
454
|
+
return name == "findstr" and "/s" in low
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _content_reader(words):
|
|
458
|
+
consumes = any(_base(w) in GREP_FAMILY or _base(w) in ("sed", "awk") for w in words)
|
|
459
|
+
return any(_base(w) in CONTENT_READERS or re.match(r"^-(?:exec|execdir|ok|okdir)$", w) or (w == "$" and consumes)
|
|
460
|
+
for w in words)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _sweep_hit(scan, stages, content):
|
|
464
|
+
has_test = TEST_RE.search(" ".join(w for st in stages if st for w in st["words"])) is not None
|
|
465
|
+
for st in stages:
|
|
466
|
+
if not st:
|
|
467
|
+
continue
|
|
468
|
+
for i, word in enumerate(st["words"]):
|
|
469
|
+
name = _base(word)
|
|
470
|
+
rec = _recursive(name, st["words"][i + 1:])
|
|
471
|
+
enum = name in ENUMERATORS
|
|
472
|
+
if (rec or (enum and content)) and scan.above(st["ops"] + [st["start"]], rec):
|
|
473
|
+
return name + " over a directory holding the holdout store"
|
|
474
|
+
if not has_test:
|
|
475
|
+
continue
|
|
476
|
+
for op in st["ops"]:
|
|
477
|
+
broad = rec or (enum and content) or (name in CONTENT_READERS and any(GLOB_RE.search(s) for s in op))
|
|
478
|
+
if broad and scan.in_tmp(op):
|
|
479
|
+
return name + " sweeping temp directories for tests"
|
|
480
|
+
return None
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def _scan_stage(scan, words, cur):
|
|
484
|
+
lead, skips, ops, calls = _lead(words), _grep_skips(words), [], []
|
|
485
|
+
for i, word in enumerate(words):
|
|
486
|
+
token = re.sub(r"^\d*[<>]+", "", word)
|
|
487
|
+
if i in skips or not token:
|
|
488
|
+
continue
|
|
489
|
+
if GIT_RAW_RE.search(token.replace("\\", "/")):
|
|
490
|
+
return token, None
|
|
491
|
+
if token.startswith("-") and "=" not in token:
|
|
492
|
+
continue
|
|
493
|
+
cands = scan.candidates(token, cur)
|
|
494
|
+
if _computed_home(token) or scan.reaches(cands):
|
|
495
|
+
return token, None
|
|
496
|
+
if i > lead:
|
|
497
|
+
ops.extend(cands)
|
|
498
|
+
gwords = [part for w in words for part in re.split(r"[,\[\]]+", w) if part]
|
|
499
|
+
for sub, args in _git_calls(gwords):
|
|
500
|
+
hit = _git_hit(sub, args)
|
|
501
|
+
if hit:
|
|
502
|
+
return hit, None
|
|
503
|
+
calls.append((sub, args))
|
|
504
|
+
return None, {"words": words, "ops": ops, "start": cur, "git": calls, "lead": lead}
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def _next_cwd(scan, st, cur):
|
|
508
|
+
words, lead = st["words"], st["lead"]
|
|
509
|
+
if lead >= len(words) or _base(words[lead]) not in CD_COMMANDS or "-" in words[lead + 1:]:
|
|
510
|
+
return cur
|
|
511
|
+
args = [w for w in words[lead + 1:] if not w.startswith("-") and not re.fullmatch(r"/[A-Za-z]", w)]
|
|
512
|
+
first = scan.candidates(args[0] if args else "~", cur)[0]
|
|
513
|
+
return cur if any(GLOB_RE.search(s) for s in first) else first
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _git_link_hit(stages, ci, links):
|
|
517
|
+
feeders, sinks = [], []
|
|
518
|
+
for si, st in enumerate(stages):
|
|
519
|
+
if not st:
|
|
520
|
+
continue
|
|
521
|
+
for sub, args in st["git"]:
|
|
522
|
+
feeder, sink = _git_role(sub, args)
|
|
523
|
+
feeders += [si] if feeder else []
|
|
524
|
+
sinks += [si] if sink else []
|
|
525
|
+
sinks += [si] if any(_base(w) == "xargs" for w in st["words"]) else []
|
|
526
|
+
links["feeders"] += [(ci, f) for f in feeders]
|
|
527
|
+
links["sinks"] += [(ci, s) for s in sinks]
|
|
528
|
+
if any(f != s for f in feeders for s in sinks):
|
|
529
|
+
return "git history listing piped into content recovery"
|
|
530
|
+
return None
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _scan_text(scan, text):
|
|
534
|
+
text = re.sub(r"`([^`]*)`", r"$(\1)", text)
|
|
535
|
+
cur, links = scan.cwd, {"feeders": [], "sinks": []}
|
|
536
|
+
for ci, chain in enumerate(re.split(r"\|\||&&|[;&\r\n]", text)):
|
|
537
|
+
stages = []
|
|
538
|
+
for part in re.split(r"[|()]", chain):
|
|
539
|
+
words = [w for w in re.split(r"\s+", part) if w]
|
|
540
|
+
hit, stage = _scan_stage(scan, words, cur) if words else (None, None)
|
|
541
|
+
if hit:
|
|
542
|
+
return hit
|
|
543
|
+
stages.append(stage)
|
|
544
|
+
cur = _next_cwd(scan, stage, cur) if stage else cur
|
|
545
|
+
content = any(st and _content_reader(st["words"]) for st in stages)
|
|
546
|
+
hit = _git_link_hit(stages, ci, links) or _sweep_hit(scan, stages, content)
|
|
547
|
+
if hit:
|
|
548
|
+
return hit
|
|
549
|
+
if LOOP_RE.search(text) and any(f != s for f in links["feeders"] for s in links["sinks"]):
|
|
550
|
+
return "git history listing piped into content recovery"
|
|
551
|
+
return None
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _inline_name_hit(text, eval_mode):
|
|
555
|
+
reduced = re.sub(r"[\s'\"+,()\[\]`\\^$/]", "", text.lower())
|
|
556
|
+
if "deepmodebot-holdout" not in reduced:
|
|
557
|
+
return None
|
|
558
|
+
if eval_mode or any(INTERPRETER_RE.match(_base(w)) for w in re.split(r"[\s;&|()'\"`]+", text) if w):
|
|
559
|
+
return HOLDOUT_DIR
|
|
560
|
+
return None
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def holdout_command_hit(command, cwd, eval_mode=False):
|
|
564
|
+
text = re.sub(r"(-m|--message)(=|\s+)(\"[^\"]*\"|'[^']*')", r'\1 ""', str(command or ""))
|
|
565
|
+
text = text.replace("\\\r\n", " ").replace("\\\n", " ")
|
|
566
|
+
scan = HoldoutScan(cwd)
|
|
567
|
+
hit = _inline_name_hit(text, eval_mode)
|
|
568
|
+
if hit:
|
|
569
|
+
return hit
|
|
570
|
+
flat = re.sub(r"\$(?=['\"])", "", text).replace("'", "").replace('"', "")
|
|
571
|
+
for view in (flat.replace("\\", "/"), re.sub(r"[\\^`]", "", flat)):
|
|
572
|
+
hit = _scan_text(scan, view)
|
|
573
|
+
if hit:
|
|
574
|
+
return hit
|
|
575
|
+
return None
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
def _tool_variants(value):
|
|
579
|
+
out = [value, re.sub(r"#[0-9A-Za-z]{4}$", "", value), re.sub(r":\d+(?:-\d+)?(?:,.*)?$", "", value)]
|
|
580
|
+
for pattern in (r"^\[(.+)#[0-9A-Za-z]+\]$", r"^(.{2,}?):[^/\\]"):
|
|
581
|
+
match = re.match(pattern, value)
|
|
582
|
+
if match:
|
|
583
|
+
out.append(match.group(1))
|
|
584
|
+
return [v for i, v in enumerate(out) if v and v not in out[:i]]
|
|
585
|
+
|
|
586
|
+
|
|
587
|
+
def _tool_strings(value):
|
|
588
|
+
if isinstance(value, str):
|
|
589
|
+
return [value]
|
|
590
|
+
return [v for v in value if isinstance(v, str)] if isinstance(value, list) else []
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def holdout_tool_hit(tool_name, tool_input, cwd):
|
|
594
|
+
name = str(tool_name or "")
|
|
595
|
+
search = SEARCH_TOOL_RE.search(name) is not None
|
|
596
|
+
pattern_ok = search and "grep" not in name.lower()
|
|
597
|
+
bases, patterns = [], []
|
|
598
|
+
for key, value in tool_input.items():
|
|
599
|
+
norm = re.sub(r"[_\-\s]", "", str(key)).lower()
|
|
600
|
+
if norm in TOOL_PATTERN_KEYS and (norm != "pattern" or pattern_ok):
|
|
601
|
+
patterns.extend(_tool_strings(value))
|
|
602
|
+
if norm in TOOL_PATH_KEYS:
|
|
603
|
+
bases.extend(_tool_strings(value))
|
|
604
|
+
if not search and not bases and not patterns:
|
|
605
|
+
return None
|
|
606
|
+
scan = HoldoutScan(cwd)
|
|
607
|
+
texts = [piece for value in bases + patterns for piece in value.split(";")]
|
|
608
|
+
texts += [b.rstrip("/\\") + "/" + p for b in (bases or [_unsegs(scan.cwd)]) for p in patterns]
|
|
609
|
+
for text in texts:
|
|
610
|
+
for variant in _tool_variants(text.strip()):
|
|
611
|
+
cands = scan.candidates(variant, scan.cwd)
|
|
612
|
+
if GIT_RAW_RE.search(variant.replace("\\", "/")) or scan.reaches(cands) or (search and scan.above(cands, True)):
|
|
613
|
+
return variant
|
|
614
|
+
if search and not bases and scan.above([scan.cwd]):
|
|
615
|
+
return _unsegs(scan.cwd)
|
|
616
|
+
return None
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
def holdout_guard_hit(event, tool_name, tool_input):
|
|
620
|
+
cwd = event.get("cwd") or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
|
|
621
|
+
if tool_name == "Bash":
|
|
622
|
+
return holdout_command_hit(tool_input.get("command") or "", cwd)
|
|
623
|
+
return holdout_tool_hit(tool_name, tool_input, cwd)
|
|
624
|
+
|
|
625
|
+
|
|
57
626
|
def real(path):
|
|
58
627
|
return os.path.normcase(os.path.realpath(os.path.expanduser(path)))
|
|
59
628
|
|
|
@@ -109,9 +678,32 @@ def rule_hints():
|
|
|
109
678
|
return []
|
|
110
679
|
dirs = [str(d).lower().strip("/") for d in spec.get("dirs", [])]
|
|
111
680
|
named = [str(n).lower() for n in spec.get("names", []) + spec.get("files", [])]
|
|
681
|
+
user = spec.get("user") or {}
|
|
682
|
+
named += [str(f).lower() for f in user.get("files", [])]
|
|
683
|
+
dirs += [str(d).lower().strip("/") for d in user.get("dirs", [])]
|
|
112
684
|
return named + dirs + [d.split("/")[0] for d in dirs] + ["deepmodebot", "rule_ledger"]
|
|
113
685
|
|
|
114
686
|
|
|
687
|
+
def load_asset(name, path):
|
|
688
|
+
mod = sys.modules.get(name)
|
|
689
|
+
if mod is None:
|
|
690
|
+
spec = importlib.util.spec_from_file_location(name, path)
|
|
691
|
+
mod = importlib.util.module_from_spec(spec)
|
|
692
|
+
sys.modules[spec.name] = mod
|
|
693
|
+
spec.loader.exec_module(mod)
|
|
694
|
+
return mod
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def session_notice(event):
|
|
698
|
+
"""SessionStart output: the unapproved-rules notice for this session, or "" when nothing is pending."""
|
|
699
|
+
watch = os.path.join(os.path.dirname(RULE_LEDGER), "rules_watch.py")
|
|
700
|
+
if not os.path.isfile(watch):
|
|
701
|
+
return ""
|
|
702
|
+
mod = load_asset("dmb_rules_watch", watch)
|
|
703
|
+
cwd = event.get("cwd") or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()
|
|
704
|
+
return mod.render(mod.check(cwd, set()), "claude")
|
|
705
|
+
|
|
706
|
+
|
|
115
707
|
def ledger_near(folder):
|
|
116
708
|
"""Whether the repo holding `folder` has an owner rule ledger in its working tree."""
|
|
117
709
|
cur = os.path.abspath(folder)
|
|
@@ -145,13 +737,11 @@ def rule_guard_reason(event, tool_name, tool_input):
|
|
|
145
737
|
needed = any(h in text for h in rule_hints()) or (tool_name == "Bash" and ledger_near(cwd))
|
|
146
738
|
if not os.path.isfile(RULE_LEDGER) or not needed:
|
|
147
739
|
return None
|
|
148
|
-
mod =
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
mod
|
|
152
|
-
|
|
153
|
-
spec.loader.exec_module(mod)
|
|
154
|
-
return mod.guard(cwd, paths=paths, command=command)
|
|
740
|
+
mod = load_asset("dmb_rule_ledger", RULE_LEDGER)
|
|
741
|
+
reason = mod.guard(cwd, paths=paths, command=command)
|
|
742
|
+
if reason:
|
|
743
|
+
mod.notify_blocked(reason, str(cwd))
|
|
744
|
+
return reason
|
|
155
745
|
|
|
156
746
|
|
|
157
747
|
def deny(reason):
|
|
@@ -159,6 +749,30 @@ def deny(reason):
|
|
|
159
749
|
"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": reason}}))
|
|
160
750
|
|
|
161
751
|
|
|
752
|
+
def agent_guard_reason(prompt):
|
|
753
|
+
env = os.environ
|
|
754
|
+
depth = env.get("DEEPMODEBOT_SUBAGENT_DEPTH")
|
|
755
|
+
nested = (env.get("TEAMWORK_RUN_ID") or env.get("SWARM_ID") or depth not in (None, "", "0")
|
|
756
|
+
or env.get("DEEPMODEBOT_MAX_SUBAGENTS") == "0")
|
|
757
|
+
if nested and env.get("ALLOW_NESTED_SUBAGENTS") != "1" and "ALLOW_NESTED_SUBAGENTS" not in str(prompt or ""):
|
|
758
|
+
return NESTED_REASON
|
|
759
|
+
return None
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def slice_guard_reason(root, worker, target):
|
|
763
|
+
if not re.fullmatch(r"[A-Za-z0-9._-]+", worker):
|
|
764
|
+
return "deepmodebot: invalid worker ID"
|
|
765
|
+
try:
|
|
766
|
+
root = Path(root).resolve()
|
|
767
|
+
manifest = root / ".scratch" / "slices" / (worker + ".json")
|
|
768
|
+
if manifest.exists():
|
|
769
|
+
gate = load_asset("dmb_worker_gate", WORKER_GATE)
|
|
770
|
+
return gate.write_issue(root, worker, target)
|
|
771
|
+
except (ValueError, OSError, RuntimeError) as exc:
|
|
772
|
+
return f"deepmodebot cannot check the owned slice for {worker}: {exc}"
|
|
773
|
+
return None
|
|
774
|
+
|
|
775
|
+
|
|
162
776
|
def session_mark(data_dir, event):
|
|
163
777
|
session = re.sub(r"[^A-Za-z0-9_-]", "", str(event.get("session_id") or ""))
|
|
164
778
|
return os.path.join(data_dir, "active-sessions", session) if data_dir and session else None
|
|
@@ -174,6 +788,11 @@ def main():
|
|
|
174
788
|
if not isinstance(event, dict):
|
|
175
789
|
return 0
|
|
176
790
|
mark = session_mark(sys.argv[2] if len(sys.argv) > 2 else "", event)
|
|
791
|
+
if mode == "session-notice":
|
|
792
|
+
notice = session_notice(event)
|
|
793
|
+
if notice:
|
|
794
|
+
print(notice)
|
|
795
|
+
return 0
|
|
177
796
|
if mode == "activate":
|
|
178
797
|
if mark and re.match(r"\s*/(?:deepmodebot:|(?:deep|deepmodebot|suggest|research|tournament|review-pr|land-pr|pr-thread|contribute|project-brief)\b)", str(event.get("prompt") or "")):
|
|
179
798
|
folder = os.path.dirname(mark)
|
|
@@ -199,14 +818,25 @@ def main():
|
|
|
199
818
|
if rule_reason:
|
|
200
819
|
deny(rule_reason)
|
|
201
820
|
return 0
|
|
202
|
-
if
|
|
821
|
+
if tool_name == "Agent":
|
|
822
|
+
reason = agent_guard_reason(tool_input.get("prompt"))
|
|
823
|
+
if reason:
|
|
824
|
+
deny(reason)
|
|
203
825
|
return 0
|
|
826
|
+
active = mode != "if-active" or bool(mark and os.path.exists(mark))
|
|
827
|
+
worker = os.environ.get("DEEPMODEBOT_WORKER_ID")
|
|
828
|
+
if active or worker:
|
|
829
|
+
hit = holdout_guard_hit(event, tool_name, tool_input)
|
|
830
|
+
if hit:
|
|
831
|
+
deny(HOLDOUT_REASON.format(hit=hit[:120]))
|
|
832
|
+
return 0
|
|
204
833
|
if tool_name == "Bash":
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
834
|
+
if active:
|
|
835
|
+
bad = check_bash_reward_hack(tool_input.get("command") or "")
|
|
836
|
+
if bad:
|
|
837
|
+
deny(f"deepmodebot anti-reward-hacking guard blocked `{bad}`: builders may not zero thresholds, skip reference/verification gates, or tamper with provenance ledgers.")
|
|
208
838
|
return 0
|
|
209
|
-
if tool_name not in ("Write", "Edit", "NotebookEdit"):
|
|
839
|
+
if tool_name not in ("Write", "Edit", "NotebookEdit") or not (active or worker):
|
|
210
840
|
return 0
|
|
211
841
|
target = tool_input.get("file_path") or tool_input.get("notebook_path")
|
|
212
842
|
if not isinstance(target, str) or not target:
|
|
@@ -215,6 +845,13 @@ def main():
|
|
|
215
845
|
path = real(target if os.path.isabs(os.path.expanduser(target)) else os.path.join(cwd, target))
|
|
216
846
|
roots = project_roots(cwd)
|
|
217
847
|
root = os.path.normpath(roots[0])
|
|
848
|
+
if worker:
|
|
849
|
+
reason = slice_guard_reason(root, worker, os.path.join(cwd, os.path.expanduser(target)))
|
|
850
|
+
if reason:
|
|
851
|
+
deny(reason)
|
|
852
|
+
return 0
|
|
853
|
+
if not active:
|
|
854
|
+
return 0
|
|
218
855
|
if any(inside(path, r) for r in allowed_roots(roots)):
|
|
219
856
|
return 0
|
|
220
857
|
deny(f"deepmodebot keeps all writes inside the project root {root}. {target} is outside it. "
|