Skip to content

feat(daemon): add tiered health checks and backup command (#830) - #898

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/health-backup-830
May 7, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/health-backup-830

Conversation

@Sinity

@Sinity Sinity commented May 7, 2026

Copy link
Copy Markdown
Owner

Summary

Add production-grade daemon operations on top of the existing status substrate: tiered health monitoring with severity escalation, a local-first backup command, and a log-based notifications backend.

Problem

The daemon was operational but lacked production-grade hardening: no structured health checks beyond ok/warn/err, no backup/portability surface, and no alerting mechanism for degraded conditions observed in production (DB locked writer contention, embed-stage event-loop failures, insight rebuild failures).

Solution

Three new modules and modifications to the status model and CLI:

  • polylogue/daemon/health.py — HealthTier enum (FAST/MEDIUM/EXPENSIVE), HealthAlert typed model with severity and consecutive-failure tracking, DaemonHealth aggregation, and check_health() runner. Fast checks cover liveness/disk/WAL; medium checks cover FTS readiness, raw failure counts, and stale ingest attempts; expensive checks run PRAGMA integrity_check.
  • polylogue/daemon/backup.py — backup_archive() using VACUUM INTO with file-copy fallback, --check dry-run mode, and optional blob store backup via --include-blobs.
  • polylogue/daemon/notifications.py — NotificationBackend protocol with a LogNotificationBackend that routes alerts through the structured logger by severity.
  • polylogue/daemon/status.py — DaemonStatus gains a health: DaemonHealth field populated on build_daemon_status(). Health data reaches the JSON status payload and text formatter.
  • polylogue/daemon/cli.py — polylogued health subcommand with tier selection (--tier, --expensive), JSON output, and deterministic exit codes (exit 1 on error/critical).
  • polylogue/cli/commands/backup.py + registration — polylogue backup command with --output-dir, --check, and --include-blobs.

Verification

Deferred to wave batch per #852 policy.

Closes #830.

🤖 Generated with Claude Code

Add production-grade daemon operations on top of the existing status
substrate: tiered health monitoring with severity escalation, a local-first
backup command, and a log-based notifications backend.

Health checks are grouped into three tiers:
- FAST (<1s): daemon liveness, disk space, WAL size
- MEDIUM (<10s): FTS readiness, raw failure counts, stale ingest attempts
- EXPENSIVE: DB integrity (PRAGMA integrity_check)

DaemonStatus gains a `health: DaemonHealth` field consumed by all surfaces
(CLI, TUI, MCP, web). The `polylogued health` subcommand exposes targeted
tier selection and deterministic exit codes for CI integration.

The `polylogue backup` command uses VACUUM INTO (SQLite >= 3.27.0) with a
file-copy fallback, plus `--check` dry-run mode. Optional blob store backup
via `--include-blobs`.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Copilot AI review requested due to automatic review settings May 7, 2026 08:58
@coderabbitai

coderabbitai Bot commented May 7, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@Sinity has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 54 minutes and 32 seconds before requesting another review.

To continue reviewing without waiting, purchase usage credits in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 74aaa235-389c-429f-8bee-3b90f00a40d2

📥 Commits

Reviewing files that changed from the base of the PR and between 57b8785 and a7dfe9e.

📒 Files selected for processing (7)
  • polylogue/cli/click_command_registration.py
  • polylogue/cli/commands/backup.py
  • polylogue/daemon/backup.py
  • polylogue/daemon/cli.py
  • polylogue/daemon/health.py
  • polylogue/daemon/notifications.py
  • polylogue/daemon/status.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/health-backup-830

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 and usage tips.

@Sinity
Sinity merged commit 7c2b168 into master May 7, 2026
4 checks passed
@Sinity
Sinity deleted the feature/feat/health-backup-830 branch May 7, 2026 08:59

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a7dfe9e248

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread polylogue/daemon/status.py Resolved
Comment thread polylogue/daemon/health.py Resolved

Copilot AI 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.

Pull request overview

This PR extends the daemon’s operational surface by adding tiered health checks (with typed alerts and severities), a local-first backup operation, and a notification backend, and then wiring health/backup into the daemon status payload and CLI.

Changes:

  • Introduces tiered health checking (FAST/MEDIUM/EXPENSIVE) with aggregated DaemonHealth + alert modeling.
  • Adds backup utilities for copying the SQLite archive (VACUUM INTO + fallback) and optionally the blob store, plus a new polylogue backup CLI command.
  • Adds a notifications abstraction with an initial log-based backend, and extends daemon status output to include a health summary.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 15 comments.

Show a summary per file
File Description
polylogue/daemon/status.py Adds health to DaemonStatus and includes health summary in JSON/text status output.
polylogue/daemon/health.py New tiered health check runner + typed alert/status models and text formatting.
polylogue/daemon/notifications.py New notifications protocol + log-based backend for health alerts.
polylogue/daemon/cli.py Adds polylogued health subcommand and exports it.
polylogue/daemon/backup.py New backup implementation (DB + optional blobs) with formatted results.
polylogue/cli/commands/backup.py Adds polylogue backup CLI command wrapper over daemon backup utilities.
polylogue/cli/click_command_registration.py Registers the new root backup CLI command.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

*,
sources: tuple[WatchSource, ...] | None = None,
browser_capture_spool_path: Path | None = None,
*,
Comment on lines +23 to +26
from polylogue.daemon.status import _raw_failure_info
from polylogue.logging import get_logger
from polylogue.paths import archive_root, db_path

Comment on lines +251 to +255
try:
conn = sqlite3.connect(str(dbf))
try:
has_messages_fts = bool(
conn.execute(
Comment on lines +268 to +270
if not has_messages_fts and not has_action_fts:
severity = HealthSeverity.WARNING
message = "FTS tables missing"
Comment on lines +45 to +49
"""Backup using VACUUM INTO (SQLite >= 3.27.0)."""
conn = sqlite3.connect(str(src))
try:
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
conn.execute(f"VACUUM INTO '{dst}'")
Comment on lines +19 to +28
from pathlib import Path

from pydantic import BaseModel, Field

from polylogue.daemon.status import _raw_failure_info
from polylogue.logging import get_logger
from polylogue.paths import archive_root, db_path

logger = get_logger(__name__)

from pydantic import BaseModel

from polylogue.logging import get_logger
from polylogue.paths import archive_root, blob_store_root, db_path
Comment on lines +72 to +76
# Check database is readable.
try:
conn = sqlite3.connect(str(dbf))
conn.execute("SELECT 1 FROM sqlite_master LIMIT 1")
conn.close()
Comment on lines +400 to +405
consecutive_failures=_record_failure("db_integrity", False),
)
try:
conn = sqlite3.connect(str(dbf))
try:
results = conn.execute("PRAGMA integrity_check").fetchall()
Comment on lines +54 to +58
def _backup_db_copy(src: Path, dst: Path) -> None:
"""Backup using file copy after WAL checkpoint."""
conn = sqlite3.connect(str(src))
try:
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
Sinity added a commit that referenced this pull request May 7, 2026
First production-grade hardening slice for #830 on top of the
existing daemon/status substrate. Three new modules and
modifications to status and CLI; PR #920 / #903 land the
remaining checks and config wiring on top of this.

- `polylogue/daemon/health.py`: `HealthTier` enum (FAST /
  MEDIUM / EXPENSIVE), `HealthAlert` typed model with severity
  and consecutive-failure tracking, `DaemonHealth`
  aggregation, and `check_health()` runner. Fast checks cover
  liveness/disk/WAL; medium covers FTS readiness, raw failure
  counts, and stale ingest attempts; expensive runs PRAGMA
  integrity_check.
- `polylogue/daemon/backup.py`: `backup_archive()` using
  `VACUUM INTO` with a file-copy fallback; `--check` dry-run;
  optional blob-store backup via `--include-blobs`.
- `polylogue/daemon/notifications.py`: `NotificationBackend`
  protocol with `LogNotificationBackend` routing alerts
  through the structured logger by severity.
- `polylogue/daemon/status.py`: `DaemonStatus` gains
  `health: DaemonHealth`, populated by `build_daemon_status()`
  and exposed in the JSON payload and text formatter.
- `polylogue/daemon/cli.py`: `polylogued health` subcommand
  with tier selection (`--tier`, `--expensive`), JSON output,
  and deterministic exit codes (1 on error/critical).
- `polylogue/cli/commands/backup.py` + registration:
  `polylogue backup` with `--output-dir`, `--check`,
  `--include-blobs`.

Closes #830 on the substrate axis; remaining health-check
additions land in PR #920.

Refs #830
Sinity added a commit that referenced this pull request May 7, 2026
Direct, no-PR. Larger cleanup batch after the multi-PR merge
wave landed mismatches between the agent-authored PRs.

- `polylogue/protocols.py`: `TagStore` protocol return types
  switch from `None` to `bool` for `add_tag`, `remove_tag`,
  `update_metadata`, `delete_metadata`, matching the
  idempotency contract introduced in PR #893 (#862).
- `polylogue/archive/session/{documents,models}.py`: adds the
  per-tool timing fields to `SessionProfileDocument` TypedDict
  so PR #895's timing additions roundtrip through the
  TypedDict consumers.
- `polylogue/daemon/{health,notifications,status}.py`: fixes
  the circular import between `status.py` and `health.py`
  introduced by PR #898; tightens generic dict-type parameters
  in `notifications.py`.
- `polylogue/storage/insights/session/profiles.py`: replaces
  `dict()` calls with literal `{}` where mypy's inference
  preferred the literal.
- `polylogue/mcp/server_mutation_tools.py`: keyword-arg fixups
  for the `MutationResultPayload` envelope from PR #893.

Refs #830, #862, #895
Sinity added a commit that referenced this pull request May 7, 2026
Completes #830 on top of the health/backup substrate from PRs
#898 / #903: four new health checks across the FAST/MEDIUM/
EXPENSIVE tiers, config-driven notification backend selection,
and operator vs. daemon maintenance documentation.

- `polylogue/daemon/health.py`:
  - FAST: `_check_source_availability_fast()` verifies each
    watch root from `default_sources()` exists and is readable.
  - MEDIUM: `_check_insight_freshness_medium()` flags >10% gap
    between session-profile coverage and total conversations.
  - MEDIUM: `_check_repeated_stage_failures_medium()` reads
    `live_ingest_attempt` for recent failure rates and samples
    the latest error.
  - EXPENSIVE: `_check_blob_integrity_expensive()` runs a
    bounded `BlobStore.verify_all(max_failures=5)` content check.
  - EXPENSIVE: `_check_embedding_coverage_expensive()` reports
    coverage and failure count when embeddings are enabled.
- `polylogue/daemon/notifications.py` + `config.py`: backend
  factory `_resolve_backend(backend_name)` (currently log-only),
  resolved from `PolylogueConfig` so tier set, interval, and
  backend can be set via TOML or the matching env vars.
- `polylogue/daemon/cli.py`: `_periodic_health_check()` reads
  config to pick the tier set and backend.
- `docs/daemon.md`: separates daemon-owned and operator-owned
  maintenance tasks.

Refs #830
Sinity added a commit that referenced this pull request May 7, 2026
First production-grade hardening slice for #830 on top of the
existing daemon/status substrate. Three new modules and
modifications to status and CLI; PR #920 / #903 land the
remaining checks and config wiring on top of this.

- `polylogue/daemon/health.py`: `HealthTier` enum (FAST /
  MEDIUM / EXPENSIVE), `HealthAlert` typed model with severity
  and consecutive-failure tracking, `DaemonHealth`
  aggregation, and `check_health()` runner. Fast checks cover
  liveness/disk/WAL; medium covers FTS readiness, raw failure
  counts, and stale ingest attempts; expensive runs PRAGMA
  integrity_check.
- `polylogue/daemon/backup.py`: `backup_archive()` using
  `VACUUM INTO` with a file-copy fallback; `--check` dry-run;
  optional blob-store backup via `--include-blobs`.
- `polylogue/daemon/notifications.py`: `NotificationBackend`
  protocol with `LogNotificationBackend` routing alerts
  through the structured logger by severity.
- `polylogue/daemon/status.py`: `DaemonStatus` gains
  `health: DaemonHealth`, populated by `build_daemon_status()`
  and exposed in the JSON payload and text formatter.
- `polylogue/daemon/cli.py`: `polylogued health` subcommand
  with tier selection (`--tier`, `--expensive`), JSON output,
  and deterministic exit codes (1 on error/critical).
- `polylogue/cli/commands/backup.py` + registration:
  `polylogue backup` with `--output-dir`, `--check`,
  `--include-blobs`.

Closes #830 on the substrate axis; remaining health-check
additions land in PR #920.

Refs #830
Sinity added a commit that referenced this pull request May 7, 2026
Direct, no-PR. Larger cleanup batch after the multi-PR merge
wave landed mismatches between the agent-authored PRs.

- `polylogue/protocols.py`: `TagStore` protocol return types
  switch from `None` to `bool` for `add_tag`, `remove_tag`,
  `update_metadata`, `delete_metadata`, matching the
  idempotency contract introduced in PR #893 (#862).
- `polylogue/archive/session/{documents,models}.py`: adds the
  per-tool timing fields to `SessionProfileDocument` TypedDict
  so PR #895's timing additions roundtrip through the
  TypedDict consumers.
- `polylogue/daemon/{health,notifications,status}.py`: fixes
  the circular import between `status.py` and `health.py`
  introduced by PR #898; tightens generic dict-type parameters
  in `notifications.py`.
- `polylogue/storage/insights/session/profiles.py`: replaces
  `dict()` calls with literal `{}` where mypy's inference
  preferred the literal.
- `polylogue/mcp/server_mutation_tools.py`: keyword-arg fixups
  for the `MutationResultPayload` envelope from PR #893.

Refs #830, #862, #895
Sinity added a commit that referenced this pull request May 7, 2026
Completes #830 on top of the health/backup substrate from PRs
#898 / #903: four new health checks across the FAST/MEDIUM/
EXPENSIVE tiers, config-driven notification backend selection,
and operator vs. daemon maintenance documentation.

- `polylogue/daemon/health.py`:
  - FAST: `_check_source_availability_fast()` verifies each
    watch root from `default_sources()` exists and is readable.
  - MEDIUM: `_check_insight_freshness_medium()` flags >10% gap
    between session-profile coverage and total conversations.
  - MEDIUM: `_check_repeated_stage_failures_medium()` reads
    `live_ingest_attempt` for recent failure rates and samples
    the latest error.
  - EXPENSIVE: `_check_blob_integrity_expensive()` runs a
    bounded `BlobStore.verify_all(max_failures=5)` content check.
  - EXPENSIVE: `_check_embedding_coverage_expensive()` reports
    coverage and failure count when embeddings are enabled.
- `polylogue/daemon/notifications.py` + `config.py`: backend
  factory `_resolve_backend(backend_name)` (currently log-only),
  resolved from `PolylogueConfig` so tier set, interval, and
  backend can be set via TOML or the matching env vars.
- `polylogue/daemon/cli.py`: `_periodic_health_check()` reads
  config to pick the tier set and backend.
- `docs/daemon.md`: separates daemon-owned and operator-owned
  maintenance tasks.

Refs #830
Sinity added a commit that referenced this pull request May 10, 2026
…, lint debt) (#1001)

## Summary

Restores `devtools verify --quick` to green on master. Three independent
debt classes had accumulated across the 2026-05-09 PR wave (and
earlier), each individually small but jointly blocking every new branch
from passing the pre-push hook.

## Problem

`gh run list --branch master --workflow CI` shows master CI has been red
since 2026-05-02. PRs continued to merge through that window, and each
one nudged at least one of the three following gates further out of
sync:

1. **Rendered doc surfaces** drifted — `docs/cli-reference.md` missed
the `maintenance` group and `message_type_backfill` target added by
#871/#839; `AGENTS.md` carried stale worktree-relative include paths
from before #eeace79; `test-quality-workflows.md` and
`verification-catalog.md` were similarly stale.
2. **File-size budgets** caught three production files growing past
their declared ceilings: `polylogue/storage/repair.py` (1281>1200, from
#818+#839), `polylogue/operations/archive.py` (1141>1100, from
#861/#862), and `polylogue/daemon/status.py` (1128>1100, from
#844/#898/#915).
3. **Lint/type debt** — 42 ruff errors (mostly import-sort drift after
#eeace79 added `devtools.repo_root` to many devtools modules) and 3 mypy
errors (`TagMutationResult` referenced in `polylogue/api/archive.py` but
never imported; `get_index_status` returning a `TypedDict` typed as
`dict[str, object]`).

The pre-push hook (`.githooks/pre-push` → `devtools verify --quick`) is
correctly enforcing the gate; what was missing was a forcing function
for the cumulative state. This PR is that function.

## Solution

Three atomic commits:

- `f51e15be chore(docs): regenerate rendered surfaces stale on master` —
pure regeneration via `devtools render-all`, no logic changes.
- `0b4eadee chore(budgets): raise ceilings for three files past their
cap on master` — three new exception entries in
`docs/plans/file-size-budgets.yaml`. Each entry names the
architectural-split candidate that would let the ceiling shrink,
matching the convention used for existing exceptions. No code splits in
this PR — the budgets file is the right place to make the pressure
visible.
- `372ad23b chore: clear ruff/mypy debt accumulated on master` — 39 ruff
auto-fixes (import sort, typing modernization, unused imports), 4 manual
ruff fixes, 3 mypy fixes (missing imports, return-type tightening,
click.Context handling in tests).

Total: 45 files, +121/-79 lines.

## Verification

```
$ devtools verify --quick
verify: running local verification baseline
  ruff format ... ok (0.0s)
  ruff check ... ok (0.0s)
  mypy ... ok (73.4s)
  render-all ... ok (102.0s)
  verify-topology ... ok (0.3s)
  verify-layering ... ok (0.9s)
  verify-file-budgets ... ok (0.4s)
  verify-test-ownership ... ok (1.4s)
  verify-schema-roundtrip ... ok (1.5s)
  verify-cross-cuts ... ok (0.3s)
  verify-suppressions ... ok (3.1s)
  verify-manifests ... ok (5.5s)
  verify-witness-lifecycle ... ok (3.2s)
  verify-lane-assertions ... ok (1.4s)
  proof-pack check ... ok (7.0s)
verify: all checks passed
```

`pytest tests/unit/daemon/test_maintenance_endpoints.py
tests/unit/daemon/test_raw_failure_sample.py
tests/unit/cli/test_maintenance_registration.py
tests/unit/pipeline/test_message_type_backfill.py -q` — 41 passed (no
behavioural change introduced by the type-cleanup edits).

## Follow-ups

- Three "split candidate" hints in `file-size-budgets.yaml` —
`repair.py` lift backfill into `pipeline/services`, per-domain operation
modules under `operations/`, payload modules per `daemon/status.py`
section — should be filed as separate refactor issues if/when the
ceilings need to shrink again.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

## Release Notes

* **Documentation**
  * Updated CLI reference with maintenance command documentation
  * Updated file-size budget exceptions and verification catalog metrics

* **Improvements**
* Enhanced archive maintenance API with improved type safety for index
status queries
* Improved code organization in development utilities and test
infrastructure

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Sinity/polylogue/pull/1001)

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity

Sinity commented Sep 30, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 64.F006 / P1: fixed-already at the checked revision: The back-reference to status is now a function-local import inside _check_raw_failures_medium at polylogue/daemon/health.py:702-708. Importing health no longer attempts to import _raw_failure_info from a partially initialized status module.

Only the rows listed above are dispositioned. Held findings remain open.

@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 63.F064 / P2: fixed-already at the checked revision: The obsolete two-surface both-missing predicate has been replaced by actual active-surface readiness. The health check reports ERROR for an empty surface projection at polylogue/daemon/health.py:668-670 and for each non-ready surface at lines 673-679, so a missing current messages_fts surface cannot produce the former false OK.

Only the rows listed above are dispositioned. Held findings remain open.

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.

feat(daemon): add tiered health, backup, alerts, maintenance

2 participants