Skip to content

fix(sources): persist hook events as session-linked evidence, not standalone sessions - #3265

Merged
Sinity merged 5 commits into
masterfrom
feature/storage/hook-events-not-sessions
Jul 22, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/storage/hook-events-not-sessions

Conversation

@Sinity

@Sinity Sinity commented Jul 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

Hook events (PreToolUse/PostToolUse/UserPromptSubmit/…) were being ingested as
standalone codex/claude-code sessions, inflating the archive with
content-less session shells. This lands the going-forward fix (hooks persist as
session-linked evidence, no raw_sessions row) plus a tested retroactive repair
for the shells already accumulated. The session↔hooks read-model + read surfaces
follow in a fast-follow PR.

Problem

sources/hooks.py:_persist_record drained each spooled hook event through
write_source_raw_session with origin=codex-session|claude-code-session,
minting a full raw_sessions row per hook. The materializer turned each into an
empty standalone index session. On the live archive /realm/db/polylogue:

  • index sessions = 83,279, but only 17,553 have any messages; the other
    65,727 are empty shells (codex 35,233 + claude-code 30,488).
  • source_path LIKE '%/hooks/pending/%' raws = codex 35,216 + claude-code
    29,679 + hermes 1 = 64,896, exactly the raw_hook_events row count.

Each hook was double-recorded: correctly as a raw_hook_events row (which
carries session_native_id; that table is indexed
(origin, session_native_id, observed_at_ms) precisely to attach a hook to its
session), and wrongly as a raw_sessions row. raw_hook_events has no FK to
raw_sessions, so the linkage never needed a session row. Nothing was lost —
every raw blob is retained.

Solution

  • write_source_hook_event (source_write.py): writes the
    raw_hook_events row + a durable raw_payload blob ref, but no
    raw_sessions row
    . Blob GC roots off blob_refs independently of
    raw_sessions, so the bytes stay retained.
  • ArchiveStore.write_hook_event (archive.py): publishes the blob then
    routes to the hook path with a deterministic raw_id.
  • _persist_record uses it; covers codex/claude-code/hermes uniformly.
  • maintenance/hook_deinflation.py: repair_hook_session_inflation deletes
    the historical hook raw_sessions rows (source, durable) + their empty index
    sessions, while KEEPING the raw_hook_events rows and retained blobs.
    Identification is exact (source_path LIKE '%/hooks/pending/%', 1:1 with
    raw_hook_events); genuinely-empty real sessions (content quarantined /
    zero-turn) do not match and are never touched (index delete additionally
    guarded by message_count=0). The four source FKs into raw_sessions are
    ON DELETE CASCADE and hook raws never appear in raw-authority
    plans/blockers, so the durable delete self-cleans without orphans and does not
    perturb convergence. dry_run=True reports counts without mutating.

The repair runs against the live archive only after this fix is deployed to the
daemon (otherwise the running old daemon re-inflates); backup already taken at
/realm/staging/polylogue-sqlite/recovery/t93b-preflight-20260722-durable.

Verification

  • devtools test tests/unit/sources/test_hook_spool.py tests/unit/storage/test_hook_event_materialization.py tests/unit/maintenance/test_hook_deinflation.py tests/unit/daemon/test_hook_liveness.py — 38 passed.
    • New guards: draining a hook asserts 0 raw_sessions / 1 raw_hook_events / 1 blob_ref across codex/claude/hermes; the repair test asserts only hook shells are removed while hook evidence + blobs + real + genuinely-empty-non-hook sessions survive.
  • devtools verify --quick — exit 0 (format + lint + mypy --strict + render all --check + layering).
  • Live dry-run against /realm/db/polylogue: hook_raw_sessions=64896, hook_index_sessions=64895, raw_hook_events unchanged=64896, blobs retained=64896.

Ref polylogue-31r1.

Summary by CodeRabbit

  • Bug Fixes

    • Hook events no longer create empty standalone sessions, preventing archive inflation.
    • Existing inflated hook sessions can be safely removed while preserving hook evidence and payloads.
    • Added dry-run reporting before applying archive repairs.
  • Tests

    • Added coverage confirming hook events are retained without creating session records.
    • Added validation for repair behavior, including preservation of real sessions and hook evidence.
  • Documentation

    • Updated topology and status metrics and refreshed plan formatting.

Sinity and others added 4 commits July 22, 2026 14:48
…sions

Problem: sources/hooks.py:_persist_record drained each spooled hook event
(PreToolUse/PostToolUse/UserPromptSubmit/...) through write_source_raw_session
with origin=codex-session|claude-code-session, minting a full raw_sessions row
per hook. The materializer turned each into an empty standalone index session.
On the live archive this produced 64,896 hook raw_sessions rows -> ~65.7K
content-less session shells (of 83K total session rows; only ~17.5K have any
messages). Each hook was double-recorded: correctly as a raw_hook_events row
carrying session_native_id (that table is indexed (origin,session_native_id,
observed_at_ms) precisely to attach a hook to its session), and wrongly as a
raw_sessions row. raw_hook_events has no FK to raw_sessions, so the linkage
never needed a session row.

What changed:
- write_source_hook_event (source_write.py): writes the raw_hook_events row +
  a durable raw_payload blob ref, but NO raw_sessions row. Blob GC roots off
  blob_refs independently of raw_sessions, so the bytes stay retained.
- ArchiveStore.write_hook_event (archive.py): publishes the blob then routes to
  the hook path with a deterministic raw_id.
- _persist_record uses write_hook_event; covers codex/claude-code/hermes.

Regression guard: draining a hook now asserts 0 raw_sessions rows, 1
raw_hook_events row keyed to its session, and 1 retained raw_payload blob ref.

This is the going-forward fix (stops the inflation). The retroactive archive
repair (removing the 64,896 existing hook raw_sessions rows + empty index
shells) and the session-linked hook read-model land in follow-up commits on
this branch.

Ref polylogue-31r1.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
Removes the raw_sessions rows (and their empty index sessions) that the old
hooks ingestion path minted per hook event, while KEEPING the hook evidence
(raw_hook_events rows) and the retained raw_payload blobs. Counterpart to the
write_source_hook_event going-forward fix.

Identification is exact: a hook raw lives under the hook spool
(source_path LIKE '%/hooks/pending/%'); on the live archive that predicate is
1:1 with raw_hook_events (64,896 == 64,896). Genuinely-empty real sessions
(content quarantined / zero-turn) do not match and are never touched. The index
delete is additionally guarded by message_count=0. The four source FKs into
raw_sessions are ON DELETE CASCADE and hook raws never appear in raw-authority
plans/blockers, so the durable delete self-cleans without orphans and does not
perturb convergence. dry_run=True reports counts without mutating.

Live dry-run confirms scope: 64,896 hook raw_sessions, 64,895 empty index
shells, raw_hook_events unchanged (64,896), 64,896 blobs retained.

Ref polylogue-31r1.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
@coderabbitai

coderabbitai Bot commented Jul 22, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

Next review available in: 45 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: 3d0c6cda-077a-4188-9c33-26017050bdb6

📥 Commits

Reviewing files that changed from the base of the PR and between 64dbfea and 9ffa483.

📒 Files selected for processing (2)
  • polylogue/maintenance/hook_deinflation.py
  • tests/unit/maintenance/test_hook_deinflation.py
📝 Walkthrough

Walkthrough

Hook ingestion now stores hook evidence without creating standalone raw sessions. A maintenance repair removes legacy hook-derived session rows from source and index databases while retaining hook events and payload blobs. Tests cover both the new ingestion path and retroactive repair.

Changes

Hook event session de-inflation

Layer / File(s) Summary
Direct hook-event persistence
polylogue/sources/hooks.py, polylogue/storage/sqlite/archive_tiers/..., tests/unit/sources/test_hook_spool.py
Hook events are written as raw hook evidence with durable payload references, without creating raw_sessions rows; the spool regression test verifies this behavior.
Legacy hook-session repair
polylogue/maintenance/hook_deinflation.py, tests/unit/maintenance/test_hook_deinflation.py, .beads/issues.jsonl, docs/topology-status.md
The repair utility supports dry-run and apply modes, removes matching empty index sessions and hook-scoped raw sessions, and verifies that hook evidence, blobs, and real sessions remain.
Topology metadata refresh
docs/plans/topology-target.yaml, docs/plans/layering.yaml
Topology locations, the new maintenance module entry, and generated placement totals are refreshed.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant HookSpool
  participant ArchiveStore
  participant BlobPublisher
  participant SourceDB
  HookSpool->>ArchiveStore: persist hook event
  ArchiveStore->>BlobPublisher: publish payload
  ArchiveStore->>SourceDB: write raw_hook_events and raw_payload
  SourceDB-->>HookSpool: acknowledge event
Loading
sequenceDiagram
  participant Operator
  participant RepairUtility
  participant IndexDB
  participant SourceDB
  Operator->>RepairUtility: run dry-run or apply repair
  RepairUtility->>SourceDB: identify hook raw sessions
  RepairUtility->>IndexDB: remove matching empty sessions
  RepairUtility->>SourceDB: remove hook raw_sessions
  SourceDB-->>RepairUtility: retain hook evidence and blobs
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 76.92% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: hook events are persisted as evidence instead of standalone sessions.
Description check ✅ Passed The PR description includes the required Summary, Problem, Solution, and Verification sections with detailed, relevant content.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/storage/hook-events-not-sessions

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.

@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: 64dbfea96f

ℹ️ 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".

…pair

Addresses two P1 findings from the Codex review on PR #3265:

- Restrict the durable delete to VERIFIED hook rows: require a raw_hook_events
  row written from the same spool file (source_path), not just a path substring
  match. A legitimate raw whose path happened to contain '/hooks/pending/' would
  otherwise lose its durable raw_sessions row without any hook evidence backing
  it. Live dry-run confirms the verified predicate still matches all 64,896.
- Refuse to race the sole-writer daemon: apply now calls
  offline_maintenance_block_reason and raises if polylogued is running, matching
  every other offline-maintenance mutation. dry_run stays read-only and allowed.

Tests: guard-refusal test asserts apply raises and mutates nothing while a
daemon is reported running, and that dry_run still works.

Ref polylogue-31r1.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QUsH3Rhq6oAZpYPWcsZqnZ
@Sinity

Sinity commented Jul 22, 2026

Copy link
Copy Markdown
Owner Author

Addressed both Codex P1 findings in 9ffa483:

  1. Verified hook rows — the durable delete now requires a raw_hook_events row written from the same spool file (source_path IN (SELECT source_path FROM raw_hook_events)), not just a path-substring match. A legitimate raw whose path merely contained /hooks/pending/ is no longer deletable without hook evidence. Live dry-run confirms the verified predicate still matches all 64,896 (the 1:1 holds).
  2. Daemon coordination — apply now calls offline_maintenance_block_reason and raises if polylogued is running, matching every other offline-maintenance mutation; dry_run stays read-only and allowed. New test asserts apply raises and mutates nothing while a daemon is reported live.

@Sinity
Sinity merged commit 998188b into master Jul 22, 2026
2 checks passed
@Sinity
Sinity deleted the feature/storage/hook-events-not-sessions branch July 22, 2026 14:30

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

Actionable comments posted: 5

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In @.beads/issues.jsonl:
- Line 1: Sanitize the Beads issue record for polylogue-31r1 by removing
personal email addresses, absolute host or backup paths, and detailed incident
evidence from the tracked entry. Keep only a concise, non-sensitive summary of
the hook-session inflation issue and required remediation, and move the full
evidence to restricted incident notes.

In `@polylogue/maintenance/hook_deinflation.py`:
- Around line 72-85: Update the source-side deletion flow in the maintenance
function around the raw_sessions delete to apply the same message_count = 0
safety condition used when building index_session_ids. Ensure hook-matching
raw_sessions rows are deleted only when no linked session contains messages;
otherwise preserve them and let the repair operation fail loudly or report the
inconsistency rather than creating dangling sessions.raw_id references.
- Around line 67-130: Explicitly close every SQLite connection in the four
blocks using sqlite3.connect: the source connection used for inspection/dry-run,
the index read-only connection, the index deletion connection, and the final
source deletion connection. Preserve each block’s commit/rollback behavior while
adding try/finally cleanup, matching the connection-lifecycle pattern used by
ArchiveStore.delete_sessions.

In `@polylogue/storage/sqlite/archive_tiers/archive.py`:
- Around line 1804-1845: In write_hook_event, validate that hook_event.origin
matches the origin derived from provider before publishing the payload or
persisting the event. Raise an appropriate validation error on mismatch, and
keep the existing persistence flow unchanged when the values agree.

In `@polylogue/storage/sqlite/archive_tiers/source_write.py`:
- Around line 536-582: Update the ContentExcisedError class docstring to
identify three acquire-time write functions and include write_source_hook_event
alongside write_source_raw_session and write_source_raw_session_blob_ref. Keep
the existing excision-gating description and invariant unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: ae840302-810d-4fd2-99ef-c738f039f5df

📥 Commits

Reviewing files that changed from the base of the PR and between ecb8e14 and 64dbfea.

📒 Files selected for processing (10)
  • .beads/issues.jsonl
  • docs/plans/layering.yaml
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/maintenance/hook_deinflation.py
  • polylogue/sources/hooks.py
  • polylogue/storage/sqlite/archive_tiers/archive.py
  • polylogue/storage/sqlite/archive_tiers/source_write.py
  • tests/unit/maintenance/test_hook_deinflation.py
  • tests/unit/sources/test_hook_spool.py

