Skip to content

test(contracts): expand CLI machine-output contract coverage (#1060) - #1080

Merged
Sinity merged 2 commits into
masterfrom
worktree-agent-ab4771d7
May 16, 2026
Merged

Sinity merged 2 commits into
masterfrom
worktree-agent-ab4771d7

Conversation

@Sinity

@Sinity Sinity commented May 16, 2026

Copy link
Copy Markdown
Owner

Summary

Adds 387 lines expanding CLI machine-output contract tests to 6 more commands with JSON envelope assertions and contract evidence artifacts.

Problem

13 of 14 CLI commands had no machine-output contract pinned as pytest evidence.

Solution

Seven new test classes in test_json_envelope_contract.py covering list, stats, status, config, cost, schema explain, and a 6-command --format json matrix. Key discovery: list/stats on empty archives return exit 2 with {"status":"error","code":"no_results"} — the actual contract, now pinned. Each covered command emits a contract evidence artifact. Skipped with comments: auth, ingest, dashboard, resume.

Verification

pytest tests/unit/cli/test_json_envelope_contract.py -v  # all pass
devtools verify --quick  # exit 0

Ref #1060

Add contract tests for six previously uncovered commands:
- list --format json: documents the no_results error envelope (exit 2)
  on empty archive — the actual machine contract, not assumed raw array
- stats --format json: same no_results error envelope pattern
- stats --by provider --format json: dimension key is "provider"
- status --format json: raw JSON with daemon_liveness key (daemon-down fallback)
- config --format json: raw JSON config object
- cost --format json: Pydantic model dump as raw JSON
- schema explain --provider claude-ai --format json: emit_success envelope

Also adds a cross-command parseable-JSON matrix (TestAllJsonCommandsProduceValidJson)
covering six commands with consistent exit-code expectations, and error-path
tests for each new command verifying no traceback leakage on invalid input.

The list/stats tests required discovering that query verbs return exit 2 +
error envelope (not exit 0 + raw data) on empty archives — this is the real
machine contract that external tooling must handle.

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented May 16, 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 59 minutes and 22 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: b12c6b30-f446-4d48-b852-219e105be57f

📥 Commits

Reviewing files that changed from the base of the PR and between 0631b1a and cf0a53a.

📒 Files selected for processing (1)
  • tests/unit/cli/test_json_envelope_contract.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch worktree-agent-ab4771d7

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.

@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: fc9e65e8c0

ℹ️ 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".

CodeRabbit P2: _invoke_raw_json_command with catch_exceptions=True
silently converted Python crashes into non-zero exit codes. Negative-path
tests asserting exit_code != 0 would pass even when commands crashed, not
just when they returned controlled error envelopes. Now re-raises any
exception that isn't SystemExit (Click's normal exit path), so crashes
propagate as test failures instead of false-passing error-path checks.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
@Sinity
Sinity merged commit 00c057f into master May 16, 2026
4 checks passed
@Sinity
Sinity deleted the worktree-agent-ab4771d7 branch May 16, 2026 09:35
Sinity added a commit that referenced this pull request May 16, 2026
)

## Summary

Adds 3 contract-marked test files
(`tests/unit/cli/test_plain_output_contract.py`,
`test_help_contract.py`, `test_completions_contract.py`) pinning the
human-facing CLI surface that #1080 (machine surface) did not cover:
plain rendering, `--help` structure across every command path, shell
completions, version identity, and stdout/stderr discipline. Also fixes
one pre-existing CLI bug surfaced by the new coverage.

## Problem

After #1080 pinned the machine surface (`--format json` envelopes), the
human-facing CLI surface still had no contract coverage. Help-text drift
would have landed silently: a command losing its docstring, a regression
to ANSI leakage in `--plain` output, a renamed shell, or a broken
`--version` shape would not have failed any test.

Concretely, this branch caught a real bug: `polylogue status
--daemon-url
not-a-url --format json` raised an unhandled `ValueError` from
`urllib.request.Request._parse` because `Request(...)` was constructed
outside the `try/except OSError` block in
`polylogue/cli/commands/status.py`.
The failing test
`TestStatusJsonContract::test_status_json_no_traceback_on_bad_url` from
#1080 was already red on master at fc3c43f (`devtools verify --quick`
exit 1 on the inherited baseline). Fixing it is part of this branch.

## Solution

Three new files under `tests/unit/cli/`, all using
`@pytest.mark.contract`, `record_contract_evidence`, and `workspace_env`
for isolation. Patterns follow `test_json_envelope_contract.py` (the
#1080 template).

- **`test_plain_output_contract.py`** (10 tests, 8 evidence streams):
  asserts no ANSI CSI sequences, raw ESC bytes, box-drawing, or block
  characters in `--plain list/stats/config/status` stdout or stderr;
  empty-archive messages are human prose (not JSON-shaped) containing
  `No conversations`; consecutive invocations produce byte-identical
  output; `--plain` does not collapse Click usage errors into stdout.
- **`test_help_contract.py`** (109 tests, 53 evidence streams):
  enumerates the full Click command tree via `iter_command_paths(cli)`
  and parametrizes over all 52 paths. Each gets two checks (`--help`
  exits 0 with no traceback + has a substantive description line). Root
  `--help` exposes `Usage:`/`Options:`/`Commands:`. `-h` aliases
  `--help`. `--version` matches
  `polylogue, version <semver>+<sha>[-dirty]` per `CONTRIBUTING.md`.
  Help output stays on stdout.
- **`test_completions_contract.py`** (9 tests, 4 evidence streams):
  `bash`/`zsh`/`fish` each produce non-empty shell-syntax output
  mentioning `polylogue`, with shell-specific markers (`compgen` for
  bash, `compdef` for zsh, `complete -c` for fish). Unknown shell exits
  non-zero with no traceback. Missing `--shell` errors land on stderr,
  not stdout.

Stdout/stderr discipline (Scope §4 in the issue) is covered as classes
within these three files rather than as a separate file — Click 8.3+
exposes `result.stdout`/`result.stderr` separately, so assertions live
where the surface they test lives.

**CLI bug fixed**: `polylogue/cli/commands/status.py` — moved
`Request(...)` inside the `try` block and broadened the catch from
`OSError` to `(OSError, ValueError)` so malformed daemon URLs fall back
to the direct archive path instead of crashing.

## Verification

```bash
nix develop -c pytest tests/unit/cli/test_plain_output_contract.py \
  tests/unit/cli/test_help_contract.py \
  tests/unit/cli/test_completions_contract.py \
  tests/unit/cli/test_json_envelope_contract.py -p no:randomly
# 172 passed in 12.36s

nix develop -c pytest tests/unit/cli -p no:randomly
# 1062 passed, 1 xfailed in 36.49s

nix develop -c devtools verify --quick
# total_duration_s 35.82, exit_code 0
# (status.py fix was required to bring this from red to green)

ls .cache/verification/evidence/ | grep -cE 'cli\.(plain|help|completions)'
# 68 new evidence artifacts
```

Ref #1060

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

Co-authored-by: Claude Opus 4.7 <[email protected]>
Sinity added a commit that referenced this pull request May 16, 2026
## Summary

Bring the MCP surface up to the pytest-first contract evidence model
from
#1058. The first MCP evidence emitter landed in
`test_server_surfaces.py` for
registration counts; the CLI machine-output family was completed in
#1080.
This PR extends evidence coverage onto the remaining MCP families and
fixes a
small not-found code drift discovered along the way.

## Problem

Before this change, the MCP family in the proof-pack evidence aggregator
had a
single recorder (the server-surfaces registration test) and no pytest
evidence
for:

- whether tool input schemas are themselves valid JSON Schema documents
- tool error envelopes returning the documented `MCPErrorPayload` shape
- search/list tools returning a classified items/total envelope on empty
  results
- privacy of error payloads (no traceback, no secret leakage)
- a stable surface inventory snapshot per run

While investigating, the tool-side not-found path (`get_conversation`,
`get_conversation_summary`, `get_messages`, `raw_artifacts`,
`export_conversation`, `session_profile`, and the mutation helper) was
returning `MCPErrorPayload` without `code="not_found"`, while the
resource
side and the CLI envelope already used the explicit code. That drift was
a
real coherence gap, not just a test gap.

## Solution

- Added `tests/unit/mcp/test_contract_evidence.py` with 21
contract-marked
  tests across five families:
1. **Runtime schema inventory** — `Draft202012Validator.check_schema`
over
     every registered tool, plus resource-template parameter and prompt
     callable assertions.
  2. **Error envelopes** — `neighbor_candidates` without args,
     `get_conversation`/`get_conversation_summary`/`get_messages`/
     `raw_artifacts`/`export_conversation` with missing IDs, and
     `bulk_tag_conversations` validation.
  3. **No-result envelopes** — `search`, `list_conversations`,
`neighbor_candidates`, and `get_session_tree` on empty data; sync and
     async invocation paths both covered.
4. **Privacy envelopes** — resource `internal_error` responses preserve
     `code`/`detail`/no-traceback invariants; `_safe_call` sanitises raw
     exception payloads (postgres URIs, bearer tokens) before raising
     `PolylogueError`.
5. **Registration drift** — full surface inventory captured as evidence
     per run, plus role-scoped capability envelopes (read/write/admin).
- Each test calls `record_contract_evidence.record(...)` at the
assertion
boundary, emitting bounded JSON under `.cache/verification/evidence/` so
  the proof-pack aggregator finds it under the `mcp` surface.
- Tightened `polylogue/mcp/server_tools.py`,
  `polylogue/mcp/server_maintenance_tools.py`,
  `polylogue/mcp/server_insight_tools.py`, and
  `polylogue/mcp/server_mutation_tools.py` to pass `code="not_found"` to
  `error_json` on missing-conversation paths so the documented
`MCPErrorPayload` shape is consistent across resources, tools, and the
CLI.

No backwards-compat shims introduced. No new proof-row registry.
Existing
coverage in `test_server_surfaces.py`, `test_envelope_contracts.py`,
`test_tool_schema_witness.py`, and `test_mcp_edge_cases.py` remains the
authority for the behaviors it already pins.

## Verification

```
nix develop -c pytest tests/unit/mcp -q
# 218 passed (was 197 before; +21 new contract tests)

nix develop -c pytest tests/unit/mcp -m contract -q
# 25 passed in 10s

nix develop -c devtools verify --quick
# total_duration_s 24.36, exit_code 0

ls .cache/verification/evidence/ | grep -c '^mcp\.'
# 21 new artifacts named mcp.{tool,resource,role,surface,prompts}.*
```

A representative artifact (`mcp.tool.get_conversation.not_found-*.json`)
carries the standard envelope:

- `contract`, `surface: "mcp"`, `test_nodeid`, `git_sha`, `dirty`,
  `timestamp`, `schema_version`, and the family-specific `facts`
  block (here: `{"code": "not_found", "is_error": true}`).

Ref #1060
Ref #1058

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

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

## Summary by CodeRabbit

## Release Notes

* **Bug Fixes**
* Standardized error responses across MCP server tools with explicit
error codes when conversations are not found.

* **Tests**
* Added comprehensive contract test suite validating tool schemas, error
response formats, privacy safeguards, result envelopes, and role-based
access control.

<!-- review_stack_entry_start -->

[![Review Change
Stack](https://storage.googleapis.com/coderabbit_public_assets/review-stack-in-coderabbit-ui.svg)](https://app.coderabbit.ai/change-stack/Sinity/polylogue/pull/1081?utm_source=github_walkthrough&utm_medium=github&utm_campaign=change_stack)

<!-- review_stack_entry_end -->

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

---------

Co-authored-by: Claude <[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.

  • 79.F044 / P2: fixed-already at the checked revision: tests/unit/cli/test_json_envelope_contract.py:263-264 re-raises result.exception unless it is SystemExit. An uncaught command exception can no longer masquerade as an expected nonzero error result without a printed traceback.

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.

1 participant