Skip to content

fix(storage): surface lineage completeness, delegation join, checkout commits - #3444

Merged
Sinity merged 5 commits into
masterfrom
feature/storage/surface-lineage-truncation-signal
Jul 31, 2026
Merged

Sinity merged 5 commits into
masterfrom
feature/storage/surface-lineage-truncation-signal

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026 •

Copy link
Copy Markdown
Owner

Summary

Three independent fixes, each closing a beads-tracked "typed evidence computed and then discarded" gap surfaced during tonight's heuristics audit, targeted at making a report about two real archive sessions (delegation fan-out, transcript completeness, git/PR linkage) state ground truth rather than infer it from prose.

Problem

  • polylogue-ppkj: get_messages_with_lineage_completeness correctly derives a DANGLING_BRANCH_POINT truncation signal, but polylogue read and GET /api/sessions/:id/messages both go through a wrapper that drops it — a composed lineage transcript could render mid-conversation with no indication.
  • polylogue-1vpm.7: delegation resolution used to pair a Task dispatch to a resolved child by rank (ordinal position), which was wrong ~90% of the time. The fix for that was already on master, but grepping the live archive found it had zero effect on one of the two target sessions (~20 subagents): that session dispatches via the newer "Agent" tool, which classify_tool routed to a generic, non-delegation bucket, so no dispatch actions were ever recognized in the first place.
  • polylogue-cijx.3: session_commits (repo checkout HEAD at session capture) had one writer and zero readers anywhere in the codebase — a durable table nothing ever read back.

Solution

ppkj (5fd73c478): message_query_reads.get_messages_paginated now composes via the completeness-aware function directly instead of the signal-dropping wrapper, returning (messages, total, LineageCompleteness). Threaded through query_store_archive → repository → api/archive.py (sync+async) → cli/messages.py (json/markdown) → daemon/http.py's two messages handlers. SessionMessagesResponsePayload gained lineage_complete/lineage_truncation_reason. New dangling-branch-point fixtures prove the signal survives to the CLI/HTTP surface (previously only MCP carried it, via a second independent computation).

1vpm.7 (da0f76746): moved "agent" from ToolCategory.AGENT to ToolCategory.SUBAGENT in classify_tool — the Agent SDK's dispatch tool is the direct successor to Claude Code's "Task" tool (same shape: tool_input.prompt reproduced verbatim in the child's first turn), not a generic control tool like askuserquestion/skill/batch. Live evidence: claude-code-session:38baa1de-... had 24 "Agent" tool_use actions and 0 classified subagent before this fix, so delegation_facts_source found nothing to join despite the correct join-key mechanism already being in place. Filed polylogue-qsb4 as an explicit, scoped follow-up for arbitrary-depth ancestry/subtree queries (the operator flagged mid-session that delegation nests — subagents dispatching their own subagents — which this bead's join-key fix doesn't address; that's a distinct query-surface capability).

