ccvet 0.0.1__tar.gz

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 (46) hide show
  1. ccvet-0.0.1/.github/workflows/publish.yml +42 -0
  2. ccvet-0.0.1/.github/workflows/test.yml +23 -0
  3. ccvet-0.0.1/.gitignore +10 -0
  4. ccvet-0.0.1/CONTRIBUTING.md +35 -0
  5. ccvet-0.0.1/Docs/PLAN.md +140 -0
  6. ccvet-0.0.1/Docs/hook-contract.md +83 -0
  7. ccvet-0.0.1/Docs/risk-taxonomy.md +102 -0
  8. ccvet-0.0.1/LICENSE +21 -0
  9. ccvet-0.0.1/PKG-INFO +130 -0
  10. ccvet-0.0.1/README.md +105 -0
  11. ccvet-0.0.1/SECURITY.md +49 -0
  12. ccvet-0.0.1/pyproject.toml +54 -0
  13. ccvet-0.0.1/src/ccvet/__init__.py +1 -0
  14. ccvet-0.0.1/src/ccvet/audit.py +67 -0
  15. ccvet-0.0.1/src/ccvet/classifier.py +129 -0
  16. ccvet-0.0.1/src/ccvet/cli.py +146 -0
  17. ccvet-0.0.1/src/ccvet/commands.py +145 -0
  18. ccvet-0.0.1/src/ccvet/config.py +63 -0
  19. ccvet-0.0.1/src/ccvet/data/default_policy.yaml +80 -0
  20. ccvet-0.0.1/src/ccvet/engine.py +21 -0
  21. ccvet-0.0.1/src/ccvet/fsrules.py +43 -0
  22. ccvet-0.0.1/src/ccvet/gate.py +60 -0
  23. ccvet-0.0.1/src/ccvet/init.py +184 -0
  24. ccvet-0.0.1/src/ccvet/paths.py +85 -0
  25. ccvet-0.0.1/src/ccvet/policy.py +15 -0
  26. ccvet-0.0.1/src/ccvet/rules.py +289 -0
  27. ccvet-0.0.1/src/ccvet/shell.py +129 -0
  28. ccvet-0.0.1/src/ccvet/shellrules.py +52 -0
  29. ccvet-0.0.1/src/ccvet/sql_guard.py +35 -0
  30. ccvet-0.0.1/src/ccvet/userpolicy.py +107 -0
  31. ccvet-0.0.1/src/ccvet/verdict.py +56 -0
  32. ccvet-0.0.1/tests/test_audit.py +97 -0
  33. ccvet-0.0.1/tests/test_bash_rules.py +263 -0
  34. ccvet-0.0.1/tests/test_classifier.py +167 -0
  35. ccvet-0.0.1/tests/test_cli.py +132 -0
  36. ccvet-0.0.1/tests/test_commands.py +207 -0
  37. ccvet-0.0.1/tests/test_concurrency_real_processes.py +53 -0
  38. ccvet-0.0.1/tests/test_config.py +36 -0
  39. ccvet-0.0.1/tests/test_engine_dispatch.py +18 -0
  40. ccvet-0.0.1/tests/test_fs_rules.py +122 -0
  41. ccvet-0.0.1/tests/test_gate.py +105 -0
  42. ccvet-0.0.1/tests/test_init.py +147 -0
  43. ccvet-0.0.1/tests/test_init_layer2.py +85 -0
  44. ccvet-0.0.1/tests/test_shell.py +128 -0
  45. ccvet-0.0.1/tests/test_shellrules_layer2.py +68 -0
  46. ccvet-0.0.1/tests/test_userpolicy.py +124 -0
