Skip to content

feat(daemon): ingest/status CLI, convergence model, systemd service - #831

Merged
Sinity merged 3 commits into
masterfrom
feature/feat/daemon-overhaul-717
May 4, 2026
Merged

Sinity merged 3 commits into
masterfrom
feature/feat/daemon-overhaul-717

Conversation

@Sinity

@Sinity Sinity commented May 4, 2026 •

Copy link
Copy Markdown
Owner

Summary

First tranche of the #717 daemon overhaul — adds polylogue ingest and polylogue status CLI commands, a daemon API endpoint for ad-hoc ingestion, a stage-based state convergence framework, and a systemd service unit.

Problem

The daemon currently wraps the old batch pipeline (ingest_sources() with acquire→validate→parse→transform→write) in an inotify watcher. There's no ad-hoc ingestion path, no CLI status command, and no convergence model — the daemon just runs the full pipeline for every changed file.

Solution

CLI surface:

  • polylogue ingest <path> — contacts daemon via POST /api/ingest, copies file into archive inbox. Thin RPC trigger, no pipeline logic.
  • polylogue status — queries daemon health via GET /api/status. Falls back to direct DB query when daemon isn't running.
  • polylogue run removed from interactive CLI registration (pipeline module stays for daemon internal use)

Daemon API:

  • POST /api/ingest — accepts {"path": "..."}, copies into archive inbox, daemon watcher picks it up
  • POST /api/reset already exists; POST /api/ingest is new

Convergence model:

  • DaemonConverger — stage-based state convergence. Each source file progresses through independent stages. CPU-bound stages dispatched to ProcessPoolExecutor, main process is the sole SQLite writer.
  • _periodic_convergence_check — safety-net task (10-min interval) detecting and repairing FTS gaps

Systemd:

  • systemd/polylogued.service — user service unit with security hardening (NoNewPrivileges, PrivateTmp, ProtectSystem=strict, read-only home with explicit write paths for ~/.local/share/polylogue, ~/.config/claude, ~/.codex)

Verification

  • ruff check → ok
  • mypy → ok
  • verify-topology, verify-layering, verify-file-budgets, verify-test-ownership, verify-schema-roundtrip, verify-cross-cuts, verify-suppressions, verify-manifests, verify-witness-lifecycle, proof-pack → all ok

Ref #717

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added polylogue ingest command to ingest files and directories into the archive
    • Added polylogue status command to display daemon health status, component states, and archive statistics
    • Daemon now includes automatic index maintenance and periodic convergence checks
    • Added systemd service unit to manage the daemon as a background service

Sinity and others added 3 commits May 4, 2026 13:50
First tranche of the #717 daemon overhaul:

- POST /api/ingest — copies requested path into archive inbox, daemon
  watcher picks it up. Returns operation ID for tracking.
- polylogue ingest <path> — thin CLI that contacts the daemon API.
  Reports "Scheduled" and directs user to check status.
- polylogue status — queries daemon health via GET /api/status.
  Falls back to direct DB query when daemon is not running.
- Remove polylogue run from interactive CLI command registration
  (pipeline module still exists for daemon internal use).

Ref #717

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…unit

Core architectural pieces for the #717 daemon overhaul:

- DaemonConverger: stage-based state convergence framework. Each source
  file progresses through acquire → parse → materialize → index →
  insights stages independently. CPU-bound stages dispatched to
  ProcessPoolExecutor, main process is the sole SQLite writer.
- _periodic_convergence_check: safety-net task running every 10 minutes
  to detect and repair FTS gaps (crash recovery, rare edge cases).
- systemd/polylogued.service: user systemd service unit with security
  hardening (NoNewPrivileges, PrivateTmp, ProtectSystem=strict,
  read-only home with explicit write paths).

Ref #717

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Start the convergence engine on daemon startup, stop it on shutdown.
The converger currently runs with an empty stage set (periodic FTS
convergence is handled by _periodic_convergence_check). Stage
implementations will be filled in incrementally as pipeline stages
are refactored into independent check+execute pairs.

Ref #717

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

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

📝 Walkthrough

Walkthrough

This PR introduces new CLI commands (ingest, status) to interact with a daemon, implements corresponding daemon API endpoints (POST /api/ingest, GET /api/status), adds a convergence framework for managing file processing stages, updates CLI command registration to reflect the new surface, and includes systemd service configuration and documentation updates.

Changes

Ingest & Status Commands + Daemon Convergence Framework

Layer / File(s) Summary
Convergence Foundation
polylogue/daemon/convergence.py, polylogue/daemon/__init__.py
Introduces StageState enum, ConvergenceStage and FileState dataclasses, and DaemonConverger class for tracking multi-stage file processing. DaemonConverger executes stages sequentially per file, skips completed stages, handles errors with retry counts, and dispatches CPU-bound work to a ProcessPoolExecutor. Convergence types are re-exported from daemon package.
Daemon API Handlers
polylogue/daemon/http.py
Adds _handle_ingest() to POST /api/ingest: parses path from JSON request body, validates/resolves path, copies file/directory to daemon inbox, emits ingest event, and returns 202 Accepted with operation_id. Adds GET /api/status handler (via status_command) to return daemon health and component states.
CLI Ingest & Status Commands
polylogue/cli/commands/ingest.py, polylogue/cli/commands/status.py
ingest_command POSTs {"path": "..."} to daemon /api/ingest endpoint, parses response, and displays scheduled operation details or errors. status_command GETs /api/status from daemon; on network failure, falls back to direct SQLite archive inspection (conversation/message counts, FTS coverage).
CLI Wiring
polylogue/cli/click_command_registration.py
Updates ROOT_COMMANDS registry: removes run_command, adds ingest_command and status_command in new order.
Daemon Lifecycle
polylogue/daemon/cli.py
Adds _periodic_convergence_check() coroutine that runs every 10 minutes to detect and rebuild FTS index gaps. Starts DaemonConverger instance at daemon startup and stops it at shutdown. Integrates convergence check into maintenance task loop.
Deployment & Documentation
systemd/polylogued.service, docs/*
Adds systemd service unit for polylogued with hardened security settings, resource limits, and restart policy. Updates CLI reference, test-quality workflows, topology status, and verification catalog to reflect command structure changes and updated metrics.

Sequence Diagram

sequenceDiagram
    participant User as User/CLI
    participant Ingest as ingest_command
    participant API as Daemon HTTP API
    participant Daemon as Daemon Service
    participant Inbox as Inbox Directory

    User->>Ingest: polylogue ingest /path/to/data
    Ingest->>API: POST /api/ingest {"path": "/path/to/data"}
    API->>Inbox: Validate & copy path to inbox
    API->>Daemon: Emit ingest event
    API-->>Ingest: 202 Accepted {operation_id, path}
    Ingest-->>User: Scheduled ingestion (operation_id, path)
Loading
sequenceDiagram
    participant User as User/CLI
    participant Status as status_command
    participant API as Daemon HTTP API
    participant Daemon as Daemon Service
    participant Archive as SQLite Archive

    User->>Status: polylogue status
    Status->>API: GET /api/status
    API->>Daemon: Query daemon state
    alt Daemon Reachable
        Daemon-->>API: {status, pid, uptime, components, version}
        API-->>Status: 200 OK with daemon metrics
        Status-->>User: Display daemon health summary
    else Daemon Unreachable
        Status->>Archive: Open local SQLite DB
        Archive-->>Status: Query counts (conversations, messages, FTS)
        Status-->>User: Display local archive metrics
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related issues

Possibly related PRs

Suggested labels

type:feature, area:cli, area:daemon, area:api

Poem

🐰 Whiskers twitch with ingestion cheer,
New paths copy far and near,
Status blooms with daemon's light,
Convergence hops through day and night,
Archive grows, the inbox fills,
Polylogue climbs the rabbit hills! 🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main changes: adding ingest/status CLI commands, a convergence model, and a systemd service, which are the core deliverables of this daemon overhaul tranche.
Description check ✅ Passed The description covers all required sections: Summary (changes and rationale), Problem (daemon limitations addressed), Solution (CLI, API, convergence, systemd details), Verification (tools run), and Changelog guidance; comprehensive and well-structured.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/daemon-overhaul-717

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
Review rate limit: 0/1 reviews remaining, refill in 60 minutes.

Comment @coderabbitai help to get the list of available commands and usage tips.

@Sinity
Sinity merged commit 5885d28 into master May 4, 2026
3 of 4 checks passed
@Sinity
Sinity deleted the feature/feat/daemon-overhaul-717 branch May 4, 2026 11: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: a62f57d773

ℹ️ 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/http.py Resolved
Comment on lines +52 to +54
overall = status.get("overall", "unknown")
color = {"ok": "green", "warn": "yellow", "err": "red", "idle": "blue"}.get(overall, "white")
env.ui.console.print(f"\n[bold {color}]Status: {overall}[/bold {color}]")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Parse daemon status using existing API fields

_show_daemon_status expects keys like overall, components, and archive_display_path, but /api/status currently serves daemon_status_payload() with fields such as component_state, live, and db_path. As a result, when the daemon is running, polylogue status reports Status: unknown and drops most health details instead of showing real component state.

Useful? React with 👍 / 👎.

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 starts the daemon-surface overhaul by adding polylogue ingest / polylogue status, introducing a new convergence module, wiring an ad-hoc ingest API endpoint, and adding a sample systemd unit. It fits into the codebase as the first step toward moving long-running ingestion and status/reporting behind polylogued.

Changes:

  • Added new interactive CLI surfaces for daemon-triggered ingest and daemon/archive status.
  • Added daemon-side HTTP handling for /api/ingest plus a new convergence module and periodic convergence check wiring.
  • Updated generated docs/catalog artifacts and added a user systemd service unit.

Assessment:

  • Not ready as-is: the new ingest path is not wired to anything the daemon actually watches, the new status CLI expects a different payload shape than /api/status returns, and several generated docs/tests are left inconsistent with the new CLI surface.

Reviewed changes

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

Show a summary per file
File Description
systemd/polylogued.service Adds a user service unit for running polylogued with API enabled and systemd hardening.
polylogue/daemon/http.py Adds POST /api/ingest handling on the daemon HTTP server.
polylogue/daemon/convergence.py Introduces new stage/state data structures for daemon convergence.
polylogue/daemon/cli.py Starts periodic convergence checks and instantiates the new converger in daemon startup/shutdown.
polylogue/daemon/__init__.py Re-exports convergence types from the daemon package.
polylogue/cli/commands/status.py Adds the new polylogue status command with daemon query and DB fallback behavior.
polylogue/cli/commands/ingest.py Adds the new polylogue ingest command that POSTs a path to the daemon.
polylogue/cli/click_command_registration.py Registers status and ingest and removes run from root interactive commands.
docs/verification-catalog.md Updates generated verification catalog command/count snapshots for the CLI surface change.
docs/topology-status.md Updates generated topology file-count snapshot.
docs/test-quality-workflows.md Updates generated workflow/scenario listings for CLI help coverage.
docs/cli-reference.md Updates generated CLI reference command list and command-help sections.

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

Comment on lines 22 to +26
ROOT_COMMANDS: tuple[click.Command, ...] = (
run_command, # timer-driven maintenance: polylogue run index, polylogue run site
check_command,
reset_command,
status_command,
ingest_command,
Comment thread polylogue/daemon/http.py
Comment on lines +525 to +551
# Stage into the archive inbox — the daemon watcher picks it up.
from polylogue.paths import archive_root

inbox = archive_root() / "inbox"
inbox.mkdir(parents=True, exist_ok=True)

import shutil

dest = inbox / source.name
try:
if source.is_dir():
shutil.copytree(source, dest, dirs_exist_ok=True)
else:
shutil.copy2(source, dest)
except OSError as exc:
self._send_json(HTTPStatus.INTERNAL_SERVER_ERROR, {"ok": False, "error": str(exc)})
return

op_id = f"ingest-{source.name}"
emit_daemon_event("ingest", operation_id=op_id, payload={"path": str(source), "inbox": str(dest)})
self._send_json(
HTTPStatus.ACCEPTED,
{
"ok": True,
"operation_id": op_id,
"path": str(source),
"message": "Ingestion scheduled. Check status for progress.",
Comment thread polylogue/daemon/http.py
Comment on lines +533 to +538
dest = inbox / source.name
try:
if source.is_dir():
shutil.copytree(source, dest, dirs_exist_ok=True)
else:
shutil.copy2(source, dest)
Comment on lines +40 to +46
try:
with urlopen(req, timeout=5) as resp:
result = json.loads(resp.read())
except OSError:
# Daemon not running — fall back to direct archive check
_show_direct_status(env)
return
Comment on lines +51 to +77
def _show_daemon_status(env: AppEnv, status: dict[str, Any]) -> None:
overall = status.get("overall", "unknown")
color = {"ok": "green", "warn": "yellow", "err": "red", "idle": "blue"}.get(overall, "white")
env.ui.console.print(f"\n[bold {color}]Status: {overall}[/bold {color}]")

pid = status.get("pid")
uptime = status.get("uptime_s")
if pid:
env.ui.console.print(f" Daemon PID: {pid}")
if uptime is not None:
env.ui.console.print(f" Uptime: {uptime:.0f}s")

components = status.get("components", [])
if components:
env.ui.console.print("\n[bold]Components:[/bold]")
for c in components:
state_color = {
"ok": "green",
"warn": "yellow",
"err": "red",
"stale": "yellow",
"idle": "blue",
"disabled": "dim",
}.get(c.get("state"), "white")
env.ui.console.print(f" [{state_color}]●[/{state_color}] {c['name']}: {c.get('summary', '')}")

env.ui.console.print(f"\n Archive: {status.get('archive_display_path', 'unknown')}")
Comment thread docs/cli-reference.md
Comment on lines 548 to +552
## Run Site

```text
Usage: polylogue run site [OPTIONS]
Usage: polylogue [OPTIONS] COMMAND [ARGS]...

Comment thread docs/cli-reference.md
Comment on lines 149 to +162
@@ -154,11 +155,11 @@ Commands:
raw Show raw archive artifacts for a conversation.
reset Reset database, blob store, assets, rendered outputs, or...
resume Reconstruct work-state context for a fresh agent session.
run Run pipeline stages on configured sources and/or transient...
schema Inspect schema packages, versions, and evidence.
select Select one matched conversation and print a field.
show Show matched conversations with default full-content output.
stats Show statistics for matched conversations.
status Show daemon and archive health.
Comment thread polylogue/daemon/http.py
Comment on lines +513 to +520
ingest_path = body.get("path")
if not ingest_path:
self._send_error(HTTPStatus.BAD_REQUEST, "missing_path")
return

from pathlib import Path as _Path

source = _Path(ingest_path).expanduser().resolve()
Comment thread polylogue/daemon/cli.py
Comment on lines +296 to +301
# Start the convergence engine — it periodically checks and repairs
# FTS gaps, insight freshness, and other archive invariants.
from polylogue.daemon.convergence import DaemonConverger

converger = DaemonConverger(stages=(), max_workers=2)
await converger.start()
Comment on lines +361 to +363
| `exercise` | `help-run` | — | — | — | — | — | Run subcommand help |
| `exercise` | `help-run-embed` | — | — | — | — | — | Run embed subcommand help |
| `exercise` | `help-run-site` | — | — | — | — | — | Run site stage help |
@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.

  • 62.F075 / P1: fixed-already at the checked revision: The ingest handler now builds a canonical ingest operation at polylogue/daemon/http.py:5520 and executes it at line 5530. Staged imports deliberately remain outside the watched inbox, so acceptance no longer depends on an unwatched staged file being discovered by a default watcher.

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.

2 participants