secondkey 0.2.0__py3-none-any.whl

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.
secondkey/classify.py ADDED
@@ -0,0 +1,616 @@
1
+ """Turn an agent tool call into a list of classified actions.
2
+
3
+ An *action* has a dotted category (``sql.drop``, ``git.force_push``,
4
+ ``secrets.read`` ...) that policies match against, a human summary, and the
5
+ details a snapshot provider needs to take a restore point.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import fnmatch
11
+ import glob
12
+ import os
13
+ import re
14
+ import shlex
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from .sql import classify_sql
19
+
20
+ SHELL_OPS = {";", "&&", "||", "|", "&", "\n", "|&"}
21
+ WRAPPERS = {"sudo", "nohup", "time", "nice", "ionice", "command", "exec", "doas"}
22
+ WRAPPER_VALUE_FLAGS = {"sudo": ("-u", "-g", "-C", "-D", "-p", "-r", "-t", "-U", "-h", "-T"),
23
+ "doas": ("-u", "-C"), "nice": ("-n",), "ionice": ("-c", "-n", "-p")}
24
+ SHELLS = {"sh", "bash", "zsh", "dash", "ksh", "fish"}
25
+ READERS = {"cat", "less", "more", "head", "tail", "grep", "rg", "egrep", "fgrep", "base64", "xxd", "od",
26
+ "strings", "cp", "scp", "rsync", "nl", "awk", "sed", "jq", "yq", "source", ".", "bat", "tac",
27
+ "openssl", "gpg", "curl", "wget", "nc", "python", "python3", "node"}
28
+ SECRET_PATTERNS = [".env", ".env.*", "*.env", "id_rsa*", "id_ed25519*", "id_ecdsa*", "*.pem", "*.key", "*.p12",
29
+ "*.pfx", "credentials", "credentials.json", ".npmrc", ".pypirc", ".netrc", ".pgpass",
30
+ "secrets.yaml", "secrets.yml", "secrets.json", "service-account*.json", "*.tfvars", "kubeconfig"]
31
+ SECRET_DIRS = ("/.ssh/", "/.aws/", "/.gnupg/", "/.config/gcloud/", "/.kube/", "/.docker/config")
32
+ SAFE_SECRET_NAMES = {".env.example", ".env.sample", ".env.template", ".env.dist"}
33
+
34
+
35
+ PURE_READERS = {"cat", "less", "more", "head", "tail", "grep", "rg", "egrep", "fgrep", "ls", "stat", "wc", "diff",
36
+ "file", "bat", "jq", "yq", "sha256sum", "md5sum", "realpath", "readlink", "test", "["}
37
+ PROTECTED_MARKERS = (".secondkey/", "/.secondkey", ".claude/settings.json", ".claude/settings.local.json",
38
+ ".cursor/hooks.json")
39
+ AGENT_READ_ONLY_SUBCOMMANDS = {"check", "pending", "show", "log", "snapshots", "policy", "doctor", "--version", "-h", "--help"}
40
+
41
+
42
+ def protected_path(path: str) -> bool:
43
+ """Files that control SecondKey itself: an agent must never change them."""
44
+ if not path:
45
+ return False
46
+ p = os.path.expanduser(path.lstrip(">")).replace("\\", "/")
47
+ home = os.environ.get("SECONDKEY_HOME")
48
+ if home and os.path.abspath(p).startswith(os.path.abspath(os.path.expanduser(home))):
49
+ return True
50
+ while p.startswith("./"):
51
+ p = p[2:]
52
+ norm = p if p.startswith("/") else "/" + p
53
+ return any(m in norm or norm.endswith(m.rstrip("/")) for m in PROTECTED_MARKERS)
54
+
55
+
56
+ @dataclass
57
+ class Action:
58
+ category: str
59
+ summary: str
60
+ provider: str | None = None # snapshot provider able to protect this action
61
+ target: dict[str, Any] = field(default_factory=dict)
62
+
63
+ def to_dict(self) -> dict[str, Any]:
64
+ return {"category": self.category, "summary": self.summary, "provider": self.provider, "target": self.target}
65
+
66
+ @classmethod
67
+ def from_dict(cls, d: dict[str, Any]) -> "Action":
68
+ return cls(d["category"], d["summary"], d.get("provider"), d.get("target") or {})
69
+
70
+
71
+ # ---------------------------------------------------------------- helpers
72
+
73
+ def is_secret_path(path: str) -> bool:
74
+ if not path or path.startswith("-"):
75
+ return False
76
+ p = os.path.expanduser(path).replace("\\", "/")
77
+ base = os.path.basename(p.rstrip("/"))
78
+ if base in SAFE_SECRET_NAMES:
79
+ return False
80
+ if any(d in "/" + p.lstrip("/") for d in SECRET_DIRS):
81
+ return True
82
+ return any(fnmatch.fnmatch(base, pat) for pat in SECRET_PATTERNS)
83
+
84
+
85
+ def _pipelines(command: str) -> list[tuple[list[str], str]]:
86
+ """Return (argv, operator-after) pairs so we can see `curl ... | sh`."""
87
+ try:
88
+ lex = shlex.shlex(command, posix=True, punctuation_chars=";&|")
89
+ lex.whitespace_split = True
90
+ lex.commenters = "#"
91
+ tokens = list(lex)
92
+ except ValueError:
93
+ return []
94
+ out: list[tuple[list[str], str]] = []
95
+ cur: list[str] = []
96
+ for t in tokens:
97
+ if t and set(t) <= set(";&|"):
98
+ out.append((cur, t))
99
+ cur = []
100
+ else:
101
+ cur.append(t)
102
+ out.append((cur, ""))
103
+ return [(a, op) for a, op in out if a]
104
+
105
+
106
+ def _unwrap(argv: list[str]) -> list[str]:
107
+ i = 0
108
+ while i < len(argv):
109
+ a = argv[i]
110
+ if re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", a):
111
+ i += 1
112
+ continue
113
+ base = os.path.basename(a)
114
+ if base in WRAPPERS:
115
+ i += 1
116
+ while i < len(argv) and argv[i].startswith("-"):
117
+ takes = WRAPPER_VALUE_FLAGS.get(base, ())
118
+ i += 2 if argv[i] in takes else 1
119
+ continue
120
+ if base == "env":
121
+ i += 1
122
+ while i < len(argv) and (argv[i].startswith("-") or "=" in argv[i]):
123
+ i += 1
124
+ continue
125
+ break
126
+ return argv[i:]
127
+
128
+
129
+ RUNNERS = {"npx": 1, "bunx": 1, "pnpx": 1, "uvx": 1}
130
+ RUNNER_SUB = {"pnpm": ("dlx", "exec"), "yarn": ("dlx", "exec"), "npm": ("exec",), "uv": ("run",), "poetry": ("run",),
131
+ "pipenv": ("run",), "bundle": ("exec",), "pdm": ("run",), "hatch": ("run",)}
132
+
133
+
134
+ def _unwrap_runner(argv: list[str]) -> list[str]:
135
+ for _ in range(3):
136
+ if not argv:
137
+ return argv
138
+ base = os.path.basename(argv[0])
139
+ if base in RUNNERS:
140
+ argv = [a for a in argv[1:] if a not in ("-y", "--yes", "--no-install")]
141
+ continue
142
+ if base in RUNNER_SUB and len(argv) > 1 and argv[1] in RUNNER_SUB[base]:
143
+ argv = [a for a in argv[2:] if a != "--"]
144
+ continue
145
+ break
146
+ return argv
147
+
148
+
149
+ def _database_url(env: dict[str, str]) -> str | None:
150
+ for var in ("SECONDKEY_DATABASE_URL", "DATABASE_URL", "POSTGRES_URL", "DB_URL"):
151
+ v = env.get(var)
152
+ if v and v.split(":", 1)[0] in ("postgres", "postgresql"):
153
+ return v
154
+ return None
155
+
156
+
157
+ MIGRATION_RULES: list[tuple[str, str, str]] = [
158
+ # (program, regex over the rest of argv joined, category)
159
+ ("alembic", r"\bdowngrade\b", "db.migrate_down"),
160
+ ("prisma", r"\bmigrate\s+reset\b|\bdb\s+push\b.*--(force-reset|accept-data-loss)", "db.reset"),
161
+ ("rails", r"\bdb:(drop|reset|schema:load|migrate:reset|purge|truncate_all)\b", "db.reset"),
162
+ ("rails", r"\bdb:(rollback|migrate:down|migrate:redo)\b", "db.migrate_down"),
163
+ ("rake", r"\bdb:(drop|reset|schema:load|migrate:reset|purge|truncate_all)\b", "db.reset"),
164
+ ("rake", r"\bdb:(rollback|migrate:down|migrate:redo)\b", "db.migrate_down"),
165
+ ("manage.py", r"\b(flush|reset_db|sqlflush)\b", "db.reset"),
166
+ ("manage.py", r"\bmigrate\s+\S+\s+zero\b", "db.migrate_down"),
167
+ ("sequelize", r"\bdb:drop\b", "db.reset"),
168
+ ("sequelize", r"\bdb:migrate:undo", "db.migrate_down"),
169
+ ("sequelize-cli", r"\bdb:drop\b", "db.reset"),
170
+ ("sequelize-cli", r"\bdb:migrate:undo", "db.migrate_down"),
171
+ ("knex", r"\bmigrate:(rollback|down)\b", "db.migrate_down"),
172
+ ("supabase", r"\bdb\s+reset\b", "db.reset"),
173
+ ("typeorm", r"\bschema:drop\b", "db.reset"),
174
+ ("typeorm", r"\bmigration:revert\b", "db.migrate_down"),
175
+ ("diesel", r"\bdatabase\s+reset\b", "db.reset"),
176
+ ("diesel", r"\bmigration\s+(revert|redo)\b", "db.migrate_down"),
177
+ ("flyway", r"\bclean\b", "db.reset"),
178
+ ("liquibase", r"\bdrop-?all\b", "db.reset"),
179
+ ("liquibase", r"\brollback", "db.migrate_down"),
180
+ ("goose", r"\breset\b", "db.reset"),
181
+ ("goose", r"\b(down|down-to)\b", "db.migrate_down"),
182
+ ("migrate", r"\bdrop\b", "db.reset"),
183
+ ("migrate", r"\bdown\b", "db.migrate_down"),
184
+ ("dbmate", r"\bdrop\b", "db.reset"),
185
+ ("dbmate", r"\b(down|rollback)\b", "db.migrate_down"),
186
+ ("drizzle-kit", r"\bdrop\b", "db.migrate_down"),
187
+ ]
188
+
189
+
190
+ def _migration(argv: list[str], env: dict[str, str]) -> Action | None:
191
+ prog = os.path.basename(argv[0])
192
+ rest = argv[1:]
193
+ if prog.startswith("python") and rest and os.path.basename(rest[0]) == "manage.py":
194
+ prog, rest = "manage.py", rest[1:]
195
+ elif prog == "manage.py" or argv[0].endswith("/manage.py"):
196
+ prog = "manage.py"
197
+ elif prog in ("rails", "rake") or argv[0].endswith(("bin/rails", "bin/rake")):
198
+ prog = "rails" if "rails" in argv[0] else "rake"
199
+ text = " ".join(rest)
200
+ for p_name, rx, cat in MIGRATION_RULES:
201
+ if prog == p_name and re.search(rx, text):
202
+ url = _database_url(env)
203
+ target = {"conn": {"dbname": url}, "tables": ["*"], "kind": cat} if url else {}
204
+ note = "" if url else " (no Postgres DATABASE_URL found, so no automatic snapshot)"
205
+ return Action(cat, f"{prog} {text}"[:110] + note, "postgres" if url else None, target)
206
+ return None
207
+
208
+
209
+ def _expand(arg: str, env: dict[str, str]) -> str:
210
+ def rep(m: re.Match) -> str:
211
+ name = m.group(1) or m.group(2)
212
+ return env.get(name, m.group(0))
213
+ return re.sub(r"\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)", rep, os.path.expanduser(arg))
214
+
215
+
216
+ def _opt_value(argv: list[str], shorts: tuple[str, ...], longs: tuple[str, ...]) -> list[str]:
217
+ vals, i = [], 0
218
+ while i < len(argv):
219
+ a = argv[i]
220
+ if a in shorts or a in longs:
221
+ if i + 1 < len(argv):
222
+ vals.append(argv[i + 1])
223
+ i += 2
224
+ continue
225
+ for lo in longs:
226
+ if a.startswith(lo + "="):
227
+ vals.append(a[len(lo) + 1:])
228
+ for sh in shorts:
229
+ if len(sh) == 2 and a.startswith(sh) and len(a) > 2 and not a.startswith("--"):
230
+ vals.append(a[2:])
231
+ i += 1
232
+ return vals
233
+
234
+
235
+ # ---------------------------------------------------------------- per-program classifiers
236
+
237
+ def _psql(argv: list[str], cwd: str, env: dict[str, str]) -> list[Action]:
238
+ args = [_expand(a, env) for a in argv[1:]]
239
+ sql_parts = _opt_value(args, ("-c",), ("--command",))
240
+ for f in _opt_value(args, ("-f",), ("--file",)):
241
+ path = os.path.join(cwd, f)
242
+ try:
243
+ with open(path, encoding="utf-8") as fh:
244
+ sql_parts.append(fh.read())
245
+ except OSError:
246
+ return [Action("sql.other", f"psql -f {f} (file not readable, contents unknown)")]
247
+ conn: dict[str, str] = {}
248
+ for key, shorts, longs in (("dbname", ("-d",), ("--dbname",)), ("host", ("-h",), ("--host",)),
249
+ ("port", ("-p",), ("--port",)), ("user", ("-U",), ("--username",))):
250
+ v = _opt_value(args, shorts, longs)
251
+ if v:
252
+ conn[key] = v[-1]
253
+ takes_value = {"-c", "-f", "-d", "-h", "-p", "-U", "-v", "-o", "-L", "-P", "-T", "-F", "-R", "--command",
254
+ "--file", "--dbname", "--host", "--port", "--username", "--set", "--variable", "--output"}
255
+ positional, skip = [], False
256
+ for a in args:
257
+ if skip:
258
+ skip = False
259
+ continue
260
+ if a in takes_value:
261
+ skip = True
262
+ continue
263
+ if a.startswith("-"):
264
+ continue
265
+ positional.append(a)
266
+ if positional and "dbname" not in conn:
267
+ conn["dbname"] = positional[0]
268
+ if len(positional) > 1 and "user" not in conn:
269
+ conn["user"] = positional[1]
270
+ if not sql_parts:
271
+ return [Action("sql.interactive", "psql interactive session (statements unknown)")]
272
+ actions = []
273
+ for st in classify_sql("\n;\n".join(sql_parts)):
274
+ target = {"conn": conn, "tables": st.tables, "sql": st.text, "where": st.where, "kind": st.category}
275
+ provider = "postgres" if st.tables and st.category in ("sql.drop", "sql.truncate", "sql.delete", "sql.update", "sql.alter") else None
276
+ label = st.text if len(st.text) <= 120 else st.text[:117] + "..."
277
+ actions.append(Action(st.category, label, provider, target))
278
+ return actions
279
+
280
+
281
+ def _mysql_conn(args: list[str]) -> dict[str, str]:
282
+ conn: dict[str, str] = {}
283
+ for key, shorts, longs in (("host", ("-h",), ("--host",)), ("port", ("-P",), ("--port",)), ("user", ("-u",), ("--user",)),
284
+ ("database", ("-D",), ("--database",))):
285
+ v = _opt_value(args, shorts, longs)
286
+ if v:
287
+ conn[key] = v[-1]
288
+ for a in args:
289
+ if a.startswith("-p") and len(a) > 2 and not a.startswith("--"):
290
+ conn["password"] = a[2:]
291
+ elif a.startswith("--password="):
292
+ conn["password"] = a.split("=", 1)[1]
293
+ takes = {"-h", "-P", "-u", "-D", "-e", "--host", "--port", "--user", "--database", "--execute"}
294
+ pos, skip = [], False
295
+ for a in args:
296
+ if skip:
297
+ skip = False
298
+ continue
299
+ if a in takes:
300
+ skip = True
301
+ continue
302
+ if not a.startswith("-"):
303
+ pos.append(a)
304
+ if pos and "database" not in conn:
305
+ conn["database"] = pos[0]
306
+ return conn
307
+
308
+
309
+ def _generic_sql(prog: str, argv: list[str], env: dict[str, str]) -> list[Action]:
310
+ args = [_expand(a, env) for a in argv[1:]]
311
+ flags = {"mysql": (("-e",), ("--execute",)), "mariadb": (("-e",), ("--execute",)),
312
+ "sqlite3": ((), ()), "duckdb": (("-c",), ())}
313
+ shorts, longs = flags.get(prog, ((), ()))
314
+ parts = _opt_value(args, shorts, longs)
315
+ if prog == "sqlite3":
316
+ pos = [a for a in args if not a.startswith("-")]
317
+ parts = pos[1:]
318
+ if not parts:
319
+ return [Action("sql.interactive", f"{prog} session (statements unknown)")]
320
+ conn = _mysql_conn(args) if prog in ("mysql", "mariadb") else {}
321
+ out = []
322
+ for st in classify_sql("\n;\n".join(parts)):
323
+ provider = "mysql" if conn and st.tables and st.category in ("sql.drop", "sql.truncate", "sql.delete", "sql.update", "sql.alter") else None
324
+ out.append(Action(st.category, st.text[:120], provider,
325
+ {"tables": st.tables, "client": prog, "conn": conn, "where": st.where, "kind": st.category}))
326
+ return out
327
+
328
+
329
+ def _rm(argv: list[str], cwd: str, env: dict[str, str]) -> list[Action]:
330
+ recursive, targets, end = False, [], False
331
+ for a in argv[1:]:
332
+ if not end and a == "--":
333
+ end = True
334
+ continue
335
+ if not end and a.startswith("-") and a != "-":
336
+ if a in ("--recursive",) or (not a.startswith("--") and re.search(r"[rR]", a)):
337
+ recursive = True
338
+ continue
339
+ targets.append(_expand(a, env))
340
+ paths: list[str] = []
341
+ for t in targets:
342
+ full = t if os.path.isabs(t) else os.path.join(cwd, t)
343
+ matches = glob.glob(full) if any(c in t for c in "*?[") else [full]
344
+ paths.extend(os.path.normpath(m) for m in matches)
345
+ critical = {"/", os.path.expanduser("~"), os.path.normpath(cwd)}
346
+ roots = {os.path.normpath(p) for p in paths}
347
+ if roots & critical or any(p in ("/*", "~/*") for p in targets) or any(is_secret_path(p) for p in paths):
348
+ cat = "fs.delete_critical"
349
+ else:
350
+ cat = "fs.delete_recursive" if recursive else "fs.delete"
351
+ shown = " ".join(targets) if targets else "(no targets)"
352
+ return [Action(cat, f"rm {'-r ' if recursive else ''}{shown}", "files" if paths else None,
353
+ {"paths": paths, "cwd": cwd})]
354
+
355
+
356
+ def _git(argv: list[str], cwd: str, env: dict[str, str]) -> list[Action]:
357
+ args, repo = argv[1:], cwd
358
+ while args and args[0].startswith("-"):
359
+ if args[0] == "-C" and len(args) > 1:
360
+ repo = os.path.join(repo, _expand(args[1], env))
361
+ args = args[2:]
362
+ continue
363
+ if args[0] in ("-c", "--git-dir", "--work-tree") and len(args) > 1:
364
+ args = args[2:]
365
+ continue
366
+ args = args[1:]
367
+ if not args:
368
+ return [Action("git.read", "git")]
369
+ sub, rest = args[0], args[1:]
370
+ t: dict[str, Any] = {"repo": repo, "args": rest}
371
+ flags = [a for a in rest if a.startswith("-")]
372
+ pos = [a for a in rest if not a.startswith("-")]
373
+ if sub == "push":
374
+ force = any(f in ("-f", "--force", "--mirror") or f.startswith("--force-with-lease") or f.startswith("--force-if-includes")
375
+ for f in flags) or any(p.startswith("+") for p in pos[1:])
376
+ deleting = "--delete" in flags or "-d" in flags or any(p.startswith(":") for p in pos[1:])
377
+ remote = pos[0] if pos else None
378
+ refs = [p.lstrip("+") for p in pos[1:]]
379
+ t.update(remote=remote, refs=refs)
380
+ if deleting:
381
+ return [Action("git.delete_remote_branch", "git push " + " ".join(rest), "git", t)]
382
+ if force:
383
+ return [Action("git.force_push", "git push " + " ".join(rest), "git", t)]
384
+ return [Action("git.push", "git push " + " ".join(rest))]
385
+ if sub == "reset" and "--hard" in flags:
386
+ return [Action("git.reset_hard", "git reset " + " ".join(rest), "git", t)]
387
+ if sub == "clean" and any(f.startswith("-") and "f" in f.lstrip("-") or f == "--force" for f in flags):
388
+ t["ignored"] = any(f in ("-x", "-X") or ("x" in f.lstrip("-") and not f.startswith("--")) for f in flags)
389
+ t["dirs"] = any("d" in f.lstrip("-") and not f.startswith("--") for f in flags)
390
+ return [Action("git.clean", "git clean " + " ".join(rest), "git", t)]
391
+ if sub == "branch" and any(f in ("-D", "-d", "--delete") for f in flags):
392
+ t["branches"] = pos
393
+ return [Action("git.branch_delete", "git branch " + " ".join(rest), "git", t)]
394
+ if (sub == "checkout" and ("--" in rest and ("." in rest or len(rest) > 1))) or \
395
+ (sub == "restore" and "--staged" not in flags) or (sub == "stash" and pos[:1] in (["drop"], ["clear"])):
396
+ return [Action("git.discard", f"git {sub} " + " ".join(rest), "git", t)]
397
+ if sub in ("rebase", "filter-branch", "filter-repo", "update-ref", "reflog", "gc", "prune") and \
398
+ (sub != "reflog" or (pos[:1] in (["expire"], ["delete"]))):
399
+ return [Action("git.rewrite", f"git {sub} " + " ".join(rest), "git", t)]
400
+ if sub in ("status", "log", "diff", "show", "fetch", "branch", "remote", "rev-parse", "ls-files", "blame",
401
+ "describe", "tag", "config", "grep", "shortlog", "ls-remote", "reflog"):
402
+ return [Action("git.read", f"git {sub}")]
403
+ return [Action("git.write", f"git {sub} " + " ".join(rest)[:80])]
404
+
405
+
406
+ def _terraform(argv: list[str], cwd: str, env: dict[str, str]) -> list[Action]:
407
+ prog, args, wd = os.path.basename(argv[0]), argv[1:], cwd
408
+ for a in list(args):
409
+ if a.startswith("-chdir="):
410
+ wd = os.path.join(cwd, a.split("=", 1)[1])
411
+ args.remove(a)
412
+ sub = next((a for a in args if not a.startswith("-")), "")
413
+ t = {"cwd": wd, "binary": prog}
414
+ if sub == "destroy" or (sub == "apply" and "-destroy" in args):
415
+ return [Action("tf.destroy", f"{prog} " + " ".join(args), "terraform", t)]
416
+ if sub == "apply":
417
+ return [Action("tf.apply", f"{prog} " + " ".join(args), "terraform", t)]
418
+ if sub == "state" and len(args) > 1 and args[1] in ("rm", "mv", "push", "replace-provider"):
419
+ return [Action("tf.state_write", f"{prog} " + " ".join(args), "terraform", t)]
420
+ if sub == "import" or sub == "taint" or sub == "untaint":
421
+ return [Action("tf.state_write", f"{prog} " + " ".join(args), "terraform", t)]
422
+ return [Action("tf.read", f"{prog} {sub}")]
423
+
424
+
425
+ def _kubectl(argv: list[str], cwd: str, env: dict[str, str]) -> list[Action]:
426
+ args = argv[1:]
427
+ verb = next((a for a in args if not a.startswith("-")), "")
428
+ t = {"args": args, "cwd": cwd}
429
+ if verb == "delete":
430
+ return [Action("k8s.delete", "kubectl " + " ".join(args), "k8s", t)]
431
+ if verb in ("drain", "cordon", "scale", "rollout", "apply", "replace", "patch", "edit", "set", "label",
432
+ "annotate", "create", "expose", "run", "taint", "autoscale"):
433
+ if verb == "scale" and any(re.fullmatch(r"--replicas=0", a) for a in args):
434
+ return [Action("k8s.scale_to_zero", "kubectl " + " ".join(args), "k8s", t)]
435
+ return [Action("k8s.write", "kubectl " + " ".join(args)[:100])]
436
+ if verb == "exec":
437
+ return [Action("k8s.exec", "kubectl " + " ".join(args)[:100])]
438
+ return [Action("k8s.read", f"kubectl {verb}")]
439
+
440
+
441
+ def _helm(argv: list[str]) -> list[Action]:
442
+ verb = next((a for a in argv[1:] if not a.startswith("-")), "")
443
+ if verb in ("uninstall", "delete", "del", "un"):
444
+ return [Action("k8s.delete", "helm " + " ".join(argv[1:]))]
445
+ if verb in ("install", "upgrade", "rollback"):
446
+ return [Action("k8s.write", "helm " + " ".join(argv[1:]))]
447
+ return [Action("k8s.read", f"helm {verb}")]
448
+
449
+
450
+ def _docker(argv: list[str]) -> list[Action]:
451
+ args = [a for a in argv[1:] if not a.startswith("-")]
452
+ joined = " ".join(args[:2])
453
+ if joined == "volume rm" or (args[:1] == ["volume"] and len(args) > 2 and args[1] == "rm"):
454
+ vols = args[2:]
455
+ return [Action("docker.delete", "docker volume rm " + " ".join(vols), "docker", {"volumes": vols})]
456
+ if joined == "volume prune" or (joined == "system prune" and ("--volumes" in argv or "-a" in argv and "--volumes" in argv)):
457
+ return [Action("docker.delete", "docker " + " ".join(argv[1:]), "docker", {"dangling": True})]
458
+ if args[:1] in (["rm"], ["rmi"]) or joined in ("system prune", "volume rm", "volume prune", "container prune",
459
+ "image prune", "network rm", "container rm", "image rm",
460
+ "compose down", "builder prune"):
461
+ return [Action("docker.delete", "docker " + " ".join(argv[1:]))]
462
+ return [Action("docker.other", "docker " + joined)]
463
+
464
+
465
+ def _aws_target(argv: list[str]) -> tuple[str, dict[str, Any]] | None:
466
+ args = argv[1:]
467
+ common = {k: v[-1] for k, v in (("region", _opt_value(args, (), ("--region",))), ("profile", _opt_value(args, (), ("--profile",)))) if v}
468
+ words = [a for a in args if not a.startswith("-")]
469
+ if words[:2] == ["ec2", "delete-volume"]:
470
+ vid = _opt_value(args, (), ("--volume-id",))
471
+ if vid:
472
+ return "ebs", {**common, "volume_id": vid[-1]}
473
+ if words[:2] == ["rds", "delete-db-instance"]:
474
+ dbi = _opt_value(args, (), ("--db-instance-identifier",))
475
+ if dbi:
476
+ return "rds", {**common, "instance": dbi[-1]}
477
+ if words[:1] == ["s3"] and len(words) > 2 and words[1] in ("rm", "rb") and words[2].startswith("s3://"):
478
+ return "s3", {**common, "uri": words[2], "recursive": "--recursive" in args or words[1] == "rb",
479
+ "bucket_delete": words[1] == "rb"}
480
+ return None
481
+
482
+
483
+ def _cloud(prog: str, argv: list[str]) -> list[Action]:
484
+ words = [a for a in argv[1:] if not a.startswith("-")]
485
+ text = " ".join(words)
486
+ if prog == "aws":
487
+ hit = _aws_target(argv)
488
+ if hit:
489
+ kind, target = hit
490
+ return [Action("cloud.delete", f"aws {text}"[:120], "aws", {"kind": kind, **target})]
491
+ if re.search(r"\b(delete|terminate|destroy|remove|purge|rb|rm|deregister|revoke)\b|\bdelete-[\w-]+|\bterminate-[\w-]+", text):
492
+ return [Action("cloud.delete", f"{prog} {text}"[:120])]
493
+ if re.search(r"\b(describe|list|get|show|ls|info)\b|\b(describe|list|get)-[\w-]+", text):
494
+ return [Action("cloud.read", f"{prog} {text}"[:120])]
495
+ return [Action("cloud.write", f"{prog} {text}"[:120])]
496
+
497
+
498
+ # ---------------------------------------------------------------- public API
499
+
500
+ def classify_shell(command: str, cwd: str, env: dict[str, str] | None = None, _depth: int = 0) -> list[Action]:
501
+ env = dict(os.environ if env is None else env)
502
+ pipes = _pipelines(command)
503
+ if not pipes:
504
+ return [Action("shell.unparsed", f"unparsable shell command: {command[:100]}")]
505
+ actions: list[Action] = []
506
+ for idx, (raw, op) in enumerate(pipes):
507
+ argv = _unwrap_runner(_unwrap(raw))
508
+ if not argv:
509
+ continue
510
+ prog = os.path.basename(argv[0])
511
+ mig = _migration(argv, env)
512
+ if mig:
513
+ actions.append(mig)
514
+ continue
515
+ prev_prog = os.path.basename(_unwrap(pipes[idx - 1][0])[0]) if idx and pipes[idx - 1][1] == "|" and _unwrap(pipes[idx - 1][0]) else ""
516
+ if prog in SHELLS and prev_prog in ("curl", "wget"):
517
+ actions.append(Action("shell.pipe_to_shell", f"{prev_prog} ... | {prog}"))
518
+ continue
519
+ if prog in SHELLS and "-c" in argv and _depth < 3:
520
+ inner = argv[argv.index("-c") + 1] if argv.index("-c") + 1 < len(argv) else ""
521
+ actions.extend(classify_shell(inner, cwd, env, _depth + 1))
522
+ continue
523
+ if prog == "eval" and _depth < 3:
524
+ actions.extend(classify_shell(" ".join(argv[1:]), cwd, env, _depth + 1))
525
+ continue
526
+ if prog == "secondkey" or (prog.startswith("python") and argv[1:3] == ["-m", "secondkey"]):
527
+ rest = argv[3:] if prog.startswith("python") else argv[1:]
528
+ sub = next((a for a in rest if not a.startswith("-") or a in ("--version", "-h", "--help")), "")
529
+ if sub in AGENT_READ_ONLY_SUBCOMMANDS:
530
+ actions.append(Action("secondkey.read", "secondkey " + " ".join(rest)[:80]))
531
+ elif sub in ("approve", "deny"):
532
+ actions.append(Action("secondkey.self_approve", f"agent tried to run secondkey {sub} itself"))
533
+ else:
534
+ actions.append(Action("secondkey.admin", "agent tried to run secondkey " + " ".join(rest)[:60]))
535
+ continue
536
+ expanded = [_expand(a, env) for a in argv[1:]]
537
+ redirect_target = any((a in (">", ">>", "1>", "2>", "&>") and i + 1 < len(expanded) and protected_path(expanded[i + 1]))
538
+ or (a.startswith(">") and protected_path(a.lstrip(">")))
539
+ for i, a in enumerate(expanded))
540
+ harmless_git = prog == "git" and next((a for a in argv[1:] if not a.startswith("-")), "") in (
541
+ "add", "diff", "log", "show", "status", "blame", "commit")
542
+ if redirect_target or (prog not in PURE_READERS and not harmless_git and any(protected_path(a) for a in expanded)):
543
+ actions.append(Action("secondkey.tamper", f"{prog} would change SecondKey's own settings or state"))
544
+ continue
545
+ candidates = [a for a in argv[1:] if not a.startswith("-")]
546
+ if prog in ("cp", "scp", "rsync") and candidates:
547
+ candidates = candidates[:-1] # the last argument is the destination
548
+ if prog in READERS and any(is_secret_path(_expand(a, env).lstrip("@")) for a in candidates):
549
+ actions.append(Action("secrets.read", f"{prog} reads a secret file: " + " ".join(argv[1:])[:100]))
550
+ continue
551
+ if prog in ("printenv",) or (prog in ("env", "export", "set") and len(argv) == 1):
552
+ actions.append(Action("secrets.env_dump", f"{prog} (prints environment variables)"))
553
+ continue
554
+ if prog == "psql":
555
+ actions.extend(_psql(argv, cwd, env))
556
+ elif prog in ("mysql", "mariadb", "sqlite3", "duckdb"):
557
+ actions.extend(_generic_sql(prog, argv, env))
558
+ elif prog in ("dropdb", "dropuser"):
559
+ actions.append(Action("sql.drop_database", " ".join(argv)))
560
+ elif prog.lower() in ("del", "erase", "rd", "remove-item", "ri") or (prog == "rmdir" and any(a.lower() == "/s" for a in argv[1:])):
561
+ # Windows / PowerShell deletes: map their flags onto rm's
562
+ recursive = any(a.lower() in ("/s", "-recurse", "-r") for a in argv[1:])
563
+ targets = [a for a in argv[1:] if not a.startswith(("/", "-"))]
564
+ actions.extend(_rm(["rm"] + (["-r"] if recursive else []) + targets, cwd, env))
565
+ elif prog in ("rm", "unlink", "rmdir", "shred"):
566
+ actions.extend(_rm(argv if prog != "shred" else ["rm"] + argv[1:], cwd, env))
567
+ elif prog == "find" and ("-delete" in argv or "-exec" in argv and "rm" in argv):
568
+ actions.append(Action("fs.delete_recursive", "find ... -delete"))
569
+ elif prog == "git":
570
+ actions.extend(_git(argv, cwd, env))
571
+ elif prog in ("terraform", "tofu", "terragrunt"):
572
+ actions.extend(_terraform(argv, cwd, env))
573
+ elif prog in ("kubectl", "oc"):
574
+ actions.extend(_kubectl(argv, cwd, env))
575
+ elif prog == "helm":
576
+ actions.extend(_helm(argv))
577
+ elif prog in ("docker", "podman"):
578
+ actions.extend(_docker(argv))
579
+ elif prog in ("aws", "gcloud", "az", "gsutil", "doctl", "flyctl", "fly", "vercel", "heroku", "railway", "supabase", "neonctl"):
580
+ actions.extend(_cloud(prog, argv))
581
+ elif prog in ("mkfs", "dd", "fdisk", "parted", "wipefs", "shutdown", "reboot", "halt", "poweroff") or prog.startswith("mkfs."):
582
+ actions.append(Action("system.destructive", " ".join(argv)[:120]))
583
+ elif prog in ("chmod", "chown") and "-R" in argv and any(a in ("/", "~") for a in argv):
584
+ actions.append(Action("system.destructive", " ".join(argv)[:120]))
585
+ else:
586
+ actions.append(Action("shell.other", " ".join(argv)[:120]))
587
+ return actions or [Action("shell.other", command[:120])]
588
+
589
+
590
+ def classify_tool(tool_name: str, tool_input: dict[str, Any], cwd: str, env: dict[str, str] | None = None) -> list[Action]:
591
+ """Classify a Claude Code / MCP tool call."""
592
+ if tool_name in ("Bash", "PowerShell", "shell", "run_shell_command"):
593
+ return classify_shell(str(tool_input.get("command", "")), cwd, env)
594
+ if tool_name == "SQL": # from the Postgres proxy
595
+ from .proxy import classify_query
596
+ return classify_query(str(tool_input.get("command", "")), dict(tool_input.get("conn") or {}))
597
+ path = str(tool_input.get("file_path") or tool_input.get("path") or tool_input.get("notebook_path") or "")
598
+ if tool_name in ("Read", "Grep", "Glob", "NotebookRead", "LS"):
599
+ if path and is_secret_path(path):
600
+ return [Action("secrets.read", f"{tool_name} {path}")]
601
+ pattern = str(tool_input.get("pattern", ""))
602
+ if tool_name == "Glob" and is_secret_path(pattern):
603
+ return [Action("secrets.read", f"Glob {pattern}")]
604
+ return [Action("fs.read", f"{tool_name} {path}".strip())]
605
+ if tool_name in ("Write", "Edit", "MultiEdit", "NotebookEdit"):
606
+ if path and protected_path(path):
607
+ return [Action("secondkey.tamper", f"{tool_name} would change SecondKey's own settings ({path})")]
608
+ if path and is_secret_path(path):
609
+ return [Action("secrets.write", f"{tool_name} {path}")]
610
+ return [Action("fs.write", f"{tool_name} {path}".strip())]
611
+ if tool_name.startswith("mcp__"):
612
+ parts = tool_name.split("__")
613
+ server = parts[1] if len(parts) > 1 else "unknown"
614
+ tool = "__".join(parts[2:]) or "unknown"
615
+ return [Action(f"mcp.{server}.{tool}", f"MCP {server}: {tool}")]
616
+ return [Action(f"tool.{tool_name}", tool_name)]