@@ -0,0 +1,42 @@
1
+ name: Publish to PyPI
2
+
3
+ # Runs on a version tag (e.g. v0.0.1). Uses PyPI trusted publishing (OIDC),
4
+ # so no API token is stored anywhere in this repo. The trusted publisher
5
+ # has to be configured once on the PyPI project's own settings page before
6
+ # this will work. See Docs/PLAN.md Phase 6 for the setup steps.
7
+
8
+ on:
9
+ push:
10
+ tags:
11
+ - "v*"
12
+
13
+ permissions:
14
+ contents: read
15
+
16
+ jobs:
17
+ build:
18
+ runs-on: ubuntu-latest
19
+ steps:
20
+ - uses: actions/checkout@v4
21
+ - uses: actions/setup-python@v5
22
+ with:
23
+ python-version: "3.12"
24
+ - run: pip install build
25
+ - run: python -m build
26
+ - uses: actions/upload-artifact@v4
27
+ with:
28
+ name: dist
29
+ path: dist/
30
+
31
+ publish:
32
+ needs: build
33
+ runs-on: ubuntu-latest
34
+ environment: pypi
35
+ permissions:
36
+ id-token: write
37
+ steps:
38
+ - uses: actions/download-artifact@v4
39
+ with:
40
+ name: dist
41
+ path: dist/
42
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,23 @@
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ pull_request:
6
+
7
+ permissions:
8
+ contents: read
9
+
10
+ jobs:
11
+ test:
12
+ runs-on: ubuntu-latest
13
+ strategy:
14
+ fail-fast: false
15
+ matrix:
16
+ python-version: ["3.10", "3.11", "3.12", "3.13"]
17
+ steps:
18
+ - uses: actions/checkout@v4
19
+ - uses: actions/setup-python@v5
20
+ with:
21
+ python-version: ${{ matrix.python-version }}
22
+ - run: pip install -e ".[dev]"
23
+ - run: pytest tests/
ccvet-0.0.1/.gitignore ADDED
@@ -0,0 +1,10 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .DS_Store
10
+ .coverage
@@ -0,0 +1,35 @@
1
+ # Contributing to ccvet
2
+
3
+ Thanks for considering a contribution. The most valuable thing you can add is almost never code: it's a command that ccvet classifies wrong.
4
+
5
+ ## Proposing a new rule or a correction to an existing one
6
+
7
+ Open an issue or a pull request with:
8
+
9
+ 1. The exact command or tool call.
10
+ 2. What ccvet currently decides (`allow`, `ask`, or `deny`). You can check this yourself without installing anything into Claude Code at all:
11
+ ```
12
+ ccvet check "the command in question"
13
+ ```
14
+ 3. What you think it should decide, and why. A short, concrete reason is more useful than a long one. "This can overwrite a production database with no confirmation" is better than a general statement that something feels risky.
15
+
16
+ If you're proposing a new hard-coded safety guard (something that should always be blocked, with no override possible), explain why it belongs on that floor rather than in the ordinary allow or ask lists. See [`Docs/risk-taxonomy.md`](Docs/risk-taxonomy.md) for how the existing rules are organized, and the reasoning behind which things are hard-coded versus user-configurable.
17
+
18
+ ## Code contributions
19
+
20
+ - Every change to the rule engine (`rules.py`, `shell.py`, `sql_guard.py`, `fsrules.py`, `paths.py`) needs a test. If you're fixing a misclassification, add the case to the relevant table in `tests/test_bash_rules.py` or `tests/test_fs_rules.py` so it can't silently regress.
21
+ - Run the full test suite before opening a pull request:
22
+ ```
23
+ pip install -e ".[dev]"
24
+ pytest tests/
25
+ ```
26
+ - Keep the safety invariant intact: a user-configurable rule (anything in `userpolicy.py`, or the optional Layer 2 classifier in `classifier.py`) must never be able to override one of the hard-coded guards. If you're not sure whether your change respects this, say so explicitly in the pull request and it'll get extra scrutiny.
27
+ - No em dashes in user-facing text (README, CLI output, `Verdict` reason strings, docs). Code comments and docstrings are fine either way.
28
+
29
+ ## Reporting a security issue
30
+
31
+ See [`SECURITY.md`](SECURITY.md).
32
+
33
+ ## Questions
34
+
35
+ Open an issue. If you're not sure whether something is a bug, a missing rule, or working as intended, ask anyway; that ambiguity is useful information on its own.
@@ -0,0 +1,140 @@
1
+ # ccvet Implementation Plan
2
+
3
+ Risk-classifying `PreToolUse` gate for Claude Code. Public repo on https://github.com/saicharansreedhara2 (not mortalapps), published to PyPI as `pip3 install ccvet`. Layer 0/1 (rules + heuristics) must fully work with zero model configured; Layer 2 (LLM) is opt-in for the gray zone only. See `risk-taxonomy.md` for the full command classification that backs Phase 1.
4
+
5
+ Legend: `[ ]` not started, `[~]` in progress, `[x]` done.
6
+
7
+ ## Phase 0: Repo and packaging scaffold
8
+ - [x] Repo layout: `src/ccvet/`, `tests/`, `pyproject.toml`, `README.md`, `LICENSE` (MIT)
9
+ - [~] CLI entry point (`ccvet`) with subcommands: `init`, `gate` done; `config`, `policy`, `status`, `check`, `log`, `allow`, `uninstall` still stubs for later phases
10
+ - [x] Minimal `pyproject.toml` (build backend, metadata, `entry_points`)
11
+ - [x] Keep runtime deps minimal and imports lazy. `gate`/`init` modules are imported inside the CLI dispatch functions, not at module load time; zero runtime dependencies so far.
12
+ - [x] `pip install -e .` + `ccvet --version` smoke test (venv at `.venv/`, gitignored)
13
+ - [x] Git init, first commit. Staying local, not pushed anywhere until Phase 6 (target: https://github.com/saicharansreedhara2).
14
+
15
+ ## Phase 0.5: Spike, verify the actual Claude Code hook contract
16
+ - [x] Confirmed exact `PreToolUse` stdin JSON shape against current docs (`code.claude.com/docs/en/hooks`). See `Docs/hook-contract.md`.
17
+ - [x] Confirmed `permissionDecision` has 4 values, not 3: `allow`/`deny`/`ask`/`defer`. `defer` (hand back to normal permission flow) is what ccvet uses for "no opinion yet". `ask` is reserved for an explicit escalation, including ccvet's own crash fallback. `defer`'s behavior depends on the session's `permission_mode`, which is the wrong failure mode for an internal error, so the two are not interchangeable.
18
+ - [x] Confirmed hook timeout: 600s default for `PreToolUse` (not 30s), configurable per-handler. On timeout the tool call falls through to normal permission flow rather than being blocked, so Layer 2's budget (Phase 4) has ample room under the 10s handler timeout `ccvet init` sets.
19
+ - [x] Hard-coded hook (`ccvet gate` returning `defer`, or `ask` on internal error) wired via `ccvet init` into a scratch project's `.claude/settings.json`, exercised with the documented stdin example piped directly into `ccvet gate`. Output matched the contract exactly. Also verified `ccvet init` is idempotent (second run is a no-op) and preserves pre-existing `PreToolUse` entries rather than clobbering them.
20
+ - [ ] Still unverified: how Claude Code reconciles multiple `PreToolUse` hooks running in parallel when their decisions disagree. Not stated in the docs page; flagged in `hook-contract.md` as an open question.
21
+
22
+ ## Phase 1: Layer 0/1 rule engine (no model required), DONE 2026-11-23
23
+ - [x] Rule schema (YAML): shipped `data/default_policy.yaml` covers the argument-insensitive program lists (`auto_programs`/`ask_programs`/git auto/ask subcommands). Argument-sensitive rules (rm -rf, chmod -R 777, git push --force, obfuscation, secret/persistence paths) are hard-coded guards in `rules.py` by design. These are the safety floor and aren't meant to be user-overridable (documented at the top of the YAML file and in risk-taxonomy.md).
24
+ - [x] Default policy shipped in-package (`src/ccvet/data/default_policy.yaml`), verified it's actually bundled into a built wheel (not just present in the editable install). A real packaging check, not an assumption.
25
+ - [x] Tool-type dispatch in `engine.py`: Bash goes to `shellrules`; Read/Grep/Glob/Edit/Write/NotebookEdit go to `fsrules`; WebSearch/WebFetch/Task/Agent are handled directly; an unknown tool returns `defer`.
26
+ - [x] Shell tokenization via `bashlex` (verified against real parse trees for lists/pipelines/command-substitution before writing the extraction code). Splits compound commands (`&&`, `;`, `|`, `$(...)`) into sub-commands; a dynamically-constructed command name (e.g. `$(echo rm) -rf /`) is detected and denied outright since it can't be statically classified.
27
+ - [x] Obfuscation heuristic: decode (`base64`/`xxd`/`openssl`) or download (`curl`/`wget`) followed anywhere later in the same parse by a shell invocation (`sh`/`bash`/`zsh`/...) is denied. Catches both `curl url | sh` and `echo <b64> | base64 -d | sh`.
28
+ - [x] Path-scope checks resolve `realpath` first (`paths.py`), tested specifically against a symlink pointing outside the project root to confirm it can't bypass the boundary.
29
+ - [x] Verdict reason-string convention implemented exactly as specified (`verdict.py`): `allow`/`ask`/`deny`/`defer` each produce a consistently prefixed, human-readable reason.
30
+ - [x] Unknown/unrecognized tool calls return `defer`, not `ask` (see verdict.py docstring for why these aren't interchangeable). `defer` is correct here since ccvet genuinely has no opinion on a tool it's never heard of, versus Bash/file gray-zone cases where ccvet does have an opinion: "ask a human".
31
+ - [x] 105 unit tests passing: `test_shell.py` (parser/extraction), `test_bash_rules.py` (taxonomy-row table: AUTO/ASK/BLOCK cases across every category), `test_fs_rules.py` (path scoping, symlink traversal, persistence/secret/manifest files), `test_engine_dispatch.py`, `test_gate.py` (end-to-end and crash safety), `test_init.py`.
32
+ - [x] Two real bugs caught and fixed by the test suite itself: `"/".rstrip("/")` collapsing to `""` and silently escaping the catastrophic rm/chmod root-path check; `npm list`/`pip show` misclassified as ASK instead of AUTO (fixed by adding subcommand-aware classifiers for npm/pip, same pattern as git).
33
+
34
+ ## Phase 2: Hook integration, DONE 2026-11-23
35
+ - [x] `ccvet gate`: reads `PreToolUse` JSON from stdin, runs the engine, emits `hookSpecificOutput` JSON (`permissionDecision`, `permissionDecisionReason`)
36
+ - [x] Top-level crash safety: any uncaught exception inside `ccvet gate` must still emit a valid `ask` decision, not `defer` (see Phase 0.5), and never a raw traceback on stdout. Implemented and tested in the Phase 0.5 spike (`gate.py`/`test_gate.py`); carries forward unchanged once the real rule engine replaces the placeholder logic.
37
+ - [x] `ccvet init`: project-local by default, `--global` writes `~/.claude/settings.json`; merges into existing hooks (never overwrites), shows a diff, asks for confirmation before writing
38
+ - [x] `ccvet uninstall`: cleanly removes just ccvet's hook entry, leaving any other configured hooks untouched (and drops the `hooks` top-level key entirely if nothing's left). Round-tripped against a real scratch project, not just unit-tested.
39
+ - [x] Audit log (JSONL) at `~/.ccvet/audit.jsonl` (one consolidated log across all projects, each entry carries `cwd`), concurrency-safe via `fcntl.flock` around each append. Tested with 50 concurrent threads writing simultaneously, no corrupted or merged lines. File created with `0600` permissions (verified, not assumed) since it can contain raw Bash command text. Write-tool content is hashed (`content_sha256` plus `content_length`), never stored verbatim, to avoid persisting secrets into the log.
40
+ - [x] `ccvet gate --dry-run`: evaluates and prints the decision but skips the audit-log write. Verified via a real end-to-end smoke test (dangerous command denied, dry-run confirmed absent from the log; a non-dry-run safe command confirmed present).
41
+ - [x] A failure inside `audit.log()` is swallowed, never allowed to affect the already-emitted decision or crash the hook (tested by injecting a forced `OSError`)
42
+
43
+ ## Phase 3: Config and status, mostly DONE 2026-11-23
44
+ - [x] `ccvet config get/set`: dotted-key YAML store at `~/.ccvet/config.yaml` (`config.py`). Nothing consumes it yet; Phase 4's classifier settings will be the first real reader, but the plumbing is built and tested now.
45
+ - [x] `ccvet status`: reports project/global hook-wiring state, project/global policy rule counts, Layer 2 config presence, and audit log entry count. Smoke-tested end to end in an isolated scratch project, not just unit-tested.
46
+ - [x] `ccvet policy edit`: opens the active `.ccvet/policy.yaml` (project by default, `--global` for the user's global one, **not** the shipped built-in `data/default_policy.yaml`, which stays code-managed) in `$EDITOR`, creating an empty `rules: []` file first if none exists
47
+ - [x] `ccvet check "<command>"` (and `--tool`/`--path`/`--url` for non-Bash tool calls): dry-runs through the real engine and prints decision, reason, and overridable status
48
+ - [x] `ccvet log --tail N`: human-readable view of the audit log (defaults to last 20 entries, `--tail 0` for all)
49
+ - [x] `ccvet allow "<pattern>"`: writes a rule to the project (or `--global`) policy.yaml. Literal by default (regex-escaped); `--regex` passes a pattern through verbatim; `--verdict ask|deny` is also supported for the "add my own stricter rule" case, not just promote-to-allow.
50
+ - [x] User policy precedence implemented in `userpolicy.py`: project `.ccvet/policy.yaml` rules are checked before global `~/.ccvet/policy.yaml` ones, first match wins. Tested, including that a malformed regex in a user rule is skipped rather than fatal.
51
+ - [x] **Safety invariant, enforced structurally, not just by convention**: added an `overridable` field to `Verdict` (default `False`). Every named safety-floor guard in `rules.py`/`shell.py`/`sql_guard.py` leaves it at the default; only the generic program-list/gray-zone fallbacks set it `True`. A user policy rule can only take effect where the built-in verdict was already `overridable=True`, verified end-to-end that a `ccvet allow "rm -rf /"` rule is silently ignored and the command still gets denied. `most_severe()` was also fixed to prefer the non-overridable verdict on a rank tie, so a compound command mixing an overridable ask with a non-overridable one can't be bypassed either.
52
+ - [ ] Policy presets at `ccvet init` time (`strict`/`default`/`permissive`), not done this pass, deferred (low value until there's real usage to calibrate presets against)
53
+
54
+ **Bug caught by integration testing, not unit testing**: the `check` subcommand's positional argument was named `command`, colliding with the top-level `argparse` subparsers' `dest="command"`. Both write into the same flat `Namespace`, so `ccvet check "docker build ."` silently set `args.command` to the command text instead of `"check"`, and the whole dispatch fell through to the help text. The `test_commands.py` tests didn't catch this because they hand-built `argparse.Namespace` objects directly, bypassing real parsing. Fixed by renaming the positional to `shell_command`, and added `test_cli.py` to parse real argv for every subcommand going forward.
55
+
56
+ ## Phase 4: Layer 2, optional LLM gray-zone classifier, DONE 2026-11-24
57
+ - [x] OpenAI-compatible client (`classifier.py`), configurable `classifier.base_url`/`model`/`api_key`/`timeout_seconds` via `ccvet config`. Covers Ollama/LM Studio/vLLM/mtplx uniformly since they all speak the same `/chat/completions` shape. Uses stdlib `urllib`, not an SDK, so there's zero added dependency for people who never enable Layer 2.
58
+ - [x] Forced structured JSON output (`risk`/`reversible`/`blast_radius`/`rationale`) via `response_format: json_object` plus a tolerant regex fallback extraction, with field-value validation (invalid enum values, non-bool `reversible`, etc. all treated as failure)
59
+ - [x] Explicit timeout (`classifier.timeout_seconds`, default 8s). Bumped the hook's own handler timeout from 10s to 20s (`HOOK_TIMEOUT_SECONDS` in `init.py`) to leave real room for a slow local model, since the Phase 0.5 finding was that a hook timeout fails open to normal permission flow rather than blocking. A generous ceiling costs nothing on the fast (Layer 0/1-only) path and only helps the slow path.
60
+ - [x] Prompt hardening: the command is fenced under an explicit "COMMAND TO EVALUATE" heading with instructions to treat it as data, not instructions, even if its text tries to address the model directly. Tested with an actual prompt-injection-shaped string.
61
+ - [x] `ccvet init` auto-detects a running local server (Ollama `:11434`, LM Studio `:1234`) via a 0.5s-timeout probe and offers to wire it in as `classifier.base_url`. Skips the prompt if already configured, silent no-op if nothing's running (verified in this sandbox, which has neither server running, that `ccvet init` doesn't error or hang).
62
+ - [x] **Deliberate asymmetry, matching the `overridable` invariant from Phase 3**: the classifier can only turn an `ask` into an `allow`, never into a `deny`. Layer 0's hard-coded guards keep exclusive denial authority, so a hallucinating or misbehaving local model can't unilaterally block the agent. Verified end-to-end that Layer 2 is never even consulted for a non-overridable verdict (`rm -rf /` stays denied regardless of classifier config).
63
+ - [x] Any failure path (disabled, timeout, transport error, malformed/invalid JSON) returns `None` from `classify()`, meaning "no opinion". The caller falls back to the original gray-zone `ask`, never defaults to `allow` on uncertainty.
64
+ - [x] Verified end-to-end with a real (unreachable) `classifier.base_url` configured: `ccvet gate` degrades to `ask` quickly (connection refused, no hang) rather than timing out or crashing
65
+ - [x] 20 new tests (`test_classifier.py`, `test_shellrules_layer2.py`, `test_init_layer2.py`), 150 total passing
66
+
67
+ ## Phase 5: Testing and hardening, DONE 2026-11-24
68
+
69
+ ### Critical finding: compound shell constructs bypassed classification entirely
70
+ While adding edge-case tests, found that **`{ rm -rf /; }`, `(rm -rf /)`, `if true; then rm -rf /; fi`, `while`, and `for` loops all evaluated to `allow`** instead of being classified at all. Root cause: bashlex represents brace groups, subshells, and the wrapper around if/while/for/until as a `CompoundNode` exposing its children through a `.list` attribute. Every other node kind uses `.parts`, which is the only attribute `shell.py`'s extraction walker checked. The compound wrapper's children were silently never visited, `extract_simple_commands()` returned an empty list, and `shellrules.evaluate()`'s "no commands found" fallback is `allow("empty command")`. That turned "nothing to classify" into "nothing dangerous found" for an entire class of shell syntax. This was a real classification bypass, not a cosmetic gap, and a determined adversary (or just an agent wrapping a command in `{ ...; }` for unrelated reasons) could have walked straight through Layer 0's hard-coded guards.
71
+
72
+ Fixed in `shell.py` (`_children()` now checks both `.parts` and `.list`). Verified against all five constructs plus confirmed a benign brace group (`{ ls -la; }`) still correctly allows. Permanent regression tests added at both the extraction level (`test_shell.py`) and the full end-to-end taxonomy table (`test_bash_rules.py`'s `BLOCK_CASES`), so this can't silently regress. `case` statements remain unparseable by bashlex entirely (a bashlex limitation, not fixable here) and fall to `ask`, not `allow`. Safe, just not actively classified; documented as a known gap rather than silently missing.
73
+
74
+ **This is exactly the kind of bug a hardening pass exists to find.** Worth flagging to the user prominently, not just logging in this file.
75
+
76
+ ### Second round: a deliberate adversarial pass found three more of the same bug shape
77
+ Before deciding the repo was ready to make public, ran a short adversarial pass specifically looking for siblings of the compound-construct bug above (anything else that might not get walked into and visited). Found three more real gaps in the same session:
78
+ - **Process substitution** (`cat <(rm -rf /)`): structured like command substitution (a `.command` attribute), but under a different node kind (`processsubstitution`) that the existing special-case check didn't cover. `cat <(rm -rf /)` extracted to just `cat`, allowing straight through. Fixed by adding `processsubstitution` to the same branch as `commandsubstitution` in `shell.py`.
79
+ - **`eval`/`exec`/`command`/`builtin`** (`eval "rm -rf /"`, `exec rm -rf /`): these transparently run their argument as the real command, but ccvet was classifying the wrapper program name itself (`eval`, `exec`, ...), which isn't on any list, so it fell to a generic "unrecognized command" ask instead of being denied. Fixed in `rules.py`: `exec`/`command`/`builtin` recursively reclassify their remaining argv directly (bashlex already split it); `eval` re-parses its joined string argument through the real shell parser first, since that's what `eval` itself does at runtime.
80
+ - **ANSI-C quoting** (`rm $'-rf' /`): bashlex mis-parses `$'-rf'` as a parameter expansion rather than dequoting it to the literal `-rf`, so the catastrophic-rm flag check doesn't recognize it. This downgrades the result from `deny` to `ask`, not to `allow`, so it's a real gap but not a silent bypass. Documented as a known limitation in `SECURITY.md` and `risk-taxonomy.md` rather than patched, since a narrow fix here risks false confidence given bashlex's own ANSI-C quoting support is the actual weak point. `select`, `coproc`, `[[ ... ]]`, and arithmetic `for ((...))` were also checked and confirmed to fail safely (parse error, falls to `ask`), joining `case` as documented unparseable constructs.
81
+
82
+ All three fixes have permanent regression tests (`test_shell.py`, `test_bash_rules.py`); 227 tests passing, 99% coverage maintained. This round came from deliberately trying to break the same code path again rather than from routine coverage work, which is worth remembering as a technique: once you find one bug in a parser's node-kind coverage, go looking for its siblings before calling the area done.
83
+
84
+ ### Rest of the pass
85
+ - [x] Golden test suite: full taxonomy table mapped to its expected verdict (was already built in Phase 1, extended here with the compound-construct cases above)
86
+ - [x] Edge-case tests: compound safe-then-dangerous and dangerous-then-safe (`ls -la && rm -rf /`, `sudo rm -rf /var && git status`; `most_severe` correctly picks the dangerous half either way); relative `../`-traversal into a credential path and outside the project root (distinct from the symlink case already covered in Phase 1)
87
+ - [x] Confirmed BLOCK tier is unoverridable by Layer 2 two ways: the existing decision-level check, plus a new spy-based test (`test_layer2_is_never_even_called_for_a_non_overridable_verdict`) proving the classifier function is structurally never invoked at all for `rm -rf /`, `sudo`, `git push --force`, `terraform destroy`. Stronger than checking the final answer, since it also rules out "got asked and got ignored by luck".
88
+ - [x] Crash-safety tests: truncated JSON, `tool_input` as the wrong type (string/null), top-level JSON array instead of object, missing `cwd` entirely. All degrade to `ask` (or a sane default), never raise.
89
+ - [x] Concurrency: in addition to the existing 50-thread same-process test (Phase 2), added a real **20-subprocess** test. Actual separate `ccvet gate` OS processes, not threads, each with its own isolated `HOME`, all appending to the same audit log file concurrently. No corruption.
90
+ - [x] Ran a full coverage pass (`pytest-cov`) and closed every gap worth closing: CLI dispatch for every subcommand via real `argparse` parsing (not just hand-built `Namespace` objects), `init.py`'s interactive decline paths and local-server probe branches, `userpolicy.py`'s malformed-rule and invalid-verdict-name paths, `fsrules.py`'s no-recognizable-path case, `commands.py`'s remaining branches (status with populated policy/audit data, log viewer skipping a malformed line, `policy edit`), `classifier.py`'s remaining validation branches. Ended at **99% line coverage, 212 tests**. The few lines left uncovered are deliberate (the real network call body in `classifier.py`, dead code after an intentional `SystemExit` in `cli.py`) or now-unreachable dead code made safe-but-moot by the compound-construct fix above.
91
+ - [x] Verified the wheel still builds cleanly after all changes
92
+
93
+ ## Phase 6: Docs and release
94
+ - [x] README: install, quickstart, policy customization, Layer 2 setup, what each verdict tier means, and a clear opening description aimed at discoverability
95
+ - [x] SECURITY.md: explicit threat model and limitations. ccvet is a heuristic plus optional-LLM advisory gate, not a sandbox; it reduces risk, it doesn't replace least-privilege or container isolation. Said plainly so nobody over-trusts it.
96
+ - [x] CONTRIBUTING.md: how the community proposes new taxonomy rules (issue/PR flow: command and current decision, via `ccvet check`, then the proposed verdict and rationale)
97
+ - [x] LICENSE: MIT
98
+ - [x] No em dashes anywhere in user-facing text: README, SECURITY.md, CONTRIBUTING.md, the Docs/ folder, CLI help strings, and every `Verdict` reason string. Docstrings and inline code comments are exempt by the project's own standing style rule.
99
+ - [x] pyproject.toml polished for PyPI discoverability: expanded description, a `keywords` list (claude-code, pretooluse, permission-hook, auto-approve, risk-classifier, security, guardrails, ollama, lm-studio, and so on), added Topic/Intended Audience classifiers, and Repository/Issues URLs
100
+ - [x] Supply-chain hygiene for ccvet's own release: `.github/workflows/test.yml` (CI across Python 3.10 through 3.13 on every push/PR, `fail-fast: false`) and `.github/workflows/publish.yml` (builds on a `v*` tag, publishes via PyPI trusted publishing/OIDC, zero stored API tokens). GitHub Action versions pinned to specific tags (`actions/checkout@v4`, etc.), not `@main`. Verified both workflow YAML files parse and that `python -m build` produces a clean sdist and wheel, exactly what the publish job runs.
101
+ - [x] First real push to GitHub (2026-11-26) caught a real CI bug immediately: the matrix included Python 3.9, but `ubuntu-latest` has moved to Ubuntu 26.04, which has no 3.9 build in the `actions/python-versions` manifest at all, and the default `fail-fast: true` cancelled every other version's job the moment 3.9's setup step failed. Python 3.9 itself passed its own upstream end-of-life in October 2025, so dropped the floor to `>=3.10` in `pyproject.toml` and the test matrix, and added `fail-fast: false` so one version's failure doesn't hide the others' results going forward.
102
+ - [ ] Push repo to https://github.com/saicharansreedhara2/ccvet (and set the GitHub repo's own description/topics for discoverability there too). **Blocked on user confirmation** since this is a visible, hard-to-reverse action.
103
+ - [ ] PyPI packaging and first publish (`ccvet`). **Blocked on a manual step only the user can do**: configuring a "pending trusted publisher" on PyPI's own site for the `ccvet` project name, pointing at this repo and the `publish.yml` workflow, before any tag push will actually succeed.
104
+ - [x] Release automation: `publish.yml` publishes on any `v*` tag push. Version bump itself (editing `pyproject.toml`'s `version` field before tagging) stays manual, which is normal for a project this size.
105
+
106
+ ## Deep review pass (2026-11-25): a full manual audit of every module, before deciding the repo was ready to push
107
+
108
+ Separate from the targeted adversarial pass earlier (which specifically hunted for siblings of one known bug shape), this was a line-by-line read of every module in `src/ccvet/` looking for anything wrong: logic bugs, missed cases, crash risks, usability gaps. Found and fixed 16 real issues, tracked here in severity order.
109
+
110
+ **High severity (real classification gaps):**
111
+ - Shell redirections (`>`, `>>`, `<`, `<<<`) were completely invisible to classification, since a redirect target never appears in a command's argument list. `curl ... < ~/.aws/credentials` (credential exfiltration via input redirect) and `echo ... >> ~/.bashrc`/`>> ~/.ssh/authorized_keys`/`>> /etc/crontab` (persistence writes) all evaded the secret/persistence guards entirely. Fixed: `shell.py` now extracts every redirect target (`extract_redirect_targets()`, reusing the same compound/substitution-aware tree walk as command extraction) and `rules.redirect_target_guard()` checks them against the same secret/persistence patterns Edit/Write tool paths already use.
112
+ - `paths.py`'s secret/persistence/manifest matching used a raw substring search on the full resolved path string: `/etc/passwd` matched `/etc/passwd_notes.md`, `.bashrc` matched `my.bashrc_backup.txt`, `package.json` matched `mypackage.json`. Since the secret-path match is a hard, non-overridable deny, a false positive there couldn't even be worked around by the user. Fixed: matching is now component-aware against the path's actual segments (`matches_any`/`path_text_matches_any`), with a pattern component ending in `_` still matching as a prefix (so `.ssh/id_` keeps catching `id_rsa`, `id_ed25519`, etc.).
113
+ - `CATASTROPHIC_RM_TARGETS`/`CATASTROPHIC_CHMOD_TARGETS` were missing `/var`, `/opt`, `/Applications`, `/Library`, `/root`, `/sbin`, `/boot`, `/private`, a bare `*`/`.*` wildcard, and any home-directory-root pattern (`/Users/<name>`, `/home/<name>`) wasn't recognized as catastrophic at all despite being just as destructive as `rm -rf /` for that user. Fixed: expanded the target lists and added `_looks_like_home_directory_root()`.
114
+ - `chmod`'s catastrophic check only recognized octal `777`/`000`, so `chmod -R a+rwx /` (symbolic mode, same effect) wasn't caught. Fixed: `_is_full_permission_grant()` also recognizes symbolic grants (`[ugoa]*[+=]rwx` in any permission-letter order).
115
+ - `find`'s guard only checked exact `-exec`/`-delete`, missing `-execdir`/`-ok`/`-okdir`, which are equally capable of running arbitrary commands on matched files. Fixed: all five flags checked.
116
+ - `sql_guard.py`'s DELETE/UPDATE-without-WHERE check scanned the whole command's text, so `psql -c "DELETE FROM users" -c "... WHERE ..."` (a genuinely unconditional delete, paired with an unrelated WHERE in a different `-c` argument) escaped detection. Fixed: the WHERE check is now scoped to the specific statement, up to the next `;` or closing quote.
117
+
118
+ **Medium severity (real bugs, generally caught by an outer safety net but degrading correctness):**
119
+ - `userpolicy.find_override()` resolved a rule's `verdict:` field via `getattr(Verdict, verdict_name, None)` with no whitelist. A hand-edited `verdict: defer` could be invoked (not something a user rule should produce), and `verdict: rank` (a real but unrelated `Verdict` method) would raise, discarding the already-computed correct built-in verdict for a generic internal-error `ask`. Fixed: an explicit `{"allow": ..., "ask": ..., "deny": ...}` whitelist.
120
+ - `userpolicy._load_file()` and `config._load()` didn't catch YAML parse errors. A malformed user `policy.yaml` or `config.yaml` would raise past the already-computed correct built-in verdict, degrading every single overridable Bash command to a generic internal-error `ask` until the file was fixed. Fixed: both now catch `yaml.YAMLError` (and reject a non-dict top level) and degrade to "nothing configured" instead.
121
+ - `classifier.classify()`'s exception handling was a curated list that missed `IndexError` (an empty `choices` array from a misbehaving server) and `TypeError` (a non-numeric `classifier.timeout_seconds`, since `ccvet config set` always stores CLI values as strings). Fixed: broadened to a blanket `except Exception`, matching the function's own stated "always fail to None" contract, and added explicit `float()` coercion with a safe fallback for the timeout.
122
+ - `classifier.py` embedded the raw command inside a markdown code fence in the Layer 2 prompt; a command containing a literal triple-backtick sequence could structurally break out of that framing. Fixed: the command is now JSON-encoded as a single string value instead, which neutralizes backticks/newlines/quotes.
123
+ - `init._load()` had no handling for malformed `.claude/settings.json`, crashing `ccvet init`/`ccvet uninstall`/`ccvet status` with a raw traceback. Fixed: raises a clear `ValueError` that all three call sites now catch and report cleanly.
124
+ - `config.set()`'s use of `setdefault` would raise `TypeError` if an intermediate key already held a non-dict value (e.g. a prior `classifier: some_string` entry). Fixed: explicitly overwrites a non-dict intermediate with `{}` instead of crashing on it.
125
+ - `commands.log_view()` used direct key access (`entry["ts"]`, etc.) with no fallback, so one valid-JSON-but-wrong-shape log line crashed the whole `ccvet log` command, not just that line. Fixed: wrapped per-entry, skipping only the bad line.
126
+ - `commands.allow()` didn't validate a `--regex` pattern before writing it, so an invalid regex silently wrote a dead rule with zero feedback. Fixed: `userpolicy.add_rule()` now validates up front and raises a clear error `ccvet allow` reports.
127
+ - `commands.policy_edit()`'s `subprocess.run([editor, ...])` had no handling for a missing `$EDITOR`/`vi`. Fixed: catches `OSError` and prints a clear message instead of a traceback.
128
+ - `commands.log_view()`'s `--tail` with a negative value produced confusing slice behavior (`--tail -5` skipped the first 5 lines rather than showing all). Fixed: anything that isn't a positive count now means "show all".
129
+
130
+ **Low severity:** a stray f-string prefix with no placeholders in `init.py`, fixed in passing.
131
+
132
+ All 16 fixes have permanent regression tests. 279 tests passing, 99% line coverage, wheel build re-verified clean.
133
+
134
+ ## Phase 7: Stretch goals (post-v1, not blocking initial release)
135
+ - [ ] Persistent local daemon mode so the hook script becomes a thin client call instead of a fresh Python process per tool call, cutting per-invocation startup latency
136
+ - [ ] Windows/PowerShell taxonomy coverage (explicitly deferred in v1, see Scope notes in risk-taxonomy.md)
137
+
138
+ ## Open decisions (not blocking Phase 0-1)
139
+ - ~~Exact repo name/account on GitHub~~ resolved: https://github.com/saicharansreedhara2/ccvet (2026-11-24)
140
+ - Whether `ask` prompts render inline in Claude Code's own permission UI or need a separate TTY prompt: resolved by the Phase 0.5 spike, not assumed
@@ -0,0 +1,83 @@
1
+ # Claude Code PreToolUse Hook Contract (verified 2026-11-23)
2
+
3
+ Source: https://code.claude.com/docs/en/hooks. Captured here because the whole tool is built on this contract. Re-verify against this page if Claude Code's hook format ever changes.
4
+
5
+ ## stdin (what `ccvet gate` receives)
6
+ ```json
7
+ {
8
+ "session_id": "abc123",
9
+ "prompt_id": "550e8400-e29b-41d4-a716-446655440000",
10
+ "transcript_path": "/home/user/.claude/projects/.../transcript.jsonl",
11
+ "cwd": "/home/user/my-project",
12
+ "scratchpad_dir": "/tmp/claude-1000/-home-user-my-project/abc123/scratchpad",
13
+ "permission_mode": "default",
14
+ "hook_event_name": "PreToolUse",
15
+ "tool_name": "Bash",
16
+ "tool_input": { "command": "npm test", "description": "Run test suite", "timeout": 120000, "run_in_background": false },
17
+ "tool_use_id": "toolu_01ABC123..."
18
+ }
19
+ ```
20
+
21
+ ## stdout (what `ccvet gate` must print, exit 0)
22
+ ```json
23
+ {
24
+ "hookSpecificOutput": {
25
+ "hookEventName": "PreToolUse",
26
+ "permissionDecision": "deny",
27
+ "permissionDecisionReason": "Destructive command blocked by hook"
28
+ }
29
+ }
30
+ ```
31
+
32
+ `permissionDecision` values:
33
+ | Value | Behavior |
34
+ |---|---|
35
+ | `allow` | Permit the tool call |
36
+ | `deny` | Block the tool call |
37
+ | `ask` | Escalate to the user |
38
+ | `defer` | Hand back to Claude Code's normal permission flow. **This is ccvet's internal fallback when it has no opinion**, not `ask`, since `ask` and `defer` are different things on the wire even though both end up asking the user in most permission modes. |
39
+
40
+ A hook can also rewrite the call instead of just approving or denying it: `{"hookSpecificOutput": {"allow": true, "updatedInput": {...}}}`. Not used by ccvet v1, but worth knowing it exists.
41
+
42
+ ## Exit codes
43
+ - `0`: success. stdout JSON (if any) is applied, otherwise normal permission flow runs.
44
+ - `2`: blocking error. Tool call is blocked regardless of any JSON printed; stderr becomes the shown reason.
45
+ - other: non-blocking error (unless `onFailure: "block"`). Tool call proceeds, stderr shown as a hook error notice.
46
+
47
+ **ccvet always exits 0 and communicates via the JSON `permissionDecision` field.** Exit code 2 is a blunter instrument (it ignores our JSON) that we don't need.
48
+
49
+ ## Timeout
50
+ Default for `PreToolUse` command/http/mcp_tool hooks: **600 seconds** (the 30s default only applies to `UserPromptSubmit`/`PreModelSwitch`/`PostModelSwitch`, not us). Configurable per-handler via `"timeout"` (seconds) in settings.json.
51
+
52
+ **On timeout**: the hook is cancelled, its output discarded, and critically, *the tool call is NOT blocked by default*. It falls through to normal permission flow unless `onFailure: "block"` is set on that handler. This is actually the right default for ccvet: if Layer 2 hangs, the user still gets a normal prompt rather than the agent silently proceeding.
53
+
54
+ `ccvet init` sets the handler timeout to **20 seconds** (`HOOK_TIMEOUT_SECONDS` in `init.py`), generous relative to Layer 0/1's sub-millisecond cost, to leave real room for a slow local model on the Layer 2 path. Layer 2's own internal LLM-call timeout (`classifier.timeout_seconds`, default **8 seconds**) is set well under that handler timeout, so it has room to emit its own `ask` fallback before Claude Code's cancellation kicks in.
55
+
56
+ ## settings.json shape
57
+ ```json
58
+ {
59
+ "hooks": {
60
+ "PreToolUse": [
61
+ {
62
+ "matcher": "*",
63
+ "hooks": [
64
+ { "type": "command", "command": "ccvet gate", "timeout": 20 }
65
+ ]
66
+ }
67
+ ]
68
+ }
69
+ }
70
+ ```
71
+ - `matcher` filters by tool name pattern (`"Bash"`, `"Edit|Write"`, regex, or `"*"` for all). ccvet installs itself with `"*"` since it wants to see every tool call and apply its own internal dispatch (Read/Grep/Glob versus Bash versus Edit/Write versus everything else) rather than relying on the matcher to pre-filter.
72
+ - Multiple matcher groups can coexist for the same event, and **hooks run in parallel when an event fires**. If the user has other `PreToolUse` hooks installed, ours runs alongside them, not before or after. `ccvet init` must merge into the `PreToolUse` array, never replace it.
73
+ - Handler `type` can be `command`, `http`, `mcp_tool`, `prompt`, or `agent`. ccvet uses `command`.
74
+
75
+ ## Visibility of `permissionDecisionReason` (verified 2026-11-23)
76
+ - **`deny`**: reason is shown to the user as a hook-error notice in the transcript.
77
+ - **`ask`/`defer`**: reason is shown as part of the permission escalation itself.
78
+ - **`allow`**: **not shown.** The docs are explicit that "Claude never sees stderr from a hook that exits 0". The same silence applies to the JSON reason field for `allow`. There's no transcript mode that lists every hook decision inline, only a debug-log flag (`claude --debug`) and a `/hooks` menu that shows *configured* hooks, not runtime decisions.
79
+
80
+ **Decision**: ccvet still populates `permissionDecisionReason` on every decision, including `allow`. It's free, and it's exactly what shows up under `claude --debug`. The real user-facing record of allow decisions is ccvet's own audit log (`ccvet log`), not the live chat transcript. The README documents `claude --debug` as the way to see allow reasons in real time for anyone who wants that during setup or testing.
81
+
82
+ ## Open question not yet resolved by the docs page
83
+ How Claude Code reconciles multiple hooks' decisions when they run in parallel and disagree (for example, one says `allow`, another says `ask`) isn't stated on this page. Treat as unknown. Don't assume ccvet's `deny` is guaranteed to win over another hook's `allow` until verified against real behavior.
@@ -0,0 +1,102 @@
1
+ # ccvet Layer 0/1 Risk Taxonomy
2
+
3
+ Goal: classify as much real-world traffic as possible with zero model calls. Layer 2 (LLM) should only ever see the leftover gray zone. Every row here ships in the default `policy.yaml` as a starting point users can edit.
4
+
5
+ Four verdicts:
6
+ - **AUTO**: auto-approve, no prompt, no log noise beyond a one-line audit entry.
7
+ - **ASK**: mutating but reversible, local-scope; surfaced to the user with a one-line reason.
8
+ - **BLOCK**: irreversible, system-wide, network-exfil-shaped, or credential-touching. No LLM verdict can override this tier; it's the safety floor.
9
+ - **GRAY**: doesn't match any rule; falls through to Layer 2 if configured, otherwise defaults to ASK.
10
+
11
+ ## Filesystem and inspection
12
+ | Verdict | Examples |
13
+ |---|---|
14
+ | AUTO | `ls`, `pwd`, `cat`, `less`, `head`, `tail`, `grep`/`rg`/`ag` (no `-exec`), `find` (no `-delete`/`-exec`/`-execdir`/`-ok`/`-okdir`), `file`, `stat`, `wc`, `diff`, `tree`, `du`, `df`, `which`, `type` |
15
+ | ASK | `mkdir`, `touch`, `cp`/`mv` within project, `chmod` (non-777, within project), `ln -s`, `env` (could print secrets, so ask, not auto) |
16
+ | BLOCK | `rm -rf /`, `/var`, `/opt`, `/Applications`, `/Library`, `/root`, and the other top-level system directories; `rm -rf ~`, a literal `/Users/<name>` or `/home/<name>` home-directory root, or a bare `*`/`.*` wildcard; `chmod -R 777 /` (octal) or `chmod -R a+rwx /` (symbolic, same effect); `chown -R` on system paths; `dd if=... of=/dev/sdX`; `mkfs.*`; `diskutil eraseDisk` |
17
+
18
+ ## Git
19
+ | Verdict | Examples |
20
+ |---|---|
21
+ | AUTO | `git status`, `git diff`, `git log`, `git show`, `git blame`, `git branch` (list), `git remote -v`, `git stash list`, `git fetch`, `git describe`, `git tag -l` |
22
+ | ASK | `git add`, `git commit`, `git checkout -b`, `git merge` (non-force), `git pull`, `git rebase` (local, unpushed), `git stash pop`, `git tag` (create) |
23
+ | BLOCK | `git push --force`/`--force-with-lease` to `main`/`master`/protected branches, `git reset --hard`, `git clean -fdx`, `git branch -D` on protected branches, `git push origin --delete <protected>`, `git filter-branch`/`filter-repo` |
24
+
25
+ ## Package managers and dependencies
26
+ | Verdict | Examples |
27
+ |---|---|
28
+ | AUTO | `npm list`, `npm view`, `pip show`, `pip list`, `pip freeze`, `cargo check`, `go list`, `brew info` |
29
+ | ASK | `npm install`/`pip install` (new deps), `npm uninstall`, `cargo add`, `go get`, `brew install` |
30
+ | BLOCK | `npm publish`, `twine upload`/`pip upload`, `curl <url> \| sh`/`bash`, `wget -O- <url> \| sh`, anything piping a download straight into a shell |
31
+
32
+ ## Build, test, and lint
33
+ | Verdict | Examples |
34
+ |---|---|
35
+ | AUTO | `tsc --noEmit`, `eslint` (no `--fix`), `pytest --collect-only`, `cargo check`, `go vet` |
36
+ | ASK | `npm run <script>` (opaque, so ask by default), `make`, `pytest` (real run, side effects possible), `eslint --fix`, `cargo build`/`run`, `docker build` |
37
+ | GRAY | Arbitrary `./script.sh` with unknown contents. No pattern to match; defer to Layer 2 or ASK. |
38
+
39
+ ## Process and system
40
+ | Verdict | Examples |
41
+ |---|---|
42
+ | AUTO | `ps`, `top` (read), `uname`, `whoami`, `id`, `uptime` |
43
+ | ASK | `kill <pid>` (specific, non-critical), `killall <user-process>` |
44
+ | BLOCK | `sudo` anything, `kill -9 1`, broad `killall -9`/`pkill -f .`, `systemctl stop/disable` on core services, `launchctl unload` on system daemons, `crontab -r` |
45
+
46
+ ## Network
47
+ | Verdict | Examples |
48
+ |---|---|
49
+ | ASK | plain `curl`/`wget` GET (no pipe to shell), `ping`, `dig`/`nslookup` |
50
+ | BLOCK | download piped to shell (see package managers), exfil-shaped commands (`tar czf - ~/.ssh \| curl -T - https://...`, `cat <secret> \| curl -d @- <host>`), reverse shells (`nc -e /bin/sh`, `bash -i >& /dev/tcp/...`) |
51
+
52
+ ## Secrets and credentials
53
+ | Verdict | Examples |
54
+ |---|---|
55
+ | BLOCK (always, regardless of read vs write, including as a shell redirect target) | any path under `~/.ssh/id_*`, `~/.aws/credentials`, `~/.config/gcloud`, `.env` with real secrets, `/etc/passwd`, `/etc/shadow`, as a plain argument, as input to a command (`cat secret \| cmd`), or as a redirect target (`cmd < ~/.aws/credentials`, `cmd >> ~/.ssh/authorized_keys`) |
56
+ | BLOCK, overridable | anything matching `*token*`/`*secret*`/`*credential*` **combined with** a network call in the same command. Fuzzy name-based matching can false-positive on two unrelated sub-commands sharing one compound statement, so unlike the exact-path match above, this one can be promoted past with `ccvet allow` once reviewed. |
57
+
58
+ Path matching (both here and for Edit/Write tool calls) is component-aware, not a raw substring search on the resolved path: `/etc/passwd` matches an actual file named `passwd` inside an `etc` directory, not `/etc/passwd_notes.md`. Redirect targets (`>`, `>>`, `<`, `<<<`) are checked the same way as Edit/Write paths, since a secret or persistence path used only as a redirect target never appears in a command's argument list at all.
59
+
60
+ ## Database
61
+ | Verdict | Examples |
62
+ |---|---|
63
+ | ASK | `SELECT`, `INSERT`, `UPDATE ... WHERE` (scoped) |
64
+ | BLOCK | `DROP DATABASE`/`DROP TABLE`, `TRUNCATE`, `DELETE FROM <table>` with no `WHERE`, `UPDATE` with no `WHERE` |
65
+
66
+ The WHERE check is scoped to the specific DELETE/UPDATE statement (up to the next `;` or closing quote), not the whole command text, so an unrelated WHERE elsewhere in a multi-statement command (`psql -c "DELETE FROM users" -c "... WHERE ..."`) doesn't mask a genuinely unconditional delete.
67
+
68
+ ## Cloud and infra CLIs
69
+ | Verdict | Examples |
70
+ |---|---|
71
+ | ASK | `aws s3 ls`, `aws s3 cp` (a few files), `kubectl get`, `kubectl apply`, `terraform plan` |
72
+ | BLOCK | `terraform destroy`, `aws s3 rm --recursive`, `kubectl delete namespace`/`--all`, `gcloud ... delete`, IAM key creation on root/admin accounts |
73
+
74
+ ## Obfuscation heuristics (Layer 1, pattern-based, not just literal string match)
75
+ These exist because a determined bad actor (or a confused model) won't always spell the dangerous command literally:
76
+ - base64/hex decode piped to a shell (`echo <b64> | base64 -d | sh`)
77
+ - command reconstructed from `$(...)`/env-var concatenation right before execution
78
+ - **Rule**: any decode-then-pipe-to-shell shape gets BLOCK regardless of what's inside. Hiding the payload from static review is itself the risk signal, independent of content.
79
+
80
+ **Engineering note**: this tier only works if commands are tokenized with a real shell parser (`bashlex`/`shlex`), not matched as raw strings. Naive regex on the literal text misses `cmd1 && cmd2`, quoted/escaped variants, and command substitution. The matcher must split compound commands (`&&`, `;`, `|`, `$(...)`) into sub-commands, classify each independently, and take the **highest** risk tier found. A pipeline is only as safe as its most dangerous segment (e.g. `grep foo file | rm -rf bar` must not slip through because `grep` alone is AUTO).
81
+
82
+ ## Beyond Bash: other Claude Code tool calls
83
+ The taxonomy above is shell-command-centric, but `PreToolUse` fires for every tool, not just Bash. These need their own rules:
84
+
85
+ | Tool | Verdict | Notes |
86
+ |---|---|---|
87
+ | `Read`, `Grep`, `Glob` | AUTO | Already read-only by construction, except reads from the secrets paths above, which stay BLOCK/ASK even for reads. |
88
+ | `Edit`/`Write`/`NotebookEdit` on normal project files | ASK (default) | Path resolved to its real, symlink-free location first (see below). AUTO is reasonable to promote once trust is established, but not the v1 default. |
89
+ | `Edit`/`Write` on build/CI/package manifests | ASK, flagged distinctly | `package.json` (especially new `scripts`/`postinstall`/`preinstall` entries), `.npmrc`, `pyproject.toml` build-system, `Pipfile`, `.github/workflows/*.yml`, `.gitlab-ci.yml`, `Jenkinsfile`, `Dockerfile`. These can grant CI secrets access or inject code that runs on someone else's machine later, so they're a supply-chain vector, not just a local file edit. |
90
+ | `Edit`/`Write` on persistence/backdoor vectors | BLOCK | `.git/hooks/*`, `~/.bashrc`/`~/.zshrc`/`~/.profile`/`~/.bash_profile`, `crontab` edits, `~/Library/LaunchAgents/*.plist` (macOS), systemd user unit files. Writing here configures *future* execution, which is the classic persistence pattern, so it's treated as BLOCK even though "just writing a file" looks harmless. |
91
+ | `Edit`/`Write` outside the project root | BLOCK (default), ASK if explicitly scoped by the user | Resolved via realpath before the scope check; `../../` traversal and symlinks must not bypass the project-root boundary. |
92
+ | `WebFetch`/`WebSearch` | ASK / AUTO | `WebSearch` (no page content fetched) can be AUTO. `WebFetch` of an arbitrary URL is ASK by default, since it's a network call that can also be a prompt-injection vector if the fetched page tries to steer the agent. |
93
+ | `Task`/`Agent` (spawning a subagent) | ASK | Kicks off autonomous work that may itself make further tool calls. Visibility matters here even if each individual sub-action would otherwise be AUTO. |
94
+ | Any other/unknown MCP tool | GRAY, defaults to ASK | No built-in opinion on a third-party MCP tool's risk. Defaults to ASK rather than AUTO for anything ccvet doesn't recognize; this is the generic fallback, separate from the Bash-specific GRAY case below. |
95
+
96
+ ## Scope notes
97
+ - **POSIX shells only for v1.** The taxonomy above targets bash/zsh on macOS and Linux. Windows/PowerShell equivalents (`Remove-Item -Recurse -Force`, `Format-Volume`, `icacls`, `Start-Process -Verb RunAs`) are a deliberate non-goal for the first release, not an oversight. This is called out in the README rather than silently under-covered.
98
+ - **`case`, `select`, `coproc`, `[[ ... ]]` test expressions, and arithmetic `for ((...))` loops aren't parseable by bashlex at all.** This is a library limitation, not something fixable in ccvet's own code. Each one fails to parse and falls to `ask` ("could not parse as shell syntax"), not `allow`. Safe, just not actively classified; noted here rather than silently missing. All other compound constructs (brace groups `{ ...; }`, subshells `(...)`, `if`/`while`/`for`, process substitution `<(...)`/`>(...)`, and the transparent wrappers `eval`/`exec`/`command`/`builtin`) parse correctly and are fully classified as of the Phase 5 hardening fixes.
99
+ - **ANSI-C quoting (`$'...'`) around a flag argument can evade the exact-flag-string checks in the hard-coded guards.** For example, `rm $'-rf' /` downgrades from the expected `deny` to `ask`, because bashlex mis-parses `$'-rf'` as a parameter expansion rather than dequoting it to the literal string `-rf`, so the catastrophic-rm check's `arg.startswith("-")` test never matches. This is a bashlex parsing limitation, not an unlimited bypass: the result still fails toward `ask`, never silently toward `allow`. Normal single and double quotes (`'-rf'`, `"-rf"`) are dequoted correctly and are not affected.
100
+
101
+ ## What stays GRAY on purpose
102
+ Anything that's a mutating action with no clean pattern match: a novel one-off shell one-liner, an unfamiliar CLI tool, a script whose contents weren't inspected. These are exactly what Layer 2 is for. Without Layer 2 configured, they fall back to ASK, never AUTO.
ccvet-0.0.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ccvet contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.