Skip to content

Serve archive-backed shell completion from a declared operation - #5158

Closed
Sinity wants to merge 1 commit into
masterfrom
cli-s7-completion
Closed

Sinity wants to merge 1 commit into
masterfrom
cli-s7-completion

Conversation

@Sinity

@Sinity Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner

Summary

Step S7 of the CLI unification design: archive-backed shell completion is served by the declared completion operation through the kernel, bounded, with a static fallback when the archive is absent.

Problem

shell_completion_values opened the archive inside the shell-completion process. _db_exists() probed resolve_active_index_path(archive_root()), _run_completion entered archive_read_context, and four completers (complete_session_ids, complete_tag_values, complete_repo_values, complete_tool_values) ran ArchiveStore.list_summaries / list_user_tags / stats_by against it. Three surface→substrate imports existed for exactly that.

A resident daemon already holds that snapshot open and was never asked. The completer also owned the vocabulary rules — which stats_by dimension backs which field, how many rows a TAB press may return — on the client side of the boundary.

Solution

CompletionRequest gains source and limit. source names an archive-backed vocabulary (session_id, tag, repo, tool); limit is part of the request because a completer wants a short list quickly, not a complete one, and the bound belongs with the question rather than in a server default.

CompletionResult gains value_completions beside query_completions, with a validator requiring exactly one. Both being optional would let {} validate — and an empty result must never be confusable with "the archive has no matching tags", which is how a completer silently produces nothing forever. (test_declared_result_contracts_reject_empty_placeholders is what catches this.)

Handler (daemon_reads._completion_values): session ids are listed and filtered on id-prefix, id-substring or title-substring exactly as before; tags come from the durable user tier's own reader and repo/tool from stats_by — the same aggregate analyze by <dimension> reports, so a completion cannot offer a value the corresponding query would not match. An undeclared source raises rather than returning [].

A grammar completion still needs no archive. execute_read_operation skipped index validation for the whole completion operation; it now skips it only when the request names no archive-backed source, so the pure-protocol read still works against the minimal archive-shaped object the public operation seam passes.

CLI side: one function, completion_values(source, incomplete, limit), dispatches through the kernel with a 1000 ms deadline and returns [] on any failure. The broad except is deliberate and documented: a completer has no channel to report on, and a traceback in a shell prompt is strictly worse than no completion.

Deleted: _db_exists, _run_completion, _stats_by_items, the ArchiveCompletionAction type, and the archive_read_context / ArchiveStore / resolve_active_index_path / archive_root imports.

origin is deliberately left local

The design counts three layering entries for S7. Only two are retired. complete_origin_values reads sources.origin_specs.public_origin_descriptions, a declared vocabulary, not archive content. Routing it through the operation makes it depend on an openable archive, so the one completion that is always answerable would return nothing on a fresh install — the exact opposite of the archive-absent fallback this step is meant to provide. Verified: with a nonexistent archive root, origin still returns 10 items while every archive-backed source correctly returns 0.

Retiring that entry needs an origin vocabulary owner the CLI may import, or a direct-execution path that does not open an archive for an archive-free operation. Neither is S7.

Golden bytes

scripts/golden_find_bytes.py — 37 documented find invocations, 0 differing. The companion non-empty harness (22 list/search/aggregate/projection cases) — 0 differing. Completion is off the find path, so this is a no-regression check rather than the primary evidence.

The primary evidence is an end-to-end smoke against a seeded cli-mixed archive through the real kernel and completers:

session_id   4 items   tag  0 items   repo 0 items   tool 2 items ('bash','2 actions')  origin 3 items
archive absent: session_id 0   tag 0   repo 0   tool 0   origin 3

Every archive-backed source degrades to empty with no archive; origin still answers.

Layering

devtools gate layering: 273 baseline entries before, 271 after (228 matched, 43 stale — the inherited count), 0 violations.

file import status
polylogue/cli/shell_completion_values.py polylogue.storage.archive_identity pruned
polylogue/cli/shell_completion_values.py polylogue.storage.sqlite.archive_tiers.archive pruned
polylogue/cli/shell_completion_values.py polylogue.sources.origin_specs kept, see above

Verification

devtools test tests/unit/cli/test_completion_matrix.py tests/unit/cli/test_completions_contract.py \
              tests/unit/cli/test_command_aux_runtime.py tests/unit/operations/test_daemon_reads.py \
              tests/unit/operations/test_daemon_protocol.py
  devtools test: PASSED exit=0 diagnosis=pytest_passed   (receipt 20260914T212109Z)

New handler-level tests run against a real bootstrapped archive rather than a mock, so they fail if the operation is wrong rather than only if the plumbing is: the bounded four-source read, the refusal on an undeclared source, and the law that a grammar completion opens nothing (which goes red the moment the handler touches archive unconditionally). test_command_aux_runtime.py's _run_completion/_db_exists fixtures are rewritten against the operation's value rows.

devtools verify --quick     → exit 0, all 17 gates ok
devtools gate layering      → exit 0, 0 violations, 271 baseline entries
devtools render all --check → exit 0, grep "out of sync": 0 hits
devtools gate mypy          → Success: no issues found in 2869 source files

tests/unit/daemon/test_daemon_operation_route.py::test_uds_refuses_when_kernel_peer_credentials_cannot_be_read fails, and fails identically on the stashed baseline (receipt 20260914T211149Z) — inherited, unrelated to this change.

Closure

out  polylogue/cli/shell_completion_values.py
out  polylogue/operations/daemon_protocol.py
out  polylogue/operations/daemon_reads.py

All OUT. This PR does not move the derived schema identity and does not gate a rebuild.

Residuals

Cold-process completion latency got worse with no daemon running, and I could not measure the case this change exists for. Measured on the same seeded archive, one completion per fresh process, POLYLOGUE_DAEMON=off:

master this PR
first archive-backed completion (cold process) 3.50 s 4.66 s
subsequent completion (warm process) 19 ms 21 ms
origin (no archive) 0.1 ms 0.1 ms

Attribution, from a phase profile: importing operation_kernel costs 45 ms — it is not the kernel module. The whole ~4.6 s is inside the first dispatch, which pulls in the daemon-client/operation-context/execution graph and then opens the archive; the second dispatch in the same process is 21 ms. Master's 3.5 s is the same shape with a lighter import set, so this step adds roughly 1.1 s to a cost that was already far past any sane completion budget.

The case the design is arguing for — a resident daemon answering from its open snapshot, with no archive open in the completion process at all — is not exercised by this measurement, because no daemon was running. I did not verify it. The design's "completion latency budget (07o1e profile)" is unmet both before and after, and someone should decide whether daemon-off completion is meant to be usable at all before this ships to a workstation without a running polylogued.

Other residuals:

  • cwd_prefix still has no archive source and still returns [] by design; it is not part of the declared source vocabulary.
  • The 1000 ms deadline bounds the socket call only. A direct read falls through to _execute_directly, which honours read_control, not deadline_ms — so the daemon-off path above is not actually time-bounded. Bounding it needs a cancellation token threaded into the direct read, which is dispatch's contract, not this module's.

🤖 Generated with Claude Code

https://claude.ai/code/session_01DYUNBGoE652b3nfmq3CtqK

…tion

Archive-backed value completion opened `index.db` inside the shell-completion
process: `_db_exists` probed for the file, `_run_completion` entered
`archive_read_context`, and four completers ran `list_summaries`,
`list_user_tags` and `stats_by` against an `ArchiveStore` the CLI opened
itself. A resident daemon already has that snapshot open and was never asked.

The `completion` operation now answers those vocabularies. `CompletionRequest`
gains `source` and `limit`; `CompletionResult` gains `value_completions`
alongside `query_completions`, with a validator requiring exactly one — an
empty result would otherwise make "no matching tags" indistinguishable from
"nothing answered", which is a completer that silently produces nothing
forever. Session ids are listed; tags come from the durable user tier and
repo/tool from `stats_by`, the same aggregate `analyze by <dimension>` reports,
so a completion cannot offer a value the query would not match.

A grammar completion still needs no archive and still skips index validation;
only a request naming an archive-backed `source` is validated as a read.

`origin` is deliberately *not* routed through the operation. It is a declared
vocabulary from `sources/origin_specs`, and making it depend on an openable
archive would mean the one always-answerable completion returned nothing on a
fresh install — the opposite of what the archive-absent fallback is for. Its
layering baseline entry therefore stays; the two storage entries go.

Layering baseline 273 → 271.

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 3 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: 62d69585-1afd-4b65-a427-7e9f040bc4e9

📥 Commits

Reviewing files that changed from the base of the PR and between 890a292 and 5f21169.

📒 Files selected for processing (6)
  • docs/plans/layering-surface-baseline.json
  • polylogue/cli/shell_completion_values.py
  • polylogue/operations/daemon_protocol.py
  • polylogue/operations/daemon_reads.py
  • tests/unit/cli/test_command_aux_runtime.py
  • tests/unit/operations/test_daemon_reads.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-14T21:29:11.357760Z 5f21169 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 added a commit that referenced this pull request Sep 14, 2026
## Summary

S8 of the CLI unification begins with a judgment call, not a migration:
the
design (§2.3) left the read-view classification open and asked for it to
be
decided "against `structural_query_units()` at S8". This lands that
decision
(D3) as a declaration every view must satisfy, plus the test that keeps
the
table total.

## Problem

`READ_VIEW_HANDLER_METADATA` described *what options a view accepts* but
not
*how the view reaches durable evidence*. Each S8 family would otherwise
have
re-derived that per PR, and the design's own hypothesis was wrong in a
way
that is easy to repeat.

The design guessed that the per-session evidence views whose names
resemble
query units would lower to `query.units` with a `session:` filter.
Checked
against the relations:

- the `observed-event` unit reads the materialized
`query_observed_events`
projection (`archive/query/metadata.py`,
`sql_query_method="query_observed_events"`);
  the `events` view renders `Session.session_events`, the parsed
session-timeline evidence (`api/archive.py:get_session_events`).
Different
  relation, different grain.
- the `file` unit reads affected file *paths* via `query_files`; the
  `file-edits` view renders the structured `file_edits` diffs
  (`api/archive.py:get_file_edits`).
- `hooks` (`hook_events`), `agent-policies` (`session_agent_policies`),
  `web-content` (`web_content_constructs`) and `effective_context` (the
  compaction-aware replay) have no unit descriptor at all —
`structural_query_units()` is `action, assertion, block,
context-snapshot,
  delegation, file, message, observed-event, run`.

## Solution

`ReadViewHandlerMetadata` gains a keyword-only `execution_kind` and the
`operations` it executes through. The decided partition:

| kind | views |
| --- | --- |
| `session-read-projection` | `agent-policies`, `dialogue`,
`effective_context`, `events`, `file-edits`, `hooks`, `messages`, `raw`,
`summary`, `transcript`, `web-content` |
| `query-units-projection` | *(none — declared, unpopulated; see
Problem)* |
| `distinct-operation` | `context`, `context-image`, `lineage`,
`topology` (`context.compile` / `session.lineage` land with S9) |
| `renderer` | `chronicle`, `correlation`, `neighbors`, `temporal` |

`_validate_read_view_classification` runs at import, so a view cannot be
added
with an execution kind that contradicts the operations it names. The
module
stays metadata-only: operation *names* are checked against
`DAEMON_OPERATION_SPECS` in the test, not the module.

No execution path changes in this PR; the eleven `session.read` families
migrate one per candidate on top of this table.

## Golden bytes

`scripts/golden_find_bytes.py` run at `890a2921e` (master) and at this
head:
**37 goldens (13 skipped), byte-identical** (`cmp` clean). Expected —
this is a
declaration-only change.

The non-empty companion cases the brief attributes to S4/S6/S7's author
are
not present on master and not in #5156/#5157/#5158's file lists, so the
documented aggregates are all the harness currently offers. Listed as a
residual.

## Layering

`docs/plans/layering-surface-baseline.json`: **273 entries before, 273
after**
(unchanged — no import added or removed). `devtools gate layering`
passed with
`count=0`, `baselined_count=230`.

## Verification

```
devtools test tests/unit/cli/test_read_view_classification.py \
  tests/unit/cli/test_query_verbs_runtime.py \
  tests/unit/cli/test_query_set_read.py \
  tests/unit/cli/test_messages.py \
  tests/unit/surfaces/test_projection_spec.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

devtools verify --quick        # 15 gates ok
devtools gate layering         # count=0
devtools render all --check    # exit 0, zero "out of sync"
```

Anti-vacuity: the three new tests go red if a read-view profile is added
without a classification, if a row names an operation the protocol does
not
declare, if a `session.read` projection reaches for another operation,
if a
renderer composes nothing, or if any view is moved between kinds —
including
reclassifying one of the per-session evidence views onto `query.units`,
the
hypothesis the relation evidence above refutes.

## Closure

`devtools schema closure` — both touched files report `out`:

- `polylogue/cli/read_view_registry.py` → out
- `tests/unit/cli/test_read_view_classification.py` → out

No rebuild-boundary constraint.

## Residuals

- `query-units-projection` is a declared kind with no members. It is
kept
rather than dropped because the S8 per-family PRs must be able to move a
  view into it if a relation turns out to be unit-expressible; the test
  enforces that such a move names a real grammar unit.
- The four `distinct-operation` rows carry no operation name because
  `session.lineage` and `context.compile` are not declared until S9. The
import-time validator enforces the empty tuple so the rows cannot
quietly
  claim a route they do not have.
- The read parity the design names for S8 (`session.read` across daemon,
direct and the API's `get_session` on the lineage corpus) belongs to the
  first family migration, not to this declaration-only change.
- `correlation` is classified `renderer` over `session.read` per D7; its
local
  `git`/`gh` evidence step is not an operation and is not modelled here.

🤖 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

Sinity commented Sep 14, 2026

Copy link
Copy Markdown
Owner Author

Included in #5165, which cherry-picks this commit whole (2465c0f) with its authorship preserved and then makes the routing pay off. Measured daemon-resident: this PR alone was slower than master (5.27s vs 4.52s on --id) because asking the daemon a question imported the machinery for not asking it; #5165 takes it to 0.71s. Closing as included rather than superseded — the routing shape here was right.

@Sinity Sinity closed this Sep 14, 2026
Sinity added a commit that referenced this pull request Sep 14, 2026
> Stacked on #5160 (the D3 classification). Review that one first; this
PR's
> base will be retargeted to `master` once it merges.

## Summary

The first S8 family migration. The `hooks` read view stops opening an
archive
through the API facade and instead lowers onto `session.read` and
renders what
the operation returns.

## Problem

`read --view hooks` reached durable evidence by opening the `Polylogue`
facade
in-process (`cli/messages.py::run_hooks` →
`api.get_hook_event_summary_for_session`).
That is a second read authority inside a surface, and it is the shape S8
exists
to remove.

Two further consequences at head:

- The view decided its own execution route. Nothing about whether a
daemon was
  resident reached the decision, because there was no dispatch at all.
- A missing session printed `Session not found: <ref>` through
`env.ui.error`
and returned normally. An operator scripting `read --view hooks` could
not
distinguish "this session recorded no hook events" from "this reference
does
  not resolve", because both produced a zero exit and no evidence.

## Solution

`session.read` grows a `kind` discriminator
(`polylogue/operations/read_contracts.py`):

- `transcript` — the message window it already served; unchanged.
- `hooks` — the first per-session evidence relation, read through the
pinned
  reader's `hook_event_summary_for_session` rather than the facade.

Evidence kinds are bounded read models answered whole, so the request
model
refuses a continuation on one and the result model refuses three states
that
would otherwise be expressible: an evidence body on a transcript window,
a
transcript kind with no body, and a `hooks` result that reports itself
partial.
`_WHOLE_EVIDENCE_KINDS` names which kinds that last rule binds, so a
kind that
later genuinely needs paging graduates to the windowed contract instead
of
silently truncating.

`lower_session_read` gains `kind=` and refuses window coordinates
alongside an
evidence kind. `run_read_hooks` becomes lowering + dispatch + render; it
never
opens an archive and never branches on daemon presence — which executor
answers
is the kernel's decision, recorded in the result's own authority. A
refusal is
classed exactly as the transcript path classes its own (`UsageError` for
an
ordinary refusal, `ClickException` for
`daemon_required`/`result_too_large`), so
it exits non-zero naming itself rather than rendering as an empty
summary.

`cli/messages.py::run_hooks` is deleted. `read_views/messages.py`
survives
because `messages` and `raw` still live there; it goes when the last of
its
views migrates.

**Behaviour change, stated plainly:** a missing session under `read
--view hooks`
now exits non-zero with a typed refusal instead of exiting zero after a
notice.
This is the operator's 2026-09-14 ruling applied — a read that could not
be
served must never read as an empty result — and it makes `hooks`
consistent with
the transcript path, which already refuses an unresolvable reference.

## Golden bytes

`scripts/golden_find_bytes.py` at `890a2921e` (master) vs this head:
**37 goldens (13 skipped), byte-identical** (`cmp` clean). The
documented `find`
surface is untouched.

As noted in #5160, the non-empty companion cases the brief attributes to
S4/S6/S7's author are not on master and not in #5156/#5157/#5158's file
lists,
so the documented aggregates are all the harness offers. The three-way
parity
test below is the non-vacuous evidence for this change.

## Layering

`docs/plans/layering-surface-baseline.json`: **273 before, 273 after.**
`devtools gate layering` passed, `count=0`, `baselined_count=230`.

The view now reaches `cli.lowering` + `cli.operation_kernel` instead of
`polylogue.api`, so no baselined surface→substrate edge was added; the
facade edge it drops belongs to `cli/messages.py`, which keeps other
users of
it until `messages`/`raw` migrate.

## Verification

```
devtools test tests/unit/operations/test_read_operation_declarations.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

devtools test tests/unit/operations/test_session_read_parity.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

devtools test tests/unit/cli/test_messages.py tests/unit/cli/test_query_verbs_runtime.py \
  tests/unit/cli/test_query_set_read.py tests/unit/cli/test_read_view_classification.py
devtools test: PASSED exit=0 diagnosis=pytest_passed

devtools verify --quick        # all gates ok
devtools gate layering         # count=0
devtools render all --check    # exit 0, zero "out of sync"
```

**Read parity (the gap the design names for S8).**
`tests/unit/operations/test_session_read_parity.py` runs the same
`session.read`
over three genuinely distinct routes on one seeded archive with hook
events
attached, and compares the bodies:

- the **daemon** route, over the real UDS listener
(`running_daemon_operations`),
  including envelope validation;
- the **direct** route, the in-process handler over a pinned reader;
- the **API** route, `Polylogue.get_hook_event_summary_for_session` —
the facade
  MCP and the Python API already use.

All three agree on the hooks body; a second test holds the transcript
window
across daemon and direct, so the `kind` discriminator is shown not to
have
changed the default read.

**Broad run.** `devtools test tests/unit/cli tests/unit/operations`
reports 9
failures. All 9 were reproduced at `890a2921e` (master):

- 4 × `test_plain_cli_snapshots.py` — the known re-recording owned
elsewhere;
-
`test_interaction_oracles.py::test_completion_script_parses_in_each_installed_real_shell`,

`test_query_expression.py::…test_descriptor_runtime_transform_units_reject_aggregate_pipeline`,
  2 × `test_archive_maintenance_cli.py`, and

`test_mutation_actuators.py::…test_a_session_absent_from_the_index_is_still_tombstoned`
  — confirmed red on master by a separate run at that commit.

Zero regressions attributable to this change.

Anti-vacuity is named per test. The load-bearing ones: answering the
hooks kind
from the transcript branch, letting the daemon and direct routes use
different
readers, relaxing either result validator, or swallowing the refusal and
printing an empty body each turn a test red.

## Closure

`devtools schema closure` — every touched file reports `out`:

- `polylogue/operations/read_contracts.py` → out
- `polylogue/operations/daemon_reads.py` → out
- `polylogue/cli/lowering.py` → out
- `polylogue/cli/read_views/messages.py` → out
- `polylogue/cli/messages.py` → out
- `tests/unit/operations/test_session_read_parity.py` → out
- `tests/unit/operations/test_read_operation_declarations.py` → out
- `tests/unit/cli/test_messages.py` → out

No rebuild-boundary constraint.

## Residuals

- `SessionReadKind` is `{"transcript", "hooks"}`. The other five
evidence
  families (`events`, `file-edits`, `agent-policies`, `web-content`,
`effective_context`) each need a **sync reader on `ArchiveStore` that
does not
exist yet** — only `hook_event_summary_for_session` was already there;
the
rest are async repository methods. That substrate work is what each of
those
  family PRs has to do first, and it is why `hooks` went first.
- `messages` and `raw` still route through `cli/messages.py`, so
  `read_views/messages.py` is not deleted by this PR.
- The API facade's `get_hook_event_summary_for_session` is retained: MCP
and the
Python API are its remaining consumers, and S8 does not own their
migration.
- `hooks` declares no view-specific options, so no option ownership
moved.

🤖 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 14, 2026
…hive (#5165)

## Summary

Shell completion is a keystroke surface that was spending seconds per
TAB press, with or without a daemon. This makes the archive-backed
completers ask the resident daemon and nothing else: no execution graph,
no archive open, no local fallback. With no daemon they render one
non-insertable message naming the remedy instead of an empty list that
reads as "no matches". `origin` remains a local declared vocabulary and
still answers on a fresh install.

Built on #5158 (cherry-picked as the first commit here, `2465c0f3d`),
not a supersession. That PR's routing through the declared `completion`
operation is the right shape and is kept whole; what it could not do was
make the shape pay off, because the cost was never the operation
protocol.

## Measurements

Cold process means one completion per fresh `polylogue` process through
Click's zsh protocol — exactly what a shell runs. Best of three.
Archive-backed sources are `--id`, `--tag`, `--tool`, `--repo`;
`--origin` is the declared vocabulary.

**(a) Daemon-off, cold process** (operator archive, 76 GB):

| completion | master | this PR |
| --- | --- | --- |
| `--origin` (declared) | 0.39 s | 0.42 s |
| `--id` | 4.05 s | 0.49 s |
| `--tag` | 3.91 s | 0.51 s |
| `--tool` | 3.89 s | 0.51 s |
| `--repo` | 3.93 s | 0.48 s |

On master every archive-backed row above returned **zero items after ~4
s** — four seconds spent to render nothing, indistinguishable from "no
matches". This PR returns the daemon refusal. On the seeded 500-session
archive the same daemon-off numbers are 0.49–0.55 s.

**(b) Daemon-off, warm** (first vs. second call in one process,
`--tag`):

| | master | this PR |
| --- | --- | --- |
| first | 3354 ms | 86 ms |
| second | 3.6 ms | 1.0 ms |

**(c) Daemon-resident** — the case #5158's author flagged as unmeasured.
A real `polylogued run` against a seeded archive (500 sessions / 5000
messages / 14501 blocks), private `XDG_RUNTIME_DIR`, cold process:

| completion | master | #5158 | this PR |
| --- | --- | --- | --- |
| `--id` | 4.52 s | 5.27 s | 0.71 s |
| `--tag` | 4.74 s | 5.71 s | 0.87 s |
| `--tool` | 4.32 s | 5.72 s | 0.97 s |
| `--repo` | 4.16 s | 6.52 s | 0.54 s |

Item counts are identical across the three columns, so this is the same
answer at a different price.

**The daemon-resident case is the finding.** #5158 routed the question
to the daemon and got *slower* than master — 5.3–6.5 s against 4.2–4.7
s. The thin-client premise was sound and the measurement did not show
it, because asking the daemon a question was itself importing the
machinery for not asking it.

## Problem

A phase profile of one daemon-off completion, attributing the ~3.5 s
baseline:

```
import operation_kernel                       0.150s
get_config()                                  0.001s
OperationRequest('completion') + .spec        0.000s
import operations.operation_context           3.736s   <-- ArchiveStore, query execution
operation_archive_root(config)                0.000s
import daemon.socket_path                     1.067s   <-- polylogue.daemon.__init__ -> daemon.cli
import daemon_client                          0.004s
```

So the bead's attribution ("the first dispatch pulling in the execution
graph and opening the archive") is half right: the archive open is real
but it is not the expensive half. `dispatch` imported
`operation_context` unconditionally to call `operation_archive_root` — a
function that resolves *where* to read from two paths — and that module
imports `ArchiveStore` and the query execution stack. Separately,
`polylogue.daemon.__init__` imported `polylogue.daemon.cli` eagerly (5.2
s cold on its own), so asking where the daemon's socket is imported the
daemon.

Both costs are paid before any socket is contacted, which is why #5158's
daemon-resident path was the slowest of all: it paid them and then made
a round trip.

## Solution

**`dispatch(..., daemon_only=True)`.** `completion` is `direct_allowed`,
so without this a missing daemon silently falls through to the local
reader — correct for every other CLI route, unaffordable for a
keystroke. `daemon_only` raises the typed `OperationUnavailableError`
instead. The local fallback is untouched for everyone else.

**A displayed refusal, not an empty list.** New
`polylogue/cli/shell_completion_classes.py` adds a `message` completion
type: zsh renders it with `_message -r` (displayed, never inserted);
bash and fish ignore unknown types, so it degrades to no completion
there rather than a bogus candidate. The zsh template is *derived* from
Click's by splicing a branch, so upstream fixes are inherited and a
changed anchor raises at import instead of silently shipping a template
without the branch. The message names `polylogued run` / `systemctl
--user start polylogued`.

**`operation_archive_root` moves to
`polylogue/operations/archive_root.py`**, which imports only `Path` and
`storage.archive_identity` (76 ms). `operation_context` keeps execution
dependencies; addressing is a different question. `dispatch` imports it
lazily and only when no `archive_root` was passed.

**`polylogue/daemon/__init__.py` exports lazily** (PEP 562), exactly as
`polylogue.cli.__init__` already does and for the same stated reason.
`polylogue.daemon.socket_path` is path and permission arithmetic;
importing it no longer imports the daemon.

**No cache.** The declared vocabularies answer locally because they are
declarations; everything archive-derived is the daemon's answer or
nothing. There is no cached completion data, so there is no staleness
bound to state.

`origin` is still deliberately local (#5158's reasoning, unchanged):
routing a declared vocabulary through the operation would make the one
always-answerable completion return nothing on a fresh install.

## Verification

```
devtools test tests/unit/cli/test_completion_matrix.py tests/unit/cli/test_completions_contract.py \
              tests/unit/cli/test_completion_daemon_boundary.py tests/unit/cli/test_command_aux_runtime.py \
              tests/unit/operations/test_daemon_reads.py tests/unit/operations/test_daemon_protocol.py \
              tests/unit/daemon/test_uds_socket_scoping.py tests/unit/cli/test_daemon_client.py \
              tests/unit/cli/test_query_completion_generation.py tests/unit/demo/test_demo_completion_claims.py
  devtools test: PASSED exit=0 diagnosis=pytest_passed   (receipt 20260914T223646Z)

devtools verify --quick     → exit 0, all 17 gates ok (layering, mypy, atlas included)
```

The load-bearing regression test is
`test_daemon_off_completion_opens_no_database`: it runs the four
archive-backed completers in a fresh interpreter under a
`sys.addaudithook` on `sqlite3.connect`, against a **bootstrapped
archive that is really there**, and asserts nothing was opened. It
asserts absence of the open rather than a latency threshold — a timing
assertion is flaky and proves less.

**Anti-vacuity, verified by reverting.** Removing `daemon_only=True`
from `completion_values` and re-running:

```
FAILED tests/unit/cli/test_completion_daemon_boundary.py::test_daemon_off_completion_says_why_it_is_empty
FAILED tests/unit/cli/test_completion_daemon_boundary.py::test_daemon_off_completion_opens_no_database
E   AssertionError: completion opened databases with no daemon:
E   [..., 'file:/.../archive/index.db?mode=ro', 'file:/.../archive/source.db?mode=ro',
E    'file:/.../archive/index.db?mode=ro', 'file:/.../archive/source.db?mode=ro', ...]
```

— the archive's own `index.db` and `source.db`, opened once per
completer. Restored afterwards; the passing run above is on the restored
tree.

Three completion-matrix tests changed, deliberately and not to make
anything pass quietly.
`test_dynamic_completers_return_nothing_on_an_empty_archive` asserted
the old silent-empty contract, which the current behaviour rejects; it
and the two seeded-archive tests now assert that a populated archive
changes nothing about the daemon-off answer. The archive-derived
vocabulary itself is proven where it is now produced, in #5158's
`test_archive_backed_completion_answers_from_the_pinned_reader`.

## Closure

```
out  polylogue/cli/operation_kernel.py
out  polylogue/cli/shell_completion_values.py
out  polylogue/cli/shell_completion_classes.py
out  polylogue/cli/click_app.py
out  polylogue/daemon/__init__.py
out  polylogue/operations/archive_root.py
out  polylogue/operations/operation_context.py
out  polylogue/operations/daemon_protocol.py
out  polylogue/operations/daemon_reads.py
```

All OUT. The derived schema identity does not move; this gates no
rebuild.

## Residuals

- **~0.4 s of the remaining time is CLI process startup, not
completion.** `--origin`, which opens nothing and reads a declaration,
costs 0.42 s cold; `polylogue.version` alone is 188 ms of that. Every
number in table (a) is within ~0.1 s of that floor, so completion's own
cost is now small and the next move on keystroke latency is the
interpreter start, not this module.
- **Daemon-resident is 0.5–1.0 s, not the 21 ms a warm in-process
dispatch shows.** The difference is process start plus the first socket
round trip. It is usable and 5–8× better than either prior state, but it
is not yet a budget anyone would call comfortable.
- **bash and fish show nothing when the daemon is off.** Neither has a
display-without-insert primitive in Click's protocol, so the refusal
reaches zsh users only. Stated rather than worked around: inventing a
fake candidate to carry the message would be worse.
- Measurements (a) and (b) are against the operator's live archive and
(c) against a seeded one; they are not the same corpus and the tables
are not cross-comparable row for row. Within each table the comparison
is like for like.
- `cwd_prefix` still has no archive source and still returns `[]` by
design.
- #5158's residual about `deadline_ms` bounding only the socket call is
now moot for completion: there is no direct read left on that path to be
unbounded.

🤖 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 14, 2026
## Summary

Commits the non-empty golden harness I built for the CLI unification
migration and cited as evidence in #5156, #5157 and #5158, so the next
steps can re-run it instead of re-deriving it. Adds a `TESTING.md`
pointer to both harnesses.

## What gap this closes

`scripts/golden_find_bytes.py` replays every documented `polylogue find`
invocation in `docs/cli-reference.md`. That is the right acceptance
evidence for "the documented surface did not change", and it is weaker
than it looks on its own.

**On the seeded `cli-mixed` corpus, the documented examples that
exercise the interesting code paths land on empty selections.** The
aggregate examples (`analyze count`, `analyze by ...`) and the
`id:`-scoped examples all match nothing. A change can therefore pass
37/37 documented goldens without a single aggregate row, ranked hit,
page boundary or attached-unit projection ever being rendered — so
aggregates, projections, `--sample` and `--latest` need non-empty
coverage before the documented set proves anything about them.

That is not a hypothesis. Measured on this branch, by perturbing the
list envelope to report `"total": 0` on every page:

| harness | invocations | differing |
| --- | --- | --- |
| `golden_find_bytes.py` (documented) | 37 | **0** |
| `golden_nonempty_bytes.py` (this PR) | 22 | 2 |

A regression that zeroes the total on every list page is completely
invisible to the documented set.

## Solution

`scripts/golden_nonempty_bytes.py`, a companion built on the same
machinery — same immutable seeded workload, same frozen clock, same
in-process `Runner`, same recorded shape (exit code + exact
stdout/stderr bytes). The two are one pair.

Its 22 cases are **hand-picked, not extracted**, and that is the point:
the documentation does not contain invocations that return rows, which
is the gap itself. Each case names one thing the documented set leaves
unproven:

- list pages in all five output formats
(`markdown`/`json`/`ndjson`/`csv`/`yaml`) — the row renderer's
per-format branches
- `--limit` and `--limit`+`--offset` — page boundary, `total`,
`next_offset`
- `--fields` — row projection
- `analyze count`, `analyze by origin`, `analyze by day` — aggregate
envelopes with rows in them, text and JSON
- a ranked search in text, JSON and CSV — hit rows, ranks, snippets
- `--origin` — a filter that actually narrows
- `--sort` / `--sort --reverse` — ordering
- `messages where role:assistant` — the unit-row renderer
- `--sample` — the sampling window
- `with messages` — the attached-unit projection fold

17 of the 22 return rows; the rest exercise formats or filters that
legitimately come back empty and still pin their bytes.

The `CASES` tuple is documented as append-only where possible: removing
a case removes coverage, and the keys are the comparison identity.

## Usage

Deliberately the same shape as S3's harness, so a migration step runs
both:

```bash
uv run python scripts/golden_find_bytes.py BEFORE.json
uv run python scripts/golden_nonempty_bytes.py BEFORE-NONEMPTY.json
# ... make the change ...
uv run python scripts/golden_find_bytes.py AFTER.json
uv run python scripts/golden_nonempty_bytes.py AFTER-NONEMPTY.json --compare BEFORE-NONEMPTY.json
```

`--compare` is the one thing the documented harness does not provide,
and it exists because I needed it three times: it exits nonzero when any
case changed and normalizes the three authority fields that vary per run
on an unmodified checkout — `run_id` (a fresh UUID), `generation_id`
(carries the archive clone's inode) and `archive_epoch` (derived from
it). Everything else is compared byte-for-byte. Without that
normalization one case (`find messages where role:assistant --format
json`) reports a false difference on every run.

## Verification

```
uv run python scripts/golden_nonempty_bytes.py A.json
  wrote 22 cases (17 exit 0 with output)

uv run python scripts/golden_nonempty_bytes.py B.json --compare A.json
  22 compared, 0 differing, 0 changed overall        exit=0
```

Anti-vacuity, run as described above: with `"total": 0` forced into the
list envelope, `--compare` reports `22 compared, 2 differing` and
**exits 1**, while the documented harness reports 0 differing across all
37. The perturbation was reverted and the clean compare re-confirmed at
`exit=0` before committing.

```
devtools verify --quick     → exit 0, all 17 gates ok
devtools gate layering      → exit 0, 0 violations, 273 baseline entries (unchanged)
devtools render all --check → exit 0, grep "out of sync": 0 hits
devtools schema closure scripts/golden_nonempty_bytes.py → out
```

No product code is touched: the diff is one new script plus a
`TESTING.md` section. Nothing from #5156/#5157/#5158 is folded in — this
branch is cut from `master` at `890a2921e`.

## Note on discoverability

Neither harness was referenced in any tracked document before this PR.
That is the actual reason the companion was re-derived by hand rather
than re-run: there was nowhere to find it. The new `TESTING.md` section
documents both, states that the pair is not optional, and gives the
`"total": 0` example as the concrete reason.

## Residuals

- The cases are pinned to the `cli-mixed` workload. A workload change
re-bases every golden; that is inherited from the documented harness and
is why both record the workload name in their output.
- `golden_find_bytes.py` still records only — it has no `--compare`, so
its consumers diff by hand. I did not add one here to keep this PR to
the gap the coordinator named; lifting `--compare` into a shared helper
is a reasonable follow-up.
- The companion covers the root query surface only. `read` views,
`continue` and the mutation ceremony have no golden-bytes coverage in
either harness.

🤖 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
Sinity deleted the cli-s7-completion branch September 22, 2026 13:15
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