Repository navigation
feat(cli): output assurance contract + JSON schemas + NDJSON streaming (#1272) - #1340
Conversation
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]>
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (23)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 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".
| for existing in sorted(output_dir.glob("*.schema.json")): | ||
| if existing not in expected_files: | ||
| drift.append(f"{existing} (stale; not in SCHEMAS registry)") |
There was a problem hiding this comment.
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 👍 / 👎.
…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]>
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
Summary
Per #1272 (slice B of #958): every primary
polyloguesubcommand now carries a declared output-assurance contract — JSON-shape stability, snapshot coverage,--plainsupport, NDJSON streaming — and stable JSON output surfaces are pinned by published JSON Schemas underdocs/schemas/cli-output/.Problem
Terminal snapshot tests covered some surfaces, but there was no authoritative answer to:
--plain,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 jsonoutput without reading the source. And there was no streaming mode forpolylogue search/list— agents and shell pipelines had to wait for the entire result set before parsing.Solution
polylogue/cli/output_assurance.py— typedASSURANCE_REGISTRYdeclaring, 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 intodocs/cli-reference.mdby the existingdevtools render-cli-referencerenderer.devtools render-cli-output-schemas— new generated surface that serializes PydanticSurfacePayloadModels (ConversationListRowPayload,ConversationSearchHitPayload,ConversationSummaryPayload,ConversationNeighborCandidatePayload,MachineErrorPayload,MachineSuccessPayload) into stable JSON Schemas underdocs/schemas/cli-output/*.schema.jsonplus a generatedREADME.mdindex. Wired intorender_allso drift failsdevtools render-all --checkanddevtools verify --quick.NDJSON streaming:
StructuredRowsDocument.render(\"ndjson\")emits one compact JSON document per line, and thendjsonchoice is added to:polylogue list --format ndjsonpolylogue stats --format ndjsonpolylogue --format ndjson <query>(default search mode)MACHINE_OUTPUT_FORMATSis extended so the search/list paths skip rich rendering and go straight to the structured renderer.Tests:
tests/unit/cli/test_cli_output_assurance_matrix.pyenumerates 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.pyvalidates real payload instances against the published schemas withjsonschema, 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-ndjsonsubcommand. Worse — duplicates the filter surface and forces users to learn a second invocation. Inline--format ndjsonis the smallest viable change.Verification
devtools verify --quick→exit_code: 0pytest tests/unit/cli/test_cli_output_assurance_matrix.py tests/unit/cli/test_cli_output_schemas.py→ 85 passedpytest tests/unit/cli/ --testmon-noselect→ 1301 passed, 1 xfailedpolylogue list --format ndjson --limit 2→ 2 lines, each parses as JSON viapython -c 'import sys, json; ...'Closes #1272. Ref #958, #1181.
🤖 Generated with Claude Code