Comment thread .beads/issues.jsonl
@@ -1,3 +1,4 @@
{"_type":"issue","id":"polylogue-31r1","title":"Hook events ingested as standalone sessions inflate archive ~4.7x (65.7K empty shells)","design":"Root cause (airtight, 2026-07-22): polylogue/sources/hooks.py:_persist_record drains each spooled hook event (~/.local/share/polylogue/hooks/pending/\u003cid\u003e.json: PreToolUse/PostToolUse/UserPromptSubmit/SessionStart/...) and calls write_source_raw_session with origin=codex-session|claude-code-session, minting a full raw_sessions row per hook -\u003e the materializer turns each into an EMPTY standalone index session (0 messages). Each hook is double-recorded: correctly as a raw_hook_events row carrying session_native_id (table indexed (origin,session_native_id,observed_at_ms) for attach-to-session), AND wrongly as a raw_sessions row.\n\nScale on live archive /realm/db/polylogue: index sessions=83,279 but only 17,553 have content; 65,727 empty shells = codex 35,233 + claude-code 30,488. source_path LIKE '%/hooks/%' raws: codex 35,216 + claude-code 29,679 + hermes 1 = 64,896 = raw_hook_events row count. Real conversations ~17.5K (matches operator memory of ~16K). raw_hook_events has NO FK to raw_sessions, so hooks can persist without minting sessions.\n\nAlso inflates the raw-authority reconciler backlog (hjpx/lkrc/t93b) which churns over hook raws mixed with real session raws.\n\nFIX (operator decisions 2026-07-22): (1) code: add write_source_hook_event writing raw_hook_events + retained blob_ref, NO raw_sessions row; _persist_record uses it; materializer guard so hook-origin raws never become sessions; covers codex/claude/hermes. (2) constructive: materialize raw_hook_events into an index read-model attached to sessions via session_native_id (index tier rebuildable) + read surfaces (MCP/CLI). Operator: hooks are always within a session; link them. (3) retroactive repair WITHOUT full reindex: delete 64,896 hook raw_sessions rows from source.db (durable; backup at /realm/staging/polylogue-sqlite/recovery/t93b-preflight-20260722-durable) + 64,896 empty index session rows (zero messages/blocks/FTS -\u003e tiny blast radius, targeted DELETE). keep raw_hook_events+blobs. (4) re-census raw-authority; deploy #3261 (whale budget fix, merged) so frontier repair doesn't abort on 298MB whale.\n\nDesign doc: .agent/scratch/hook-session-inflation-2026-07-22.md. Verification: sessions count ~17.5K post-repair; every hook event still resolves to its session via session_native_id; no message/block/FTS row dropped.","status":"open","priority":0,"issue_type":"bug","owner":"[email protected]","created_at":"2026-07-22T12:42:26Z","created_by":"Sinity","updated_at":"2026-07-22T12:42:26Z","dependency_count":0,"dependent_count":0,"comment_count":0}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Repo root: '; pwd
printf '\nTracked .beads files:\n'
git ls-files .beads || true

printf '\nTop-level files:\n'
git ls-files | sed -n '1,120p'

printf '\nSearch for beads-related docs/config:\n'
rg -n --hidden --glob '!.git' --glob '!node_modules' '\.beads|beads|issues\.jsonl' -S . || true

Repository: Sinity/polylogue

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Tracked .beads files:\n'
git ls-files .beads || true

printf '\nSearch for docs mentioning .beads or issue storage:\n'
rg -n --hidden --glob '!.git' --glob '!node_modules' '\.beads|beads|issues\.jsonl' -S . || true

printf '\nRelevant metadata files:\n'
find . -maxdepth 2 \( -name 'README*' -o -name '*.md' -o -name '.gitignore' -o -name '.ignore' \) | sed -n '1,120p'

Repository: Sinity/polylogue

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Tracked .beads/issues.jsonl:\n'
git ls-files -- .beads/issues.jsonl || true

printf '\n.gitignore mentions:\n'
rg -n --hidden --glob '!.git' '(^|/)\.beads(/|$)|issues\.jsonl|beads' .gitignore .git/info/exclude **/.gitignore 2>/dev/null || true

printf '\nDocs/config mentions:\n'
rg -n --hidden --glob '!.git' --glob '!node_modules' '\.beads|issues\.jsonl' README* docs .agent .github polylogue tests 2>/dev/null | head -n 200 || true

Repository: Sinity/polylogue

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Tracked bead files:\n'
git ls-files -- .beads .beads/issues.jsonl || true

printf '\nIgnore rules:\n'
for f in .gitignore .git/info/exclude; do
  if [ -f "$f" ]; then
    printf '\n[%s]\n' "$f"
    rg -n '\.beads|issues\.jsonl|beads' "$f" || true
  fi
done

printf '\nDocs mentioning beads:\n'
rg -n --hidden --glob '!.git' --glob '!node_modules' '\.beads|issues\.jsonl|beads' README* docs .agent .github polylogue tests --max-count 40 || true

Repository: Sinity/polylogue

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "tracked:"
git ls-files -- .beads .beads/issues.jsonl || true

echo
echo "ignored:"
git check-ignore -v .beads .beads/issues.jsonl || true

echo
echo "markdown mentions:"
files=$(git ls-files '*.md' 'README*' '.gitignore' '.git/info/exclude' | tr '\n' ' ')
if [ -n "$files" ]; then
  rg -n '\.beads|issues\.jsonl|beads' $files || true
fi

Repository: Sinity/polylogue

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "tracked:"
git ls-files -- .beads/issues.jsonl || true

echo
echo "ignored:"
git check-ignore -v .beads .beads/issues.jsonl || true

echo
echo "policy snippets:"
for f in CLAUDE.md README.md .gitignore; do
  if [ -f "$f" ]; then
    echo "== $f =="
    rg -n --max-count 8 '\.beads|issues\.jsonl|Beads' "$f" || true
  fi
done

Repository: Sinity/polylogue

Length of output: 1175


Keep this Beads record sanitized .beads/issues.jsonl is tracked and re-imported by hooks, so personal emails, absolute host/backup paths, and other incident details should stay out of the shared issue log. Move the full evidence to restricted incident notes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In @.beads/issues.jsonl at line 1, Sanitize the Beads issue record for
polylogue-31r1 by removing personal email addresses, absolute host or backup
paths, and detailed incident evidence from the tracked entry. Keep only a
concise, non-sensitive summary of the hook-session inflation issue and required
remediation, and move the full evidence to restricted incident notes.

Comment on lines +67 to +130
with sqlite3.connect(source_db) as source_conn:
source_conn.execute("PRAGMA foreign_keys = ON")
hook_raw_ids = _hook_raw_ids(source_conn)
raw_hook_events_before = int(source_conn.execute("SELECT COUNT(*) FROM raw_hook_events").fetchone()[0])

# Index-side target session ids: sessions whose source raw is a hook raw
# AND which carry no content (belt-and-suspenders against ever deleting a
# session that somehow materialized messages).
index_session_ids: list[str] = []
if index_db.is_file() and hook_raw_ids:
with sqlite3.connect(index_db) as idx_ro:
_load_ids(idx_ro, "_hook_raw_ids", hook_raw_ids)
index_session_ids = [
str(row[0])
for row in idx_ro.execute(
"SELECT session_id FROM sessions "
"WHERE raw_id IN (SELECT id FROM _hook_raw_ids) AND message_count = 0"
)
]

if dry_run:
hook_blob_refs = int(
source_conn.execute(
"SELECT COUNT(*) FROM blob_refs WHERE ref_type='raw_payload' "
"AND ref_id IN (SELECT raw_id FROM raw_sessions WHERE " + _HOOK_RAW_PREDICATE + ")"
).fetchone()[0]
)
return HookDeinflationReport(
hook_raw_sessions=len(hook_raw_ids),
hook_index_sessions=len(index_session_ids),
raw_hook_events_before=raw_hook_events_before,
raw_hook_events_after=raw_hook_events_before,
hook_blob_refs_retained=hook_blob_refs,
applied=False,
)

# --- Apply: index first (rebuildable), then durable source. ---
if index_session_ids:
with sqlite3.connect(index_db) as idx:
idx.execute("PRAGMA foreign_keys = ON")
_load_ids(idx, "_del_sessions", index_session_ids)
idx.execute("DELETE FROM sessions WHERE session_id IN (SELECT id FROM _del_sessions)")

with sqlite3.connect(source_db) as source_conn:
source_conn.execute("PRAGMA foreign_keys = ON")
# Retain the blob refs (bytes stay rooted for GC, matching the new
# write_source_hook_event path) and raw_hook_events. Delete only the
# spurious session rows; FK cascade removes their parser-census rows.
source_conn.execute(f"DELETE FROM raw_sessions WHERE {_HOOK_RAW_PREDICATE}")
raw_hook_events_after = int(source_conn.execute("SELECT COUNT(*) FROM raw_hook_events").fetchone()[0])
hook_blob_refs = int(
source_conn.execute(
"SELECT COUNT(*) FROM blob_refs WHERE ref_type='raw_payload' AND source_path LIKE '%/hooks/pending/%'"
).fetchone()[0]
)

