Skip to content

feat(hooks): durably spool Claude and Codex events (#2781) - #2781

Merged
Sinity merged 5 commits into
masterfrom
feature/fanout/hooks-capture
Jul 12, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/fanout/hooks-capture

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner

Summary

Adds crash-safe local hook-event capture for Claude Code and Codex. Each hook invocation atomically creates an immutable pending envelope; the daemon persists it in source.db and moves it to acknowledged only after the raw_hook_events write commits.

Problem

The existing hook command appended session JSONL sidecars, but the live watcher classified those sidecars as non-session artifacts and excluded them before the source-tier materializer ran. Events could therefore be configured yet never become queryable evidence.

Solution

  • Add polylogue.sources.hooks with atomic pending/acknowledged spool directories, record validation, and stable-event-id replay.
  • Route polylogue-hook for both Claude Code and Codex through the durable spool while retaining the legacy journal for local-tool compatibility.
  • Watch pending envelopes directly and drain them at startup/periodic catch-up; failed writes remain pending.
  • Regenerate the topology projection after adding the new source module.

Acceptance criteria

Criterion Status
Claude Code and Codex events are captured going forward into a queryable table Satisfied: both providers land in source.db.raw_hook_events before acknowledgement.
polylogue-9e5.10 can rerun with observed events Satisfied for new Claude/Codex sessions after hook installation and daemon drain.
Hermes coverage is folded into or investigated against fs1 scope Deferred: polylogue-fs1.7 owns the Hermes atomic lifecycle spool; this change does not touch Hermes parser or spool work.

Anti-vacuity evidence

  • test_hook_spool_acknowledges_only_after_source_tier_materialization exercises enqueue_hook_event → drain_hook_event_spool → ArchiveStore/write_source_raw_session → real SQLite raw_hook_events for Claude Code and Codex. Removing source-tier persistence or acknowledging before it commits makes the assertion fail.
  • test_hook_spool_keeps_event_pending_when_source_tier_write_fails exercises the receiver failure path against an unusable archive target. Removing the no-ack-on-error branch falsely moves the real pending file and fails.
  • test_hook_spool_replay_is_idempotent_after_interrupted_acknowledgement replays an already persisted envelope through the production drain. Removing stable event identity/upsert semantics produces more than one durable event row.

Verification

  • nix develop --command devtools test tests/unit/sources -k hook — 75 passed.
  • nix develop --command mypy polylogue/sources/hooks.py polylogue/sources/live/watcher.py polylogue/hooks/__init__.py — Success: no issues found in 3 source files.
  • nix develop --command devtools verify --quick — success (format, lint, mypy, generated surfaces, topology, layering, schema roundtrip, and remaining quick gates).

Ref polylogue-qqyg

@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 15 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 587b5f6f-921c-4897-a46c-79b7706e3b71

📥 Commits

Reviewing files that changed from the base of the PR and between 8ec9955 and d03f900.

📒 Files selected for processing (10)
  • contrib/polylogue-hook
  • docs/hooks.md
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • packaging/polylogue-hooks/README.md
  • packaging/polylogue-hooks/src/polylogue_hooks/cli.py
  • polylogue/hooks/__init__.py
  • polylogue/sources/hooks.py
  • polylogue/sources/live/watcher.py
  • tests/unit/sources/test_hook_spool.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fanout/hooks-capture

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity Sinity changed the title feat(hooks): durably spool Claude and Codex events feat(hooks): durably spool Claude and Codex events (#2781) Jul 12, 2026
@Sinity
Sinity marked this pull request as ready for review July 12, 2026 21:27

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c269d106df

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/sources/hooks.py Resolved
Comment thread polylogue/sources/hooks.py Resolved
@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 1

Independent review found two real gaps:

  1. A daemon started before the first hook did not watch the later-created nested pending/ directory.
  2. sqlite3.Error could escape the receiver drain, leaving a pending envelope but also terminating the watcher path instead of recording retryable debt.

Fixed in 969dc96e9:

  • Create the hook pending directory before awatch snapshots roots.
  • Drain the exact root owned by the watcher’s hooks WatchSource; this also makes POLYLOGUE_HOOK_SIDECAR_DIR a shared producer/daemon override.
  • Retain SQLite write failures as pending, fsync directory metadata after atomic publish/acknowledgement, and update operator docs to the actual receipt protocol.
  • Add real watcher startup-after-absent-spool, configured-root, SQLite-failure, persistence-before-ack, and replay-idempotency tests.

Verification: POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-pytest nix develop --command devtools test tests/unit/sources/test_hook_spool.py → 7 passed; narrow mypy clean; pre-push devtools verify --quick passed.

What survived scrutiny: Hermes remains correctly deferred to polylogue-fs1.7; the source-tier receipt and stable-event replay claims are covered by real SQLite tests.

@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 2

Independent review found one real gap: the new spool tests began at enqueue_hook_event, so deleting the installed polylogue-hook entrypoint wiring could leave every new test green.

Fixed in a61bbaeb4:

  • Add a parameterized Claude Code/Codex production test that invokes hook_main, inspects the immutable pending envelope, drains it, and asserts the real source.db.raw_hook_events receipt.
  • Narrow docs/hooks.md from an unsupported “100% data coverage” claim to capture of configured events that supplements post-hoc JSONL.

Verification: POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-pytest nix develop --command devtools test tests/unit/sources/test_hook_spool.py → 9 passed; narrow mypy clean; pre-push devtools verify --quick passed.

What survived scrutiny: pending/acknowledged crash semantics, custom spool-root watcher wiring, SQLite retry retention, and Hermes deferral to polylogue-fs1.7 remain supported by code and focused tests.

@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 3

Independent review found one real closure failure: the documented standalone polylogue-hooks package and contrib/polylogue-hook script still used the old journal-only path, even though the docs recommended the standalone package.

Fixed in 0635e599a:

  • Port atomic pending-envelope publication and directory fsync to the standalone Python package and contrib shell script.
  • Add a production test that launches each published adapter, drains its real pending envelope, and asserts the source-tier receipt.
  • Correct installation/adapter docs so they describe the common durable protocol and limit the legacy journal note to the bundled command.

Verification: POLYLOGUE_PYTEST_BASETEMP_ROOT=/realm/tmp/polylogue-pytest nix develop --command devtools test tests/unit/sources/test_hook_spool.py → 11 passed; narrow mypy and ruff clean; pre-push devtools verify --quick passed.

What survived scrutiny: all documented producer forms now enter the same durable pending/acknowledged route; watcher startup, configured-root delivery, SQLite retry retention, entrypoint wiring, and Hermes deferral to polylogue-fs1.7 remain covered or explicitly scoped.

@Sinity

Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner Author

Adversarial review — iteration 4 (converged)

No legitimate gaps found across all ACs after iteration 4 review. The cold review independently checked the bundled main entrypoint, standalone Python package, and contrib shell adapter; their immutable pending envelopes; directory fsync and stable-id replay; watcher startup/change/periodic drain; source-tier acknowledgement; SQLite failure retention; tests; PR claims; and Hermes scope.

Final acceptance matrix

Acceptance criterion Status Evidence / residual
Claude Code and Codex hook events are captured going forward into a queryable table Satisfied All three documented producers write pending/*.json; the watcher persists each event to source.db.raw_hook_events before acknowledgement. Focused source-route tests cover bundled, standalone, and contrib producers.
polylogue-9e5.10 can be rerun with n>0 in at least one arm Satisfied (capability) New installed hooks now produce queryable rows for future sessions; this PR does not perform the separate live efficacy experiment itself.
Hermes coverage is folded into fs1.2 or given verified investigation Deferred to beads polylogue-fs1.7 owns the upstream Hermes atomic lifecycle spool; polylogue-fs1.2 owns normalization/reconciliation. This PR intentionally does not alter Hermes parser or spool code.

Adversarial loop record: iteration 1 fixed cold-start watcher and SQLite retry gaps (969dc96e9); iteration 2 added production entrypoint coverage (a61bbaeb4); iteration 3 repaired standalone/contrib producer routes (0635e599a); iteration 4 found no further legitimate gap.

Verification retained: focused spool suite (11 passed, explicit /realm/tmp basetemp), narrow mypy/ruff, and each pushed commit’s devtools verify --quick pre-push gate.

Sinity added 5 commits July 13, 2026 01:57
Problem: hook sidecars were append-only files that the live session watcher\nexcluded before raw_hook_events could be materialized.\n\nWhat changed: atomically spool one immutable envelope per hook event, drain it\ninto source.db with a stable event id, and acknowledge it only after the\nsource-tier write commits. The watcher observes pending envelopes directly.\n\nCompatibility: retain the legacy per-session JSONL journal for local tooling\nwhile the daemon consumes the acknowledged spool protocol.\n\nRef polylogue-qqyg.
Regenerate the module topology projection after adding the durable hook\nspool source module.\n\nRef polylogue-qqyg.
Problem: a fresh nested spool root was not watched until daemon restart, and\nSQLite receiver faults escaped instead of leaving events retryable.\n\nWhat changed: create the pending root before watcher startup, pair draining with\nthe watch source root, retain SQLite failures, and fsync spool directory\nrenames. Document the pending/acknowledged receipt protocol.\n\nRef polylogue-qqyg.
The durable-spool tests previously started after the command boundary. Cover\nthe production polylogue-hook entrypoint for both supported runtimes and\nnarrow the hook documentation's coverage claim.\n\nRef polylogue-qqyg.
Problem: standalone and shell hook adapters retained the old journal-only\nroute despite being documented installation paths.\n\nWhat changed: publish durable pending envelopes atomically from both adapters\nand prove each executable reaches the source-tier receipt path.\n\nRef polylogue-qqyg.
@Sinity
Sinity force-pushed the feature/fanout/hooks-capture branch from 0635e59 to d03f900 Compare July 12, 2026 23:58
@Sinity
Sinity merged commit 58fb2bc into master Jul 12, 2026
3 of 15 checks passed
@Sinity
Sinity deleted the feature/fanout/hooks-capture branch July 12, 2026 23:59
Sinity added a commit that referenced this pull request Jul 13, 2026
…800,2781

2ilz (origin-interop, PR #2794), 3v1.1 (capture-hardening, PR #2785), and
qqyg (hooks-capture, PR #2781) fully satisfied — closed. 9e5.16 (api-parity,
PR #2782), 57rp/5k5l (capture-hardening, PR #2785), and 7fj (beads-ingest,
PR #2800) partially satisfied — noted with disposition, left open.

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 29, 2026
…esult blocks

Problem: Claude Code persists a tool result to <session>/tool-results/<name>
whenever the transcript envelope would be too large, leaving only a ~2KB
truncated preview inline (measured live: 12,588 sidecar files, 1.34 GB across
~582 sessions). None of it was ever read -- FTS cannot match a term that only
existed in a large tool output, and 3,058 already-archived tool_result blocks
contain the literal text "Full output saved to" pointing at bytes the archive
never acquires.

Measurement (sampled ~330 MB across 80 live sessions, corpus read-only):
genuinely-truncated overflow sidecars are a minority of files (~12%) but the
majority of bytes (~60-65%, ~99% new content beyond the inline preview);
never-truncated "full mirror" sidecars (Read/Grep/Edit results Claude Code
persists unconditionally) are ~85% of files but <2% of bytes and are already
~97% duplicate of the inline block text; a residual (~1-5% of files, mostly
from compaction pruning the referencing turn) has no owning tool_result block
left in the retained transcript at all. The filename alone does not signal
which case applies -- both toolu_<id> and Claude's internal short-slug/call_/
mcp-<server>-<tool> naming schemes are used for both truncated-overflow and
full-mirror sidecars; the real join key is always the owning tool_result
block's tool_use_id, recovered either directly (filename stem) or via the
"Full output saved to"/"Output has been saved to" pointer embedded in that
block's own preview text -- including across Task subagent transcripts, whose
large outputs persist to the session-level tool-results/ dir under the
subagent's own (non-toolu_) tool id.

Solution: polylogue/sources/live/tool_result_sidecars.py performs the
read-only join (payload + tool-results dir -> matched/debt), reusable by
whichever acquisition layer eventually feeds it a session's sidecar
directory. polylogue/sources/parsers/claude/code_parser.py:
apply_tool_result_sidecars() attaches it to an already-parsed ParsedSession:
a genuinely-truncated sidecar's full text replaces its tool_result block's
preview (so FTS, which indexes block content, now finds it); a
never-truncated mirror is left alone; every sidecar (matched or debt) becomes
a bounded claude_tool_result_sidecar session_event (id/filename/size/hash/
status only -- never raw bytes in the event itself) needing no schema bump.
hook-*.txt captures under the same directory are a distinct, already-tracked
mechanism (raw hook stdout, polylogue-qqyg/#2781) and are always skipped, not
counted as debt. parse_code/parse_code_stream take the join result as an
optional kwarg; passing nothing preserves current behavior exactly.

Not yet wired: polylogue/sources/dispatch.py (out of this lane's write
scope) still needs to build a session's tool-results dir path from its
source_path and pass the join result into parse_code -- a small, precisely
scoped change reported separately. Full blob-store content-addressed
dedup (AC4) and a default-off flag gated on ingest wall-clock measurement
against the polylogue-623q envelope (AC5) need storage/daemon/config work
that is explicitly out of this lane's OWNS list; reported as follow-up scope
rather than implemented here.

Verification: devtools test tests/unit/sources/test_tool_result_sidecars.py
tests/unit/sources/test_parsers_claude_code_artifacts.py -> 31 passed.
mypy --strict on both changed modules: no issues. ruff check/format: clean.
Anti-vacuity: nulling the truncated-replacement dict in
apply_tool_result_sidecars makes
test_apply_tool_result_sidecars_replaces_truncated_block_text_only fail
exactly on the AC2 (FTS-findable) assertion, confirming the test exercises
the real code path, not a self-validating mock.

Ref polylogue-rujy

Co-Authored-By: Claude <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 71.F044 / P2: stale at the checked revision: drain_hook_event_spool and the watcher's direct _drain_hook_spool callback no longer exist. The replacement source contract at polylogue/sources/hooks.py:7-8 acquires and materializes retained carrier revisions through ordinary ingestion, removing the per-pending-envelope source write that could throw out of that live-watch callback.
  • 71.F045 / P2: refuted at the checked revision: The premise of a crash-durable renamed pending envelope is not the current producer contract. polylogue/sources/hooks.py:6-16 explicitly makes hook return a no-fsync carrier append, with durable publication at carrier acquisition rather than per event; reinstating the retired pending-file publication protocol conflicts with AGENTS.md:192-194.

Only the rows listed above are dispositioned. Held findings remain open.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant