Skip to content

fix(sources): stop claude-code tool-result sidecars over-counting debt - #3448

Merged
Sinity merged 4 commits into
masterfrom
feature/fix/tool-result-sidecar-debt-scope
Jul 31, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/fix/tool-result-sidecar-debt-scope

Conversation

@Sinity

@Sinity Sinity commented Jul 31, 2026

Copy link
Copy Markdown
Owner

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 fix(storage): surface lineage completeness, delegation join, checkout commits #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

Sinity and others added 3 commits July 31, 2026 13:43
Problem: a conversation-fidelity audit found 554,251 (98%) of 565,536
claude_tool_result_sidecar session events classified as
no_owning_tool_result_block debt, against a module docstring claiming
1-5%. occurred_at_ms was NULL on all of them, so historical vs still-
accruing was undecidable.

Root cause established against the live archive and real ~/.claude/
projects transcripts: every Claude Code subagent transcript shares one
session-level tool-results/ directory with its parent, but the join was
scoped to a single transcript's own tool_use_id index. A subagent that
doesn't own a file in that shared directory still enumerated it and
recorded it as debt -- once per sibling subagent. Deduplicating by
(session, filename) drops the reported 556,871 debt rows to 14,209
physically distinct files; a session-wide union-index join (parent +
every sibling subagent .jsonl read from disk) resolved 100% of files in
3 sampled multi-subagent sessions and 99.6% (478/480) across a further
25-session random sample -- the debt was a join-scope bug, not lost
content.

Solution:
- join_tool_result_sidecars_session_scoped (+ ToolResultIndexAccumulator.
  join_session_scoped for the streaming path) in tool_result_sidecars.py:
  a subagent transcript only ever matches its own ids and never
  originates debt for a directory it doesn't own; the root/parent
  transcript builds a union index from every sibling .jsonl on disk
  (resolve_sibling_transcript_paths) and classifies debt against that
  union, so each physical file is judged, and reported as debt at most,
  once. 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 threads it into the
  emitted event's timestamp so occurred_at_ms is populated instead of
  permanently NULL going forward.

What this does NOT fix: the derived index is rebuildable, not durable
-- these fixes only change future parses. The live archive's existing
554,251 debt rows keep their current (inflated, NULL-timestamp) values
until an operator-scheduled `polylogue ops reset --index && polylogued
run` re-materializes the index with this code, which is a
SEMANTIC_REPARSE per storage/sqlite/lifecycle.py and out of scope here
(read-only live archive per task constraints). Sampling also does not
prove the residual is zero: of the ~14,209 physically distinct debt
files, the 25-session sample found 2 that remained unresolved even
against the full session union (compaction-pruned candidates); a live
rebuild is needed for an exhaustive count and cause partition.

Verification:
- devtools test tests/unit/sources/test_tool_result_sidecars.py
  tests/unit/sources/test_dispatch_payloads.py -- 29 passed (new tests:
  session-scoped resolution of a sibling-owned file without duplicate
  debt/match, resolve_sibling_transcript_paths on real directory
  layouts, occurred_at_ms populated from a controlled file mtime via
  os.utime).
- mypy --strict polylogue/sources/live/tool_result_sidecars.py
  polylogue/sources/parsers/claude/code_parser.py
  polylogue/sources/dispatch.py -- Success: no issues found.
- ruff format --check / ruff check on all four changed files -- clean.
- devtools render all --check -- exit 0, no drift.
- devtools verify topology: pre-existing orphan
  (polylogue/storage/sqlite/queries/session_commits.py, from a prior
  unrelated merge) confirmed present on origin/master via git stash;
  untouched by this change.

Co-Authored-By: Claude <[email protected]>
Problem: origin/master (as of 8beef5f, #3444) added
polylogue/storage/sqlite/queries/session_commits.py without regenerating
the topology projection, leaving it an undeclared orphan (realized=1105
declared=1104, blocking=True) -- verified pre-existing via `git stash`
against a clean origin/master checkout before this commit, unrelated to
the sidecar-debt fix on this branch. It blocked `devtools verify
--quick` (and therefore the pre-push hook) for any branch based on
master, including this one.

Solution: `devtools render topology-projection` per CLAUDE.md's
"Adding a module without regenerating the topology projection breaks
render all --check" gotcha -- a mechanical projection sync, no change to
session_commits.py itself.

Verification: devtools verify topology -- realized=1105 declared=1105,
blocking=False.

Co-Authored-By: Claude <[email protected]>
…t count

Problem: independent re-measurement (basename match against files
physically present under ~/.claude/projects) found the debt cohort is
~12,000 distinct files (~1.4GB), all present on disk, not the 14,209
(~2.02GB) this branch's first commit computed by string-parsing
session_id prefixes out of the archive alone. Root cause of that gap:
Claude Code's agent-*.meta.json subagent metadata companion (a
DISTINCT capture surface, AGENT_SIDECAR_META) is ingested as its own
quasi-session with a session_id shaped
"claude-code-session:agent-<hash>.meta" -- no session UUID segment --
so the ':agent-' prefix-stripping used to reconstruct a "root session"
collapsed every one of these onto one degenerate bucket, double-
counting each such file once under its real owning session and once
under that bucket.

