Skip to content

feat(insights): materialize capture-completeness coverage measure - #3541

Merged
Sinity merged 3 commits into
masterfrom
feature/insights/capture-completeness-coverage
Aug 2, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/insights/capture-completeness-coverage

Conversation

@Sinity

@Sinity Sinity commented Aug 2, 2026

Copy link
Copy Markdown
Owner

Summary

Adds a capture-completeness coverage measure: for each origin/window, correlate SessionStart hook evidence (raw_hook_events, source.db) against archived sessions (sessions, index.db) to answer "how much of what exists did we ingest," not just "how converged is what we ingested." Materializes the result as a versioned, content-addressed CoverageAssessment, wires a health alert for seeded misses, and adds the primitives a result surface needs to cite the number and downgrade an exact-enumeration claim when coverage is incomplete.

Problem

Convergence legibility (the rest of polylogue/insights/) answers how converged the archive is against what it already has. Nothing answered how much of what actually happened got captured at all. A silent capture regression (a hook stops firing, a watched harness goes unwired) had no number to trip an alert on, and no result surface could honestly caveat "this count assumes full capture" because there was no coverage number to check.

Solution

  • New polylogue/insights/capture_coverage.py:
    • CoverageAssessment / EvidenceSourceCoverage: a content-addressed coverage:<hash> ref (same content_ref mechanism MetricDefinition's metric:<hash> already uses) binding origin, interval, evidence-source inventory, method version, generations, and known misses.
    • compute_capture_coverage() correlates SessionStart hook evidence against archived sessions.native_id for claude-code-session/codex-session (the two origins the hook harnesses cover today), clamped by a grace window so in-flight ingest is never counted as a miss.
    • Two evidence sources the design names but has not wired yet (watcher_file_inventory, browser_extension_observation) are always reported status="unknown" with an explicit reason -- never silently folded into a false 100%. An assessment with zero computed sources is itself unknown (coverage_ratio is None, is_frame_complete is False).
    • apply_coverage_to_enumeration(): downgrades an "exact" enumeration claim to "frame_incomplete" when coverage disagrees.
    • coverage_citation() / render_capture_coverage_report(): an embeddable citation payload and a per-origin drillable text report.
  • polylogue/daemon/health.py: new _check_capture_coverage_medium medium-tier health check running the same computation over the trailing 24h and alerting on known misses (wired into _run_medium_checks); its broad except now logs (fixed a devtools verify degrade-loudly finding on the new code).

Two unrelated fixes needed to get past the repo-wide devtools verify --quick pre-push gate, discovered while verifying this branch:

Acceptance criteria disposition (polylogue-3uw)

Per the bead's own scope note ("if full scope is too large for one PR, land the coverage computation + AC1/AC4/AC7 as the primary deliverable, and treat AC2/AC3 as a clearly-scoped follow-up"):

  1. Coverage renders per origin, known-miss list drillable to refs -- satisfied: render_capture_coverage_report() renders per origin, CoverageAssessment.known_missing_native_ids names the exact missing session native ids. Not yet wired to a CLI/MCP surface (no devtools/polylogue command exposes it yet) -- follow-up.
  2. Seeded missed-session scenario trips the health alert -- satisfied: _check_capture_coverage_medium wired into _run_medium_checks; tests/unit/daemon/test_capture_coverage_alert.py proves a seeded miss trips HealthSeverity != OK.
  3. Sample-frame stanzas can cite the coverage number -- partially satisfied: coverage_citation() produces the citable payload, but no existing report/finding stanza has been updated to call it yet -- follow-up.
  4. Coverage artifact is resolvable and binds origin, interval, evidence-source inventory, method, generations -- satisfied: CoverageAssessment.ref/canonical_payload().
  5. A result frame can cite it -- satisfied at the primitive level (coverage_citation()); no concrete result-envelope surface wired yet -- follow-up (same gap as AC3).
  6. Seeded missing signal makes an otherwise enumeration-exact result render frame-incomplete -- satisfied at the mechanism level: apply_coverage_to_enumeration("exact", assessment) flips to "frame_incomplete" given a seeded miss, proven by test_seeded_missing_signal_flips_exact_enumeration_to_frame_incomplete. Not yet wired into an actual query-result envelope type -- follow-up.
  7. Unknown signal-source coverage remains unknown, not 100% -- satisfied: unwired origins and the two undeclared evidence sources always report status="unknown"; zero computed sources yields coverage_ratio is None.
  8. Focused materialization and result-envelope tests prove the production reference path -- satisfied for materialization (bootstrap-initialized source.db/index.db, real raw_hook_events/sessions tables, no mocked computation); no result-envelope integration test exists yet since no envelope wiring was added (follow-up, tied to AC3/AC5).

Honest summary: AC1/AC2/AC4/AC6/AC7/AC8 (the core measurement, its content-addressed identity, its health-alert wiring, and the frame-incompleteness mechanism) are delivered and tested against the production path. AC3/AC5, and the CLI/MCP surface half of AC1, are the scoped follow-up the bead itself anticipates -- wiring the citation primitive into an actual report/finding/result-envelope surface, which needs its own design decision about which surface goes first.

Verification

  • devtools test tests/unit/insights/test_capture_coverage.py tests/unit/daemon/test_capture_coverage_alert.py => 15 passed.
  • mypy --strict on both changed modules: clean.
  • devtools verify --quick => exit_code: 0 (19/19 steps green, including verify degrade-loudly and lab policy classifier-fingerprints).
  • devtools render all --check: clean (topology projection regenerated for the new module).
  • Not run: devtools verify --all / full non-slow suite (a --seed-testmon --skip-slow baseline run was kicked off separately in this worktree to establish testmon state, since it had never been seeded here; that is baseline bookkeeping, not evidence specific to this diff).

Ref polylogue-3uw

@coderabbitai

coderabbitai Bot commented Aug 2, 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: 26 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: 8b18883a-d7d5-494b-8406-16081dc3ce42

📥 Commits

Reviewing files that changed from the base of the PR and between 2a02f46 and bf53fc6.

📒 Files selected for processing (5)
  • docs/plans/topology-target.yaml
  • polylogue/daemon/health.py
  • polylogue/insights/capture_coverage.py
  • tests/unit/daemon/test_capture_coverage_alert.py
  • tests/unit/insights/test_capture_coverage.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.

Sinity and others added 3 commits August 2, 2026 13:33
Problem: convergence legibility answers "how converged is what we
ingested" but nothing answers "how much of what exists did we ingest".
A silent capture regression (a harness stops firing, a hook goes
unwired) previously had no number to trip an alert on.

What changed: new polylogue/insights/capture_coverage.py correlates
SessionStart hook evidence (raw_hook_events, source.db) against archived
sessions (index.db) per origin/window, materializing a content-addressed
CoverageAssessment (coverage:<hash>, same content_ref mechanism as
MetricDefinition's metric:<hash>). Known misses are drillable to native_id
refs. Sources this module has not wired evidence for yet
(watcher_file_inventory, browser_extension_observation) are always
reported status="unknown" with an explicit reason, never folded into a
false 100%; an assessment with zero computed sources is itself unknown
(coverage_ratio is None, is_frame_complete is False).

Wired a new capture_coverage medium-tier daemon health check
(polylogue/daemon/health.py) that runs the same computation over the
trailing 24h for claude-code-session/codex-session and alerts when known
misses exceed threshold. Added apply_coverage_to_enumeration() so a
result surface can downgrade an "exact" enumeration claim to
"frame_incomplete" when coverage evidence disagrees, and
coverage_citation()/render_capture_coverage_report() for sample-frame
stanzas and per-origin drill-down rendering to build on.

Ref polylogue-3uw

Verification: devtools test tests/unit/insights/test_capture_coverage.py
tests/unit/daemon/test_capture_coverage_alert.py => 15 passed. mypy
--strict clean on both changed modules. devtools render all --check
clean (topology projection regenerated for the new module).

Co-Authored-By: Claude <[email protected]>
The new polylogue/insights/capture_coverage.py module requires a
regenerated topology projection per CLAUDE.md's generated-surface rule.

Ref polylogue-3uw

Co-Authored-By: Claude <[email protected]>
devtools verify degrade-loudly flagged the new check's broad except
Exception as an undeclared silent soft-fail (no log call, no re-raise).
Add a logger.warning(exc_info=True) call matching the existing
cursor_lag_anomaly pattern in the same module.

Ref polylogue-3uw

Co-Authored-By: Claude <[email protected]>
@Sinity
Sinity force-pushed the feature/insights/capture-completeness-coverage branch from 21f43a0 to bf53fc6 Compare August 2, 2026 11:35
@Sinity
Sinity merged commit 59ce364 into master Aug 2, 2026
3 checks passed
@Sinity
Sinity deleted the feature/insights/capture-completeness-coverage branch August 2, 2026 11:39
Sinity added a commit that referenced this pull request Aug 2, 2026
…3554)

## Summary

Fixes two of the four observability defects audited in polylogue-7eo7
(alert-count/verdict contradiction, silent heartbeat staleness) plus the
schema-blocked health-loop gap, and scopes the fourth (dead cursor-lag
SLO check) as a documented follow-up rather than a silent no-op.

## Problem

An audit of the daemon health/status pipeline (polylogue-7eo7) found:

1. `polylogued status` printed `"Health: ok (6 alerts)"` while
`hook_flow [error]` fires in the journal -- because `alert_count`
counted every FAST-tier check run (including OK ones), not actual
problems. A fully healthy daemon always shows exactly `len(fast checks)`
"alerts", making "ok (N alerts)" read as a contradiction regardless of
N.
2. `"Status: running (heartbeat 1369.8s ago)"` on a 15-minute (900s)
interval produced no staleness signal at all -- the only existing
threshold was the 2x-interval (1800s) "vanished" floor, so anything
short of that read as flat "running".
3. `ops.db.cursor_lag_samples` has 0 rows ever: the SLO check reads a
table whose only producer runs inside a MEDIUM-tier check, and
`health_check_tiers` defaults to `"fast"` -- so the producer never
executes under default daemon operation.
4. When the watcher is schema-blocked, `_periodic_health_check()` only
started inside the `if not watcher_blocked:` branch in
`run_daemon_services`, so the daemon ran with zero periodic health
checks/notifications for the entire blocked duration -- exactly when an
operator most needs to see "archive tier layout is not ready".

## Solution

- **#1**: `alert_count` in `daemon_status_payload()`'s `"health"` dict
now counts only non-OK alerts; a new `checks_run` field carries the
previous "every check" total for anyone who still wants it
(`polylogue/daemon/status.py`).
- **#2**: New FAST-tier `heartbeat_staleness` check plus
`DAEMON_HEARTBEAT_STALE_WARN_SECONDS` (1.5x
`DAEMON_HEARTBEAT_INTERVAL_SECONDS`, derived, not hardcoded) fills the
gap between "fresh" and the pre-existing 2x "vanished" floor with a
WARNING-severity `"stale"` lifecycle state
(`polylogue/daemon/lifecycle.py`, `polylogue/daemon/health.py`).
`format_daemon_status_lines` renders a `[STALE]` marker on the
plain-text status line so the signal is visible without reading alerts
separately.
- **#4**: `_periodic_health_check()` moved into the unconditional
`maintenance_tasks` list in `run_daemon_services`
(`polylogue/daemon/cli.py`), so it now starts regardless of
`watcher_blocked`. All FAST-tier checks are read-only (schema_version
via `mode=ro` connections, disk/WAL space stats, hook flow, source
availability, heartbeat staleness), so this does not reintroduce the
archive-write concern the schema-block guard exists for.
- **#3 (deferred, findings recorded)**: `record_cursor_lag_sample` is
only ever called from `_check_cursor_lag_anomaly_layer`, invoked by
`_check_cursor_lag_medium` (MEDIUM tier). `health_check_tiers` defaults
to `"fast"` (`polylogue/config.py`), and `docs/daemon.md` already
documents MEDIUM/EXPENSIVE as deliberate "explicit operator diagnostics"
-- not accidentally disabled. So the check is not dead code in the sense
of being unreachable, but its only producer never runs under default
daemon operation, making the table permanently empty in practice. Two
real options for a follow-up: (a) decouple sample recording from the
MEDIUM gate since it's a cheap read+write, not an expensive scan, or (b)
make the gap explicit in status output (e.g. surface "0 samples,
producer not scheduled" rather than silence). Left to a follow-up bead
since either choice is a behavior decision, not a pure bug fix, and out
of the "prioritize #1/#2" scope this bead itself calls for.

## Verification

```
devtools test tests/unit/daemon/test_health_check_paths.py tests/unit/daemon/test_health_contract.py \
  tests/unit/daemon/test_daemon_lifecycle.py tests/unit/daemon/test_daemon_status.py tests/unit/daemon/test_daemon_cli.py
# 241 passed
```

New tests added: `test_health_alert_count_excludes_ok_severity_checks`
and `test_health_alert_count_reflects_a_real_problem_not_ok` (proves a
nonzero-alert scenario no longer reports "ok" and an all-OK scenario
reports `(0 alerts)` instead of `(6 alerts)`),
`test_heartbeat_staleness_warning_between_warn_and_vanished_floors` and
`test_lifecycle_status_reports_stale_between_warn_and_vanished_floors`
(proves the exact observed 1369.8s/900s scenario now produces a WARNING
alert and a `"stale"` lifecycle state),
`test_cli_status_marks_a_stale_but_still_running_heartbeat` (proves the
`[STALE]` marker renders), and
`test_run_daemon_services_schema_block_skips_write_but_starts_health_check`
(renamed/rewritten from the old `..._skips_db_background_work` test,
which previously asserted the opposite -- that health checks must NOT
start when blocked).

Also fixed an unrelated pre-existing drift in the same
pinned-check-inventory test: `capture_coverage` (added in #3541) was
missing from `EXPECTED_MEDIUM_CHECKS`, causing
`test_medium_tier_inventory_pinned` to fail independent of this change.

`devtools verify --quick` passes (ruff format/check, mypy --strict,
render all --check, layering, degrade-loudly, closure-matrix, and the
rest of the static gate set) -- also ran automatically via the pre-push
hook.

A broader `devtools test tests/unit/daemon/` run (2010 tests) shows 2009
passing; the one remaining failure
(`test_no_token_in_log_or_print_calls` in
`test_daemon_http_security.py`, about `polylogue/daemon/api_auth.py`) is
unrelated and pre-existing -- this PR does not touch that file.

Not run: full `devtools verify` (seed-testmon, non-slow suite) --
started once, killed per operator instruction to avoid cross-turn
backgrounding; the focused command above covers every file this PR
touches.

Ref polylogue-7eo7

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