Skip to content

Forward Cursor file-read hooks as steps/toolCallRequest (#212) - #807

Open
almogbhl wants to merge 2 commits into
integrationfrom
refimpl/212-cursor-read-hooks
Open

almogbhl wants to merge 2 commits into
integrationfrom
refimpl/212-cursor-read-hooks

Conversation

@almogbhl

@almogbhl almogbhl commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

What changed

Map Cursor's beforeReadFile and beforeTabFileRead hooks to steps/toolCallRequest (Read and TabRead) carrying file_path, content, and optional attachments, so a Guardian can inspect and block sensitive file reads before Cursor passes them to the model or Tab completions.

Key details:

  • hook.py & adapter.py: Emit each hook's documented output shape ({"permission": "allow"} or {"permission": "deny", "user_message": ...} on beforeReadFile; {"permission": "allow"} or {"permission": "deny"} on beforeTabFileRead). Substitute ask and defer to deny (audited as unenforceable_decision), and modify to deny (audited as modify_unsupported).
  • Live Cursor replay fix (adapter.py): Real Cursor sends the same tool_use_id on both preToolUse and beforeReadFile for a single Read call. Pin the deterministic uuid5 request_id only on preToolUse (for postToolUse request_id_ref correlation) and issue a fresh uuid4 on tool-specific hooks so beforeReadFile never collides with preToolUse as a replay.
  • wire.py: Add beforeReadFile and beforeTabFileRead to GATE_HOOKS (failClosed: true and ACS_DEFAULT_DENY=1) when opted in via --hooks, and clean up optional hooks on acs-cursor-wire --unwire without --hooks.
  • Tests & docs: Add schema emission, allow/deny/ask/modify conformance, replay-collision, fail-closed gate, and wire/unwire tests, and update the Cursor adapter docs (mapping.md, README.md, example_payloads.md).

Which issue does this implement

Closes #212

  • This is an editorial correction (typo, grammar, link, formatting) with no change in
    meaning, so it needs no issue

Base branch

  • integration. Every pull request targets integration, documentation included.
    Only a promotion targets main (see CONTRIBUTING.md)
  • release/0.2, because this changes normative specification text, a schema, or a
    conformance requirement for 0.2, or carries out such a change in code

Type of change

  • Specification change (schema, hooks, events, AgBOM)
  • Reference implementation or adapter
  • Documentation
  • Tooling or CI
  • Governance (licensing, security policy, contributor docs)

I tested this

  • I synced my branch with the base branch before opening this
  • uv run pytest -v passes on my machine
  • uv run mkdocs build --strict passes on my machine

Also verified:

  • lint-imports (2 contracts kept, 0 broken) and adapters Cursor conformance suite (584 passed, 0 failed, plus new replay regression test)
  • Live manual verification in Cursor against acs-example-guardian + OPA (beforeReadFile and beforeTabFileRead allow and deny paths)

Checklist

  • Commits are signed off with git commit -s (required by the DCO)
  • Prose follows STYLE.md
  • No secrets, tokens, or internal URLs in the diff

Security

  • This change has no security impact

Governs Cursor file reads (beforeReadFile and beforeTabFileRead) fail-closed when wired (failClosed: true and ACS_DEFAULT_DENY=1), closing the Cursor read-path gap tracked in #212, and prevents tool_use_id-derived request_id collisions across preToolUse and tool-specific hooks.

@github-actions

github-actions Bot commented Dec 4, 2026

Copy link
Copy Markdown

This pull request's description says it closes #212, which is on the project roadmap. When it merges, GitHub closes that issue and the roadmap counts it as delivered. Please confirm the change delivers the whole issue before merging.

@almogbhl
almogbhl force-pushed the refimpl/212-cursor-read-hooks branch from c18e82d to c3e9a0e Compare December 4, 2026 16:03
@almogbhl almogbhl self-assigned this Dec 4, 2026

@rocklambros rocklambros left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, @almogbhl. The read gates are useful, and much of this PR is solid. Every new test fails on the base branch and passes on your branch, every fail-closed path denies, and CI is green.

I found three things I think need a fix before merge. Details are below, each with a way to check the fix. I also have five questions and suggestions that do not block the merge.

Before merge

  1. adapters/tests/integrations/cursor/test_adapter.py:79: the new replay test passes only once on a developer machine. The second local run fails with -32005 REPLAY_DETECTED. Details are in the inline comment.
  2. adapters/src/acs/integrations/cursor/adapter.py:237: the read gates send the full file content to the Guardian. A file larger than about 1 MiB is always denied, and the README does not say that file content leaves the machine. Details are in the inline comment.
  3. adapters/docs/cursor/README.md:328: the docs read as if file reads are governed by default. The default wiring does not include the two read gates. Details are in the inline comment.

Questions and suggestions (optional)

  1. Did you check in live Cursor whether {"permission": "allow"} from beforeReadFile can override Cursor's own read protections, such as .cursorignore? Cursor's docs do not say. I could not check this myself.
  2. When preToolUse is not wired, I think the request_id_ref link for a file read is lost. Decision D-016 in docs/decisions/index.md covers how request_id_ref is resolved. Is the missing link intended in that case?
  3. adapters/src/acs/integrations/cursor/wire.py:378: the --unwire help text does not mention the two new hooks. If you have time, maybe build the unwire list from HOOK_MAP? Then the two lists always name the same hooks.
  4. wire.py sets a hook timeout only for sessionEnd. The beforeTabFileRead gate runs while the user types, so a slow Guardian may delay Tab completions. Would a short timeout on that gate help?
  5. adapters/docs/cursor/example_payloads.md shows only the response shapes for beforeReadFile and beforeTabFileRead. A stdin example for each hook would help adapter authors.

What I checked

  • Commit reviewed: c3e9a0e9be36137536f9ee9702541c23f1165da6.
  • Conformance suites: with nat, 824 passed. Without nat, everything passed except the replay test in item 1, on a second run.
  • Example Guardian suite: 611 passed. The ML-DSA-65 suites and the Go interop check passed.
  • Wheel build and wheel check on Python 3.11 and 3.12 passed. The gateway suite passed with 928 tests. The labs pytest jobs passed.
  • Repository pytest: 9382 passed. The import-boundary check passed.
  • The 23 new tests fail on the base branch and pass on your branch.
  • End to end, acs-cursor-hook beforeReadFile returned allow, deny, and deny on an unreachable Guardian, each in Cursor's response shape.
  • The docs' claims about the 19 mapped events match HOOK_MAP.
  • A security review of the diff found no other problems.
  • CI: 29 checks pass and 1 is skipped.

self.assertEqual(rc, 0, err)
self.assertEqual(json.loads(out), {}, "an allow leaves the call to Cursor's own sandbox and approval")

def test_pre_tool_use_then_before_read_file_sharing_tool_use_id_does_not_replay(self) -> None:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this test needs a fix before merge, because it passes only once on a developer machine.

The test uses a fixed session_id ("cur-read-seq") and a fixed tool_use_id. So the uuid5 request_id is the same on every run. The CursorAdapter class starts the example Guardian without ACS_GUARDIAN_STATE_DIR. So the Guardian stores the seen request_id values in ~/.cache/acs-guardian-state, and they stay there after the run.

The first local run passes. The second local run fails with -32005 REPLAY_DETECTED. CI passes only because each runner starts empty. CONTRIBUTING asks contributors to run run_conformance.py locally, so after one run that command fails for everyone. The test also writes to the developer's real ~/.cache.

Could you give the Guardian a temporary state directory in setUpClass? adapters/tests/common/test_edge_cases.py:65 does the same thing:

@classmethod
def setUpClass(cls) -> None:
    env = {k: v for k, v in os.environ.items() if k != "ACS_HMAC_SECRET_FILE"}
    env.update(signing_env())
    cls.statedir = tempfile.mkdtemp(prefix="acs-guardian-state-")
    env["ACS_GUARDIAN_STATE_DIR"] = cls.statedir
    cls.guardian_proc, cls.port = launch_guardian(env=env)

Please also remove the directory in tearDownClass with shutil.rmtree(cls.statedir, ignore_errors=True), and add import shutil at the top of the file.

A fresh tool_use_id on each run also works, for example f"toolu_shared_read_{uuid.uuid4().hex}", used on both calls. I ran each fix three times in a row, and the test passed every time.

To check the fix, run this command twice in a row. Both runs should pass:

uv run python -m pytest adapters/tests/integrations/cursor/test_adapter.py -k does_not_replay

Comment on lines +237 to +243
def _payload_before_read(event: dict[str, Any], *, tool_name: str = "Read") -> dict[str, Any]:
args: dict[str, Any] = {"file_path": event.get("file_path", "")}
if event.get("content") is not None:
args["content"] = event["content"]
if isinstance(event.get("attachments"), list):
args["attachments"] = event["attachments"]
return {"tool": {"name": tool_name}, "arguments": _wrap_arguments(args)}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this needs a fix before merge, because large file reads are now always denied.

_payload_before_read puts the full file content into arguments.content. A file over about 1 MiB makes the request larger than the maximum payload size. The same happens with about 525 KB of CJK text, because JSON escapes each character. The adapter then denies the read with request_exceeds_max_payload, even with ACS_DEFAULT_DENY=0. The Guardian receives no request at all. So a legitimate read is denied in every posture, which did not happen before this PR.

Could you cap the content and send its length and a SHA-256 hash above the cap? For example:

_MAX_INLINE_CONTENT_BYTES = 512 * 1024


def _payload_before_read(event: dict[str, Any], *, tool_name: str = "Read") -> dict[str, Any]:
    args: dict[str, Any] = {"file_path": event.get("file_path", "")}
    content = event.get("content")
    if content is not None:
        encoded = json.dumps(content).encode("utf-8")
        if len(encoded) <= _MAX_INLINE_CONTENT_BYTES:
            args["content"] = content
        else:
            raw = content.encode("utf-8") if isinstance(content, str) else encoded
            args["content_length"] = len(raw)
            args["content_sha256"] = hashlib.sha256(raw).hexdigest()
    if isinstance(event.get("attachments"), list):
        args["attachments"] = event["attachments"]
    return {"tool": {"name": tool_name}, "arguments": _wrap_arguments(args)}

Could you also add a test that reads a 2 MB file through beforeReadFile? The test should check that the Guardian receives the request and that the answer is {"permission": "allow"}.

There is a second point about the same lines. The full content goes to the Guardian before the read, and that includes files such as .env. The other adapters send only the path before a read. Today only mapping.md:23 mentions the content. Could you add one sentence to adapters/docs/cursor/README.md? For example:

`beforeReadFile` and `beforeTabFileRead` send the file's content to the Guardian before Cursor reads the file. Content above 512 KiB is sent as its length and SHA-256 hash.

Comment thread adapters/docs/cursor/README.md Resolved
@acs-board-reconciler acs-board-reconciler Bot moved this from Needs triage to In progress in ACS Project Tracker Dec 5, 2026
@bar-capsule

Copy link
Copy Markdown
Collaborator

@almogbhl thanks, this closes the gap #212 describes. I reproduced Rock's first two blockers here too, and a large file is denied even with ACS_DEFAULT_DENY=0. Two more points:

  1. beforeReadFile sends the file's content in a toolCallRequest, while the Claude Code adapter sends a read's content as the Read tool's toolCallResult. So a Guardian rule that inspects read content has to look in two places depending on the host. Is that intended, or should the content go out as a toolCallResult?
  2. On Rock's item 7: Tab reads run while the user types, so I'd measure the latency each gate adds before we suggest wiring them by default.

Signed-off-by: almogbhl <almogbh.l@gmail.com>
…t state (#212)

Signed-off-by: almogbhl <almogbh.l@gmail.com>
@almogbhl
almogbhl force-pushed the refimpl/212-cursor-read-hooks branch from 35e9d0e to ab3c670 Compare December 5, 2026 17:08
@almogbhl

almogbhl commented Dec 5, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks @rocklambros and @bar-capsule for the careful reviews, and for reproducing the blockers. The new commit fixes all three blockers.

Fixed:

  1. The test now keeps its replay state in a temporary directory, so a second local run passes.
  2. Content above 512 KiB now goes to the Guardian as its length and SHA-256 hash, not the full text. So a large file is no longer always denied. A new test covers ASCII and CJK files for both hooks. The README now says that both hooks send the file's content to the Guardian.
  3. The README and mapping.md now say the read gates are opt-in, and the README shows the --hooks command that wires them.

Questions:

  1. Checked in live Cursor. With hello.txt in .cursorignore and the Guardian allowing it, Cursor refused the read ("Permission denied") before calling beforeReadFile. So Cursor's own list wins, and our allow can't override it.
  2. Yes, that's intended. D-016 covers it: an unresolved or missing request_id_ref is recorded, and the Guardian's policy decides what to do.
  3. A bare --unwire now removes the ACS entry from every event, and --hooks narrows it. So there is no separate list to keep in sync.
  4. and Bar's point 2: I agree we should measure first. The adapter already uses the shared 5 s timeout. The read gates stay opt-in, and we can pick a Tab timeout once we have the numbers.
  5. Added a stdin example for each hook to example_payloads.md. They're built from Cursor's docs, not captured.

Bar's point 1: Yes, for Cursor that's intended. I checked the current hooks docs for all four hosts.
Cursor is the only one that shows the file content before the read, and its after-read hook can't replace file output, so the request is the only place we can stop it.

Claude Code, Codex and OpenCode work the other way: they can replace the tool's output after the read, before the model sees it. Our Codex and OpenCode adapters don't use that yet.

So a rule that checks read content has to look in a different place for each host.
Should we open a Discussion about putting it in one place?

@almogbhl
almogbhl requested a review from rocklambros December 5, 2026 17:17

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: In progress

Development

Successfully merging this pull request may close these issues.

Forward Cursor's file-read hooks so a Guardian can govern file reads

3 participants