return HookDeinflationReport(
hook_raw_sessions=len(hook_raw_ids),
hook_index_sessions=len(index_session_ids),
raw_hook_events_before=raw_hook_events_before,
raw_hook_events_after=raw_hook_events_after,
hook_blob_refs_retained=hook_blob_refs,
applied=True,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Close the sqlite3 connections explicitly.

All four with sqlite3.connect(...) as X: blocks (lines 67, 77, 105, 110) rely on sqlite3.Connection's context manager, which only commits/rolls back — it never calls close(). ArchiveStore.delete_sessions in polylogue/storage/sqlite/archive_tiers/archive.py does the equivalent index-side delete with a correct try/finally: conn.close() pattern; this file should match it.

🔧 Proposed fix pattern (applies to all four connections)
-    with sqlite3.connect(source_db) as source_conn:
-        source_conn.execute("PRAGMA foreign_keys = ON")
-        hook_raw_ids = _hook_raw_ids(source_conn)
-        ...
+    source_conn = sqlite3.connect(source_db)
+    try:
+        source_conn.execute("PRAGMA foreign_keys = ON")
+        hook_raw_ids = _hook_raw_ids(source_conn)
+        ...
+    finally:
+        source_conn.close()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
with sqlite3.connect(source_db) as source_conn:
source_conn.execute("PRAGMA foreign_keys = ON")
hook_raw_ids = _hook_raw_ids(source_conn)
raw_hook_events_before = int(source_conn.execute("SELECT COUNT(*) FROM raw_hook_events").fetchone()[0])
# Index-side target session ids: sessions whose source raw is a hook raw
# AND which carry no content (belt-and-suspenders against ever deleting a
# session that somehow materialized messages).
index_session_ids: list[str] = []
if index_db.is_file() and hook_raw_ids:
with sqlite3.connect(index_db) as idx_ro:
_load_ids(idx_ro, "_hook_raw_ids", hook_raw_ids)
index_session_ids = [
str(row[0])
for row in idx_ro.execute(
"SELECT session_id FROM sessions "
"WHERE raw_id IN (SELECT id FROM _hook_raw_ids) AND message_count = 0"
)
]
if dry_run:
hook_blob_refs = int(
source_conn.execute(
"SELECT COUNT(*) FROM blob_refs WHERE ref_type='raw_payload' "
"AND ref_id IN (SELECT raw_id FROM raw_sessions WHERE " + _HOOK_RAW_PREDICATE + ")"
).fetchone()[0]
)
return HookDeinflationReport(
hook_raw_sessions=len(hook_raw_ids),
hook_index_sessions=len(index_session_ids),
raw_hook_events_before=raw_hook_events_before,
raw_hook_events_after=raw_hook_events_before,
hook_blob_refs_retained=hook_blob_refs,
applied=False,
)
# --- Apply: index first (rebuildable), then durable source. ---
if index_session_ids:
with sqlite3.connect(index_db) as idx:
idx.execute("PRAGMA foreign_keys = ON")
_load_ids(idx, "_del_sessions", index_session_ids)
idx.execute("DELETE FROM sessions WHERE session_id IN (SELECT id FROM _del_sessions)")
with sqlite3.connect(source_db) as source_conn:
source_conn.execute("PRAGMA foreign_keys = ON")
# Retain the blob refs (bytes stay rooted for GC, matching the new
# write_source_hook_event path) and raw_hook_events. Delete only the
# spurious session rows; FK cascade removes their parser-census rows.
source_conn.execute(f"DELETE FROM raw_sessions WHERE {_HOOK_RAW_PREDICATE}")
raw_hook_events_after = int(source_conn.execute("SELECT COUNT(*) FROM raw_hook_events").fetchone()[0])
hook_blob_refs = int(
source_conn.execute(
"SELECT COUNT(*) FROM blob_refs WHERE ref_type='raw_payload' AND source_path LIKE '%/hooks/pending/%'"
).fetchone()[0]
)
return HookDeinflationReport(
hook_raw_sessions=len(hook_raw_ids),
hook_index_sessions=len(index_session_ids),
raw_hook_events_before=raw_hook_events_before,
raw_hook_events_after=raw_hook_events_after,
hook_blob_refs_retained=hook_blob_refs,
applied=True,
)
source_conn = sqlite3.connect(source_db)
try:
source_conn.execute("PRAGMA foreign_keys = ON")
hook_raw_ids = _hook_raw_ids(source_conn)
raw_hook_events_before = int(source_conn.execute("SELECT COUNT(*) FROM raw_hook_events").fetchone()[0])
# Index-side target session ids: sessions whose source raw is a hook raw
# AND which carry no content (belt-and-suspenders against ever deleting a
# session that somehow materialized messages).
index_session_ids: list[str] = []
if index_db.is_file() and hook_raw_ids:
idx_ro = sqlite3.connect(index_db)
try:
_load_ids(idx_ro, "_hook_raw_ids", hook_raw_ids)
index_session_ids = [
str(row[0])
for row in idx_ro.execute(
"SELECT session_id FROM sessions "
"WHERE raw_id IN (SELECT id FROM _hook_raw_ids) AND message_count = 0"
)
]
finally:
idx_ro.close()
if dry_run:
hook_blob_refs = int(
source_conn.execute(
"SELECT COUNT(*) FROM blob_refs WHERE ref_type='raw_payload' "
"AND ref_id IN (SELECT raw_id FROM raw_sessions WHERE " + _HOOK_RAW_PREDICATE + ")"
).fetchone()[0]
)
return HookDeinflationReport(
hook_raw_sessions=len(hook_raw_ids),
hook_index_sessions=len(index_session_ids),
raw_hook_events_before=raw_hook_events_before,
raw_hook_events_after=raw_hook_events_before,
hook_blob_refs_retained=hook_blob_refs,
applied=False,
)
finally:
source_conn.close()
# --- Apply: index first (rebuildable), then durable source. ---
if index_session_ids:
idx = sqlite3.connect(index_db)
try:
idx.execute("PRAGMA foreign_keys = ON")
_load_ids(idx, "_del_sessions", index_session_ids)
idx.execute("DELETE FROM sessions WHERE session_id IN (SELECT id FROM _del_sessions)")
finally:
idx.close()
source_conn = sqlite3.connect(source_db)
try:
source_conn.execute("PRAGMA foreign_keys = ON")
# Retain the blob refs (bytes stay rooted for GC, matching the new
# write_source_hook_event path) and raw_hook_events. Delete only the
# spurious session rows; FK cascade removes their parser-census rows.
source_conn.execute(f"DELETE FROM raw_sessions WHERE {_HOOK_RAW_PREDICATE}")
raw_hook_events_after = int(source_conn.execute("SELECT COUNT(*) FROM raw_hook_events").fetchone()[0])
hook_blob_refs = int(
source_conn.execute(
"SELECT COUNT(*) FROM blob_refs WHERE ref_type='raw_payload' AND source_path LIKE '%/hooks/pending/%'"
).fetchone()[0]
)
finally:
source_conn.close()
return HookDeinflationReport(
hook_raw_sessions=len(hook_raw_ids),
hook_index_sessions=len(index_session_ids),
raw_hook_events_before=raw_hook_events_before,
raw_hook_events_after=raw_hook_events_after,
hook_blob_refs_retained=hook_blob_refs,
applied=True,
)
🧰 Tools
🪛 OpenGrep (1.25.0)

[ERROR] 115-115: SQL query built via f-string passed to execute()/executemany(). Use parameterized queries with placeholders instead.

(coderabbit.sql-injection.python-fstring-execute)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/maintenance/hook_deinflation.py` around lines 67 - 130, Explicitly
close every SQLite connection in the four blocks using sqlite3.connect: the
source connection used for inspection/dry-run, the index read-only connection,
the index deletion connection, and the final source deletion connection.
Preserve each block’s commit/rollback behavior while adding try/finally cleanup,
matching the connection-lifecycle pattern used by ArchiveStore.delete_sessions.

Comment on lines +72 to +85
# Index-side target session ids: sessions whose source raw is a hook raw
# AND which carry no content (belt-and-suspenders against ever deleting a
# session that somehow materialized messages).
index_session_ids: list[str] = []
if index_db.is_file() and hook_raw_ids:
with sqlite3.connect(index_db) as idx_ro:
_load_ids(idx_ro, "_hook_raw_ids", hook_raw_ids)
index_session_ids = [
str(row[0])
for row in idx_ro.execute(
"SELECT session_id FROM sessions "
"WHERE raw_id IN (SELECT id FROM _hook_raw_ids) AND message_count = 0"
)
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Source-side delete has no message_count guard, unlike the matching index-side delete.

The index-side deletion (lines 82-85) is explicitly guarded by message_count = 0 — the code's own comment calls this "belt-and-suspenders against ever deleting a session that somehow materialized messages." The source-side delete (line 115) deletes every raw_sessions row matching _HOOK_RAW_PREDICATE unconditionally. Since sessions.raw_id in index.db has no real cross-database FK to raw_sessions.raw_id in source.db, if a hook raw were ever linked to a session with message_count > 0 (the exact case the index-side guard defends against), the index-side delete would correctly skip that session, but the source-side delete would still remove its raw_sessions row — leaving that surviving session with a dangling raw_id reference, silently, with nothing in either database able to detect it.

The module docstring asserts this predicate is empirically 1:1 with raw_hook_events on the live archive, so this may never trigger in practice — but a repair tool whose entire purpose is fixing corruption should fail loudly rather than silently propagate a new (much rarer) corruption if that invariant is ever wrong.

🛡️ Proposed guard before the destructive delete
         if index_db.is_file() and hook_raw_ids:
             with sqlite3.connect(index_db) as idx_ro:
                 _load_ids(idx_ro, "_hook_raw_ids", hook_raw_ids)
                 index_session_ids = [...]
+                non_empty = int(
+                    idx_ro.execute(
+                        "SELECT COUNT(*) FROM sessions WHERE raw_id IN "
+                        "(SELECT id FROM _hook_raw_ids) AND message_count > 0"
+                    ).fetchone()[0]
+                )
+                if non_empty:
+                    raise RuntimeError(
+                        f"{non_empty} hook-derived raw ids are linked to non-empty sessions; "
+                        "refusing to delete their raw_sessions rows"
+                    )

Also applies to: 103-121

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/maintenance/hook_deinflation.py` around lines 72 - 85, Update the
source-side deletion flow in the maintenance function around the raw_sessions
delete to apply the same message_count = 0 safety condition used when building
index_session_ids. Ensure hook-matching raw_sessions rows are deleted only when
no linked session contains messages; otherwise preserve them and let the repair
operation fail loudly or report the inconsistency rather than creating dangling
sessions.raw_id references.

Comment on lines +1804 to +1845
def write_hook_event(
self,
*,
provider: Provider,
payload: bytes,
source_path: str,
acquired_at_ms: int,
hook_event: ArchiveHookEvent,
source_index: int = 0,
) -> str:
"""Persist a hook event as session-linked evidence, not a session.

Publishes the raw bytes (durable blob) and writes a ``raw_hook_events``
row keyed to its parent session via ``hook_event.session_native_id`` —
but NO ``raw_sessions`` row, so a hook can never materialize into a
standalone empty session (polylogue-31r1).
"""
if self._blob_publisher is None:
raise RuntimeError("raw archive writes require a writable archive publisher")
raw_hash, _raw_size = self._blob_publisher.write_from_bytes(payload)
receipt_id = self._blob_publisher.receipt_id(raw_hash)
self._blob_publisher.flush()
origin = origin_from_provider(provider)
raw_id = deterministic_raw_session_id(
origin,
source_path,
source_index,
deterministic_blob_hash(payload),
hook_event.native_id,
)
return write_source_hook_event(
self._ensure_source_conn(),
origin=origin,
source_path=source_path,
payload=payload,
acquired_at_ms=acquired_at_ms,
raw_id=raw_id,
hook_event=hook_event,
blob_publication_receipt_id=receipt_id,
manage_transaction=True,
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Assert hook_event.origin matches the derived origin before persisting.

write_hook_event derives origin from provider for the deterministic raw_id, but hook_event.origin (stored in raw_hook_events.origin) is a separately-supplied value from the caller. Nothing here checks the two agree — currently true by convention in hooks.py, but not enforced by this substrate method.

♻️ Proposed guard
         origin = origin_from_provider(provider)
+        if _enum_value(hook_event.origin) != origin.value:
+            raise ValueError(
+                f"hook_event.origin ({hook_event.origin!r}) does not match provider-derived origin ({origin!r})"
+            )
         raw_id = deterministic_raw_session_id(
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def write_hook_event(
self,
*,
provider: Provider,
payload: bytes,
source_path: str,
acquired_at_ms: int,
hook_event: ArchiveHookEvent,
source_index: int = 0,
) -> str:
"""Persist a hook event as session-linked evidence, not a session.
Publishes the raw bytes (durable blob) and writes a ``raw_hook_events``
row keyed to its parent session via ``hook_event.session_native_id`` —
but NO ``raw_sessions`` row, so a hook can never materialize into a
standalone empty session (polylogue-31r1).
"""
if self._blob_publisher is None:
raise RuntimeError("raw archive writes require a writable archive publisher")
raw_hash, _raw_size = self._blob_publisher.write_from_bytes(payload)
receipt_id = self._blob_publisher.receipt_id(raw_hash)
self._blob_publisher.flush()
origin = origin_from_provider(provider)
raw_id = deterministic_raw_session_id(
origin,
source_path,
source_index,
deterministic_blob_hash(payload),
hook_event.native_id,
)
return write_source_hook_event(
self._ensure_source_conn(),
origin=origin,
source_path=source_path,
payload=payload,
acquired_at_ms=acquired_at_ms,
raw_id=raw_id,
hook_event=hook_event,
blob_publication_receipt_id=receipt_id,
manage_transaction=True,
)
def write_hook_event(
self,
*,
provider: Provider,
payload: bytes,
source_path: str,
acquired_at_ms: int,
hook_event: ArchiveHookEvent,
source_index: int = 0,
) -> str:
"""Persist a hook event as session-linked evidence, not a session.
Publishes the raw bytes (durable blob) and writes a ``raw_hook_events``
row keyed to its parent session via ``hook_event.session_native_id`` —
but NO ``raw_sessions`` row, so a hook can never materialize into a
standalone empty session (polylogue-31r1).
"""
if self._blob_publisher is None:
raise RuntimeError("raw archive writes require a writable archive publisher")
raw_hash, _raw_size = self._blob_publisher.write_from_bytes(payload)
receipt_id = self._blob_publisher.receipt_id(raw_hash)
self._blob_publisher.flush()
origin = origin_from_provider(provider)
if _enum_value(hook_event.origin) != origin.value:
raise ValueError(
f"hook_event.origin ({hook_event.origin!r}) does not match provider-derived origin ({origin!r})"
)
raw_id = deterministic_raw_session_id(
origin,
source_path,
source_index,
deterministic_blob_hash(payload),
hook_event.native_id,
)
return write_source_hook_event(
self._ensure_source_conn(),
origin=origin,
source_path=source_path,
payload=payload,
acquired_at_ms=acquired_at_ms,
raw_id=raw_id,
hook_event=hook_event,
blob_publication_receipt_id=receipt_id,
manage_transaction=True,
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/sqlite/archive_tiers/archive.py` around lines 1804 - 1845,
In write_hook_event, validate that hook_event.origin matches the origin derived
from provider before publishing the payload or persisting the event. Raise an
appropriate validation error on mismatch, and keep the existing persistence flow
unchanged when the values agree.

Comment on lines +536 to +582
def write_source_hook_event(
conn: sqlite3.Connection,
*,
origin: Origin | str,
source_path: str,
payload: bytes,
acquired_at_ms: int,
raw_id: str,
hook_event: ArchiveHookEvent,
blob_publication_receipt_id: str | None = None,
manage_transaction: bool = True,
) -> str:
"""Persist a hook event WITHOUT minting a session.

A hook event (PreToolUse / PostToolUse / UserPromptSubmit / …) is evidence
*within* an existing session (identified by ``hook_event.session_native_id``),
never a conversation of its own. It therefore gets a durable ``raw_payload``
blob ref (so blob GC + copy-forward treat it like any other retained bytes)
and a ``raw_hook_events`` row, but — unlike :func:`write_source_raw_session` —
NO ``raw_sessions`` row. Writing a ``raw_sessions`` row per hook is exactly
the defect that inflated the archive with tens of thousands of empty
session shells (polylogue-31r1); ``raw_hook_events`` has no FK to
``raw_sessions``, so the linkage stands on its own via ``session_native_id``.
"""
conn.execute("PRAGMA foreign_keys = ON")
if _enum_value(origin) is None:
raise ValueError("origin is required for hook events")
blob_hash = deterministic_blob_hash(payload)
if is_blob_hash_excised(conn, blob_hash):
raise ContentExcisedError(blob_hash=blob_hash, source_path=source_path)
blob_size = len(payload)
with conn if manage_transaction else nullcontext():
_insert_blob_ref(
conn,
ArchiveSourceBlobRef(
blob_hash=blob_hash,
raw_id=raw_id,
ref_type="raw_payload",
source_path=source_path,
size_bytes=blob_size,
acquired_at_ms=acquired_at_ms,
publication_receipt_id=blob_publication_receipt_id,
),
)
_insert_hook_event(conn, raw_id, hook_event)
return raw_id

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Update ContentExcisedError's docstring to list the third gating function.

The class docstring (lines 22-41) says excision-gating is enforced by "two acquire-time raw-session write functions" — write_source_raw_session and write_source_raw_session_blob_ref. write_source_hook_event now gates identically but isn't mentioned, so a future reader auditing this invariant could miss it.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/storage/sqlite/archive_tiers/source_write.py` around lines 536 -
582, Update the ContentExcisedError class docstring to identify three
acquire-time write functions and include write_source_hook_event alongside
write_source_raw_session and write_source_raw_session_blob_ref. Keep the
existing excision-gating description and invariant unchanged.

Sinity added a commit that referenced this pull request Jul 27, 2026
## Summary
- New `ArchiveStore.hook_event_summary_for_session()` read model joining `raw_hook_events` to a session by `(origin, native_id)`.
- Exposed via a new `hooks` CLI read-view (`polylogue read <session> --view hooks`), following the existing messages/raw view registration pattern.

## Problem
polylogue-31r1's original bug (hook events ingested as standalone sessions, inflating the archive ~4.7x) was fixed weeks ago (PR #3265). The bead stayed open for one named fast-follow: hook events are now persisted correctly as `raw_hook_events` linked to their originating session, but no read surface exposed "how many/which hook events happened during session X" — `polylogue/cli/commands/hooks.py` only covered hook-harness install/status.

## Solution
`hook_event_summary_for_session()` returns per-event-type counts plus first/last observed timestamps. Hook rows have no `raw_id` link since they attach to the session identity, not to any one raw acquisition record, so the join is by `(origin, native_id)`.

## Verification
- `tests/unit/core/test_facade_api.py` (archive-layer summary correctness including missing-session/no-hooks cases)
- `tests/unit/cli/test_messages.py` (CLI JSON/YAML/missing-session)
- `tests/unit/api/test_facade_contracts.py` (registers the new facade method in `READ_BY_ID_NONE_METHODS`)
- 328 tests passed across the three files
- `mypy --strict` clean on all 8 changed source files
- `ruff check` + `format`: clean
- `devtools render all --check`: clean (topology projection regenerated)
- pre-push quick gate: all 16 checks green

Ref polylogue-31r1
Sinity added a commit that referenced this pull request Jul 27, 2026
…ry (#3328)

## Summary

Adds `devtools/mandate_continuity_replay.py` (`devtools workspace
mandate-continuity-replay`), the z9gh.7-owned artifact its own
2026-07-20 notes named as the missing residual: a replay runner wiring
polylogue-t8t's continuity scenarios, polylogue-1vpm.6.2's work-evidence
effect-reconciliation adapters, and polylogue-z9gh.3's query-discovery
catalog into one privacy-safe JSON artifact.

## Problem

`bd show polylogue-z9gh.7` (P0 terminal mandate gate, "Prove mandate
recovery through real agent continuity replays") records this exact gap
in its 2026-07-20 "CONCRETE BAR" note:

> a z9gh.7-owned replay runner wiring t8t scenarios + work-evidence
graph + discovery into one privacy-safe live-scale artifact (size M,
does not exist)

Each dependency is independently proven but nothing combined them:
- polylogue-t8t (closed) proves the 7 continuity scenarios +
parallel-Claude incident variant in isolation via
`devtools/continuity_replay.py`.
- polylogue-1vpm.6.2 (closed, PR #3199) supplies real
`GitCommitEffectAdapter`/`BeadsIssueEffectAdapter`/`GitHubPullRequestEffectAdapter`
in `polylogue/insights/work_effects.py`, but nothing outside its own
tests exercises them at repository scale.
- polylogue-z9gh.3 (in progress) supplies `QUERY_DISCOVERY_EXAMPLES`,
but nothing cross-checks it against what the continuity scenarios
actually execute.

(The bead's note also names `polylogue-1vpm.6.2`'s effect adapters as
"confirmed DEAD CODE" — that note predates 1vpm.6.2's own closure later
the same day; source review here confirms
`reconcile_graph_repository_effects` is real, wired production code with
a CLI (`polylogue/cli/commands/reconcile_work_effects.py`). That gap is
closed already and untouched by this PR.)

## Solution

`devtools/mandate_continuity_replay.py`:

- **Continuity lane**: calls `devtools.continuity_replay.replay_archive`
unmodified against a freshly seeded synthetic corpus (default, CI-safe)
or an authorized `--archive-root` (live-scale lane).
- **Discovery lane** (`check_discovery_coverage`): for every
`query`-tool route step any continuity scenario issues, proves a
matching positive example exists in `QUERY_DISCOVERY_EXAMPLES` with the
same unit-source/route shape — i.e. a cold model relying on the
published catalog alone could have formulated that plan family.
- **Work-evidence lane** (`build_repository_claim_graph` +
`run_work_evidence_effect_proof`): builds independent claim nodes from
this repository's own `.beads/interactions.jsonl` "issue closed"
transitions, then reconciles them through the real
`GitCommitEffectAdapter`/`BeadsIssueEffectAdapter`/`GitHubPullRequestEffectAdapter`
against this repo's actual git history — real, full-repo scale,
privacy-safe because both are already public/committed project
artifacts, not private chat content. The GitHub adapter's explicit
`EffectAdapterUnavailableError` is recorded as the honest "cites PR
effects with uncertainty" AC clause, not a silent omission.
- **`redact_report`**: recursively hashes evidence-prose fields
(`label`/`claim_text`/`reason`), keeping refs/ids/counts — a no-op proof
on the synthetic lane, load-bearing on an authorized live-archive run.
- **AC matrix** (`build_ac_matrix`): maps the run onto z9gh.7's own 7
acceptance-criteria items, each explicitly
`satisfied`/`deferred`/`blocking` with a cited reason.

Registered in `devtools/command_catalog.py`; regenerated
`docs/devtools.md` + `docs/plans/topology-target.yaml` (new module needs
the topology projection per repo convention).

**Real pre-existing bug found and fixed along the way**: t8t's own
`self-inspection` oracle (`tests/data/continuity/catalog.json`) still
declared 11 read-views; production `polylogue/cli/read_view_registry.py`
has shipped 12 (the `hooks` view, added after #3265) for a while.
`tests/integration/test_continuity_replay.py` was already failing on
current master before this PR for the same reason — confirmed by running
it unmodified prior to the fix. Fixed the fixture fact (11→12, added
`hooks` to the id list); not otherwise in scope for this PR.

## What this PR does NOT close (stated honestly, matching the artifact's
own AC matrix)

- **AC2** (the live 2026-07-15 incident replay finding the real
coordinator `cf0c6474-...`/run `wf_54d4fb2e-841` in a promoted live
archive) needs an authorized live archive this sandbox does not have.
The artifact proves the identical mechanism against t8t's synthetic
91/38/129/4 census and reports this item `deferred`, with an explicit
note on how to re-run it live (`--archive-root`).
- **AC6** (mutation checks) is already t8t's own proven scope
(`tests/infra/continuity_mutations.py`, 6 named families); this artifact
cites that suite rather than duplicating it.
- polylogue-1vpm.6.2's own residual (`session_commit` retirement, named
in its own PR #3199 body) is untouched — out of scope here.

## Verification

- `devtools test tests/unit/devtools/test_mandate_continuity_replay.py
tests/integration/test_mandate_continuity_replay.py` → 15 passed
- `devtools test tests/integration/test_continuity_replay.py` → 12
passed (confirms the read-view-count fixture fix; was 11 passed/1 failed
before)
- `mypy --strict` on all touched files → Success: no issues found
- `ruff format`/`ruff check` on all touched files → All checks passed
- `devtools render all --check` → exit 0
- `devtools verify --quick` → exit 0 (ran automatically on push via
pre-push hook)

Ref polylogue-z9gh.7

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 30, 2026
polylogue-b508 records that 4,945 of 16,312 claude-code sessions (30.3%) are
agent-<id>.meta subagent metadata sidecars materialized as conversations, none
carrying messages, with the real subagent transcript separately present in all
300 sampled cases. Plus 10 sessions keyed on tool-use and workflow ids.

Same bug class as the hook-event inflation already fixed once (83,286 -> 18,391,
PR #3265) -- a different sidecar type surviving because that fix targeted hook
events specifically rather than the category. Proposed direction is the
structural rule: a payload may only become a session when the PROVIDER asserted
a session identity, so a filename-derived fallback is a parse refusal.

Co-Authored-By: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 30, 2026
…ds (#3403)

## Summary

Fixes the mechanism behind polylogue-b508 (21% of claude-code-session
index
rows being `agent-*.meta.json`/`toolu_*`/`wf_*` phantom sessions):
closes the
one dispatch branch with no provider-specific identity handling, and
gates
the offline index-rebuild replay path against the same OriginSpec
"fact-not-session" rule the live daemon already enforces.

## Problem

The bead's hypothesis ("provider detection treats any JSON under
`subagents/` as session-bearing, session id falls back to the filename
stem") was traced in code rather than assumed, per the bead's own
instruction, and turned out to be partly wrong in an important way:

- The **live daemon ingest path** (`sources/live/batch.py` +
  `pipeline/services/ingest_worker.py`) already refuses to session-parse

`agent-*.meta.json`/workflow-run-snapshot/workflow-journal/adopt-manifest
artifacts, via `classify_artifact_path`'s OriginSpec-driven rule table.
  Proved empirically: ingesting 9 real files pulled from a live
  `~/.claude/projects` corpus (1 top-level session, 3 real subagent
  transcripts, 4 real `agent-*.meta.json` sidecars, 1 standalone
  meta+transcript pair) through `LiveBatchProcessor` produced exactly 5
  real sessions, 0 phantom `.meta` rows.
- The **actual live bug** is a second, separate parse chokepoint:
  `sources/revision_backfill.py` (`_parse_one`/`_parse_stream`, driving
  `polylogue ops reset --index` / the offline rebuild-index path) called
  `dispatch.parse_payload`/`parse_stream_payload` on every retained raw
  **unconditionally**, with no OriginSpec/artifact-taxonomy awareness at
  all. Reproduced live: rebuilding an index from the same 9-file corpus
  through this path (bypassing the daemon) produced 4 phantom
`claude-code-session:agent-<id>.meta` sessions (0 messages, 0 events) —
the exact reported shape, because `fallback_id = Path(source_path).stem`
  on `agent-<id>.meta.json` strips only `.json`. This means the bead's
suggested remediation ("rebuild the index") would have **recreated** the
  defect on every future rebuild, not eliminated it.
- A structural gap also existed independent of both: `dispatch.py`'s
`_generic_messages_session` — the one payload-lowering branch with zero
  provider-specific identity handling — fell back to a filename-stem
  `fallback_id` whenever a payload merely had a `messages` list and no
  `id`. It didn't reproduce with real `.meta.json` fixtures (those are
  covered by OriginSpec), but is exactly the "next sidecar format" risk
  the bead is about (same pathology class as the hook-event inflation
  fixed once by PR #3265, which didn't generalize).

## Solution

1. `polylogue/sources/dispatch.py`: `_generic_messages_session` now
requires the payload to assert its own `id`; absent that, it refuses to
parse (`None`) instead of synthesizing an identity from `fallback_id`.
2. `polylogue/sources/revision_backfill.py`:
`_parse_one`/`_parse_stream`
   now consult `artifact_rule_for_path` (the same OriginSpec table
   `batch.py` already uses) and refuse to parse when the declared
   artifact's `parse_policy` isn't `"session"`. One rule table enforced
   at both entry points, so a rebuild and a live ingest can no longer
   disagree.

Metadata retention (AC: no data loss): unaffected by this change.
`insights/claude_workflow_materializer.py`/`claude_workflow_evidence.py`
already read `agent_sidecar_meta` facts from retained raw bytes
independent of whether a `sessions` row exists, and materialize them
into
the `claude-workflow:*` work-evidence graph. This fix only removes the
duplicate phantom `sessions` row; the raw bytes and the metadata graph
are
untouched.

`toolu_*`/`wf_*` (10 rows total in the live archive): `wf_*` is covered
structurally by fix #2 (same declared-fact mechanism as `.meta.json`).
`toolu_*` (3 rows) could not be reproduced with real fixture data — real
`tool-results/*.txt` sidecars are excluded by suffix filtering and never
declared in OriginSpec, so any surviving `toolu_*` rows are likely
relics
of an older, already-superseded acquisition-scope bug; flagged as a
narrow follow-up if any survive the live remediation rebuild.

Live-archive remediation (not run by this PR — evidence-only, per
operator instruction): `polylogue ops reset --index && polylogued run`.
Verified there is no `parsed_at_ms`-style skip in the rebuild path
(`all_index_rebuild_raw_ids` selects every raw unconditionally,
`RebuildIndexRequest(only_missing=False)` forces a full replay, and
content-hash idempotency is moot against a freshly wiped index.db) — no
additional durable-tier invalidation is needed beyond this code fix.
Full procedure recorded on polylogue-b508.

## Verification

- `devtools test tests/unit/sources/test_source_laws.py` — 130 passed
  (128 pre-existing + 2 new).
- `devtools test tests/unit/sources/test_revision_backfill.py` — 50
passed
  (49 pre-existing + 1 new, parametrized ×4).
- Anti-vacuity (both fixes): reverted each guard in isolation and
  confirmed the new regression test(s) fail before restoring the fix.
- Real-corpus end-to-end proof: rebuilding a throwaway archive from 9
real
Claude Code files (4 `agent-*.meta.json` sidecars among them) produced 9
sessions / 4 phantom `.meta` rows before fix #2, 5 sessions / 0 phantom
  after — with identical message counts on the 3 real subagent
  transcripts in both states (no data loss).
- `git push` ran the pre-push `devtools verify --quick` gate (format +
  lint + mypy + `render all --check`) — clean on both commits.
- Not run: `devtools verify --all`/broad testmon pass (background, will
  report before merge); no mutation against the live archive
  (`/realm/db/polylogue`, explicitly out of scope for this session).

Ref polylogue-b508

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Prevented unidentified message payloads from being incorrectly created
as sessions.
* Prevented fact artifacts, sidecars, snapshots, and manifests from
appearing as phantom sessions during replay.
* Improved session parsing reliability for unsupported or ambiguous
source formats.

* **Tests**
* Added regression coverage for artifact filtering and payloads missing
asserted session IDs.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude <[email protected]>
Sinity added a commit that referenced this pull request Jul 31, 2026
… repair

Problem: polylogue/maintenance/hook_deinflation.py was the retroactive
repair for hook events ingested as standalone sessions (polylogue-31r1).
The forward fix (write_source_hook_event) has owned the invariant since
PR #3265, the retroactive pass ran on the live archive, and the module
has zero production callers — only its own test imported it.

Evidence: live source.db count of rows matching the repair predicate
(source_path LIKE '%/hooks/pending/%' AND source_path IN raw_hook_events)
is 0; grep for repair_hook_session_inflation finds no caller outside the
deleted test.

Repair scaffolding for a fixed defect is pure surface area; the invariant
(hook events are never persisted as raw sessions) is maintained by the
write path and covered by its own tests.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01KAAzxpu1wNZLmuAb8Wgyso
@Sinity

Sinity commented Sep 30, 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.

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