Skip to content

feat(acquisition): Claude Code + Codex hook integration for 100% session data coverage #802

Closed

Description

@Sinity

Problem

Post-hoc session JSONL misses 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.

Claude Code and Codex both expose hook systems that can capture this data at creation time.

Target architecture

Hook capture should write structured hook artifacts through Polylogue's artifact/blob pipeline, linked to the session by link_group_key or equivalent provenance.

The integration should use the shared config system from #829 for install paths, enabled events, auth/token concerns, and provider-specific hook config generation.

Scope

  • Ship a polylogue-hook handler or equivalent installed script.
  • Handle Claude Code hook events and Codex hook events through one normalized hook artifact schema where practical.
  • Add polylogue hooks install or another explicit install surface that writes the right provider config.
  • Ingest hook artifacts into blob/raw/artifact taxonomy and link them to sessions.
  • Capture paste ground truth, tool annotations, structured outputs, errors/interrupts, permissions, cwd/file changes, and session lifecycle data where available.
  • Leave room for future context injection at SessionStart, but do not make injection part of the first capture slice unless it is small and tested.

Non-goals

Acceptance criteria

  • Hook handler handles the supported Claude Code and Codex events or records explicit unsupported-event behavior.
  • Hook artifacts are stored through the archive/blob/artifact pipeline and linked to the parent session.
  • Install/config flow is driven by feat(config): unified config system — polylogue.toml, four-layer precedence, shared daemon/CLI config #829 config conventions.
  • Artifact taxonomy discovers hook artifacts alongside session JSONL.
  • Paste ground truth and tool/error/permission metadata are captured in tests.
  • Security/privacy boundaries are tested for local hook ingestion.

Refs #829 #804 #803 #838 #852.