This also means the .meta.json companion was ITself a live source of
false debt before this branch's first commit: it lives under
subagents/ exactly like an agent-*.jsonl transcript and shares the same
tool-results/ directory, so a naive single-transcript join
misclassified the whole directory as debt from IT too -- a second,
independent copy of the .jsonl fanout this branch already fixed.

Solution: no new logic needed. _is_root_transcript's path-shape check
(parent.name == "subagents") already applies uniformly to
agent-*.meta.json paths, so join_tool_result_sidecars_session_scoped
already treats them as non-root: never emits debt, and -- since a
metadata file carries no tool_result blocks -- never emits a spurious
match either. Added
test_session_scoped_join_never_emits_debt_for_subagent_meta_companion_files
to lock this in explicitly rather than leave it an accidental
consequence.

Docstring: reconciled to the corrected, disk-verified counts (~12,000
distinct files / ~1.4GB, 100% present) and made explicit that the
"debt" unit 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. Confirmed the original file-counted "1-5%" docstring claim was
never actually in conflict with the archive-wide "98%" figure -- they
counted different denominators (files vs. events) -- so no
"docstring was wrong" framing belongs in this fix.

Verification:
- devtools test tests/unit/sources/test_tool_result_sidecars.py
  tests/unit/sources/test_dispatch_payloads.py -- 30 passed.
- mypy --strict polylogue/sources/live/tool_result_sidecars.py --
  Success: no issues found.
- ruff format / ruff check on both changed files -- clean.

Co-Authored-By: Claude <[email protected]>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

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

Next review available in: 8 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: 34d58590-3917-4dd7-970f-a6920f39e4cf

📥 Commits

Reviewing files that changed from the base of the PR and between 614dc44 and 572842e.

📒 Files selected for processing (4)
  • polylogue/sources/dispatch.py
  • polylogue/sources/live/tool_result_sidecars.py
  • polylogue/sources/parsers/claude/code_parser.py
  • tests/unit/sources/test_tool_result_sidecars.py

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.

