stacktrace-cli 0.23.0__py3-none-any.whl → 0.25.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.
Files changed (55) hide show
  1. stacktrace/__init__.py +1 -1
  2. stacktrace/agentspec/author.py +131 -26
  3. stacktrace/agentspec/checks.py +229 -13
  4. stacktrace/agentspec/effects/__init__.py +214 -4
  5. stacktrace/agentspec/engine.py +222 -65
  6. stacktrace/agentspec/grants.py +17 -7
  7. stacktrace/agentspec/ledger.py +44 -6
  8. stacktrace/agentspec/packs/kubernetes.py +3 -2
  9. stacktrace/agentspec/redact.py +223 -5
  10. stacktrace/agentspec/rule.py +44 -18
  11. stacktrace/agentspec/serve.py +24 -12
  12. stacktrace/agentspec/triggers.py +86 -17
  13. stacktrace/analysis.py +7 -0
  14. stacktrace/cli.py +15 -1
  15. stacktrace/daemon/db.py +5 -0
  16. stacktrace/daemon/injection_state.py +123 -0
  17. stacktrace/daemon/inline_hook.py +339 -26
  18. stacktrace/daemon/observer.py +76 -8
  19. stacktrace/daemon/policy_engine.py +205 -21
  20. stacktrace/daemon/policy_inputs.py +57 -0
  21. stacktrace/daemon/policy_result.py +40 -4
  22. stacktrace/daemon/policy_runtime.py +207 -43
  23. stacktrace/daemon/protocol.py +8 -0
  24. stacktrace/daemon/runtime.py +7 -0
  25. stacktrace/daemon/server.py +27 -1
  26. stacktrace/daemon/store.py +21 -3
  27. stacktrace/detector/command_actions.py +36 -0
  28. stacktrace/detector/deterministic.py +367 -1
  29. stacktrace/detector/hook_table.py +17 -0
  30. stacktrace/detector/injection.py +784 -0
  31. stacktrace/detector/injection_marks.py +557 -0
  32. stacktrace/detector/injection_values.py +208 -0
  33. stacktrace/detector/inline.py +42 -18
  34. stacktrace/detector/profanity-en.txt +375 -0
  35. stacktrace/detector/profanity.py +234 -0
  36. stacktrace/detector/render.py +13 -2
  37. stacktrace/detector/rules.py +175 -3
  38. stacktrace/detector/run.py +6 -2
  39. stacktrace/detector/settings.py +27 -0
  40. stacktrace/finding_contract.py +27 -0
  41. stacktrace/finding_titles.py +3 -0
  42. stacktrace/gateway/marker.py +55 -3
  43. stacktrace/hooks/claude.py +382 -48
  44. stacktrace/hooks/codex.py +61 -11
  45. stacktrace/hooks/cursor.py +40 -4
  46. stacktrace/hooks/devin.py +43 -6
  47. stacktrace/hydrant_cli.py +57 -16
  48. stacktrace/monitor/render.py +6 -1
  49. stacktrace/monitor/site/app.js +3 -0
  50. stacktrace/prompt_text.py +50 -0
  51. stacktrace/remote/sync_detect.py +8 -0
  52. {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.25.0.dist-info}/METADATA +2 -2
  53. {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.25.0.dist-info}/RECORD +55 -46
  54. {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.25.0.dist-info}/WHEEL +0 -0
  55. {stacktrace_cli-0.23.0.dist-info → stacktrace_cli-0.25.0.dist-info}/entry_points.txt +0 -0
@@ -32,7 +32,8 @@ from stacktrace.detector.deterministic import (
32
32
  )
33
33
 
34
34
  __all__ = ["BREADTHS", "MUTATING", "OPS", "TARGET_KEYS", "Effect", "Extraction", "Where",
35
- "extract", "matches", "question"] # fmt: skip
35
+ "by_path", "extract", "matches", "question", "ran_file", "ran_files", "runner_command",
36
+ "runs_other"] # fmt: skip
36
37
 
37
38
  #: Programs that change nothing outside this machine and its repo. A segment run
38
39
  #: by one of these is no effect and no unknown.
@@ -74,9 +75,211 @@ def _arguments(words: list[str]) -> list[str]:
74
75
  return out
75
76
 
76
77
 
77
- #: Package managers: local unless publishing.
78
+ #: Package managers: local unless publishing or running a script.
78
79
  _PACKAGE = frozenset({"npm", "pnpm", "yarn", "pip", "pip3", "uv", "poetry", "bun", "deno"})
79
80
  _PUBLISH = frozenset({"publish", "deploy", "release"})