cijx.3 (04ec36f28): new SessionCommitRecord + reader (storage/sqlite/queries/session_commits.py, following the session_refs precedent), wired into both existing git-correlation entrypoints (api/archive.py::session_correlation_payload — the HTTP surface, and insights/correlation_view.py::run_correlation_view's JSON output — the CLI surface) as a checkout_commits field, explicitly kept separate from the heuristic commits list rather than merged into it.

Beads bookkeeping (51438b3f9): closed all three beads with full AC disposition; .beads/issues.jsonl synced into this branch (bd export writes to the main checkout regardless of invocation cwd, a known hazard for worktree branches).

Operational note (1vpm.7)

blocks.semantic_type is computed at parse/write time and stored — a SEMANTIC_REPARSE-class change per the schema regime rules. This PR does not trigger a reindex against the live archive (forbidden for this session; read-only access only). The fix takes effect immediately for newly-ingested/reprocessed sessions; the two target sessions' existing rows need an operator-run polylogue ops reset --index && polylogued run before their delegation resolves.

Verification

  • devtools test tests/unit/storage/test_lineage_normalization.py tests/unit/cli/test_messages.py tests/infra/mcp.py tests/unit/api/test_facade_contracts.py tests/unit/core/test_facade_api.py tests/unit/core/test_sync_surface_runtime.py tests/unit/storage/test_message_query_reads.py tests/unit/storage/test_archive_tiers_write.py — all pass except one pre-existing, unrelated failure (test_archive_tiers_api_raw_artifacts_read_source_tier, a known "clock freeze_clock does not patch" gap, untouched by this diff).
  • devtools test tests/unit/sources/test_tool_aliases.py tests/unit/storage/test_delegations_view.py tests/unit/storage/test_store_ops.py — 86 passed.
  • devtools test tests/unit/api/test_facade_contracts.py tests/unit/cli/test_correlate_view.py tests/unit/insights/test_session_commit.py — pass (same one pre-existing failure).
  • mypy (repo-wide; two new modules needed the topology projection regenerated) — 0 issues.
  • devtools verify --quick — exit 0 (ran again automatically via the pre-push hook).

Per-bead AC disposition

Full disposition recorded in each bead's bd close --reason:

  • polylogue-ppkj: all 4 AC satisfied.
  • polylogue-1vpm.7: AC1/2/3/5 already satisfied on master pre-session; companion classify_tool gap fixed here; depth/UX explicitly deferred to polylogue-qsb4 per operator direction.
  • polylogue-cijx.3: AC1/2/4/5 already satisfied by prior sessions (polylogue-l9su); AC3 fixed here.

Ref polylogue-ppkj, polylogue-1vpm.7, polylogue-cijx.3, polylogue-qsb4

Summary by CodeRabbit

  • New Features

    • Session message results now report whether lineage is complete and explain when it was truncated.
    • CLI and HTTP outputs include lineage status consistently, including for missing or partial sessions.
    • Correlation views now separately display detected checkout commits with repository, confidence, and evidence details.
  • Bug Fixes

    • Agent and spawn-agent tools are now classified correctly as subagent activity.
    • Lineage completeness is preserved across paginated and filtered message queries.

@coderabbitai

coderabbitai Bot commented Jul 31, 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: 53 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 Plus

Run ID: fbfd7f44-fefd-4c17-b036-4c0292c3c61f

📥 Commits

Reviewing files that changed from the base of the PR and between bd50d0d and 29e2de1.

📒 Files selected for processing (3)
  • polylogue/api/archive.py
  • polylogue/cli/messages.py
  • tests/unit/api/test_facade_contracts.py
📝 Walkthrough

Walkthrough

The change propagates lineage completeness through SQLite, archive APIs, CLI, HTTP, and schemas. It adds typed session checkout-commit records and correlation output. It also corrects delegation-tool classification and updates topology metadata and issue records.

Changes

Lineage completeness propagation

Layer / File(s) Summary
Lineage completeness in archive reads
polylogue/storage/sqlite/..., polylogue/storage/repository/archive/sessions.py, tests/unit/storage/*
Paginated reads now return LineageCompleteness. Composed transcripts report dangling branch-point truncation.
Lineage metadata in APIs and outputs
polylogue/api/..., polylogue/cli/..., polylogue/daemon/http.py, polylogue/surfaces/payloads.py, docs/schemas/..., tests/unit/cli/*, tests/unit/api/*
CLI JSON, Markdown, HTTP responses, and schemas expose completion status and truncation reasons.
Checkout-commit retrieval and correlation
polylogue/storage/runtime/..., polylogue/storage/sqlite/queries/session_commits.py, polylogue/insights/correlation_view.py, tests/unit/cli/test_correlate_view.py
Typed session commit records and SQLite readers expose recorded checkout commits separately from heuristic correlation commits.
Delegation classification and project metadata
polylogue/archive/viewport/tools.py, tests/unit/sources/test_tool_aliases.py, docs/plans/topology-target.yaml, .beads/issues.jsonl
agent and spawn_agent classify as SUBAGENT. Topology counts and related issue records are updated.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ArchiveAPI
  participant SQLiteArchive
  participant CLI
  participant HTTP
  Client->>ArchiveAPI: request paginated session messages
  ArchiveAPI->>SQLiteArchive: read messages, total, and completeness
  SQLiteArchive-->>ArchiveAPI: return pagination metadata
  ArchiveAPI-->>CLI: serialize lineage metadata
  ArchiveAPI-->>HTTP: serialize lineage metadata
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but omits the required Unreleased changelog entry for user-visible output changes. Add a one-line Unreleased changelog entry describing the lineage metadata and checkout_commits output changes.
Docstring Coverage ⚠️ Warning Docstring coverage is 43.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the three main storage and archive fixes.
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 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch feature/storage/surface-lineage-truncation-signal
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/storage/surface-lineage-truncation-signal

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: 51438b3f93

ℹ️ 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/cli/read_views/messages.py Resolved
Comment on lines +44 to +46
FROM session_commits
WHERE session_id = ?
ORDER BY created_at_ms

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Resolve native session IDs before querying checkout commits

When either correlation entrypoint is called with a provider-native ID, get_session(session_id) successfully resolves it, but the new commit reader compares that original value directly against the canonical session_commits.session_id. The payload therefore reports an empty checkout_commits list even when the row exists; resolve the identifier before this query (or pass the hydrated session's canonical ID) so both canonical and native IDs expose the evidence.

AGENTS.md reference: AGENTS.md:L47-L52

Useful? React with 👍 / 👎.

@Sinity
Sinity force-pushed the feature/storage/surface-lineage-truncation-signal branch from 51438b3 to 3ba7f49 Compare July 31, 2026 11:06
Sinity and others added 4 commits July 31, 2026 13:07
Problem: get_messages_with_lineage_completeness (message_query_reads.py)
correctly derives DANGLING_BRANCH_POINT/DEPTH_LIMIT truncation for a
composed lineage transcript, but its own get_messages() wrapper discarded
the signal, and get_messages_paginated (the function `polylogue read` and
GET /api/sessions/:id/messages actually call) never surfaced it either.
MCP was the only "safe" surface, via a second independent computation
(ArchiveSessionEnvelope). Consequence: the CLI and HTTP messages surfaces
could render a transcript that starts mid-conversation with no indication
whenever a branch point goes dangling (0 of 537 live branch points today,
per polylogue-ppkj -- dormant, not fixed).

What changed:
- message_query_reads.get_messages_paginated composes via
  get_messages_with_lineage_completeness directly (not the signal-dropping
  get_messages) and returns (messages, total, LineageCompleteness) instead
  of a 2-tuple. Added a standalone get_lineage_completeness probe for the
  material-origin-filtered read path, which builds its message list a
  different way (through the full Session domain object).
- Threaded the 3-tuple through query_store_archive, the repository layer,
  api/archive.py (Polylogue facade, both sync and async), cli/messages.py
  (json/markdown), cli/read_views/messages.py, and daemon/http.py's two
  messages handlers (DB-backed _do_get_messages and the archive-root
  fallback _do_archive_get_messages, whose ArchiveSessionEnvelope already
  carried the signal but never included it in the response body).
- SessionMessagesResponsePayload gained lineage_complete/
  lineage_truncation_reason fields, mirroring MCP's existing
  MCPMessagesListPayload naming; regenerated the CLI output schema.
- cli/messages.py and daemon/http.py's markdown/card-placement paths
  overlay the real read-time signal onto lineage_descriptor_from_session's
  hard-coded lineage_complete=None (the DB-backed Session domain model
  still carries no completeness field -- overlaying at the call site was
  the minimal fix; adding the field to Session itself is a larger,
  separate change).

Callers exercising the fix in production: `polylogue read`/`messages`
verb (cli/messages.py) and `GET /api/sessions/:id/messages`
(daemon/http.py, both the DB-backed and archive-root-backed handlers).

polylogue-ppkj AC disposition:
1. Satisfied -- lineage_complete/lineage_truncation_reason now appear in
   both `polylogue read --format json` and the HTTP messages response,
   plus the markdown/card-placement render for both.
2. Satisfied -- get_messages_paginated propagates the signal from
   get_messages_with_lineage_completeness; the plain get_messages()
   wrapper is left in place (other callers, e.g. get_messages_batch/
   iter_messages, don't need the signal and deleting it would be a wider,
   unrelated refactor).
3. Satisfied -- new fixtures in test_lineage_normalization.py and
   test_messages.py compose a session with a hard-deleted parent (dangling
   branch_point_message_id) and assert get_messages_paginated / the CLI
   JSON output are marked truncated; both fail against the pre-fix 2-tuple
   signature.
4. Deferred, decision recorded, not silently dropped: the full lineage
   repair (daemon/lineage_startup.py) still runs once per daemon start
   only, not as a DaemonConverger stage. Live measurement (0 dangling of
   537 branch points) means nothing is actively broken today, but a branch
   point going dangling between restarts would go unrepaired until the
   next restart. Making it a convergence stage is a distinct, non-trivial
   change (bounded scan cost, session-scoped retry semantics matching
   other stages) and is out of this fix's scope -- filed as a follow-up.

Verification: devtools test tests/unit/storage/test_lineage_normalization.py
tests/unit/cli/test_messages.py tests/infra/mcp.py
tests/unit/api/test_facade_contracts.py tests/unit/core/test_facade_api.py
tests/unit/core/test_sync_surface_runtime.py
tests/unit/storage/test_message_query_reads.py
tests/unit/storage/test_archive_tiers_write.py (all pass except one
pre-existing, unrelated failure: test_archive_tiers_api_raw_artifacts_read_source_tier
reads an unfrozen datetime.now(UTC) in ArchiveStore._raw_parse_success_state,
a known "clock freeze_clock does not patch" gap per recent history, not
touched by this change). devtools verify --quick: exit 0 (ruff
format/check, mypy --strict, render all --check, layering, closure-matrix,
schema-versioning, docs-coverage all green).

Ref polylogue-ppkj

Co-Authored-By: Claude <[email protected]>
Problem: polylogue-1vpm.7's join-key fix (content-identity matching,
already on master) correctly resolves a Task dispatch to its child
session -- but only for actions with semantic_type='subagent'
(delegation_facts_source: `WHERE a.semantic_type = 'subagent'`).
classify_tool (archive/viewport/tools.py) put the Claude Agent SDK's
"Agent" tool (the direct successor to Claude Code's "Task" tool, same
dispatch shape: tool_input carries a "prompt" field the child's first
turn reproduces verbatim) into the generic ToolCategory.AGENT bucket
alongside non-delegation control tools (askuserquestion/skill/batch/
todo*), not ToolCategory.SUBAGENT.

Consequence, measured live against the archive (read-only):
claude-code-session:38baa1de-... (~20 subagents dispatched via "Agent")
had 24 "Agent" tool_use actions and 0 actions classified 'subagent' --
delegation_facts_source found zero dispatch actions for this session, so
every one of its 21 resolved session_links children surfaced as
mapping_state='edge_only' (a resolved child observed only from the
session_links side, no dispatch instruction ever attached). The join-key
fix has nothing to join for any session using this tool.

What changed: classify_tool("agent", ...) now returns ToolCategory.
SUBAGENT instead of ToolCategory.AGENT.

blast radius / operational note: blocks.semantic_type is computed at
parse/write time (write.py:_semantic_type -> classify_tool) and stored,
not derived at read time -- a SEMANTIC_REPARSE-class change per the
schema regime rules (no schema/index version bump needed since no DDL
changed, but existing archives need `polylogue ops reset --index &&
polylogued run` to reclassify already-ingested "Agent" tool_use blocks).
This PR does not trigger that reindex against the live archive; the
fix takes effect for newly-ingested/reprocessed sessions immediately
and for the live archive's existing "Agent"-tool sessions once an
operator runs the reindex.

Caller exercising the fix in production: delegation_facts_source (the
view backing the `delegations` table), read through
ArchiveStore.get_delegation_card/get_delegation_attempt (api/archive.py's
`delegation:` object-ref resolution, reachable via the MCP `get` tool)
and ArchiveStore.query_delegations (the `delegations` query-unit source).

Verification: devtools test tests/unit/sources/test_tool_aliases.py
tests/unit/storage/test_delegations_view.py tests/unit/storage/test_store_ops.py
(86 passed); mypy --strict polylogue/archive/viewport/tools.py.

Ref polylogue-1vpm.7

Co-Authored-By: Claude <[email protected]>
Problem: polylogue-cijx.3 AC3 -- session_commits (the repo checkout's
HEAD commit at the moment a session was captured, written by
write_parsed_session_to_archive from ParsedSession.git_commit_hash,
method='parser-git-meta', confidence=1.0) had exactly one writer and
zero readers anywhere in the codebase (verified: grep for `FROM
session_commits` across polylogue/ found only the INSERT in write.py).
A durable table that only ever gets written is functionally dead weight
and, per the bead, "does not survive as a write-only table" -- it must
either gain a reader or be deleted. This is a genuinely distinct, honest
fact (narrow: "what commit was checked out when the session began", not
"this session produced/is associated with this commit") from the
on-demand git/GitHub correlation surface (insights/session_commit.py's
detect_session_commits, which scores commits by time-window/
file-overlap or a Claude-Session git trailer match), so it deserved its
own reader rather than being merged into that heuristic list.

What changed:
- New SessionCommitRecord model (storage/runtime/archive/records.py) and
  async/sync readers (storage/sqlite/queries/session_commits.py),
  following the same shape as the session_refs reader precedent
  (polylogue-2qx.4).
- Threaded through query_store_archive.SQLiteQueryStore and
  repository.RepositoryArchiveSessionMixin.get_session_commits.
- Wired into both existing correlation entrypoints as a `checkout_commits`
  field, clearly separated from the heuristic `commits` list (matching
  polylogue-l9su's "both existing entrypoints" precedent for typed vs
  heuristic evidence):
  - api/archive.py::session_correlation_payload (the HTTP
    GET /api/sessions/:id/correlate surface, daemon/http.py:4535)
  - insights/correlation_view.py::run_correlation_view's JSON output path
    (the CLI `read --view correlation --format json` surface)

Verification: devtools test tests/unit/api/test_facade_contracts.py
tests/unit/cli/test_correlate_view.py tests/unit/insights/test_session_commit.py
(all pass except the pre-existing, unrelated
test_archive_tiers_api_raw_artifacts_read_source_tier clock gap). mypy
(repo-wide, since a new module needs the topology projection regenerated):
0 issues. devtools render topology-projection (new module
polylogue/storage/sqlite/queries/session_commits.py registered).
devtools verify --quick: exit 0.

Ref polylogue-cijx.3

Co-Authored-By: Claude <[email protected]>
…low-up

Beads state sync into this branch's .beads/issues.jsonl -- bd export
writes to the main checkout regardless of invocation cwd (known hazard),
so worktree branches carry the closure separately.

- polylogue-ppkj: closed, fixed by 5fd73c4.
- polylogue-1vpm.7: closed, join-key fix was already on master; da0f767
  fixes the companion "Agent" tool_name classification gap that made it
  ineffective for the actual target session.
- polylogue-cijx.3: closed, fixed by 04ec36f (session_commits reader);
  most other AC already satisfied by prior sessions (polylogue-l9su).
- polylogue-qsb4: filed (new), arbitrary-depth delegation ancestry/subtree
  query surface -- scoped follow-up per operator direction, not folded
  into 1vpm.7.

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity force-pushed the feature/storage/surface-lineage-truncation-signal branch from 3ba7f49 to bd50d0d Compare July 31, 2026 11:13
# Conflicts:
#	docs/plans/topology-target.yaml

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
polylogue/cli/read_views/messages.py (1)

115-167: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Preserve lineage metadata in JSON file output.

Line 115 obtains completeness, but the JSON envelope at Lines 141-168 omits lineage_complete and lineage_truncation_reason. A truncated transcript written with read --view messages --to file is therefore indistinguishable from a complete transcript.

Write both fields into the JSON envelope. Omit lineage_truncation_reason only when it is None.

🤖 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/cli/read_views/messages.py` around lines 115 - 167, Update the JSON
envelope in the non-NDJSON output branch to include lineage_complete from the
existing completeness value and lineage_truncation_reason, omitting the reason
field when its value is None. Preserve the existing message, total, limit, and
offset fields and keep NDJSON output unchanged.
🤖 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 23: Reopen polylogue-1vpm.7 or remove its closed status until AC4 is
satisfied. The close_reason must not claim completion while the live
mapping_state distribution remains unmeasured; have the operator reindex the
existing archive and record the distribution, or create and link an explicit
operational follow-up and revise the closure text to identify AC4 as
outstanding.

In `@polylogue/api/archive.py`:
- Line 5793: Update the checkout-commit lookup in the surrounding session
retrieval flow to pass str(session.id) to repository.get_session_commits instead
of the caller-provided session_id, ensuring resolved abbreviated session IDs
query the correct session.

In `@polylogue/insights/correlation_view.py`:
- Around line 85-111: Move the session-commit retrieval from the JSON-only
branch to before output-format selection, reusing the resulting records for both
formats. Extend `_print_correlation_result` to accept and render
`checkout_commits` distinctly from `commits`, and add coverage for the non-JSON
CLI output path.

In `@polylogue/storage/runtime/archive/records.py`:
- Around line 370-377: Update the _parse_evidence validator to use
polylogue.core.json.loads instead of the standard json.loads, preserving the
empty-string fallback to {}. Validate that the parsed result is a JSON object
before returning it, rejecting non-object evidence values.

In `@polylogue/storage/sqlite/queries/message_query_reads.py`:
- Around line 390-407: Wrap session resolution, prefix-sharing detection,
lineage composition, filtering, counting, and page slicing in a single deferred
read transaction around the relevant query flow. Update the path using
_prefix_sharing_edge and get_messages_with_lineage_completeness so the nested
composition call reuses that transaction, preventing a link committed between
detection and retrieval from selecting the normal SQL path.

---

Outside diff comments:
In `@polylogue/cli/read_views/messages.py`:
- Around line 115-167: Update the JSON envelope in the non-NDJSON output branch
to include lineage_complete from the existing completeness value and
lineage_truncation_reason, omitting the reason field when its value is None.
Preserve the existing message, total, limit, and offset fields and keep NDJSON
output 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 Plus

Run ID: c87b017d-f34f-4fdf-a238-4be6d67b7fa1

📥 Commits

Reviewing files that changed from the base of the PR and between a8f7410 and bd50d0d.

📒 Files selected for processing (29)
  • .beads/issues.jsonl
  • devtools/self_verify.py
  • docs/plans/topology-target.yaml
  • docs/schemas/cli-output/session-messages-response.schema.json
  • polylogue/api/archive.py
  • polylogue/api/sync/sessions.py
  • polylogue/archive/viewport/tools.py
  • polylogue/cli/messages.py
  • polylogue/cli/read_views/messages.py
  • polylogue/daemon/http.py
  • polylogue/insights/correlation_view.py
  • polylogue/storage/repository/archive/sessions.py
  • polylogue/storage/runtime/__init__.py
  • polylogue/storage/runtime/archive/records.py
  • polylogue/storage/sqlite/async_sqlite_archive.py
  • polylogue/storage/sqlite/queries/mappers.py
  • polylogue/storage/sqlite/queries/mappers_archive.py
  • polylogue/storage/sqlite/queries/message_query_reads.py
  • polylogue/storage/sqlite/queries/messages.py
  • polylogue/storage/sqlite/queries/session_commits.py
  • polylogue/storage/sqlite/query_store_archive.py
  • polylogue/surfaces/payloads.py
  • tests/unit/api/test_facade_contracts.py
  • tests/unit/cli/test_correlate_view.py
  • tests/unit/cli/test_messages.py
  • tests/unit/core/test_facade_api.py
  • tests/unit/sources/test_tool_aliases.py
  • tests/unit/storage/test_lineage_normalization.py
  • tests/unit/storage/test_message_query_reads.py

Comment thread .beads/issues.jsonl
@@ -20,7 +20,7 @@
{"_type":"issue","id":"polylogue-ah21","title":"BrowserCaptureTurn has no blocks channel: structure is destroyed at acquisition, irreversibly","description":"ROOT CAUSE of browser-capture flattening, and it is in the wire schema, not the adapters.\n\n class BrowserCaptureTurn(BaseModel): # polylogue/browser_capture/models.py\n provider_turn_id: str\n role: Role\n text: str | None = None # \u003c- the ONLY content channel\n timestamp: str | None = None\n ordinal: int = 0\n parent_turn_id: str | None = None\n attachments: list[BrowserCaptureAttachment]\n provider_meta: dict[str, object] # \u003c- untyped escape hatch\n\nThere is no blocks field. A turn's role may be 'tool', but the call's input,\noutput and outcome have nowhere to go except free text. Every provider adapter\nis forced through one content channel regardless of what it observed.\n\nTHE EXTENSION IS NOT THE PROBLEM -- it is more capable than the transport.\nbrowser-extension/src/content/chatgpt_bridge.js intercepts window.fetch and\nacquires a session access token, so it can obtain ChatGPT's authoritative API\npayload (the mapping tree with tool nodes and status). The adapters already\nrecognise tool roles (backfill/providers.js:58, content/chatgpt.js:368). The\nstructure is available and the schema cannot carry it.\n\nMEASURED CONSEQUENCE: captured ChatGPT sessions yield 22,992 tool_result blocks\nagainst 7,745 tool_use blocks -- 3x more results than calls -- because pairing\nis reconstructed from prose rather than observed.\n\nWHY THIS IS THE WORST PLACE IN THE PIPELINE TO LOSE STRUCTURE: a parse gap is\nre-runnable against retained bytes. A capture that never recorded the structure\ncannot be recovered at any later date, for any past session. Every day this\nstands, more conversations are permanently flattened.","acceptance_criteria":"1. BrowserCaptureTurn carries typed content blocks; text remains as a rendering, not as the only channel. 2. The ChatGPT adapter emits the API payload's structure via the native bridge rather than reconstructing from rendered prose. 3. tool_use and tool_result counts are consistent for captured sessions -- the current 3:1 ratio is the regression signal. 4. parent_turn_id survives into the archive, so the conversation DAG is not flattened to a list. 5. Report per-origin block-kind coverage for captures before and after.","status":"closed","priority":0,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-29T04:52:43Z","created_by":"Sinity","updated_at":"2026-07-29T17:16:54Z","closed_at":"2026-07-29T17:16:54Z","close_reason":"Implemented. BrowserCaptureTurn now carries a typed content-blocks channel (BrowserCaptureBlock, mirroring ParsedContentBlock minus web_constructs, which is a derived enrichment not observable at the wire boundary); text remains a rendering rather than the only channel. The ChatGPT extension adapter classifies mapping-node content_type/recipient into typed blocks with constructed tool_id pairing. Important correction to this bead's premise, established by measurement: the cited 22,992:7,745 tool_result:tool_use ratio does NOT originate in the capture transport -- only 20 of 455 real captured sessions use the compact/DOM-fallback path this fixed; 435 delegate natively to sources/parsers/chatgpt.py, where the ratio is worse (~4.6:1). That parser-side pairing defect is filed separately as polylogue-4fm3 and is being fixed there. AC1/AC2/AC4 satisfied, AC3 partially (see 4fm3), AC5 reported.","labels":["area:capture","lane:capture-reliability"],"comments":[{"id":"019faea2-35e0-7960-9a05-cef50b174ba0","issue_id":"polylogue-ah21","author":"Sinity","text":"Implemented on feature/browser-capture/typed-content-blocks (PR pending).\n\nScope actually implemented (AC1, AC2, AC4 satisfied; AC3 partially satisfied,\npartially misframed by new evidence -- see below):\n\nAC1 (typed blocks channel) -- SATISFIED. Added `BrowserCaptureBlock`\n(polylogue/browser_capture/models.py), mirroring ParsedContentBlock\n(type/text/tool_name/tool_id/tool_input/media_type/metadata/is_error/\nexit_code; no web_constructs -- that's a derived enrichment, not observable\nat the wire boundary). `BrowserCaptureTurn.blocks: list[BrowserCaptureBlock]`\nadded; `text` stays as a rendering, no longer the only channel;\nrequire_content now accepts blocks-only turns.\n\nAC2 (ChatGPT adapter emits API structure via the bridge, not DOM prose) --\nSATISFIED for the concrete gap that actually existed: the compact/backfill\nbridge path (browser-extension/src/backfill/page_transport.js's\ncompactChatGptConversation, used when a conversation exceeds the executeScript\nscripting-result size cap) explicitly cannot be trusted as a native mapping\npayload by the parser (_has_chatgpt_native_payload rejects\npolylogue_bridge_projection == \"chatgpt-native-compact-v1\"), so it fell\nthrough to the parser's generic per-turn loop with zero blocks. Fixed:\nChatGptBackfillAdapter.normalizeCapture (providers.js) and the live content\nscript's collectNativeTurns (chatgpt.js) now classify each mapping node's own\ncontent_type/recipient evidence into typed blocks (code-interpreter\ncall -\u003e tool_use, its output -\u003e tool_result, paired by constructed tool_id:\nthe call's own node id, and the result's parent node id). Was already true\nfor the FULL native-payload case (delegates entirely to\nsources/parsers/chatgpt.py) -- unaffected, no regression.\n\nAC3 (tool_use:tool_result 1:1) -- PARTIALLY SATISFIED, PARTIALLY MISFRAMED.\nVerified via read-only query against /realm/db/polylogue/index.db\n(file:...?mode=ro, no write): the bead's cited 22,992:7,745 ratio does NOT\noriginate in the browser-capture transport this bead scoped -- it originates\nin sources/parsers/chatgpt.py's own code/execution_output classification\n(content_type \"code\" -\u003e BlockType.CODE not TOOL_USE, \"execution_output\"\nunconditionally -\u003e TOOL_RESULT, neither sets tool_id). Evidence: restricting\nto sessions actually tagged capture:* (455 of 2635 chatgpt-export sessions),\n435 used capture:browser-native-payload (full delegation to chatgpt.py,\nuntouched by this PR) vs only 3 compact + 17 dom-fallback (the paths this PR\nactually reaches) -- and the ratio among captured sessions is *worse*\n(tool_use=3877, tool_result=17768, ~4.6:1), confirming chatgpt.py is the\ndominant contributor, not the browser-capture wire schema. chatgpt.py is\nexplicitly out of this PR's scope (owned by another lane). Filed\npolylogue-4fm3 with the full evidence and a proposed fix. This PR does fix the\n20 compact/dom-fallback sessions' structural gap and closes it for all future\ncaptures that take those paths (including any future non-ChatGPT adapter).\n\nAC4 (parent_turn_id survives) -- SATISFIED, was already true. Verified across\nall four capture paths (native full delegation, compact/generic loop, Claude\nfallback, live collectNativeTurns) that parent_turn_id -\u003e parent_message_id\nthreads through; added explicit test assertions.\n\nAC5 (per-origin block-kind coverage before/after) -- reported in the PR body\nwith the exact read-only query and counts above; \"after\" numbers for the live\narchive require a derived-tier reprocess this PR does not run (no consequential\nwrite to /realm/db/polylogue authorized here). New synthetic tests demonstrate\nthe fix end-to-end via the real receiver -\u003e parser -\u003e materialize -\u003e index.db\nroute (tests/unit/sources/test_browser_capture.py).\n\nNot touched, per explicit scope: polylogue/storage/sqlite/** (schema lane),\npolylogue/sources/parsers/chatgpt.py (parser lane, see polylogue-4fm3).\n","created_at":"2026-07-29T16:08:14Z"}],"dependency_count":0,"dependent_count":0,"comment_count":1}
{"_type":"issue","id":"polylogue-2qx.3","title":"Connect the schema inference that already exists: it found every unread field and nothing consumes it","description":"THE INFERENCE ENGINE ALREADY DID THE WORK. This is not a missing capability; it is an unconnected pipeline.\n\npolylogue/schemas/providers/claude-code/versions/v1/elements/session_record_stream.schema.json.gz\nis 140 KB uncompressed, generated from 2,171,910 samples, and contains:\n stop_reason PRESENT structuredPatch PRESENT parentToolUseID PRESENT\n agentId PRESENT slug PRESENT ttftMs PRESENT\n originalFile PRESENT oldString PRESENT toolUseResult PRESENT\nEvery field this backlog records as discarded is IN THE COMMITTED SCHEMA, and\nhas been since 2026-03-16.\n\nThe engine is good. Its extension keywords (codex package) carry far more than\nfield names:\n 110x x-polylogue-frequency 35x x-polylogue-values (observed value sets)\n 21x x-polylogue-range 10x x-polylogue-format (iso8601 detection)\n 10x x-polylogue-multiline 9x x-polylogue-array-lengths\n 6x x-polylogue-semantic-role 5x x-polylogue-evidence (depth/fanout/name_signal)\n 1x x-polylogue-mutually-exclusive\n\nTHREE JOINS ARE MISSING, and each is cheap and static:\n\n (1) SCHEMA -\u003e PARSER READS. Nothing asks 'the schema observed field X across\n 2.1M samples; does any parser read it?' A leaf-name diff between the\n committed schema and polylogue/sources/ produces the acquired-and-unread\n list directly. This replaces the blob-sampling enumeration an earlier\n draft of this bead proposed -- deterministic, versioned, and far cheaper.\n\n (2) SCHEMA -\u003e HARDCODED VOCABULARIES. sources/ carries 51 frozenset/dict\n constants. Filesystem ones are fine (_SUPPORTED_EXTENSIONS, _SKIP_DIRS).\n Provider-data ones duplicate what the schema observed:\n _SKIPPED_SIDECAR_RECORD_TYPES 12 record types hand-listed with no\n per-type rationale -- the schema knows which types exist; this is\n the OriginSpec artifact-kind declaration living in a parser\n _SUCCESS_OUTCOMES = {ok, success, succeeded, completed, outcome_ok}\n five GUESSED synonyms where x-polylogue-values holds the observed set\n _COMPACTION_END_REASONS, _REQUIRED_SESSION_COLUMNS, _GIT_BRANCH_PREFIXES\n Note _GIT_BRANCH_PREFIXES heuristics run against a git_branch column that\n is empty on 100% of claude-code sessions.\n\n (3) PER-FIELD FIRST-SEEN. The package stamps\n x-polylogue-element-first-seen == -last-seen == -generated-at\n all the same microsecond (2026-03-16T12:26:12.880141+00:00), and there are\n NO per-field first/last-seen keys. Yet every record carries a timestamp --\n the schema itself annotates it semantic-role=message_timestamp,\n format=iso8601. The inference walks those timestamps and stamps wall-clock\n instead. Per-field first-seen is min(timestamp of records containing the\n field) and is free at generation time.\n Without it the drift sentinel (polylogue-da1, #3362) can only say\n NEW_FIELD relative to a 134-day-old package -- it cannot distinguish a\n field that arrived yesterday from one present since March.\n\nTHE SENTINEL'S MISSING FOURTH CLASSIFICATION. schemas/drift_sentinel.py\nclassifies UNSEEN_SHAPE (no candidate schema), NEW_FIELD (schema lacks the\nfield), FIELD_CHANGED (validation failed). All three ask what the SCHEMA does\nnot know. There is no classification for 'schema knows it, parser ignores it',\nwhich is the actual defect -- and because those payloads validate cleanly, the\nsentinel marks them benign.\n\nGENERATE RAN; PROMOTE DID NOT. All nine providers have exactly one version\ndirectory (v1). Recent work is real -- #2934 (2026-07-17) derived archive\nworkload profiles from provider schemas and added\nproviders/claude-code/pins.json rejecting two mis-inferred semantic roles\n($.gitBranch as session_title, $.toolUseResult.oldTodos as message_container),\nwhich is direct evidence the engine was run on claude-code that week and SAW\ntoolUseResult.oldTodos. But no regenerated package was promoted, so the\ncommitted artifact is still March-old while the machinery is current.\nbrowser-capture v1 was rewritten 2026-07-27 with sample_count=1 -- a token\nregeneration, not a corpus run.\n\nDO NOT rebuild a sampler. Promote the schema, then run the three joins.","acceptance_criteria":"1. lab schema promote runs for every provider so committed packages reflect current data; report each package's sample_count and age before and after. 2. A static schema-vs-parser diff is committed and runnable, and its output is triaged per key into read / deliberately-dropped-with-recorded-reason / to-acquire in the owning OriginSpec. 3. Provider-data vocabularies hardcoded in sources/ are replaced by, or checked against, x-polylogue-values; _SKIPPED_SIDECAR_RECORD_TYPES becomes an OriginSpec declaration with a per-type reason. 4. Per-field first-seen/last-seen are emitted at generation from record timestamps the pass already reads. 5. The drift sentinel gains the fourth classification (schema-known, parser-unread) and it runs in a gate. 6. No blob-sampling enumeration is built; the schema is the source.","notes":"2026-07-29 (worktree-agent-acd6757a7a8b152f2, parser-diff triage for claude-ai/claude-code): partial AC#2 slice, not closure. Rebased onto origin/master and cherry-picked the already-landed lab schema parser-diff tool (ab4a9a304, on feature/chore/promote-schemas-and-wire-gates) plus the prior sidecar-persistence commits (514900789/05099666c) as a starting base. Found the tool currently returns 0 rows against every COMMITTED provider schema (claude-ai/claude-code/codex/chatgpt/gemini*/hermes*/antigravity all checked) because x-polylogue-observed-distribution is absent from every committed .gz package -- it only works against a freshly regenerated, uncommitted schema. Used it in-memory at min-encountered=0 for the referenced-name list instead, then verified real corpus frequency directly (~/.claude/projects + /realm/db/polylogue source.db blob store) since the promote step (AC#1) hasn't run.\\n\\nTriaged and landed for claude-code (commits e4d0715d5, cebb70e00): fixed a real bug (compactMetadata/preservedSegment/anchorUuid read via wrong snake_case keys, silently nulling trigger/pre_tokens on every compaction since ~ac9cfeb0b); added microcompact_boundary detection (previously fell through to a placeholder message, losing trigger/preTokens/tokensSaved/compactedToolIds entirely); added custom-title and file-history-delta as two MORE sidecar record types beyond the original twelve in _SKIPPED_SIDECAR_RECORD_TYPES (custom-title also now wins session-title precedence over ai-title); added toolUseResult structural-fact projection (sandbox/interrupted/file extents/structuredPatch counts/todo priority state) via two new session_event types; extended message_usage with ttft_ms/stop_reason/cache_creation TTL split/service_tier/inference_geo/cache_miss_reason; added claude_session_kind event and direct gitBranch capture (previously ONLY populated via a separate, often-absent legacy sessions-index.json sidecar).\\n\\nTriaged and landed for claude-ai (commit e793e6d55): tool_use/tool_result segment fields (start_timestamp/stop_timestamp, integration_name/integration_icon_url, approval_key/approval_options, display_content, is_mcp_app, mcp_server_url) now flow into ParsedContentBlock.metadata; top-level conversation summary now persists as claude_ai_conversation_summary.\\n\\nNOT done (still open against this bead's real AC): no schema promote ran (AC#1); _SKIPPED_SIDECAR_RECORD_TYPES/_SIDECAR_EVENT_TYPES are still hand-maintained dict/frozenset constants, not OriginSpec-declared (AC#3); no per-field first/last-seen (AC#4); no drift-sentinel fourth classification (AC#5). Also left explicitly to-acquire (documented as code comments, not silently dropped): claude-ai's nested Drive/doc-citation content[].content[] cluster needs its own ParsedWebConstruct-shaped design distinct from the existing citations[] projection.\n2026-07-29 (worktree-agent-a6d396610f6c9a165): confirmed AC#2 (static schema-vs-parser diff, committed+runnable) and AC#5 (drift sentinel's fourth classification, KNOWN_FIELD_UNREAD) were BOTH already fully done and wired into the live path before this session -- polylogue/schemas/schema_parser_coverage.py + drift_sentinel.py + pipeline/services/ingest_worker.py:475-500 (out of my scope to touch, verified read-only). This session's contribution: ran the parser-diff/coverage join against gemini/gemini-cli/antigravity/browser-capture/codex (the providers with no prior triage pass) and fixed two accuracy bugs in the join itself -- PROVIDER_PARSERS was missing drive_support_attachments.py (gemini) and browser_capture/models.py (browser-capture), producing false-positive \"unread\" rows for both; fixed in both copies of the map (devtools/schema_parser_diff.py + schemas/schema_parser_coverage.py, commit 0d7a19c47). Also closed one real gap the join surfaced for codex: patch_apply_end.changes/.success, plus turn_context.personality/.summary/.collaboration_mode -- see polylogue-cgfy note for full disposition table.\n\nStill NOT done (unchanged from the prior lane's note): AC#1 (schema promote hasn't run for codex/browser-capture -- explicitly out of this session's scope, polylogue/schemas/providers/** was reserved for a concurrent regeneration lane); AC#3 (_SKIPPED_SIDECAR_RECORD_TYPES/_SUCCESS_OUTCOMES/_COMPACTION_END_REASONS/_REQUIRED_SESSION_COLUMNS/_GIT_BRANCH_PREFIXES are still hand-maintained frozenset/dict constants, not OriginSpec-declared); AC#4 (no per-field first/last-seen, that lives in schemas/generation/ which is also reserved for the regeneration lane).\nVerification (group2 sweep, 2026-07-30): PARTIAL. Own notes (2026-07-29) enumerate status per AC: AC2 (schema-vs-parser diff) done; AC5 (drift sentinel KNOWN_FIELD_UNREAD) done. Still open: AC1 (schema promote), AC3 (OriginSpec-declared vocabularies), AC4 (per-field first/last-seen). Not safe to close.","status":"open","priority":0,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-29T04:52:42Z","created_by":"Sinity","updated_at":"2026-07-31T05:48:29Z","labels":["area:ingest","area:sources","delivery:K-interop-origin-export","delivery:ac-patched","horizon:frontier","lane:origin-interop-export","refactor"],"dependencies":[{"issue_id":"polylogue-2qx.3","depends_on_id":"polylogue-2qx","type":"parent-child","created_at":"2026-07-29T06:52:41Z","created_by":"Sinity","metadata":"{}"}],"comments":[{"id":"019fac95-35fb-7dd7-a040-a15160be6a1e","issue_id":"polylogue-2qx.3","author":"Sinity","text":"Hermes triage complete (polylogue-2qx.3 instance, this task's scope: hermes_state.py,\nhermes_spans.py, hermes_lifecycle.py, hermes_verification.py, hermes_identity.py).\n\ndevtools lab schema parser-diff --provider hermes --min-encountered 1 --json (run from\na temp copy of the schema_parser_diff.py branch, feature/chore/promote-schemas-and-wire-gates,\nsince that command isn't on master yet) found 301 unread keys over 167+2 sampled documents.\n\nSplit into two document shapes:\n - 21 keys belong to the mainstream 167-document JSON snapshot shape, parsed by\n polylogue/sources/parsers/local_agent.py::parse_hermes (shared with gemini-cli,\n outside this task's write scope) -- filed as polylogue-5o05.\n - 280 keys belong to the real NeMo Relay ATIF trajectory format (2 sampled documents),\n parsed by hermes_spans.py -- fixed directly on branch\n worktree-agent-aa47c5139f1933ae3, commits aa9fc858c/0e46f702a/b9f14bbd2:\n * step-level extra telemetry: ancestry/tool_ancestry (delegation chain),\n invocation/tool_invocations (framework+timing), llm_response.usage /\n sibling metrics (per-step token accounting), tool-call provider_data ids,\n observation.results[] correlation ids/metadata\n * new hermes_tool_availability_span event: the tool-definition schema (name/\n description/parameters) OFFERED to the model at each llm-request step --\n materially distinct from hermes_tool_execution_span (a tool actually called),\n and previously unrepresented anywhere in the archive\n * document-level: trajectory_id, agent.extra.plugin, final_metrics.* totals\n Deliberately still dropped, with reasons documented inline in hermes_spans.py's\n module docstring: event_payload.conversation_history (a second copy of the\n session's own messages -- payload-hygiene rule), per-tool-call arguments and\n observation.results[].content (conversation-adjacent content, bounded-evidence-only\n per the module's pre-existing policy), llm_request instructions/input (bounded to\n presence, not value), and llm_request internal API plumbing (extra_headers/store/\n prompt_cache_key/include -- no evidentiary value). tools[]._truncated_items is not\n a real Hermes field at all -- a schema-generation-tool artifact (grepped, zero\n references anywhere in polylogue/ source).\n\nNo index-tier storage needed -- all new evidence rides existing session_events\n(event_type has no CHECK vocabulary) and existing event payloads. No index/schema\nversion bump.\n\nVerification: devtools test tests/unit/sources/parsers/test_hermes_spans.py\ntests/unit/insights/test_hermes_topology_projection.py -\u003e 36 + 13 passed; mypy\n--strict clean; ruff clean.\n","created_at":"2026-07-29T06:34:48Z"}],"dependency_count":0,"dependent_count":0,"comment_count":1}
{"_type":"issue","id":"polylogue-cgfy","title":"34 of the 70 most common wire keys are never read, including 105,123 structured diffs","description":"SYSTEMATIC ENUMERATION 2026-07-29. Method: parse 60 real Claude Code transcripts, count every top-level / message / usage / toolUseResult key, then grep polylogue/sources/ for each name. This is the complete answer to 'what else arrives typed and is discarded', replacing the ad-hoc list.\n\n34 of the 70 most frequent keys have ZERO references in polylogue/sources/.\n\nTHE FILE-EDIT CORPUS -- entirely unread, corpus-wide counts:\n structuredPatch 105,123 real unified diffs:\n {\"oldStart\":143,\"oldLines\":6,\"newStart\":143,\n \"newLines\":14,\"lines\":[...]}\n originalFile 92,313 the pre-edit file content\n oldString 86,085 with newString and replaceAll alongside\n filePath which file each edit touched\n userModified whether the human changed it afterwards\n\npolylogue-cijx grades file trajectories 'observed' -- 'only tool/action-derived\ndeltas' -- and states that 'checkpointed' requires captured pre/post state.\nThe pre-state IS captured, in originalFile, and the deltas ARE structured, in\nstructuredPatch. The tier cijx declares out of reach is sitting in the bytes.\n\nOTHER UNREAD KEYS OF SUBSTANCE (occurrences in the 60-file sample):\n slug 1,500 human-readable agent name (the subagent display\n problem: '5ecdb160-...:agent-af4e' vs 'greedy-\n squishing-hamming')\n message.stop_reason 1,184 terminal state (see the outcome bead)\n message.stop_sequence 1,184\n parentToolUseID 657 the delegation join key (see the delegation bead)\n toolUseID 679\n sourceToolAssistantUUID 143\n usage.cache_creation 664 cache-creation token detail\n message.ttftMs 36 time to first token\n todos / oldTodos / newTodos agent task-list evolution over a session\n thinkingMetadata 34\n permissionMode 33\n hookCount / hookInfos 22\n toolUseResult.sandbox 60\n toolUseResult.filenames / numFiles 46\n requestId 1,171\n userType 2,789\n\nMEASURED NEGATIVE, recorded so nobody re-files it: usage.service_tier looked\nlike the answer to the API-vs-subscription cost question. It is NOT --\n1,651,137 occurrences, every one 'standard'. A constant. Acquiring it would add\nnothing. Check payloads before filing.","acceptance_criteria":"1. Every key in this enumeration is classified read / deliberately-dropped-with-reason / to-acquire, recorded in the Claude Code OriginSpec fidelity declaration rather than an unexplained frozenset. 2. structuredPatch, originalFile and oldString/newString are persisted; cijx's file-trajectory grading rises from observed to checkpointed where they exist, proven on a sample. 3. slug reaches read surfaces so subagent rows carry names. 4. The enumeration is re-runnable and its output committed, so a future wire change surfaces new unread keys instead of hiding them. 5. Report bytes and row counts added per key acquired.","notes":"2026-07-29 (worktree-agent-a6d396610f6c9a165, un-triaged-provider pass: gemini/gemini-cli/antigravity/browser-capture/codex): branch fast-forwarded to b3ae790be (feature/chore/promote-schemas-and-wire-gates), which already carried a huge amount of prior work: claude-code/claude-ai/gemini/gemini-cli/hermes/antigravity all promoted to schema v2, block-metadata routed to session_events for chatgpt/gemini-cli/hermes/browser-capture/codex, and the drift-sentinel 4th classification (KNOWN_FIELD_UNREAD, polylogue/schemas/schema_parser_coverage.py) fully implemented AND wired into the live ingest path (pipeline/services/ingest_worker.py:475-500) -- polylogue-2qx.3's core ask was already done before this session.\n\nRan devtools lab schema parser-diff --min-encountered 1 against the committed (already-promoted) v2 packages for gemini/gemini-cli/antigravity/browser-capture; codex has no v2 (still stale March v1, no x-polylogue-observed-distribution) so its 0-row output is a tool blind spot, not evidence of full coverage -- verified codex frequency directly against ~3,200 real ~/.codex session files instead.\n\nFindings/dispositions:\n- gemini: all \"unread\" rows (runSettings.enable*/environmentMode/responseSchema) are FALSE POSITIVES -- drive.py:_model_config_event stores the whole runSettings dict verbatim (origin_specs.py:625). _polylogue_drive_live_bytes_b64 was a second false positive: read by drive_support_attachments.py, missing from PROVIDER_PARSERS in both devtools/schema_parser_diff.py and schemas/schema_parser_coverage.py -- fixed both maps.\n- gemini-cli: memoryScratchpad.* is a FALSE POSITIVE -- local_agent.py:_gemini_cli_memory_scratchpad_event already stores it verbatim. toolCalls.args.*/resultDisplay.* also verbatim-captured.\n- antigravity/browser-capture: browser-capture's 8 rows were the same PROVIDER_PARSERS gap (browser_capture/models.py missing) -- fixed. antigravity's single row (version, 0 encountered documents) has zero corpus signal either way.\n- codex (real gap, FIXED, commit 0d7a19c47): patch_apply_end.success/.changes (per-file add/update/delete + unified_diff + move_path) was completely unread -- the direct codex analogue of this bead's own structuredPatch finding. Now retained verbatim. turn_context.personality/.summary/.collaboration_mode also newly captured.\n- codex measured-negative: event_msg.memory_citation is null on every sampled record across the full corpus -- a constant.\n- codex to-acquire, deferred: internal_chat_message_metadata_passthrough carries only {turn_id}; needs a ParsedMessage metadata channel plumbed through every codex.py message constructor, left as a named follow-up.\n\nAll codex dispositions recorded in origin_specs.py's codex fidelity_notes.\n[Verification sweep 2026-07-31, bead-landing-check group5] Verdict: PARTIAL. Field capture landed 2026-07-29 (v46 file_edits schema: structured_patch_json/original_file/old_string/new_string persisted per storage/sqlite/queries/file_edits.py; slug captured in claude/code_parser.py:1050; codex patch_apply diffs fixed commit 0d7a19c47) satisfying much of AC2/AC3. But AC2's specific \"cijx grading rises from observed to checkpointed\" wiring not found (grepped polylogue/insights - no such evidence-tier concept referencing file_edits), and full AC1 classification-recorded-in-fidelity-declaration / AC4 re-runnable committed enumeration not independently verified complete.","status":"open","priority":0,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-29T04:52:32Z","created_by":"Sinity","updated_at":"2026-07-31T05:52:10Z","labels":["area:ingest","lane:origin-interop-export"],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"polylogue-1vpm.7","title":"Delegation resolution guesses by count-equality while the provider supplies the exact join key","description":"MECHANISM. delegation_facts_source pairs Task dispatches to child sessions with no join key at all:\n\n pairable AS (\n SELECT dc.parent_session_id FROM dispatch_counts dc\n JOIN child_counts cc ON cc.parent_session_id = dc.parent_session_id\n WHERE dc.n = cc.n) \u003c- count equality is the entire gate\n\nIt counts Task dispatches in the parent (ordered by message_id), counts resolved\nchildren (ordered by observed_at_ms), and if the counts match, pairs them BY\nORDINAL POSITION -- two unrelated orderings assumed to correspond.\n\nRESULT, full scan of 11,692 delegation_facts rows:\n edge_only 5,951 50.9%\n unresolved 2,207 18.9%\n ambiguous 2,041 17.5%\n resolved 1,493 12.8% \u003c- the only complete delegations\n\nWHY IT FAILS ALL-OR-NOTHING: the gate is per parent. One dispatch whose child\nwas not captured makes dc.n != cc.n and EVERY dispatch in that session becomes\nambiguous. One local gap poisons a whole session, which is why the distribution\nis lumpy rather than a smooth partial.\n\nWHY session_links SUCCEEDS AT 97.6% ON THE SAME DATA: links are derived from the\nCHILD side, where the child literally states its parent sessionId. Delegation is\nderived from the PARENT side, where nothing stated which child a dispatch\nproduced -- so a heuristic was invented instead.\n\nTHE KEY EXISTS, TYPED, AND IS DISCARDED. Claude Code progress records carry:\n parentToolUseID -\u003e the dispatching Task tool_use id\n toolUseID, slug, sessionId\nCorpus-wide: 842,819 progress records carry parentToolUseID, referencing 185,982\ndistinct dispatch ids. progress is in _SKIPPED_SIDECAR_RECORD_TYPES.\n\nSecondary keys also present and unused: the child transcript's first record\ncarries agentId, slug, and its first message IS the Task prompt (verified: 1\nmatch against 102 tool_use blocks in the parent -- unique on that sample, NOT\nyet corpus-verified). sourceToolAssistantUUID appears in child records with\nZERO references anywhere in polylogue/sources/.\n\nTHE INVARIANT: join on identity, never on cardinality. Then 'ambiguous' becomes\nunrepresentable -- you either have the key or you don't -- and missing capture\ndegrades per dispatch instead of per session. Heuristics smear uncertainty;\njoins localize absence. An unavoidable gap is one thing; a gap that PROPAGATES\nis the actual defect.","acceptance_criteria":"1. Dispatch-to-child resolution joins on parentToolUseID; no code path pairs by ordinal position or gates on count equality. 2. The 'ambiguous' mapping state is removed from the vocabulary, not merely reduced -- with the key it is not a reachable state. 3. A parent with N dispatches and M\u003cN captured children yields M resolved and N-M unresolved, proven by a fixture; it never yields N ambiguous. 4. Live re-measure of the mapping_state distribution against the 12.8%-resolved baseline. 5. Corpus-wide collision check on any secondary key before it is relied on.","notes":"Filed 2026-07-29. Note the shape: the epistemic vocabulary here (edge_only/unresolved/ambiguous/quarantined, mapped honestly onto WorkEvidenceAssociationState, with an explicit refusal to 'fabricate a one-to-one attempt') is well designed and correctly implemented. It faithfully reports the uncertainty of a heuristic that did not need to exist. Sophisticated epistemology over an avoidable uncertainty is itself the smell -- the distinctions are real but 87% of what they distinguish is self-inflicted.","status":"open","priority":0,"issue_type":"task","owner":"[email protected]","created_at":"2026-07-29T04:52:22Z","created_by":"Sinity","updated_at":"2026-07-29T04:52:22Z","labels":["area:ingest","area:substrate","delivery:I-analytics-experiments","horizon:mid","lane:analytics-experiments","lane:read-contracts","tech-tree"],"dependencies":[{"issue_id":"polylogue-1vpm.7","depends_on_id":"polylogue-1vpm","type":"parent-child","created_at":"2026-07-29T06:52:21Z","created_by":"Sinity","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0}
{"_type":"issue","id":"polylogue-1vpm.7","title":"Delegation resolution guesses by count-equality while the provider supplies the exact join key","description":"MECHANISM. delegation_facts_source pairs Task dispatches to child sessions with no join key at all:\n\n pairable AS (\n SELECT dc.parent_session_id FROM dispatch_counts dc\n JOIN child_counts cc ON cc.parent_session_id = dc.parent_session_id\n WHERE dc.n = cc.n) \u003c- count equality is the entire gate\n\nIt counts Task dispatches in the parent (ordered by message_id), counts resolved\nchildren (ordered by observed_at_ms), and if the counts match, pairs them BY\nORDINAL POSITION -- two unrelated orderings assumed to correspond.\n\nRESULT, full scan of 11,692 delegation_facts rows:\n edge_only 5,951 50.9%\n unresolved 2,207 18.9%\n ambiguous 2,041 17.5%\n resolved 1,493 12.8% \u003c- the only complete delegations\n\nWHY IT FAILS ALL-OR-NOTHING: the gate is per parent. One dispatch whose child\nwas not captured makes dc.n != cc.n and EVERY dispatch in that session becomes\nambiguous. One local gap poisons a whole session, which is why the distribution\nis lumpy rather than a smooth partial.\n\nWHY session_links SUCCEEDS AT 97.6% ON THE SAME DATA: links are derived from the\nCHILD side, where the child literally states its parent sessionId. Delegation is\nderived from the PARENT side, where nothing stated which child a dispatch\nproduced -- so a heuristic was invented instead.\n\nTHE KEY EXISTS, TYPED, AND IS DISCARDED. Claude Code progress records carry:\n parentToolUseID -\u003e the dispatching Task tool_use id\n toolUseID, slug, sessionId\nCorpus-wide: 842,819 progress records carry parentToolUseID, referencing 185,982\ndistinct dispatch ids. progress is in _SKIPPED_SIDECAR_RECORD_TYPES.\n\nSecondary keys also present and unused: the child transcript's first record\ncarries agentId, slug, and its first message IS the Task prompt (verified: 1\nmatch against 102 tool_use blocks in the parent -- unique on that sample, NOT\nyet corpus-verified). sourceToolAssistantUUID appears in child records with\nZERO references anywhere in polylogue/sources/.\n\nTHE INVARIANT: join on identity, never on cardinality. Then 'ambiguous' becomes\nunrepresentable -- you either have the key or you don't -- and missing capture\ndegrades per dispatch instead of per session. Heuristics smear uncertainty;\njoins localize absence. An unavoidable gap is one thing; a gap that PROPAGATES\nis the actual defect.","acceptance_criteria":"1. Dispatch-to-child resolution joins on parentToolUseID; no code path pairs by ordinal position or gates on count equality. 2. The 'ambiguous' mapping state is removed from the vocabulary, not merely reduced -- with the key it is not a reachable state. 3. A parent with N dispatches and M\u003cN captured children yields M resolved and N-M unresolved, proven by a fixture; it never yields N ambiguous. 4. Live re-measure of the mapping_state distribution against the 12.8%-resolved baseline. 5. Corpus-wide collision check on any secondary key before it is relied on.","notes":"Filed 2026-07-29. Note the shape: the epistemic vocabulary here (edge_only/unresolved/ambiguous/quarantined, mapped honestly onto WorkEvidenceAssociationState, with an explicit refusal to 'fabricate a one-to-one attempt') is well designed and correctly implemented. It faithfully reports the uncertainty of a heuristic that did not need to exist. Sophisticated epistemology over an avoidable uncertainty is itself the smell -- the distinctions are real but 87% of what they distinguish is self-inflicted.","status":"closed","priority":0,"issue_type":"task","assignee":"Sinity","owner":"[email protected]","created_at":"2026-07-29T04:52:22Z","created_by":"Sinity","updated_at":"2026-07-31T10:54:44Z","started_at":"2026-07-31T10:54:42Z","closed_at":"2026-07-31T10:54:44Z","close_reason":"VERIFICATION FIRST (per method note: verify claims against current master\nbefore starting). The identity-join fix this bead describes was ALREADY\nLANDED on master before this session started: storage/sqlite/archive_tiers/\nindex.py's delegation_facts_source view joins dispatches to children by\nprovider-asserted content identity (the child's own first turn IS the\ndispatching Task/Agent tool_use's own prompt field), not rank-pairing by\ncardinality. The view's own comment cites this bead by id and documents\nthe corpus verification (of 3,534 dispatches with \u003e=1 same-parent\ncandidate, 1,933 match exactly one child's text and vice versa; 14/22\nambiguous collisions correctly excluded rather than guessed).\ntests/unit/storage/test_delegations_view.py::test_delegation_dispatch_without_matching_content_stays_unresolved\nalready pins this. AC1/AC2/AC3/AC5 are satisfied by that already-landed\ncode (git history shows this as commit a386f5462, squash-merged into\n5e23e6abf's v46 batch; the same source text is present verbatim in the\ncurrent index.py DDL). AC4 (live re-measure of mapping_state distribution)\nwas not re-run by me since the view code, not the corpus, is what needed\nre-verifying, and the two-target-session investigation below is the more\ndirect proof.\n\nWHAT I ACTUALLY FIXED (fix/archive/companion commit da0f76746, same\nbranch): grepping the live archive for the two target sessions\n(read-only) found the join-key fix had ZERO effect on\nclaude-code-session:38baa1de-... (~20 subagents) -- every one of its 21\nresolved session_links children surfaced as mapping_state='edge_only'\n(a resolved child with no parent-side dispatch action ever attached),\n0 rows resolved or unresolved. Root cause: this session dispatches\nsubagents via the \"Agent\" tool (the Claude Agent SDK's dispatch tool,\nnot Claude Code's \"Task\"), and classify_tool (archive/viewport/tools.py)\nput \"Agent\" in the generic ToolCategory.AGENT bucket (alongside\naskuserquestion/skill/batch/todo*) rather than ToolCategory.SUBAGENT --\nso delegation_facts_source's `WHERE a.semantic_type = 'subagent'` found\nno dispatch actions for this session at all. The join-key fix had\nnothing to join. Fixed classify_tool to route \"agent\" to SUBAGENT (same\ndispatch shape as Task: tool_input carries a \"prompt\" field the child's\nfirst turn reproduces verbatim -- verified against the real record).\n\nOPERATIONAL CAVEAT, stated explicitly: blocks.semantic_type is computed\nat parse/write time and stored (write.py:_semantic_type -\u003e classify_tool),\nnot derived at read time -- a SEMANTIC_REPARSE-class change per the\nschema regime rules. This PR does NOT trigger `polylogue ops reset\n--index \u0026\u0026 polylogued run` against the live archive (forbidden for this\nsession; read-only). The fix takes effect for newly-ingested/reprocessed\nsessions immediately; the live archive's existing \"Agent\"-tool sessions\n(including both target sessions) need an operator-run reindex before\ntheir delegation_facts rows actually resolve.\n\nDEPTH/UX SCOPE CLARIFICATION (operator, mid-session): delegation is a\ntree, not one level -- filed as polylogue-qsb4 (arbitrary-depth\nancestry/subtree query surface, cycle/orphan handling reusing\nsession_links' TopologyEdgeStatus precedent, work_evidence_nodes/edges\njoin-vs-parallel design question, production surface requirement). Not\nfolded into this bead: 1vpm.7's own AC are about the join MECHANISM\n(count-equality vs identity), which is fully satisfied; tree-depth query\nsurface is a distinct, larger capability this bead never claimed.\n\nVerification: devtools test tests/unit/sources/test_tool_aliases.py\ntests/unit/storage/test_delegations_view.py\ntests/unit/storage/test_store_ops.py (86 passed). mypy --strict on\ntouched files. devtools verify --quick: exit 0.\n\nFollow-up: polylogue-qsb4 (arbitrary-depth delegation tree/UX).","labels":["area:ingest","area:substrate","delivery:I-analytics-experiments","horizon:mid","lane:analytics-experiments","lane:read-contracts","tech-tree"],"dependencies":[{"issue_id":"polylogue-1vpm.7","depends_on_id":"polylogue-1vpm","type":"parent-child","created_at":"2026-07-29T06:52:21Z","created_by":"Sinity","metadata":"{}"}],"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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Do not close polylogue-1vpm.7 with AC4 incomplete.

Line 23 sets the issue to closed, but the close_reason states that the live mapping_state re-measurement was not run. Keep the issue open until the operator reindexes the existing archive and records that distribution, or create a linked operational follow-up and remove AC4 from this closure claim.

🤖 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 23, Reopen polylogue-1vpm.7 or remove its closed
status until AC4 is satisfied. The close_reason must not claim completion while
the live mapping_state distribution remains unmeasured; have the operator
reindex the existing archive and record the distribution, or create and link an
explicit operational follow-up and revise the closure text to identify AC4 as
outstanding.

Comment thread polylogue/api/archive.py
# it here, clearly separated from `commits` (which is
# detect_session_commits' scored/heuristic list) rather than merged
# into it.
checkout_commits = await self.repository.get_session_commits(session_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.

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

Use the resolved session ID for checkout-commit lookup.

Line 5793 uses the caller token after get_session() has already resolved the session. session_commits queries by exact session_id, so a valid abbreviated session ID returns an empty checkout_commits list. Use str(session.id) for this lookup.

Proposed fix
-        checkout_commits = await self.repository.get_session_commits(session_id)
+        checkout_commits = await self.repository.get_session_commits(str(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
checkout_commits = await self.repository.get_session_commits(session_id)
checkout_commits = await self.repository.get_session_commits(str(session.id))
🤖 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/api/archive.py` at line 5793, Update the checkout-commit lookup in
the surrounding session retrieval flow to pass str(session.id) to
repository.get_session_commits instead of the caller-provided session_id,
ensuring resolved abbreviated session IDs query the correct session.

Comment on lines 85 to 111
if output_format == "json":
from polylogue.insights.session_commit import correlation_result_to_payload

env.ui.console.print(json.dumps(correlation_result_to_payload(result), indent=2))
payload = correlation_result_to_payload(result)
# polylogue-cijx.3 AC3: session_commits (the parser-reported repo
# checkout HEAD at session capture) was a write-only table with no
# reader anywhere. Surface it as a distinct field, clearly separate
# from `commits` (detect_session_commits' scored/heuristic list
# above), matching the same field added to the HTTP correlation
# surface (api/archive.py::session_correlation_payload).
checkout_commits = run_coroutine_sync(env.polylogue.repository.get_session_commits(session_id))
payload["checkout_commits"] = [
{
"commit_sha": record.commit_sha,
"short_sha": record.commit_sha[:8],
"repo_id": record.repo_id,
"detection_type": record.detection_type,
"method": record.method,
"confidence": record.confidence,
"evidence": record.evidence,
}
for record in checkout_commits
]
env.ui.console.print(json.dumps(payload, indent=2))
return

_print_correlation_result(env, result)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Expose checkout_commits in non-JSON CLI output.

Lines 88-108 retrieve and serialize checkout commits only for JSON output. The non-JSON path calls _print_correlation_result(env, result) without the records. Users of that CLI output cannot see the new checkout-commit data.

Load the records before format selection. Extend the non-JSON renderer and add coverage for that output path.

🧰 Tools
🪛 ast-grep (0.45.0)

[info] 107-107: use jsonify instead of json.dumps for JSON output
Context: json.dumps(payload, indent=2)
Note: [CWE-116] Improper Encoding or Escaping of Output.

(use-jsonify)

🤖 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/insights/correlation_view.py` around lines 85 - 111, Move the
session-commit retrieval from the JSON-only branch to before output-format
selection, reusing the resulting records for both formats. Extend
`_print_correlation_result` to accept and render `checkout_commits` distinctly
from `commits`, and add coverage for the non-JSON CLI output path.

Comment on lines +370 to +377
@field_validator("evidence", mode="before")
@classmethod
def _parse_evidence(cls, v: object) -> object:
if isinstance(v, str):
import json

return json.loads(v) if v else {}
return v

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use the project JSON parser for evidence.

json.loads accepts non-finite tokens such as NaN. polylogue.core.json.loads rejects these tokens. A stored NaN value can later make the CLI emit non-standard JSON through json.dumps.

Parse with polylogue.core.json.loads and require a JSON object before returning the value.

🤖 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/runtime/archive/records.py` around lines 370 - 377, Update
the _parse_evidence validator to use polylogue.core.json.loads instead of the
standard json.loads, preserving the empty-string fallback to {}. Validate that
the parsed result is a JSON object before returning it, rejecting non-object
evidence values.

Comment on lines 390 to +407
session_id = await _resolve_session_id(conn, session_id)

# A prefix-sharing child stores only its divergent tail, so paginating its
# own ``messages`` rows returns a truncated transcript. Compose the full
# lineage view, filter in Python, and slice it for offset/limit (#2470).
# ``total`` is the filtered composed length so page math stays consistent.
# Uses ``get_messages_with_lineage_completeness`` directly (not the
# signal-dropping ``get_messages`` wrapper) so pagination -- the actual
# `polylogue read` / HTTP messages surface -- can report truncation
# instead of silently rendering a short transcript as if it were whole.
if await _prefix_sharing_edge(conn, session_id) is not None:
composed_full, completeness = await get_messages_with_lineage_completeness(conn, session_id)
composed = _filter_composed(
await get_messages(conn, session_id),
composed_full,
message_role=message_role,
message_type=message_type,
)
return composed[offset : offset + limit], len(composed)
return composed[offset : offset + limit], len(composed), completeness

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

Use one read transaction for lineage detection and page retrieval.

Line 400 checks for a prefix-sharing edge before get_messages_with_lineage_completeness() starts its deferred transaction. If a writer commits a prefix-sharing link after this check, this function takes the normal SQL path and returns the child tail with complete=True.

Wrap resolution, edge detection, composition, counting, and page retrieval in one deferred read transaction. The nested composition call will reuse that transaction.

Proposed fix
 async def get_messages_paginated(
     conn: aiosqlite.Connection,
     session_id: str,
@@
 ) -> tuple[list[MessageRecord], int, LineageCompleteness]:
+    if not conn.in_transaction:
+        await conn.execute("BEGIN DEFERRED")
+        try:
+            return await get_messages_paginated(
+                conn,
+                session_id,
+                message_role=message_role,
+                message_type=message_type,
+                limit=limit,
+                offset=offset,
+            )
+        finally:
+            await conn.execute("ROLLBACK")
+
     session_id = await _resolve_session_id(conn, 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
session_id = await _resolve_session_id(conn, session_id)
# A prefix-sharing child stores only its divergent tail, so paginating its
# own ``messages`` rows returns a truncated transcript. Compose the full
# lineage view, filter in Python, and slice it for offset/limit (#2470).
# ``total`` is the filtered composed length so page math stays consistent.
# Uses ``get_messages_with_lineage_completeness`` directly (not the
# signal-dropping ``get_messages`` wrapper) so pagination -- the actual
# `polylogue read` / HTTP messages surface -- can report truncation
# instead of silently rendering a short transcript as if it were whole.
if await _prefix_sharing_edge(conn, session_id) is not None:
composed_full, completeness = await get_messages_with_lineage_completeness(conn, session_id)
composed = _filter_composed(
await get_messages(conn, session_id),
composed_full,
message_role=message_role,
message_type=message_type,
)
return composed[offset : offset + limit], len(composed)
return composed[offset : offset + limit], len(composed), completeness
if not conn.in_transaction:
await conn.execute("BEGIN DEFERRED")
try:
return await get_messages_paginated(
conn,
session_id,
message_role=message_role,
message_type=message_type,
limit=limit,
offset=offset,
)
finally:
await conn.execute("ROLLBACK")
session_id = await _resolve_session_id(conn, session_id)
# A prefix-sharing child stores only its divergent tail, so paginating its
# own ``messages`` rows returns a truncated transcript. Compose the full
# lineage view, filter in Python, and slice it for offset/limit (`#2470`).
# ``total`` is the filtered composed length so page math stays consistent.
# Uses ``get_messages_with_lineage_completeness`` directly (not the
# signal-dropping ``get_messages`` wrapper) so pagination -- the actual
# `polylogue read` / HTTP messages surface -- can report truncation
# instead of silently rendering a short transcript as if it were whole.
if await _prefix_sharing_edge(conn, session_id) is not None:
composed_full, completeness = await get_messages_with_lineage_completeness(conn, session_id)
composed = _filter_composed(
composed_full,
message_role=message_role,
message_type=message_type,
)
return composed[offset : offset + limit], len(composed), completeness
🤖 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/queries/message_query_reads.py` around lines 390 -
407, Wrap session resolution, prefix-sharing detection, lineage composition,
filtering, counting, and page slicing in a single deferred read transaction
around the relevant query flow. Update the path using _prefix_sharing_edge and
get_messages_with_lineage_completeness so the nested composition call reuses
that transaction, preventing a link committed between detection and retrieval
from selecting the normal SQL path.

@Sinity
Sinity merged commit 8beef5f into master Jul 31, 2026
1 of 3 checks passed
@Sinity
Sinity deleted the feature/storage/surface-lineage-truncation-signal branch July 31, 2026 11:20
Sinity added a commit that referenced this pull request Jul 31, 2026
#3448)

## Summary

Claude Code subagent transcripts (`Task` invocations) share ONE
session-level
`tool-results/` sidecar directory with their parent, but the join that
attaches/accounts for those sidecar files was scoped to a single
transcript's
own `tool_use_id` index. This PR makes the join session-wide and
instruments
`occurred_at_ms` on the resulting session events, which was previously
always
NULL.

## Problem

A conversation-fidelity audit flagged 554,251 (98%) of 565,536
`claude_tool_result_sidecar` session events in the live archive as
`no_owning_tool_result_block` debt, with `occurred_at_ms` NULL on every
one
(no way to tell historical vs. still-accruing), against this module's
own
docstring claiming a 1-5% rate.

Investigating against the live archive
(`file:/realm/db/polylogue/index.db?mode=ro`)
and the real `~/.claude/projects` corpus established the actual
mechanism:

- Every subagent transcript (`<session>/subagents/agent-*.jsonl`), and
separately its `agent-*.meta.json` metadata companion
(`AGENT_SIDECAR_META`,
ingested as its own lightweight quasi-session), gets independently
parsed
and independently re-enumerates the SAME shared `tool-results/`
directory.
A transcript that doesn't own a given sidecar file still classified it
as
  debt -- once per non-owning sibling.
- The unit that matters is the physical file, not the event: the same
file
re-observed by N non-owning siblings is one piece of missing evidence,
not
  N.
- Disk cross-check (basename match against files physically present
under
`~/.claude/projects/*/*/tool-results/`): **~12,000 distinct debt files,
  ~1.4GB, 100% still present on disk.** No data loss, no rotation. The
archive-wide "98%"/"72GB" figures were per-event artifacts of ~46x
replay
fanout on top of ~12,000 real files -- this reconciles cleanly with the
  module's original file-counted "1-5%" docstring claim (different
denominators, never actually in conflict; the docstring was not wrong
and
  was not changed to "fix" it).
- Verified the fix resolves the scope bug directly: 3 hand-picked
  multi-subagent sessions (172, 73, 49 physical sidecar files) resolved
**100%** once sibling transcripts were joined into a session-wide index;
a
  further 25-session random sample resolved 99.6% (478/480).

## Solution

- `join_tool_result_sidecars_session_scoped` (+
  `ToolResultIndexAccumulator.join_session_scoped` for the streaming
  multi-GiB path) in `polylogue/sources/live/tool_result_sidecars.py`:
  - A non-root transcript (anything under `subagents/`, `.jsonl` or
`.meta.json`) never originates debt for a directory it doesn't own -- it
    only ever matches its own ids, silently skipping files it doesn't
    recognize so the true owner's own pass can match them.
- The root/parent transcript builds a session-wide union index from
every
    sibling `.jsonl` transcript read from disk
(`resolve_sibling_transcript_paths`) and classifies debt against that
union, so each physical file is judged, and reported as debt at most,
    once.
- `polylogue/sources/dispatch.py`'s eager and streaming Claude Code
paths
now call the session-scoped join instead of the single-transcript one.
- `SidecarMatch`/`SidecarDebt` now carry the sidecar file's own mtime
  (`file_mtime_ms`); `apply_tool_result_sidecars`
(`polylogue/sources/parsers/claude/code_parser.py`) threads it into the
  emitted event's `timestamp`, populating `occurred_at_ms` going forward
  (the join has no better time source -- sidecar files carry no embedded
  timestamp).
- Unrelated, pre-existing drift fix folded in because it blocked the
  pre-push hook for any branch off current `master`: registered
  `polylogue/storage/sqlite/queries/session_commits.py` (added by #3444,
  the immediately preceding commit) in the topology projection via
  `devtools render topology-projection` -- confirmed present on a clean
`origin/master` checkout via `git stash` before fixing it, not caused by
  this branch's own changes.

## What this does NOT fix

The derived index (`index.db`) is rebuildable, not durable -- these
changes
only affect future parses. The live archive's existing 556,871 debt rows
keep their current (inflated, NULL-timestamp) values until an
operator-scheduled `polylogue ops reset --index && polylogued run`
re-materializes the index, which is a `SEMANTIC_REPARSE` per
`storage/sqlite/lifecycle.py` and out of scope here (the live archive
was
read-only for this investigation). Filed `polylogue-x1gd` to re-measure
after that rebuild and partition whatever residue remains by cause (not
a
single undifferentiated number) -- sampling found a small number of
files
(2 of 480 sampled) that stayed unresolved even against the full
session-wide union, plausibly compaction-pruned turns that are genuinely
gone; an exhaustive post-rebuild count is needed to confirm the scale.

## Verification

- `devtools test tests/unit/sources/test_tool_result_sidecars.py
tests/unit/sources/test_dispatch_payloads.py` -- 30 passed (new:
session-scoped resolution of a sibling-owned file without duplicate
debt/match, `.meta.json` companion never emits debt,
`resolve_sibling_transcript_paths` on real directory layouts,
`occurred_at_ms` populated from a controlled file mtime via `os.utime`).
- `mypy --strict` on all three changed source files -- Success: no
issues found.
- `ruff format --check` / `ruff check` on all changed files -- clean.
- `devtools render all --check` -- exit 0, no drift.
- `devtools verify --quick` -- green (after the topology fix above).

Ref polylogue-x1gd

---------

Co-authored-by: Claude <[email protected]>
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

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

  • 61.F128 / P2: fixed-already at the checked revision: The file writer now retains each window's lineage completeness and reason, passes them to message_page_outcome at polylogue/cli/read_views/messages.py:221, and serializes that outcome into the JSON document. The file therefore carries the partial-lineage warning instead of presenting incomplete evidence as complete.

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