Skip to content

feat(acquisition): add hook integration for Claude Code + Codex (#802) - #937

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/hook-integration-802
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/hook-integration-802

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

Hook shell script, artifact taxonomy, config, watcher, docs. 10 files + 51 tests.

- 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]>
Copilot AI review requested due to automatic review settings May 7, 2026 18:22
@Sinity
Sinity merged commit 6488162 into master May 7, 2026
@Sinity
Sinity deleted the feature/feat/hook-integration-802 branch May 7, 2026 18:22
@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 5 minutes and 37 seconds before requesting another review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 8cdd68e9-fce0-4e4a-8558-935672de6e0d

📥 Commits

Reviewing files that changed from the base of the PR and between 1de9b99 and 3fc5d98.

📒 Files selected for processing (16)
  • contrib/polylogue-hook
  • docs/hooks.md
  • polylogue/archive/artifact_taxonomy/models.py
  • polylogue/archive/artifact_taxonomy/runtime.py
  • polylogue/archive/artifact_taxonomy/support.py
  • polylogue/archive/session/runtime.py
  • polylogue/config.py
  • polylogue/core/common.py
  • polylogue/insights/archive_models.py
  • polylogue/paths/__init__.py
  • polylogue/paths/_roots.py
  • polylogue/sources/live/watcher.py
  • polylogue/storage/insights/session/profiles.py
  • polylogue/storage/runtime/archive/records.py
  • polylogue/storage/sqlite/queries/message_query_writes.py
  • tests/unit/sources/test_hook_events.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/hook-integration-802

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 and usage tips.

@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: 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".

Comment thread polylogue/archive/session/runtime.py Resolved
Comment thread polylogue/core/common.py Resolved
Comment thread polylogue/sources/live/watcher.py Resolved

Copilot AI 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.

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_EVENT plus 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.

Comment thread polylogue/core/common.py
Comment on lines 52 to +59
_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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Comment on lines +57 to +64
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)
Comment on lines 112 to +124
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,
),
Comment on lines 259 to +266
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,
Comment on lines +76 to +81
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"
Comment thread docs/hooks.md
Comment on lines +93 to +94
enabled = true
sidecar_dir = "/home/user/.local/share/polylogue/hooks"
Comment thread docs/hooks.md
Comment on lines +249 to +250
(`polylogued run`) and that the hooks sidecar directory exists. The daemon
watcher creates it on startup if needed.
Comment thread contrib/polylogue-hook
Comment on lines +85 to +128
# 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")
Comment thread polylogue/config.py
Comment on lines 221 to +227
@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()))
Comment thread docs/hooks.md
Comment on lines +18 to +19
4. Hook events are classified as `ArtifactKind.HOOK_EVENT` and linked to the
parent session via `link_group_key`.
Sinity added a commit that referenced this pull request May 7, 2026
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
Sinity added a commit that referenced this pull request May 7, 2026
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
@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.

  • 58.F039 / P1: fixed-already at the checked revision: polylogue/archive/session/models.py:104-110 declares the input/output/cache token, credit and provenance fields supplied by build_session_profile. Those cost keyword arguments no longer raise an unexpected-keyword TypeError.

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

@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.

  • 63.F012 / P2: fixed-already at the checked revision: The current message schema includes the token columns in the shared tier specification: input_tokens, output_tokens, cache_read_tokens and cache_write_tokens are declared at polylogue/storage/sqlite/archive_tiers/archive_tiers_specs.py:477,483,489,495. The former upsert-without-token-DDL mismatch is absent from the fresh archive schema.

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

@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.F067 / P2: stale at the checked revision: The old hooks_sidecar_dir configuration contract has been removed with custom source roots. polylogue/sources/live/watcher.py:1598-1606 now declares a canonical daemon watch set, and hook carriers are watched through their explicit topology-derived roots rather than the former ignored PolylogueConfig field.

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.

2 participants