81
+ #: A package manager's verbs that run a script or package the command does not
82
+ #: show: `npm run deploy`, `npm test`, `pnpm dlx x`, `uv tool run x`.
83
+ _PACKAGE_RUNS = frozenset({"run", "run-script", "exec", "x", "dlx", "test", "start", "create"})
84
+ #: Package managers whose scripts are `package.json`'s.
85
+ _SCRIPTS_IN_PACKAGE_JSON = frozenset({"npm", "pnpm", "yarn", "bun"})
86
+ #: Runners whose `run` runs the command after it: `uv run pytest` is pytest.
87
+ _RUNNERS = frozenset({"uv", "poetry", "pdm", "pipenv"})
88
+ #: Each runner's `run` options: (those that take the next word as their value, those that
89
+ #: take none). From `uv run --help` (uv 0.11.32) and `poetry run --help`'s global options.
90
+ #: `-m`/`--module` and `-s`/`--script` are left out, so a segment using them stays a `run`.
91
+ _RUNNER_OPTIONS: dict[str, tuple[frozenset[str], frozenset[str]]] = {
92
+ "uv": (
93
+ frozenset({
94
+ "--allow-insecure-host", "--cache-dir", "--color", "--config-file", "--config-setting",
95
+ "--config-settings-package", "--default-index", "--directory", "--env-file",
96
+ "--exclude-newer", "--exclude-newer-package", "--extra", "--extra-index-url",
97
+ "--find-links", "--fork-strategy", "--group", "--index", "--index-strategy",
98
+ "--index-url", "--keyring-provider", "--link-mode", "--no-binary-package",
99
+ "--no-build-isolation-package", "--no-build-package", "--no-editable-package",
100
+ "--no-extra", "--no-group", "--no-sources-package", "--only-group", "--package",
101
+ "--prerelease", "--project", "--python", "--python-platform", "--refresh-package",
102
+ "--reinstall-package", "--resolution", "--upgrade-group", "--upgrade-package",
103
+ "--with", "--with-editable", "--with-requirements", "-C", "-P", "-f", "-i", "-p", "-w",
104
+ }),
105
+ frozenset({
106
+ "--active", "--all-extras", "--all-groups", "--all-packages", "--compile-bytecode",
107
+ "--exact", "--frozen", "--isolated", "--locked", "--managed-python", "--no-binary",
108
+ "--no-build", "--no-build-isolation", "--no-cache", "--no-config",
109
+ "--no-default-groups", "--no-dev", "--no-editable", "--no-env-file", "--no-index",
110
+ "--no-managed-python", "--no-progress", "--no-project", "--no-python-downloads",
111
+ "--no-sources", "--no-sync", "--offline", "--only-dev", "--quiet", "--refresh",
112
+ "--reinstall", "--system-certs", "--upgrade", "--verbose", "-U", "-n", "-q", "-v",
113
+ }),
114
+ ),
115
+ "poetry": (frozenset(), frozenset({"-q", "--quiet", "-v", "-vv", "-vvv", "--verbose",
116
+ "-n", "--no-interaction", "--ansi", "--no-ansi"})),
117
+ } # fmt: skip
118
+ #: `<interpreter> [options] <file>` runs that file.
119
+ _INTERPRETERS = frozenset(
120
+ {"sh", "bash", "zsh", "dash", "ksh", "node", "deno", "bun", "ruby", "perl", "php", "tsx",
121
+ "ts-node", "Rscript"}
122
+ ) # fmt: skip
123
+ _PYTHON = re.compile(r"^python[\d.]*$")
124
+
125
+
126
+ def runner_command(tokens: list[str]) -> list[str]:
127
+ """The command a runner runs: `uv run --frozen pytest -q` is `pytest -q`,
128
+ and `uv run --with pytest deploy.py` is `deploy.py`. An option whose arity
129
+ is not in the runner's table leaves the segment as written, so it stays a
130
+ runner's `run`: code that could be anything, never a guess at the command."""
131
+ if by_path(tokens[0]):
132
+ return tokens # `./uv run x` runs the repository's `./uv`, whatever it does
133
+ if len(tokens) > 2 and os.path.basename(tokens[0]) in _RUNNERS and tokens[1] == "run":
134
+ values, flags = _RUNNER_OPTIONS.get(os.path.basename(tokens[0]), (frozenset(), frozenset()))
135
+ i = 2
136
+ while i < len(tokens) and tokens[i].startswith("-"):
137
+ t = tokens[i]
138
+ if t == "--":
139
+ i += 1
140
+ break
141
+ if t in values:
142
+ i += 2
143
+ elif t in flags or ("=" in t and t.split("=", 1)[0] in values):
144
+ i += 1 # a flag, or `--with=pytest`
145
+ elif len(t) > 2 and not t.startswith("--") and t[:2] in values:
146
+ i += 1 # `-wpytest`: a short option with its value attached
147
+ else:
148
+ return tokens # arity unknown: which word is the command is unknown
149
+ return tokens[i:] or tokens
150
+ return tokens
151
+
152
+
153
+ def ran_file(tokens: list[str]) -> str | None:
154
+ """The file one segment runs, as the command names it: a path run directly
155
+ (`./deploy.sh`, `scripts/x.sh`; not an installed program in a `bin`
156
+ directory), a file an interpreter runs (`bash x.sh`, `python3 x.py`), a
157
+ sourced file, the makefile `make` reads, or the `package.json` a script
158
+ comes from (`npm run x`). None when the segment runs no file."""
159
+ program = tokens[0]
160
+ base = os.path.basename(program)
161
+ if by_path(program):
162
+ return program
163
+ if base in ("source", "."):
164
+ return tokens[1] if len(tokens) > 1 else None
165
+ if base in _PACKAGE:
166
+ if base in _SCRIPTS_IN_PACKAGE_JSON and _runs_script(tokens):
167
+ return "package.json"
168
+ words = [t for t in _arguments(tokens[1:]) if t != "run" and not t.startswith("-")]
169
+ if base not in _INTERPRETERS or not words or "." not in os.path.basename(words[0]):
170
+ return None # `bun install`; `bun x.ts` and `deno run x.ts` run x.ts
171
+ return words[0]
172
+ if base in _INTERPRETERS or _PYTHON.match(base):
173
+ words = _operands(tokens[1:])
174
+ return words[0] if words else None
175
+ if base == "make":
176
+ here, name = "", "Makefile"
177
+ for i, t in enumerate(tokens[1:], 1):
178
+ value = tokens[i + 1] if i + 1 < len(tokens) else ""
179
+ if t in ("-f", "--file", "--makefile"):
180
+ name = value
181
+ elif t.startswith(("--file=", "--makefile=")):
182
+ name = t.split("=", 1)[1]
183
+ elif t.startswith("-f") and len(t) > 2:
184
+ name = t[2:]
185
+ elif t in ("-C", "--directory"):
186
+ here = value
187
+ return os.path.join(here, name) if name else None
188
+ return None
189
+
190
+
191
+ def by_path(program: str) -> bool:
192
+ """Whether `program` is run by its path (`./deploy.sh`, `tools/kubectl`), so
193
+ it is a file of the caller's, not an installed program in a `bin` directory."""
194
+ return "/" in program and os.path.basename(os.path.dirname(program)) not in ("bin", ".bin")
195
+
196
+
197
+ def runs_other(tokens: list[str]) -> bool:
198
+ """Whether one segment runs code the command does not show, so its effect
199
+ is whatever runs: `find -exec`, `go run`, a package script, or a file
200
+ (`ran_file`). Code knows nothing such a segment cannot do."""
201
+ program = os.path.basename(tokens[0])
202
+ if _RUNS_OTHER.get(program, set()) & set(tokens[1:]):
203
+ return True
204
+ if program in _RUNNERS and len(tokens) > 1 and tokens[1] == "run":
205
+ return True # a `run` `runner_command` could not see past
206
+ if program in _PACKAGE and _runs_script(tokens):
207
+ return True
208
+ return ran_file(tokens) is not None
209
+
210
+
211
+ def _runs_script(tokens: list[str]) -> bool:
212
+ """A package manager's command that runs a script or package: its verb is
213
+ one of `_PACKAGE_RUNS`, or `uv tool run`. `yarn add test` adds a package."""
214
+ verbs = [t for t in tokens[1:] if not t.startswith("-")][:2]
215
+ return bool(verbs) and (verbs[0] in _PACKAGE_RUNS or verbs == ["tool", "run"])
216
+
217
+
218
+ def _operands(words: list[str]) -> list[str]:
219
+ """Every word of a segment's arguments that may name a file: each word that
220
+ is not an option, and the value of a `--name=value` option. Which of them
221
+ the program runs is not decided here: options cluster (`-qW x`) and take
222
+ values in ways no table keeps up with, so every candidate is kept and the
223
+ reader keeps the ones that are real files."""
224
+ out: list[str] = []
225
+ for w in _arguments(words):
226
+ if w.startswith("--") and "=" in w:
227
+ out.append(w.split("=", 1)[1])
228
+ elif not w.startswith(("-", "+")) and w:
229
+ out.append(w)
230
+ return out
231
+
232
+
233
+ def ran_files(command: str) -> list[str]:
234
+ """Every file a shell command may run, in order, once each, relative to the
235
+ call's directory or absolute; a `cd` before it moves it. For a segment that
236
+ runs other code (`runs_other`, an interpreter, a runner's `run`), that is
237
+ the file `ran_file` names, then every word of its arguments (`_operands`):
238
+ the reader keeps only real files, so a word that is an option's value costs
239
+ nothing and the file that runs is never left out by a misread option."""
240
+ try:
241
+ segments = [t for t, _ in _executed_segments(command)]
242
+ except Exception: # noqa: BLE001 - unparseable shell: nothing named to read
243
+ return []
244
+ here, out = "", []
245
+ for tokens in segments:
246
+ while len(tokens) > 1 and tokens[0] in _TIMERS: # `timeout 60 ./x.sh` runs ./x.sh
247
+ timer, tokens = tokens[0], tokens[1:]
248
+ while len(tokens) > 1 and tokens[0].startswith("-"):
249
+ tokens = tokens[1:]
250
+ if timer in ("timeout", "nice") and len(tokens) > 1 and tokens[0][:1].isdigit():
251
+ tokens = tokens[1:]
252
+ if tokens[0] == "cd":
253
+ if len(tokens) > 1 and not tokens[1].startswith("-"):
254
+ here = os.path.join(here, tokens[1])
255
+ continue
256
+ for program in _as_written(tokens[0], command):
257
+ written = [program, *tokens[1:]]
258
+ base = os.path.basename(program)
259
+ found = [f for f in [ran_file(written)] if f]
260
+ if runs_other(written) or base in _INTERPRETERS or _PYTHON.match(base):
261
+ found += _operands(tokens[1:])
262
+ out += [os.path.normpath(os.path.join(here, f)) for f in found]
263
+ return list(dict.fromkeys(out))
264
+
265
+
266
+ #: Programs that run the command after them and its options, unchanged.
267
+ _TIMERS = frozenset({"timeout", "nohup", "nice", "time"})
268
+
269
+
270
+ def _as_written(program: str, command: str) -> list[str]:
271
+ """`program` with each path the command wrote it with: the shared segment
272
+ parser keeps only a program's last component (`scripts/x.sh` is `x.sh`).
273
+ The parser gives no position, so a segment cannot tell which of two paths
274
+ with one basename is its own (`./a/x.sh; ./b/x.sh`); every one is returned,
275
+ so neither file is left out of what the judge sees."""
276
+ found = re.findall(
277
+ r"(?:^|(?<=[\s;&|(`'\"]))((?:[\w.~+-]*/)+" + re.escape(program) + r")(?=$|[\s;&|)`'\"])",
278
+ command,
279
+ )
280
+ return list(dict.fromkeys(found)) or [program]
281
+
282
+
80
283
  _MCP_READ = re.compile(r"(^|_)(get|list|search|read|query|fetch|find|describe|show|lookup)")
