Repository navigation
feat(refs): resolve public archive refs (#2181) - #2194
Conversation
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.
|
Warning Review limit reached
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 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughImplements a ChangesPublic Ref Resolution Feature
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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: 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".
| try: | ||
| session_id = archive.resolve_session_id(object_ref.object_id) | ||
| except KeyError: |
There was a problem hiding this comment.
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 👍 / 👎.
| summary_offset = 0 | ||
| while True: | ||
| summaries = archive.list_summaries(limit=200, offset=summary_offset) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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 winDocument direct-ref output constraints in this command section.
read [REF]currently only allows--format jsonand--to terminal|stdout(enforced inpolylogue/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
📒 Files selected for processing (18)
docs/cli-reference.mddocs/search.mdpolylogue/api/archive.pypolylogue/cli/commands/status.pypolylogue/cli/query_verbs.pypolylogue/daemon/http.pypolylogue/daemon/route_contracts.pypolylogue/mcp/payloads.pypolylogue/mcp/server_tools.pypolylogue/surfaces/payloads.pytests/infra/mcp.pytests/unit/api/test_facade_contracts.pytests/unit/cli/__snapshots__/test_plain_cli_snapshots.ambrtests/unit/cli/test_query_verbs_runtime.pytests/unit/daemon/test_web_reader.pytests/unit/mcp/test_envelope_contracts.pytests/unit/mcp/test_server_surfaces.pytests/unit/mcp/test_tool_discovery.py
| 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) |
There was a problem hiding this comment.
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.
| object_refs=(f"session:{session_id}", f"message:{message_id}"), | ||
| evidence_refs=() if evidence_ref is None else (evidence_ref.format(),), |
There was a problem hiding this comment.
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.
| self._send_json( | ||
| HTTPStatus.BAD_REQUEST, {"error": "missing_ref", "message": "ref query parameter is required"} | ||
| ) |
There was a problem hiding this comment.
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.
| 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.
| 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" |
There was a problem hiding this comment.
🧹 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.
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
PublicRefResolutionPayloadinstead 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
PublicRefResolutionPayloadandRefResolutionActionPayloadinpolylogue.surfaces.payloads.Polylogue.resolve_ref(...)for session, message, block, assertion, run, observed-event, and context-snapshot refs, including EvidenceRef projection to the nearest object payload.polylogue read REF --format json,resolve_ref,GET /api/refs/resolve?ref=...,Polylogue.resolve_ref(...).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
polylogue read [REF]), HTTP API, Python API, and MCP interfacesDocumentation