Skip to content

Replace the CLI's browser HTTP calls with declared operations - #5173

Merged
Sinity merged 1 commit into
masterfrom
cli-transport-daemon-operations
Sep 15, 2026
Merged

Sinity merged 1 commit into
masterfrom
cli-transport-daemon-operations

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

Step S11 of the CLI-unification design: the CLI's four remaining hand-rolled
browser-HTTP calls are deleted and replaced with declared daemon operations.
urlopen no longer appears anywhere under polylogue/cli/.

Problem

Route Was Now
polylogue import PATH urlopen POST {daemon_url}/api/ingest declared ingest operation
polylogue import --demo --wait urlopen POST /api/demo/augment new maintenance.demo.augment
polylogue dashboard urlopen GET /api/status status operation
polylogue tutorial urlopen GET /api/status status operation

Four clients, each with its own auth header, timeout and error vocabulary, for
work the operation protocol already carries — while the declared ingest
operation sat in CLI_PENDING_ADOPTION, declared and unused.

The design recorded the ingest request contract as inferred. It is now
verified: daemon/http.py::_handle_ingest resolves the staged inbox source,
runs preflight_import_source, and submits
{path, source_path, idempotency_key} as the ingest operation — precisely
IngestRequest. The route's only other work is decorating the response with a
synthesized status. So the CLI loses nothing by submitting directly; it has to
absorb the preflight, which is a local read-only admissibility check and is
better run before staging anything.

Solution

Acceptance is not completion. import prints "Scheduled" and returns;
--wait is the separate opt-in. configured_mutation_operation drives
operation_to_completion, which would block until the whole ingest finished — a
behaviour change. This adds configured_accepted_operation to
operation_kernel.py: the same client, auth and MUTATION_OPERATION_NAMES
construction, but single-shot client.operation(...), plus a refusal when the
spec declares no accepted_reference — "submit and take the durable reference"
is its whole contract, so an operation with no reference to take does not belong
on it. Acceptance is then derived from that reference and the outcome exactly as
the HTTP route did, preserving the module's promise that there is no silent
success path.

maintenance.demo.augment (WRITE / NEVER / archive.demo_augment / 120s)
is declared and served, applying apply_demo_post_ingest_augmentation and
seed_demo_user_overlays under the daemon's writer. It runs to completion,
because its only caller is already inside --wait.

The status probes are the subtle part. status declares DIRECT_READ, so
dispatch succeeds with no daemon by falling back to a local reader. Reporting
that as "daemon reachable" would be a lie, and strictly worse than the HTTP
probe it replaces. polylogue/cli/daemon_probe.py::daemon_serving_probe
therefore discriminates on OperationResult.authority["mode"] == "daemon" and
says why in its docstring, so the next reader does not "simplify" it back into a
lie. It never raises: a probe that explodes is worse than one that says no.

A layering boundary was respected rather than baselined. Importing
polylogue.sources.import_preflight from the CLI is a new cli -> sources
edge, which devtools gate layering forbids (the ratchet may only shrink). The
preflight is reached through a new operation-layer entry point,
operations.import_operations.import_source_admissibility, which owns the
boundary.

Two stale registry pointers fixed in passing. cli.query and query.units
still named archive_query:_emit_daemon_list_payload / :_emit_rows, which an
earlier step's move of the row renderers into cli/render/rows.py left
resolving to nothing — on master, not just here. Catching that is what the
registry is for.

Verification

devtools test tests/unit/cli/test_import.py \
  tests/unit/operations/test_cli_operation_binding_registry.py \
  tests/unit/operations/test_daemon_protocol.py \
  tests/unit/cli/test_dashboard_command.py tests/unit/cli/test_tutorial.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260914T233651Z-focused-test-207162-9c829ea9/run.json

devtools verify --quick        exit 0
devtools gate layering         violations 0
devtools render all --check    exit 0, zero "out of sync" lines

grep -n "urlopen\|urllib" polylogue/cli/commands/import_command.py   # no output

Schema closure (devtools schema closure): out for all nine touched
files — import_command.py, dashboard.py, tutorial.py, daemon_probe.py,
operation_kernel.py, operation_bindings.py, daemon_protocol.py,
daemon_mutations.py, import_operations.py.

