Skip to content

feat(cli): output assurance contract + JSON schemas + NDJSON streaming (#1272) - #1340

Merged
Sinity merged 1 commit into
masterfrom
feature/feat/cli-output-assurance-1272
May 18, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/feat/cli-output-assurance-1272

Conversation

@Sinity

@Sinity Sinity commented May 18, 2026

Copy link
Copy Markdown
Owner

Summary

Per #1272 (slice B of #958): every primary polylogue subcommand now carries a declared output-assurance contract — JSON-shape stability, snapshot coverage, --plain support, NDJSON streaming — and stable JSON output surfaces are pinned by published JSON Schemas under docs/schemas/cli-output/.

Problem

Terminal snapshot tests covered some surfaces, but there was no authoritative answer to:

  • which commands emit a stable JSON shape vs. human-only output,
  • which commands are covered by a snapshot,
  • which commands honour --plain,
  • whether output drift would actually be caught in CI.

Per command family there was also no published JSON Schema, so external shell pipelines and LLM tool-use harnesses had no way to validate polylogue ... --format json output without reading the source. And there was no streaming mode for polylogue search / list — agents and shell pipelines had to wait for the entire result set before parsing.

Solution

  1. polylogue/cli/output_assurance.py — typed ASSURANCE_REGISTRY declaring, for every primary subcommand, its family + (json_contract, snapshot, plain, streaming, schema, notes). render_matrix_markdown() formats the registry as a per-family Markdown table that is embedded into docs/cli-reference.md by the existing devtools render-cli-reference renderer.

  2. devtools render-cli-output-schemas — new generated surface that serializes Pydantic SurfacePayloadModels (ConversationListRowPayload, ConversationSearchHitPayload, ConversationSummaryPayload, ConversationNeighborCandidatePayload, MachineErrorPayload, MachineSuccessPayload) into stable JSON Schemas under docs/schemas/cli-output/*.schema.json plus a generated README.md index. Wired into render_all so drift fails devtools render-all --check and devtools verify --quick.

  3. NDJSON streaming: StructuredRowsDocument.render(\"ndjson\") emits one compact JSON document per line, and the ndjson choice is added to:

    • polylogue list --format ndjson
    • polylogue stats --format ndjson
    • root polylogue --format ndjson <query> (default search mode)

    MACHINE_OUTPUT_FORMATS is extended so the search/list paths skip rich rendering and go straight to the structured renderer.

  4. Tests:

    • tests/unit/cli/test_cli_output_assurance_matrix.py enumerates every top-level Click subcommand and fails when a new command lands without a registry entry, with a gate not satisfied (json_contract or snapshot), or with a registry entry that no longer corresponds to a live command.
    • tests/unit/cli/test_cli_output_schemas.py validates real payload instances against the published schemas with jsonschema, asserts schema-file/source-model drift per surface, and pins the NDJSON shape (one doc per line, no enclosing array, empty result set → empty string).

Rejected alternative: adding a separate polylogue search-ndjson subcommand. Worse — duplicates the filter surface and forces users to learn a second invocation. Inline --format ndjson is the smallest viable change.

Verification

  • devtools verify --quick → exit_code: 0
  • pytest tests/unit/cli/test_cli_output_assurance_matrix.py tests/unit/cli/test_cli_output_schemas.py → 85 passed
  • pytest tests/unit/cli/ --testmon-noselect → 1301 passed, 1 xfailed
  • polylogue list --format ndjson --limit 2 → 2 lines, each parses as JSON via python -c 'import sys, json; ...'

Closes #1272. Ref #958, #1181.

🤖 Generated with Claude Code

Per #1272 (slice B of #958): every primary `polylogue` subcommand
now carries a declared output-assurance contract — JSON-shape
stability, snapshot coverage, --plain support, NDJSON streaming —
and stable JSON output surfaces are pinned by published JSON
Schemas under `docs/schemas/cli-output/`.

Problem

Terminal snapshot tests covered some surfaces, but there was no
authoritative answer to:
* which commands emit a stable JSON shape vs. human-only output,
* which commands are covered by a snapshot,
* which commands honour `--plain`,
* whether output drift would actually be caught in CI.

Per command family there was also no published JSON Schema, so
external shell pipelines and LLM tool-use harnesses had no way to
validate `polylogue ... --format json` output without reading the
source.

Solution

1. `polylogue/cli/output_assurance.py` — typed `ASSURANCE_REGISTRY`
   declaring, for every primary subcommand, its family +
   `(json_contract, snapshot, plain, streaming, schema, notes)`.
   `render_matrix_markdown()` formats the registry as a per-family
   table that is embedded into `docs/cli-reference.md` by the
   existing `devtools render-cli-reference` renderer.

2. `devtools render-cli-output-schemas` — new generated surface that
   serializes Pydantic `SurfacePayloadModel`s
   (`ConversationListRowPayload`, `ConversationSearchHitPayload`,
   `ConversationSummaryPayload`, `ConversationNeighborCandidatePayload`,
   `MachineErrorPayload`, `MachineSuccessPayload`) into stable JSON
   Schemas under `docs/schemas/cli-output/*.schema.json` plus a
   generated `README.md` index. Wired into `render_all` so drift
   fails `devtools render-all --check` and `devtools verify --quick`.

3. NDJSON streaming: `StructuredRowsDocument.render("ndjson")` now
   emits one compact JSON document per line, and the `ndjson`
   choice is added to:
   * `polylogue list --format ndjson`
   * `polylogue stats --format ndjson`
   * root `polylogue --format ndjson <query>` (default search mode)
   `MACHINE_OUTPUT_FORMATS` is extended so the search/list paths
   skip rich rendering and go straight to the structured renderer.

4. Tests:
   * `tests/unit/cli/test_cli_output_assurance_matrix.py` enumerates
     every top-level Click subcommand and fails when a new command
     lands without a registry entry, with a gate not satisfied
     (`json_contract or snapshot`), or with a registry entry that no
     longer corresponds to a live command.
   * `tests/unit/cli/test_cli_output_schemas.py` validates real
     payload instances against the published schemas with
     `jsonschema`, asserts schema-file/source-model drift per
     surface, and pins the NDJSON shape (one doc per line, no
     enclosing array, empty result set → empty string).

Verification

* `devtools verify --quick` → `exit_code: 0`
* `pytest tests/unit/cli/test_cli_output_assurance_matrix.py
   tests/unit/cli/test_cli_output_schemas.py` → 85 passed
* `pytest tests/unit/cli/ --testmon-noselect` → 1301 passed, 1 xfailed
* `polylogue list --format ndjson --limit 2` → 2 lines, each parses
  as JSON via `python -c 'import sys, json; ...'`

Closes #1272.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@Sinity
Sinity merged commit 7d8dae1 into master May 18, 2026
2 of 4 checks passed
@coderabbitai

coderabbitai Bot commented May 18, 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 15 minutes and 59 seconds before requesting another review.

You’ve run out of usage credits. Purchase more 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: 97c5f93b-3991-429b-b571-8f82e0077522

📥 Commits

Reviewing files that changed from the base of the PR and between cf98e72 and 86f2c7f.

📒 Files selected for processing (23)
  • devtools/command_catalog.py
  • devtools/generated_surfaces.py
  • devtools/render_cli_output_schemas.py
  • devtools/render_cli_reference.py
  • docs/cli-reference.md
  • docs/devtools.md
  • docs/plans/topology-target.yaml
  • docs/schemas/cli-output/README.md
  • docs/schemas/cli-output/conversation-list-row.schema.json
  • docs/schemas/cli-output/conversation-neighbor-candidate.schema.json
  • docs/schemas/cli-output/conversation-search-hit.schema.json
  • docs/schemas/cli-output/conversation-summary.schema.json
  • docs/schemas/cli-output/machine-error.schema.json
  • docs/schemas/cli-output/machine-success.schema.json
  • docs/topology-status.md
  • polylogue/cli/click_option_groups.py
  • polylogue/cli/output_assurance.py
  • polylogue/cli/query_output.py
  • polylogue/cli/query_output_contracts.py
  • polylogue/cli/query_verbs.py
  • tests/unit/cli/__snapshots__/test_terminal_snapshots.ambr
  • tests/unit/cli/test_cli_output_assurance_matrix.py
  • tests/unit/cli/test_cli_output_schemas.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/cli-output-assurance-1272

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 deleted the feature/feat/cli-output-assurance-1272 branch May 18, 2026 20:40

@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: 86f2c7f566

ℹ️ 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/cli/query_verbs.py Resolved
Comment thread polylogue/cli/query_output.py Resolved
Comment on lines +213 to +215
for existing in sorted(output_dir.glob("*.schema.json")):
if existing not in expected_files:
drift.append(f"{existing} (stale; not in SCHEMAS registry)")

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 Make schema renderer clear stale files in write mode

The renderer detects stale *.schema.json files but only appends them to drift; in non---check mode it never removes them, then exits non-zero and tells users to rerun the same command. That means a removed schema entry leaves the generator unable to self-heal, and render-all --check remains blocked until someone manually deletes files.

Useful? React with 👍 / 👎.

Sinity added a commit that referenced this pull request May 19, 2026
…1266) (#1370)

## Summary

Foundation slice (#873 slice A) for the shared ranked-result envelope.
Introduces `SearchEnvelope` — a typed Pydantic model carrying hits +
total + limit/offset + next_offset/next_cursor + query + sort +
retrieval_lane + ranking_policy/version + diagnostics — and routes CLI
JSON, MCP, the Python API, and daemon HTTP through one shared builder so
all four surfaces emit semantically-equivalent envelopes. Also emits an
OpenAPI 3.1 schema (`docs/openapi/search.yaml`) generated from the
Pydantic models so external tooling can auto-discover the daemon's
ranked-search contract.

Closes #1266.

## Problem

Before this PR each surface emitted its own ad-hoc search shape. MCP
exposed `MCPPaginatedSearchResultPayload` with `{hits, total, limit,
offset, next_offset, next_cursor, diagnostics}`. Daemon HTTP
`_do_search_list` built a hand-shaped dict with flat-row hits and a
parallel `match` sub-object. CLI `--format json` emitted a bare list of
`ConversationSearchHitPayload`. The Python API only returned the legacy
`SearchResult` (a `list[ConversationSearchHit]` wrapper). None of these
surfaces declared the ranking policy, version, or carried the query /
retrieval_lane / sort metadata required by #873. Reader/MCP clients had
no way to discover the daemon HTTP shape mechanically — there was no
OpenAPI document.

## Solution

- `polylogue/surfaces/payloads.py`:
- new `SearchEnvelope` model with all the required fields, plus
`RANKING_POLICY_MIXED` / `RANKING_POLICY_VERSION` constants.
- new helpers: `build_search_envelope()` (canonical builder with
cursor/next_offset logic) and `build_search_cursor()`.
- `polylogue/mcp/payloads.py`: `MCPPaginatedSearchResultPayload` now
aliases `SearchEnvelope`. `conversation_search_result_payload()`
delegates to `build_search_envelope` and threads `query` /
`retrieval_lane` / `sort` from `MCPConversationQueryRequest`.
- `polylogue/mcp/server_tools.py`: search tool passes query/lane/sort
into the envelope builder.
- `polylogue/daemon/http.py`: `_do_search_list` builds the typed
envelope and `model_dump`s it. The HTTP `hits` payload now uses the
canonical `ConversationSearchHitPayload` shape (`{conversation: {...},
match: {...}}`) — the existing reader test was updated; no public
clients besides the web reader consume this endpoint yet.
- `polylogue/cli/query_output.py`: `output_search_hits()` emits the
envelope for `--format json` (the format that #1266 calls out); `ndjson`
/ `yaml` / `csv` keep streaming per-row payloads. New
`format_search_envelope()` helper.
- `polylogue/api/archive.py` +
`polylogue/api/search_envelope_builder.py`:
`Polylogue.search_envelope()` typed API method; build logic extracted to
`polylogue/api/search_envelope_builder.py` (keeps `archive.py` under the
per-file LOC budget).
- `devtools/render_openapi.py` + `docs/openapi/search.yaml`: generated
OpenAPI 3.1 description of the daemon HTTP search endpoint, derived from
the Pydantic models with `$defs` hoisted into `components/schemas`.
Wired into `command_catalog`, `generated_surfaces`, and therefore
`devtools render-all` / `--check`.
- `devtools/render_cli_output_schemas.py`: `SearchEnvelope` published as
`docs/schemas/cli-output/search-envelope.schema.json` alongside the
existing per-hit schema (reuses the #1272 pattern from PR #1340).
- `tests/unit/surfaces/test_search_envelope_contract.py`: cross-surface
contract test that runs the same query through the Python helper, the
MCP helper, and the CLI formatter and asserts the envelope-level
metadata (limit, offset, query, retrieval_lane, ranking_policy,
ranking_policy_version, hit ranks, hit lanes, hit conversation IDs)
matches across all three. Also pins the `SearchEnvelope` field set and
verifies the OpenAPI schema is committed.

The legacy `MCPPaginatedSearchResultPayload` export is retained as an
alias so external imports keep working through the transition.

## Verification

```
python -m pytest tests/unit/surfaces tests/unit/cli/test_query_fmt.py tests/unit/cli/test_query_exec_laws.py tests/unit/mcp tests/unit/daemon tests/unit/api -q
# → 1106 passed in 18.75s

python -m devtools verify --quick
# → exit_code: 0 (format + lint + mypy + render-all --check + manifest checks all pass)

python -m devtools render-all --check
# → all generated surfaces in sync (includes new render-openapi)
```

Cross-surface equivalence is verified by
`tests/unit/surfaces/test_search_envelope_contract.py::test_all_surfaces_emit_semantically_equivalent_envelope`.
The OpenAPI schema renders cleanly and
`tests/unit/surfaces/test_search_envelope_contract.py::test_openapi_schema_is_present_and_well_formed`
ensures it stays committed and references `SearchEnvelope`.

## Follow-ups

This is the slice-A foundation. Slices B–E under #873 (lane-rank
contribution preservation in hybrid RRF, cursor-based stable pagination
wiring at the query plan level, scoped facets, surface convergence of
the two `ConversationSearchHit` models) build on this envelope.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@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.

  • 60.F044 / P1: fixed-already at the checked revision: The shared empty-page renderer explicitly emits no rows for NDJSON at polylogue/cli/render/outcome.py:305. Human no-match text is confined to the other-format branch, so an empty NDJSON page is not contaminated by prose.
  • 60.F046 / P1: fixed-already at the checked revision: Ungrouped statistics reject unsupported formats rather than falling through to human output at polylogue/cli/archive_query.py:1365. Grouped statistics use the common row serializer, whose NDJSON branch emits one JSON object per row at polylogue/cli/render/rows.py:168.

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(cli): output-assurance contract — stable JSON schemas + snapshot gate per command family (#958 slice B)

1 participant