81
284
 
82
285
 
@@ -113,15 +316,22 @@ def extract(
113
316
  except Exception: # noqa: BLE001 - unparseable shell: code cannot rule anything out
114
317
  return Extraction(unknown=("shell",))
115
318
  for tokens, stdin in segments:
319
+ if any(by_path(p) for p in _as_written(tokens[0], command)):
320
+ unknown.append(os.path.basename(tokens[0])) # `./uv run x`: the repository's `./uv`
321
+ continue
322
+ tokens = runner_command(tokens)
116
323
  program = os.path.basename(tokens[0])
324
+ if any(by_path(p) for p in _as_written(tokens[0], command)):
325
+ unknown.append(program) # `./kubectl` is the repository's file, not the CLI
326
+ continue
117
327
  parser = parsers.get(program)
118
328
  if parser is not None:
119
329
  args = _arguments(tokens[1:])
120
330
  effects += parser(program, args, here, _segment_text(tokens, stdin), stdin)
121
- elif program in LOCAL and not _RUNS_OTHER.get(program, set()) & set(tokens[1:]):
331
+ elif program in LOCAL and not runs_other(tokens):
122
332
  continue
123
333
  elif program in _PACKAGE:
124
- if _PUBLISH & set(tokens[1:3]):
334
+ if _PUBLISH & set(tokens[1:3]) or runs_other(tokens):
125
335
  unknown.append(program)
126
336
  else:
127
337
  unknown.append(program)