Every deleted-transport test law survives at the operation seam rather than
being dropped:

Law Was Now
daemon unreachable is named, not silent URLError OperationUnavailableError, asserting polylogued run + archive root
a refusal names the staged file HTTP 4xx/5xx OperationFailedError
an inadmissible source is refused HTTP 415 refused before submitting — the test asserts no operation was sent
an unrecognized status never claims success unknown status completed with no durable reference still fails

New: indeterminate submission, failed demo augmentation, and — the two that
matter most — test_dashboard_direct_served_status_is_not_reported_as_a_reachable_daemon
and test_daemon_alive_rejects_a_directly_served_status_read, which are exactly
the lie the DIRECT_READ fallback invites.

Residuals

  • ops embed backfill is deliberately not here (polylogue-d02y8). It is
    not a transport repoint: the loop builds its vector provider from a Voyage API
    key held in the CLI process, so moving it means the daemon holds that
    credential — a policy decision, not a refactor. It also streams per-session
    progress and enforces a live cumulative cost cap, both of which need declared
    progress events and a typed partial-result outcome.
  • ops maintenance migrate-tier is unchanged. It already implements D8
    option (a) in substance — _require_stopped_daemon refuses while a daemon
    owns the archive and records stopped_daemon_evidence_ref as proof. What D8
    asks for beyond that is that the offline-maintenance class be declared where
    a reader will find it; that belongs with the rest of the S12 census.
  • The daemon's own /api/ingest and /api/demo/augment HTTP routes are
    untouched — the browser upload UI still uses them. Only the CLI stopped.
  • Two test_import.py fixtures changed because the placeholder
    {"type": "session"} is genuinely inadmissible to the preflight. The Hermes
    state.db case is refused as unsupported_import_source by the daemon
    route too
    (_preflight_sqlite admits only Antigravity trajectory stores),
    so the client-side check surfaces an existing product gap earlier rather than
    creating one. Documented in that test's docstring; not fixed here.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

`polylogue import` POSTed the staged path to the browser route `/api/ingest`
with `urlopen`, and `import --demo --wait` POSTed `/api/demo/augment` the same
way, while the declared `ingest` operation sat in `CLI_PENDING_ADOPTION` unused.
`dashboard` and `tutorial` each probed `GET /api/status` to decide whether a
daemon was alive. Four hand-rolled HTTP clients, each with its own auth header,
timeout and error vocabulary, for work the operation protocol already carries.

Reading `daemon/http.py::_handle_ingest` shows it only resolves the staged
source, preflights it, and submits `{path, source_path, idempotency_key}` as the
`ingest` operation -- exactly `IngestRequest`. So the CLI loses nothing by
submitting directly; it only has to absorb the preflight, which is a local
read-only admissibility check that is better run before staging anything.

`import` needs acceptance, not completion: it prints "Scheduled" and returns,
and `--wait` is the separate opt-in. `configured_mutation_operation` drives
`operation_to_completion`, so this adds `configured_accepted_operation` --
single-shot submit, refusing any operation that declares no
`accepted_reference`, because "take the durable reference" is its whole
contract. Acceptance is derived from that reference and the outcome exactly as
the HTTP route did, so the module's promise that there is no silent success
path is unchanged.

`maintenance.demo.augment` is declared and served for the demo overlay writes.

The status probes are the subtle one: `status` declares `DIRECT_READ`, so the
dispatch succeeds with no daemon by falling back to a local reader. Reporting
that as "daemon reachable" would be a lie and strictly worse than the HTTP probe
it replaces. `cli/daemon_probe.py` therefore discriminates on the result's
`authority["mode"]`, and says so in its docstring.

Also repoints two binding references that S4's move of the row renderers into
`cli/render/rows.py` left pointing at `archive_query`. They resolve to nothing
on master, which is what the registry exists to catch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 29 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: f22d3613-83d4-464a-8a2d-b87e5c0b84fa

📥 Commits

Reviewing files that changed from the base of the PR and between 724d175 and bc575a5.

📒 Files selected for processing (13)
  • polylogue/cli/commands/dashboard.py
  • polylogue/cli/commands/import_command.py
  • polylogue/cli/commands/tutorial.py
  • polylogue/cli/daemon_probe.py
  • polylogue/cli/operation_bindings.py
  • polylogue/cli/operation_kernel.py
  • polylogue/operations/daemon_mutations.py
  • polylogue/operations/daemon_protocol.py
  • polylogue/operations/import_operations.py
  • tests/unit/cli/test_dashboard_command.py
  • tests/unit/cli/test_import.py
  • tests/unit/cli/test_tutorial.py
  • tests/unit/operations/test_cli_operation_binding_registry.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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 14, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
🔒 Security Review ✅ Completed 2026-09-14T23:47:22.001895Z bc575a5 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@Sinity
Sinity merged commit 743c712 into master Sep 15, 2026
3 checks passed
@Sinity
Sinity deleted the cli-transport-daemon-operations branch September 15, 2026 01:50
Sinity added a commit that referenced this pull request Sep 15, 2026
## Summary

Three pagination tests error before reaching any assertion because a
`patch()` target still names a symbol #5156 deleted. Replaces #5174,
which was closed after #5173 independently landed the product half of
the same fix.

## Evidence

Receipt `.cache/verify/runs/20260914T233651Z-all-207009-89ddea6b`
(`verify_all`, job 1699, 22,540 selected, 29 failed).

**Caveat on that receipt:** its `run.json` records `git_head:
f7964ac` — the tip of branch
`rebase-5165`, *not* `master` and not an ancestor of it — and
`final_git_head: 724d175`. The shared checkout advanced across 7
merged PRs during the run, so it is not evidence of a frozen tree. I
re-ran all 29 node ids at true `master` HEAD: 17 reproduce, 12 do not.
These 3 are among the 17, and still reproduce at `4105e3698`.

## Per-failure classification

| Failure | Classification | Cause |
| --- | --- | --- |
|
`test_archive_query::TestDaemonSearchEnvelopeHonestPagination::test_clamped_page_reports_the_next_offset`
| **stale test** | `patch("polylogue.cli.archive_query._emit_rows")` —
#5156 moved it to `cli/render/rows.py` as public `emit_rows` |
| `…::test_final_page_reports_no_next_offset` | **stale test** | same |
| `…::test_limit_reports_what_the_daemon_applied` | **stale test** |
same |

## Problem

#5156 moved the CLI row renderers out of `archive_query` into
`cli/render/rows.py` and made them public. This file's *imports* were
retargeted at the time; the `patch()` dotted string was not. A patch
target is a string, so nothing failed at collection — instead `mock`
raised `AttributeError` inside the context manager, before any assertion
ran.

`emit_session_search_page` calls `emit_rows` from its own module
namespace, so `polylogue.cli.render.rows.emit_rows` is the seam that
actually intercepts it.

#5173 fixed the other half of this same rename —
`CLI_OPERATION_BINDINGS` still naming
`archive_query:_emit_daemon_list_payload`,
`:_emit_daemon_search_payload` and `:_emit_rows`, none of which
resolved. I had that product fix in #5174; #5173 landed the identical
change first (as `_RENDER_ROWS`), so #5174 was closed as conflicting and
this PR carries only the remaining test half. After it, there is no
reference to `archive_query._emit_rows` left in the tree.

## Solution

One line: patch `polylogue.cli.render.rows.emit_rows`.

## Anti-vacuity

The three tests keep the conditions stated in their own docstrings —
hard-code `next_offset` to `None`, or echo the requested `limit` instead
of the one the daemon applied, and they go red. They could not go red
**for any reason** while the patch target was wrong, since they errored
before the assertions. That is what this restores, and it is why the fix
is worth making rather than deleting the tests: the behaviour they cover
(a daemon-proxied clamped page must not present itself as complete) is
not covered elsewhere — the golden-parity suite seeds a corpus smaller
than its own `--limit` and never reaches a clamped page, as the class
docstring notes.

## Verification

```
devtools test tests/unit/cli/test_archive_query.py tests/unit/operations/test_cli_operation_binding_registry.py
devtools test: PASSED exit=0 diagnosis=pytest_passed receipt=.cache/verify/runs/20260915T015359Z-focused-test-338452-90aec230/run.json
```

The binding registry file is included to confirm #5173's half and this
half agree at the current head.

## Schema closure

`tests/unit/cli/test_archive_query.py` — **out** of the derived
schema-identity closure. Test-only change; no product file touched. Does
not need to land before an archive rebuild.

## Residuals

None. This is the last stale reference to the pre-#5156 renderer names.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Sinity added a commit that referenced this pull request Sep 15, 2026
## Summary

Clears five of the six real failures on `master` at `c676444409`. All
five are tests pinning behaviour their product route no longer has; no
product code changed.

## Receipt and provenance

Full-corpus `verify_all`, agentctl job `polylogue-verify_all-3e42cd1b`,
receipt
`.cache/verify/runs/20260915T020605Z-all-348770-0b1b4d33/run.json`:

- `git_head = c676444`
- `final_git_head = c676444`
- `git_dirty = False`, `final_git_dirty = False`
- `verification_scope = complete`, `diagnosis = pytest_failed`, 22,588
selected, 6 failures

The checkout did not move across the 6,205 s run and was clean at both
ends, so every failure is real. (Two earlier runs reporting 147 and 29
spanned a moving checkout; only 17 of the 29 reproduced at a settled
head.)

## Per-failure classification

| Test | Classification |
| --- | --- |
|
`test_schema_preflight.py::test_live_batch_marks_structural_database_error_degraded`
| stale test double |
|
`test_schema_preflight.py::test_ingest_files_short_circuits_when_degraded`
| stale test double |
|
`test_schema_preflight.py::test_ingest_files_short_circuits_under_burst_after_degraded`
| stale test double |
|
`test_cli_action_contracts.py::test_import_contract_guard_requires_daemon_acceptance`
| stale fixture + wording pin (**not** a product defect) |
|
`test_note.py::test_terminal_note_idempotency_survives_root_judgment_canary_route`
| missing daemon + wording pin |
| `test_demo_seed_verify` | **not in scope** — `polylogue-wrvy2`, open
operator decision; left red |

### A. `_StubCursor` has no `ops_write_scope` (3)

#5169 added `CursorStore.ops_write_scope()` so one `ops.db` connection
is shared per ingest batch; `LiveBatchProcessor.ingest_files` opens it
unconditionally. The double in `test_schema_preflight.py` predates it
and every call raised `AttributeError`.

### B. Daemon-required refusal wording (2) — wording drift, not a
product defect

Investigated both before retargeting, as instructed.

**`import`**: the `'Error: unsupported_import_source: ...'` message is
*not* the daemon guard failing for the wrong reason. `import_command.py`
calls `_preflight_or_fail(staged)` (local `import_source_admissibility`)
**before** `_submit_ingest`, which is where `daemon_accepts_schedule`
lives. The test's source was `{}`, which is genuinely not a parseable
Polylogue export shape, so it was refused by the earlier, correct guard
and never reached the daemon guard at all. The ordering is deliberate
and documented in `_preflight_or_fail`: refuse a locally-detectable
inadmissible source rather than schedule an operation that can only fail
later. Nothing to fix in the product; the fixture was invalid for what
the test claims to test.

**`judge`**: #5172/#5173 routed durable `user.db` writes through
declared daemon operations, so `judge --accept` now refuses with a typed
`OperationUnavailableError` when no daemon answers. Per the operator
ruling, that is correct. The refusal itself is already pinned by
`tests/unit/cli/test_cli_operation_authority.py::test_judge_accept_refuses_without_a_daemon`;
the note canary is about capture/judge/replay idempotency and needed the
daemon it now requires.

## Solution

- `_StubCursor` implements the real `ops_write_scope` contract rather
than a no-op: thread-local, depth-counted re-entry, and a flush of
buffered stage events on **every** exit path including exceptions, with
a thread-identity assertion on exit. It also gained
`record_ingest_stage_event`, so the buffer and its flush are real rather
than decorative. New `assert_scopes_balanced(at_least=n)` checks depth
returned to zero, nothing was left unflushed, and the expected number of
scopes completed.
- `test_import_contract_guard_requires_daemon_acceptance` now writes an
admissible ChatGPT-shaped export (asserting
`import_source_admissibility(...).admissible` first, so the fixture
cannot silently regress to being refused by the earlier guard), and
asserts `result.exit_code == OUTCOME_EXIT_CODES["error"]` plus zero rows
in `sessions` — the typed outcome and the absence of a CLI-side write,
not the prose.
- `test_terminal_note_idempotency_survives_root_judgment_canary_route`
runs its lifecycle inside
`tests.infra.daemon_operations.cli_daemon_archive`, a real
`DaemonOperationRuntime` behind the socket the CLI probes. No assertion
was weakened; only the fixture supplies what `judge` now requires.

## Verification

Each retargeted test names an anti-vacuity condition, verified by
reverting. Observed text:

**A** — removed the `with self._cursor.ops_write_scope():` wrapper from
`LiveBatchProcessor.ingest_files`; all three go red:

```
E  AssertionError: expected at least 5 completed ops write scope(s), saw 0
E  AssertionError: expected at least 2 completed ops write scope(s), saw 0
E  AssertionError: expected at least 1 completed ops write scope(s), saw 0
```

**B/import** — replaced the `OperationUnavailableError` refusal in
`_submit_ingest` with a fabricated local acceptance; the test goes red
on the fabricated success:

```
E  AssertionError: Scheduled: .../archive/inbox/session.json
E      Operation:    local-fallback
```

**B/note** — passed `idempotency_key=None` in
`polylogue/cli/commands/note.py`; the replay stops resolving to the same
candidate:

```
E  AssertionError: assert 'assertion-te...-abdd99ef922a' == 'assertion-te...-089dae5a7e32'
E  - assertion-terminal-note:c5812cf3-3455-4e0d-8405-089dae5a7e32
E  + assertion-terminal-note:f14ae865-ef88-4112-9cb9-abdd99ef922a
```

Product code restored to `c676444409` state after each mutation; the
staged diff is tests only.

Focused run (the three changed files plus the two suites that own the
contracts being relied on):

```
devtools test tests/unit/daemon/test_schema_preflight.py \
  tests/unit/cli/test_cli_action_contracts.py tests/unit/cli/test_note.py \
  tests/unit/cli/test_cli_operation_authority.py \
  tests/unit/sources/test_cursor_ops_write_scope.py
devtools test: PASSED exit=0 diagnosis=pytest_passed
  receipt=.cache/verify/runs/20260915T040329Z-focused-test-435941-3ba8618b/run.json
======================== 66 passed, 1 warning in 17.09s ========================
```

Static gates:

```
devtools verify --quick   # exit 0; 17 gates, all ok
```

## Schema closure

Run on every touched file; none is in a fingerprint closure, so no
reconvergence is implied:

```
devtools schema closure tests/unit/cli/test_cli_action_contracts.py  -> out
devtools schema closure tests/unit/cli/test_note.py                  -> out
devtools schema closure tests/unit/daemon/test_schema_preflight.py   -> out
```

## Residuals

- `test_demo_seed_verify` is still red by design: `polylogue-wrvy2` is
an open operator decision (the demo builds a Claude-Code-shaped `Task`
dispatch inside a Codex parent and expects `mapping_state:resolved`,
which the Codex wire cannot express). Untouched.
- Evidence here is the focused selection above plus the static gates. No
affected/full suite was run; a full corpus run at the merged head is the
only thing that proves the 6 → 1 reduction end to end.
- The note canary now starts a real daemon stack (UDS listener plus
coordinator loop), so it is heavier than the other tests in its module.
That is the cost of exercising a route the daemon owns.
- `pre-commit` secret-scan reports one candidate span in
`test_cli_action_contracts.py`; it is the pre-existing
`sk-voyage-CONTRACT-LEAKME` synthetic literal in the redaction test,
untouched by this change.

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

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK


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

## Summary by CodeRabbit

- **Reliability**
- Improved validation of daemon-mediated imports and note operations,
including clearer handling when the daemon is unavailable.
- Confirmed that failed or unreachable daemon operations do not create
incomplete archive entries.
- Strengthened safeguards around batched processing and database error
handling to help maintain consistent operation state.

- **Tests**
- Expanded coverage for operation lifecycle, schema preflight checks,
and repeated note-processing scenarios.

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

Co-authored-by: Claude Opus 5 (1M context) <[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