Skip to content

feat(refs): resolve public archive refs (#2181) - #2194

Merged
Sinity merged 2 commits into
masterfrom
feature/feat/public-ref-resolution-2181
Jun 19, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/feat/public-ref-resolution-2181

Conversation

@Sinity

@Sinity Sinity commented Jun 19, 2026 •

Copy link
Copy Markdown
Owner

Summary

Adds a shared public-ref resolver so ObjectRef/EvidenceRef strings in archive payloads become actionable across CLI, Python API, MCP, and daemon HTTP. The resolver returns a bounded PublicRefResolutionPayload instead of widening unsupported refs into search.

Problem

Polylogue already emits refs from recovery, work-packet, assertion, and runtime projection surfaces, but users and agents could not ask the product to dereference those refs consistently. That made evidence links less useful and encouraged each surface to invent local lookup behavior.

Solution

  • Added PublicRefResolutionPayload and RefResolutionActionPayload in polylogue.surfaces.payloads.
  • Implemented Polylogue.resolve_ref(...) for session, message, block, assertion, run, observed-event, and context-snapshot refs, including EvidenceRef projection to the nearest object payload.
  • Exposed the resolver through:
    • polylogue read REF --format json,
    • MCP resolve_ref,
    • daemon GET /api/refs/resolve?ref=...,
    • Python API Polylogue.resolve_ref(...).
  • Updated daemon route contracts, MCP envelope/tool discovery contracts, status route catalogs, CLI reference, and search docs.
  • Added behavior coverage for object refs, EvidenceRefs, unsupported refs, CLI JSON output, daemon route output, MCP payload reuse, and status snapshot/catalog drift.

Closes #2181

Verification

  • devtools test tests/unit/cli/test_status.py::test_archive_facade_route_catalog_covers_public_async_facade tests/unit/cli/commands/test_status.py tests/unit/api/test_facade_contracts.py::test_resolve_ref_returns_bounded_session_message_block_and_runtime_payloads tests/unit/api/test_facade_contracts.py::test_resolve_ref_returns_assertion_payload → 89 passed.
  • devtools test tests/unit/cli/test_plain_cli_snapshots.py::test_json_status_snapshot tests/unit/cli/test_status.py::test_archive_facade_route_catalog_covers_public_async_facade tests/unit/api/test_facade_contracts.py::test_resolve_ref_returns_bounded_session_message_block_and_runtime_payloads → 3 passed.
  • devtools verify --quick → exit 0.
  • devtools verify --seed-testmon --skip-slow → 11,556 passed, 9 warnings; peak pytest RSS 3,374 MB.
  • devtools verify → 7 affected tests passed; exit 0.

Summary by CodeRabbit

  • New Features

    • Added public reference resolution across CLI (polylogue read [REF]), HTTP API, Python API, and MCP interfaces
    • Enables resolution of references to sessions, messages, blocks, assertions, and runtime objects with standardized bounded payloads
  • Documentation

    • Updated CLI command documentation with optional reference argument and usage examples
    • Added reference resolution guide documenting available resolver entry points and supported reference types

Problem: ObjectRef and EvidenceRef strings were present in payloads, but users and agents could not consistently dereference them across surfaces without inventing broad searches or one-off lookup logic. That left evidence links less useful in CLI, MCP, daemon, and API workflows.\n\nWhat changed: add a shared PublicRefResolutionPayload, implement Polylogue.resolve_ref for sessions, messages, blocks, assertions, and runtime projection refs, and expose the resolver through CLI direct read, MCP resolve_ref, and GET /api/refs/resolve. Update docs, status route catalogs, MCP contracts, and behavior tests for object refs, evidence refs, unsupported refs, and cross-surface payload reuse.\n\nVerification: devtools test for focused resolver/catalog/snapshot nodes passed; devtools verify --quick passed; devtools verify --seed-testmon --skip-slow passed with 11556 tests; devtools verify passed with the affected testmon set.
github-actions Bot pushed a commit that referenced this pull request Jun 19, 2026
@coderabbitai

coderabbitai Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Sinity, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 45 minutes and 38 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan refill rate.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, the refill rate gradually slows as usage increases. The highest same-day bursts are limited more strictly.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 7d27c241-5944-49b6-923e-45cf657340c7

📥 Commits

Reviewing files that changed from the base of the PR and between 3ba05ca and d2ad137.

📒 Files selected for processing (1)
  • tests/baselines/showcase/help-read.txt
📝 Walkthrough

Walkthrough

Implements a resolve_ref service that resolves public object/evidence refs (session, message, block, assertion, run, context-snapshot, observed-event) into a shared PublicRefResolutionPayload. The resolver is exposed through the Python archive API, CLI polylogue read [REF], daemon GET /api/refs/resolve, and a new MCP resolve_ref tool.

Changes

Public Ref Resolution Feature

Layer / File(s) Summary
Payload models and MCP alias
polylogue/surfaces/payloads.py, polylogue/mcp/payloads.py, docs/cli-reference.md, docs/search.md
Defines RefResolutionActionPayload and PublicRefResolutionPayload Pydantic models with field normalizers and exports them; introduces MCPPublicRefResolutionPayload alias; adds CLI usage signature update and a new "Public Ref Resolution" docs section.
Archive resolve_ref implementation
polylogue/api/archive.py, tests/unit/api/test_facade_contracts.py
Adds parse_public_ref import and helper functions _resolution_action/_unresolved_ref_payload; implements resolve_ref entrypoint dispatching to five per-kind private resolvers (session, message, block, assertion, runtime) including batched session scanning for runtime kinds; covered by two new facade contract tests.
CLI read verb ref argument and status catalog
polylogue/cli/query_verbs.py, polylogue/cli/commands/status.py, tests/unit/cli/...
Adds optional positional ref Click argument to read_verb, imports run_coroutine_sync/serialize_surface_payload, implements early-return ref path with format/destination guard, registers resolve_ref in _ARCHIVE_FACADE_ROUTES; CLI runtime test and snapshot counts updated.
Daemon HTTP endpoint and route contract
polylogue/daemon/http.py, polylogue/daemon/route_contracts.py, tests/unit/daemon/test_web_reader.py
Wires GET /api/refs/resolve into the static GET route table with _handle_ref_resolve (400 on missing ref, 503 on no archive); adds RouteContract entry (stable, read_query, bearer_if_configured); integration test asserts resolved envelope fields.
MCP resolve_ref tool
polylogue/mcp/server_tools.py, tests/unit/mcp/..., tests/infra/mcp.py
Registers resolve_ref MCP tool calling poly.resolve_ref(ref) under async_safe_call; adds tool to EXPECTED_TOOL_NAMES, TOOL_CONTRACT, and typed envelope map; MCP server surface test and discovery minimal kwargs added.

Sequence Diagram(s)

sequenceDiagram
  participant Client as Client (CLI / MCP / HTTP)
  participant Surface as Surface Handler
  participant PolylogueArchiveMixin as PolylogueArchiveMixin.resolve_ref
  participant KindResolver as Per-Kind Resolver
  participant Archive as Archive / user.db

  Client->>Surface: ref string (e.g. session:abc123)
  Surface->>PolylogueArchiveMixin: resolve_ref(ref)
  PolylogueArchiveMixin->>PolylogueArchiveMixin: parse_public_ref(ref) → kind
  alt unsupported / parse error
    PolylogueArchiveMixin-->>Surface: PublicRefResolutionPayload(resolved=False)
  else supported kind
    PolylogueArchiveMixin->>KindResolver: _resolve_<kind>_object_ref(archive, parsed_ref)
    KindResolver->>Archive: SQL query / session load / user.db read
    Archive-->>KindResolver: row / payload object
    KindResolver-->>PolylogueArchiveMixin: PublicRefResolutionPayload(resolved=True, payload=...)
    PolylogueArchiveMixin-->>Surface: PublicRefResolutionPayload
  end
  Surface-->>Client: serialized JSON envelope
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • Sinity/polylogue#2158: Refactors the daemon HTTP routing to a table-driven contract system that this PR extends with the new GET /api/refs/resolve route contract entry.

Suggested labels

area:schema

🐇 A ref once lost in a haystack of strings,
Now resolves to a payload with actions and things!
Session or block, assertion or run —
Each hop through the archive is boundedly done.
The rabbit cheers: resolved: true! 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'feat(refs): resolve public archive refs (#2181)' accurately describes the main change: implementing a public reference resolver across the product.
Description check ✅ Passed The PR description covers all required template sections: Summary, Problem, Solution with module details, Verification with exact test commands, and Changelog applicability.
Linked Issues check ✅ Passed The PR fulfills all key acceptance criteria from #2181: resolver exists across CLI, Python API, MCP, and daemon surfaces; supports session, message, block, assertion, and runtime refs; handles EvidenceRef projection; includes typed errors for unsupported kinds; and has comprehensive documentation and test coverage.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing the public reference resolver. Updates to documentation, route contracts, payloads, CLI, MCP, daemon HTTP, and test coverage all align with the stated objectives and linked issue requirements.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/feat/public-ref-resolution-2181

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: 3ba05ca961

ℹ️ 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/api/archive.py
Comment on lines +1596 to +1598
try:
session_id = archive.resolve_session_id(object_ref.object_id)
except KeyError:

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 Handle ambiguous session ref prefixes

When a caller resolves a shortened session ref that matches more than one session, ArchiveStore.resolve_session_id() raises ValueError, but this branch only converts KeyError into an unresolved payload. That makes the new CLI/API/MCP resolver surface an internal error for ambiguous prefixes instead of returning a bounded resolved: false response, even though prefix resolution is what this helper is using for session:<token> refs.

Useful? React with 👍 / 👎.

Comment thread polylogue/api/archive.py
Comment on lines +1797 to +1799
summary_offset = 0
while True:
summaries = archive.list_summaries(limit=200, offset=summary_offset)

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 Bound runtime ref resolution to the addressed session

For runtime refs such as context-snapshot:<session_id>:session_start or observed-event:<session_id>:..., the ref already identifies the owning session, but this path pages through every summary and then hydrates/compiles each session until it finds a match. On large archives or missing runtime refs, the new CLI/MCP/daemon resolver becomes an O(all sessions) scan rather than the bounded lookup promised by the ref-resolution surface, so resolving a link near the end of the archive can be very slow or time out.

Useful? React with 👍 / 👎.

@coderabbitai coderabbitai 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.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/cli-reference.md (1)

213-236: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Document direct-ref output constraints in this command section.

read [REF] currently only allows --format json and --to terminal|stdout (enforced in polylogue/cli/query_verbs.py). Without noting that here, the options list implies unsupported combinations.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docs/cli-reference.md` around lines 213 - 236, The documentation for the
polylogue read command does not document the output constraints that apply when
using a direct reference (REF parameter). Add documentation (such as a note or
constraints section) to clarify that when providing a direct REF, only --format
json combined with --to terminal|stdout are supported options, even though the
general usage examples might suggest other combinations are available. Reference
that these constraints are enforced in polylogue/cli/query_verbs.py to help
maintainers understand where the validation happens.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@polylogue/api/archive.py`:
- Around line 1668-1669: The message reference in object_refs is emitting only
message:{message_id} without session scope, which can cause ambiguous resolution
when the same message_id exists in multiple sessions. Update the message
reference on line 1668 and line 1742 to include the session scope in the format,
making it session-scoped (such as session:{session_id}:message:{message_id} or
similar) to ensure deterministic dereferencing across multiple sessions.
- Around line 1573-1575: The methods _resolve_assertion_object_ref and
_resolve_runtime_object_ref are not receiving the evidence_ref parameter, which
prevents them from preserving the original evidence reference in resolved
payloads. Pass evidence_ref to both method calls at lines 1573 and 1575, update
the method signatures of _resolve_assertion_object_ref and
_resolve_runtime_object_ref to accept the evidence_ref parameter, and ensure
they use it to consistently preserve the original evidence reference in the
resolved payloads for assertion, run, observed-event, and context-snapshot
object types. Apply the same fix pattern to the related code sections at lines
1749-1786 and 1788-1934.

In `@polylogue/daemon/http.py`:
- Around line 2487-2489: The error response for the missing ref query parameter
uses a non-standard error shape that violates the daemon-wide error contract.
Replace the direct _send_json call with HTTPStatus.BAD_REQUEST and the custom
error object with a call to the standard _send_error method (or equivalent
canonical error envelope function documented in QueryErrorPayload) to ensure the
error response follows the established daemon error format for consistency
across all error handling.

In `@tests/unit/cli/test_query_verbs_runtime.py`:
- Around line 168-225: The test_read_direct_ref_emits_shared_resolution_payload
function only tests the success path for direct reference resolution. Add
explicit test assertions to verify that UsageError is raised when the
wrapped_read function is called with output_format values other than "json" or
destination values other than "terminal"/"stdout". These tests should validate
the contract guardrails enforced in lines 350-353 by calling wrapped_read with
invalid format/destination combinations and asserting that a UsageError is
raised in each case.

---

Outside diff comments:
In `@docs/cli-reference.md`:
- Around line 213-236: The documentation for the polylogue read command does not
document the output constraints that apply when using a direct reference (REF
parameter). Add documentation (such as a note or constraints section) to clarify
that when providing a direct REF, only --format json combined with --to
terminal|stdout are supported options, even though the general usage examples
might suggest other combinations are available. Reference that these constraints
are enforced in polylogue/cli/query_verbs.py to help maintainers understand
where the validation happens.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 10056a6a-64ea-4520-a0b5-be2cddc1817d

📥 Commits

Reviewing files that changed from the base of the PR and between 861a84d and 3ba05ca.

📒 Files selected for processing (18)
  • docs/cli-reference.md
  • docs/search.md
  • polylogue/api/archive.py
  • polylogue/cli/commands/status.py
  • polylogue/cli/query_verbs.py
  • polylogue/daemon/http.py
  • polylogue/daemon/route_contracts.py
  • polylogue/mcp/payloads.py
  • polylogue/mcp/server_tools.py
  • polylogue/surfaces/payloads.py
  • tests/infra/mcp.py
  • tests/unit/api/test_facade_contracts.py
  • tests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambr
  • tests/unit/cli/test_query_verbs_runtime.py
  • tests/unit/daemon/test_web_reader.py
  • tests/unit/mcp/test_envelope_contracts.py
  • tests/unit/mcp/test_server_surfaces.py
  • tests/unit/mcp/test_tool_discovery.py

Comment thread polylogue/api/archive.py
Comment on lines +1573 to +1575
return self._resolve_assertion_object_ref(archive_root, ref, normalized_ref, object_ref)
if object_ref.kind in {"run", "observed-event", "context-snapshot"}:
return self._resolve_runtime_object_ref(archive, ref, normalized_ref, object_ref)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve original EvidenceRef for assertion/runtime branches too.

When ref parses as EvidenceRef, Line 1573 and Line 1575 route into handlers that never receive evidence_ref, so resolved payloads for assertion, run, observed-event, and context-snapshot cannot preserve the original evidence ref consistently.

Suggested fix
-            if object_ref.kind == "assertion":
-                return self._resolve_assertion_object_ref(archive_root, ref, normalized_ref, object_ref)
+            if object_ref.kind == "assertion":
+                return self._resolve_assertion_object_ref(
+                    archive_root, ref, normalized_ref, object_ref, evidence_ref
+                )
             if object_ref.kind in {"run", "observed-event", "context-snapshot"}:
-                return self._resolve_runtime_object_ref(archive, ref, normalized_ref, object_ref)
+                return self._resolve_runtime_object_ref(archive, ref, normalized_ref, object_ref, evidence_ref)

     def _resolve_assertion_object_ref(
         self,
         archive_root: Path,
         ref: str,
         normalized_ref: str,
         object_ref: ObjectRef,
+        evidence_ref: EvidenceRef | None,
     ) -> PublicRefResolutionPayload:
@@
-            evidence_refs=payload.evidence_refs,
+            evidence_refs=((evidence_ref.format(), *payload.evidence_refs) if evidence_ref else payload.evidence_refs),
@@
     def _resolve_runtime_object_ref(
         self,
         archive: Any,
         ref: str,
         normalized_ref: str,
         object_ref: ObjectRef,
+        evidence_ref: EvidenceRef | None,
     ) -> PublicRefResolutionPayload:
@@
                 resolved = self._resolve_runtime_object_ref_for_summary(
-                    archive, ref, normalized_ref, object_ref, summary
+                    archive, ref, normalized_ref, object_ref, summary, evidence_ref
                 )
@@
     def _resolve_runtime_object_ref_for_summary(
         self,
         archive: Any,
         ref: str,
         normalized_ref: str,
         object_ref: ObjectRef,
         summary: Any,
+        evidence_ref: EvidenceRef | None,
     ) -> PublicRefResolutionPayload | None:
@@
-                    evidence_refs=run_payload.evidence_refs,
+                    evidence_refs=((evidence_ref.format(), *run_payload.evidence_refs) if evidence_ref else run_payload.evidence_refs),
@@
-                    evidence_refs=event_payload.evidence_refs,
+                    evidence_refs=((evidence_ref.format(), *event_payload.evidence_refs) if evidence_ref else event_payload.evidence_refs),
@@
-                    evidence_refs=snapshot_payload.evidence_refs,
+                    evidence_refs=((evidence_ref.format(), *snapshot_payload.evidence_refs) if evidence_ref else snapshot_payload.evidence_refs),

Also applies to: 1749-1786, 1788-1934

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/api/archive.py` around lines 1573 - 1575, The methods
_resolve_assertion_object_ref and _resolve_runtime_object_ref are not receiving
the evidence_ref parameter, which prevents them from preserving the original
evidence reference in resolved payloads. Pass evidence_ref to both method calls
at lines 1573 and 1575, update the method signatures of
_resolve_assertion_object_ref and _resolve_runtime_object_ref to accept the
evidence_ref parameter, and ensure they use it to consistently preserve the
original evidence reference in the resolved payloads for assertion, run,
observed-event, and context-snapshot object types. Apply the same fix pattern to
the related code sections at lines 1749-1786 and 1788-1934.

Comment thread polylogue/api/archive.py
Comment on lines +1668 to +1669
object_refs=(f"session:{session_id}", f"message:{message_id}"),
evidence_refs=() if evidence_ref is None else (evidence_ref.format(),),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Emit session-scoped message refs in object_refs to keep dereference deterministic.

Line 1668 and Line 1742 currently emit message:{message_id}. That drops session scope from the returned reference and can resolve ambiguously when the same message id exists in multiple sessions.

Suggested fix
-            object_refs=(f"session:{session_id}", f"message:{message_id}"),
+            object_refs=(f"session:{session_id}", f"message:{session_id}:{message_id}"),
@@
-            object_refs=(f"session:{payload.session_id}", f"message:{payload.message_id}", f"block:{payload.block_id}"),
+            object_refs=(
+                f"session:{payload.session_id}",
+                f"message:{payload.session_id}:{payload.message_id}",
+                f"block:{payload.block_id}",
+            ),

Also applies to: 1742-1743

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/api/archive.py` around lines 1668 - 1669, The message reference in
object_refs is emitting only message:{message_id} without session scope, which
can cause ambiguous resolution when the same message_id exists in multiple
sessions. Update the message reference on line 1668 and line 1742 to include the
session scope in the format, making it session-scoped (such as
session:{session_id}:message:{message_id} or similar) to ensure deterministic
dereferencing across multiple sessions.

Comment thread polylogue/daemon/http.py
Comment on lines +2487 to +2489
self._send_json(
HTTPStatus.BAD_REQUEST, {"error": "missing_ref", "message": "ref query parameter is required"}
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use canonical daemon error envelope for missing ref.

This branch returns a non-standard error shape ({"error","message"}), which breaks the daemon-wide error contract documented in _send_error (QueryErrorPayload envelope).

Suggested fix
-        if not ref:
-            self._send_json(
-                HTTPStatus.BAD_REQUEST, {"error": "missing_ref", "message": "ref query parameter is required"}
-            )
+        if not ref:
+            self._send_error(HTTPStatus.BAD_REQUEST, "missing_ref", "ref query parameter is required")
             return
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
self._send_json(
HTTPStatus.BAD_REQUEST, {"error": "missing_ref", "message": "ref query parameter is required"}
)
if not ref:
self._send_error(HTTPStatus.BAD_REQUEST, "missing_ref", "ref query parameter is required")
return
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@polylogue/daemon/http.py` around lines 2487 - 2489, The error response for
the missing ref query parameter uses a non-standard error shape that violates
the daemon-wide error contract. Replace the direct _send_json call with
HTTPStatus.BAD_REQUEST and the custom error object with a call to the standard
_send_error method (or equivalent canonical error envelope function documented
in QueryErrorPayload) to ensure the error response follows the established
daemon error format for consistency across all error handling.

Comment on lines +168 to +225
def test_read_direct_ref_emits_shared_resolution_payload(capsys: pytest.CaptureFixture[str]) -> None:
_, child = _context_pair()
child.obj = SimpleNamespace(polylogue=SimpleNamespace(resolve_ref=lambda ref: f"resolve:{ref}"))
wrapped_read = getattr(query_verbs.read_verb.callback, "__wrapped__", None)
assert callable(wrapped_read)
payload = PublicRefResolutionPayload(
ref="session:abc",
normalized_ref="session:abc",
kind="session",
resolved=True,
payload_kind="session-summary",
payload={"id": "abc", "title": "Resolved"},
)

with patch("polylogue.cli.query_verbs.run_coroutine_sync", return_value=payload) as run_sync:
wrapped_read(
ctx=child,
view="summary",
destination="terminal",
output_format="json",
out_path=None,
export_all=False,
message_role=(),
message_type=None,
limit=None,
offset=0,
window_hours=24,
repo_path=None,
since_hours=2,
confidence_threshold=0.3,
github_api=True,
otlp=False,
related_limit=5,
recovery_report=None,
project_path=None,
project_repo=None,
since=None,
until=None,
pack_origin=None,
pack_query=None,
max_sessions=5,
max_messages=20,
no_redact=False,
no_code_blocks=False,
no_tool_calls=False,
no_tool_outputs=False,
no_file_reads=False,
prose_only=False,
fields=None,
show_views=False,
ref="session:abc",
)

run_sync.assert_called_once()
emitted = json.loads(capsys.readouterr().out)
assert emitted["mode"] == "ref-resolution"
assert emitted["normalized_ref"] == "session:abc"
assert emitted["payload"]["id"] == "abc"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick | 🔵 Trivial | ⚡ Quick win

Add direct-ref failure-path tests for CLI contract guardrails.

This new test covers the success path only. Please add explicit assertions for UsageError on non-JSON --format and non-terminal/stdout destinations to lock Lines 350-353 behavior.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/unit/cli/test_query_verbs_runtime.py` around lines 168 - 225, The
test_read_direct_ref_emits_shared_resolution_payload function only tests the
success path for direct reference resolution. Add explicit test assertions to
verify that UsageError is raised when the wrapped_read function is called with
output_format values other than "json" or destination values other than
"terminal"/"stdout". These tests should validate the contract guardrails
enforced in lines 350-353 by calling wrapped_read with invalid
format/destination combinations and asserting that a UsageError is raised in
each case.

@Sinity
Sinity merged commit d758d33 into master Jun 19, 2026
14 checks passed
@Sinity
Sinity deleted the feature/feat/public-ref-resolution-2181 branch June 19, 2026 20:58
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(refs): resolve public object and evidence refs across CLI, API, MCP, and daemon

1 participant