Repository navigation
feat(analyze): add --postmortem distilled session bundle (#2380) - #2431
Conversation
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
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (6)
📝 WalkthroughWalkthroughAdds a postmortem bundle model and compiler, wires a new ChangesPostmortem bundle feature
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
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]>
There was a problem hiding this comment.
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
📒 Files selected for processing (9)
docs/cli-reference.mddocs/plans/topology-target.yamldocs/topology-status.mdpolylogue/api/archive.pypolylogue/cli/query_verbs.pypolylogue/insights/postmortem.pytests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambrtests/unit/cli/test_plain_cli_snapshots.pytests/unit/insights/test_postmortem.py
…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.
|
Addressed all six CodeRabbit findings in 56a4228:
Verification: |
Summary
Adds
polylogue analyze --postmortem(aka "blame") — one compact, shareableartifact over a matched session scope, available as plain text, Markdown, and
JSON, all rendered from a single typed
PostmortemBundle. Every real headlinemetric 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, theblamepreset,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_msalready 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 typedPostmortemBundlemodel 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): resolvesthe matched session set via the same summary path
facetsuses, batch-fetchesprofiles, 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/query_verbs.py):--postmortemas a mutually-exclusive analyzemode; plain (default),
--format json(via the standardsuccess(...)envelope), and
--format markdown.Real vs degraded headline fields (honest accounting)
Real, each carrying
EvidenceRefs:session_count,wallclock_span(earliestfirst_message_at→ latestlast_message_at, plus summed realwall_duration_ms),estimated_costwith 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 fromrun_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 pathologydetector is not built yet (AC5 explicitly permits absent-or-degraded here).
longest_tool_gap→status: "unavailable"— neither the session profile northe recovery digest carries per-tool-call timestamps in v0. Using
latency_percentiles_ms(inter-message latency) would have mislabeled it, soit 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-populatedmulti-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.
test_{plain,json}_analyze_postmortem_snapshot) pin therendered artifact against a deterministic, private-data-free corpus archive
with insights materialized —
analyzed_session_count=4, populatedwallclock_span. This is the AC3 stable snapshot-able artifact.formats.
Known limitation / follow-up
polylogue demo seedalone does not materialize session-profile insights, sodemo seed→analyze --postmortemreportsanalyzed=0and 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 --postmortemreturns every named field; each real headline metriccarries ≥1 drillable
EvidenceRef.artifact (CLI snapshot test).
is real per-session duration.
failure_mode/wasted_loop(andlongest_tool_gap) are absent-or-degradedwith explicit status, never fabricated.
Ref #2380. Ref #1807.
Summary by CodeRabbit
analyze --postmortemoption to view a distilled session postmortem in plain text, Markdown, or JSON.