Repository navigation
feat(acquisition): add hook integration for Claude Code + Codex (#802) - #937
Conversation
- contrib/polylogue-hook shell script handling 22 event types - HOOK_EVENT artifact kind for taxonomy-based acquisition - hooks_sidecar_dir in config and default watcher sources - docs/hooks.md with protocol documentation - 51 tests covering detection/classification/security Co-Authored-By: Claude Opus 4.7 <[email protected]>
|
Warning Rate limit exceeded
To continue reviewing without waiting, purchase usage credits in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (16)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3fc5d985b0
ℹ️ 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".
There was a problem hiding this comment.
Pull request overview
This PR introduces a hook-event ingestion path for AI coding agents (Claude Code, Codex) by adding a sidecar directory, watcher integration, artifact taxonomy classification, a polylogue-hook helper script, and documentation/tests. It also extends message/session profiling to persist token/model/cost fields, but the current branch is missing the required model + schema support for those new fields.
Changes:
- Add
ArtifactKind.HOOK_EVENTplus hook-record/stream detection and classification. - Add a hooks sidecar directory path and include it in default live watch sources; document hook setup and add taxonomy tests.
- Extend message upsert writes and session profile building to include token/model/cost fields (currently inconsistent with schema/models).
Reviewed changes
Copilot reviewed 16 out of 16 changed files in this pull request and generated 11 comments.
Show a summary per file
| File | Description |
|---|---|
polylogue/archive/artifact_taxonomy/models.py |
Adds HOOK_EVENT artifact kind. |
polylogue/archive/artifact_taxonomy/support.py |
Adds hook event record/stream detection helpers. |
polylogue/archive/artifact_taxonomy/runtime.py |
Classifies hook events before record streams. |
tests/unit/sources/test_hook_events.py |
Adds unit coverage for hook taxonomy/detection/security boundaries. |
polylogue/paths/_roots.py |
Introduces hooks_sidecar_dir() path helper. |
polylogue/paths/__init__.py |
Exports hooks_sidecar_dir. |
polylogue/sources/live/watcher.py |
Adds hooks sidecar dir as a default watch source. |
polylogue/config.py |
Adds config keys/properties for hooks enablement + sidecar dir. |
contrib/polylogue-hook |
Adds hook handler script that enriches events and writes JSONL sidecars. |
docs/hooks.md |
Documents hook integration, formats, configuration, and setup steps. |
polylogue/core/common.py |
Extends canonical messages upsert SQL with token/model columns. |
polylogue/storage/runtime/archive/records.py |
Extends MessageRecord with token/model fields. |
polylogue/storage/sqlite/queries/message_query_writes.py |
Writes new token/model fields on message upsert. |
polylogue/archive/session/runtime.py |
Attempts to compute/store session-level token/cost summary (currently broken). |
polylogue/insights/archive_models.py |
Adds token/cost provenance fields to session evidence payload. |
polylogue/storage/insights/session/profiles.py |
Attempts to persist token/cost fields into session profile records (currently inconsistent). |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| _MESSAGE_UPSERT_SQL = """ | ||
| INSERT INTO messages ( | ||
| message_id, conversation_id, provider_message_id, role, text, | ||
| sort_key, content_hash, version, parent_message_id, branch_index, | ||
| provider_name, word_count, has_tool_use, has_thinking, has_paste, message_type | ||
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) | ||
| provider_name, word_count, has_tool_use, has_thinking, has_paste, | ||
| input_tokens, output_tokens, cache_read_tokens, cache_write_tokens, | ||
| model_name, message_type | ||
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) |
| from polylogue.archive.cost.compute import compute_session_cost | ||
| from polylogue.archive.semantic.pricing import harmonize_session_cost | ||
|
|
||
| session_analysis = analysis or build_session_analysis(conversation) | ||
| facts = session_analysis.facts | ||
| attribution = session_analysis.attribution | ||
| cost_usd, cost_is_estimated = harmonize_session_cost(conversation) | ||
| cost_summary = compute_session_cost(conversation) |
| cost_is_estimated=cost_is_estimated, | ||
| total_input_tokens=cost_summary.total_input_tokens, | ||
| total_output_tokens=cost_summary.total_output_tokens, | ||
| total_cache_read_tokens=cost_summary.total_cache_read_tokens, | ||
| total_cache_write_tokens=cost_summary.total_cache_write_tokens, | ||
| total_credit_cost=cost_summary.total_credit_cost, | ||
| cost_provenance=cost_summary.cost_provenance, | ||
| per_model_cost_json=_json.dumps( | ||
| [b.model_dump(mode="json") for b in cost_summary.per_model] | ||
| if cost_summary.per_model | ||
| else [], | ||
| default=str, | ||
| ), |
| cost_is_estimated=profile.cost_is_estimated, | ||
| total_input_tokens=profile.total_input_tokens, | ||
| total_output_tokens=profile.total_output_tokens, | ||
| total_cache_read_tokens=profile.total_cache_read_tokens, | ||
| total_cache_write_tokens=profile.total_cache_write_tokens, | ||
| total_credit_cost=profile.total_credit_cost, | ||
| cost_provenance=profile.cost_provenance, | ||
| per_model_cost_json=profile.per_model_cost_json, |
| total_input_tokens: int = 0 | ||
| total_output_tokens: int = 0 | ||
| total_cache_read_tokens: int = 0 | ||
| total_cache_write_tokens: int = 0 | ||
| total_credit_cost: float = 0.0 | ||
| cost_provenance: str = "unknown" |
| enabled = true | ||
| sidecar_dir = "/home/user/.local/share/polylogue/hooks" |
| (`polylogued run`) and that the hooks sidecar directory exists. The daemon | ||
| watcher creates it on startup if needed. |
| # Extract session_id from payload | ||
| session_id = None | ||
| for key in ("session_id", "sessionId", "session"): | ||
| val = payload.get(key) | ||
| if isinstance(val, str) and val.strip(): | ||
| session_id = val.strip() | ||
| break | ||
|
|
||
| if not session_id: | ||
| print("polylogue-hook: could not extract session_id from payload", file=sys.stderr) | ||
| sys.exit(1) | ||
|
|
||
| # Detect provider | ||
| provider = os.environ.get("POLYLOGUE_HOOK_PROVIDER") | ||
| if not provider: | ||
| if "permission_mode" in payload or "model" in payload: | ||
| provider = "claude-code" | ||
| elif "source" in payload: | ||
| provider = "codex" | ||
| else: | ||
| provider = "unknown" | ||
|
|
||
| if provider not in ("claude-code", "codex"): | ||
| print( | ||
| "polylogue-hook: could not detect provider; " | ||
| "set POLYLOGUE_HOOK_PROVIDER=claude-code|codex", | ||
| file=sys.stderr, | ||
| ) | ||
| sys.exit(1) | ||
|
|
||
| # Build enriched event record | ||
| record = { | ||
| "event_type": event_type, | ||
| "session_id": session_id, | ||
| "timestamp": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), | ||
| "provider": provider, | ||
| "payload": payload, | ||
| } | ||
|
|
||
| # Write to sidecar file (one JSONL file per provider+session) | ||
| os.makedirs(sidecar_dir, exist_ok=True) | ||
| outfile = os.path.join(sidecar_dir, f"{provider}-{session_id}.jsonl") | ||
| with open(outfile, "a") as f: | ||
| f.write(json.dumps(record, ensure_ascii=False, default=str) + "\n") |
| @property | ||
| def hooks_enabled(self) -> bool: | ||
| return bool(self._data.get("hooks_enabled")) | ||
|
|
||
| @property | ||
| def hooks_sidecar_dir(self) -> str: | ||
| return str(self._data.get("hooks_sidecar_dir", hooks_sidecar_dir())) |
| 4. Hook events are classified as `ArtifactKind.HOOK_EVENT` and linked to the | ||
| parent session via `link_group_key`. |
Post-hoc session JSONL discovery loses high-value lifecycle and
tool metadata: paste ground truth before expansion, tool
annotations, structured MCP output, error subtypes, permission
decisions, file diffs, cwd changes, and precise timing. Both
Claude Code and Codex expose hook systems that capture these at
creation time, lifting coverage from ~79% post-hoc to 100%.
- `contrib/polylogue-hook`: shell entrypoint installable from the
Claude Code / Codex hook configurations.
- `polylogue/archive/artifact_taxonomy/{models,runtime,support}.py`
+ `archive/session/runtime.py`: hook artifacts flow through the
artifact/blob pipeline as first-class kinds (session lifecycle,
pre/post tool, notification) linked by `link_group_key` rather
than a parallel ingest path.
- `config.py`, `core/common.py`: shared config wiring (uses #829
precedence) for hook install paths and watch roots.
- `docs/hooks.md`: install + lifecycle reference for both
agents.
Refs #802
Post-hoc session JSONL discovery loses high-value lifecycle and
tool metadata: paste ground truth before expansion, tool
annotations, structured MCP output, error subtypes, permission
decisions, file diffs, cwd changes, and precise timing. Both
Claude Code and Codex expose hook systems that capture these at
creation time, lifting coverage from ~79% post-hoc to 100%.
- `contrib/polylogue-hook`: shell entrypoint installable from the
Claude Code / Codex hook configurations.
- `polylogue/archive/artifact_taxonomy/{models,runtime,support}.py`
+ `archive/session/runtime.py`: hook artifacts flow through the
artifact/blob pipeline as first-class kinds (session lifecycle,
pre/post tool, notification) linked by `link_group_key` rather
than a parallel ingest path.
- `config.py`, `core/common.py`: shared config wiring (uses #829
precedence) for hook install paths and watch roots.
- `docs/hooks.md`: install + lifecycle reference for both
agents.
Refs #802
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Hook shell script, artifact taxonomy, config, watcher, docs. 10 files + 51 tests.