# Conflicts:
#	docs/plans/topology-target.yaml
@Sinity
Sinity merged commit 04cb44c into master Jul 31, 2026
1 of 3 checks passed
@Sinity
Sinity deleted the feature/fix/tool-result-sidecar-debt-scope branch July 31, 2026 12:05
Sinity added a commit that referenced this pull request Aug 2, 2026
…ad model (#3543)

## Summary

Ingests Claude Code's live plan-snapshot directory
(`~/.claude/todos/*.json`) into the archive end-to-end: raw admission
with provenance, a session-linked read model over every retained
revision, and a registered plan-completion metric.
`~/.claude/file-history/` is deferred as a scoped follow-up (see below).

## Problem

polylogue-t0p: Claude Code writes several artifacts beyond the session
JSONL transcript that answer questions the transcript alone cannot, and
the harness prunes some of them on its own schedule -- unread state is
eventually lost, not merely delayed.
`~/.claude/todos/<session-id>[-agent-<agent-id>].json` holds the agent's
current TODO/plan list (task content/status/priority/id), overwritten
wholesale on every `TodoWrite` call. Nothing in the archive captured
this before.

## Solution

- **Admission**: a new `todo_snapshot` `OriginArtifactRule` in
`polylogue/sources/origin_specs.py` classifies `todos/*.json` as a
fact-tier Claude Code artifact, the same admission shape already used
for `workflow_run_snapshot`/`agent_sidecar_meta` (PR #3419/#3437/#3448
sidecar-join precedent this bead pointed at). Fidelity is declared
explicitly: preserved -- every item's content/status/priority/id and the
agent's own list order; lost -- intermediate status transitions between
two watcher-observed snapshots (each write is a full overwrite, no
in-file timestamp), and anything pruned before observation.
- **Parser**: `polylogue/sources/parsers/claude/todos.py` parses the
bare JSON array and recovers `session_id`/`agent_id` from the filename
(`<uuid>[-agent-<uuid>].json`, verified against the real on-disk shape
under `~/.claude/todos/`).
- **Watched root**: `~/.claude/todos` is a new configured/watched source
(`polylogue/config.py`, `polylogue/paths/_roots.py`,
`polylogue/sources/live/watcher.py` -- a second `WatchSource` sibling to
`claude-code`, same pattern as the existing `codex-state` root), aliased
to the `claude-code` provider (`polylogue/core/provider_identity.py`) so
the existing `_admit_non_session_origin_artifacts` admission path and
`classify_artifact_path` pick it up with zero bespoke wiring --
confirmed by tracing that gate's `Provider.from_string(source.name) is
Provider.CLAUDE_CODE` filter.
- **Read model**: `polylogue/insights/claude_todo_projection.py` is a
storage-free, session-linked projection (same justification as
`insights/run_projection.py`) over every retained `todo_snapshot` raw
revision in `raw_sessions` (not just the current-pointer `raw_artifacts`
row, which would collapse history to the latest snapshot) -- per-session
plan state, latest completion rate, and per-item status-transition
history across observed snapshots.
- **Measure registration**: `plan_completion_rate` registered in
`insights/measurement/registered_metrics.py`'s `DEFAULT_METRIC_REGISTRY`
(rxdo.9.1 identity layer), the same bounded slice `session_cost_usd`
already uses -- reachable via MCP
`get(ref="metric:plan_completion_rate")`. polylogue-9l5.7's full
statistics/composition registry (checked: still open, `MeasureSpec`
unimplemented) is *not* duplicated here; this registers identity only,
same limitation `session_cost_usd` already documents.

## Deferred: `~/.claude/file-history/`

Investigated the real on-disk shape to save the follow-up lane research
time:

- Each session has a directory
`~/.claude/file-history/<session-id>/<hash>@v<N>` holding **raw pre-edit
file bytes with no wrapper** (no path, no timestamp inside the file
itself).
- The mapping from `<hash>@v<N>` back to a real file path lives **inside
the session's own JSONL transcript**, in a `type:
"file-history-snapshot"` record's `snapshot.trackedFileBackups: {<path>:
{backupFileName, version, backupTime}}` map (plus `type:
"file-history-delta"` records for incremental updates).
- This is **already parsed today** as an evidence-only session event
(`code_parser.py`'s `_sidecar_evidence_payload` for
`file-history-snapshot`/`file-history-delta`, `#2qx.4`) -- it records
the file list and backup pointers, but never acquires the actual
snapshot bytes at `~/.claude/file-history/`.
- Follow-up scope: join the already-parsed `trackedFileBackups` pointers
to the sibling `~/.claude/file-history/<session-id>/` directory,
content-address-acquire each snapshot as a blob keyed to (session, path,
version), and apply the same privacy/redaction discipline
`_acquire_attachment_blob` uses for attachments (these are literal
pre-edit file contents from real projects). This is a distinct
acquisition shape from `todo_snapshot` (cross-referencing two
directories, not a single self-contained file) and was intentionally
left out of this PR per the bead's own note that if full scope is too
large for one PR, todos should land alone.

Lower-priority artifacts the bead also names (`history.jsonl`,
`history-summaries/`, `debug/`, `mcp-logs/`, `ide/` locks, `jobs/`,
`ccusage`/stats caches) were not investigated this session; still open.

## Verification

- `devtools test tests/unit/sources/test_origin_specs.py
tests/unit/sources/test_parsers_claude_todos.py
tests/unit/insights/test_claude_todo_projection.py
tests/unit/core/test_config.py tests/unit/sources/test_live_watcher.py`
-> 219 passed. (One pre-existing failure,
`test_live_batch_processor_records_durable_attempt`, reproduces
identically with this diff stashed on this same checkout -- unrelated
codex-path assertion, not touched by this change.)
- `mypy polylogue` -> `Success: no issues found in 1113 source files`.
- `ruff check` / `ruff format --check` -> clean.
- `devtools render all --check` -> OK (topology projection regenerated
for the two new modules, `devtools render topology-projection`).
- `devtools verify --quick` -> exit 0 (includes a cherry-picked,
already-vetted-elsewhere ack commit for an unrelated pre-existing
`classifier-fingerprints` gate failure from PR #3537, tracked separately
at issue #3540 -- confirmed via `git stash` that this failure predates
and is independent of this branch's changes).

Anti-vacuity: removing the `todo_snapshot` `OriginArtifactRule` (or
narrowing its path pattern) makes
`artifact_rule_for_path`/`classify_artifact_path` return `None` for a
real todos path, which
`test_origin_spec_admits_todos_directory_artifact_as_fact_tier` and the
end-to-end
`test_todos_admitted_and_materialized_into_session_linked_plan_states`
(via `parse_sources_archive`) both catch. Removing the
`claude-code-todos` -> `claude-code` provider alias makes
`_admit_non_session_origin_artifacts`'s
`Provider.from_string(source.name) is Provider.CLAUDE_CODE` gate skip
the source entirely, caught by
`test_todos_source_name_resolves_to_claude_code_provider` and the same
end-to-end test (would return zero plan states).

Ref polylogue-t0p

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

Co-authored-by: Claude <[email protected]>
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