Activity

  1. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor
  2. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Claude Code Hook System → Polylogue Synergy

    Hook system overview (from /realm/project/_inactive/claude-code-src)

    Claude Code hooks are user-provided shell scripts executed at 16 lifecycle events. Each hook receives JSON on stdin with event-specific context and can return JSON on stdout to influence behavior or inject context.

    16 hook events:

    Event Trigger What's available on stdin
    SessionStart New session starts session_id, cwd, model, permission_mode
    Setup One-time setup (first CC run) —
    UserPromptSubmit User submits a prompt prompt text (with paste references BEFORE expansion!)
    PreToolUse Before tool execution tool_name, tool_input, tool_call_id
    PostToolUse After successful tool execution tool_name, tool_output, tool_call_id
    PostToolUseFailure After failed tool execution tool_name, error message, is_interrupt flag
    PermissionRequest Tool needs permission tool_name, proposed command
    PermissionDenied User denied permission tool_name
    Notification System notification message, severity
    Elicitation Modal dialog shown prompt, options
    ElicitationResult User responds to dialog selected option
    CwdChanged Working directory changed old_cwd, new_cwd
    FileChanged File modified by tool file path, diff stats
    WorktreeCreate Git worktree created path
    SubagentStart Subagent spawned subagent_type, prompt
    Stop Session ending session_id, reason

    Hook output capabilities:

    • additionalContext — inject text into Claude's system prompt (all events)
    • permissionDecision — approve/block tool calls (PreToolUse)
    • updatedInput — modify tool arguments before execution (PreToolUse)
    • updatedMCPToolOutput — modify MCP tool results (PostToolUse)
    • decision — answer permission requests (PermissionRequest)
    • watchPaths — register paths for FileChanged hooks (SessionStart, CwdChanged)
    • stopReason — custom stop message (Stop)

    Codex hook system (6 events)

    Codex has an equivalent hook system at /realm/project/_inactive/codex/codex-rs/hooks/:

    Codex event Equivalent CC event What's available
    PreToolUse PreToolUse tool_name, tool_input
    PostToolUse PostToolUse tool_name, tool_output
    PermissionRequest PermissionRequest proposed action
    SessionStart SessionStart session_id, cwd, source
    UserPromptSubmit UserPromptSubmit prompt text
    Stop Stop session_id

    Codex has 6 events vs Claude Code's 16. The same integration strategy works for both — a single handler script that writes structured JSONL. Codex discovers hooks differently (TOML config + JSON files, not just settings.json), but the output format can be identical. One polylogue-hook script handles both providers.

    Polylogue workflows BEYOND data capture

    Hooks don't just let polylogue READ data — they let polylogue INJECT back into sessions:

    Hooks provide data that is NOT in the session JSONL:

    1. Paste ground truth (UserPromptSubmit)

    The hook receives the prompt BEFORE paste expansion — with [Pasted text #N] markers intact. This is exactly what history.jsonl provides but for 100% of sessions, not 29.9%. One hook handler could write prompt text + paste markers to a polylogue sidecar file.

    2. Tool execution metadata (PreToolUse + PostToolUse)

    Tool annotations (read_only/destructive), structured input/output, updated MCP tool results. This fills all 10 tool call schema gaps found by the upstream analysis. Data that exists at hook time but is never written to JSONL.

    3. Error/interrupt data (PostToolUseFailure)

    Error subtypes, interrupt flags, whether the failure is transient or permanent. Currently only described in SDK schemas, never exposed in transcripts.

    4. Permission audit trail (PermissionRequest + PermissionDenied)

    What was proposed, what was decided, who decided. Currently invisible in session JSONL.

    5. Session lifecycle (SessionStart + Stop)

    Model configuration at session start, working directory, permission mode. Final state at session end. Session start could trigger polylogue ingestion; session end could trigger finalization.

    6. File change tracking (FileChanged)

    Lines added/removed per file per tool call. Currently calculated by CC's diff engine but only surfaced in aggregated form.

    7. Working directory tracking (CwdChanged)

    All directory changes during the session, not just the initial cwd recorded in session JSONL.

    Integration approach

    Full: Ship a polylogue hooks install CLI command that generates the hook configuration and installs the handler script. Each hook event writes to a dedicated sidecar file under .claude/polylogue-hooks/. Schema inference handles the auto-discovery of new event types.

    Why this is better than JSONL extraction

    Data JSONL extraction Hook capture
    Paste ground truth history.jsonl (29.9% coverage) UserPromptSubmit hook (100% coverage)
    Tool annotations Not in JSONL PreToolUse stdin has tool_name + input
    Structured MCP output Not in JSONL PostToolUse can capture raw output
    Error subtypes Not in JSONL PostToolUseFailure has structured error
    Permission decisions Not in JSONL PermissionRequest + PermissionDenied
    File diffs Not in JSONL FileChanged has file path + diff stats
    Before/after paste expansion Separate history.jsonl Same hook event, just capture stdin

    The hook system gives polylogue access to data at the moment of creation, before any downstream transformation or loss. This is a strictly richer data source than the session JSONL for several metadata dimensions.

  3. Sinity commented on May 4, 2026

    @Sinity
    OwnerAuthor

    Acceptance Criteria

    1. polylogue-hook shell script handles all 16 CC events + 6 Codex events
    2. Hook data writes to blob store via polylogue hook-ingest, linked to session via link_group_key
    3. One hooks config block in settings.json installs it
    4. Artifact taxonomy auto-discovers hook artifacts alongside session JSONL
    5. Paste ground truth captured at 100% coverage (UserPromptSubmit hook before paste expansion)
    6. Tool annotations, structured MCP output, error subtypes, permission decisions all captured

    When closing: comment on this issue or the PR explicitly stating how each criterion was satisfied, deferred, or found misframed.

  4. added
    theme:analysis
    on May 6, 2026
  5. Sinity commented on May 6, 2026

    @Sinity
    OwnerAuthor

    Execution supplement

    Mass-execution wave: #852 Wave 5 after #829 config is available where hook install/config paths need it.

    Focused verification:

    • hook artifact taxonomy tests for Claude Code and Codex hook event shapes;
    • acquisition/parser tests proving hook events preserve provenance, raw blobs, and session linkage;
    • install/config tests for hook enablement without writing untracked sidecars as the primary contract;
    • security/privacy tests for local path and payload handling where hooks expose sensitive data;
    • devtools verify --quick, then full devtools verify before PR.

    Do not make hook sidecars the canonical archive model; hook data should flow through artifact/blob/source ingestion semantics.

  6. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Reconnaissance Report: #802 feat(acquisition): Claude Code + Codex hook integration

    Date: 2026-05-07 | Prep agent: file-search (read-only)


    Codebase State

    Hook code does not exist yet. rg hook polylogue/ returns only MCP server hook/plugin-registration paths — zero CC/Codex hook integration code exists. This is a green-field builder issue.

    Existing acquisition pipeline (the surface hooks must feed into):

    Module Role
    polylogue/sources/dispatch.py Provider detection, payload lowering, parse dispatch
    polylogue/sources/parsers/claude/code_parser.py CC JSONL parsing (parse_code(), parse_stream())
    polylogue/sources/parsers/codex.py Codex JSONL parsing (parse(), parse_stream())
    polylogue/sources/assembly_claude_code.py CC sessions-index.json sidecar discovery
    polylogue/sources/assembly_codex.py Codex assembly/sidecar
    polylogue/sources/source_acquisition.py Source acquisition orchestration
    polylogue/pipeline/semantic_capture.py Detects context compactions, enriches
    polylogue/storage/artifacts/ Blob store persistence and queries

    Config surface (where hook keys will live per #829):

    • polylogue/config.py — Config dataclass, Source, DriveConfig, IndexConfig
    • polylogue/paths/__init__.py — claude_code_path(), codex_path(), config_root(), data_root()
    • polylogue/paths/_roots.py — XDG path resolution

    Build This

    1. Hook handler script (polylogue-hook): a single shell script handling all 16 CC events + 6 Codex events. Writes structured JSONL to a sidecar directory (e.g., .claude/polylogue-hooks/). Each event type gets its own output stream.

    2. Hook event taxonomy (polylogue/sources/hook_events.py or similar): typed event payloads for each hook event, with shared provenance fields (session_id, cwd, timestamp, event_type). Schema inference for auto-discovery.

    3. Hook artifact ingestion (polylogue/sources/hook_ingest.py): a source acquisition component that discovers hook sidecar files alongside session JSONL, reads them, validates event shapes, and routes them to the blob store with link_group_key connecting them to the parent session.

    4. Hook install CLI (polylogue cli hooks install): generates hook config in settings.json (or equivalent for Codex TOML), installs the handler script, and validates the hook pipeline end-to-end.

    5. Config keys in feat(config): unified config system — polylogue.toml, four-layer precedence, shared daemon/CLI config #829 (polylogue.toml [hooks] section): enabled, path to handler script, sidecar output dir, event filter allowlist.

    6. Artifact taxonomy integration: hook artifacts appear alongside session JSONL in the artifact taxonomy with auto-discovered event types.


    Do NOT Build

    • Do NOT make hook sidecars the canonical archive model. Hook data must flow through artifact/blob/source ingestion semantics — the sidecar directory is ephemeral capture, the blob store is durable storage.
    • Do NOT create separate handler scripts for CC vs Codex. One polylogue-hook script handles both.
    • Do NOT implement hook capture by modifying the existing JSONL parser. Hooks produce new artifact streams; they do not alter the existing code_parser.py/codex.py parse logic (except to link artifacts).
    • Do NOT build a real-time hook streaming daemon. This issue is about capture + ingestion, not live SSE forwarding.

    Files to Touch

    File Change
    polylogue/sources/hook_events.py NEW — typed hook event models, taxonomy
    polylogue/sources/hook_ingest.py NEW — hook artifact ingestion/validation
    polylogue/cli/hook_commands.py NEW — polylogue hooks install CLI
    polylogue/sources/source_acquisition.py Add hook discovery step
    polylogue/sources/dispatch.py Register hook event types in artifact taxonomy
    polylogue/config.py Add HookConfig dataclass
    polylogue/paths/_roots.py Add hook sidecar dir path
    contrib/polylogue-hook NEW — the handler shell script
    polylogue/storage/artifacts/persistence.py Hook artifact write path if needed

    Coordination


    Focused Tests

    # Unit: hook event taxonomy tests
    pytest tests/unit/sources/test_hook_events.py -v
    
    # Integration: hook artifact ingest roundtrip
    pytest tests/unit/sources/test_hook_ingest.py -v
    
    # CLI: hook install command
    pytest tests/unit/cli/test_hook_commands.py -v
    
    # Static: no accidental broad gates
    ruff check polylogue/sources/hook_events.py polylogue/sources/hook_ingest.py

    Acceptance Criteria

    1. polylogue-hook shell script handles all 16 CC events + 6 Codex events
    2. Hook data writes to blob store via polylogue hook-ingest, linked to session via link_group_key
    3. One hooks config block in settings.json installs it
    4. Artifact taxonomy auto-discovers hook artifacts alongside session JSONL
    5. Paste ground truth captured at 100% coverage
    6. Tool annotations, structured MCP output, error subtypes, permission decisions all captured

    Ambiguities / Stale Notes

    • The issue body mentions "Schema inference handles the auto-discovery of new event types." This should use the existing schema resolution/registry pattern (polylogue/schemas/) rather than inventing a separate inference mechanism.
    • The issue mentions .claude/polylogue-hooks/ as the sidecar dir — confirm this path against the existing polylogue/paths/_roots.py convention (should use XDG data/cache dirs like other Polylogue paths).
    • Codex "discovers hooks differently (TOML config + JSON files)" — verify the exact Codex hook config format against /realm/project/_inactive/codex/codex-rs/hooks/ before implementing. The issue claims one handler script handles both, but the install path differs.
  7. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Implementation Scope

    What's being built

    1. Shell script (contrib/polylogue-hook) — handles all 16 CC events + 6 Codex events, writes structured JSONL to sidecar directory
    2. Artifact taxonomy — new ArtifactKind.HOOK_EVENT, classification detection in classify_artifact()
    3. Hook config — extend PolylogueConfig with hooks_sidecar_dir, add path resolution in _roots.py
    4. Daemon integration — add hooks sidecar directory to default_sources() so daemon picks up hook files automatically
    5. Documentation (docs/hooks.md) — hook protocol, supported events, sidecar layout, example configs

    Non-goals (per issue instructions)

    • Don't build the hook installer CLI (users configure hooks in their AI agent settings)
    • Don't implement the hook event protocol in Python (the shell script is the interface)
    • Don't add hook-specific ingest pipeline (reuse existing daemon ingestion)

    Files to touch

    • polylogue/archive/artifact_taxonomy/models.py — add HOOK_EVENT to ArtifactKind
    • polylogue/archive/artifact_taxonomy/support.py — add looks_like_hook_event() detection
    • polylogue/archive/artifact_taxonomy/runtime.py — classify hook events
    • polylogue/paths/_roots.py — add hooks_sidecar_dir()
    • polylogue/paths/__init__.py — export hooks_sidecar_dir
    • polylogue/config.py — add hooks_sidecar_dir property, extend TOML merge
    • polylogue/sources/live/watcher.py — add hook sidecar to default_sources()
    • contrib/polylogue-hook — NEW shell script
    • docs/hooks.md — NEW documentation
    • tests/unit/sources/test_hook_events.py — NEW tests

    Acceptance Criteria

    • AC1: polylogue-hook shell script handles all 16 CC events + 6 Codex events
    • AC2: Hook data writes to blob store via existing daemon pipeline, linked to session via link_group_key
    • AC3: Config follows feat(config): unified config system — polylogue.toml, four-layer precedence, shared daemon/CLI config #829 conventions (already has hooks_enabled, adding hooks_sidecar_dir)
    • AC4: Artifact taxonomy discovers hook artifacts alongside session JSONL (new ArtifactKind.HOOK_EVENT)
    • AC5: Paste ground truth and tool/error/permission metadata captured in tests
    • AC6: Security/privacy boundaries tested for local hook ingestion
  8. Sinity commented on May 7, 2026

    @Sinity
    OwnerAuthor

    Closed-scope audit found the hook taxonomy captures UserPromptSubmit payload shape, but the paste-detection promise is not wired through to stored message/query semantics; leaving this issue closed and tracking reconciliation in #944.

    Evidence:

    • Default live watcher roots include ~/.claude/projects, Codex sessions, inbox, and hook sidecars, but not top-level ~/.claude/history.jsonl.
    • Hook UserPromptSubmit records classify as ArtifactKind.HOOK_EVENT, with tests preserving [Pasted text #N] markers, but I did not find code that converts those events into message has_paste facts.
    • polylogue/pipeline/materialization_runtime.py currently initializes has_paste = 0 for every materialized message, and detect_paste() appears unit-tested but unused in production paths.

    #944 now tracks wiring paste evidence into materialization/derived updates or explicitly narrowing the claim.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:parsertheme:analysistool:claudetool:codextype:feat

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions