# Ledger collections and record retrieval

A collection saves a named selection of ledger IDs and who may use or administer
that selection. It does not store records, saved filters or ledger permissions.
Search records or ledger definitions with optional `ledger_ids` or `collection_id`.
Omitting both searches everything readable in the selected store or tenant.
An empty ID list or both selectors is invalid. Feed still requires exactly one
explicit scope. Collections never grant access.

## Search and follow records

```python
from op_sys import OpSys

client = OpSys(connection="local")  # or an already configured hosted connection
page = client.records.search(ledger_ids=[first_ledger_id, second_ledger_id])

client.collections.create(
    collection_id=collection_id, name="Materials research",
    admins=[my_principal], read=[my_principal],
    ledger_ids=[first_ledger_id, second_ledger_id],
)
page = client.records.search(collection_id=collection_id,
                             filter={"contract_id": "observation"})
activity = client.records.feed(collection_id=collection_id, start="now")
# Later, with the same scope and filters:
activity = client.records.feed(collection_id=collection_id,
                               checkpoint=activity["checkpoint"])
```

The identifiers above refer to existing authorized ledgers and authenticated
principal subjects. Choose a collection ID of `collection_` followed by 32
lowercase hexadecimal digits. `collections.get` returns the selection visible
to the caller and an excluded count; it does not retrieve records. Updating a
collection uses `collections.update` with its current expected_revision and complete desired settings.

