Skip to content

refactor(archive): consume structural tool_result outcome in terminal_state - #2730

Merged
Sinity merged 3 commits into
masterfrom
refactor/structural-outcome-evidence
Jul 12, 2026
Merged

Sinity merged 3 commits into
masterfrom
refactor/structural-outcome-evidence

Conversation

@Sinity

@Sinity Sinity commented Jul 12, 2026

Copy link
Copy Markdown
Owner

Summary

Converts _terminal_state's (session_profiles' terminal-state classifier) mid-session error detection from an unconditional prose-keyword scan to the structural blocks.tool_result_is_error/tool_result_exit_code columns (index schema v16 keystone), with an honest per-origin coverage caveat and an evidence_class tag (raw_evidence/text_derived) on every branch. Also completes the module:line -> verdict inventory the bead's acceptance criteria requires, documenting sites that were already structural, sites with no structural equivalent (LABEL, not CONVERT), and sites out of scope.

Problem

polylogue-b0b's design note: wherever detectors/insights modules regex-match prose to infer outcomes, consume tool_result_is_error/tool_result_exit_code instead, with per-origin coverage caveats where structure is absent. polylogue-9e5.9's closing evidence found the sibling keyword classifier in the same file (runtime.py::_terminal_state's _ERROR_MARKERS fallback) scores only 50.5% (coin-flip) agreement against structural ground truth on 14,377 real runs — the exact "construct-validity moat" this bead exists to protect.

Grepping insights/, archive/, schemas/code_detection/, and the pathology surfaces for prose-pattern outcome matching found:

  • archive/session/runtime.py::_terminal_state's action-loop _ERROR_MARKERS scan over action.output_text — the live CONVERT target.
  • archive/session/runtime.py::_terminal_state's last-message scan and its clean_finish complement — no structural equivalent (LABEL).
  • archive/actions/followup.py's ACKNOWLEDGMENT_MARKERS/classify_failed_followup(_evidence) — classifies whether the assistant acknowledged an already-structural failure; no structural equivalent (LABEL). Two live consumers: the public followup_class query-DSL field (SQL reimplementation in archive_tiers/archive.py) and devtools claim-vs-evidence.
  • Several sites already fully structural, needing only documentation: insights/pathology.py (the former prose-mined missed_review detector was already removed in feat: polylogue topic-pack — staged multi-channel topic-lineage retrieval #2482 — the bead's own cautionary fixture), insights/transforms.py::_extract_events/_tool_status, insights/run_projection.py::_main_run_status, _terminal_state's session-event status check (a typed key on Codex's own protocol event payload, not prose), schemas/code_detection/tree_sitter.py's tree-sitter AST error node, and sources/providers/claude_code_models.py's anchored parse-time notification-envelope regexes.
  • insights/transforms.py::_tool_handler_kind/_looks_like_test_output — a category classifier (test vs. shell), not a pass/fail determination (already 100% structural); adjacent to but outside the outcome/pathology scope.

Solution

  • archive/actions/parsing.py: new tool_result_outcome()/tool_result_block_outcome() helpers implementing the canonical exit_code/is_error precedence (exit_code authoritative when present, else is_error, else "unknown" — never guessed from prose). Reads both the hydrated storage-column keys and the bare parse-time keys (ParsedContentBlock.is_error/exit_code), matching the dual-key convention rendering/block_models.py already uses. build_tool_calls_from_content_blocks now populates the previously-declared-but-dead ToolCall.success field from this structural signal.
  • archive/actions/actions.py: Action gains tool_success: bool | None, propagated from ToolCall.success.
  • archive/session/runtime.py: _terminal_state resolves a session-wide tool_id -> (outcome, text) map (_session_tool_results), mirroring _pending_tool_blocks's and insights/transforms.py's existing session-wide tool_use/tool_result pairing — per-message Action pairing alone misses the common Claude/Codex shape where a tool_use and its tool_result land in separate messages (discovered while writing the regression tests: a naive per-message Action.tool_success never fired for realistic fixtures). A structural "failed" verdict is used directly; a structural "ok" verdict suppresses the prose fallback (fixes a real false positive: "0 errors found" previously matched the "error" keyword substring); only a genuinely absent structural signal falls back to the tagged _ERROR_MARKERS scan. Every branch now returns an evidence_class key ("raw_evidence"/"text_derived") in terminal_state_evidence.
  • insights/transforms.py::_tool_status delegates to the new canonical tool_result_outcome() instead of duplicating the same precedence rule (dedup, per the sibling-drift risk the bead's construct-validity framing calls out).
  • insights/rigor.py + docs/insights-rigor-matrix.md: session_profiles contract gains a notes entry (following the #b0b.1 established pattern) describing the CONVERT, its origin-gated coverage caveat (tool_result_is_error well-populated only for claude-code-session/claude-ai-export, tool_result_exit_code only for codex-session at 14%), and the evidence_class contract.
  • archive/actions/followup.py: documents the LABEL verdict for ACKNOWLEDGMENT_MARKERS/its consumers in the module docstring.
  • archive/query/metadata.py: followup_class DSL field description now reads "(keyword-heuristic, text-derived)" so query discovery/CLI help surfaces the tier honestly.

Alternatives rejected

Fixing build_tool_calls_from_content_blocks to pair tool_use/tool_result session-wide (instead of adding a dedicated session-wide helper in runtime.py) was rejected — it would change Action.output_text/search_text for every Action consumer (CLI action rendering, tool-usage stats, search text), a much larger blast radius than this bead's outcome-heuristic scope.

Verification

  • devtools test tests/unit/core/test_semantic_facts.py -k terminal_state — 9 passed (6 existing tests updated for the new evidence_class key, 3 new tests: structural failure caught with zero error-marker prose anywhere in the session; structural "ok" suppressing a misleading "0 errors found" false positive; an origin with no structural coverage still getting the tagged text fallback).
  • devtools test tests/unit/core/test_semantic_facts.py tests/unit/archive/ tests/unit/insights/ tests/unit/devtools/test_claim_vs_evidence.py — clean individually and in this combined run (678+ passed); large multi-directory/whole-suite batches on this shared host show unrelated pre-existing flakiness (confirmed identical failure sets reproduce with these changes fully git stashed out — shared seeded_db/host contention, not this diff).
  • devtools lab policy insight-honesty — every registered insight contracted or exempt.
  • devtools verify --quick — exit 0 (ran twice: pre-rebase and via the pre-push hook).

Not run: full devtools verify --all / testmon-seeded suite (fresh worktree requiring a full-suite seed pass; the targeted runs above cover every file this change touches).

Ref polylogue-b0b

Sinity and others added 3 commits July 12, 2026 03:27
…_state

Problem: archive/session/runtime.py::_terminal_state (session_profiles'
terminal_state heuristic) determined mid-session tool errors purely by
regex-scanning Action.output_text/last-message text for words like
"error"/"failed", even though blocks.tool_result_is_error/
tool_result_exit_code (index schema v16 keystone) already carry the
provider-reported structural verdict for the same tool_result. The
9e5.9 audit found a sibling keyword classifier in the same file scores
only 50.5% (coin-flip) agreement against structural ground truth.

Solution:
- polylogue/archive/actions/parsing.py: new tool_result_outcome() /
  tool_result_block_outcome() helpers implementing the canonical
  exit_code/is_error precedence (exit_code authoritative when present,
  else is_error, else "unknown" -- never guessed from prose). Reads
  both the hydrated storage-column keys and the bare parse-time keys
  (ParsedContentBlock.is_error/exit_code), matching the dual-key
  convention rendering/block_models.py already uses.
  build_tool_calls_from_content_blocks now populates the previously
  dead ToolCall.success field from this structural signal.
- polylogue/archive/actions/actions.py: Action gains tool_success: bool
  | None, propagated from ToolCall.success.
- polylogue/archive/session/runtime.py: _terminal_state now resolves a
  session-wide tool_id -> (outcome, text) map (_session_tool_results,
  mirroring _pending_tool_blocks' and insights/transforms.py's existing
  session-wide tool_use/tool_result pairing -- per-message Action
  pairing alone misses the common Claude/Codex shape where tool_use and
  its tool_result land in separate messages). A structural "failed"
  verdict is used directly; a structural "ok" verdict suppresses the
  prose fallback (fixing a real false-positive: "0 errors found"
  previously matched the "error" keyword); only a genuinely absent
  structural signal falls back to the tagged _ERROR_MARKERS scan. Every
  terminal_state branch now returns an evidence_class key
  ("raw_evidence" or "text_derived") in terminal_state_evidence so
  consumers can filter to grounded rows.
- polylogue/insights/transforms.py::_tool_status delegates to the new
  canonical tool_result_outcome() instead of duplicating the same
  precedence rule.

Verification:
- devtools test tests/unit/core/test_semantic_facts.py -k terminal_state
  (9 passed: 6 existing terminal_state tests updated for the new
  evidence_class key, 3 new tests proving (a) a structural failure is
  caught with zero reliance on error-marker prose, (b) a structural
  "ok" verdict suppresses a misleading "0 errors found" false positive,
  (c) an origin with no structural coverage still gets the tagged text
  fallback).
- devtools test tests/unit/core/test_semantic_facts.py tests/unit/archive/
  tests/unit/insights/ tests/unit/devtools/test_claim_vs_evidence.py:
  clean individually/small-batch (large multi-directory batches on this
  host show unrelated pre-existing flakiness reproducible with these
  changes stashed out -- see PR body).
- devtools verify --quick: exit 0.

Ref polylogue-b0b

Co-Authored-By: Claude <[email protected]>
Adds regression coverage for the structural tool_result_outcome
conversion in _terminal_state (polylogue-b0b): a structural failure
caught with no error-marker prose anywhere in the session, a
structural "ok" verdict suppressing a misleading "0 errors found"
false positive that the old unconditional prose scan would have
misclassified, and an origin with no structural coverage still
getting the tagged text_derived fallback instead of a silent gap.
Updates the six pre-existing terminal_state assertions for the new
evidence_class key every branch now returns.

Verify: devtools test tests/unit/core/test_semantic_facts.py -k
terminal_state (9 passed).

Ref polylogue-b0b

Co-Authored-By: Claude <[email protected]>
Problem: polylogue-b0b requires a committed module:line -> verdict
inventory for every prose/regex outcome heuristic, not just the one
converted in the prior commit. Several sites were already correctly
structural (insights/pathology.py's detectors, insights/transforms.py
_extract_events/_tool_status, run_projection.py's _main_run_status)
or have no structural equivalent to convert to and were never
labelled as such.

Solution:
- polylogue/insights/rigor.py + docs/insights-rigor-matrix.md (hand-
  maintained mirror, per the #1275/#b0b.1 pattern): session_profiles
  contract gains a notes entry describing the terminal_state CONVERT,
  its origin-gated coverage caveat, and the evidence_class contract
  every branch now honors.
- polylogue/archive/actions/followup.py: ACKNOWLEDGMENT_MARKERS and
  its classify_failed_followup(_evidence) consumers (the public query
  surface's followup_class SQL path in
  storage/sqlite/archive_tiers/archive.py, and devtools
  claim-vs-evidence) classify whether the *next* assistant turn
  acknowledges an already-structural failure -- prose judgment with no
  structural equivalent, explicit LABEL/heuristic-tier verdict
  documented in the module docstring, not silently left unlabeled.
- polylogue/archive/query/metadata.py: the followup_class DSL field
  description now says "keyword-heuristic, text-derived" so query
  discovery/CLI help surfaces the tier honestly.

Full inventory (module:line -> verdict), beyond what's covered above:
- archive/session/runtime.py _terminal_state's session-event status
  check: already structural (typed key on Codex's own tool-call
  protocol event payload, not prose) -- no change.
- archive/session/extraction.py _TEXT_SIGNAL_TABLE (work-event
  activity-type): already labelled heuristic-tier in #b0b.1 (no
  structural proxy exists for "what category of work is this").
- insights/transforms.py _tool_handler_kind/_looks_like_test_output:
  a category classifier (test vs. shell vs. generic), not a pass/fail
  determination -- the pass/fail itself is already 100% structural via
  _tool_status/_extract_events; adjacent to but outside b0b's
  outcome/pathology scope, no change.
- schemas/code_detection/tree_sitter.py ts_error_ratio: tree-sitter's
  own AST ERROR node, not a prose heuristic -- no change.
- sources/providers/claude_code_models.py
  _BACKGROUND_COMMAND_(SUCCESS|FAILURE)_RE: anchored full-string parse
  of Claude Code's own fixed-format notification envelope at parse
  time, not fuzzy prose scanning -- no change.
- insights/pathology.py: already fully structural (the former
  prose-mined missed_review detector was removed in #2482, the
  standing cautionary fixture referenced in b0b's own design note).

Verify: devtools lab policy insight-honesty (every registered insight
contracted or exempt); devtools verify --quick (render all --check
included, exit 0).

Ref polylogue-b0b

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, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 12, 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: 34 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: eb298d65-380e-470f-a0b1-53b362b67d8e

📥 Commits

Reviewing files that changed from the base of the PR and between 62dc0b0 and dd8a387.

📒 Files selected for processing (9)
  • docs/insights-rigor-matrix.md
  • polylogue/archive/actions/actions.py
  • polylogue/archive/actions/followup.py
  • polylogue/archive/actions/parsing.py
  • polylogue/archive/query/metadata.py
  • polylogue/archive/session/runtime.py
  • polylogue/insights/rigor.py
  • polylogue/insights/transforms.py
  • tests/unit/core/test_semantic_facts.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/structural-outcome-evidence

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.

@Sinity
Sinity merged commit dc8d128 into master Jul 12, 2026
3 of 15 checks passed
@Sinity
Sinity deleted the refactor/structural-outcome-evidence branch July 12, 2026 01:33
Sinity added a commit that referenced this pull request Jul 12, 2026
Beads-only bookkeeping. polylogue-sjf6 closed with honest AC accounting
(root cause merged PR #2729, AC#5 deferred to polylogue-t0dy);
polylogue-b0b closed (PR #2730 merged).

CI blocked repo-wide by account billing lock; GitGuardian passed.
devtools verify --quick passed locally (14/14).

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