diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index cce65a5..01a170e 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "statutor", - "version": "0.7.4", - "description": "Typed project-ledger framework: four planes, single-writer files, hook-enforced mutation policies. Kernel + adapters for Claude Code, Grok Build, OpenCode, Codex, git, and custom harnesses.", + "version": "0.7.5", + "description": "Typed project-ledger framework: four planes, single-writer files, hook-enforced mutation policies. Kernel + adapters for Claude Code, Cursor, Grok Build, OpenCode, Codex, git, and custom harnesses.", "author": { "name": "Hoo" } diff --git a/.cursor/hooks.json b/.cursor/hooks.json new file mode 100644 index 0000000..9fad571 --- /dev/null +++ b/.cursor/hooks.json @@ -0,0 +1,30 @@ +{ + "version": 1, + "hooks": { + "preToolUse": [ + { + "command": "python3 core/statutor_core.py hook", + "matcher": "Write|StrReplace|Shell|Delete|MultiEdit|NotebookEdit|ApplyPatch", + "timeout": 30 + } + ], + "beforeShellExecution": [ + { + "command": "python3 core/statutor_core.py hook", + "timeout": 30 + } + ], + "beforeMCPExecution": [ + { + "command": "python3 core/statutor_core.py hook", + "timeout": 30 + } + ], + "stop": [ + { + "command": "python3 core/statutor_core.py hook --stop", + "timeout": 30 + } + ] + } +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index af4f488..74f1866 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -11,7 +11,7 @@ jobs: strategy: fail-fast: false matrix: - python-version: ["3.10", "3.12", "3.14"] + python-version: ["3.10", "3.12", "3.14", "3.15"] steps: - name: Checkout uses: actions/checkout@v7 diff --git a/DECISIONS.md b/DECISIONS.md index b87447a..28fa2b6 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -198,3 +198,15 @@ **Decision:** Managed instruction/skill operations validate recorded logical/resolved target identity and content tokens, including restore and rollback. Failed post-write checks restore the prior physical artifact when safe; concurrent external edits remain untouched and retain a recovery artifact. These checks do not claim protection against an adversary replacing physical directories during operating-system calls. **Decision:** Worker ingress follows declared capabilities. Sessions bind to the initiating worktree and ledger; per-ledger completion state prevents nested ledgers from interfering. Registry version 1 gains optional `session.ledger_root` and `worktree.completed_by_ledger` fields. Old registries remain readable, but sessions without recorded ledger scope must begin a new session before recording or completing. Scope is never guessed from a shared worktree. **Consequences:** T-0049..T-0054. Python/root and Antigravity plugins move to 0.7.4; the native crate moves to 0.1.2; the first published OpenCode 2.x adapter remains 0.2.0 and requires the hardened Python CLI. Regression cases precede fixes in history. Publication is verified independently per registry; Git tags and checked task boxes do not substitute for registry evidence. + +## D-0030 — Cursor is a protocol map; 0.7.5 closes the 0.7.4 audit +**Status:** accepted +**Context:** The 0.7.4 audit found in-loop holes (Antigravity relative TargetFile vs process CWD; truncated apply_patch allowed; malformed HEAD policy fail-open in the hook; MultiEdit/NotebookEdit unproved; matcher missing `run_terminal_cmd`; Stop could doctor process CWD; Rust receipt missing-key ≠ Python `dict.get`; worker complete hardcoded `HANDOFF.md`) and no Cursor adapter. Cursor hooks.json v1 is a distinct stdin protocol (`hook_event_name`, `workspace_roots`, permission JSON). Empty stdout plus exit 0 fail-closes Cursor permission events. +**Decision:** Ship Cursor as 0.7.5 on the existing kernel. Auto-detect `hook_event_name` in `{preToolUse, beforeShellExecution, beforeMCPExecution, stop}`. Map Write/StrReplace/Shell/Delete/MultiEdit/NotebookEdit and MCP JSON-string payloads onto `validate()`. Permission hooks always emit `{"permission":...}`; fail-open is `allow`. Empty `workspace_roots` stays silent. Stable harness id is `cursor`. Automatic hooks prove attempt only. Dogfood `.cursor/hooks.json` against `core/statutor_core.py`. Close the listed 0.7.4 holes in the same release: relative TargetFile uses workspace CWD; truncated apply_patch denies; `_PolicyFailure` in the hook is `committed policy invalid`; unproved MultiEdit/NotebookEdit deny when governed; matcher includes `run_terminal_cmd`; Stop/doctor/worker honor the overwrite_bounded basename and D-0026 empty-workspace silence; Rust `yaml_optional_string` treats a missing optional OID key as `None`. +**Consequences:** T-0056, T-0057. Python/root and Antigravity plugins move to 0.7.5; the native crate moves to 0.1.3; npm stays 0.2.0. Tab completions and unmapped MCP payloads remain git-floor gaps. Publication remains a human step. Do not reopen D-0028 empty-`old_string` Claude Edit, D-0015 bootstrap receipts, TASKS pruning, or research-note D-number relabel. + +## D-0031 — Repair CLI recovery without changing the local registry format +**Status:** accepted +**Context:** The follow-up flow audit reproduced ignored root arguments, misleading completion retry conflicts, inconsistent CLI help/errors, and Cursor setup/Stop mismatches. Transparent completion replay would need new saved digest evidence, but an extra session field under schema 1 would make older strict readers reject newly written registries. +**Decision:** Preserve the schema-1 registry shape. A completed session reports `already completed` and directs the caller to inspect the recorded result or begin a new session; it never invents a competing completion. Root options work before or after machine/worker subcommands, with explicit child values taking precedence. Invalid `check` invocations return usage status 64; policy denials remain 2 and automatic hooks still fail open. Cursor Stop uses the native [`followup_message`](https://cursor.com/docs/hooks#stop) once at loop count 0, with later loops and aborted/error turns quiet. A fresh 1970 scaffold is described as not yet verified without changing its template or stamping unperformed verification. D-0029's [Unicode 16 decimal grammar](https://www.unicode.org/Public/16.0.0/ucd/extracted/DerivedNumericType.txt) stays fixed; tests no longer derive its accepted alphabet from the interpreter's Unicode database. +**Consequences:** T-0058, T-0059. Add Python 3.15 CI coverage, consumer-project Cursor install/upgrade guidance, global-skill help, and initialization recovery messages. Versions remain Python/plugins 0.7.5, npm 0.2.0, and crate 0.1.3. Publication remains a human step. diff --git a/HANDOFF.md b/HANDOFF.md index 6bcffa0..4de2b68 100644 --- a/HANDOFF.md +++ b/HANDOFF.md @@ -1,40 +1,35 @@ # HANDOFF -last_verified: 2026-10-21 (UTC) by all PR CI, 15 focused checks, independent editorial review, public GitHub rendering/file hashes, and desktop/narrow layout measurements -last_worker: codex +last_verified: 2026-10-27 by `/opt/homebrew/bin/python3 -m pytest -q` (863 passed, 5 skipped) +last_worker: grok last_machine: unknown -handoff_id: b41b8ad341034c5c85c3756a1bb00974 -supersedes: 57e014efb00e443187d60ce57339a5a0 +handoff_id: none +supersedes: adc8ff0ea687dddc32a72682ca45db44 ## Goal -Completed the README redesign approved by the human (T-0055). +Publish GitHub tag v0.7.5 and install that release locally for live dogfood. ## Last verified state -- README is 144 lines, with a compact masthead, badges, navigation, example, - quickstart, agent chooser, Git setup, and visible coverage limits. -- Four linked guides preserve policy/trust, architecture/API, optional global - instructions/skills, and worker provenance. Repository links resolve. -- Antigravity setup now names a real checkout location, registers batch edits, - and describes fail-open behavior and the local Git hook's bypass honestly. -- GitHub Markdown rendering preserves all navigation targets and four images. - Browser DOM layout has no article overflow at 1200 px and 390 px widths. -- Independent editorial review PASS; 15 focused checks pass, including real - npm/Cargo payload audits. Runtime code, versions, and policy are unchanged. -- Hardened release remains Python/plugins 0.7.4, npm 0.2.0, and crate 0.1.2. - PR #2/tag publication and public package verification remain complete. -- PR #3 merged as d0a3bd2; public README, guides, logo, badges, and navigation verified. +- Python and plugins are 0.7.5. npm stays 0.2.0. The crate stays 0.1.3. +- Cursor is a first-class adapter. Governed MultiEdit and NotebookEdit stay + denied. Case variants match only the same directory entry. Invalid UTF-8 + is a denial. apply_patch state IDs must advance. Append-only writes use + the line-subsequence test. +- Pytest on 2026-10-27: 863 passed, 5 skipped. The release gate and the host + probe still have to pass on this commit before the tag. ## Next action -No documentation work remains. Select the next milestone with the human. +Run the v0.7.5 release gate and the host probe. Tag and publish only after +both exit 0. Then install the published package with pipx. ## Gotchas -- CLI installation and project initialization do not register agent hooks. -- Hooks fail open; staged checks fail closed. Git hooks allow --no-verify. -- Begin fresh legacy worker sessions after upgrading; restart Claude for its - already-updated 0.7.4 plugin. Global migration remains a separate opt-in. +- Hooks fail open on a validate exception. Staged mode fails closed. +- Use Homebrew Python 3.15. The system python3 is 3.9.6. +- Tag v0.7.5 starts publish.yml and uploads to PyPI. Do not move the tag. +- Host pins stay Claude 2.1.296, Codex 0.162.1, and OpenCode 2.1.1. ## Do not touch -Embedded templates/init profiles; frozen archive; DECISIONS.md header; -root pre-commit metadata. Preserve untracked .agents/, _local/, assets/, -notes/, and plans/v0.4-dogfood.pdf. +Embedded templates and init profiles; plans/archive/; the DECISIONS.md +header; root pre-commit metadata; ROADMAP.md. npm and crates.io stay pending. +Keep untracked .agents/, _local/, assets/, notes/, and plans/v0.4-dogfood.pdf. diff --git a/README.md b/README.md index 557d79d..b65d5fe 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ the CLI and initializing a ledger do not register agent hooks. | OpenCode | File edits, shell, and patches | [Guide](https://github.com/hoohugokim/statutor/blob/main/adapters/opencode/README.md) | | Google Antigravity | File edits, batch edits, and shell | [Guide](https://github.com/hoohugokim/statutor/blob/main/adapters/antigravity/README.md) | | Grok Build | File edits and shell | [Guide](https://github.com/hoohugokim/statutor/blob/main/adapters/grok/README.md) | +| Cursor | File edits, shell, and MCP when mapped | [Guide](https://github.com/hoohugokim/statutor/blob/main/adapters/cursor/README.md) | | Custom agents | Checks through the CLI or Python API | [API and architecture](https://github.com/hoohugokim/statutor/blob/main/docs/architecture.md) | #### Claude Code @@ -76,7 +77,7 @@ installed, add this entry to your project's `.pre-commit-config.yaml`: ```yaml repos: - repo: https://github.com/hoohugokim/statutor - rev: v0.7.4 + rev: v0.7.5 hooks: [{id: statutor}] ``` diff --git a/ROADMAP.md b/ROADMAP.md index 372f621..e3770db 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,9 +2,9 @@ # ROADMAP ## Current milestone -v0.7.4 hardening is released: Python/plugins 0.7.4, npm 0.2.0, and crate 0.1.2. -T-0049 through T-0054 are complete with independent review and registry proof. -The next milestone is undecided. Release runbook: `docs/releasing.md`. +v0.7.5 candidate: Cursor adapter plus 0.7.4 audit fixes (D-0030). +Python/plugins 0.7.5, npm still 0.2.0, crate 0.1.3. Publication remains a +human step. Release runbook: `docs/releasing.md`. ## Next milestone (human context, agents ignore) Undecided. Candidates: live-binary E2E automation, host role-signal watch diff --git a/TASKS.md b/TASKS.md index 3b7fb11..0485472 100644 --- a/TASKS.md +++ b/TASKS.md @@ -56,3 +56,7 @@ - [x] T-0053 Reconcile release docs, tracked runbooks, completed specifications, and current-host verification; prove hardened artifacts and obtain independent review — DONE 2026-10-22: exact-index artifact gate at ab454d5 passed 769 tests with zero skips, seven Rust tests, all package audits and installed-wheel smoke; native Claude/Codex/OpenCode probes pass; independent runtime PASS+NOTES and Standards PASS - [x] T-0054 Release the hardened Python/plugin, npm adapter, and native crate through available channels — DONE 2026-10-22: [GitHub v0.7.4](https://github.com/hoohugokim/statutor/releases/tag/v0.7.4), [PyPI 0.7.4](https://pypi.org/project/statutor/0.7.4/), [npm 0.2.0](https://www.npmjs.com/package/statutor/v/0.2.0), and [crate 0.1.2](https://crates.io/crates/statutor/0.1.2) verified; published payloads match release source; clean registry installs and runtime smoke pass; tag CI/publisher successful; local CLI/plugin updated to 0.7.4 (Claude restart required) - [x] T-0055 Reorganize the README around a concrete example, quickstart, and agent setup — DONE 2026-10-22: [PR #3](https://github.com/hoohugokim/statutor/pull/3) merged; README reduced from 245 to 144 lines with compact branding/navigation and four linked reference guides; Antigravity setup corrected; independent editorial review, 15 focused checks, and all PR CI pass; published images/navigation and GitHub file hashes verified +- [x] T-0056 Close 0.7.4 audit holes in kernel, Stop, worker, and Rust receipt optional-key parity (D-0030) — DONE 2026-10-22: relative TargetFile, truncated apply_patch, malformed HEAD policy, MultiEdit/NotebookEdit, run_terminal_cmd matcher, Stop/worker basename, Rust s61; pytest 785 passed / 5 skipped +- [x] T-0057 Add first-class Cursor adapter, kernel mapping, worker harness id, dogfood hooks, and 0.7.5/0.1.3 claim revision (D-0030) — DONE 2026-10-22: adapters/cursor/, .cursor/hooks.json, harness `cursor`, Python/plugins 0.7.5, crate 0.1.3; npm stays 0.2.0; publication remains a human step +- [x] T-0058 Address the flow audit (D-0031): preserve explicit CLI roots, report completed-session retries accurately without changing schema 1, validate check input, fix Cursor Stop/setup, improve help and fresh-setup guidance, and pin Unicode conformance independently of the interpreter — DONE 2026-10-23: worker 86, kernel/Cursor/Stop 340, setup diagnostics 72, and Unicode parity 3 focused tests pass; independent CLI and old-reader compatibility probes pass +- [x] T-0059 Verify the revised 0.7.5 candidate with regression probes, Python 3.15 coverage, the complete artifact gate, and independent review — DONE 2026-10-23: 853 tests with zero skips, seven Rust tests, real npm/crate audits, sdist/wheel builds and installed-wheel smoke pass at 81f9d3f; Standards/Spec pass after restoring absolute Antigravity target scoping; original candidate, shared index, and frozen history preserved diff --git a/adapters/antigravity/plugin.json b/adapters/antigravity/plugin.json index 5a8e6ed..46d88ed 100644 --- a/adapters/antigravity/plugin.json +++ b/adapters/antigravity/plugin.json @@ -1,7 +1,7 @@ { "name": "statutor", "displayName": "Statutor Ledger", - "version": "0.7.4", + "version": "0.7.5", "description": "Typed project-ledger discipline for agentic repos: constitution, state, log, and plan planes enforced by hooks and the git floor for Google Antigravity.", "suggestedPrompts": [ "Initialize a Statutor ledger in this repository", diff --git a/adapters/cursor/README.md b/adapters/cursor/README.md new file mode 100644 index 0000000..eed2b41 --- /dev/null +++ b/adapters/cursor/README.md @@ -0,0 +1,72 @@ +# statutor × Cursor + +Cursor hooks use a version-1 `hooks.json` file and JSON over stdin/stdout. +`statutor hook` auto-detects `hook_event_name` and returns Cursor +`permission` JSON. Claude nested `hookSpecificOutput` still works for +`preToolUse` because Cursor accepts that shape too. + +The kernel first resolves the nearest `.statutor.yaml` marker. Permission +events outside an opted-in ledger return `allow` without policy checks or +messages. Inside a ledger, policy comes from HEAD. +Requires Statutor **0.7.5 or newer** on `PATH`. Check `statutor version` before +enabling the hooks; earlier versions do not support Cursor hooks. + +## Install once + +Install or upgrade the CLI with `pipx install 'statutor>=0.7.5'` or +`pipx upgrade statutor`. + +From your ledger repository, copy [hooks.json](hooks.json) from a clone of +the Statutor repository. Replace the absolute source path below with your own: + +```sh +mkdir -p .cursor +cp /absolute/path/to/statutor/adapters/cursor/hooks.json .cursor/hooks.json +``` + +If `.cursor/hooks.json` already exists, merge the four events instead of +replacing it. Project hooks run from the repository root. This Statutor +repository already dogfoods `.cursor/hooks.json` against +`core/statutor_core.py`, so this checkout works without a global CLI. + +Do not set `failClosed`. Hook crashes and missing CLI must fail open. +Invalid JSON on exit 0 would block Cursor permission events, so the kernel +always emits a permission object on a detected Cursor event. + +The Stop hook reports ledger drift through Cursor's native +[`followup_message`](https://cursor.com/docs/hooks#stop). It requests at most +one follow-up per completion chain; a repeated Stop, an aborted or failed +run, and a clean ledger stay quiet. + +## What the kernel treats as a mutation + +| Cursor event | Canonical | Body | +|---|---|---| +| `preToolUse` `Write` | `write` | `path` / `contents` | +| `preToolUse` `StrReplace` | `edit` | `path`, `old_string`, `new_string` | +| `preToolUse` `Shell` | `bash` | `command` | +| `preToolUse` `Delete` | deny if governed | `path` | +| `preToolUse` `MultiEdit` / `NotebookEdit` | deny-unproved if governed | `path` / `file_path` | +| `beforeShellExecution` | `bash` | top-level `command` | +| `beforeMCPExecution` | mapped tool, else bash if `command` | `tool_input` JSON string | + +`workspace_roots[0]` is the ledger search root when `cwd` is absent. +When `cwd` is absent, an empty workspace list is allowed without policy +checks. Stop stays quiet without a ledger workspace. + +## Worker provenance + +Stable harness id is `cursor`. Automatic hooks prove an attempt only. + +```bash +statutor worker begin --harness cursor +statutor worker complete --session +``` + +`--event mutation` under `cursor` is denied. + +## Gaps the git floor still covers + +- MCP tools whose payload cannot be mapped to write/edit/bash. +- Tab completions (`afterTabFileEdit`) are post-hoc; use `statutor staged`. +- Local Git hooks can be skipped with `--no-verify`. diff --git a/adapters/cursor/hooks.json b/adapters/cursor/hooks.json new file mode 100644 index 0000000..f5a3698 --- /dev/null +++ b/adapters/cursor/hooks.json @@ -0,0 +1,30 @@ +{ + "version": 1, + "hooks": { + "preToolUse": [ + { + "command": "statutor hook", + "matcher": "Write|StrReplace|Shell|Delete|MultiEdit|NotebookEdit|ApplyPatch", + "timeout": 30 + } + ], + "beforeShellExecution": [ + { + "command": "statutor hook", + "timeout": 30 + } + ], + "beforeMCPExecution": [ + { + "command": "statutor hook", + "timeout": 30 + } + ], + "stop": [ + { + "command": "statutor hook --stop", + "timeout": 30 + } + ] + } +} diff --git a/adapters/git/README.md b/adapters/git/README.md index 06bc77e..33d1a3b 100644 --- a/adapters/git/README.md +++ b/adapters/git/README.md @@ -25,7 +25,7 @@ at the statutor repo root): # .pre-commit-config.yaml in your project repos: - repo: https://github.com/hoohugokim/statutor - rev: v0.7.4 + rev: v0.7.5 hooks: [ { id: statutor } ] Fallback: copy ./pre-commit into .git/hooks/. When the `statutor` CLI is diff --git a/adapters/grok/README.md b/adapters/grok/README.md index b96ba67..b4261b3 100644 --- a/adapters/grok/README.md +++ b/adapters/grok/README.md @@ -29,7 +29,7 @@ Or, with no plugin, one user hook file `~/.grok/hooks/statutor.json`: "hooks": { "PreToolUse": [ { - "matcher": "^(Write|Edit|Bash|apply_patch|write|search_replace|hashline_edit|run_terminal_command|StrReplace|Shell)$", + "matcher": "^(Write|Edit|Bash|apply_patch|write|search_replace|hashline_edit|run_terminal_command|run_terminal_cmd|StrReplace|Shell|MultiEdit|NotebookEdit|Delete)$", "hooks": [ { "type": "command", "command": "statutor hook", "timeout": 30 } ] @@ -51,7 +51,7 @@ that same layer, not beside it): ```toml [[hooks.PreToolUse]] -matcher = "^(Write|Edit|Bash|apply_patch|write|search_replace|hashline_edit|run_terminal_command|StrReplace|Shell)$" +matcher = "^(Write|Edit|Bash|apply_patch|write|search_replace|hashline_edit|run_terminal_command|run_terminal_cmd|StrReplace|Shell|MultiEdit|NotebookEdit|Delete)$" hooks = [ { type = "command", command = "statutor hook", timeout = 30 }, ] diff --git a/adapters/opencode/README.md b/adapters/opencode/README.md index 799e619..f879f75 100644 --- a/adapters/opencode/README.md +++ b/adapters/opencode/README.md @@ -6,7 +6,7 @@ the first release with object entrypoints). Both register the same guard on tool execution and shell out to the Python kernel CLI. -1. `pipx install 'statutor>=0.7.4'` — the adapter shells out to the kernel; without the +1. `pipx install 'statutor>=0.7.5'` — the adapter shells out to the kernel; without the CLI on `PATH` the plugin is a no-op. From a source checkout, the developer equivalent is `python -m pip install -e .` at the repository root. The adapter calls `statutor check --if-ledger`: it stays silent unless the diff --git a/core/statutor_core.py b/core/statutor_core.py index 536b9a5..b121d1b 100644 --- a/core/statutor_core.py +++ b/core/statutor_core.py @@ -53,7 +53,7 @@ import sys from typing import NamedTuple -__version__ = "0.7.4" +__version__ = "0.7.5" # -------------------------------------------------------------------------- # policy @@ -352,6 +352,19 @@ def load_worktree_policy(cwd: str) -> dict: return parse_policy(stream.read(), ".statutor.yaml") +def overwrite_bounded_filename(root: str, fallback: str = "HANDOFF.md") -> str: + """Basename of the overwrite_bounded state file, or `fallback`.""" + try: + for rule in load_worktree_policy(root).get("governed", []): + pattern = rule.get("pattern", "") + if (rule.get("policy") == "overwrite_bounded" and pattern + and "*" not in pattern and "/" not in pattern): + return pattern + except Exception: + pass + return fallback + + def find_ledger_root(start: str) -> str | None: """Nearest ancestor carrying Statutor's explicit ledger marker.""" current = os.path.abspath(start) @@ -366,8 +379,7 @@ def find_ledger_root(start: str) -> str | None: current = parent -def _match_rule(rel_path: str, policy: dict) -> dict | None: - rel_path = rel_path.replace(os.sep, "/") +def _match_rule_text(rel_path: str, policy: dict) -> dict | None: base = os.path.basename(rel_path) for rule in policy.get("governed", []): pat = rule.get("pattern", "") @@ -376,13 +388,63 @@ def _match_rule(rel_path: str, policy: dict) -> dict | None: return None +def _stored_rel_path(root: str, rel_path: str) -> str | None: + """Directory-entry spelling of `rel_path` when it names one existing file. + + A case-insensitive volume stores one entry, so `agents.md` and + `AGENTS.md` are that entry. A case-sensitive volume can store both, + and only the entry that is the same file is returned. + """ + absolute = os.path.abspath(os.path.join(root, rel_path)) + if not os.path.exists(absolute): + return None + parent = os.path.dirname(absolute) + try: + names = os.listdir(parent) + except OSError: + return None + matches: list[str] = [] + for name in names: + try: + if os.path.samefile(os.path.join(parent, name), absolute): + matches.append(name) + except OSError: + continue + if len(matches) > 1: + return None + if len(matches) != 1: + return None + stored = matches[0] + parent_rel = os.path.dirname(rel_path) + if parent_rel in ("", "."): + return stored + return parent_rel.replace(os.sep, "/") + "/" + stored + + +def _match_rule(rel_path: str, policy: dict, root: str | None = None) -> dict | None: + rel_path = rel_path.replace(os.sep, "/") + rule = _match_rule_text(rel_path, policy) + if rule is not None or not root: + return rule + stored = _stored_rel_path(root, rel_path) + if stored is None or stored == rel_path: + return None + return _match_rule_text(stored, policy) + + _SHELL_ALIASES = frozenset({ "run_command", "run_terminal_command", "run_terminal_cmd", "shell", }) # Edits whose body is not Claude's Edit shape. An empty old_string on these # names cannot fall through: that path allows a governed edit the kernel # never reconstructed. Claude's own "edit" name keeps the historical behavior. -_PROVED_EDIT_ALIASES = frozenset({"search_replace", "strreplace", "hashline_edit"}) +_PROVED_EDIT_ALIASES = frozenset({ + "search_replace", "strreplace", "hashline_edit", +}) +# MultiEdit and NotebookEdit payloads are not reconstructed. A governed +# path stays denied whether or not old_string, edits, or any other field +# is present; the caller rewrites the file with write. +_WHOLE_FILE_TOOLS = frozenset({"multiedit", "notebookedit"}) def _norm(payload: dict, *, copy_path: bool = False) -> dict: @@ -420,7 +482,10 @@ def _canonicalize(tool: str, payload: dict) -> tuple[str, dict, str]: canonical = "write" elif original in ("replace_file_content", "search_replace", "strreplace"): canonical = "edit" - copy_path = canonical in ("write", "edit") or original == "hashline_edit" + copy_path = ( + canonical in ("write", "edit") + or original in ("hashline_edit", "multiedit", "notebookedit", "delete") + ) normalized = _norm(payload, copy_path=copy_path) if original == "hashline_edit" and normalized.get("old_string"): canonical = "edit" @@ -435,7 +500,7 @@ def _governed_rel( if not file_path: return None _absolute, rel = _resolve_tool_path(file_path, cwd, root) - if _match_rule(rel, policy) is None: + if _match_rule(rel, policy, root) is None: return None return rel @@ -465,6 +530,18 @@ def _physical_line_count(content: str | bytes) -> int: return content.count(newline) + (0 if content.endswith(newline) else 1) +def _utf8_denial(rel: str) -> str: + return (f"{rel} cannot be read as UTF-8, so the edit cannot be proved safe.") + + +def _decode_governed(blob: bytes) -> str | None: + """Return the UTF-8 text, or None when the caller must deny.""" + try: + return blob.decode("utf-8") + except UnicodeDecodeError: + return None + + _TASK_LINE_RE = re.compile(rf"^- \[([ xX])\] (T-([{_DECIMAL_DIGITS}]{{4,}}))\s+(.+)$") @@ -516,7 +593,7 @@ def _guard_batch_edit(payload: dict, cwd: str, policy: dict, root: str) -> str | if rel is None: return None path, _ = _resolve_tool_path(payload["file_path"], cwd, root) - rule = _match_rule(rel, policy) + rule = _match_rule(rel, policy, root) if rule and rule.get("policy") == "frozen": return f"{rel} is frozen (archived plan). Archived records are immutable." unproved = (f"{rel} batch edit cannot be proved safe. Supply exact, disjoint " @@ -573,6 +650,12 @@ def validate( tool, payload, original = _canonicalize(tool, payload) if tool == "multi_replace_file_content": return _guard_batch_edit(payload, cwd, policy, root) + if original in _WHOLE_FILE_TOOLS: + rel = _governed_rel(payload, cwd, policy, root) + if rel is None: + return None + return (f"{rel} {original} cannot be proved safe. " + "Use write with the complete file.") if original in _PROVED_EDIT_ALIASES and not payload.get("old_string"): rel = _governed_rel(payload, cwd, policy, root) if rel is not None: @@ -580,6 +663,12 @@ def validate( "old_string. Retry with the existing text in old_string, " "or use write with the full file.") return None + if original == "delete": + rel = _governed_rel(payload, cwd, policy, root) + if rel is not None: + return (f"{rel} is governed: delete is denied. Records are " + "superseded, never removed.") + return None if tool == "bash": return guard_bash(payload.get("command", ""), policy) @@ -592,7 +681,7 @@ def validate( if not file_path: return None absolute_path, rel = _resolve_tool_path(file_path, cwd, root) - rule = _match_rule(rel, policy) + rule = _match_rule(rel, policy, root) if rule is None: return None kind = rule.get("policy", "") @@ -609,9 +698,14 @@ def validate( if tool == "write": if payload.get("append"): try: - existing = open(absolute_path, encoding="utf-8", newline="").read() + with open(absolute_path, "rb") as handle: + blob = handle.read() except OSError: existing = "" + else: + existing = _decode_governed(blob) + if existing is None: + return _utf8_denial(rel) candidate = existing + payload.get("content", "") else: candidate = payload.get("content", "") @@ -620,9 +714,14 @@ def validate( new = payload.get("new_string", "") if old: try: - existing = open(absolute_path, encoding="utf-8", newline="").read() + with open(absolute_path, "rb") as handle: + blob = handle.read() except OSError: existing = None + else: + existing = _decode_governed(blob) + if existing is None: + return _utf8_denial(rel) if existing is not None and old in existing: count = -1 if payload.get("replace_all", False) else 1 candidate = existing.replace(old, new, count) @@ -634,11 +733,16 @@ def validate( if kind == "state": candidate: str | None = None try: - existing = open(absolute_path, encoding="utf-8", newline="").read() + with open(absolute_path, "rb") as handle: + blob = handle.read() except FileNotFoundError: existing = "" except OSError: existing = None + else: + existing = _decode_governed(blob) + if existing is None: + return _utf8_denial(rel) if tool == "write": if payload.get("append") and existing is not None: candidate = existing + payload.get("content", "") @@ -665,10 +769,14 @@ def validate( elif tool == "write": if not payload.get("append"): try: - existing = open(absolute_path, encoding="utf-8", newline="").read() + with open(absolute_path, "rb") as handle: + existing_bytes = handle.read() except FileNotFoundError: - existing = "" - if existing.strip() and existing.strip() not in payload.get("content", ""): + existing_bytes = b"" + if _decode_governed(existing_bytes) is None: + return _utf8_denial(rel) + content = payload.get("content", "") + if not _is_pure_line_insertion(existing_bytes, content.encode("utf-8")): return (f"{rel} is append-only. A full rewrite must contain the " "existing content verbatim; records are never modified or deleted.") return None @@ -810,6 +918,22 @@ def _resolve_patch_path( return _resolve_tool_path(path, cwd, policy_root) +def _apply_update_text(existing: str, minus: list[str], plus: list[str]) -> str: + """Apply an update's removed and added lines to the on-disk body.""" + lines = existing.splitlines(keepends=True) + for raw in minus: + key = raw[1:].rstrip("\r\n") + for index, line in enumerate(lines): + if line.rstrip("\r\n") == key: + del lines[index] + break + added = [raw[1:].rstrip("\r\n") + "\n" for raw in plus] + text = "".join(lines) + if text and not text.endswith("\n") and added: + text += "\n" + return text + "".join(added) + + def _size_reason(rel: str, kind: str, rule: dict, content: str) -> str | None: """Cap/sections denial for a fully-known body (write tool and Add File).""" n = _physical_line_count(content) @@ -858,10 +982,11 @@ def guard_apply_patch( text = payload.get("command", payload.get("patch", "")) if not isinstance(text, str) or "*** Begin Patch" not in text: return None + match_root = os.path.abspath(policy_root or cwd) for t in _patch_targets(text): absolute_path, rel = _resolve_patch_path(t["path"], cwd, policy_root) - rule = _match_rule(rel, policy) + rule = _match_rule(rel, policy, match_root) kind = rule.get("policy", "") if rule else "" if t["op"] == "delete": @@ -879,7 +1004,7 @@ def guard_apply_patch( "the archive is denied.") if (move_rel is not None and kind in ("constitution", "overwrite_bounded", "append_only", "state") - and _match_rule(move_rel, policy) is not rule): + and _match_rule(move_rel, policy, match_root) is not rule): return (f"{rel} is governed ({kind}): moving it to ungoverned path " f"{move_rel} is denied. Keep it under the same policy rule.") @@ -925,15 +1050,36 @@ def guard_apply_patch( if line[1:].startswith("- [") and not _TASK_LINE_RE.fullmatch(line[1:]): return (f"{rel}: added state task line must use " "`- [ ] T-NNNN detail` or `- [x] T-NNNN detail`.") + try: + with open(absolute_path, "rb") as handle: + blob = handle.read() + except FileNotFoundError: + existing = "" + except OSError: + return f"{rel}: state file cannot be read; refusing the update." + else: + existing = _decode_governed(blob) + if existing is None: + return (f"{rel}: state file cannot be read as UTF-8; " + "refusing the update.") + candidate = _apply_update_text(existing, t["minus"], t["plus"]) + reason = _state_reason(rel, candidate, existing) + if reason: + return reason continue if kind in ("constitution", "overwrite_bounded") and (adds or dels): cap_key = "hard_max_lines" if kind == "constitution" else "max_lines" cap = int(rule.get(cap_key, 200)) try: - cur_n = _physical_line_count( - open(absolute_path, encoding="utf-8", newline="").read()) + with open(absolute_path, "rb") as handle: + blob = handle.read() except OSError: cur_n = None # unreadable/unmapped path: let the floor judge + else: + text = _decode_governed(blob) + if text is None: + return _utf8_denial(rel) + cur_n = _physical_line_count(text) if cur_n is not None and cur_n + adds - dels > cap: est = cur_n + adds - dels return (f"{rel} would grow to ~{est} lines (cap {cap}).") @@ -979,9 +1125,11 @@ def _truncation_reason( ) -> str | None: """Deny when a cut body would hide a governed mutation or a shell write.""" canonical, normalized, _original = _canonicalize(tool, payload) - if canonical == "bash": + if canonical in ("bash", "apply_patch"): return ("tool input was truncated; a shell command inside a ledger " - "cannot be proved safe.") + "cannot be proved safe." if canonical == "bash" else + "tool input was truncated; an apply_patch envelope inside a " + "ledger cannot be proved safe.") if canonical not in ("write", "edit", "hashline_edit"): return None rel = _governed_rel(normalized, cwd, policy, root) @@ -998,7 +1146,10 @@ def _automatic_reason( root = find_ledger_root(cwd) if root is None: return None - policy = load_policy(root) + try: + policy = load_policy(root) + except _PolicyFailure as exc: + return f"committed policy invalid: {exc}" if truncated: reason = _truncation_reason(tool, payload, cwd, root, policy) else: @@ -1017,7 +1168,7 @@ def _stop_reason_is_session_end(event: dict) -> bool: return isinstance(reason, str) and reason != "end_turn" -def _run_stop_event(event: dict, is_antigravity: bool) -> int: +def _run_stop_event(event: dict, is_antigravity: bool, *, is_cursor: bool = False) -> int: try: if _stop_reason_is_session_end(event): return 0 @@ -1046,25 +1197,17 @@ def _run_stop_event(event: dict, is_antigravity: bool) -> int: statutor_doctor.check(project_dir) findings = [f"WARN {w}" for w in statutor_doctor.warnings] + [f"ERROR {e}" for e in statutor_doctor.errors] - state_filename = "HANDOFF.md" - try: - for rule in load_worktree_policy(project_dir).get("governed", []): - pattern = rule.get("pattern", "") - if (rule.get("policy") == "overwrite_bounded" and pattern - and "*" not in pattern and "/" not in pattern): - state_filename = pattern - break - except Exception: - pass + state_filename = overwrite_bounded_filename(project_dir) - sentinel_prefix = f"WARN {state_filename} last verified" + sentinel_prefixes = (f"WARN {state_filename} last verified", + f"WARN {state_filename} is not yet verified") handoff_path = os.path.join(project_dir, state_filename) - if os.path.isfile(handoff_path) and len(findings) == 1 and findings[0].startswith(sentinel_prefix): + if os.path.isfile(handoff_path) and len(findings) == 1 and findings[0].startswith(sentinel_prefixes): try: handoff_text = open(handoff_path, encoding="utf-8").read() except Exception: handoff_text = "" - if "last_verified: 1970-01-01" in handoff_text: + if re.search(r"(?m)^last_verified:\s*1970-01-01(?:\s|$)", handoff_text): findings = [] if not findings: @@ -1073,7 +1216,11 @@ def _run_stop_event(event: dict, is_antigravity: bool) -> int: return 0 report = "\n".join(findings) - if is_antigravity: + if is_cursor: + print(json.dumps({ + "followup_message": f"statutor-doctor found drift in the ledger:\n{report}", + })) + elif is_antigravity: print(json.dumps({ "decision": "continue", "reason": f"statutor-doctor found drift in the ledger:\n{report}", @@ -1095,6 +1242,82 @@ def _run_stop_event(event: dict, is_antigravity: bool) -> int: return 0 +_CURSOR_EVENTS = frozenset({ + "preToolUse", "beforeShellExecution", "beforeMCPExecution", "stop", +}) + + +def _is_cursor(event: dict) -> bool: + return event.get("hook_event_name") in _CURSOR_EVENTS + + +def _cursor_permission(decision: str, reason: str | None = None) -> int: + payload: dict = {"permission": decision} + if reason: + message = f"[statutor] {reason}" + payload["user_message"] = message + payload["agent_message"] = message + print(json.dumps(payload)) + return 0 + + +def _cursor_mcp_payload(event: dict) -> tuple[str, dict]: + tool = str(event.get("tool_name") or "") + if tool.startswith("MCP:"): + tool = tool[4:] + raw = event.get("tool_input", {}) + if isinstance(raw, str): + try: + payload = json.loads(raw) if raw.strip() else {} + except Exception: + payload = {} + elif isinstance(raw, dict): + payload = raw + else: + payload = {} + if not isinstance(payload, dict): + payload = {} + return tool, payload + + +def _run_cursor_event(event: dict, stop_mode: bool) -> int: + """Cursor hooks.json protocol: permission JSON, fail-open as allow.""" + try: + roots = event.get("workspace_roots") or [] + workspace = roots[0] if isinstance(roots, list) and roots else None + cwd = event.get("cwd") if isinstance(event.get("cwd"), str) else None + cwd = cwd or workspace + name = event.get("hook_event_name") + if stop_mode or name == "stop": + if event.get("status") in ("aborted", "error"): + return 0 + if not cwd or event.get("loop_count", 0) != 0: + return 0 + return _run_stop_event({**event, "cwd": cwd}, False, is_cursor=True) + if not cwd: + return _cursor_permission("allow") + if name == "beforeShellExecution": + reason = _automatic_reason( + "bash", {"command": event.get("command", "")}, cwd) + elif name == "beforeMCPExecution": + tool, payload = _cursor_mcp_payload(event) + reason = _automatic_reason(tool, payload, cwd) + if reason is None and payload.get("command"): + reason = _automatic_reason("bash", payload, cwd) + else: + tool, payload = _event_tool(event) + reason = _automatic_reason( + tool, payload, cwd, truncated=_truncated_input(event)) + if reason: + return _cursor_permission("deny", reason) + return _cursor_permission("allow") + except Exception: + try: + return _cursor_permission("allow") + except Exception: + return 0 + + def run_hook(argv: list[str] | None = None) -> int: argv = argv or [] stop_mode = "--stop" in argv @@ -1107,6 +1330,7 @@ def run_hook(argv: list[str] | None = None) -> int: "run `statutor --help` for modes.", file=sys.stderr) return 64 is_antigravity = force_antigravity + raw = "" try: raw = sys.stdin.read() if not raw.strip(): @@ -1115,8 +1339,17 @@ def run_hook(argv: list[str] | None = None) -> int: if not isinstance(event, dict): return 0 except Exception: + # Cursor permission hooks fail-closed on exit 0 plus invalid JSON. + if "hook_event_name" in raw: + try: + return _cursor_permission("allow") + except Exception: + return 0 return 0 # fail open + if _is_cursor(event): + return _run_cursor_event(event, stop_mode) + if "toolCall" in event or "workspacePaths" in event or "executionNum" in event or "terminationReason" in event: is_antigravity = True @@ -1129,9 +1362,12 @@ def run_hook(argv: list[str] | None = None) -> int: raw_tool = tool_call.get("name", "") raw_args = tool_call.get("args", {}) or {} workspace_paths = event.get("workspacePaths", []) + workspace = workspace_paths[0] if workspace_paths else None target_file = raw_args.get("TargetFile") - file_dir = os.path.dirname(os.path.abspath(target_file)) if target_file else None - cwd = raw_args.get("Cwd") or file_dir or event.get("cwd") or (workspace_paths[0] if workspace_paths else None) + target_dir = (os.path.dirname(target_file) + if isinstance(target_file, str) and os.path.isabs(target_file) + else None) + cwd = raw_args.get("Cwd") or event.get("cwd") or workspace or target_dir if not cwd: print(json.dumps({"decision": "allow"})) return 0 @@ -1187,13 +1423,26 @@ def run_hook(argv: list[str] | None = None) -> int: # -------------------------------------------------------------------------- def run_check(argv: list[str]) -> int: + usage = "usage: statutor check [--if-ledger] TOOL JSON [CWD]" if_ledger = bool(argv and argv[0] == "--if-ledger") if if_ledger: argv = argv[1:] - if len(argv) < 2: - print("usage: statutor check [--if-ledger] TOOL JSON [CWD]", file=sys.stderr) + if argv in (["--help"], ["-h"]): + print(usage) + return 0 + if len(argv) not in (2, 3): + print(usage, file=sys.stderr) + return 64 + try: + payload = json.loads(argv[1]) + except json.JSONDecodeError as exc: + print(f"statutor check: expected a JSON object; {exc.msg} " + f"(line {exc.lineno}, column {exc.colno}).", file=sys.stderr) return 64 - tool, payload = argv[0], json.loads(argv[1]) + if not isinstance(payload, dict): + print("statutor check: expected a JSON object.", file=sys.stderr) + return 64 + tool = argv[0] cwd = argv[2] if len(argv) > 2 else os.getcwd() try: if if_ledger: @@ -1499,8 +1748,8 @@ def _policy_violations(cwd: str, # Pass 1: record lifecycle and frozen-path transitions. for status, old, new in changes: code = status[0] - old_rule = _match_rule(old, policy) if old is not None else None - new_rule = _match_rule(new, policy) if new is not None else None + old_rule = _match_rule(old, policy, cwd) if old is not None else None + new_rule = _match_rule(new, policy, cwd) if new is not None else None old_kind = old_rule.get("policy", "") if old_rule else "" new_kind = new_rule.get("policy", "") if new_rule else "" @@ -1528,14 +1777,14 @@ def _policy_violations(cwd: str, for status, old, path in changes: if path is None: continue - rule = _match_rule(path, policy) + rule = _match_rule(path, policy, cwd) if not rule: continue kind = rule.get("policy", "") code = status[0] if kind == "append_only": baseline = b"" - old_rule = _match_rule(old, policy) if old is not None else None + old_rule = _match_rule(old, policy, cwd) if old is not None else None if (code in ("M", "T") or (code == "R" and old_rule is rule)): baseline = _git_bytes(cwd, "show", f"HEAD:{old}") candidate = _git_bytes(cwd, "show", f":{path}") @@ -1559,7 +1808,7 @@ def _policy_violations(cwd: str, violations.append(f"{path}: state content must be valid UTF-8 text.") continue baseline: str | None = None - old_rule = _match_rule(old, policy) if old is not None else None + old_rule = _match_rule(old, policy, cwd) if old is not None else None if (code in ("M", "T") or (code == "R" and old_rule is rule)): try: baseline = _git_bytes(cwd, "show", f"HEAD:{old}").decode("utf-8") @@ -1600,6 +1849,10 @@ def run_staged(cwd: str) -> int: def run_trust_approve(argv: list[str]) -> int: """Create the exact-tree local authorization receipt from D-0015.""" + if argv in (["--help"], ["-h"]): + print("usage: statutor trust approve --decision D-NNNN --reason TEXT " + "[--confirm-tree OID] [CWD]") + return 0 cwd = os.getcwd() decision = None reason = None @@ -2004,6 +2257,12 @@ def main() -> None: if mode == "check": sys.exit(run_check(argv[1:])) if mode in ("staged", "--staged"): + if argv[1:] in (["--help"], ["-h"]): + print("usage: statutor staged [CWD]") + sys.exit(0) + if len(argv) > 2: + print("usage: statutor staged [CWD]", file=sys.stderr) + sys.exit(64) sys.exit(run_staged(argv[1] if len(argv) > 1 else os.getcwd())) if mode == "trust" and len(argv) > 1 and argv[1] == "approve": sys.exit(run_trust_approve(argv[2:])) @@ -2018,7 +2277,8 @@ def main() -> None: if mode == "worker": import statutor_worker sys.exit(statutor_worker.worker_cli(argv[1:])) - print(__doc__) + print(f"unknown command: {mode}; run `statutor --help` for commands.", + file=sys.stderr) sys.exit(64) diff --git a/core/statutor_doctor.py b/core/statutor_doctor.py index 697505f..92e8161 100644 --- a/core/statutor_doctor.py +++ b/core/statutor_doctor.py @@ -66,6 +66,16 @@ def _rule_filename(rule: dict | None, default: str) -> str: return default +def _read_text(path: str, label: str) -> str | None: + """Read one governed file. An undecodable body is an error, not a crash.""" + try: + with open(path, encoding="utf-8", newline="") as handle: + return handle.read() + except UnicodeDecodeError: + errors.append(f"{label} cannot be read as UTF-8.") + return None + + def check(root: str) -> None: errors.clear() warnings.clear() @@ -106,65 +116,74 @@ def p(name: str) -> str: errors.append(f"missing governed file: {name} (run `statutor init .`)") if os.path.isfile(p(agents_filename)): - n = sum(1 for _ in open(p(agents_filename), encoding="utf-8")) - if n > soft_agents_lines: - warnings.append( - f"{agents_filename} is {n} lines (soft budget {soft_agents_lines}): " - "trim derivable content, move procedures to skills." - ) + agents_text = _read_text(p(agents_filename), agents_filename) + if agents_text is not None: + n = len(agents_text.splitlines()) + if n > soft_agents_lines: + warnings.append( + f"{agents_filename} is {n} lines (soft budget {soft_agents_lines}): " + "trim derivable content, move procedures to skills." + ) if os.path.isfile(p(handoff_filename)): - text = open(p(handoff_filename), encoding="utf-8").read() - m = re.search(r"last_verified:\s*(\d{4}-\d{2}-\d{2})", text) - if not m: - errors.append(f"{handoff_filename} has no `last_verified: YYYY-MM-DD` stamp.") - else: - stamp = m.group(1) - try: - verified = datetime.strptime(stamp, "%Y-%m-%d").date() - except ValueError: - errors.append(f"{handoff_filename} has invalid last_verified date {stamp}.") - verified = None - if verified is not None and verified > date.today(): - errors.append(f"{handoff_filename} last_verified date {stamp} is in the future.") - elif verified is not None and (date.today() - verified).days > handoff_stale_days: - age = (date.today() - verified).days - warnings.append( - f"{handoff_filename} last verified {age} days ago — re-verify or rewrite." + text = _read_text(p(handoff_filename), handoff_filename) + if text is not None: + m = re.search(r"last_verified:\s*(\d{4}-\d{2}-\d{2})", text) + if not m: + errors.append(f"{handoff_filename} has no `last_verified: YYYY-MM-DD` stamp.") + else: + stamp = m.group(1) + try: + verified = datetime.strptime(stamp, "%Y-%m-%d").date() + except ValueError: + errors.append(f"{handoff_filename} has invalid last_verified date {stamp}.") + verified = None + if verified is not None and verified > date.today(): + errors.append(f"{handoff_filename} last_verified date {stamp} is in the future.") + elif verified is not None and stamp == "1970-01-01": + warnings.append( + f"{handoff_filename} is not yet verified — run project checks, " + "then replace last_verified with the verification date." + ) + elif verified is not None and (date.today() - verified).days > handoff_stale_days: + age = (date.today() - verified).days + warnings.append( + f"{handoff_filename} last verified {age} days ago — re-verify or rewrite." + ) + + required_sections = overwrite_rule.get("required_sections", []) if overwrite_rule else [] + missing_sections = [s for s in required_sections if s not in text] + if missing_sections: + errors.append( + f"{handoff_filename} is missing required sections: " + f"{', '.join(missing_sections)} — a file on disk without these " + "bypassed the hook/floor (that's drift)." ) - required_sections = overwrite_rule.get("required_sections", []) if overwrite_rule else [] - missing_sections = [s for s in required_sections if s not in text] - if missing_sections: - errors.append( - f"{handoff_filename} is missing required sections: " - f"{', '.join(missing_sections)} — a file on disk without these " - "bypassed the hook/floor (that's drift)." - ) - - fields = statutor_worker.parse_handoff_fields(text) - if all(fields[name] is None - for name in statutor_worker.ATTRIBUTION_FIELDS): - warnings.append( - f"{handoff_filename} has no v0.5 worker attribution block " - "(last_worker/last_machine/handoff_id/supersedes) — pre-v0.5 " - "ledger, still valid; add it on the next rewrite and record " - "completion with `statutor worker complete --session `." - ) - else: - for problem in statutor_worker.validate_handoff_metadata(text): - errors.append(f"{handoff_filename}: {problem}") + fields = statutor_worker.parse_handoff_fields(text) + if all(fields[name] is None + for name in statutor_worker.ATTRIBUTION_FIELDS): + warnings.append( + f"{handoff_filename} has no v0.5 worker attribution block " + "(last_worker/last_machine/handoff_id/supersedes) — pre-v0.5 " + "ledger, still valid; add it on the next rewrite and record " + "completion with `statutor worker complete --session `." + ) + else: + for problem in statutor_worker.validate_handoff_metadata(text): + errors.append(f"{handoff_filename}: {problem}") done_ids: set[str] = set() if os.path.isfile(p(tasks_filename)): - state_body = open(p(tasks_filename), encoding="utf-8").read() - state_error = statutor_core._state_reason(tasks_filename, state_body) - if state_error: - errors.append(state_error) - for line in state_body.splitlines(): - m = re.match(r"- \[x\]\s+(\S+)", line, re.IGNORECASE) - if m: - done_ids.add(m.group(1)) + state_body = _read_text(p(tasks_filename), tasks_filename) + if state_body is not None: + state_error = statutor_core._state_reason(tasks_filename, state_body) + if state_error: + errors.append(state_error) + for line in state_body.splitlines(): + m = re.match(r"- \[x\]\s+(\S+)", line, re.IGNORECASE) + if m: + done_ids.add(m.group(1)) plans_dir = p("plans") if os.path.isdir(plans_dir): @@ -172,7 +191,9 @@ def p(name: str) -> str: fpath = os.path.join(plans_dir, fname) if not fname.endswith(".md") or not os.path.isfile(fpath): continue - body = open(fpath, encoding="utf-8").read() + body = _read_text(fpath, f"plans/{fname}") + if body is None: + continue hit = [t for t in done_ids if t in body] if hit: warnings.append( @@ -181,14 +202,15 @@ def p(name: str) -> str: ) if os.path.isfile(p(decisions_filename)): - body = open(p(decisions_filename), encoding="utf-8").read() - records = re.findall(r"^## D-\d+", body, re.MULTILINE) - statuses = re.findall(r"^\*\*Status:\*\*", body, re.MULTILINE) - if len(statuses) < len(records): - warnings.append( - f"{decisions_filename}: {len(records)} records but only {len(statuses)} " - "Status fields — every record needs one." - ) + body = _read_text(p(decisions_filename), decisions_filename) + if body is not None: + records = re.findall(r"^## D-\d+", body, re.MULTILINE) + statuses = re.findall(r"^\*\*Status:\*\*", body, re.MULTILINE) + if len(statuses) < len(records): + warnings.append( + f"{decisions_filename}: {len(records)} records but only {len(statuses)} " + "Status fields — every record needs one." + ) def main() -> None: diff --git a/core/statutor_global_cli.py b/core/statutor_global_cli.py index edbc9f8..672c7c3 100644 --- a/core/statutor_global_cli.py +++ b/core/statutor_global_cli.py @@ -694,7 +694,10 @@ def main(argv: list[str] | None = None) -> int: if argv and argv[0] == "skill": import statutor_skills return statutor_skills.main(argv[1:]) - parser = argparse.ArgumentParser(prog="statutor global") + parser = argparse.ArgumentParser( + prog="statutor global", + epilog="Manage reusable skills with: statutor global skill --help", + ) subparsers = parser.add_subparsers(dest="command", required=True) for name in ("init", "plan", "apply", "status", "doctor", "uninstall"): child = subparsers.add_parser(name) diff --git a/core/statutor_global_status.py b/core/statutor_global_status.py index e88111a..1955592 100644 --- a/core/statutor_global_status.py +++ b/core/statutor_global_status.py @@ -133,16 +133,39 @@ def finish_entry() -> None: return limit, disabled +def _document_missing(path: Path) -> bool: + try: + path.lstat() + except FileNotFoundError: + return True + except OSError: + return False + return False + + def _load_documents( roots: substrate.ResolvedRoots, diagnostics: list[dict[str, object]], ) -> tuple[dict[str, object] | None, dict[str, object] | None]: config = None state = None - for label, path, validator in ( + documents = ( ("config", lifecycle._config_path(roots), substrate.validate_config), ("state", lifecycle._state_path(roots), substrate.validate_state), - ): + ) + missing = {label for label, path, _ in documents if _document_missing(path)} + if len(missing) == len(documents): + _diagnostic( + diagnostics, "error", "global-not-initialized", + "global layer is not initialized; run `statutor global init`") + return None, None + for label, path, validator in documents: + if label in missing: + _diagnostic( + diagnostics, "error", f"global-{label}-missing", + f"global {label} is missing; run `statutor global init`", + path=path) + continue try: value = validator(substrate.load_json(path)) except substrate.GlobalError as error: diff --git a/core/statutor_worker.py b/core/statutor_worker.py index 415f9af..523a6a8 100644 --- a/core/statutor_worker.py +++ b/core/statutor_worker.py @@ -30,7 +30,7 @@ import statutor_global as substrate SCHEMA_VERSION = 1 -HARNESSES = ("claude", "codex", "opencode", "antigravity", "gemini", "grok", "custom", "human", "unknown") +HARNESSES = ("claude", "codex", "opencode", "antigravity", "gemini", "grok", "cursor", "custom", "human", "unknown") ROLES = ("primary", "subagent", "unknown") EVENTS = ("activity", "attempt", "mutation") BASES = ("completed", "mutation", "activity", "attempt") @@ -114,6 +114,20 @@ "matcher. Subagent PreToolUse is unproved; the 1.0.62 probe " "saw no child session.", }, + "cursor": { + "verified_against": "Cursor hooks.json schema version 1", + "attempt_surface": "preToolUse / beforeShellExecution / beforeMCPExecution", + "proves": ["activity", "attempt"], + "proves_mutation": False, + "proves_completion": False, + "role_signal": False, + "session_correlation": "host conversation_id when exposed, else generated", + "note": "Permission hooks always emit Cursor permission JSON, " + "including fail-open allow. Stop surfaces drift only; " + "completion is executor-run `worker complete`. Tab " + "completions and unmapped MCP payloads stay with the " + "git floor.", + }, "custom": { "verified_against": "n/a (caller-proved)", "attempt_surface": "`worker record` CLI ingress", @@ -437,13 +451,21 @@ def parse_handoff_fields(text: str) -> dict[str, str | None]: return fields +def _handoff_filename(ledger_root: str | None) -> str: + if ledger_root is None: + return "HANDOFF.md" + import statutor_core + return statutor_core.overwrite_bounded_filename(ledger_root) + + def _read_handoff_text(ledger_root: str | None, cwd: str, ref: str | None = None) -> tuple[str | None, str | None]: """Return (digest, text) for the worktree file or a git ref blob.""" + name = _handoff_filename(ledger_root) if ref is None: if ledger_root is None: return None, None - path = Path(ledger_root) / "HANDOFF.md" + path = Path(ledger_root) / name try: content = path.read_bytes() except OSError: @@ -453,10 +475,10 @@ def _read_handoff_text(ledger_root: str | None, cwd: str, return digest, content.decode("utf-8") except UnicodeDecodeError: return digest, None - relative = "HANDOFF.md" + relative = name if ledger_root is not None: try: - relative = os.path.relpath(os.path.join(ledger_root, "HANDOFF.md"), + relative = os.path.relpath(os.path.join(ledger_root, name), _resolve_worktree(cwd)).replace(os.sep, "/") except ValueError: return None, None @@ -995,20 +1017,18 @@ def worker_complete(state_root: Path, cwd: str, *, project_id, derivation, display = _resolve_project(cwd) wt_root = _resolve_worktree(cwd) wt_id = _worktree_id(wt_root) - current_digest, current_handoff = read_handoff(ledger, cwd) + current_digest, handoff_text = _read_handoff_text(ledger, cwd) + name = _handoff_filename(ledger) if current_digest is None: - raise WorkerError("completion requires a HANDOFF.md in the ledger") - current_id = current_handoff if current_handoff else "none" - ledger_path = Path(ledger) / "HANDOFF.md" - try: - handoff_text = ledger_path.read_text(encoding="utf-8") - except OSError as exc: - raise WorkerError(f"cannot read HANDOFF.md: {exc}") from exc + raise WorkerError(f"completion requires a {name} in the ledger") + if handoff_text is None: + raise WorkerError(f"cannot read {name} as UTF-8") shape_problems = validate_handoff_metadata(handoff_text) if shape_problems: raise WorkerError("HANDOFF attribution block is malformed: " + "; ".join(shape_problems)) handoff_fields = parse_handoff_fields(handoff_text) + current_id = handoff_fields.get("handoff_id") or "none" with _ProjectLock(_project_dir(state_root, project_id)): registry, expected = _load_or_init(state_root, project_id, derivation, display) @@ -1023,6 +1043,11 @@ def worker_complete(state_root: Path, cwd: str, *, prior = completed_by_ledger.get(ledger) prior_id = str(prior.get("handoff_id", "none")) if isinstance( prior, dict) else "none" + if session["status"] == "completed": + raise WorkerError( + "session already completed; inspect the local completion with " + "`statutor worker show --basis completed`. Begin a new session " + "before completing further work") supersedes = handoff_fields.get("supersedes") names = {part.strip() for part in (supersedes or "").split(",") if part.strip()} if supersedes else set() @@ -1192,18 +1217,20 @@ def _emit(data: object, json_output: bool) -> None: print(json.dumps(data, sort_keys=True)) +def _root_arguments(parser, *, child: bool = False) -> None: + import argparse + for option in ("--home", "--config-root", "--state-root"): + parser.add_argument(option, default=argparse.SUPPRESS if child else None) + + def machine_cli(argv: list[str]) -> int: import argparse parser = argparse.ArgumentParser(prog="statutor machine") - parser.add_argument("--home") - parser.add_argument("--config-root") - parser.add_argument("--state-root") + _root_arguments(parser) sub = parser.add_subparsers(dest="command", required=True) for name in ("show", "set-label", "rotate"): child = sub.add_parser(name) - child.add_argument("--home") - child.add_argument("--config-root") - child.add_argument("--state-root") + _root_arguments(child, child=True) child.add_argument("--json", action="store_true") if name == "set-label": child.add_argument("label") @@ -1244,14 +1271,10 @@ def worker_cli(argv: list[str]) -> int: # plan's "explicit confirmation" before rotation. import argparse parser = argparse.ArgumentParser(prog="statutor worker") - parser.add_argument("--home") - parser.add_argument("--config-root") - parser.add_argument("--state-root") + _root_arguments(parser) sub = parser.add_subparsers(dest="command", required=True) begin = sub.add_parser("begin") - begin.add_argument("--home") - begin.add_argument("--config-root") - begin.add_argument("--state-root") + _root_arguments(begin, child=True) begin.add_argument("--harness", required=True, choices=HARNESSES) begin.add_argument("--role", default="unknown", choices=ROLES) begin.add_argument("--origin-harness", default="unknown", @@ -1260,24 +1283,18 @@ def worker_cli(argv: list[str]) -> int: begin.add_argument("--cwd") begin.add_argument("--json", action="store_true") show = sub.add_parser("show") - show.add_argument("--home") - show.add_argument("--config-root") - show.add_argument("--state-root") + _root_arguments(show, child=True) show.add_argument("--basis", default="completed", choices=BASES) show.add_argument("--worktree", action="store_true") show.add_argument("--cwd") show.add_argument("--json", action="store_true") active = sub.add_parser("active") - active.add_argument("--home") - active.add_argument("--config-root") - active.add_argument("--state-root") + _root_arguments(active, child=True) active.add_argument("--worktree", action="store_true") active.add_argument("--cwd") active.add_argument("--json", action="store_true") record = sub.add_parser("record") - record.add_argument("--home") - record.add_argument("--config-root") - record.add_argument("--state-root") + _root_arguments(record, child=True) record.add_argument("--harness", required=True, choices=HARNESSES) record.add_argument("--event", required=True, choices=EVENTS) record.add_argument("--role", default="unknown", choices=ROLES) @@ -1287,27 +1304,22 @@ def worker_cli(argv: list[str]) -> int: record.add_argument("--cwd") record.add_argument("--json", action="store_true") complete = sub.add_parser("complete") - complete.add_argument("--home") - complete.add_argument("--config-root") - complete.add_argument("--state-root") + _root_arguments(complete, child=True) complete.add_argument("--session", required=True) complete.add_argument("--cwd") complete.add_argument("--json", action="store_true") compare = sub.add_parser("compare") - compare.add_argument("--home") - compare.add_argument("--config-root") - compare.add_argument("--state-root") + _root_arguments(compare, child=True) compare.add_argument("ref") compare.add_argument("--cwd") compare.add_argument("--json", action="store_true") capabilities = sub.add_parser("capabilities") - capabilities.add_argument("--home") - capabilities.add_argument("--config-root") - capabilities.add_argument("--state-root") + _root_arguments(capabilities, child=True) capabilities.add_argument("--json", action="store_true") new_id = sub.add_parser( "new-id", help="mint a fresh random handoff id for a HANDOFF rewrite") + _root_arguments(new_id, child=True) new_id.add_argument("--json", action="store_true") args = parser.parse_args(argv) roots = _roots(args) diff --git a/crates/statutor/Cargo.lock b/crates/statutor/Cargo.lock index bc8a121..919fa69 100644 --- a/crates/statutor/Cargo.lock +++ b/crates/statutor/Cargo.lock @@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "statutor" -version = "0.1.2" +version = "0.1.3" dependencies = [ "yaml-rust2", ] diff --git a/crates/statutor/Cargo.toml b/crates/statutor/Cargo.toml index 0107e41..2691d4d 100644 --- a/crates/statutor/Cargo.toml +++ b/crates/statutor/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "statutor" -version = "0.1.2" +version = "0.1.3" edition = "2021" rust-version = "1.75" license = "MIT" diff --git a/crates/statutor/src/lib.rs b/crates/statutor/src/lib.rs index dabcd7e..b499f61 100644 --- a/crates/statutor/src/lib.rs +++ b/crates/statutor/src/lib.rs @@ -453,13 +453,92 @@ fn parse_policy(text: &str) -> Result { /// First rule whose pattern matches the rel path or its basename — /// statutor_core._match_rule semantics, including backslash normalization. -pub fn match_rule<'a>(rel_path: &str, policy: &'a Policy) -> Option<&'a Rule> { +/// +/// When `root` is set, a case-variant path matches only if it is the same +/// directory entry as a spelling the pattern already accepts. Patterns +/// themselves stay case-sensitive. +pub fn match_rule<'a>( + rel_path: &str, + policy: &'a Policy, + root: Option<&Path>, +) -> Option<&'a Rule> { let rel = rel_path.replace(std::path::MAIN_SEPARATOR, "/"); + if let Some(rule) = match_rule_text(&rel, policy) { + return Some(rule); + } + let root = root?; + let stored = stored_rel_path(root, &rel)?; + if stored == rel { + return None; + } + match_rule_text(&stored, policy) +} + +fn match_rule_text<'a>(rel: &str, policy: &'a Policy) -> Option<&'a Rule> { let base = rel.rsplit('/').next().unwrap_or(""); policy .governed .iter() - .find(|r| fnmatch(&r.pattern, &rel) || fnmatch(&r.pattern, base)) + .find(|r| fnmatch(&r.pattern, rel) || fnmatch(&r.pattern, base)) +} + +fn same_file(left: &Path, right: &Path) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let Ok(left) = std::fs::metadata(left) else { + return false; + }; + let Ok(right) = std::fs::metadata(right) else { + return false; + }; + return left.dev() == right.dev() && left.ino() == right.ino(); + } + #[cfg(windows)] + { + use std::os::windows::fs::MetadataExt; + let Ok(left) = std::fs::metadata(left) else { + return false; + }; + let Ok(right) = std::fs::metadata(right) else { + return false; + }; + return left.volume_serial_number() == right.volume_serial_number() + && left.file_index() == right.file_index(); + } + #[cfg(not(any(unix, windows)))] + { + let _ = (left, right); + false + } +} + +fn stored_rel_path(root: &Path, rel_path: &str) -> Option { + if rel_path.starts_with('/') || rel_path.contains('\0') { + return None; + } + let absolute = root.join(rel_path); + if !absolute.exists() { + return None; + } + let parent = absolute.parent()?; + let mut matches = Vec::new(); + for entry in std::fs::read_dir(parent).ok()?.flatten() { + let Some(name) = entry.file_name().to_str().map(str::to_string) else { + continue; + }; + if same_file(&entry.path(), &absolute) { + matches.push(name); + if matches.len() > 1 { + return None; + } + } + } + let stored = matches.pop()?; + match rel_path.rsplit_once('/') { + Some((parent_rel, _)) if !parent_rel.is_empty() => Some(format!("{parent_rel}/{stored}")), + _ => Some(stored), + } } /// Python `fnmatch.fnmatch` (case-sensitive, POSIX) subset: `*`, `?`, @@ -937,7 +1016,10 @@ fn yaml_string<'a>(map: &'a yaml_rust2::yaml::Hash, key: &str) -> Option<&'a str } fn yaml_optional_string(map: &yaml_rust2::yaml::Hash, key: &str) -> Result, ()> { - let value = map.get(&yaml_rust2::Yaml::from_str(key)).ok_or(())?; + // Match Python dict.get: a missing key is None, not a parse failure. + let Some(value) = map.get(&yaml_rust2::Yaml::from_str(key)) else { + return Ok(None); + }; if value.is_null() { Ok(None) } else { @@ -1125,8 +1207,8 @@ fn staged_violations(cwd: &Path, policy: &Policy) -> Result, String> // Pass 1 — governed-record lifecycle and frozen transitions. for change in &changes { let code = change.status.as_bytes()[0] as char; - let old_rule = change.old.as_deref().and_then(|p| match_rule(p, policy)); - let new_rule = change.new.as_deref().and_then(|p| match_rule(p, policy)); + let old_rule = change.old.as_deref().and_then(|p| match_rule(p, policy, Some(cwd))); + let new_rule = change.new.as_deref().and_then(|p| match_rule(p, policy, Some(cwd))); let old_kind = old_rule.map(|r| r.policy.as_str()).unwrap_or(""); let new_kind = new_rule.map(|r| r.policy.as_str()).unwrap_or(""); @@ -1169,13 +1251,13 @@ fn staged_violations(cwd: &Path, policy: &Policy) -> Result, String> let Some(path) = change.new.as_deref() else { continue; }; - let Some(rule) = match_rule(path, policy) else { + let Some(rule) = match_rule(path, policy, Some(cwd)) else { continue; }; let code = change.status.as_bytes()[0] as char; match rule.policy.as_str() { "append_only" => { - let old_rule = change.old.as_deref().and_then(|p| match_rule(p, policy)); + let old_rule = change.old.as_deref().and_then(|p| match_rule(p, policy, Some(cwd))); let same_rule = matches!(old_rule, Some(old) if std::ptr::eq(old, rule)); let baseline = if matches!(code, 'M' | 'T') || (code == 'R' && same_rule) { let old = change.old.as_deref().unwrap_or(""); @@ -1218,7 +1300,7 @@ or reorders existing lines. Append superseding records instead." continue; } }; - let old_rule = change.old.as_deref().and_then(|p| match_rule(p, policy)); + let old_rule = change.old.as_deref().and_then(|p| match_rule(p, policy, Some(cwd))); let same_rule = matches!(old_rule, Some(old) if std::ptr::eq(old, rule)); let baseline = if matches!(code, 'M' | 'T') || (code == 'R' && same_rule) { let old = change.old.as_deref().unwrap_or(""); @@ -1353,16 +1435,16 @@ mod tests { fn default_policy_governs_expected_paths() { let p = default_policy(); assert_eq!( - match_rule("docs/DECISIONS.md", &p).unwrap().policy, + match_rule("docs/DECISIONS.md", &p, None).unwrap().policy, "append_only" ); assert_eq!( - match_rule("plans/archive/x.md", &p).unwrap().policy, + match_rule("plans/archive/x.md", &p, None).unwrap().policy, "frozen" ); - assert!(match_rule("src/main.rs", &p).is_none()); + assert!(match_rule("src/main.rs", &p, None).is_none()); assert_eq!( - match_rule("plans\\archive\\win.md", &p).is_some(), + match_rule("plans\\archive\\win.md", &p, None).is_some(), cfg!(windows) ); } @@ -1406,4 +1488,51 @@ mod tests { .unwrap() .contains("greater than existing maximum")); } + + #[test] + fn match_rule_case_variant_follows_directory_entry() { + if let Ok(spec) = std::env::var("STATUTOR_MATCH_CASES") { + let text = std::fs::read_to_string(&spec).expect("match cases"); + let mut lines = text.lines(); + let root = PathBuf::from(lines.next().expect("root")); + let policy = default_policy(); + for rel in lines.filter(|line| !line.is_empty()) { + let got = match_rule(rel, &policy, Some(&root)) + .map(|rule| rule.policy.clone()) + .unwrap_or_else(|| "none".to_string()); + println!("STATUTOR_MATCH {rel} {got}"); + } + return; + } + + let dir = std::env::temp_dir().join(format!("statutor-match-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("AGENTS.md"), b"short\n").unwrap(); + let policy = default_policy(); + let variant = dir.join("agents.md"); + let canonical = dir.join("AGENTS.md"); + if super::same_file(&variant, &canonical) { + assert_eq!( + match_rule("agents.md", &policy, Some(&dir)).unwrap().policy, + "constitution" + ); + } else { + assert!(match_rule("agents.md", &policy, Some(&dir)).is_none()); + std::fs::write(&variant, b"other\n").unwrap(); + assert!(match_rule("agents.md", &policy, Some(&dir)).is_none()); + assert_eq!( + match_rule("AGENTS.md", &policy, Some(&dir)).unwrap().policy, + "constitution" + ); + } + std::fs::create_dir_all(dir.join("notes")).unwrap(); + std::fs::write(dir.join("notes").join("agents.md"), b"nope\n").unwrap(); + assert!(match_rule("notes/agents.md", &policy, Some(&dir)).is_none()); + assert_eq!( + match_rule("AGENTS.md", &policy, Some(&dir)).unwrap().policy, + "constitution" + ); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/docs/architecture.md b/docs/architecture.md index d3e1d2f..1e5f2a5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -40,16 +40,19 @@ Explicit checks can be used by custom integrations. The ## Agent adapters The root of this repository is the Claude Code plugin. Grok Build uses the -same hook protocol and plugin with its own tool vocabulary. OpenCode uses a -TypeScript adapter with 2.x `setup()` and 1.x `server()` entrypoints. Codex -uses the shared hook command for shell and `apply_patch` events. Antigravity -normalizes native tool arguments, including batch replacements. +same hook protocol and plugin with its own tool vocabulary. Cursor uses +`hooks.json` v1 (`preToolUse`, `beforeShellExecution`, `beforeMCPExecution`, +`stop`) and Cursor permission JSON. OpenCode uses a TypeScript adapter with +2.x `setup()` and 1.x `server()` entrypoints. Codex uses the shared hook +command for shell and `apply_patch` events. Antigravity normalizes native +tool arguments, including batch replacements. Use each adapter guide for registration and exact coverage: [Codex](../adapters/codex/README.md), [OpenCode](../adapters/opencode/README.md), -[Antigravity](../adapters/antigravity/README.md), and -[Grok Build](../adapters/grok/README.md). +[Antigravity](../adapters/antigravity/README.md), +[Grok Build](../adapters/grok/README.md), and +[Cursor](../adapters/cursor/README.md). Hook coverage varies by host. Server-namespaced MCP tool IDs and required sections in partial Update File patches are known gaps. The floor judges the diff --git a/docs/releasing.md b/docs/releasing.md index 6fe72b3..2dbed72 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -2,7 +2,7 @@ Python, the root plugin, and the Antigravity plugin share a version. npm and Cargo have independent versions. The hardening candidate uses Python/plugin -0.7.4, npm 0.2.0, and Cargo 0.1.2. Read the manifests for later candidates. +0.7.5, npm 0.2.0, and Cargo 0.1.3. Read the manifests for later candidates. 1. Add behavioral regressions before fixing a reproduced failure. Run the affected tests, then obtain independent review of the final patch. @@ -14,7 +14,7 @@ Cargo have independent versions. The hardening candidate uses Python/plugin and optional-test dependency `PyYAML`, Node 24, and Cargo available: ```sh - python scripts/release_gate.py --tag v0.7.4 --dist-dir /tmp/statutor-release-dist + python scripts/release_gate.py --tag v0.7.5 --dist-dir /tmp/statutor-release-dist ``` The output directory must be empty. The gate tests a clone of the exact diff --git a/docs/workers.md b/docs/workers.md index a5578d7..fb0c556 100644 --- a/docs/workers.md +++ b/docs/workers.md @@ -27,9 +27,10 @@ statutor worker record --harness codex --event attempt --session SESSION_ID ``` Use `statutor worker capabilities --json` to inspect declared evidence and -verification baselines for each agent. Automatic agent integrations cannot -record `--event mutation`; only a human or a custom integration with actual -post-success evidence may do so. An `unknown` agent proves activity only. +verification baselines for each agent. Automatic agent integrations +(`claude`, `codex`, `opencode`, `antigravity`, `gemini`, `grok`, `cursor`) +cannot record `--event mutation`; only a human or a custom integration with +actual post-success evidence may do so. An `unknown` agent proves activity only. Roles and origin agents stay `unknown` unless explicitly proved. ## Complete the handoff @@ -53,6 +54,10 @@ statutor worker complete --session SESSION_ID Completion validates the HANDOFF attribution and revision lineage. It refuses a stale or foreign session and detects a competing local completion. An active lease is a machine-local presence hint, not proof that useful work occurred. +Retrying a completed session reports that it is already completed. Inspect +the recorded result with `statutor worker show --basis completed --json`; +begin a new session for further work. A competing completion after your +session's baseline still requires reconciliation. The registry retains at most 50 sessions per project and 20 leases per worktree. Durable completion history lives in HANDOFF revisions committed to Git. diff --git a/hooks/hooks.json b/hooks/hooks.json index 927cea5..5732ec7 100644 --- a/hooks/hooks.json +++ b/hooks/hooks.json @@ -2,7 +2,7 @@ "hooks": { "PreToolUse": [ { - "matcher": "^(Write|Edit|Bash|apply_patch|write|search_replace|hashline_edit|run_terminal_command|StrReplace|Shell)$", + "matcher": "^(Write|Edit|Bash|apply_patch|write|search_replace|hashline_edit|run_terminal_command|run_terminal_cmd|StrReplace|Shell|MultiEdit|NotebookEdit|Delete)$", "hooks": [ { "type": "command", "command": "python3 \"${CLAUDE_PLUGIN_ROOT}/core/statutor_core.py\" hook" } ] diff --git a/hooks/stop_doctor.py b/hooks/stop_doctor.py index 990394e..a313a44 100644 --- a/hooks/stop_doctor.py +++ b/hooks/stop_doctor.py @@ -27,6 +27,7 @@ import json import os +import re import subprocess import sys @@ -43,22 +44,15 @@ def _state_filename(project_dir: str) -> str: - """Policy-derived name of the overwrite_bounded file (basename-only - patterns, matching statutor_doctor's `_rule_filename`); conventional + """Policy-derived name of the overwrite_bounded file; conventional fallback on any resolution failure (fail-open).""" try: if CORE_DIR not in sys.path: sys.path.insert(0, CORE_DIR) import statutor_core - - for rule in statutor_core.load_worktree_policy(project_dir).get("governed", []): - pattern = rule.get("pattern", "") - if (rule.get("policy") == "overwrite_bounded" and pattern - and "*" not in pattern and "/" not in pattern): - return pattern + return statutor_core.overwrite_bounded_filename(project_dir) except Exception: - pass - return "HANDOFF.md" + return "HANDOFF.md" def _find_ledger_root(start: str) -> str | None: @@ -84,6 +78,8 @@ def _run() -> int: is_antigravity = ("executionNum" in event or "workspacePaths" in event or "terminationReason" in event) + is_cursor = event.get("hook_event_name") in ( + "stop", "preToolUse", "beforeShellExecution", "beforeMCPExecution") reason = event.get("reason") if isinstance(reason, str) and reason != "end_turn": @@ -94,9 +90,29 @@ def _run() -> int: if is_antigravity: print(json.dumps({"decision": "allow"})) return 0 + if event.get("status") in ("aborted", "error"): + return 0 + if is_cursor and event.get("loop_count", 0) != 0: + return 0 workspace_paths = event.get("workspacePaths", []) - cwd = event.get("cwd") or (workspace_paths[0] if workspace_paths else os.getcwd()) + if not isinstance(workspace_paths, list): + workspace_paths = [] + cursor_roots = event.get("workspace_roots") or [] + if not isinstance(cursor_roots, list): + cursor_roots = [] + cwd = event.get("cwd") if isinstance(event.get("cwd"), str) else None + if is_antigravity: + cwd = cwd or (workspace_paths[0] if workspace_paths else None) + if not cwd: + print(json.dumps({"decision": "allow"})) + return 0 + elif is_cursor: + cwd = cwd or (cursor_roots[0] if cursor_roots else None) + if not cwd: + return 0 + else: + cwd = cwd or (workspace_paths[0] if workspace_paths else os.getcwd()) project_dir = _find_ledger_root(cwd) if project_dir is None: if is_antigravity: @@ -119,15 +135,16 @@ def _run() -> int: ] state_filename = _state_filename(project_dir) - sentinel_prefix = f"WARN {state_filename} last verified" + sentinel_prefixes = (f"WARN {state_filename} last verified", + f"WARN {state_filename} is not yet verified") handoff_stamp_present = os.path.isfile(os.path.join(project_dir, state_filename)) if (handoff_stamp_present and len(findings) == 1 - and findings[0].startswith(sentinel_prefix)): + and findings[0].startswith(sentinel_prefixes)): try: handoff_text = open(os.path.join(project_dir, state_filename), encoding="utf-8").read() except Exception: handoff_text = "" - if f"last_verified: {_SENTINEL_DATE}" in handoff_text: + if re.search(r"(?m)^last_verified:\s*" + _SENTINEL_DATE + r"(?:\s|$)", handoff_text): findings = [] # untouched scaffold: init-state noise, not drift if not findings: @@ -136,7 +153,11 @@ def _run() -> int: return 0 # clean ledger (or only-sentinel scaffold): completely silent report = "\n".join(findings) - if is_antigravity: + if is_cursor: + print(json.dumps({ + "followup_message": f"statutor-doctor found drift in the ledger:\n{report}", + })) + elif is_antigravity: print(json.dumps({ "decision": "continue", "reason": f"statutor-doctor found drift in the ledger:\n{report}", diff --git a/pyproject.toml b/pyproject.toml index 02abbed..ae0cc6b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,14 +4,14 @@ build-backend = "setuptools.build_meta" [project] name = "statutor" -version = "0.7.4" +version = "0.7.5" description = "Typed project-ledger framework for agentic repos: four planes, single-writer files, enforced mutation policies." readme = "README.md" license = "MIT" license-files = ["LICENSE"] authors = [{ name = "Hoo" }] requires-python = ">=3.10" -keywords = ["agents", "claude", "opencode", "codex", "gemini", "antigravity", "grok", +keywords = ["agents", "claude", "opencode", "codex", "gemini", "antigravity", "grok", "cursor", "ledger", "governance", "hooks", "pre-commit", "adr", "decision-records"] classifiers = [ "Development Status :: 4 - Beta", @@ -23,6 +23,7 @@ classifiers = [ "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", "Topic :: Software Development :: Quality Assurance", ] diff --git a/skills/statutor/SKILL.md b/skills/statutor/SKILL.md index 8771ac8..dac1192 100644 --- a/skills/statutor/SKILL.md +++ b/skills/statutor/SKILL.md @@ -49,7 +49,8 @@ Non-negotiable rules: 6. **Single writer per file.** Subagents use `notes/.md`. 7. **No shell writes to governed files** (`>>`, `sed -i`, ...) — the bash guard denies them; use the editor tools. On Grok Build those tools are - `search_replace`, `write`, and `run_terminal_command`. + `search_replace`, `write`, and `run_terminal_command`. On Cursor those + tools are `Write`, `StrReplace`, `Shell`, and mapped MCP payloads. 8. **Drift surfaces at Stop, not just in-loop.** The host Stop hook (`hooks/stop_doctor.py`) runs `statutor-doctor` after each turn and adds its WARN/ERROR lines as context — once per turn, silent on a clean ledger. diff --git a/tests/conformance_scenarios.py b/tests/conformance_scenarios.py index b2b6790..715e4f8 100644 --- a/tests/conformance_scenarios.py +++ b/tests/conformance_scenarios.py @@ -10,6 +10,7 @@ from __future__ import annotations +import json import os import shutil import subprocess @@ -553,6 +554,38 @@ def s60_tmp_swap_onto_policy_denied(root: Path) -> None: git(root, "mv", "-f", "evil.tmp", ".statutor.yaml") +def s61_receipt_omitting_null_optional_oids_authorizes(root: Path) -> None: + """Python dict.get treats a missing optional OID key as None. The Rust + twin must too: a receipt that omits JSON-null optional keys still + authorizes when those expected values are None.""" + base_ledger(root) + (root / ".statutor.yaml").write_text(TRUST_POLICY, encoding="utf-8") + git(root, "add", ".statutor.yaml") + git(root, "commit", "-q", "-m", "policy") + git(root, "rm", "-q", ".statutor.yaml") + tree = subprocess.run( + ["git", "write-tree"], cwd=root, env=GIT_ENV, capture_output=True, + text=True, check=True).stdout.strip() + kernel = REPO_ROOT / "core" / "statutor_core.py" + subprocess.run( + [__import__("sys").executable, str(kernel), "trust", "approve", str(root), + "--decision", "D-0015", "--reason", "conformance fixture", + "--confirm-tree", tree], + cwd=root, env=GIT_ENV, capture_output=True, text=True, check=True) + raw = subprocess.run( + ["git", "rev-parse", "--git-path", "statutor/trust-receipt.json"], + cwd=root, env=GIT_ENV, capture_output=True, text=True, check=True, + ).stdout.strip() + path = Path(raw) if os.path.isabs(raw) else root / raw + receipt = json.loads(path.read_text(encoding="utf-8")) + for key in ("head_oid", "baseline_policy_oid", "candidate_policy_oid"): + if receipt.get(key) is None: + receipt.pop(key, None) + path.write_text(json.dumps(receipt, indent=2, sort_keys=True) + "\n", + encoding="utf-8") + os.chmod(path, 0o600) + + SCENARIOS = { name: fn for name, fn in sorted(globals().items()) diff --git a/tests/test_adapter_antigravity.py b/tests/test_adapter_antigravity.py index 68a0b2f..509892e 100644 --- a/tests/test_adapter_antigravity.py +++ b/tests/test_adapter_antigravity.py @@ -105,6 +105,70 @@ def test_native_batch_event_denies_frozen_write(tmp_path: Path) -> None: assert json.loads(result.stdout)["decision"] == "deny" +@pytest.mark.parametrize("filename,decision", [ + ("plans/archive/probe.md", "deny"), + ("notes/plain.md", "allow"), +]) +def test_absolute_target_alone_resolves_its_ledger(tmp_path: Path, filename, decision): + ledger = tmp_path / "ledger" + kernel.run_init(str(ledger)) + event = { + "workspacePaths": [], + "toolCall": {"name": "write_to_file", "args": { + "TargetFile": str(ledger / filename), "CodeContent": "change\n", + }}, + } + result = subprocess.run( + [sys.executable, str(REPO_ROOT / "core/statutor_core.py"), "hook"], + input=json.dumps(event), cwd=str(tmp_path), text=True, + capture_output=True, check=True, + ) + out = json.loads(result.stdout) + assert out["decision"] == decision + if decision == "deny": + assert "frozen" in out["reason"] + + +@pytest.mark.parametrize("target", [None, 42, "plans/archive/probe.md"]) +def test_unresolved_target_does_not_infer_process_ledger(tmp_path: Path, target): + kernel.run_init(str(tmp_path)) + args = {"CodeContent": "change\n"} + if target is not None: + args["TargetFile"] = target + event = {"workspacePaths": [], + "toolCall": {"name": "write_to_file", "args": args}} + result = subprocess.run( + [sys.executable, str(REPO_ROOT / "core/statutor_core.py"), "hook"], + input=json.dumps(event), cwd=str(tmp_path), text=True, + capture_output=True, check=True, + ) + assert json.loads(result.stdout)["decision"] == "allow" + + +@pytest.mark.parametrize("context", ["Cwd", "cwd", "workspacePaths"]) +def test_explicit_context_precedes_absolute_target_fallback(tmp_path: Path, context): + ledger = tmp_path / "ledger" + kernel.run_init(str(ledger)) + non_ledger = tmp_path / "outside" + non_ledger.mkdir() + args = {"TargetFile": str(ledger / "plans/archive/probe.md"), + "CodeContent": "change\n"} + event = {"workspacePaths": [], + "toolCall": {"name": "write_to_file", "args": args}} + if context == "Cwd": + args[context] = str(non_ledger) + elif context == "cwd": + event[context] = str(non_ledger) + else: + event[context] = [str(non_ledger)] + result = subprocess.run( + [sys.executable, str(REPO_ROOT / "core/statutor_core.py"), "hook"], + input=json.dumps(event), cwd=str(tmp_path), text=True, + capture_output=True, check=True, + ) + assert json.loads(result.stdout)["decision"] == "allow" + + def test_batch_tool_is_registered() -> None: matcher = json.loads((ADAPTER_ROOT / "hooks.json").read_text())["statutor"]["PreToolUse"][0]["matcher"] assert "multi_replace_file_content" in matcher.split("|") @@ -396,6 +460,34 @@ def test_hook_pre_tool_use_outside_workspace_without_cwd_allows(monkeypatch, cap assert out["decision"] == "allow" +def test_hook_relative_target_file_uses_workspace_not_process_cwd( + monkeypatch, capsys, tmp_path: Path, +) -> None: + ledger = tmp_path / "ledger" + kernel.run_init(str(ledger)) + capsys.readouterr() + (ledger / "plans" / "archive" / "probe.md").write_text("old\n", encoding="utf-8") + plugin = tmp_path / "plugin" + plugin.mkdir() + event = { + "toolCall": { + "name": "write_to_file", + "args": { + "TargetFile": "plans/archive/probe.md", + "CodeContent": "touch", + }, + }, + "workspacePaths": [str(ledger)], + } + monkeypatch.chdir(plugin) + monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(event))) + exit_code = kernel.run_hook() + assert exit_code == 0 + out = json.loads(capsys.readouterr().out.strip()) + assert out["decision"] == "deny" + assert "frozen" in out["reason"] + + # -------------------------------------------------------------------------- # 4. Worker provenance & capabilities # -------------------------------------------------------------------------- diff --git a/tests/test_adapter_cursor.py b/tests/test_adapter_cursor.py new file mode 100644 index 0000000..cdc4eec --- /dev/null +++ b/tests/test_adapter_cursor.py @@ -0,0 +1,241 @@ +"""Tests for the Cursor hooks.json adapter and kernel mapping.""" + +from __future__ import annotations + +import io +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "core")) + +import statutor_core as kernel +import statutor_worker as worker + +REPO_ROOT = Path(__file__).resolve().parents[1] +ADAPTER_ROOT = REPO_ROOT / "adapters" / "cursor" + + +def _cursor_hook(monkeypatch, capsys, event: dict) -> dict: + monkeypatch.setattr(sys, "stdin", io.StringIO(json.dumps(event))) + assert kernel.run_hook() == 0 + out = capsys.readouterr().out.strip() + return json.loads(out) if out else {} + + +def test_cursor_write_denies_frozen(monkeypatch, capsys, tmp_path: Path) -> None: + kernel.run_init(str(tmp_path)) + capsys.readouterr() + event = { + "hook_event_name": "preToolUse", + "tool_name": "Write", + "tool_input": { + "path": "plans/archive/probe.md", + "contents": "touch", + }, + "cwd": str(tmp_path), + "workspace_roots": [str(tmp_path)], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "deny" + assert "frozen" in out["agent_message"] + + +def test_cursor_shell_denies_handoff_redirect(monkeypatch, capsys, tmp_path: Path) -> None: + kernel.run_init(str(tmp_path)) + capsys.readouterr() + event = { + "hook_event_name": "beforeShellExecution", + "command": "echo x >> HANDOFF.md", + "cwd": str(tmp_path), + "workspace_roots": [str(tmp_path)], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "deny" + assert "HANDOFF.md" in out["agent_message"] + + +def test_cursor_silent_outside_ledger(monkeypatch, capsys, tmp_path: Path) -> None: + event = { + "hook_event_name": "preToolUse", + "tool_name": "Write", + "tool_input": {"path": "DECISIONS.md", "contents": "x"}, + "cwd": str(tmp_path), + "workspace_roots": [str(tmp_path)], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "allow" + + +def test_cursor_missing_workspace_allows(monkeypatch, capsys) -> None: + event = { + "hook_event_name": "beforeShellExecution", + "command": "echo x >> HANDOFF.md", + "workspace_roots": [], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "allow" + + +def test_cursor_mcp_write_denies_append_only(monkeypatch, capsys, tmp_path: Path) -> None: + kernel.run_init(str(tmp_path)) + capsys.readouterr() + event = { + "hook_event_name": "beforeMCPExecution", + "tool_name": "write", + "tool_input": json.dumps({ + "file_path": "DECISIONS.md", + "content": "rewritten\n", + }), + "mcp_server_name": "files", + "cwd": str(tmp_path), + "workspace_roots": [str(tmp_path)], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "deny" + assert "append-only" in out["agent_message"] + + +def test_cursor_strreplace_denies_decision_edit(monkeypatch, capsys, tmp_path: Path) -> None: + kernel.run_init(str(tmp_path)) + capsys.readouterr() + (tmp_path / "DECISIONS.md").write_text("kept\n", encoding="utf-8") + event = { + "hook_event_name": "preToolUse", + "tool_name": "StrReplace", + "tool_input": { + "path": "DECISIONS.md", + "old_string": "kept", + "new_string": "gone", + }, + "cwd": str(tmp_path), + "workspace_roots": [str(tmp_path)], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "deny" + assert "append-only" in out["agent_message"] + + +def test_cursor_fail_open_emits_allow_json(monkeypatch, capsys, tmp_path: Path) -> None: + kernel.run_init(str(tmp_path)) + capsys.readouterr() + + def boom(*_args, **_kwargs): + raise RuntimeError("kernel bug") + + monkeypatch.setattr(kernel, "_automatic_reason", boom) + event = { + "hook_event_name": "preToolUse", + "tool_name": "Write", + "tool_input": {"path": "DECISIONS.md", "contents": "x\n"}, + "cwd": str(tmp_path), + "workspace_roots": [str(tmp_path)], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "allow" + + +def test_cursor_malformed_json_emits_allow(monkeypatch, capsys) -> None: + monkeypatch.setattr(sys, "stdin", io.StringIO( + '{"hook_event_name": "preToolUse",')) + assert kernel.run_hook() == 0 + out = json.loads(capsys.readouterr().out.strip()) + assert out["permission"] == "allow" + + +def test_cursor_stop_emits_native_followup_once(monkeypatch, capsys, tmp_path): + kernel.run_init(str(tmp_path)) + capsys.readouterr() + (tmp_path / "TASKS.md").unlink() + event = {"hook_event_name": "stop", "status": "completed", + "loop_count": 0, "workspace_roots": [str(tmp_path)]} + out = _cursor_hook(monkeypatch, capsys, event) + assert set(out) == {"followup_message"} + assert "missing governed file: TASKS.md" in out["followup_message"] + event["loop_count"] = 1 + assert _cursor_hook(monkeypatch, capsys, event) == {} + + +@pytest.mark.parametrize("status", ["aborted", "error"]) +def test_cursor_stop_does_not_continue_failed_turn(monkeypatch, capsys, tmp_path, status): + kernel.run_init(str(tmp_path)) + capsys.readouterr() + (tmp_path / "TASKS.md").unlink() + event = {"hook_event_name": "stop", "status": status, + "loop_count": 0, "workspace_roots": [str(tmp_path)]} + assert _cursor_hook(monkeypatch, capsys, event) == {} + + +@pytest.mark.parametrize("scaffold", [False, True]) +def test_cursor_stop_clean_or_outside_ledger_stays_silent(monkeypatch, capsys, tmp_path, scaffold): + if scaffold: + kernel.run_init(str(tmp_path)) + capsys.readouterr() + event = {"hook_event_name": "stop", "status": "completed", + "loop_count": 0, "workspace_roots": [str(tmp_path)]} + assert _cursor_hook(monkeypatch, capsys, event) == {} + + +def test_cursor_stop_missing_workspace_stays_silent(monkeypatch, capsys, tmp_path): + kernel.run_init(str(tmp_path)) + capsys.readouterr() + (tmp_path / "TASKS.md").unlink() + monkeypatch.chdir(tmp_path) + assert _cursor_hook(monkeypatch, capsys, { + "hook_event_name": "stop", "status": "completed", + "loop_count": 0, "workspace_roots": [], + }) == {} + + +def test_cursor_stop_doctor_crash_fails_open(monkeypatch, capsys, tmp_path): + import statutor_doctor + + kernel.run_init(str(tmp_path)) + capsys.readouterr() + + def boom(*_args, **_kwargs): + raise RuntimeError("doctor bug") + + monkeypatch.setattr(statutor_doctor, "check", boom) + assert _cursor_hook(monkeypatch, capsys, { + "hook_event_name": "stop", "status": "completed", + "loop_count": 0, "workspace_roots": [str(tmp_path)], + }) == {} + + +def test_cursor_delete_denies_governed(monkeypatch, capsys, tmp_path: Path) -> None: + kernel.run_init(str(tmp_path)) + capsys.readouterr() + event = { + "hook_event_name": "preToolUse", + "tool_name": "Delete", + "tool_input": {"path": "DECISIONS.md"}, + "cwd": str(tmp_path), + "workspace_roots": [str(tmp_path)], + } + out = _cursor_hook(monkeypatch, capsys, event) + assert out["permission"] == "deny" + assert "delete is denied" in out["agent_message"] + + +def test_cursor_registered_in_worker_capabilities() -> None: + assert "cursor" in worker.HARNESSES + caps = worker.host_capabilities("cursor") + assert caps["proves_mutation"] is False + assert "preToolUse" in str(caps["attempt_surface"]) + + +def test_cursor_adapter_hooks_json_exists() -> None: + data = json.loads((ADAPTER_ROOT / "hooks.json").read_text(encoding="utf-8")) + assert data["version"] == 1 + for name in ("preToolUse", "beforeShellExecution", "beforeMCPExecution", "stop"): + assert name in data["hooks"] + + +def test_repo_dogfoods_cursor_hooks() -> None: + data = json.loads((REPO_ROOT / ".cursor" / "hooks.json").read_text(encoding="utf-8")) + assert data["version"] == 1 + assert "preToolUse" in data["hooks"] + assert "statutor_core.py" in data["hooks"]["preToolUse"][0]["command"] diff --git a/tests/test_conformance_rust.py b/tests/test_conformance_rust.py index a18613d..b16f692 100644 --- a/tests/test_conformance_rust.py +++ b/tests/test_conformance_rust.py @@ -71,6 +71,7 @@ "s58_state_new_id_must_advance": (1, "greater than existing maximum T-0001"), "s59_state_binary_denied": (1, "state content must be valid UTF-8"), "s60_tmp_swap_onto_policy_denied": (1, "missing, stale, or unsafe receipt"), + "s61_receipt_omitting_null_optional_oids_authorizes": (0, ""), } @@ -371,17 +372,24 @@ def test_state_spacing_and_diagnostic_order_match_python( @git_required -def test_decimal_blocks_supported_by_canonical_python_match_rust( +def test_pinned_unicode_16_decimal_blocks_match_rust( tmp_path: Path, staged_bin: Path) -> None: - import unicodedata - - starts = [point for point in range(sys.maxunicode + 1) - if unicodedata.category(chr(point)) == "Nd" - and unicodedata.decimal(chr(point)) == 0] import statutor_core - assert set(starts) <= set(statutor_core._DECIMAL_STARTS) - starts = statutor_core._DECIMAL_STARTS + # D-0029 pins the grammar to this version, independently of Python's UCD: + # https://www.unicode.org/Public/16.0.0/ucd/extracted/DerivedNumericType.txt + starts = ( + 0x30, 0x660, 0x6F0, 0x7C0, 0x966, 0x9E6, 0xA66, 0xAE6, 0xB66, 0xBE6, + 0xC66, 0xCE6, 0xD66, 0xDE6, 0xE50, 0xED0, 0xF20, 0x1040, 0x1090, 0x17E0, + 0x1810, 0x1946, 0x19D0, 0x1A80, 0x1A90, 0x1B50, 0x1BB0, 0x1C40, 0x1C50, + 0xA620, 0xA8D0, 0xA900, 0xA9D0, 0xA9F0, 0xAA50, 0xABF0, 0xFF10, + 0x104A0, 0x10D30, 0x10D40, 0x11066, 0x110F0, 0x11136, 0x111D0, 0x112F0, + 0x11450, 0x114D0, 0x11650, 0x116C0, 0x116D0, 0x116DA, 0x11730, 0x118E0, + 0x11950, 0x11BF0, 0x11C50, 0x11D50, 0x11DA0, 0x11F50, 0x16130, 0x16A60, + 0x16AC0, 0x16B50, 0x16D70, 0x1CCF0, 0x1D7CE, 0x1D7D8, 0x1D7E2, 0x1D7EC, + 0x1D7F6, 0x1E140, 0x1E2F0, 0x1E4F0, 0x1E5F1, 0x1E950, 0x1FBF0, + ) + assert set(starts) == set(statutor_core._DECIMAL_STARTS) policy = "governed:\n" + "".join( f" - pattern: note-{index}.md\n policy: constitution\n" f" max_lines: '{chr(start + 1)}{chr(start + 2)}'\n" @@ -400,6 +408,28 @@ def test_decimal_blocks_supported_by_canonical_python_match_rust( assert _run_kernel(tmp_path).returncode == _run_rust(staged_bin, tmp_path).returncode == 0 +@git_required +@pytest.mark.parametrize("mode", ["cap", "task"]) +def test_unicode_17_decimal_digits_remain_outside_pinned_grammar( + tmp_path: Path, staged_bin: Path, mode: str) -> None: + cs.init_repo(tmp_path) + if mode == "cap": + policy = ("governed:\n - pattern: NOTE.md\n policy: constitution\n" + " max_lines: '\U00011de1\U00011de2'\n") + else: + policy = "governed:\n - pattern: TASKS.md\n policy: state\n" + (tmp_path / "TASKS.md").write_text( + "- [ ] T-\U00011de0\U00011de0\U00011de0\U00011de1 detail\n", encoding="utf-8") + (tmp_path / ".statutor.yaml").write_text(policy, encoding="utf-8") + cs.git(tmp_path, "add", "-A") + py = _run_kernel(tmp_path) + rs = _run_rust(staged_bin, tmp_path) + assert py.returncode == rs.returncode == 1 + assert py.stdout == rs.stdout + assert ("invalid or unsupported Statutor policy" if mode == "cap" + else "state line 1 must be") in py.stdout + + @git_required def test_arbitrary_size_decimal_caps_and_state_ids_match( tmp_path: Path, staged_bin: Path) -> None: @@ -440,3 +470,57 @@ def test_literal_backslash_filename_keeps_python_policy_matching( assert py.returncode == rs.returncode == 1 assert py.stdout == rs.stdout assert "frozen" in py.stdout + + +def _rust_match_names(root: Path, rels: list[str]) -> dict[str, str]: + """Ask the shipped Rust matcher which policy each relative path takes.""" + spec = root.parent / f"match-cases-{root.name}.txt" + spec.write_text(str(root) + "\n" + "\n".join(rels) + "\n", encoding="utf-8") + env = {**os.environ, "STATUTOR_MATCH_CASES": str(spec)} + proc = subprocess.run( + ["cargo", "test", "--lib", "--locked", "--manifest-path", + str(CRATE / "Cargo.toml"), + "tests::match_rule_case_variant_follows_directory_entry", + "--", "--exact", "--nocapture"], + env=env, capture_output=True, text=True) + assert proc.returncode == 0, proc.stdout + "\n" + proc.stderr + found: dict[str, str] = {} + for line in (proc.stdout + "\n" + proc.stderr).splitlines(): + if not line.startswith("STATUTOR_MATCH "): + continue + _, rel, policy = line.split(" ", 2) + found[rel] = policy + return found + + +def test_match_rule_case_variant_agrees_with_rust(tmp_path: Path) -> None: + """Python and Rust agree on directory-entry case variants.""" + if not _cargo_available(): + pytest.skip("cargo unavailable") + sys.path.insert(0, str(REPO_ROOT / "core")) + import statutor_core + + root = tmp_path / "ledger" + root.mkdir() + (root / "AGENTS.md").write_text("short\n", encoding="utf-8") + notes = root / "notes" + notes.mkdir() + (notes / "agents.md").write_text("other\n", encoding="utf-8") + variant = root / "agents.md" + if variant.exists() and os.path.samefile(root / "AGENTS.md", variant): + want_variant = "constitution" + else: + variant.write_text("different\n", encoding="utf-8") + assert not os.path.samefile(root / "AGENTS.md", variant) + want_variant = "none" + expected = { + "AGENTS.md": "constitution", + "agents.md": want_variant, + "notes/agents.md": "none", + } + policy = statutor_core.DEFAULT_POLICY + for rel, want in expected.items(): + rule = statutor_core._match_rule(rel, policy, root=str(root)) + got = rule["policy"] if rule else "none" + assert got == want, rel + assert _rust_match_names(root, list(expected)) == expected diff --git a/tests/test_doctor.py b/tests/test_doctor.py index b9fbed3..93ec720 100644 --- a/tests/test_doctor.py +++ b/tests/test_doctor.py @@ -180,6 +180,19 @@ def test_clean_ledger_ok(tmp_path, monkeypatch, capsys): assert "ERROR" not in out +def test_invalid_utf8_records_error_and_keeps_checking(tmp_path): + _write_ledger(tmp_path) + (tmp_path / "AGENTS.md").write_bytes(b"# AGENTS\n\xff\n") + handoff = (tmp_path / "HANDOFF.md").read_text(encoding="utf-8").replace( + "## Goal", "## Aim") + (tmp_path / "HANDOFF.md").write_text(handoff, encoding="utf-8") + statutor_doctor.check(str(tmp_path)) + assert any("AGENTS.md" in item and "UTF-8" in item + for item in statutor_doctor.errors) + assert any("missing required sections" in item and "## Goal" in item + for item in statutor_doctor.errors) + + def test_missing_governed_file_errors(tmp_path, monkeypatch, capsys): _write_ledger(tmp_path, omit={"TASKS.md"}) out, code = run_doctor(monkeypatch, capsys, tmp_path) @@ -187,6 +200,28 @@ def test_missing_governed_file_errors(tmp_path, monkeypatch, capsys): assert "ERROR missing governed file: TASKS.md" in out +@pytest.mark.parametrize("filename", ["HANDOFF.md", "STATUS.md"]) +def test_unverified_sentinel_explains_next_step_without_rewriting( + tmp_path, monkeypatch, capsys, filename, +): + _write_ledger(tmp_path, omit={"HANDOFF.md"}) + state = tmp_path / filename + original = _handoff_text("1970-01-01") + state.write_text(original, encoding="utf-8") + policy = _policy_soft_max_5() + policy["governed"][1]["pattern"] = filename + _stub_yaml(monkeypatch, policy) + + out, code = run_doctor(monkeypatch, capsys, tmp_path) + + assert code == 0 + assert f"{filename} is not yet verified" in out + assert "run project checks" in out + assert "replace last_verified with the verification date" in out + assert "days ago" not in out + assert state.read_text(encoding="utf-8") == original + + @pytest.mark.parametrize("tasks,fragment", [ ("- [ ] T-0001 one\n- [x] T-0001 duplicate\n", "duplicate state task ID T-0001"), ("- [maybe] T-0001 malformed\n", "state line 1 must be"), diff --git a/tests/test_global_instructions.py b/tests/test_global_instructions.py index 49718de..753d4b3 100644 --- a/tests/test_global_instructions.py +++ b/tests/test_global_instructions.py @@ -31,6 +31,20 @@ def _roots(tmp_path: Path) -> substrate.ResolvedRoots: ) +def test_global_help_exposes_delegated_skills(capsys) -> None: + with pytest.raises(SystemExit) as stopped: + lifecycle.main(["--help"]) + assert stopped.value.code == 0 + assert "statutor global skill --help" in capsys.readouterr().out + + with pytest.raises(SystemExit) as stopped: + lifecycle.main(["skill", "--help"]) + assert stopped.value.code == 0 + output = capsys.readouterr().out + assert "statutor global skill" in output + assert "import" in output and "uninstall" in output + + def test_init_only_scaffolds_statutor_sources_and_is_idempotent(tmp_path: Path) -> None: roots = _roots(tmp_path) assert all(item["action"] == "write" for item in lifecycle.init_plan(roots)["actions"]) diff --git a/tests/test_global_status.py b/tests/test_global_status.py index e038e9a..c3b1d53 100644 --- a/tests/test_global_status.py +++ b/tests/test_global_status.py @@ -70,6 +70,58 @@ def test_empty_inventory_has_stable_schema_and_no_false_errors(tmp_path: Path) - roots, admin_root=tmp_path / "admin") == result +@pytest.mark.parametrize("command, expected_exit", [("status", 0), ("doctor", 1)]) +@pytest.mark.parametrize("json_output", [False, True]) +def test_uninitialized_global_cli_gives_one_recovery_step_without_writes( + tmp_path, capsys, monkeypatch, command, expected_exit, json_output, +): + roots = substrate.resolve_roots( + home=tmp_path / "home", config_root=tmp_path / "config", + state_root=tmp_path / "state", environ={}, platform="posix") + monkeypatch.setenv("CLAUDE_CONFIG_DIR", roots.claude_home) + monkeypatch.setenv("CODEX_HOME", roots.codex_home) + monkeypatch.setenv("XDG_CONFIG_HOME", str(Path(roots.opencode_home).parent)) + args = [command, "--home", roots.home, + "--config-root", roots.config_root, "--state-root", roots.state_root] + if json_output: + args.append("--json") + + assert instructions.main(args) == expected_exit + output = capsys.readouterr().out + if json_output: + result = json.loads(output) + assert result["schema_version"] == 1 + assert result["summary"] == {"errors": 1, "warnings": 0} + assert [item["code"] for item in result["diagnostics"]] == [ + "global-not-initialized"] + output = result["diagnostics"][0]["message"] + assert "global layer is not initialized" in output + assert "run `statutor global init`" in output + assert "cannot load JSON" not in output + assert not Path(roots.config_root).exists() + assert not Path(roots.state_root).exists() + + +@pytest.mark.parametrize("config_kind", ["malformed", "broken-link"]) +def test_partial_global_setup_preserves_invalid_config_diagnostic(tmp_path, config_kind): + roots = _roots(tmp_path) + config = Path(roots.config_root, "global.json") + if config_kind == "malformed": + config.write_text("broken", encoding="utf-8") + else: + config.unlink() + config.symlink_to(tmp_path / "missing.json") + Path(roots.state_root, "global-state.json").unlink() + + result = diagnostics.global_doctor(roots, admin_root=tmp_path / "admin") + + assert "global-config-invalid" in _codes(result) + assert "global-state-missing" in _codes(result) + assert "global-not-initialized" not in _codes(result) + assert "cannot read JSON" in next(item["message"] for item in result["diagnostics"] + if item["code"] == "global-config-invalid") + + @pytest.mark.parametrize("host", substrate.HOSTS) def test_filtered_doctor_does_not_orphan_other_managed_hosts( tmp_path: Path, host: str, diff --git a/tests/test_kernel.py b/tests/test_kernel.py index fdd9baa..a27b5f3 100644 --- a/tests/test_kernel.py +++ b/tests/test_kernel.py @@ -229,6 +229,91 @@ def test_match_rule_outside_cwd_still_governed_quirk(): assert rule["policy"] == "append_only" +def test_case_variant_same_directory_entry_is_governed(tmp_path): + """On a case-insensitive volume, agents.md is the AGENTS.md entry.""" + canonical = tmp_path / "AGENTS.md" + canonical.write_text("short\n", encoding="utf-8") + variant = tmp_path / "agents.md" + if not (variant.exists() and os.path.samefile(canonical, variant)): + pytest.skip("this volume keeps agents.md and AGENTS.md as different files") + reason = statutor_core.validate( + "write", {"file_path": str(variant), "content": lines(300)}, + str(tmp_path), POLICY) + assert reason is not None + assert "300" in reason + assert "hard cap" in reason + deleted = statutor_core.validate( + "delete", {"file_path": str(variant)}, str(tmp_path), POLICY) + assert deleted is not None + assert "delete is denied" in deleted + + +def _case_distinct_root(tmp_path: Path) -> tuple[Path, callable]: + """A directory where agents.md and AGENTS.md are different entries.""" + probe = tmp_path / "fold-probe" + probe.mkdir() + (probe / "AGENTS.md").write_text("A\n", encoding="utf-8") + variant = probe / "agents.md" + if not (variant.exists() and os.path.samefile(probe / "AGENTS.md", variant)): + return tmp_path, lambda: None + image = tmp_path / "cs.sparseimage" + mount = tmp_path / "cs-mnt" + mount.mkdir() + create = subprocess.run( + ["hdiutil", "create", "-size", "20m", "-type", "SPARSE", + "-fs", "Case-sensitive APFS", "-volname", "stcs", str(image)], + capture_output=True, text=True) + if create.returncode != 0: + pytest.skip(f"case-sensitive volume unavailable: {create.stderr}") + attach = subprocess.run( + ["hdiutil", "attach", str(image), "-mountpoint", str(mount), "-nobrowse"], + capture_output=True, text=True) + if attach.returncode != 0: + pytest.skip(f"case-sensitive attach failed: {attach.stderr}") + + def cleanup() -> None: + subprocess.run(["hdiutil", "detach", str(mount)], capture_output=True) + + return mount, cleanup + + +def test_case_variant_distinct_files_do_not_share_a_rule(tmp_path): + root, cleanup = _case_distinct_root(tmp_path) + try: + (root / "AGENTS.md").write_text("governed\n", encoding="utf-8") + (root / "agents.md").write_text("other\n", encoding="utf-8") + assert not os.path.samefile(root / "AGENTS.md", root / "agents.md") + assert statutor_core._match_rule("agents.md", POLICY, root=str(root)) is None + assert statutor_core._match_rule( + "AGENTS.md", POLICY, root=str(root))["policy"] == "constitution" + assert statutor_core.validate( + "write", {"file_path": str(root / "agents.md"), "content": lines(300)}, + str(root), POLICY) is None + denied = statutor_core.validate( + "write", {"file_path": str(root / "AGENTS.md"), "content": lines(300)}, + str(root), POLICY) + assert denied is not None + assert "hard cap" in denied + finally: + cleanup() + + +def test_case_variant_other_directory_entry_is_not_governed(tmp_path): + canonical = tmp_path / "AGENTS.md" + canonical.write_text("short\n", encoding="utf-8") + other = tmp_path / "notes" / "agents.md" + other.parent.mkdir() + other.write_text("notes\n", encoding="utf-8") + assert not os.path.samefile(canonical, other) + assert statutor_core.validate( + "write", {"file_path": str(other), "content": lines(300)}, + str(tmp_path), POLICY) is None + assert statutor_core._match_rule( + "notes/agents.md", POLICY, root=str(tmp_path)) is None + assert statutor_core._match_rule( + "AGENTS.md", POLICY, root=str(tmp_path))["policy"] == "constitution" + + # -------------------------------------------------------------------------- # load_policy (K-13..K-22) # -------------------------------------------------------------------------- @@ -296,6 +381,23 @@ def test_load_policy_malformed_committed_policy_is_error(tmp_path): statutor_core.load_policy(str(tmp_path)) +@git_required +def test_hook_denies_malformed_committed_policy(tmp_path): + git(tmp_path, "init", "-q", "-b", "main") + (tmp_path / ".statutor.yaml").write_text("::: not yaml [\n", encoding="utf-8") + commit_all(tmp_path, "bad policy") + result = run_kernel(["hook"], input_str=json.dumps({ + "tool_name": "Write", + "tool_input": {"file_path": "notes/x.md", "content": "x"}, + "cwd": str(tmp_path), + })) + assert result.returncode == 0 + data = json.loads(result.stdout) + reason = data["hookSpecificOutput"]["permissionDecisionReason"] + assert data["hookSpecificOutput"]["permissionDecision"] == "deny" + assert "committed policy invalid" in reason + + def test_load_policy_empty_governed_list_honored(tmp_path): git(tmp_path, "init", "-q", "-b", "main") (tmp_path / ".statutor.yaml").write_text("governed: []\n", encoding="utf-8") @@ -331,11 +433,65 @@ def test_validate_non_mutating_tools_pass(tmp_path, tool): @pytest.mark.parametrize("tool,file_path", [ ("multiedit", "DECISIONS.md"), ("notebookedit", "DECISIONS.md"), - ("multiedit", "plans/archive/x.md"), ("notebookedit", "plans/archive/x.md"), + ("MultiEdit", "plans/archive/x.md"), ("NotebookEdit", "plans/archive/x.md"), ]) -def test_validate_multiedit_notebookedit_uncovered_quirk(tmp_path, tool, file_path): +def test_validate_multiedit_notebookedit_deny_unproved_governed(tmp_path, tool, file_path): payload = {"file_path": str(tmp_path / file_path)} - assert statutor_core.validate(tool, payload, str(tmp_path), POLICY) is None + reason = statutor_core.validate(tool, payload, str(tmp_path), POLICY) + assert reason is not None + assert "cannot be proved safe" in reason + + +def test_validate_multiedit_ungoverned_path_stays_silent(tmp_path): + payload = {"file_path": str(tmp_path / "notes" / "scratch.md")} + assert statutor_core.validate("multiedit", payload, str(tmp_path), POLICY) is None + + +def _whole_file_denial(reason: str) -> None: + assert reason is not None + assert "cannot be proved safe" in reason + assert "write" in reason + assert "complete file" in reason + assert "old_string" not in reason + + +@pytest.mark.parametrize("tool", ["MultiEdit", "NotebookEdit"]) +def test_whole_file_edits_deny_governed_paths_with_or_without_old_string(tmp_path, tool): + """MultiEdit and NotebookEdit stay denied once the path is governed.""" + target = tmp_path / "DECISIONS.md" + target.write_text("# DECISIONS\n\nkept\n", encoding="utf-8") + edits = {"file_path": str(target), "edits": [ + {"old_string": "kept", "new_string": "gone"}]} + _whole_file_denial(statutor_core.validate(tool, edits, str(tmp_path), POLICY)) + with_old = {**edits, "old_string": "kept", "new_string": "gone"} + _whole_file_denial(statutor_core.validate(tool, with_old, str(tmp_path), POLICY)) + silent = {"file_path": str(tmp_path / "notes" / "scratch.md"), + "old_string": "kept", "edits": [{"old_string": "kept", "new_string": "gone"}]} + assert statutor_core.validate(tool, silent, str(tmp_path), POLICY) is None + + +def test_proved_edit_aliases_and_empty_claude_edit_stay_put(tmp_path): + target = tmp_path / "DECISIONS.md" + target.write_text("kept\n", encoding="utf-8") + path = str(target) + for tool in ("search_replace", "strreplace", "hashline_edit"): + missing = statutor_core.validate( + tool, {"file_path": path, "new_string": "x"}, str(tmp_path), POLICY) + assert missing is not None + assert "old_string" in missing + allowed = statutor_core.validate( + tool, {"file_path": path, "old_string": "kept", "new_string": "kept\nmore"}, + str(tmp_path), POLICY) + assert allowed is None + denied = statutor_core.validate( + tool, {"file_path": path, "old_string": "kept", "new_string": "gone"}, + str(tmp_path), POLICY) + assert denied is not None + assert "append-only" in denied + empty = statutor_core.validate( + "Edit", {"file_path": path, "old_string": "", "new_string": "x"}, + str(tmp_path), POLICY) + assert empty is None @pytest.mark.parametrize("tool", ["write", "edit"]) @@ -593,16 +749,28 @@ def test_append_only_write_missing_file_treated_as_empty(tmp_path): assert statutor_core.validate("write", payload, str(tmp_path), POLICY) is None -def test_append_only_write_whitespace_only_existing_ok(tmp_path): +def test_append_only_write_whitespace_lines_must_survive(tmp_path): (tmp_path / "DECISIONS.md").write_text(" \n\n", encoding="utf-8") - payload = {"file_path": str(tmp_path / "DECISIONS.md"), "content": "unrelated\n"} - assert statutor_core.validate("write", payload, str(tmp_path), POLICY) is None + path = str(tmp_path / "DECISIONS.md") + replaced = statutor_core.validate( + "write", {"file_path": path, "content": "unrelated\n"}, str(tmp_path), POLICY) + assert replaced is not None + assert "append-only" in replaced + kept = statutor_core.validate( + "write", {"file_path": path, "content": " \n\nmore\n"}, str(tmp_path), POLICY) + assert kept is None -def test_append_only_write_strip_based_containment_quirk(tmp_path): +def test_append_only_write_trailing_newline_is_part_of_the_line(tmp_path): (tmp_path / "DECISIONS.md").write_text("abc\n", encoding="utf-8") - payload = {"file_path": str(tmp_path / "DECISIONS.md"), "content": "abc"} - assert statutor_core.validate("write", payload, str(tmp_path), POLICY) is None + path = str(tmp_path / "DECISIONS.md") + dropped = statutor_core.validate( + "write", {"file_path": path, "content": "abc"}, str(tmp_path), POLICY) + assert dropped is not None + assert "append-only" in dropped + kept = statutor_core.validate( + "write", {"file_path": path, "content": "abc\nmore\n"}, str(tmp_path), POLICY) + assert kept is None def test_append_only_write_directory_path_raises_quirk(tmp_path): @@ -613,6 +781,60 @@ def test_append_only_write_directory_path_raises_quirk(tmp_path): statutor_core.validate("write", payload, str(tmp_path), POLICY) +def test_append_only_write_middle_insertion_allowed(tmp_path): + (tmp_path / "DECISIONS.md").write_text("line1\nline2\n", encoding="utf-8") + payload = {"file_path": str(tmp_path / "DECISIONS.md"), + "content": "line1\ninserted\nline2\n"} + assert statutor_core.validate("write", payload, str(tmp_path), POLICY) is None + + +def test_append_only_write_reorder_or_drop_denied(tmp_path): + (tmp_path / "DECISIONS.md").write_text("line1\nline2\n", encoding="utf-8") + path = str(tmp_path / "DECISIONS.md") + reordered = statutor_core.validate( + "write", {"file_path": path, "content": "line2\nline1\n"}, str(tmp_path), POLICY) + assert reordered is not None + assert "append-only" in reordered + dropped = statutor_core.validate( + "write", {"file_path": path, "content": "line1\n"}, str(tmp_path), POLICY) + assert dropped is not None + assert "append-only" in dropped + + +def test_invalid_utf8_governed_write_denies_instead_of_raising(tmp_path): + (tmp_path / "DECISIONS.md").write_bytes(b"# D\n\xff\n") + reason = statutor_core.validate( + "write", {"file_path": str(tmp_path / "DECISIONS.md"), "content": "# D\nmore\n"}, + str(tmp_path), POLICY) + assert isinstance(reason, str) + assert "UTF-8" in reason + + +def test_append_only_edit_drop_denies_when_body_is_invalid_utf8(tmp_path): + (tmp_path / "DECISIONS.md").write_bytes(b"kept\n\xff\n") + reason = statutor_core.validate( + "edit", + {"file_path": str(tmp_path / "DECISIONS.md"), + "old_string": "kept", "new_string": "gone"}, + str(tmp_path), POLICY) + assert reason is not None + assert "append-only" in reason + assert "new_string must contain old_string verbatim" in reason + + +def test_hook_denies_invalid_utf8_rewrite(tmp_path): + mark_ledger(tmp_path) + (tmp_path / "DECISIONS.md").write_bytes(b"# D\n\xff\n") + event = {"tool_name": "write", + "tool_input": {"file_path": str(tmp_path / "DECISIONS.md"), + "content": "# D\nmore\n"}, + "cwd": str(tmp_path)} + result = run_kernel(["hook"], input_str=json.dumps(event)) + assert result.returncode == 0 + data = _hook_deny_json(result) + assert "UTF-8" in data["hookSpecificOutput"]["permissionDecisionReason"] + + # -------------------------------------------------------------------------- # frozen (K-56..K-59) # -------------------------------------------------------------------------- @@ -866,6 +1088,34 @@ def test_apply_patch_state_malformed_addition_denied(tmp_path): assert "added state task line must use" in result +def test_apply_patch_state_new_id_must_advance(tmp_path): + (tmp_path / "TASKS.md").write_text("- [ ] T-0005 highest\n", encoding="utf-8") + low = ap(tmp_path, "*** Update File: TASKS.md\n@@\n+- [ ] T-0001 low") + assert low is not None + assert "T-0001" in low + assert "greater than existing maximum T-0005" in low + kept = ap(tmp_path, + "*** Update File: TASKS.md\n@@\n-- [ ] T-0005 highest\n+- [x] T-0005 done") + assert kept is None + higher = ap(tmp_path, "*** Update File: TASKS.md\n@@\n+- [ ] T-0006 next") + assert higher is None + + +def test_apply_patch_state_unreadable_target_denied(tmp_path): + as_dir = tmp_path / "dir-case" + as_dir.mkdir() + (as_dir / "TASKS.md").mkdir() + blocked = ap(as_dir, "*** Update File: TASKS.md\n@@\n+- [ ] T-0006 next") + assert blocked is not None + assert "cannot be read" in blocked + as_bytes = tmp_path / "byte-case" + as_bytes.mkdir() + (as_bytes / "TASKS.md").write_bytes(b"- [ ] T-0005 highest\n\xff\n") + invalid = ap(as_bytes, "*** Update File: TASKS.md\n@@\n+- [ ] T-0006 next") + assert invalid is not None + assert "UTF-8" in invalid + + @pytest.mark.parametrize("section", [ "*** Add File: plans/archive/new.md\n+x", "*** Update File: plans/archive/a1.md\n@@\n-old\n+new", @@ -1227,6 +1477,15 @@ def test_grok_truncated_governed_write_denies_other_paths_stay_silent(tmp_path): assert allowed.stdout == "" +def test_truncated_apply_patch_denies_inside_ledger(tmp_path): + denied = _grok_hook(tmp_path, { + "tool_name": "apply_patch", + "tool_input": {"command": "*** Begin Patch\n"}, + "tool_input_truncated": True, + }) + assert "truncated" in _hook_deny_json(denied)["hookSpecificOutput"]["permissionDecisionReason"] + + def test_grok_hashline_without_old_string_denies_governed_path(tmp_path): result = _grok_hook(tmp_path, { "tool_name": "hashline_edit", @@ -1390,10 +1649,36 @@ def test_check_honors_explicit_cwd_argument_over_process_cwd(tmp_path): assert "frozen" in result.stderr -def test_check_not_fail_open_on_invalid_json_quirk(): - result = run_kernel(["check", "Write", "{not json"]) - assert result.returncode == 1 - assert "Traceback" in result.stderr +@pytest.mark.parametrize("payload", ["{not json", "42", "[]", "null", '"text"']) +@pytest.mark.parametrize("prefix", [[], ["--if-ledger"]]) +def test_check_invalid_payload_has_usage_error(payload, prefix): + result = run_kernel(["check", *prefix, "Write", payload]) + assert result.returncode == 64 + assert "JSON object" in result.stderr + assert "Traceback" not in result.stderr + assert result.stdout == "" + + +def test_check_rejects_surplus_arguments(tmp_path): + result = run_kernel(["check", "write", "{}", str(tmp_path), "extra"]) + assert result.returncode == 64 + assert "usage: statutor check" in result.stderr + + +@pytest.mark.parametrize("command", [["check"], ["check", "--if-ledger"], + ["staged"], ["trust", "approve"]]) +@pytest.mark.parametrize("flag", ["--help", "-h"]) +def test_command_help_without_ledger(command, flag, tmp_path): + result = run_kernel([*command, flag], cwd=str(tmp_path)) + assert result.returncode == 0 + assert result.stdout.startswith("usage: statutor ") + assert result.stderr == "" + + +def test_staged_rejects_surplus_arguments(tmp_path): + result = run_kernel(["staged", str(tmp_path), "extra"]) + assert result.returncode == 64 + assert "usage: statutor staged" in result.stderr # -------------------------------------------------------------------------- @@ -1403,7 +1688,9 @@ def test_check_not_fail_open_on_invalid_json_quirk(): def test_cli_unknown_mode(): result = run_kernel(["bogus"]) assert result.returncode == 64 - assert "typed project-ledger kernel" in result.stdout + assert "unknown command: bogus" in result.stderr + assert "statutor --help" in result.stderr + assert result.stdout == "" # -------------------------------------------------------------------------- diff --git a/tests/test_package_payloads.py b/tests/test_package_payloads.py index 258a903..869b3b2 100644 --- a/tests/test_package_payloads.py +++ b/tests/test_package_payloads.py @@ -92,7 +92,7 @@ def _archive_payload(path: Path, expected_root: str) -> dict[str, bytes]: def test_package_metadata_is_explicit_and_versioned() -> None: cargo_table = _cargo_package_table() cargo_version = _cargo_value(cargo_table, "version") - assert cargo_version == "0.1.2" + assert cargo_version == "0.1.3" assert _cargo_array(cargo_table, "include") == CARGO_INCLUDE cargo_lock = (CRATE / "Cargo.lock").read_text(encoding="utf-8") diff --git a/tests/test_public_claims.py b/tests/test_public_claims.py index c8e9bf4..bee567e 100644 --- a/tests/test_public_claims.py +++ b/tests/test_public_claims.py @@ -20,8 +20,8 @@ def test_install_snippets_use_real_repository_and_supported_pin() -> None: assert f"/plugin marketplace add {expected_repo}" in root assert f"repo: {expected_repo}" in root assert f"repo: {expected_repo}" in git_adapter - assert "rev: v0.7.4" in root - assert "rev: v0.7.4" in git_adapter + assert "rev: v0.7.5" in root + assert "rev: v0.7.5" in git_adapter for stale in ("", "", "", "rev: v0.2.0", "rev: v0.4.0", "rev: v0.5.0", "rev: v0.5.1", "rev: v0.6.0"): assert stale not in root assert stale not in git_adapter @@ -60,7 +60,8 @@ def test_codex_and_shared_hook_match_apply_patch() -> None: matcher = hooks["hooks"]["PreToolUse"][0]["matcher"] assert matcher == ( "^(Write|Edit|Bash|apply_patch|write|search_replace|hashline_edit|" - "run_terminal_command|StrReplace|Shell)$") + "run_terminal_command|run_terminal_cmd|StrReplace|Shell|" + "MultiEdit|NotebookEdit|Delete)$") grok = _read("adapters/grok/README.md") assert matcher in grok assert "nearest `.statutor.yaml` marker" in grok @@ -77,6 +78,9 @@ def test_automatic_adapters_are_explicit_ledger_only() -> None: assert "statutor check --if-ledger" in opencode_source grok = _read("adapters/grok/README.md") assert "nearest `.statutor.yaml` marker" in grok + cursor = _read("adapters/cursor/README.md") + assert "nearest `.statutor.yaml` marker" in cursor + assert "always emits a permission object" in cursor def test_ci_keeps_dependency_free_matrix_and_complete_release_audit() -> None: diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py index 3efa8c0..5124130 100644 --- a/tests/test_release_gate.py +++ b/tests/test_release_gate.py @@ -20,11 +20,11 @@ def test_release_versions_are_explicit_and_compatible() -> None: assert release_gate.versions(ROOT) == { - "python": "0.7.4", - "plugin": "0.7.4", - "antigravity": "0.7.4", + "python": "0.7.5", + "plugin": "0.7.5", + "antigravity": "0.7.5", "npm": "0.2.0", - "cargo": "0.1.2", + "cargo": "0.1.3", } @@ -44,7 +44,7 @@ def test_python_and_plugin_versions_must_match(tmp_path: Path) -> None: data = json.loads(plugin.read_text(encoding="utf-8")) data["version"] = "9.9.9" plugin.write_text(json.dumps(data), encoding="utf-8") - with pytest.raises(RuntimeError, match="Python 0.7.4 != Claude plugin 9.9.9"): + with pytest.raises(RuntimeError, match="Python 0.7.5 != Claude plugin 9.9.9"): release_gate.versions(tmp_path) diff --git a/tests/test_stop_hook.py b/tests/test_stop_hook.py index c240ebf..707b755 100644 --- a/tests/test_stop_hook.py +++ b/tests/test_stop_hook.py @@ -41,6 +41,78 @@ def test_malformed_event_metadata_fails_open(event: dict) -> None: assert result.stderr == "" +def test_empty_workspace_paths_does_not_doctor_process_cwd(tmp_path) -> None: + _scaffold(tmp_path) + (tmp_path / "TASKS.md").unlink() + event = { + "executionNum": 1, + "workspacePaths": [], + "terminationReason": "model_stop", + } + result = subprocess.run( + [sys.executable, str(STOP_HOOK)], + input=json.dumps(event), cwd=str(tmp_path), + capture_output=True, text=True, + ) + assert result.returncode == 0 + assert json.loads(result.stdout)["decision"] == "allow" + + +def test_cursor_empty_workspace_roots_does_not_doctor_process_cwd(tmp_path) -> None: + _scaffold(tmp_path) + (tmp_path / "TASKS.md").unlink() + event = { + "hook_event_name": "stop", + "status": "completed", + "workspace_roots": [], + } + result = subprocess.run( + [sys.executable, str(STOP_HOOK)], + input=json.dumps(event), cwd=str(tmp_path), + capture_output=True, text=True, + ) + assert result.returncode == 0 + assert result.stdout.strip() == "" + + +def test_cursor_stop_hook_emits_native_followup_once(tmp_path): + _scaffold(tmp_path) + (tmp_path / "TASKS.md").unlink() + event = {"hook_event_name": "stop", "status": "completed", + "loop_count": 0, "workspace_roots": [str(tmp_path)]} + result = run_stop_hook(json.dumps(event)) + assert result.returncode == 0 + out = json.loads(result.stdout) + assert set(out) == {"followup_message"} + assert "missing governed file: TASKS.md" in out["followup_message"] + event["loop_count"] = 1 + result = run_stop_hook(json.dumps(event)) + assert result.returncode == 0 + assert result.stdout == "" + + +@pytest.mark.parametrize("status", ["aborted", "error"]) +def test_cursor_stop_hook_failed_turn_stays_silent(tmp_path, status): + _scaffold(tmp_path) + (tmp_path / "TASKS.md").unlink() + result = run_stop_hook(json.dumps({ + "hook_event_name": "stop", "status": status, + "loop_count": 0, "workspace_roots": [str(tmp_path)], + })) + assert result.returncode == 0 + assert result.stdout == "" + + +def test_cursor_stop_hook_clean_scaffold_stays_silent(tmp_path): + _scaffold(tmp_path) + result = run_stop_hook(json.dumps({ + "hook_event_name": "stop", "status": "completed", + "loop_count": 0, "workspace_roots": [str(tmp_path)], + })) + assert result.returncode == 0 + assert result.stdout == "" + + def _scaffold(root: Path) -> None: statutor_core.run_init(str(root)) diff --git a/tests/test_worker.py b/tests/test_worker.py index fb780d0..f146307 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -108,7 +108,7 @@ def test_unknown_role_survives_without_inference(tmp_path: Path) -> None: assert begun["session"]["origin_harness"] == "unknown" -@pytest.mark.parametrize("harness", ["claude", "grok"]) +@pytest.mark.parametrize("harness", ["claude", "grok", "cursor"]) def test_automatic_harness_cannot_record_mutation(tmp_path: Path, harness: str) -> None: state = _state(tmp_path) repo = _repo(tmp_path, "repo") @@ -138,6 +138,42 @@ def test_complete_cas_rejects_second_session(tmp_path: Path) -> None: session_id=second["session"]["session_id"]) +def test_complete_uses_policy_overwrite_bounded_filename(tmp_path: Path) -> None: + state = _state(tmp_path) + repo = tmp_path / "renamed" + repo.mkdir() + _git(repo, "init", "-q") + _git(repo, "config", "user.email", "test@example.com") + _git(repo, "config", "user.name", "Test") + (repo / ".statutor.yaml").write_text( + "bash_guard: true\n" + "governed:\n" + " - pattern: STATUS.md\n" + " policy: overwrite_bounded\n" + " max_lines: 40\n", + encoding="utf-8") + machine, _ = worker.ensure_machine(state) + (repo / "STATUS.md").write_text( + "# STATUS\n\nlast_verified: 2026-10-22 by test\n" + "last_worker: human\nlast_machine: " + + str(machine["machine_id"]) + + "\nhandoff_id: abc123\nsupersedes: none\n", + encoding="utf-8") + _git(repo, "add", "-A") + _git(repo, "commit", "-qm", "init") + begun = worker.worker_begin(state, str(repo), harness="human") + assert begun["session"]["baseline_handoff_id"] == "abc123" + (repo / "STATUS.md").write_text( + "# STATUS\n\nlast_verified: 2026-10-22 by test\n" + "last_worker: human\nlast_machine: " + + str(machine["machine_id"]) + + "\nhandoff_id: def456\nsupersedes: abc123\n", + encoding="utf-8") + done = worker.worker_complete(state, str(repo), + session_id=begun["session"]["session_id"]) + assert done["record"]["handoff_id"] == "def456" + + def test_complete_requires_fresh_id_and_supersedes(tmp_path: Path) -> None: state = _state(tmp_path) repo = _repo(tmp_path, "repo") diff --git a/tests/test_worker_integration.py b/tests/test_worker_integration.py index 17b56a7..ca318f8 100644 --- a/tests/test_worker_integration.py +++ b/tests/test_worker_integration.py @@ -89,6 +89,57 @@ def test_first_completion_from_attributed_baseline(tmp_path: Path) -> None: assert done["reconciled"] is None +@pytest.mark.parametrize("legacy", [False, True]) +def test_completion_retry_preserves_record_and_registry( + tmp_path: Path, legacy: bool) -> None: + state = _state(tmp_path) + machine, _ = worker.ensure_machine(state) + block = "" if legacy else ATTRIBUTED.format( + mid=machine["machine_id"], hid="h0", sup="none") + repo = _repo(tmp_path, "repo", block) + begun = worker.worker_begin(state, str(repo), harness="claude") + sid = begun["session"]["session_id"] + if not legacy: + (repo / "HANDOFF.md").write_text(_handoff(ATTRIBUTED.format( + mid=machine["machine_id"], hid="h1", sup="h0"))) + done = worker.worker_complete(state, str(repo), session_id=sid) + registry = worker._registry_path(state, begun["project_id"]) + before = registry.read_bytes() + with pytest.raises(worker.WorkerError, match="session already completed") as error: + worker.worker_complete(state, str(repo), session_id=sid) + assert "worker show --basis completed" in str(error.value) + assert "reconcile" not in str(error.value) + assert registry.read_bytes() == before + assert worker.worker_show(state, str(repo))["record"] == done["record"] + assert worker.worker_active(state, str(repo))["leases"] == [] + + +@pytest.mark.parametrize("change", ["body", "id", "machine"]) +def test_completed_session_cannot_claim_changed_handoff( + tmp_path: Path, change: str) -> None: + state = _state(tmp_path) + machine, _ = worker.ensure_machine(state) + repo = _repo(tmp_path, "repo", ATTRIBUTED.format( + mid=machine["machine_id"], hid="h0", sup="none")) + begun = worker.worker_begin(state, str(repo), harness="claude") + sid = begun["session"]["session_id"] + path = repo / "HANDOFF.md" + path.write_text(_handoff(ATTRIBUTED.format( + mid=machine["machine_id"], hid="h1", sup="h0"))) + worker.worker_complete(state, str(repo), session_id=sid) + if change == "machine": + worker.rotate_machine(state, confirm=True) + else: + text = path.read_text() + path.write_text(text + "changed\n" if change == "body" + else text.replace("handoff_id: h1", "handoff_id: h2")) + registry = worker._registry_path(state, begun["project_id"]) + before = registry.read_bytes() + with pytest.raises(worker.WorkerError, match="already completed"): + worker.worker_complete(state, str(repo), session_id=sid) + assert registry.read_bytes() == before + + # -------------------------------------------------------------------------- # same-machine sibling reconciliation # -------------------------------------------------------------------------- @@ -115,6 +166,12 @@ def test_reconciliation_absorbing_sibling_completes(tmp_path: Path) -> None: done = worker.worker_complete(state, str(repo), session_id=sid) assert done["record"]["handoff_id"] == "hC" assert set(done["reconciled"]) == {"h0", "hA"} + path = worker._registry_path(state, done["project_id"]) + before = path.read_bytes() + with pytest.raises(worker.WorkerError, match="session already completed"): + worker.worker_complete(state, str(repo), session_id=sid) + assert path.read_bytes() == before + assert worker.worker_show(state, str(repo))["record"] == done["record"] def test_reconciliation_ignoring_sibling_rejected(tmp_path: Path) -> None: @@ -125,6 +182,34 @@ def test_reconciliation_ignoring_sibling_rejected(tmp_path: Path) -> None: worker.worker_complete(state, str(repo), session_id=sid) +def test_old_completion_retry_cannot_replace_newer_local_completion( + tmp_path: Path) -> None: + state = _state(tmp_path) + machine, _ = worker.ensure_machine(state) + repo = _repo(tmp_path, "repo", ATTRIBUTED.format( + mid=machine["machine_id"], hid="h0", sup="none")) + first = worker.worker_begin(state, str(repo), harness="claude") + path = repo / "HANDOFF.md" + first_text = _handoff(ATTRIBUTED.format( + mid=machine["machine_id"], hid="hA", sup="h0")) + path.write_text(first_text) + worker.worker_complete(state, str(repo), + session_id=first["session"]["session_id"]) + second = worker.worker_begin(state, str(repo), harness="claude") + path.write_text(_handoff(ATTRIBUTED.format( + mid=machine["machine_id"], hid="hB", sup="hA"))) + latest = worker.worker_complete(state, str(repo), + session_id=second["session"]["session_id"]) + path.write_text(first_text) + registry = worker._registry_path(state, first["project_id"]) + before = registry.read_bytes() + with pytest.raises(worker.WorkerError, match="already completed"): + worker.worker_complete(state, str(repo), + session_id=first["session"]["session_id"]) + assert registry.read_bytes() == before + assert worker.worker_show(state, str(repo))["record"] == latest["record"] + + # -------------------------------------------------------------------------- # crashes: expiry never labels completion; newcomers proceed # -------------------------------------------------------------------------- @@ -166,7 +251,7 @@ def test_expired_session_may_still_complete_explicitly(tmp_path: Path) -> None: def test_capabilities_pin_surfaces_and_gaps() -> None: caps = worker.all_capabilities() assert set(caps["capabilities"]) == set(worker.HARNESSES) - for auto in ("claude", "codex", "opencode", "grok"): + for auto in ("claude", "codex", "opencode", "grok", "cursor"): entry = caps["capabilities"][auto] assert entry["proves_mutation"] is False assert entry["proves_completion"] is False @@ -262,6 +347,85 @@ def test_cli_record_outside_ledger_denied( assert code == 1 +@pytest.mark.parametrize("mode", ["machine", "worker"]) +@pytest.mark.parametrize("position", ["before", "after", "override"]) +def test_cli_root_options_reach_resolver( + tmp_path: Path, capsys: pytest.CaptureFixture, + monkeypatch: pytest.MonkeyPatch, mode: str, position: str) -> None: + expected = {name: str(tmp_path / name) + for name in ("home", "config_root", "state_root")} + seen = [] + resolve = worker.substrate.resolve_roots + + def capture(**kwargs): + seen.append(kwargs) + return resolve(**kwargs) + + monkeypatch.setattr(worker.substrate, "resolve_roots", capture) + monkeypatch.setenv("HOME", str(tmp_path / "fallback-home")) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "fallback-config")) + monkeypatch.setenv("XDG_STATE_HOME", str(tmp_path / "fallback-state")) + options = [item for name, value in expected.items() + for item in ("--" + name.replace("_", "-"), value)] + command = "show" if mode == "machine" else "capabilities" + if position == "before": + argv = [mode, *options, command, "--json"] + elif position == "after": + argv = [mode, command, *options, "--json"] + else: + parent_options = [item for name in expected + for item in ("--" + name.replace("_", "-"), + str(tmp_path / ("parent-" + name)))] + argv = [mode, *parent_options, command, *options, "--json"] + assert _cli(argv, capsys)[0] == 0 + assert seen[-1] == expected + + +@pytest.mark.parametrize("position", ["before", "after"]) +def test_cli_state_root_contains_entire_worker_flow_and_rotation( + tmp_path: Path, capsys: pytest.CaptureFixture, + monkeypatch: pytest.MonkeyPatch, position: str) -> None: + state = _state(tmp_path, "explicit-state") + fallback = tmp_path / "fallback-state" + monkeypatch.setenv("HOME", str(tmp_path / "fake-home")) + monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "fake-config")) + monkeypatch.setenv("XDG_STATE_HOME", str(fallback)) + repo = _repo(tmp_path, "repo", "") + + def run(mode, command, *options): + roots = ["--state-root", str(state)] + argv = ([mode, *roots, command] if position == "before" + else [mode, command, *roots]) + code, result = _cli([*argv, *options, "--json"], capsys) + assert code == 0 + return result + + machine = run("machine", "show")["machine"] + assert (state / "machine.json").is_file() + run("machine", "set-label", "explicit-only") + begun = run("worker", "begin", "--harness", "human", "--cwd", str(repo)) + sid = begun["session"]["session_id"] + run("worker", "record", "--harness", "human", "--event", "activity", + "--session", sid, "--cwd", str(repo)) + assert run("worker", "active", "--cwd", str(repo))["leases"] + completed = run("worker", "complete", "--session", sid, "--cwd", str(repo)) + roots = ["--state-root", str(state)] + retry = (["worker", *roots, "complete"] if position == "before" + else ["worker", "complete", *roots]) + code, _ = _cli([*retry, "--session", sid, "--cwd", str(repo), "--json"], capsys) + assert code == 1 + assert run("worker", "show", "--cwd", str(repo))["record"] == completed["record"] + run("worker", "compare", "HEAD", "--cwd", str(repo)) + run("worker", "capabilities") + run("worker", "new-id") + rotated = run("machine", "rotate", "--confirm") + assert rotated["previous_machine_id"] == machine["machine_id"] + assert rotated["machine"]["machine_id"] != machine["machine_id"] + assert json.loads((state / "machine.json").read_text())["machine_id"] == \ + rotated["machine"]["machine_id"] + assert not (fallback / "statutor").exists() + + # -------------------------------------------------------------------------- # two fake machines, one git history (plan acceptance: pulled HANDOFF names # the remote completing machine without importing its local state)