To discover ledger definitions first, use `ledgers.search` with exact name and
typed metadata filters, or add `query.text` for relevance. It works locally or against the selected service. For exact retrieval, page
through `next_cursor` before treating discovery as complete, then pass the chosen
ledger IDs to record retrieval or save them in a collection. See
[Find ledgers](/docs/raw/manuals/ledger-core.md#find-ledgers) for the shared CLI/SDK/MCP/HTTP contract.

`records.search` performs exact filtering by `contract_id`, `contract_version`,
`producer_id` and scalar values within the consumer-defined payload. Without `query`, it uses
bounded exact scans. Text queries use lexical and vector indexes with the same filters. Filters belong to
the request and may differ each time a collection is used. A single ledger can
be supplied as a one-element `ledger_ids` list. A producer selector is `producer_`
plus the first 32 hex digits of the SHA-256 of the canonical acceptance principal
(issuer and subject); it stays stable when the accepted record is replicated. `records.list` remains the
single-ledger snapshot operation with definition context and `changes_from`.

These operations work in the selected local store without an account, remote or
HTTP server, or in one selected service tenant. CLI, SDK and MCP use the same
contracts locally and remotely; HTTP exposes them through a reachable service.
They do not silently search across different stores, servers or tenants.

Groups and collections belong to the selected store and identity issuer. Ledger
synchronization does not copy their definitions. A collection never grants access
to its ledgers. Local permissions cannot protect files from the filesystem owner;
hosted authentication and credential scopes provide the service security boundary.

## Semantic query availability

`query.text` performs hybrid semantic and lexical search across the selected
authorized ledgers. Results use `order: relevance` and include original evidence
in `matches`. This development slice requires a provisioned search runtime and
indexing worker; automatic installation is still being implemented. An unavailable
model returns `authority_unavailable`, never an unannounced lexical fallback.

For additional ranked results, pass only `next_cursor` as `cursor` to the same
search capability. The indexed content boundary stays fixed: newly indexed records
appear in a fresh search. Replaying a cursor returns the same page while its context
remains valid. Access, source deletion, changed selections and index replacement
can require restarting; `expires_at` gives the actual deadline. Each page is ranked
among the candidates retrieved for that step, not an exact global ordering.
If indexing is incomplete and no useful result can be returned, search returns
`authority_unavailable` with retry guidance.
`continuation: limited` reports incomplete coverage or a processing limitation,
never full exhaustion. Storage/deadline limits return an actionable error. Exact
searches retain their existing cursor traversal. `query.files` accepts supported file bytes or
authorized file references, alone or with text; see [file search](/docs/raw/manuals/search-files.md)
for formats, source locations, permissions and limits. Pending indexing appears in compact `coverage`.

For example: `client.records.search(query={"text": "evidence about corrosion prevention"}, limit=10)`.
 Empty or blank queries are invalid. Existing
file references use `{ledger_id, file_id}` and require independent `files.read`;
record access alone does not grant access to attachment contents. JSON file inputs
use `{name, media_type, bytes_base64}`, never a server filesystem path. Input bytes
are bounded to 8 MiB total. Exact requests omit `query` and need no model.

## Match payload fields

Search and feed accept the same `filter`. Every metadata filter and payload
condition must match (AND):

```python
predicate = {"payload": [
    {"path": ["reference_id"], "eq": "example-42"},
    {"path": ["details", "confirmed"], "eq": True},
]}
page = client.records.search(ledger_ids=[first_ledger_id], filter=predicate)
activity = client.records.feed(ledger_ids=[first_ledger_id],
                               filter=predicate, start="now")
```

`path` is a sequence of literal object keys and array indexes. For example,
`["items", 0, "code"]` selects the first item's code. A string `"0"` selects an
object key; the integer `0` selects an array position. Dots and slashes in keys
are literal. There are no wildcards or implicit array traversal. An empty path
`[]` selects the whole payload, useful for records whose payload is a scalar.

`eq` accepts a string, number, boolean or null, not an object or array. Types are
never coerced: `false`, `0` and `"0"` are distinct. Numbers use the shared JSON
binary64 representation (`1` equals `1.0`; `-0` equals `0`). Strings are exact,
case-sensitive and not Unicode-normalized. Missing paths never match, including
against null; null matches only an explicitly stored null. Only the payload's
own object keys are traversed.

Supply 1–8 conditions when including `filter.payload`; omit it for no payload
restriction. Each path has at most 16 segments, each string key at most 256
characters, and array indexes range from 0 to 9,999. Equality strings have a
4,096-character limit. The complete filter is limited to 65,536 canonical UTF-8
bytes. Unsupported operators and malformed paths return `invalid_input`;
oversized filters return `limit_exceeded`.

Search cursors restore the original filters; conflicting inputs are invalid.
Feed requires the original scope, filter and limit with each checkpoint. Exact filtering happens only
after authorization, within the existing per-page scan bounds. A selective
filter may return an empty page with a continuation; follow it to finish the
search. Erased payloads cannot be evaluated: they remain `availability="purged"`,
`match="unknown"` markers with incomplete coverage, rather than false matches or
silently omitted history.

## Equivalent interfaces

```sh
op-sys --connection team records search --ledger-ids '["ledger_<32-hex-id>"]'
op-sys --connection team records search --collection-id collection_<32-hex-id>
op-sys --connection team records feed --collection-id collection_<32-hex-id> --start now
op-sys --connection team records search --ledger-ids '["ledger_<32-hex-id>"]' --filter '{"payload":[{"path":["reference_id"],"eq":"example-42"}]}'
```

MCP uses `op_sys_records_search` and `op_sys_records_feed` with the same input
fields. HTTP uses `POST /v1/records/search` and `POST /v1/records/feed` with a JSON
body and the usual authenticated tenant selection. For example:

```json
{"collection_id":"collection_<32-hex-id>","filter":{"payload":[{"path":["reference_id"],"eq":"example-42"}]},"limit":25}
```

Collections themselves use `collections.create/get/list/update/delete`, MCP `op_sys_collections_create/get/list/update/delete`
and POST/GET/PUT/DELETE `/v1/collections/{collection_id}`, plus GET `/v1/collections`. There are no collection query/feed
methods or HTTP routes. Groups remain authorization resources; their IDs are
not retrieval scopes.

## Pagination, authorization and coverage

Exact search returns a bounded snapshot. Pass only `next_cursor` as `cursor`
in the same configured environment; Veylar restores the original scope, filters
and page size. Check `continuation` (`available` or `exhausted`) as well as the token. New records are excluded from that
snapshot. An empty filtered page can still have a continuation. Feed returns a
renewable `checkpoint` and `caught_up`; preserve the checkpoint to retrieve later
activity. `start="now"` begins at the current head, while `start="beginning"`
includes retained history. A search cursor cannot be used as a feed checkpoint.

Every request checks credential scope, raw-data access, each ledger's current
permissions and authority availability. A collection grants no ledger access.
Search reports compact `coverage.status` (`complete`, `partial`, or `unknown`),
`observed_at` and bounded `reasons`. Exact coverage concerns retained history,
not semantic-index readiness. Results preserve authoritative acceptance and their
individual observations. An explicit inaccessible or absent ledger returns the
same `permission_denied`; a collection silently omits unreadable members without
exposing their IDs or counts. Feed retains its existing included IDs, excluded
count, unavailable-history count and per-ledger observations. Authorities and completed replicas can both contribute retained
accepted records. Store sequence orders retrieval entries, not admissions across
independent authorities. A replica feed being `caught_up` means caught up to its
retained data, not to an unreachable remote authority.
Erased records have a reference and `availability="purged"`, without their
payload. Never treat excluded or unavailable history as an empty ledger.

Cursors bind the scope, principal, issuer, selected store/tenant, filters, limit and effective
access. A changed collection, ledger policy, group revision, authority boundary or replica
generation invalidates the
continuation; start a fresh search/feed and reconcile coverage rather than
assuming the old stream is complete. Expired or mismatched tokens are errors.

Bounds: at most 4,096 explicitly supplied ledger IDs, 25 returned items and 250
scanned entries per exact-search page. Ranked search explores indexed candidates
independently of the returned page size. Omitting search scope is not a 4,096-ledger corpus cap. Exact-search snapshots last 15 minutes; feed checkpoints renew for seven
days. These are accepted records; local pending submissions are excluded.

## Read multiple pages and resume later

The SDK provides `records.search_pages()` and `records.feed_pages()` as convenience
iterators over the same search/feed operations. They yield complete pages,
including empty pages and coverage metadata. Each call fetches only when you
advance the iterator; it does not prefetch, retry errors or restart invalid tokens.

```python
scope = {"ledger_ids": [first_ledger_id], "filter": predicate, "limit": 25}
cursor = None  # Or the last cursor saved after successful page processing.
for page in client.records.search_pages(**scope, cursor=cursor, max_pages=20):
    print("Coverage:", page["coverage"])
    for item in page["items"]:
        print(item["reference"], item["availability"], item["match"])
    cursor = page["next_cursor"]  # Save only after processing this page.
if cursor is not None:
    print("Page budget reached; resume with this cursor and unchanged scope.")
```

Both helpers default to 100 pages and accept `max_pages` from 1 to 10,000.
Reaching the budget does not mean retrieval is complete. Search finishes only
when `next_cursor` is null. Feed finishes the current catch-up when `caught_up`
is true; it never waits indefinitely for new records.

```python
head = client.records.feed(**scope, start="now")
checkpoint = head["checkpoint"]
# Later, after other participants have contributed:
for page in client.records.feed_pages(**scope, checkpoint=checkpoint, max_pages=20):
    print("Coverage:", page["coverage"])
    for item in page["items"]:
        print(item["reference"], item["availability"], item["match"])
    checkpoint = page["checkpoint"]  # Persist after processing, including empty pages.
    caught_up = page["caught_up"]
```

To include existing history instead, initially call `feed_pages(start="beginning",
...)`. When resuming, provide `checkpoint` and omit `start`. A helper clears
`start` automatically after its first page. Helpers copy scope/filter inputs when
iteration begins; changing those inputs requires a new retrieval. Keep the same
client connection, tenant and identity throughout an iteration.

Search and feed have separate continuations. To establish a baseline and follow
new contributions without a handoff gap, capture a feed checkpoint with `start="now"`
**before** starting the search, complete the search, then follow that checkpoint.
Records may appear in both; deduplicate by their selected destination, ledger and record IDs.
Persist progress durably according to your application's needs. These helpers
do not acknowledge work or promise exactly-once application processing.

### The same continuation through CLI, MCP and HTTP

The CLI human output summarizes matches, unavailable records, coverage and progress.
Use JSON for the complete result, payloads and tokens. For example, run search
with `--output json`, then copy `payload.next_cursor` into `--cursor`:

```sh
op-sys --connection team --output json records search --ledger-ids '["ledger_<32-hex-id>"]' --filter '{"payload":[{"path":["reference_id"],"eq":"example-42"}]}' --limit 25
op-sys --connection team --output json records search --cursor '<next_cursor from the previous result>'
```

MCP calls `op_sys_records_search` with the cursor-only continuation:

```json
{"cursor":"<next_cursor from the previous result>"}
```

Read the page from MCP `result.structuredContent`. HTTP sends that same JSON body
to `POST /v1/records/search` with normal authentication and tenant selection;
the response body is the page itself. The first request omits `cursor`.

| Retrieval | CLI | MCP tool | HTTP endpoint | Resume field |
| --- | --- | --- | --- | --- |
| Snapshot search | `records search` | `op_sys_records_search` | `POST /v1/records/search` | `next_cursor` → `cursor` / `--cursor` |
| Accepted activity | `records feed` | `op_sys_records_feed` | `POST /v1/records/feed` | `checkpoint` → `checkpoint` / `--checkpoint` |

On every surface, process each page and inspect coverage, retain its continuation,
and resume search with only its cursor, or feed with unchanged scope, filter and limit. Empty `items` is not a stopping
condition: search ends at a null cursor; feed is caught up when `caught_up=true`.
CLI and MCP do not need separate pagination capabilities: ordinary calls expose
the same tokens and behavior used by the SDK helpers.

### Recover when access or selection changes

An invalid or expired token, or one whose scope, filter, limit or identity no
longer matches, returns `record_cursor_invalid`. Changed effective permissions or
selection history return `record_selection_changed`. Losing access
to a collection itself can return `permission_denied`. SDK helpers propagate these
errors, CLI reports an error and exits nonzero, and MCP/HTTP return the structured
error. None silently restarts from a new head.

Inspect the error and current access or collection settings first. When appropriate,
start a fresh search, or feed from `beginning`, and reconcile already processed
record references. Incremental sync within a replica generation preserves feed
continuation. A revoked ledger can now be excluded even if the request itself
succeeds. Feed reports `coverage.excluded_count`; search does not disclose hidden
collection membership. An explicitly selected ledger that loses access returns
`permission_denied`. Starting from `now` deliberately skips
earlier activity and is not a lossless recovery strategy. Do not treat exclusion
or unavailable history as proof that no records exist.

## Find and remove saved selections

```python
page = client.collections.list(limit=25)
while True:
    for collection in page["items"]:
        print(collection["collection_id"], collection["name"], collection["revision"])
    if page["next"] is None:
        break
    page = client.collections.list(limit=25, continuation=page["next"])

current = client.collections.get(collection_id=collection_id)
client.collections.delete(collection_id=collection_id,
                          expected_revision=current["revision"])
```

```sh
op-sys --connection team collections list --limit 25
op-sys --connection team collections delete --collection-id collection_<32-hex-id> --expected-revision 1
```

Listing returns ID, name and revision for collections you may read, including
access through a group. It requires a read-capable credential with raw-data
access, just like `collections.get`. It discloses no hidden ledger IDs or resource
access settings and grants no ledger access. Use `collections.get` to resolve
the currently authorized ledger selection.

Listing is a live directory ordered by collection ID, not a snapshot. Every
page checks current permissions. Concurrent additions before your continuation
may require restarting the listing. Pass `next` as `continuation` with the same
limit, identity, tenant and credential policy; null ends the listing. An empty
page may still have a continuation. Pages return up to 100 entries (25 by default)
and scan at most 250 candidates; cursors expire after 15 minutes. Inspect JSON
output for the continuation token.

Deletion requires an admin-capable credential, collection administrator access
and the current `expected_revision`. Concurrent updates reject a stale deletion;
read the collection again and reconsider before retrying with its new revision.
Only the saved selection is removed: its ledgers, records and ledger grants remain
unchanged. An identical authorized retry returns the same deletion result. Deleted
IDs cannot be recreated or updated; create a new ID for a new collection. Retrieval
through the deleted collection fails, including existing record search/feed
continuations; explicit authorized ledger retrieval continues to work.
