Skip to content

feat(analyze): add --postmortem distilled session bundle (#2380) - #2431

Merged
Sinity merged 4 commits into
masterfrom
feature/feat/analyze-postmortem-bundle
Jun 26, 2026
Merged

Sinity merged 4 commits into
masterfrom
feature/feat/analyze-postmortem-bundle

Conversation

@Sinity

@Sinity Sinity commented Jun 26, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds polylogue analyze --postmortem (aka "blame") — one compact, shareable
artifact over a matched session scope, available as plain text, Markdown, and
JSON, all rendered from a single typed PostmortemBundle. Every real headline
metric carries ≥1 drillable EvidenceRef. This is Train 1, item 2 ("the blade")
of the #1807 epic.

Problem

The source review behind #2380: "the logs are the ore; do not mail them a
mountain — forge a blade."
#1807 lists these exact cockpit questions (what did
an agent do, what did it cost, what did it touch). The recovery-digest substrate
(compile_recovery_digest, the blame preset, get_recovery_report) was ~70%
of the way there but had no scope-level aggregator and no first-class CLI verb.

Note on the issue premise: it lists per-session wallclock as a missing gap.
It is not — wall_duration_ms already exists on the session profile
(archive_models.py), so the bundle uses real per-session wall time directly.

Solution

  • polylogue/insights/postmortem.py (new): the typed PostmortemBundle
    model set and a pure compile_postmortem_bundle(profiles, digests, *, scope)
    aggregator (no I/O — unit-testable in isolation), plus render_postmortem_plain
    / render_postmortem_markdown (both derive from the same bundle object).
  • Polylogue.postmortem_bundle(spec, *, limit) (api/archive.py): resolves
    the matched session set via the same summary path facets uses, batch-fetches
    profiles, fetches per-session recovery digests for a bounded set (cap 200;
    truncation is flagged on the bundle and logged, never silent), delegates to the
    pure aggregator.
  • CLI (cli/query_verbs.py): --postmortem as a mutually-exclusive analyze
    mode; plain (default), --format json (via the standard success(...)
    envelope), and --format markdown.

Real vs degraded headline fields (honest accounting)

Real, each carrying EvidenceRefs: session_count, wallclock_span (earliest
first_message_at → latest last_message_at, plus summed real
wall_duration_ms), estimated_cost with separately labelled token lanes
(input / output / cache-read / cache-write — no undifferentiated "tokens", per
AC4) + total_cost_usd, repos_touched, top_expensive_session,
subagent_branch_count (counted from run_projection.runs[].role == "subagent").

Degraded honestly (null + explicit status + reason, never fabricated):

  • failure_mode, wasted_loop → status: "no_signal" — the feat(insights): mine agent-workflow failure-mode pathologies #2383 pathology
    detector is not built yet (AC5 explicitly permits absent-or-degraded here).
  • longest_tool_gap → status: "unavailable" — neither the session profile nor
    the recovery digest carries per-tool-call timestamps in v0. Using
    latency_percentiles_ms (inter-message latency) would have mislabeled it, so
    it degrades rather than fabricates. Tracked as a v0 follow-up.

Verification

  • devtools verify --quick → exit_code 0 (ruff format/check, mypy --strict,
    render all --check).
  • devtools test tests/unit/insights/test_postmortem.py tests/unit/cli/test_plain_cli_snapshots.py
    → 20 passed, 11 snapshots passed. The unit tests cover a fully-populated
    multi-session case (cost / repos / subagent / top-expensive all exercised with
    constructed inputs incl. a subagent-bearing recovery digest), a degradation
    case (proves the three degraded fields are null-with-status, never fabricated),
    and a JSON-headline-key contract.
  • CLI snapshots (test_{plain,json}_analyze_postmortem_snapshot) pin the
    rendered artifact against a deterministic, private-data-free corpus archive
    with insights materialized — analyzed_session_count=4, populated
    wallclock_span. This is the AC3 stable snapshot-able artifact.
  • Live CLI run against a seeded archive returns exit 0 and renders all three
    formats.

Known limitation / follow-up

polylogue demo seed alone does not materialize session-profile insights, so
demo seed → analyze --postmortem reports analyzed=0 and an empty bundle
(the command degrades correctly). A populated bundle requires materialized
profiles — present after a daemon-backed ingest (polylogue import --demo --wait)
or in the corpus test fixture used by the snapshots. Wiring the #2379 README
first-contact demo to the daemon-backed demo path (so the postmortem renders
populated there) is a small follow-up, not part of this substrate slice.

Acceptance criteria (#2380)

  • analyze --postmortem returns every named field; each real headline metric
    carries ≥1 drillable EvidenceRef.
  • JSON envelope contract-tested; plain + Markdown render from the same payload.
  • Runs against a no-private-data archive, producing a stable snapshot-able
    artifact (CLI snapshot test).
  • Cost fields label provider/cache/reasoning token lanes separately; wallclock
    is real per-session duration.
  • failure_mode / wasted_loop (and longest_tool_gap) are absent-or-degraded
    with explicit status, never fabricated.

Ref #2380. Ref #1807.

Summary by CodeRabbit

  • New Features
    • Added a new analyze --postmortem option to view a distilled session postmortem in plain text, Markdown, or JSON.
    • Introduced postmortem summaries with scope, timing, cost, repository activity, and diagnostic highlights.
  • Documentation
    • Updated CLI reference and topology docs to include the new postmortem capability and refreshed project metrics.
  • Bug Fixes
    • Improved handling of incomplete data by clearly marking unavailable values instead of showing fabricated results.

Sinity and others added 2 commits June 26, 2026 15:07
Add `analyze --postmortem`: one compact, shareable artifact over a matched
session scope, rendered as plain text, Markdown, or JSON from a single typed
PostmortemBundle. Every headline metric carries >=1 drillable EvidenceRef.

Problem: there was no distilled cross-session "blame" view for an agent-session
scope. Operators had to assemble cost, wallclock, repos, and subagent counts by
hand across multiple read surfaces.

Solution: new pure module polylogue/insights/postmortem.py defines the frozen
typed model set plus compile_postmortem_bundle (no I/O, unit-testable) and the
plain/markdown renderers. New API method Polylogue.postmortem_bundle resolves the
matched session set from the query spec (same summary path as facets),
batch-fetches profiles, fetches per-session recovery digests for a bounded set
(cap 200; truncation is flagged and logged, never silent), and delegates to the
pure aggregator. CLI gains a mutually-exclusive --postmortem analyze mode.

failure_mode and wasted_loop degrade honestly (null + status:no_signal) because
the pathology detector (#2383) is not built. longest_tool_gap degrades
(unavailable) because per-tool-call timestamps are absent from the profile and
digest in v0. Token lanes are labelled separately (input/output/cache-read/
cache-write) — no undifferentiated "tokens".

Ref #2380

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_014pcNXbmmzXHFrpARz48gN6
Add pure-aggregator unit tests for compile_postmortem_bundle: a populated
multi-session case asserting every headline field plus a drillable EvidenceRef,
and a degradation case proving failure_mode/wasted_loop/longest_tool_gap and the
no-signal top_expensive_session never fabricate a value. Add CLI syrupy
snapshots (plain + JSON) over a corpus-seeded archive with rebuilt insights, plus
a JSON contract assertion on the stable headline keys and labelled token lanes.

Ref #2380

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

coderabbitai Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

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

More reviews will be available in 45 minutes and 32 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

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 credits.

🚦 How do rate 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 see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3f89df81-73bb-4559-84bc-a56daade52c7

📥 Commits

Reviewing files that changed from the base of the PR and between 6bb5c3f and 56a4228.

📒 Files selected for processing (6)
  • polylogue/api/archive.py
  • polylogue/cli/query_verbs.py
  • polylogue/insights/postmortem.py
  • tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
  • tests/unit/cli/test_plain_cli_snapshots.py
  • tests/unit/insights/test_postmortem.py
📝 Walkthrough

Walkthrough

Adds a postmortem bundle model and compiler, wires a new analyze --postmortem CLI path through the archive facade, and updates tests, snapshots, docs, and topology metadata.

Changes

Postmortem bundle feature

Layer / File(s) Summary
Bundle schema and rendering
polylogue/insights/postmortem.py
Defines the postmortem bundle schema, aggregation logic, and plain-text and Markdown renderers.
Archive facade and CLI mode
polylogue/api/archive.py, polylogue/cli/query_verbs.py, docs/cli-reference.md
Adds the archive postmortem_bundle method, the analyze --postmortem CLI branch and exclusivity checks, and the CLI help text for the new option.
Bundle unit tests
tests/unit/insights/test_postmortem.py
Verifies bundle compilation, degradation cases, and JSON key stability with in-memory inputs.
CLI snapshot tests
tests/unit/cli/test_plain_cli_snapshots.py, tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
Adds seeded CLI snapshot coverage for the new postmortem output shapes.
Topology docs refresh
docs/plans/topology-target.yaml, docs/topology-status.md
Updates generated topology loc metadata for many modules and increments the summary totals.

Sequence Diagram(s)

sequenceDiagram
  participant analyze_verb
  participant postmortem_bundle
  participant compile_postmortem_bundle
  participant render_postmortem_plain
  participant render_postmortem_markdown
  analyze_verb->>analyze_verb: check analyze mode exclusivity
  analyze_verb->>postmortem_bundle: request bundle for spec and limit
  postmortem_bundle->>compile_postmortem_bundle: profiles, digests, scope
  compile_postmortem_bundle-->>postmortem_bundle: PostmortemBundle
  postmortem_bundle-->>analyze_verb: bundle
  analyze_verb->>analyze_verb: wrap bundle in JSON envelope when --format json
  analyze_verb->>render_postmortem_markdown: bundle when --format markdown
  analyze_verb->>render_postmortem_plain: bundle when terminal text
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Poem

A rabbit hopped through logs so bright, 🐇
Found postmortems tucked in bundle light.
Markdown nibble, JSON crunch,
Plain-text carrots for a brunch.
Hop, hop—sessions gleam tonight!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely names the new analyze --postmortem session bundle feature.
Description check ✅ Passed The description is mostly complete and covers the required summary, problem, solution, verification, and follow-up details.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/analyze-postmortem-bundle

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.

The --postmortem callback param was inserted mid-signature (after
cost_outlook), which shifted positional arguments for unit tests that call
the analyze_verb callback positionally — plan_name received a stray value and
the '--plan requires --cost-outlook' guard fired. Click binds options by dest
name, so moving the new param to the end of the signature preserves positional
callers with no change to CLI behavior.

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

@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: 6

🤖 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 `@polylogue/api/archive.py`:
- Around line 1676-1683: The warning in postmortem_bundle is logging the entire
overflow tail via session_ids[cap:], which can expose many archive IDs and cause
unbounded log volume. Update the logger.warning call in postmortem_bundle to
keep only the matched/cap/dropped totals and, if needed, include a small bounded
preview of the dropped session IDs instead of the full slice. Use the existing
truncated handling around logger.warning and the session_ids/cap variables to
locate the fix.

In `@polylogue/cli/query_verbs.py`:
- Around line 1484-1498: The show_postmortem branch in query_verbs.py rejects
the advertised plaintext format even though render_postmortem_plain already
exists. Update the output_format validation and branching around show_postmortem
so `plaintext` is accepted alongside the default text path, and route it to
render_postmortem_plain just like the current fallback case; keep the json and
markdown handling unchanged.

In `@polylogue/insights/postmortem.py`:
- Around line 177-213: The wallclock span metric in postmortem.py can emit
summed_wall_duration_ms without any evidence_refs when both boundary timestamps
are missing. Update the wallclock_span construction to add a fallback
EvidenceRef when profiles contribute wall_duration_ms but neither
earliest_profile nor latest_profile yields a timestamp, using the existing
session/profile identifiers from the loop to keep the metric drillable.
- Around line 310-404: The plain-text and Markdown renderers in
render_postmortem_plain and render_postmortem_markdown omit the bundle’s
evidence_refs, so the generated postmortem artifacts lose drill-down links.
Update both renderers to include the evidence_refs from the relevant
PostmortemBundle payload sections alongside the existing scope/headline fields,
using the same formatting style as the surrounding output so the refs remain
readable and actionable.

In `@tests/unit/cli/test_plain_cli_snapshots.py`:
- Around line 214-274: Add coverage for the Markdown renderer in the postmortem
CLI snapshots: the existing tests around test_plain_analyze_postmortem_snapshot
and test_json_analyze_postmortem_snapshot pin plain text and JSON, but the new
third output format is not asserted. Introduce a markdown snapshot test
alongside these, invoking the same analyze --postmortem path with --format
markdown and comparing the result to a snapshot so the public Markdown contract
stays stable.

In `@tests/unit/insights/test_postmortem.py`:
- Around line 275-304: The postmortem JSON contract test is checking the raw
Pydantic dump instead of the CLI’s actual JSON serialization path, so it can
miss fields dropped by exclude_none. Update
test_postmortem_bundle_json_envelope_has_stable_headline_keys to exercise the
same public serialization used by analyze --postmortem --format json (the
model_json_document path in the CLI) and assert the emitted JSON preserves
explicit null degraded-field values; keep the existing headline-key and
token-lane checks against that serialized payload.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: deec8fd8-ef3a-476e-9059-d6e6e8e078ab

📥 Commits

Reviewing files that changed from the base of the PR and between 52532aa and 6bb5c3f.

📒 Files selected for processing (9)
  • docs/cli-reference.md
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/api/archive.py
  • polylogue/cli/query_verbs.py
  • polylogue/insights/postmortem.py
  • tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
  • tests/unit/cli/test_plain_cli_snapshots.py
  • tests/unit/insights/test_postmortem.py

Comment thread polylogue/api/archive.py Resolved
Comment thread polylogue/cli/query_verbs.py Resolved
Comment thread polylogue/insights/postmortem.py Resolved
Comment thread polylogue/insights/postmortem.py Resolved
Comment thread tests/unit/insights/test_postmortem.py Resolved
…bounded log

CodeRabbit (PR #2431), six findings:
- Render evidence_refs in the plain and Markdown artifacts (new Evidence
  section in both) so the shared bundle is actually drillable, not just the
  JSON — restores the AC1 "every headline number drills to a ref" contract.
- Accept `--format plaintext` (advertised by the CLI; was rejected by the
  postmortem mode guard) and route it through the plain renderer.
- Give wallclock_span a fallback session evidence ref when no boundary
  timestamp is present, so a non-zero summed_wall_duration_ms stays drillable.
- Bound the truncation log to a 5-id preview instead of dumping the full
  dropped-session tail (avoids leaking/ballooning session ids in logs).
- Assert the JSON degradation contract on the shipped serialization path
  (model_json_document(exclude_none=True)), not raw model_dump — the prior
  test could not catch the shipped JSON dropping degraded-field markers.
- Add a Markdown CLI snapshot so the third public renderer is pinned.

Verification:
- devtools test tests/unit/insights/test_postmortem.py -> 3 passed
- devtools test test_plain_cli_snapshots.py -k postmortem -> 4 passed
  (plain/json/markdown/headline-keys; plain+markdown snapshots now show the
  Evidence section)
- devtools verify --quick -> exit 0

Ref #2380.
@Sinity

Sinity commented Jun 26, 2026

Copy link
Copy Markdown
Owner Author

Addressed all six CodeRabbit findings in 56a4228:

  1. Drillable artifacts (Major): both the plain-text and Markdown renderers now emit an Evidence section mapping each headline field to its EvidenceRefs — the shared bundle is drillable, not just the JSON.
  2. --format plaintext (Major): accepted and routed through the plain renderer (was wrongly rejected).
  3. wallclock_span fallback ref (Major): falls back to a session ref so a non-zero summed_wall_duration_ms stays drillable when boundary timestamps are absent.
  4. Bounded truncation log (Major/Security): logs a 5-id preview instead of the full dropped-session tail.
  5. JSON contract on the shipped path (Major): the unit test now asserts against model_json_document(..., exclude_none=True) (the CLI's actual serializer) and verifies degraded fields keep status+reason with no fabricated value.
  6. Markdown snapshot (Trivial): added so the third renderer is pinned.

Verification: devtools test tests/unit/insights/test_postmortem.py → 3 passed; -k postmortem → 4 passed; devtools verify --quick → exit 0.

github-actions Bot pushed a commit that referenced this pull request Jun 26, 2026
@Sinity
Sinity merged commit b2b12e1 into master Jun 26, 2026
15 checks passed
@Sinity
Sinity deleted the feature/feat/analyze-postmortem-bundle branch June 26, 2026 13:45
@github-actions github-actions Bot mentioned this pull request Jul 5, 2026
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