返回 CodeWhale
agent-guard.py
根目录 / scripts / agent-guard.py
1 #!/usr/bin/env python3
2 import fnmatch
3 import glob
4 import json
5 import os
6 import re
7 import shlex
8 import sys
9
10 FREEZE_VARIABLE = "CODEWHALE_RELEASE_FREEZE"
11 FROZEN_GLOBS = (".github/workflows/release*.yml", ".github/workflows/auto-tag.yml")
12
13 SHELL_TOOLS = {"bash", "Bash", "exec_shell"}
14 FILE_TOOLS = {
15 "write",
16 "edit",
17 "write_file",
18 "edit_file",
19 "fim_edit",
20 "File",
21 "file",
22 "apply_patch",
23 "Write",
24 "Edit",
25 "MultiEdit",
26 "NotebookEdit",
27 }
28 FILE_READ_ACTIONS = {"read", "list", "search_name", "search_content"}
29
30 KEYWORDS = {"if", "then", "do", "else", "elif", "while", "until", "!", "{", "}"}
31 WRAPPERS = {"time", "sudo", "doas", "env", "command", "builtin", "exec", "nice", "nohup", "xargs"}
32 SHELLS = {"sh", "bash", "zsh", "dash", "ksh"}
33 READ_ONLY_PROGRAMS = {
34 "cat", "less", "more", "head", "tail", "grep", "egrep", "fgrep", "rg", "ag", "wc",
35 "diff", "cmp", "ls", "stat", "file", "shasum", "sha256sum", "md5", "md5sum", "jq",
36 "yq", "bat", "actionlint", "yamllint", "echo", "printf", "test", "[", "realpath",
37 "basename", "dirname", "sed", "awk", "gawk", "perl",
38 }
39 IN_PLACE_PROGRAMS = {"sed", "awk", "gawk", "perl"}
40 READ_ONLY_GIT = {
41 "diff", "log", "show", "status", "blame", "annotate", "grep", "ls-files",
42 "cat-file", "rev-parse", "shortlog",
43 }
44 GIT_VALUE_OPTIONS = {"-C", "-c", "--git-dir", "--work-tree", "--namespace", "--config-env", "--super-prefix"}
45 COMMIT_VALUE_OPTIONS = {
46 "--message", "--file", "--reuse-message", "--reedit-message", "--fixup", "--squash",
47 "--author", "--date", "--template", "--cleanup", "--trailer", "--pathspec-from-file",
48 }
49
50 TEMPLATE_SUFFIXES = (".example", ".sample", ".template")
51 KEY_SUFFIXES = (".pem", ".key", ".p8", ".p12", ".pfx", ".jks", ".keystore", ".ppk")
52 SSH_IDENTITIES = {"id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"}
53 BUILD_FOLDERS = ("target", "node_modules", ".mimosa")
54 FORBIDDEN_SAMPLES = (
55 ".env", ".env.local", "prod.env", "id_rsa", "id_ed25519", "server.pem", "server.key",
56 "AuthKey.p8", "cert.p12", "cert.pfx", "release.jks", "release.keystore", "putty.ppk",
57 )
58
59 BLANKET = (
60 "Staging guard: this stages everything at once (the A, all or update flags, a dot, a "
61 "star or the repo root) and can sweep in credentials, build output and unfinished work "
62 "from other agents. Stage your own files by name."
63 )
64 COMMIT_ALL = (
65 "Staging guard: commit with the a or all flag sweeps in every tracked change, including "
66 "edits other agents have not finished. Stage your own changes by name, then commit "
67 "without that flag."
68 )
69 CREDENTIALS = (
70 "Staging guard: {name} holds credentials (.env style), which are never committed. "
71 "Templates ending in .example, .sample or .template are fine. Keep the real one "
72 "untracked and listed in .gitignore."
73 )
74 PRIVATE_KEY = (
75 "Staging guard: {name} looks like a private key (pem, key, p8, p12, pfx, keystore or an "
76 "ssh identity), and keys are never committed. If it is a deliberate test fixture, ask "
77 "the person to stage it."
78 )
79 BUILD_OUTPUT = (
80 "Staging guard: {name} holds build output, dependencies or tool state, which never "
81 "belongs in git. Stage the source change only, and add that folder to .gitignore if it "
82 "shows up as untracked."
83 )
84 FROZEN = (
85 "Release freeze: {name} is a release workflow, frozen while CODEWHALE_RELEASE_FREEZE "
86 "is set. Reading it is fine; ask the person before changing it. The freeze lifts when "
87 "that variable is unset."
88 )
89
90 HEREDOC = re.compile(r"<<-?[ \t]*(['\"]?)([A-Za-z_][A-Za-z0-9_]*)\1[^\n]*\n.*?\n[ \t]*\2[ \t]*(?=\n|$)", re.S)
91 PATCH_PATHS = re.compile(
92 r"^(?:\+\+\+|---) (?:[ab]/)?(\S+)|^\*\*\* (?:Update|Add|Delete) File: (.+?)\s*$|^\*\*\* Move to: (.+?)\s*$",
93 re.M,
94 )
95 ASSIGNMENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*=")
96 COMMAND_FIELD = re.compile(r'"command"\s*:\s*"((?:[^"\\]|\\.)*)')
97
98
99 def display(name):
100 cleaned = "".join(ch for ch in name if ch not in "'\"`").strip()
101 return cleaned[:32] or "this"
102
103
104 def freeze_on():
105 return os.environ.get(FREEZE_VARIABLE, "").strip().lower() not in ("", "0", "false", "no", "off")
106
107
108 def is_separator(token):
109 return bool(token) and all(ch in "();|&\n" for ch in token)
110
111
112 def is_redirect(token):
113 return bool(token) and set(token) <= set("<>&|") and ("<" in token or ">" in token)
114
115
116 def segments(text):
117 text = HEREDOC.sub("\n", text)
118 try:
119 lexer = shlex.shlex(text, posix=True, punctuation_chars="();<>|&\n")
120 lexer.whitespace = " \t\r"
121 lexer.whitespace_split = True
122 lexer.commenters = ""
123 tokens = list(lexer)
124 except ValueError:
125 for piece in re.split(r"[;&|\n]+", text):
126 yield [token.strip("'\"") for token in piece.split()], []
127 return
128 words, targets = [], []
129 index = 0
130 while index < len(tokens):
131 token = tokens[index]
132 if token.startswith("#"):
133 while index < len(tokens) and tokens[index] != "\n":
134 index += 1
135 continue
136 if is_redirect(token):
137 if index + 1 < len(tokens):
138 operand = tokens[index + 1]
139 duplicate = token.endswith("&") and (operand.isdigit() or operand == "-")
140 if not duplicate and "<" not in token:
141 targets.append(operand)
142 index += 2
143 continue
144 if is_separator(token):
145 if words:
146 yield words, targets
147 words, targets = [], []
148 else:
149 words.append(token)
150 index += 1
151 if words:
152 yield words, targets
153
154
155 def strip_leading(words):
156 index, wrapped = 0, False
157 while index < len(words):
158 word = words[index]
159 if word in KEYWORDS or word in WRAPPERS or ASSIGNMENT.match(word) or (wrapped and word.startswith("-")):
160 wrapped = wrapped or word in WRAPPERS
161 index += 1
162 continue
163 break
164 return words[index:]
165
166
167 def shell_argument(words):
168 for index, word in enumerate(words[1:-1], start=1):
169 if word.startswith("-") and not word.startswith("--") and "c" in word[1:]:
170 return words[index + 1]
171 return None
172
173
174 def commands(text, depth=0):
175 for words, targets in segments(text):
176 words = strip_leading(words)
177 if not words:
178 if targets:
179 yield [], targets
180 continue
181 program = os.path.basename(words[0])
182 if depth < 3 and program in SHELLS:
183 inner = shell_argument(words)
184 if inner is not None:
185 yield from commands(inner, depth + 1)
186 continue
187 if depth < 3 and program == "eval":
188 yield from commands(" ".join(words[1:]), depth + 1)
189 continue
190 yield words, targets
191
192
193 def git_subcommand(words):
194 index = 1
195 while index < len(words):
196 word = words[index]
197 if word in GIT_VALUE_OPTIONS:
198 index += 2
199 continue
200 if word.startswith("-"):
201 index += 1
202 continue
203 return word, words[index + 1:]
204 return None, []
205
206
207 def pathspec_body(spec):
208 spec = spec.replace("\\", "/")
209 if spec.startswith(":("):
210 magic, _, rest = spec[2:].partition(")")
211 if "exclude" in magic:
212 return None
213 return rest
214 if spec.startswith(":"):
215 rest = spec[1:]
216 if rest[:1] in ("!", "^"):
217 return None
218 return rest.lstrip("/")
219 return spec
220
221
222 def is_blanket(spec):
223 body = pathspec_body(spec)
224 if body is None:
225 return False
226 parts = [part for part in body.strip().split("/") if part]
227 return all(part in (".", "..", "*") for part in parts)
228
229
230 def forbidden(spec):
231 body = pathspec_body(spec)
232 if body is None:
233 return None
234 parts = [part for part in body.split("/") if part not in ("", ".")]
235 if not parts:
236 return None
237 for folder in BUILD_FOLDERS:
238 if folder in parts and "fixtures" not in parts:
239 return BUILD_OUTPUT.format(name=folder)
240 base = parts[-1]
241 lower = base.lower()
242 if any(ch in lower for ch in "*?["):
243 samples = [sample for sample in FORBIDDEN_SAMPLES if fnmatch.fnmatch(sample.lower(), lower)]
244 if not samples:
245 return None
246 lower = samples[0].lower()
247 if lower.endswith(TEMPLATE_SUFFIXES):
248 return None
249 if lower == ".env" or lower.startswith(".env.") or lower.endswith(".env"):
250 return CREDENTIALS.format(name=display(base))
251 if lower in SSH_IDENTITIES or lower.endswith(KEY_SUFFIXES):
252 return PRIVATE_KEY.format(name=display(base))
253 return None
254
255
256 def add_verdict(args):
257 specs, blanket, dry_run, literal = [], False, False, False
258 for arg in args:
259 if literal:
260 specs.append(arg)
261 elif arg == "--":
262 literal = True
263 elif arg in ("--all", "--no-ignore-removal", "--update"):
264 blanket = True
265 elif arg == "--dry-run":
266 dry_run = True
267 elif arg.startswith("--"):
268 continue
269 elif arg.startswith("-") and len(arg) > 1:
270 letters = arg[1:]
271 dry_run = dry_run or "n" in letters
272 blanket = blanket or "A" in letters or "u" in letters
273 else:
274 specs.append(arg)
275 if dry_run:
276 return None
277 if blanket or any(is_blanket(spec) for spec in specs):
278 return BLANKET
279 for spec in specs:
280 reason = forbidden(spec)
281 if reason:
282 return reason
283 return None
284
285
286 def commit_verdict(args):
287 specs, literal, index = [], False, 0
288 while index < len(args):
289 arg = args[index]
290 if literal:
291 specs.append(arg)
292 elif arg == "--":
293 literal = True
294 elif arg == "--all":
295 return COMMIT_ALL
296 elif arg.startswith("--"):
297 if "=" not in arg and arg in COMMIT_VALUE_OPTIONS:
298 index += 1
299 elif arg.startswith("-") and len(arg) > 1:
300 letters = arg[1:]
301 for position, letter in enumerate(letters):
302 if letter == "a":
303 return COMMIT_ALL
304 if letter in "mFCct":
305 if position == len(letters) - 1:
306 index += 1
307 break
308 if letter in "Su":
309 break
310 else:
311 specs.append(arg)
312 index += 1
313 if any(is_blanket(spec) for spec in specs):
314 return BLANKET
315 for spec in specs:
316 reason = forbidden(spec)
317 if reason:
318 return reason
319 return None
320
321
322 def relative(token, workspace):
323 text = token.strip().replace("\\", "/")
324 if not text or text.startswith("~"):
325 return None
326 if os.path.isabs(text):
327 root = workspace.replace("\\", "/").rstrip("/") + "/"
328 if not text.startswith(root):
329 return None
330 text = text[len(root):]
331 while text.startswith("./"):
332 text = text[2:]
333 text = text.rstrip("/")
334 return text if text and text != "." else None
335
336
337 def frozen_files(workspace):
338 found = set()
339 for pattern in FROZEN_GLOBS:
340 for path in glob.glob(os.path.join(workspace, pattern)):
341 found.add(os.path.relpath(path, workspace).replace("\\", "/"))
342 return sorted(found)
343
344
345 def frozen_hit(token, workspace, frozen):
346 rel = relative(token, workspace)
347 if rel is None:
348 return None
349 globbed = any(ch in rel for ch in "*?[")
350 for path in frozen:
351 same_depth = path.count("/") == rel.count("/") or "**" in rel
352 if rel == path or path.startswith(rel + "/") or (globbed and same_depth and fnmatch.fnmatch(path, rel)):
353 return os.path.basename(path)
354 for pattern in FROZEN_GLOBS:
355 if fnmatch.fnmatch(rel, pattern):
356 return os.path.basename(rel)
357 return None
358
359
360 def writes_in_place(words):
361 for word in words[1:]:
362 if word.startswith("--in-place") or word == "inplace":
363 return True
364 if word.startswith("-") and not word.startswith("--") and "i" in word[1:]:
365 return True
366 return False
367
368
369 def shell_freeze_verdict(words, targets, workspace, frozen):
370 for target in targets:
371 hit = frozen_hit(target, workspace, frozen)
372 if hit:
373 return FROZEN.format(name=display(hit))
374 hits = [hit for hit in (frozen_hit(word, workspace, frozen) for word in words[1:]) if hit]
375 if not hits:
376 return None
377 program = os.path.basename(words[0])
378 if program in IN_PLACE_PROGRAMS and writes_in_place(words):
379 return FROZEN.format(name=display(hits[0]))
380 if program in READ_ONLY_PROGRAMS:
381 return None
382 if program == "git" and git_subcommand(words)[0] in READ_ONLY_GIT:
383 return None
384 return FROZEN.format(name=display(hits[0]))
385
386
387 def shell_verdict(text, workspace, freeze):
388 frozen = frozen_files(workspace) if freeze else []
389 for words, targets in commands(text):
390 if freeze:
391 reason = shell_freeze_verdict(words, targets, workspace, frozen)
392 if reason:
393 return reason
394 if not words or os.path.basename(words[0]) != "git":
395 continue
396 subcommand, args = git_subcommand(words)
397 if subcommand in ("add", "stage"):
398 reason = add_verdict(args)
399 elif subcommand == "commit":
400 reason = commit_verdict(args)
401 else:
402 reason = None
403 if reason:
404 return reason
405 return None
406
407
408 def file_targets(args):
409 paths = []
410 for key in ("path", "file_path", "filePath", "notebook_path"):
411 value = args.get(key)
412 if isinstance(value, str):
413 paths.append(value)
414 for key in ("replace", "changes", "edits"):
415 items = args.get(key)
416 if isinstance(items, list):
417 paths.extend(item["path"] for item in items if isinstance(item, dict) and isinstance(item.get("path"), str))
418 patch = args.get("patch") or args.get("input")
419 if isinstance(patch, str):
420 for groups in PATCH_PATHS.findall(patch):
421 paths.extend(group for group in groups if group)
422 return paths
423
424
425 def file_freeze_verdict(args, raw, workspace):
426 frozen = frozen_files(workspace)
427 if not isinstance(args, dict):
428 for path in frozen:
429 if path in raw:
430 return FROZEN.format(name=display(os.path.basename(path)))
431 return None
432 if str(args.get("action", "")).lower() in FILE_READ_ACTIONS:
433 return None
434 for target in file_targets(args):
435 hit = frozen_hit(target, workspace, frozen)
436 if hit:
437 return FROZEN.format(name=display(hit))
438 return None
439
440
441 def shell_text(args, raw):
442 if isinstance(args, dict) and isinstance(args.get("command"), str):
443 return args["command"]
444 match = COMMAND_FIELD.search(raw)
445 if match:
446 fragment = match.group(1)
447 while fragment:
448 try:
449 return json.loads('"' + fragment + '"')
450 except ValueError:
451 fragment = fragment[:-1]
452 return raw
453
454
455 def verdict(tool, args, raw, workspace):
456 freeze = freeze_on()
457 if tool in SHELL_TOOLS:
458 return shell_verdict(shell_text(args, raw), workspace, freeze)
459 if freeze and tool in FILE_TOOLS:
460 return file_freeze_verdict(args, raw, workspace)
461 return None
462
463
464 def parse(raw):
465 try:
466 return json.loads(raw)
467 except ValueError:
468 return None
469
470
471 def main():
472 if "DEEPSEEK_TOOL_NAME" in os.environ:
473 raw = os.environ.get("DEEPSEEK_TOOL_ARGS", "")
474 workspace = os.environ.get("DEEPSEEK_WORKSPACE") or os.getcwd()
475 reason = verdict(os.environ["DEEPSEEK_TOOL_NAME"], parse(raw), raw, workspace)
476 if reason:
477 print(json.dumps({"decision": "deny", "reason": reason}))
478 return 0
479 payload = json.load(sys.stdin)
480 tool_input = payload.get("tool_input")
481 raw = json.dumps(tool_input)
482 workspace = os.environ.get("CLAUDE_PROJECT_DIR") or payload.get("cwd") or os.getcwd()
483 reason = verdict(payload.get("tool_name", ""), tool_input, raw, workspace)
484 if reason:
485 print(reason, file=sys.stderr)
486 return 2
487 return 0
488
489
490 if __name__ == "__main__":
491 sys.exit(main())
492
492 lines PYTHON