diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b224094ef6b..542981d8e9d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1151,6 +1151,7 @@ jobs: run: >- pytest -q tests/integration/test_pg_authority.py + tests/integration/test_mcp_worker_pg_fence.py tests/integration/test_pg_durable_publish.py tests/integration/test_pg_pipeline_metrics.py tests/integration/test_knowledge_pg_heads.py diff --git a/docs/architecture/mcp-source-worker-boundary.md b/docs/architecture/mcp-source-worker-boundary.md new file mode 100644 index 00000000000..17b479826a3 --- /dev/null +++ b/docs/architecture/mcp-source-worker-boundary.md @@ -0,0 +1,184 @@ +# Document source worker boundary + +Loom reads one selected document live through an operator-provisioned source worker +that holds the upstream credential; this page states that boundary and what stored +copies and refresh still require. + +Loom serves stored document search and explicit live document reads through its +existing MCP endpoint. Stored search reads indexed copies. A live read asks an +approved source worker to read one selected resource under the current caller's +connection. It returns the source link and fetch time. It does not index the +result, save it as a memory or record its body as a diagnostic. The client that +receives the result controls what it retains. + +The source worker owns upstream credentials, outbound MCP requests and account +consent. Loom owns source configuration, schedules, access policy, selected +copies and their normal erasure lifecycle. Loom stores opaque worker and +connection identifiers, their generations and the approved profile digest. The +worker resolves the connection within its own credential authority. Neither side +uses the other side's credential at the upstream endpoint. + +Enrollment matches a short worker-signed statement to a challenge issued for +the authenticated owner and current approved profile. The statement contains +opaque connection metadata only. Loom verifies the worker's separate enrollment +key, consumes the challenge with the link write, and never uses an enrollment +statement to authorize a read. A newer connection generation replaces older +authority without erasing a copy or moving it to another account. + +## Worker provisioning + +The operator mounts a worker routes file and sets +`LOOM_KNOWLEDGE_SOURCE_WORKER_ROUTES_FILE` to its path. An empty setting leaves the +worker directory disabled. Live reads and worker metadata also require Postgres +knowledge authority so the store that serves the metadata erases it. Version 1 of the +JSON file contains a `workers` list. Each entry names a `worker_id`, HTTPS `origin`, +grant `issuer`, and a `profiles` map from exact organization names to profile entries. +Each entry lists a `digest`, approved `modes`, and optional `team_access`. A +collection approval cannot add an organization, profile, mode or team permission that +the operator did not allow. + +The `trust_ca_file`, `client_certificate_file` and `client_key_file` entries +configure mutual TLS. `grant_key_file` names Loom's Ed25519 key for signing +requests. `enrollment_verifier_file`, when present, names the worker's separate +public Ed25519 key. File paths are relative to the routes file or absolute. These +files authenticate communication between Loom and the worker. The operator does +not put upstream credentials or upstream endpoint configuration in this file. + +A worker source uses the existing source registry. Its versioned configuration +contains opaque identifiers and generations. The items hold exact selected resource +identities. No new ClickHouse table or upstream credential is needed. A worker source +has kind `mcp`, which is not one of the native kinds, and mirrored access; a build +that serves only shared namespace-access sources skips it. The release must qualify +mixed builds before enabling worker registration or copy writes. + +## Binding a live read + +Loom proves the current caller and collection grant, finds the exact selected +resource and resolves the caller's approved worker connection. It signs a short +read grant for that worker. The grant binds the request, operation, organization, +namespace, source and selection generation, requester, connection and its +generation, profile digest and exact resource identity. The grant is for the +worker audience. It carries no credential, URL or tool arguments. The worker +accepts grants only from its configured Loom issuer and resolves that exact +connection with matching ownership and profile. It rejects an anonymous caller +or a grant for another worker, owner, organization, connection or generation. +For a team source, the reader enrolls a specific connection for the current +selection. A different connection for the same endpoint or profile cannot +stand in for it. The owner and reader connections must share a verified resource +realm before the reader can request access to the selected identity. + +The worker validates the current connection before upstream use and before return. +Loom checks current source, selection, connection and reader standing again before +delivering a result. During each frame handoff, Loom holds the namespace's Postgres +source lock shared, rereads the source row with sequential consistency and refuses the +frame if it differs at all from the row the frame's authority check read, and locks +the exact approval, account and team link rows. Every source write holds that lock +exclusively alongside its source lease, so a retirement or update that commits before +the handoff withholds the frame. Live reads of one collection share the lock, and +Postgres queues a new frame behind a waiting write, so a write waits only for the +frames already running. No upstream call happens while these locks are held. A frame +holds one pooled Postgres connection while it waits for the shared lock and sends, and +a source write holds one for as long as its source lease, so a burst of live reads +behind a write can use up to the replica's pool for at most the frame deadline. If a +holder's host disappears, Postgres drops its session over TCP keepalives, so for about +a minute source writes of that collection answer `overloaded` and its live reads wait +out their frame deadline and are refused; the keepalives apply only to TCP sessions, +not to a Unix socket. A Postgres outage in the lookups before the response, or in a +source write's lock, answers 503; one during a frame's handoff withholds the response. +A build without the lock takes only the source lease when it writes, so during a +rolling upgrade a retirement from such a replica can let the one frame already past +its reread through; the next frame's reread stops the response. + +`knowledge.source.live` is experimental. It requires a protected session with a +namespace-scoped token, an approved route, and a current source selection. It refuses +tokens restricted to one user or session. Registration remains disabled, so this +prerequisite does not enable user setup on its own. A live request lives with its API +request. It has a separate read deadline and admission limit from refresh work, a +bounded delivery budget after the read, and no durable payload queue. Loom checks the +size of the document before publication. Document text is limited to 4,000,000 UTF-8 +bytes, and the encoded document with its escaped MCP text copy to 16 MiB. A document +beyond either limit returns `unsupported` with no document. Delivery rechecks +authority for each 512 KiB chunk within the publication deadline. When that deadline +passes during delivery, the client gets a truncated response after the status line, +not `timeout`. A slow client, slow authority reads, a source write holding the source +lock, or a revocation between chunks can each cause it. The transports also reject +echoed argument names and MCP request IDs that exceed their size limits or cannot be +encoded as UTF-8. Loom returns ignored argument names to the caller without logging or +caching them. Denial, reconnect, saturation, unavailable and timeout remain distinct +outcomes. Team viewers without current source enrollment see the same denial for +selected and unselected IDs. Every refusal returns the explicit status, never a stored +copy. + +Each worker resolves approved profiles to its own endpoint and read mappings. +Resource reads and validated tool reads share the same bounds. Caller input and +server descriptions cannot expand the accepted operations or outbound addresses. +Returned data is evidence for the requested resource only. An account host can +implement this worker contract locally if it can resolve the exact requester +and connection for the requested operation without an active agent session or +credential export. An agent's own integration does not establish that authority. + +## Account enrollment + +An authenticated owner selects an externally provisioned connection. Loom +issues a short challenge for its exact organization, owner, worker, profile, +nonce, opaque connection ID and generation. The worker has a separate key for +signing its statement about the current account. Neither the challenge nor the +statement includes the token or endpoint. Loom verifies the statement and +checks approval again under the same store locks as it consumes the challenge. +A retired generation cannot be restored by replaying a proof. Team readers +still enroll their own accounts separately for the selected source. + +The Postgres enrollment records contain only scoped identity, provenance, +bindings, generation and expiry. Expired challenges can be removed in bounded +batches. Account revocation retains its generation fence until erasure. Enable +writes only when owner erasure and worker approval take the same authority +locks and every runnable eraser covers these tables. + +## Requirements for stored copies + +Worker copy writes and stored read authorization are not connected. Before they +are, imports must use the existing original, document, chunk, extraction, indexing and +accounting paths. The identity of a copy is its source UUID and the exact scoped +resource identity. A display link is provenance only. The copy's stable source +URI is never an outbound fetch target. Refresh must retain the copy identity while +updating content or receipt time. + +Team collection membership is only one requirement. A reader also needs current +upstream permission evidence for their own connection to the exact resource. +Evidence binds the reader, collection, source and selection generation, worker, +connection generation, resource identity and expiry. An import receipt from one +reader cannot authorize another. Missing, expired, denied or disconnected +evidence fails closed. Evidence from reading current content cannot establish +access to historical content unless the approved upstream contract covers it. +Apply the same check to search, direct reads, originals, contextual results and +publication. Derived memory and cached results must not extend access. + +## Requirements for refresh and retirement + +The runtime does not schedule refresh or accept worker uploads. Before it does, Loom +must schedule and claim bounded refresh jobs. Each claim targets one worker and +the approved source revision, with a lease and a monotonically fenced attempt. +The worker must upload an idempotent completion for the exact claim. The server +must check the fence, deadline, registration and current connection before +accepting writes and advance the checkpoint only for an accepted result. “Sync now” +requests the same work as a schedule. Interruptions leave copies and originals +intact; stale completion does not renew permission or replace a copy. Partial +pages, missing items, timeouts and ambiguous errors do not prove deletion. + +The refresh metadata queue must remain separate from ingestion jobs. It must +leave ingestion fairness and extractor scheduling intact. Postgres must commit +the accepted receipt with the document head and its delivery obligation. Index +delivery can recover after that commit. A deployment without Postgres knowledge +authority refuses worker refresh; ordinary ingestion still follows its configured +store. Install the queue schema and its erasure support before allowing writes, +and admit work only when every runnable eraser can remove the queue's rows. + +Disconnect must invalidate live reads, claims and permissions without erasing +stored bytes. The existing erasure pipeline handles a separate deletion request. Older +builds must retain opaque registrations and must fail closed on worker-authorized +copies. Keep manual import available throughout the transition. A native source +keeps its stored copies, provenance and originals through upgrade. Reuse a copy +identity only when the owner authorizes a replacement connection and the old and +new resource identities have a verified one-to-one binding. An unmapped copy +keeps its old address and erasure history. Deployment requires compatible builds, +an approved worker binding and a separate operator cutover. diff --git a/docs/architecture/storage-layout.md b/docs/architecture/storage-layout.md index d75215d75a6..864b6025987 100644 --- a/docs/architecture/storage-layout.md +++ b/docs/architecture/storage-layout.md @@ -1209,6 +1209,10 @@ Postgres step the flip splits off it, which joins `PG_ONLY_STEPS` | `document_catalog`, `document_uploaders` | `(org, namespace, sha256)`, `(org, user_id, namespace, sha256)` | SoR | a `pg:` census row each, owned by the Postgres step the flip splits off the steps that own the census rows of `document_blobs` and `blob_uploads` today, which joins `PG_ONLY_STEPS` (`documents.tombstone`, and the user step through `document_uploaders`) | | `knowledge_datasets` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_datasets`, step `pg_knowledge.delete` | | `knowledge_jobs` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_jobs`, step `pg_knowledge.delete` | +| `mcp_worker_enrollment_challenges` | `(org, nonce)` | SoR | One time account enrollment challenges; erased with the owner or collection. Census `pg:loom.mcp_worker_enrollment_challenges`, step `pg_knowledge.delete`. | +| `mcp_worker_accounts` | `(org, connection_id)` | SoR | Opaque connection bindings and revocation generations; erased with the owner or collection. Census `pg:loom.mcp_worker_accounts`, step `pg_knowledge.delete`. | +| `mcp_worker_approvals` | `(org, namespace, worker_id, profile_digest)` | SoR | Allowed modes and approval generations; erased with the approving administrator or collection. Census `pg:loom.mcp_worker_approvals`, step `pg_knowledge.delete`. | +| `mcp_worker_source_readers` | `(org, namespace, source_id, user_id)` | SoR | Explicit team reader bindings; erased with the reader or collection. Census `pg:loom.mcp_worker_source_readers`, step `pg_knowledge.delete`. | | `knowledge_heads`, `knowledge_deliveries` | [storage authority](storage-authority.md#the-tables) | SoR | census `pg:loom.knowledge_heads`, `pg:loom.knowledge_deliveries` | | `jobs`, `job_users`, `job_memories` | `(org, id)`, `(org, user_id, job_id)`, `(org, namespace, memory_id, job_id)` | SoR | a census row, a step by namespace and user, a redaction step | | `leases`, `write_marks`, `graph_inflight` | `(org, name)`, `(org, namespace, surface)`, `(org, namespace, token)` | Coord | no content | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index d7c2add7413..c5af32edd0a 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1044,6 +1044,11 @@ Knowledge documents and conversations: chunking, search floor, thread titles. | `LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED` | `bool` | `False` | | The knowledge_source_sync worker: pulls each registered document source's changed files into its namespace's documents. Off by default: it needs each source's credential, spends embedding calls on every changed document and model calls mining it for decisions. | | `LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED` | `bool` | `True` | live | Off refuses knowledge.source.add and rotate (SELF_SERVICE_OFF). Connected-account OAuth is separate: it stays on for each provider whose connect_*_client_id is set. | | `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED` | `bool` | `False` | | Require protected automatic session capture and persist deployment privacy state. Off does not lift protection while the deployment latch remains set. | +| `LOOM_KNOWLEDGE_SOURCE_WORKER_ROUTES_FILE` | `str` | `''` | | Path to the operator's source worker routes file. Empty disables the worker directory. | +| `LOOM_KNOWLEDGE_SOURCE_WORKER_LIVE_TIMEOUT_S` | `float` | `8.0` | | Seconds a live read may spend on authority checks and its worker request. At most 8, the default: a value can only shorten it. | +| `LOOM_KNOWLEDGE_SOURCE_WORKER_PUBLICATION_TIMEOUT_S` | `float` | `2.0` | | Seconds reserved after a live read for accounting and delivery. At most 2, the default: a value can only shorten it. | +| `LOOM_KNOWLEDGE_SOURCE_WORKER_FRAME_TIMEOUT_S` | `float` | `1.0` | | Seconds one response frame may spend acquiring authority locks and sending. At most 1, the default; the remaining publication deadline can shorten it further. | +| `LOOM_KNOWLEDGE_SOURCE_WORKER_SELECTION_PARALLELISM` | `int` | `2` | | Concurrent worker access checks when proving a selection for setup. | | `LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS` | `int` | `3600` | | Mirrored reads require a complete listing and group observation within this many seconds; missing or older evidence admits nobody. | | `LOOM_KNOWLEDGE_SOURCE_ACL_MAX_ENTRIES` | `int` | `10000` | | Maximum team and member rows read for one project's complete permission list. A larger list refuses publication rather than granting from a partial page. | | `LOOM_KNOWLEDGE_SOURCE_PUSH_ENABLED` | `bool` | `False` | | Enable optional source push setup, callbacks and Drive renewal; false keeps polling only. | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 5f1766dd5f7..afde9b1e5a7 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -123,7 +123,7 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal -379 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +380 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). Columns: **Role** is the minimum role (`viewer` < `writer` < `admin` < `org_admin` < `platform_admin`); **Kind** is `read` (idempotent, viewer, unaudited, writes nothing — MCP `readOnlyHint`), `idempotent` (safe to retry) or `write`; **Listed under `all`** says whether an MCP connection on the `all` toolset lists the op in `tools/list` (`code.*` ops only with `LOOM_MCP_CODE_TOOLS=true`); an op marked `no` is still callable by name or through `loom_op`, unless it is hidden from MCP; **Audit** marks ops that leave an `audit_log` row. @@ -449,6 +449,7 @@ Fields for every `knowledge` op: [operations/knowledge.md](operations/knowledge. | [`knowledge.source.check`](operations/knowledge.md#knowledgesourcecheck) | Probe a registered document source with its stored credential now (a check of every item, or of the 20 added last, and a listing), nothing written. | writer | idempotent | no | | | [`knowledge.source.inspect`](operations/knowledge.md#knowledgesourceinspect) | One registered document source: its items, its sync state and the documents it wrote (the 200 most recently ingested). | viewer | read | no | | | [`knowledge.source.list`](operations/knowledge.md#knowledgesourcelist) | The document sources registered on a namespace, with each one's sync state. | viewer | read | no | | +| [`knowledge.source.live`](operations/knowledge.md#knowledgesourcelive) | Read one selected resource through the caller's current worker connection. | viewer | read | no | | | [`knowledge.source.parse_links`](operations/knowledge.md#knowledgesourceparse_links) | Read pasted links as a source's items, with no request to any store and nothing written: each link answers its kind and item, or why it is unreadable. | viewer | read | no | | | [`knowledge.source.push_configure`](operations/knowledge.md#knowledgesourcepush_configure) | Enable provider sync hints for an existing source, or disable its setup. | admin | write | no | yes | | [`knowledge.source.push_confirm`](operations/knowledge.md#knowledgesourcepush_confirm) | Activate the exact pending setup. | admin | write | no | yes | diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 1a4f72d5f16..9cccb2be105 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -708,6 +708,24 @@ The document sources registered on a namespace, with each one's sync state. | `accepts_sources` | `bool` | False where add would refuse the namespace (PERSONAL_NAMESPACE, NAMESPACE_INACTIVE). | | `self_service` | `bool` | Whether knowledge.source.add and rotate answer on this deployment (LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED); the page offers neither when false. | +## `knowledge.source.live` + +Read one selected resource through the caller's current worker connection. + +`POST /v1/knowledge.source.live` · MCP `loom_knowledge_source_live` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | Organization that owns the collection. | +| `namespace` | `str` | required | Collection that owns the source. | +| `name` | `str` | required | Name of the registered source in the collection. | +| `resource_id` | `str` | required | Exact selected resource identifier returned by source setup. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `status` | `Literal['ok', 'denied', 'reconnect', 'overloaded', 'timeout', 'unavailable', 'unsupported']` | One of ok, denied, reconnect, overloaded, timeout, unavailable or unsupported; only ok carries a document, and only overloaded and timeout are worth retrying. denied: no current access to this selected resource. reconnect: the caller's… | +| `document` | `KnowledgeSourceLiveDocument \| None` | The document when `status` is `ok`. | + ## `knowledge.source.parse_links` Read pasted links as a source's items, with no request to any store and nothing written: each link answers its kind and item, or why it is unreadable. diff --git a/docs/reference/status.md b/docs/reference/status.md index f24f3ad1b48..c75d24a9f04 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -379 operations, 265 of them experimental. +380 operations, 266 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -51,7 +51,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `help` | 0 | [`help.get`](operations/help.md#helpget), [`help.search`](operations/help.md#helpsearch) | | `inbox` | 0 | [`inbox.list`](operations/inbox.md#inboxlist), [`inbox.policy_list`](operations/inbox.md#inboxpolicy_list), [`inbox.policy_set`](operations/inbox.md#inboxpolicy_set), [`inbox.principals`](operations/inbox.md#inboxprincipals), [`inbox.register`](operations/inbox.md#inboxregister) | | `insights` | 0 | [`insights.catalog`](operations/insights.md#insightscatalog), [`insights.query`](operations/insights.md#insightsquery) | -| `knowledge` | 5 | [`knowledge.bulk_delete`](operations/knowledge.md#knowledgebulk_delete), [`knowledge.dataset_approve`](operations/knowledge.md#knowledgedataset_approve), [`knowledge.dataset_get`](operations/knowledge.md#knowledgedataset_get), [`knowledge.dedup_list`](operations/knowledge.md#knowledgededup_list), [`knowledge.dedup_resolve`](operations/knowledge.md#knowledgededup_resolve), [`knowledge.delete`](operations/knowledge.md#knowledgedelete), [`knowledge.formats`](operations/knowledge.md#knowledgeformats), [`knowledge.gaps.draft`](operations/knowledge.md#knowledgegapsdraft), [`knowledge.gaps.list`](operations/knowledge.md#knowledgegapslist), [`knowledge.ingest`](operations/knowledge.md#knowledgeingest), [`knowledge.ingest_cancel`](operations/knowledge.md#knowledgeingest_cancel), [`knowledge.ingest_status`](operations/knowledge.md#knowledgeingest_status), [`knowledge.inspect`](operations/knowledge.md#knowledgeinspect), [`knowledge.move`](operations/knowledge.md#knowledgemove), [`knowledge.outline`](operations/knowledge.md#knowledgeoutline), [`knowledge.query`](operations/knowledge.md#knowledgequery), [`knowledge.query_history.add`](operations/knowledge.md#knowledgequery_historyadd), [`knowledge.query_history.list`](operations/knowledge.md#knowledgequery_historylist), [`knowledge.query_history.remove`](operations/knowledge.md#knowledgequery_historyremove), [`knowledge.reads`](operations/knowledge.md#knowledgereads), [`knowledge.restore`](operations/knowledge.md#knowledgerestore), [`knowledge.source.add`](operations/knowledge.md#knowledgesourceadd), [`knowledge.source.check`](operations/knowledge.md#knowledgesourcecheck), [`knowledge.source.inspect`](operations/knowledge.md#knowledgesourceinspect), [`knowledge.source.list`](operations/knowledge.md#knowledgesourcelist), [`knowledge.source.parse_links`](operations/knowledge.md#knowledgesourceparse_links), [`knowledge.source.push_configure`](operations/knowledge.md#knowledgesourcepush_configure), [`knowledge.source.push_confirm`](operations/knowledge.md#knowledgesourcepush_confirm), [`knowledge.source.push_status`](operations/knowledge.md#knowledgesourcepush_status), [`knowledge.source.remove`](operations/knowledge.md#knowledgesourceremove), [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate), [`knowledge.source.sync_now`](operations/knowledge.md#knowledgesourcesync_now), [`knowledge.source.update`](operations/knowledge.md#knowledgesourceupdate), [`knowledge.synthesize`](operations/knowledge.md#knowledgesynthesize), [`knowledge.update_metadata`](operations/knowledge.md#knowledgeupdate_metadata), [`knowledge.upsert`](operations/knowledge.md#knowledgeupsert) | +| `knowledge` | 5 | [`knowledge.bulk_delete`](operations/knowledge.md#knowledgebulk_delete), [`knowledge.dataset_approve`](operations/knowledge.md#knowledgedataset_approve), [`knowledge.dataset_get`](operations/knowledge.md#knowledgedataset_get), [`knowledge.dedup_list`](operations/knowledge.md#knowledgededup_list), [`knowledge.dedup_resolve`](operations/knowledge.md#knowledgededup_resolve), [`knowledge.delete`](operations/knowledge.md#knowledgedelete), [`knowledge.formats`](operations/knowledge.md#knowledgeformats), [`knowledge.gaps.draft`](operations/knowledge.md#knowledgegapsdraft), [`knowledge.gaps.list`](operations/knowledge.md#knowledgegapslist), [`knowledge.ingest`](operations/knowledge.md#knowledgeingest), [`knowledge.ingest_cancel`](operations/knowledge.md#knowledgeingest_cancel), [`knowledge.ingest_status`](operations/knowledge.md#knowledgeingest_status), [`knowledge.inspect`](operations/knowledge.md#knowledgeinspect), [`knowledge.move`](operations/knowledge.md#knowledgemove), [`knowledge.outline`](operations/knowledge.md#knowledgeoutline), [`knowledge.query`](operations/knowledge.md#knowledgequery), [`knowledge.query_history.add`](operations/knowledge.md#knowledgequery_historyadd), [`knowledge.query_history.list`](operations/knowledge.md#knowledgequery_historylist), [`knowledge.query_history.remove`](operations/knowledge.md#knowledgequery_historyremove), [`knowledge.reads`](operations/knowledge.md#knowledgereads), [`knowledge.restore`](operations/knowledge.md#knowledgerestore), [`knowledge.source.add`](operations/knowledge.md#knowledgesourceadd), [`knowledge.source.check`](operations/knowledge.md#knowledgesourcecheck), [`knowledge.source.inspect`](operations/knowledge.md#knowledgesourceinspect), [`knowledge.source.list`](operations/knowledge.md#knowledgesourcelist), [`knowledge.source.live`](operations/knowledge.md#knowledgesourcelive), [`knowledge.source.parse_links`](operations/knowledge.md#knowledgesourceparse_links), [`knowledge.source.push_configure`](operations/knowledge.md#knowledgesourcepush_configure), [`knowledge.source.push_confirm`](operations/knowledge.md#knowledgesourcepush_confirm), [`knowledge.source.push_status`](operations/knowledge.md#knowledgesourcepush_status), [`knowledge.source.remove`](operations/knowledge.md#knowledgesourceremove), [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate), [`knowledge.source.sync_now`](operations/knowledge.md#knowledgesourcesync_now), [`knowledge.source.update`](operations/knowledge.md#knowledgesourceupdate), [`knowledge.synthesize`](operations/knowledge.md#knowledgesynthesize), [`knowledge.update_metadata`](operations/knowledge.md#knowledgeupdate_metadata), [`knowledge.upsert`](operations/knowledge.md#knowledgeupsert) | | `learnings` | 0 | [`learnings.list`](operations/learnings.md#learningslist), [`learnings.quality`](operations/learnings.md#learningsquality), [`learnings.review`](operations/learnings.md#learningsreview) | | `memory` | 38 | [`memory.aggregate`](operations/memory.md#memoryaggregate), [`memory.append_batch`](operations/memory.md#memoryappend_batch), [`memory.apply`](operations/memory.md#memoryapply), [`memory.assign_category`](operations/memory.md#memoryassign_category), [`memory.auto_retirements`](operations/memory.md#memoryauto_retirements), [`memory.backlinks`](operations/memory.md#memorybacklinks), [`memory.copy_to`](operations/memory.md#memorycopy_to), [`memory.cross_promote`](operations/memory.md#memorycross_promote), [`memory.dedup_collapse`](operations/memory.md#memorydedup_collapse), [`memory.definitions.list`](operations/memory.md#memorydefinitionslist), [`memory.delete_version`](operations/memory.md#memorydelete_version), [`memory.demonstrate`](operations/memory.md#memorydemonstrate), [`memory.demote`](operations/memory.md#memorydemote), [`memory.exposure_summary`](operations/memory.md#memoryexposure_summary), [`memory.extraction_retry_mine`](operations/memory.md#memoryextraction_retry_mine), [`memory.extraction_status_mine`](operations/memory.md#memoryextraction_status_mine), [`memory.history`](operations/memory.md#memoryhistory), [`memory.import`](operations/memory.md#memoryimport), [`memory.import_curated`](operations/memory.md#memoryimport_curated), [`memory.inspect`](operations/memory.md#memoryinspect), [`memory.keys`](operations/memory.md#memorykeys), [`memory.lineage`](operations/memory.md#memorylineage), [`memory.lock`](operations/memory.md#memorylock), [`memory.outcome`](operations/memory.md#memoryoutcome), [`memory.outline`](operations/memory.md#memoryoutline), [`memory.owner_report`](operations/memory.md#memoryowner_report), [`memory.pin`](operations/memory.md#memorypin), [`memory.promote`](operations/memory.md#memorypromote), [`memory.proposal_decide`](operations/memory.md#memoryproposal_decide), [`memory.proposals`](operations/memory.md#memoryproposals), [`memory.record.conflicts`](operations/memory.md#memoryrecordconflicts), [`memory.redact`](operations/memory.md#memoryredact), [`memory.reindex`](operations/memory.md#memoryreindex), [`memory.reject`](operations/memory.md#memoryreject), [`memory.related`](operations/memory.md#memoryrelated), [`memory.stack`](operations/memory.md#memorystack), [`memory.statuses`](operations/memory.md#memorystatuses), [`memory.sweep_expired`](operations/memory.md#memorysweep_expired), [`memory.timeline`](operations/memory.md#memorytimeline), [`memory.touch`](operations/memory.md#memorytouch), [`memory.unlock`](operations/memory.md#memoryunlock), [`memory.unpin`](operations/memory.md#memoryunpin) | | `memory_schema` | 1 | [`memory_schema.approve`](operations/memory_schema.md#memory_schemaapprove), [`memory_schema.list`](operations/memory_schema.md#memory_schemalist), [`memory_schema.propose`](operations/memory_schema.md#memory_schemapropose) | diff --git a/llms.txt b/llms.txt index c36e1a9d960..c2d43438e9b 100644 --- a/llms.txt +++ b/llms.txt @@ -176,6 +176,7 @@ Start with [the docs map](docs/index.md). To install Loom, a coding agent reads - [Knowledge gaps](docs/architecture/knowledge-gaps.md): Loom records the searches that found nothing a caller could use and groups them, once a day, into knowledge gaps: the questions several people asked that the namespace's memory and documents do not answer. - [Live connected-source search](docs/architecture/live-source-search.md): `search.query(live=true)` adds an ephemeral section from the asker's own connected Drive, Notion and Linear registrations. - [LLM and embedding architecture](docs/architecture/llm-architecture.md): Loom uses pluggable embedders and model clients configured through server settings. +- [Document source worker boundary](docs/architecture/mcp-source-worker-boundary.md): Loom reads one selected document live through an operator-provisioned source worker that holds the upstream credential; this page states that boundary and what stored copies and refresh still require. - [Memory architecture](docs/architecture/memory-architecture.md): The memory plane stores facts in `loom.memory`, makes them searchable through `loom.memory_embeddings`, and derives evidence, chunks, graph rows and statistics from them. - [Memory consent and derived text](docs/architecture/memory-consent.md): A deletion contracts memory and records content refusal before its tombstone commits. - [n8n adapter](docs/architecture/n8n-adapter.md): The n8n community package stores conversation history and durable facts in a Loom deployment through the TypeScript SDK. diff --git a/loom.example.yaml b/loom.example.yaml index ab052503454..0e5d943948f 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -3115,6 +3115,25 @@ settings: # Off does not lift protection while the deployment latch remains set. [restart] # knowledge_mirrored_sources_enabled: false + # Path to the operator's source worker routes file. Empty disables the worker + # directory. [restart] + # knowledge_source_worker_routes_file: "" + + # Seconds a live read may spend on authority checks and its worker request. At most 8, + # the default: a value can only shorten it. [restart] + # knowledge_source_worker_live_timeout_s: 8.0 + + # Seconds reserved after a live read for accounting and delivery. At most 2, the + # default: a value can only shorten it. [restart] + # knowledge_source_worker_publication_timeout_s: 2.0 + + # Seconds one response frame may spend acquiring authority locks and sending. At most + # 1, the default; the remaining publication deadline can shorten it further. [restart] + # knowledge_source_worker_frame_timeout_s: 1.0 + + # Concurrent worker access checks when proving a selection for setup. [restart] + # knowledge_source_worker_selection_parallelism: 2 + # Mirrored reads require a complete listing and group observation within this many # seconds; missing or older evidence admits nobody. [restart] # knowledge_source_acl_stale_seconds: 3600 diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index bef78fe9d2f..c2133b01b33 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -3733,6 +3733,39 @@ "type": "integer", "description": "Seconds one sync pass may run before it is cancelled; it stops starting sources at three quarters of it. At least 180: 90 for the sync, then 60 of read time for one document's extraction and 30 for its writes before the deadline." }, + "knowledge_source_worker_frame_timeout_s": { + "default": 1.0, + "exclusiveMinimum": 0, + "maximum": 1.0, + "type": "number", + "description": "Seconds one response frame may spend acquiring authority locks and sending. At most 1, the default; the remaining publication deadline can shorten it further." + }, + "knowledge_source_worker_live_timeout_s": { + "default": 8.0, + "exclusiveMinimum": 0, + "maximum": 8.0, + "type": "number", + "description": "Seconds a live read may spend on authority checks and its worker request. At most 8, the default: a value can only shorten it." + }, + "knowledge_source_worker_publication_timeout_s": { + "default": 2.0, + "exclusiveMinimum": 0, + "maximum": 2.0, + "type": "number", + "description": "Seconds reserved after a live read for accounting and delivery. At most 2, the default: a value can only shorten it." + }, + "knowledge_source_worker_routes_file": { + "default": "", + "type": "string", + "description": "Path to the operator's source worker routes file. Empty disables the worker directory." + }, + "knowledge_source_worker_selection_parallelism": { + "default": 2, + "maximum": 2, + "minimum": 1, + "type": "integer", + "description": "Concurrent worker access checks when proving a selection for setup." + }, "knowledge_sources_max_per_namespace": { "default": 8, "minimum": 1, diff --git a/schemas/pg_migrations/015_mcp_worker_enrollment.sql b/schemas/pg_migrations/015_mcp_worker_enrollment.sql new file mode 100644 index 00000000000..67fe6ee1bf9 --- /dev/null +++ b/schemas/pg_migrations/015_mcp_worker_enrollment.sql @@ -0,0 +1,48 @@ +CREATE TABLE IF NOT EXISTS loom.mcp_worker_enrollment_challenges ( + org text COLLATE "C" NOT NULL, + namespace text COLLATE "C" NOT NULL, + agent text COLLATE "C" NOT NULL, + user_id text COLLATE "C" NOT NULL CHECK (length(user_id) BETWEEN 1 AND 255 AND user_id <> '-'), + session_id text COLLATE "C" NOT NULL, + actor text NOT NULL, + source_class text NOT NULL, + worker_id uuid NOT NULL CHECK (worker_id <> '00000000-0000-0000-0000-000000000000'), + profile_digest text COLLATE "C" NOT NULL CHECK (profile_digest ~ '^[0-9a-f]{64}$'), + connection_id uuid NOT NULL CHECK (connection_id <> '00000000-0000-0000-0000-000000000000'), + generation bigint NOT NULL CHECK (generation > 0), + nonce uuid NOT NULL CHECK (nonce <> '00000000-0000-0000-0000-000000000000'), + issued_at bigint NOT NULL CHECK (issued_at >= 0), + expires_at bigint NOT NULL CHECK (expires_at - issued_at BETWEEN 1 AND 120), + consumed boolean NOT NULL DEFAULT false, + PRIMARY KEY (org, nonce) +); + +CREATE INDEX IF NOT EXISTS mcp_worker_enrollment_challenges_expiry + ON loom.mcp_worker_enrollment_challenges (org, expires_at, nonce); + +CREATE INDEX IF NOT EXISTS mcp_worker_enrollment_challenges_active_connection + ON loom.mcp_worker_enrollment_challenges (org, connection_id, expires_at) WHERE NOT consumed; + +CREATE INDEX IF NOT EXISTS mcp_worker_enrollment_challenges_by_user + ON loom.mcp_worker_enrollment_challenges (org, user_id, namespace); + +CREATE TABLE IF NOT EXISTS loom.mcp_worker_accounts ( + org text COLLATE "C" NOT NULL, + namespace text COLLATE "C" NOT NULL, + agent text COLLATE "C" NOT NULL, + user_id text COLLATE "C" NOT NULL CHECK (length(user_id) BETWEEN 1 AND 255 AND user_id <> '-'), + session_id text COLLATE "C" NOT NULL, + actor text NOT NULL, + source_class text NOT NULL, + worker_id uuid NOT NULL CHECK (worker_id <> '00000000-0000-0000-0000-000000000000'), + profile_digest text COLLATE "C" NOT NULL CHECK (profile_digest ~ '^[0-9a-f]{64}$'), + connection_id uuid NOT NULL CHECK (connection_id <> '00000000-0000-0000-0000-000000000000'), + generation bigint NOT NULL CHECK (generation > 0), + resource_space text COLLATE "C" CHECK (resource_space ~ '^[0-9a-f]{64}$'), + active boolean NOT NULL, + updated_at timestamptz NOT NULL DEFAULT clock_timestamp(), + PRIMARY KEY (org, connection_id) +); + +CREATE INDEX IF NOT EXISTS mcp_worker_accounts_by_user + ON loom.mcp_worker_accounts (org, user_id, namespace); diff --git a/schemas/pg_migrations/016_mcp_worker_approvals.sql b/schemas/pg_migrations/016_mcp_worker_approvals.sql new file mode 100644 index 00000000000..d3a40a174b0 --- /dev/null +++ b/schemas/pg_migrations/016_mcp_worker_approvals.sql @@ -0,0 +1,22 @@ +CREATE SEQUENCE IF NOT EXISTS loom.mcp_worker_approval_generations AS bigint; + +CREATE TABLE IF NOT EXISTS loom.mcp_worker_approvals ( + org text COLLATE "C" NOT NULL, + namespace text COLLATE "C" NOT NULL, + agent text COLLATE "C" NOT NULL, + user_id text COLLATE "C" NOT NULL, + session_id text COLLATE "C" NOT NULL, + actor text NOT NULL, + source_class text NOT NULL, + worker_id uuid NOT NULL CHECK (worker_id <> '00000000-0000-0000-0000-000000000000'), + profile_digest text COLLATE "C" NOT NULL CHECK (profile_digest ~ '^[0-9a-f]{64}$'), + generation bigint NOT NULL CHECK (generation > 0), + modes smallint NOT NULL CHECK (modes BETWEEN 0 AND 7), + team_access boolean NOT NULL, + active boolean NOT NULL, + CHECK ((active AND modes > 0) OR (NOT active AND modes = 0 AND NOT team_access)), + PRIMARY KEY (org, namespace, worker_id, profile_digest) +); + +CREATE INDEX IF NOT EXISTS mcp_worker_approvals_by_user + ON loom.mcp_worker_approvals (org, user_id, namespace); diff --git a/schemas/pg_migrations/017_mcp_worker_source_readers.sql b/schemas/pg_migrations/017_mcp_worker_source_readers.sql new file mode 100644 index 00000000000..e61f6e8a46e --- /dev/null +++ b/schemas/pg_migrations/017_mcp_worker_source_readers.sql @@ -0,0 +1,21 @@ +CREATE SEQUENCE IF NOT EXISTS loom.mcp_worker_source_reader_generations AS bigint; + +CREATE TABLE IF NOT EXISTS loom.mcp_worker_source_readers ( + org text COLLATE "C" NOT NULL, + namespace text COLLATE "C" NOT NULL, + user_id text COLLATE "C" NOT NULL CHECK (length(user_id) BETWEEN 1 AND 255 AND user_id <> '-'), + agent text COLLATE "C" NOT NULL, + session_id text COLLATE "C" NOT NULL, + actor text NOT NULL, + source_class text NOT NULL, + source_id uuid NOT NULL CHECK (source_id <> '00000000-0000-0000-0000-000000000000'), + selection_generation bigint NOT NULL CHECK (selection_generation > 0), + connection_id uuid NOT NULL CHECK (connection_id <> '00000000-0000-0000-0000-000000000000'), + connection_generation bigint NOT NULL CHECK (connection_generation > 0), + link_generation bigint NOT NULL CHECK (link_generation > 0), + active boolean NOT NULL, + PRIMARY KEY (org, namespace, source_id, user_id) +); + +CREATE INDEX IF NOT EXISTS mcp_worker_source_readers_by_user + ON loom.mcp_worker_source_readers (org, user_id, namespace); diff --git a/sdk/go/client.gen.go b/sdk/go/client.gen.go index a43305bf158..b0a04bc4622 100644 --- a/sdk/go/client.gen.go +++ b/sdk/go/client.gen.go @@ -1415,6 +1415,15 @@ type KnowledgeSourceListInput = wire.KnowledgeSourceListInput // KnowledgeSourceListOutput is the response from knowledge.source.list. type KnowledgeSourceListOutput = wire.KnowledgeSourceListOutput +// KnowledgeSourceLiveDocument is a model used by Loom operations. +type KnowledgeSourceLiveDocument = wire.KnowledgeSourceLiveDocument + +// KnowledgeSourceLiveInput is the request to knowledge.source.live. +type KnowledgeSourceLiveInput = wire.KnowledgeSourceLiveInput + +// KnowledgeSourceLiveOutput is the response from knowledge.source.live. +type KnowledgeSourceLiveOutput = wire.KnowledgeSourceLiveOutput + // KnowledgeSourceParseLinksInput is the request to knowledge.source.parse_links. type KnowledgeSourceParseLinksInput = wire.KnowledgeSourceParseLinksInput @@ -5721,6 +5730,17 @@ func (s KnowledgeService) SourceList(ctx context.Context, opts ...Option[Knowled return callOperation[KnowledgeSourceListOutput](s.client, ctx, "knowledge.source.list", in) } +// SourceLive calls knowledge.source.live. +func (s KnowledgeService) SourceLive(ctx context.Context, in KnowledgeSourceLiveInput) (*KnowledgeSourceLiveOutput, error) { + if in.Namespace == "" { + in.Namespace = s.client.identity.Namespace + } + if in.Org == "" { + in.Org = s.client.identity.Org + } + return callOperation[KnowledgeSourceLiveOutput](s.client, ctx, "knowledge.source.live", in) +} + // SourceParseLinks calls knowledge.source.parse_links. func (s KnowledgeService) SourceParseLinks(ctx context.Context, in KnowledgeSourceParseLinksInput) (*KnowledgeSourceParseLinksOutput, error) { if in.Namespace == "" { diff --git a/sdk/go/wire/models.gen.go b/sdk/go/wire/models.gen.go index 7eefc5fd6fb..ae301f156b9 100644 --- a/sdk/go/wire/models.gen.go +++ b/sdk/go/wire/models.gen.go @@ -1,5 +1,5 @@ // Code generated by scripts/codegen/sdk_go_gen.py; DO NOT EDIT. -// Registry model schema SHA-256: 2bbacf08033ddb0d38cc26fa5fdf514d3d49a9659f9bdd5c0452ffeffa751179 +// Registry model schema SHA-256: 73716290651dd78cf8a6b0b8701328b9cd48b89056034e268fcb6675f2b0d364 // Package wire contains the Go requests and responses for Loom operations. package wire @@ -5644,6 +5644,35 @@ type KnowledgeSourceListOutput struct { SelfService *bool `json:"self_service,omitempty"` } +// KnowledgeSourceLiveDocument is a model used by Loom operations. +type KnowledgeSourceLiveDocument struct { + SourceID string `json:"source_id"` + ResourceID string `json:"resource_id"` + URI string `json:"uri"` + SourceLink *string `json:"source_link"` + FetchedAt int64 `json:"fetched_at"` + Title string `json:"title"` + Text string `json:"text"` + MimeType string `json:"mime_type"` +} + +// KnowledgeSourceLiveInput is the request to knowledge.source.live. +type KnowledgeSourceLiveInput struct { + Org string `json:"org"` + Namespace string `json:"namespace"` + Name string `json:"name"` + ResourceID string `json:"resource_id"` +} + +// KnowledgeSourceLiveOutput is the response from knowledge.source.live. +type KnowledgeSourceLiveOutput struct { + IgnoredArgs *[]string `json:"ignored_args,omitempty"` + DidYouMean *map[string]string `json:"did_you_mean,omitempty"` + Mirrored *bool `json:"mirrored,omitempty"` + Status string `json:"status"` + Document Optional[KnowledgeSourceLiveDocument] `json:"document,omitempty"` +} + // KnowledgeSourceParseLinksInput is the request to knowledge.source.parse_links. type KnowledgeSourceParseLinksInput struct { Org string `json:"org"` diff --git a/sdk/python/examples/audience_scoped_retrieval.py b/sdk/python/examples/audience_scoped_retrieval.py index d29a7c226b1..8738c1f301a 100644 --- a/sdk/python/examples/audience_scoped_retrieval.py +++ b/sdk/python/examples/audience_scoped_retrieval.py @@ -40,6 +40,7 @@ # `knowledge.search` takes `namespace` and at most 100 `namespaces`; a wider scope is # searched in batches of this size. SEARCH_COLLECTIONS = 101 +GRANT_WAIT_S = 10 REVOKE_WAIT_S = 10 # Everything the agent may ask of Loom, and every argument each tool takes. The person, @@ -238,13 +239,33 @@ def signer(org: str) -> Callable[[str], str]: def sign(person: str) -> str: now = int(time.time()) - claims = {"iss": issuer, "aud": audience, "sub": f"user:{person}", "org": org} + claims: dict[str, str | int] = { + "iss": issuer, + "aud": audience, + "sub": f"user:{person}", + "org": org, + } claims |= {"iat": now, "exp": now + 120, "jti": uuid.uuid4().hex} return jwt.encode(claims, key, algorithm="RS256", headers={"kid": kid}) return sign +async def _wait_for_fixture_grants(host: Host, person: str, collections: set[str]) -> bool: + # The serving replica may still have the previous grants when setup returns. + wait = asyncio.timeout(GRANT_WAIT_S) + try: + async with wait: + while True: + if collections.issubset(await host.scope(person, f"dm:{person}")): + return True + await asyncio.sleep(0.5) + except TimeoutError: + if wait.expired(): + return False + raise + + async def main(sign: Callable[[str], str] | None = None) -> int: org = os.environ.get("LOOM_ORG", "dev") run = secrets.token_hex(3) @@ -271,7 +292,10 @@ async def main(sign: Callable[[str], str] | None = None) -> int: await loom.knowledge.add(f"# Renewal\n\n{text}\n", source_uri=SOURCE_URI) async with host.as_person(person) as loom: await loom.knowledge.add(f"# Renewal\n\n{NOTE}\n", source_uri=SOURCE_URI) - failures = await ask_in_private_then_in_shared(host, person, lead, support) + if await _wait_for_fixture_grants(host, person, {support, finance}): + failures = await ask_in_private_then_in_shared(host, person, lead, support) + else: + failures.append("the shared collections did not become visible to the recipient") finally: # Delete the note and both collections, even when a step failed. Each delete is # tried on its own, so one that fails does not leave the others behind. diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index ce08b6daa61..b1556d69e0e 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -1579,6 +1579,15 @@ async def source_list( await self._agent.call("knowledge.source.list", body, **options), ) + async def source_live( + self, body: _ops.KnowledgeSourceLiveBody | None = None, /, **options: Any + ) -> _ops.KnowledgeSourceLiveOutput: + """`knowledge.source.live`.""" + return cast( + "_ops.KnowledgeSourceLiveOutput", + await self._agent.call("knowledge.source.live", body, **options), + ) + async def source_parse_links( self, body: _ops.KnowledgeSourceParseLinksBody | None = None, /, **options: Any ) -> _ops.KnowledgeSourceParseLinksOutput: diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 9eda95c644e..03fe07997ad 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -199,6 +199,7 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.live", "knowledge.source.parse_links", "knowledge.source.push_configure", "knowledge.source.push_confirm", @@ -581,6 +582,7 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.live", "knowledge.source.parse_links", "knowledge.source.push_configure", "knowledge.source.push_confirm", @@ -2723,6 +2725,18 @@ class OpSpec: False, True, ), + "knowledge.source.live": OpSpec( + "knowledge.source.live", + "KnowledgeSourceLiveInput", + "KnowledgeSourceLiveBody", + "KnowledgeSourceLiveOutput", + True, + "viewer", + "experimental", + 8000, + False, + True, + ), "knowledge.source.parse_links": OpSpec( "knowledge.source.parse_links", "KnowledgeSourceParseLinksInput", @@ -12160,6 +12174,44 @@ class KnowledgeSourceEntry(TypedDict, total=False): sync: NotRequired["KnowledgeSourceSync"] +class KnowledgeSourceLiveInput(TypedDict, total=False): + "Read one selected resource through the caller's current worker connection." + + org: Required[str] + namespace: Required[str] + name: Required[str] + resource_id: Required[str] + + +class KnowledgeSourceLiveBody(TypedDict, total=False): + "Read one selected resource through the caller's current worker connection." + + org: NotRequired[str] + namespace: NotRequired[str] + name: Required[str] + resource_id: Required[str] + + +class KnowledgeSourceLiveOutput(TypedDict, total=False): + status: Required[ + Literal["ok", "denied", "reconnect", "overloaded", "timeout", "unavailable", "unsupported"] + ] + document: NotRequired[Optional["KnowledgeSourceLiveDocument"]] + + +class KnowledgeSourceLiveDocument(TypedDict, total=False): + "The current selected document. It is not written to the index." + + source_id: Required[str] + resource_id: Required[str] + uri: Required[str] + source_link: Required[Optional[str]] + fetched_at: Required[int] + title: Required[str] + text: Required[str] + mime_type: Required[str] + + class KnowledgeSourceParseLinksInput(TypedDict, total=False): "Read pasted links as a source's items, with no request to any store and" diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index 83f7e54ad53..a87d4780c9b 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb @@ -8,7 +8,7 @@ module Loom # Every served operation: its spec in OPS, and one method per op on the class # of its group (`client.memory.set(...)` is `memory.set`). module Generated - OP_COUNT = 379 + OP_COUNT = 380 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -172,6 +172,7 @@ module Generated "knowledge.source.check" => OpSpec.new("knowledge.source.check", "knowledge", "source_check", true, false, "writer", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), "knowledge.source.inspect" => OpSpec.new("knowledge.source.inspect", "knowledge", "source_inspect", true, true, "viewer", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), "knowledge.source.list" => OpSpec.new("knowledge.source.list", "knowledge", "source_list", true, true, "viewer", "experimental", %w[org namespace].freeze, %w[org namespace].freeze), + "knowledge.source.live" => OpSpec.new("knowledge.source.live", "knowledge", "source_live", true, true, "viewer", "experimental", %w[org namespace name resource_id].freeze, %w[org namespace name resource_id].freeze), "knowledge.source.parse_links" => OpSpec.new("knowledge.source.parse_links", "knowledge", "source_parse_links", true, true, "viewer", "experimental", %w[org namespace links].freeze, %w[org namespace links].freeze), "knowledge.source.push_configure" => OpSpec.new("knowledge.source.push_configure", "knowledge", "source_push_configure", false, false, "admin", "experimental", %w[org namespace name enabled agent user_id session_id].freeze, %w[org namespace name].freeze), "knowledge.source.push_confirm" => OpSpec.new("knowledge.source.push_confirm", "knowledge", "source_push_confirm", false, false, "admin", "experimental", %w[org namespace name generation challenge_fingerprint signing_secret].freeze, %w[org namespace name generation].freeze), @@ -1483,6 +1484,13 @@ def source_list(body = nil, request_options: nil, **fields) call_op("knowledge.source.list", body, fields, request_options) end + # `knowledge.source.live` (viewer, read-only, experimental). + # Read one selected resource through the caller's current worker connection. + # Required: org, namespace, name, resource_id. + def source_live(body = nil, request_options: nil, **fields) + call_op("knowledge.source.live", body, fields, request_options) + end + # `knowledge.source.parse_links` (viewer, read-only, experimental). # Read pasted links as a source's items, with no request to any store and # Required: org, namespace, links. diff --git a/sdk/rust/src/blocking_operations.rs b/sdk/rust/src/blocking_operations.rs index 6b07db86efc..6ca13ab8592 100644 --- a/sdk/rust/src/blocking_operations.rs +++ b/sdk/rust/src/blocking_operations.rs @@ -1991,6 +1991,23 @@ impl crate::blocking::Client { ) -> Result, crate::CallFailure> { self.call("knowledge.source.sync_now", &request, options) } + /// Call `knowledge.source.live`. + pub fn knowledge_source_live( + &self, + request: crate::KnowledgeSourceLiveInput, + ) -> Result { + self.knowledge_source_live_with_options(request, crate::CallOptions::default()) + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.source.live` with per-request options and metadata. + pub fn knowledge_source_live_with_options( + &self, + request: crate::KnowledgeSourceLiveInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.source.live", &request, options) + } /// Call `connection.list`. pub fn connection_list( &self, diff --git a/sdk/rust/src/operations.rs b/sdk/rust/src/operations.rs index 721893a77ab..7bb43d7676c 100644 --- a/sdk/rust/src/operations.rs +++ b/sdk/rust/src/operations.rs @@ -2129,6 +2129,24 @@ impl crate::Client { self.call("knowledge.source.sync_now", &request, options) .await } + /// Call `knowledge.source.live`. + pub async fn knowledge_source_live( + &self, + request: crate::KnowledgeSourceLiveInput, + ) -> Result { + self.knowledge_source_live_with_options(request, crate::CallOptions::default()) + .await + .map(|result| result.data) + .map_err(|failure| failure.error) + } + /// Call `knowledge.source.live` with per-request options and metadata. + pub async fn knowledge_source_live_with_options( + &self, + request: crate::KnowledgeSourceLiveInput, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + self.call("knowledge.source.live", &request, options).await + } /// Call `connection.list`. pub async fn connection_list( &self, diff --git a/sdk/rust/src/wire_models.rs b/sdk/rust/src/wire_models.rs index ec19f20e824..289cd160738 100644 --- a/sdk/rust/src/wire_models.rs +++ b/sdk/rust/src/wire_models.rs @@ -751,6 +751,13 @@ pub(crate) const OP_POLICIES: &[OperationPolicy] = &[ &["namespace", "org"], &[], ), + ( + "knowledge.source.live", + true, + true, + &["namespace", "org"], + &[], + ), ("connection.list", true, true, &["org"], &[]), ("connection.disconnect", true, false, &["org"], &[]), ( @@ -27385,22 +27392,132 @@ impl KnowledgeSourceListInput { } } +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[non_exhaustive] +pub enum KnowledgeSourceLiveOutputStatus { + #[serde(rename = "ok")] + Ok, + #[serde(rename = "denied")] + Denied, + #[serde(rename = "reconnect")] + Reconnect, + #[serde(rename = "overloaded")] + Overloaded, + #[serde(rename = "timeout")] + Timeout, + #[serde(rename = "unavailable")] + Unavailable, + #[serde(rename = "unsupported")] + Unsupported, +} + +#[derive(Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeSourceLiveDocument { + pub source_id: String, + pub resource_id: String, + pub uri: String, + #[serde(deserialize_with = "required_nullable")] + pub source_link: Option, + pub fetched_at: Integer, + pub title: String, + pub text: String, + pub mime_type: String, +} +impl std::fmt::Debug for KnowledgeSourceLiveDocument { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("KnowledgeSourceLiveDocument") + .field("source_id", &self.source_id) + .field("fetched_at", &self.fetched_at) + .field("mime_type", &self.mime_type) + .finish_non_exhaustive() + } +} + +#[derive(Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeSourceLiveOutput { + pub status: KnowledgeSourceLiveOutputStatus, + #[serde(default = "default_1262")] + pub document: Option, +} +impl std::fmt::Debug for KnowledgeSourceLiveOutput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("KnowledgeSourceLiveOutput") + .field("status", &self.status) + .finish_non_exhaustive() + } +} + +#[derive(Clone, PartialEq, Serialize, Deserialize)] +#[non_exhaustive] +pub struct KnowledgeSourceLiveInput { + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub org: Option, + #[serde( + default, + skip_serializing_if = "Option::is_none", + deserialize_with = "present_value" + )] + pub namespace: Option, + pub name: String, + pub resource_id: String, +} +impl std::fmt::Debug for KnowledgeSourceLiveInput { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("KnowledgeSourceLiveInput") + .field("org", &self.org) + .field("namespace", &self.namespace) + .field("name", &self.name) + .finish_non_exhaustive() + } +} +impl KnowledgeSourceLiveInput { + pub fn new(name: impl Into, resource_id: impl Into) -> Self { + Self { + org: None, + namespace: None, + name: name.into(), + resource_id: resource_id.into(), + } + } + pub fn org(mut self, org: impl Into) -> Self { + self.org = Some(org.into()); + self + } + pub fn namespace(mut self, namespace: impl Into) -> Self { + self.namespace = Some(namespace.into()); + self + } + pub async fn send( + self, + client: &crate::Client, + options: crate::CallOptions, + ) -> Result, crate::CallFailure> { + client.call("knowledge.source.live", &self, options).await + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceParsedLink { pub link: String, - #[serde(default = "default_1262")] - pub kind: String, #[serde(default = "default_1263")] - pub item: std::collections::HashMap, + pub kind: String, #[serde(default = "default_1264")] + pub item: std::collections::HashMap, + #[serde(default = "default_1265")] pub unreadable: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct KnowledgeSourceParseLinksOutput { - #[serde(default = "default_1265")] + #[serde(default = "default_1266")] pub links: Vec, } @@ -27451,25 +27568,25 @@ impl KnowledgeSourceParseLinksInput { #[derive(Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct PushStatusOutput { - #[serde(default = "default_1266")] - pub enabled: bool, #[serde(default = "default_1267")] - pub status: String, + pub enabled: bool, #[serde(default = "default_1268")] - pub provider: String, + pub status: String, #[serde(default = "default_1269")] - pub generation: String, + pub provider: String, #[serde(default = "default_1270")] - pub callback_url: String, + pub generation: String, #[serde(default = "default_1271")] - pub provider_id: String, + pub callback_url: String, #[serde(default = "default_1272")] - pub challenge_fingerprint: String, + pub provider_id: String, #[serde(default = "default_1273")] - pub verification_token: String, + pub challenge_fingerprint: String, #[serde(default = "default_1274")] - pub channels: Integer, + pub verification_token: String, #[serde(default = "default_1275")] + pub channels: Integer, + #[serde(default = "default_1276")] pub expires_at: f64, } impl std::fmt::Debug for PushStatusOutput { @@ -27714,7 +27831,7 @@ impl PushStatusInput { #[non_exhaustive] pub struct KnowledgeSourceRemoveOutput { pub name: String, - #[serde(default = "default_1276")] + #[serde(default = "default_1277")] pub documents_pending: Integer, } @@ -27777,9 +27894,9 @@ impl KnowledgeSourceRemoveInput { #[non_exhaustive] pub struct KnowledgeSourceRotateOutput { pub name: String, - #[serde(default = "default_1277")] - pub probe: KnowledgeSourceProbe, #[serde(default = "default_1278")] + pub probe: KnowledgeSourceProbe, + #[serde(default = "default_1279")] pub rotated_at: String, } @@ -27831,7 +27948,7 @@ impl KnowledgeSourceRotateInput { #[non_exhaustive] pub struct KnowledgeSourceSyncNowOutput { pub name: String, - #[serde(default = "default_1279")] + #[serde(default = "default_1280")] pub enabled: bool, } @@ -27894,17 +28011,17 @@ impl KnowledgeSourceSyncNowInput { #[non_exhaustive] pub struct KnowledgeSourceUpdateOutput { pub name: String, - #[serde(default = "default_1280")] - pub items: Vec>, #[serde(default = "default_1281")] - pub include: Vec, + pub items: Vec>, #[serde(default = "default_1282")] - pub config: std::collections::HashMap, + pub include: Vec, #[serde(default = "default_1283")] - pub added: Vec>, + pub config: std::collections::HashMap, #[serde(default = "default_1284")] - pub removed: Vec>, + pub added: Vec>, #[serde(default = "default_1285")] + pub removed: Vec>, + #[serde(default = "default_1286")] pub probe: KnowledgeSourceProbe, } @@ -28020,9 +28137,9 @@ impl KnowledgeSourceUpdateInput { pub struct CitedChunk { pub source_uri: String, pub chunk_idx: Integer, - #[serde(default = "default_1287")] - pub revision: Integer, #[serde(default = "default_1288")] + pub revision: Integer, + #[serde(default = "default_1289")] pub locator: Option>, } @@ -28031,12 +28148,12 @@ pub struct CitedChunk { pub struct SynthesizeCalculation { pub columns: Vec, pub rows: Vec>, - #[serde(default = "default_1295")] - pub row_ids: Vec>, #[serde(default = "default_1296")] + pub row_ids: Vec>, + #[serde(default = "default_1297")] pub truncated: bool, pub complete: bool, - #[serde(default = "default_1297")] + #[serde(default = "default_1298")] pub incomplete: Vec, pub receipt: QueryReceipt, pub citation: String, @@ -28050,23 +28167,23 @@ pub struct KnowledgeSynthesizeOutput { pub chunks_read: Integer, pub documents: Integer, pub reduce_rounds: Integer, - #[serde(default = "default_1286")] + #[serde(default = "default_1287")] pub citations: Vec, - #[serde(default = "default_1289")] - pub cited_chunks: Vec, #[serde(default = "default_1290")] - pub unsupported_citations: Vec, + pub cited_chunks: Vec, #[serde(default = "default_1291")] - pub truncated: bool, + pub unsupported_citations: Vec, #[serde(default = "default_1292")] - pub abstain: bool, + pub truncated: bool, #[serde(default = "default_1293")] - pub abstain_reason: String, + pub abstain: bool, #[serde(default = "default_1294")] + pub abstain_reason: String, + #[serde(default = "default_1295")] pub clarification: String, - #[serde(default = "default_1298")] - pub calculations: Vec, #[serde(default = "default_1299")] + pub calculations: Vec, + #[serde(default = "default_1300")] pub model: String, } @@ -28182,13 +28299,13 @@ impl KnowledgeSynthesizeInput { #[non_exhaustive] pub struct KnowledgeUpdateMetadataOutput { pub updated: bool, - #[serde(default = "default_1300")] - pub title: String, #[serde(default = "default_1301")] - pub description: String, + pub title: String, #[serde(default = "default_1302")] - pub tags: Vec, + pub description: String, #[serde(default = "default_1303")] + pub tags: Vec, + #[serde(default = "default_1304")] pub chunks_reindexed: Integer, } @@ -28300,13 +28417,13 @@ pub struct KnowledgeUpsertOutput { pub chunks_superseded: Integer, pub embedding_model: String, pub embedding_dim: Integer, - #[serde(default = "default_1304")] - pub duplicate_of_uri: String, #[serde(default = "default_1305")] - pub duplicate_chunk_count: Integer, + pub duplicate_of_uri: String, #[serde(default = "default_1306")] - pub namespace: String, + pub duplicate_chunk_count: Integer, #[serde(default = "default_1307")] + pub namespace: String, + #[serde(default = "default_1308")] pub source_uri: String, } @@ -28491,26 +28608,26 @@ pub struct LearningEntry { pub memory_type: String, pub proposed_value: Value, pub supporter_count: Integer, - #[serde(default = "default_1308")] - pub supporter_sessions: Integer, #[serde(default = "default_1309")] + pub supporter_sessions: Integer, + #[serde(default = "default_1310")] pub supporter_writers: Integer, pub confidence_avg: f64, pub supporters: Vec, pub rationale: String, - #[serde(default = "default_1310")] - pub source_kind: String, #[serde(default = "default_1311")] - pub source_resource_id: String, + pub source_kind: String, #[serde(default = "default_1312")] + pub source_resource_id: String, + #[serde(default = "default_1313")] pub agent: String, pub status: LearningEntryStatus, pub proposed_at: String, - #[serde(default = "default_1313")] - pub decided_at: Option, #[serde(default = "default_1314")] - pub decided_by: String, + pub decided_at: Option, #[serde(default = "default_1315")] + pub decided_by: String, + #[serde(default = "default_1316")] pub decision_reason: String, } @@ -28713,11 +28830,11 @@ pub enum LearningsReviewOutputNewStatus { pub struct LearningsReviewOutput { pub candidate_id: String, pub new_status: LearningsReviewOutputNewStatus, - #[serde(default = "default_1316")] - pub promoted_to_shared: bool, #[serde(default = "default_1317")] - pub promoted_to_knowledge: bool, + pub promoted_to_shared: bool, #[serde(default = "default_1318")] + pub promoted_to_knowledge: bool, + #[serde(default = "default_1319")] pub knowledge_source_uri: String, pub decided_at: String, } @@ -28921,7 +29038,7 @@ impl MemoryAgentsListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct AggregateRow { - #[serde(default = "default_1319")] + #[serde(default = "default_1320")] pub group: std::collections::HashMap, pub metric: f64, } @@ -28929,9 +29046,9 @@ pub struct AggregateRow { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryAggregateOutput { - #[serde(default = "default_1320")] - pub rows: Vec, #[serde(default = "default_1321")] + pub rows: Vec, + #[serde(default = "default_1322")] pub sql_executed: String, } @@ -29099,15 +29216,15 @@ impl MemoryAggregateInput { pub struct BulkSetResult { pub memory_key: String, pub version: Integer, - #[serde(default = "default_1322")] - pub memory_id: String, #[serde(default = "default_1323")] - pub conflict_verdict: String, + pub memory_id: String, #[serde(default = "default_1324")] - pub peers: Vec, + pub conflict_verdict: String, #[serde(default = "default_1325")] - pub next: String, + pub peers: Vec, #[serde(default = "default_1326")] + pub next: String, + #[serde(default = "default_1327")] pub pinned_blocker_id: String, } @@ -29115,29 +29232,29 @@ pub struct BulkSetResult { #[non_exhaustive] pub struct MemoryBulkSetOutput { pub written: Vec, - #[serde(default = "default_1327")] - pub skipped_pinned: Vec, #[serde(default = "default_1328")] - pub skipped_locked: Vec, + pub skipped_pinned: Vec, #[serde(default = "default_1329")] - pub skipped_blacklisted: Vec, + pub skipped_locked: Vec, #[serde(default = "default_1330")] - pub merged: Vec, + pub skipped_blacklisted: Vec, #[serde(default = "default_1331")] - pub value_updates_linked: Integer, + pub merged: Vec, #[serde(default = "default_1332")] - pub rejected_pinned: Vec, + pub value_updates_linked: Integer, #[serde(default = "default_1333")] - pub duplicates: Vec, + pub rejected_pinned: Vec, #[serde(default = "default_1334")] - pub conflicted: Vec, + pub duplicates: Vec, #[serde(default = "default_1335")] - pub unchecked: Integer, + pub conflicted: Vec, #[serde(default = "default_1336")] - pub retyped: Vec, + pub unchecked: Integer, #[serde(default = "default_1337")] - pub identity_duplicates: std::collections::HashMap, + pub retyped: Vec, #[serde(default = "default_1338")] + pub identity_duplicates: std::collections::HashMap, + #[serde(default = "default_1339")] pub stage_ms: std::collections::HashMap, } @@ -29287,18 +29404,18 @@ pub enum ApplyRowStatus { #[non_exhaustive] pub struct ApplyRow { pub memory_key: String, - #[serde(default = "default_1346")] - pub memory_id: String, #[serde(default = "default_1347")] - pub agent: String, + pub memory_id: String, #[serde(default = "default_1348")] - pub user_id: String, + pub agent: String, #[serde(default = "default_1349")] + pub user_id: String, + #[serde(default = "default_1350")] pub session_id: String, pub status: ApplyRowStatus, - #[serde(default = "default_1350")] - pub version: Option, #[serde(default = "default_1351")] + pub version: Option, + #[serde(default = "default_1352")] pub detail: String, } @@ -29308,21 +29425,21 @@ pub struct MemoryApplyOutput { pub action: String, pub dry_run: bool, pub target: String, - #[serde(default = "default_1339")] - pub matched: Integer, #[serde(default = "default_1340")] - pub applied: Integer, + pub matched: Integer, #[serde(default = "default_1341")] - pub would_apply: Integer, + pub applied: Integer, #[serde(default = "default_1342")] - pub refused: Integer, + pub would_apply: Integer, #[serde(default = "default_1343")] - pub noop: Integer, + pub refused: Integer, #[serde(default = "default_1344")] - pub failed: Integer, + pub noop: Integer, #[serde(default = "default_1345")] + pub failed: Integer, + #[serde(default = "default_1346")] pub truncated: bool, - #[serde(default = "default_1352")] + #[serde(default = "default_1353")] pub rows: Vec, } @@ -30056,137 +30173,137 @@ pub enum MemoryAskOutputDeepFirst { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryAskOutput { - #[serde(default = "default_1353")] - pub answer: String, #[serde(default = "default_1354")] - pub source: MemoryAskOutputSource, + pub answer: String, #[serde(default = "default_1355")] - pub abstain: bool, + pub source: MemoryAskOutputSource, #[serde(default = "default_1356")] - pub abstain_reason: String, + pub abstain: bool, #[serde(default = "default_1357")] - pub memory_keys: Vec, + pub abstain_reason: String, #[serde(default = "default_1358")] - pub results: Vec, + pub memory_keys: Vec, #[serde(default = "default_1359")] - pub cited_sessions: Vec, + pub results: Vec, #[serde(default = "default_1360")] - pub next: String, + pub cited_sessions: Vec, #[serde(default = "default_1361")] - pub synth_model: String, + pub next: String, #[serde(default = "default_1362")] - pub route_tier: MemoryAskOutputRouteTier, + pub synth_model: String, #[serde(default = "default_1363")] - pub route_reason: String, + pub route_tier: MemoryAskOutputRouteTier, #[serde(default = "default_1364")] - pub llm_cache_hits: Integer, + pub route_reason: String, #[serde(default = "default_1365")] - pub llm_cache_misses: Integer, + pub llm_cache_hits: Integer, #[serde(default = "default_1366")] - pub llm_cache: bool, + pub llm_cache_misses: Integer, #[serde(default = "default_1367")] - pub llm_cache_saved_usd: f64, + pub llm_cache: bool, #[serde(default = "default_1368")] - pub temporal_consistency: Option, + pub llm_cache_saved_usd: f64, #[serde(default = "default_1369")] - pub citation_concentration: Option, + pub temporal_consistency: Option, #[serde(default = "default_1370")] - pub escalated: bool, + pub citation_concentration: Option, #[serde(default = "default_1371")] - pub gate_mode: String, + pub escalated: bool, #[serde(default = "default_1372")] - pub gate_kept: Integer, + pub gate_mode: String, #[serde(default = "default_1373")] - pub gate_dropped: Integer, + pub gate_kept: Integer, #[serde(default = "default_1374")] - pub pending_extraction: Integer, + pub gate_dropped: Integer, #[serde(default = "default_1375")] - pub pending_evidence: Integer, + pub pending_extraction: Integer, #[serde(default = "default_1376")] - pub retrieval_query: String, + pub pending_evidence: Integer, #[serde(default = "default_1377")] - pub facets: Vec, + pub retrieval_query: String, #[serde(default = "default_1378")] - pub facet_memories_added: Integer, + pub facets: Vec, #[serde(default = "default_1379")] - pub consistency: MemoryAskOutputConsistency, + pub facet_memories_added: Integer, #[serde(default = "default_1380")] - pub consistency_score: f64, + pub consistency: MemoryAskOutputConsistency, #[serde(default = "default_1381")] - pub consistency_note: String, + pub consistency_score: f64, #[serde(default = "default_1382")] - pub identifier_chase_hops: Integer, + pub consistency_note: String, #[serde(default = "default_1383")] - pub identifier_chase_added: Integer, + pub identifier_chase_hops: Integer, #[serde(default = "default_1384")] - pub premise_conflict: String, + pub identifier_chase_added: Integer, #[serde(default = "default_1385")] - pub premise_note: String, + pub premise_conflict: String, #[serde(default = "default_1386")] - pub premise_verdict: String, + pub premise_note: String, #[serde(default = "default_1387")] - pub attribution_note: String, + pub premise_verdict: String, #[serde(default = "default_1388")] - pub depth: MemoryAskOutputDepth, + pub attribution_note: String, #[serde(default = "default_1389")] - pub deep_fired: bool, + pub depth: MemoryAskOutputDepth, #[serde(default = "default_1390")] - pub decomposed: Vec, + pub deep_fired: bool, #[serde(default = "default_1391")] - pub decomposed_parts: Integer, + pub decomposed: Vec, #[serde(default = "default_1392")] - pub superseded_dropped: Integer, + pub decomposed_parts: Integer, #[serde(default = "default_1393")] - pub stale_sentences_masked: Integer, + pub superseded_dropped: Integer, #[serde(default = "default_1394")] - pub entity_followed: Vec, + pub stale_sentences_masked: Integer, #[serde(default = "default_1395")] - pub when_evidence_turns: Integer, + pub entity_followed: Vec, #[serde(default = "default_1396")] - pub decompose_failed: Integer, + pub when_evidence_turns: Integer, #[serde(default = "default_1397")] - pub pool_k: Integer, + pub decompose_failed: Integer, #[serde(default = "default_1398")] - pub grounding: MemoryAskOutputGrounding, + pub pool_k: Integer, #[serde(default = "default_1399")] - pub deep_reason: String, + pub grounding: MemoryAskOutputGrounding, #[serde(default = "default_1400")] - pub deep_keys: Vec, + pub deep_reason: String, #[serde(default = "default_1401")] - pub deep_chars: Integer, + pub deep_keys: Vec, #[serde(default = "default_1402")] - pub code_hits: Integer, + pub deep_chars: Integer, #[serde(default = "default_1403")] - pub pool_facts: Integer, + pub code_hits: Integer, #[serde(default = "default_1404")] - pub pool_chunks: Integer, + pub pool_facts: Integer, #[serde(default = "default_1405")] - pub prompt_blocks: std::collections::HashMap, + pub pool_chunks: Integer, #[serde(default = "default_1406")] - pub deep_selector: MemoryAskOutputDeepSelector, + pub prompt_blocks: std::collections::HashMap, #[serde(default = "default_1407")] - pub deep_first: MemoryAskOutputDeepFirst, + pub deep_selector: MemoryAskOutputDeepSelector, #[serde(default = "default_1408")] - pub synth_calls: Integer, + pub deep_first: MemoryAskOutputDeepFirst, #[serde(default = "default_1409")] - pub synth_input_tokens: Integer, + pub synth_calls: Integer, #[serde(default = "default_1410")] - pub synth_cached_input_tokens: Integer, + pub synth_input_tokens: Integer, #[serde(default = "default_1411")] - pub synth_cache_write_tokens: Integer, + pub synth_cached_input_tokens: Integer, #[serde(default = "default_1412")] - pub synth_cost_usd: f64, + pub synth_cache_write_tokens: Integer, #[serde(default = "default_1413")] - pub context_tokens_est: Integer, + pub synth_cost_usd: f64, #[serde(default = "default_1414")] - pub context_trimmed: Integer, + pub context_tokens_est: Integer, #[serde(default = "default_1415")] - pub summary_hits: Integer, + pub context_trimmed: Integer, #[serde(default = "default_1416")] - pub knowledge_hits: Integer, + pub summary_hits: Integer, #[serde(default = "default_1417")] - pub timeline_rows: Integer, + pub knowledge_hits: Integer, #[serde(default = "default_1418")] + pub timeline_rows: Integer, + #[serde(default = "default_1419")] pub count_recomputed: bool, } @@ -31141,36 +31258,36 @@ pub struct MemoryAutoRetirement { pub reason: String, pub memory_id: String, pub memory_key: String, - #[serde(default = "default_1419")] - pub agent: String, #[serde(default = "default_1420")] - pub user_id: String, + pub agent: String, #[serde(default = "default_1421")] - pub session_id: String, + pub user_id: String, #[serde(default = "default_1422")] - pub superseded_by: String, + pub session_id: String, #[serde(default = "default_1423")] - pub superseded_by_key: String, + pub superseded_by: String, #[serde(default = "default_1424")] - pub label: String, + pub superseded_by_key: String, #[serde(default = "default_1425")] - pub unconfirmed: bool, + pub label: String, #[serde(default = "default_1426")] - pub judge_verdict: String, + pub unconfirmed: bool, #[serde(default = "default_1427")] - pub judge_confidence: Option, + pub judge_verdict: String, #[serde(default = "default_1428")] - pub judge_model: String, + pub judge_confidence: Option, #[serde(default = "default_1429")] + pub judge_model: String, + #[serde(default = "default_1430")] pub judge_prompt_version: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryAutoRetirementsOutput { - #[serde(default = "default_1430")] - pub rows: Vec, #[serde(default = "default_1431")] + pub rows: Vec, + #[serde(default = "default_1432")] pub next_cursor: Option, } @@ -31264,9 +31381,9 @@ impl MemoryAutoRetirementsInput { #[non_exhaustive] pub struct BacklinkVersion { pub version: Integer, - #[serde(default = "default_1433")] - pub status: String, #[serde(default = "default_1434")] + pub status: String, + #[serde(default = "default_1435")] pub created_at: String, } @@ -31274,7 +31391,7 @@ pub struct BacklinkVersion { #[non_exhaustive] pub struct BacklinkDigest { pub session_id: String, - #[serde(default = "default_1436")] + #[serde(default = "default_1437")] pub date: String, } @@ -31282,9 +31399,9 @@ pub struct BacklinkDigest { #[non_exhaustive] pub struct BacklinkEdge { pub memory_key: String, - #[serde(default = "default_1438")] - pub relation: String, #[serde(default = "default_1439")] + pub relation: String, + #[serde(default = "default_1440")] pub created_at: String, } @@ -31292,7 +31409,7 @@ pub struct BacklinkEdge { #[non_exhaustive] pub struct BacklinkRelated { pub memory_key: String, - #[serde(default = "default_1443")] + #[serde(default = "default_1444")] pub shared_entities: Vec, } @@ -31300,19 +31417,19 @@ pub struct BacklinkRelated { #[non_exhaustive] pub struct MemoryBacklinksOutput { pub memory_key: String, - #[serde(default = "default_1432")] + #[serde(default = "default_1433")] pub found: bool, - #[serde(default = "default_1435")] + #[serde(default = "default_1436")] pub versions: Vec, - #[serde(default = "default_1437")] + #[serde(default = "default_1438")] pub digests: Vec, - #[serde(default = "default_1440")] - pub links_in: Vec, #[serde(default = "default_1441")] - pub links_out: Vec, + pub links_in: Vec, #[serde(default = "default_1442")] + pub links_out: Vec, + #[serde(default = "default_1443")] pub evidence_count: Integer, - #[serde(default = "default_1444")] + #[serde(default = "default_1445")] pub related: Vec, } @@ -31417,36 +31534,36 @@ impl MemoryBacklinksInput { #[non_exhaustive] pub struct BriefEvidence { pub memory_key: String, - #[serde(default = "default_1449")] - pub source: String, #[serde(default = "default_1450")] - pub source_class: String, + pub source: String, #[serde(default = "default_1451")] - pub verified: bool, + pub source_class: String, #[serde(default = "default_1452")] - pub when: String, + pub verified: bool, #[serde(default = "default_1453")] - pub session_id: String, + pub when: String, #[serde(default = "default_1454")] + pub session_id: String, + #[serde(default = "default_1455")] pub excerpt: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryBriefOutput { - #[serde(default = "default_1445")] - pub query: String, #[serde(default = "default_1446")] - pub answer: String, + pub query: String, #[serde(default = "default_1447")] - pub abstained: bool, + pub answer: String, #[serde(default = "default_1448")] + pub abstained: bool, + #[serde(default = "default_1449")] pub grounding: String, - #[serde(default = "default_1455")] - pub evidence: Vec, #[serde(default = "default_1456")] - pub unknowns: Vec, + pub evidence: Vec, #[serde(default = "default_1457")] + pub unknowns: Vec, + #[serde(default = "default_1458")] pub next_reads: Vec, } @@ -31860,9 +31977,9 @@ pub struct MemoryBulkGetOutputMemoryGetOutput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryBulkGetOutput { - #[serde(default = "default_1458")] - pub results: std::collections::HashMap, #[serde(default = "default_1459")] + pub results: std::collections::HashMap, + #[serde(default = "default_1460")] pub missing: Vec, } @@ -32375,7 +32492,7 @@ pub struct MemoryClearOutput { pub cleared_at: String, pub rows_affected: std::collections::HashMap, pub total: Integer, - #[serde(default = "default_1460")] + #[serde(default = "default_1461")] pub locked_skipped: Integer, } @@ -32463,21 +32580,21 @@ pub struct MemoryConsolidateResult { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryConsolidateOutput { - #[serde(default = "default_1461")] - pub consolidated: Vec, #[serde(default = "default_1462")] - pub examined: Integer, + pub consolidated: Vec, #[serde(default = "default_1463")] - pub clusters_found: Integer, + pub examined: Integer, #[serde(default = "default_1464")] - pub clusters_failed: Integer, + pub clusters_found: Integer, #[serde(default = "default_1465")] - pub clusters_refused_lossy: Integer, + pub clusters_failed: Integer, #[serde(default = "default_1466")] - pub skipped_in_flight: Integer, + pub clusters_refused_lossy: Integer, #[serde(default = "default_1467")] - pub tokens_in: Integer, + pub skipped_in_flight: Integer, #[serde(default = "default_1468")] + pub tokens_in: Integer, + #[serde(default = "default_1469")] pub tokens_out: Integer, } @@ -32618,7 +32735,7 @@ impl MemoryConsolidateInput { #[non_exhaustive] pub struct MemoryCopyToOutput { pub copied: bool, - #[serde(default = "default_1469")] + #[serde(default = "default_1470")] pub target_memory_id: String, pub target_namespace: String, pub target_key: String, @@ -32729,11 +32846,11 @@ impl MemoryCopyToInput { #[non_exhaustive] pub struct MemoryCrossPromoteOutput { pub promoted: bool, - #[serde(default = "default_1470")] + #[serde(default = "default_1471")] pub target_memory_id: String, pub target_namespace: String, pub target_key: String, - #[serde(default = "default_1471")] + #[serde(default = "default_1472")] pub cross_promoted_from_memory_id: String, } @@ -32816,23 +32933,23 @@ pub struct DedupCollapsePair { #[non_exhaustive] pub struct MemoryDedupCollapseOutput { pub namespace: String, - #[serde(default = "default_1472")] - pub prefix: String, #[serde(default = "default_1473")] - pub dry_run: bool, + pub prefix: String, #[serde(default = "default_1474")] - pub pairs: Integer, + pub dry_run: bool, #[serde(default = "default_1475")] - pub canonical_live: Integer, + pub pairs: Integer, #[serde(default = "default_1476")] - pub orphans: Integer, + pub canonical_live: Integer, #[serde(default = "default_1477")] - pub mirror_stale: Integer, + pub orphans: Integer, #[serde(default = "default_1478")] - pub restamped: Integer, + pub mirror_stale: Integer, #[serde(default = "default_1479")] - pub truncated: bool, + pub restamped: Integer, #[serde(default = "default_1480")] + pub truncated: bool, + #[serde(default = "default_1481")] pub sample: Vec, } @@ -32931,7 +33048,7 @@ pub struct DedupDuplicate { pub memory_id: String, pub memory_key: String, pub agent: String, - #[serde(default = "default_1483")] + #[serde(default = "default_1484")] pub created_at: Option, } @@ -32939,12 +33056,12 @@ pub struct DedupDuplicate { #[non_exhaustive] pub struct DedupCluster { pub canonical_id: String, - #[serde(default = "default_1481")] - pub canonical_key: String, #[serde(default = "default_1482")] + pub canonical_key: String, + #[serde(default = "default_1483")] pub canonical_agent: String, pub dup_count: Integer, - #[serde(default = "default_1484")] + #[serde(default = "default_1485")] pub duplicates: Vec, } @@ -33016,11 +33133,11 @@ pub struct MemoryDedupResolveOutput { pub canonical_key: String, pub duplicate_key: String, pub decision: String, - #[serde(default = "default_1485")] - pub canonical_tombstoned: bool, #[serde(default = "default_1486")] - pub duplicate_tombstoned: bool, + pub canonical_tombstoned: bool, #[serde(default = "default_1487")] + pub duplicate_tombstoned: bool, + #[serde(default = "default_1488")] pub ignored_args: Vec, } @@ -33158,17 +33275,17 @@ pub struct LostName { pub struct DefinitionEntry { pub memory_key: String, pub promoted_at: String, - #[serde(default = "default_1488")] - pub capped: bool, #[serde(default = "default_1489")] - pub term: Option, + pub capped: bool, #[serde(default = "default_1490")] - pub aliases: Vec, + pub term: Option, #[serde(default = "default_1491")] - pub verdict: Option, + pub aliases: Vec, #[serde(default = "default_1492")] - pub lapse_reason: Option, + pub verdict: Option, #[serde(default = "default_1493")] + pub lapse_reason: Option, + #[serde(default = "default_1494")] pub lost: Vec, } @@ -33229,15 +33346,15 @@ impl MemoryDefinitionsListInput { #[non_exhaustive] pub struct MemoryDeleteVersionOutput { pub tombstoned: bool, - #[serde(default = "default_1494")] - pub version: Integer, #[serde(default = "default_1495")] - pub found: bool, + pub version: Integer, #[serde(default = "default_1496")] - pub reason: String, + pub found: bool, #[serde(default = "default_1497")] - pub dependents_tombstoned: Integer, + pub reason: String, #[serde(default = "default_1498")] + pub dependents_tombstoned: Integer, + #[serde(default = "default_1499")] pub dependents_downgraded: Integer, } @@ -33364,21 +33481,21 @@ pub struct DemonstrationRow { pub struct MemoryDemonstrateOutput { pub query: String, pub demonstrations: Vec, - #[serde(default = "default_1499")] - pub votes: std::collections::HashMap, #[serde(default = "default_1500")] - pub predicted_label: String, + pub votes: std::collections::HashMap, #[serde(default = "default_1501")] - pub margin: f64, + pub predicted_label: String, #[serde(default = "default_1502")] - pub abstain: bool, + pub margin: f64, #[serde(default = "default_1503")] - pub abstain_reason: String, + pub abstain: bool, #[serde(default = "default_1504")] - pub few_shot_block: String, + pub abstain_reason: String, #[serde(default = "default_1505")] - pub examined: Integer, + pub few_shot_block: String, #[serde(default = "default_1506")] + pub examined: Integer, + #[serde(default = "default_1507")] pub labelled: Integer, } @@ -33518,7 +33635,7 @@ impl MemoryDemonstrateInput { pub struct MemoryDemoteOutput { pub demoted: bool, pub was_reversible: bool, - #[serde(default = "default_1507")] + #[serde(default = "default_1508")] pub tombstoned_at: Option, } @@ -33580,15 +33697,15 @@ impl MemoryDemoteInput { pub struct DigestRow { pub session_id: String, pub summary_text: String, - #[serde(default = "default_1508")] - pub key_facts: Vec, #[serde(default = "default_1509")] - pub derived_from: Vec, + pub key_facts: Vec, #[serde(default = "default_1510")] - pub valid_at: Option, + pub derived_from: Vec, #[serde(default = "default_1511")] - pub created_at: Option, + pub valid_at: Option, #[serde(default = "default_1512")] + pub created_at: Option, + #[serde(default = "default_1513")] pub version: Integer, } @@ -33596,7 +33713,7 @@ pub struct DigestRow { #[non_exhaustive] pub struct MemoryDigestsOutput { pub rows: Vec, - #[serde(default = "default_1513")] + #[serde(default = "default_1514")] pub truncated: bool, } @@ -33721,17 +33838,17 @@ pub struct MemoryEvidenceItem { pub evidence_id: String, pub support_type: String, pub scope: MemoryEvidenceItemScope, - #[serde(default = "default_1517")] - pub role: String, #[serde(default = "default_1518")] - pub observed_at: Option, + pub role: String, #[serde(default = "default_1519")] - pub content: String, + pub observed_at: Option, #[serde(default = "default_1520")] - pub char_start: Integer, + pub content: String, #[serde(default = "default_1521")] - pub char_end: Integer, + pub char_start: Integer, #[serde(default = "default_1522")] + pub char_end: Integer, + #[serde(default = "default_1523")] pub span: String, } @@ -33739,23 +33856,23 @@ pub struct MemoryEvidenceItem { #[non_exhaustive] pub struct MemoryEvidenceOutput { pub found: bool, - #[serde(default = "default_1514")] - pub memory_key: String, #[serde(default = "default_1515")] - pub memory_id: String, + pub memory_key: String, #[serde(default = "default_1516")] + pub memory_id: String, + #[serde(default = "default_1517")] pub value: String, - #[serde(default = "default_1523")] - pub items: Vec, #[serde(default = "default_1524")] - pub truncated: bool, + pub items: Vec, #[serde(default = "default_1525")] - pub cited: Integer, + pub truncated: bool, #[serde(default = "default_1526")] - pub lexical: Integer, + pub cited: Integer, #[serde(default = "default_1527")] - pub window: Integer, + pub lexical: Integer, #[serde(default = "default_1528")] + pub window: Integer, + #[serde(default = "default_1529")] pub derived: Integer, } @@ -33860,26 +33977,26 @@ impl MemoryEvidenceInput { #[non_exhaustive] pub struct EvidenceChunk { pub session_id: String, - #[serde(default = "default_1529")] + #[serde(default = "default_1530")] pub chunk_index: Integer, pub content: String, - #[serde(default = "default_1530")] - pub content_sha256: String, #[serde(default = "default_1531")] - pub agent: String, + pub content_sha256: String, #[serde(default = "default_1532")] - pub user_id: String, + pub agent: String, #[serde(default = "default_1533")] - pub parent_memory_key: String, + pub user_id: String, #[serde(default = "default_1534")] - pub memory_keys: Vec, + pub parent_memory_key: String, #[serde(default = "default_1535")] - pub line_start: Integer, + pub memory_keys: Vec, #[serde(default = "default_1536")] - pub line_end: Integer, + pub line_start: Integer, #[serde(default = "default_1537")] - pub created_at: String, + pub line_end: Integer, #[serde(default = "default_1538")] + pub created_at: String, + #[serde(default = "default_1539")] pub source_url: String, } @@ -33888,17 +34005,17 @@ pub struct EvidenceChunk { pub struct EvidenceDigest { pub session_id: String, pub summary_text: String, - #[serde(default = "default_1540")] - pub agent: String, #[serde(default = "default_1541")] - pub user_id: String, + pub agent: String, #[serde(default = "default_1542")] - pub key_facts: Vec, + pub user_id: String, #[serde(default = "default_1543")] - pub derived_from: Vec, + pub key_facts: Vec, #[serde(default = "default_1544")] - pub valid_at: String, + pub derived_from: Vec, #[serde(default = "default_1545")] + pub valid_at: String, + #[serde(default = "default_1546")] pub created_at: String, } @@ -33908,28 +34025,28 @@ pub struct EvidenceEdge { pub from_key: String, pub to_key: String, pub relation: String, - #[serde(default = "default_1547")] - pub confidence: f64, #[serde(default = "default_1548")] - pub explanation: String, + pub confidence: f64, #[serde(default = "default_1549")] + pub explanation: String, + #[serde(default = "default_1550")] pub created_at: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExportEvidenceOutput { - #[serde(default = "default_1539")] + #[serde(default = "default_1540")] pub chunks: Vec, - #[serde(default = "default_1546")] + #[serde(default = "default_1547")] pub digests: Vec, - #[serde(default = "default_1550")] - pub edges: Vec, #[serde(default = "default_1551")] - pub has_more: bool, + pub edges: Vec, #[serde(default = "default_1552")] - pub next_cursor: String, + pub has_more: bool, #[serde(default = "default_1553")] + pub next_cursor: String, + #[serde(default = "default_1554")] pub held_high: Integer, } @@ -34122,15 +34239,15 @@ impl ExposureSummaryInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExtractionRetryMineOutput { - #[serde(default = "default_1554")] - pub requeued: Vec, #[serde(default = "default_1555")] - pub not_failed: Vec, + pub requeued: Vec, #[serde(default = "default_1556")] - pub model_calls_off: Vec, + pub not_failed: Vec, #[serde(default = "default_1557")] - pub expired: Vec, + pub model_calls_off: Vec, #[serde(default = "default_1558")] + pub expired: Vec, + #[serde(default = "default_1559")] pub unknown: Vec, } @@ -34191,20 +34308,20 @@ pub struct ExtractionQueueRow { pub content_chars: Integer, pub written: Integer, pub last_error: String, - #[serde(default = "default_1559")] - pub enqueued_at: Option, #[serde(default = "default_1560")] + pub enqueued_at: Option, + #[serde(default = "default_1561")] pub updated_at: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExtractionStatusOutput { - #[serde(default = "default_1561")] - pub batches: Vec, #[serde(default = "default_1562")] - pub pending: Integer, + pub batches: Vec, #[serde(default = "default_1563")] + pub pending: Integer, + #[serde(default = "default_1564")] pub failed: Integer, } @@ -34352,13 +34469,13 @@ impl MemoryExtractionStatusInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryExtractionStatusMineOutput { - #[serde(default = "default_1564")] - pub batches: Vec, #[serde(default = "default_1565")] - pub unknown: Vec, + pub batches: Vec, #[serde(default = "default_1566")] - pub pending: Integer, + pub unknown: Vec, #[serde(default = "default_1567")] + pub pending: Integer, + #[serde(default = "default_1568")] pub failed: Integer, } @@ -34479,39 +34596,39 @@ pub struct MemoryForFileHit { pub memory_key: String, pub memory_type: String, pub value: String, - #[serde(default = "default_1568")] - pub value_truncated: bool, #[serde(default = "default_1569")] - pub tags: Vec, + pub value_truncated: bool, #[serde(default = "default_1570")] - pub confidence: f64, + pub tags: Vec, #[serde(default = "default_1571")] - pub pinned: bool, + pub confidence: f64, #[serde(default = "default_1572")] - pub status: String, + pub pinned: bool, #[serde(default = "default_1573")] - pub agent: String, + pub status: String, #[serde(default = "default_1574")] - pub updated_at: Option, + pub agent: String, #[serde(default = "default_1575")] - pub namespace: String, + pub updated_at: Option, #[serde(default = "default_1576")] - pub actor: String, + pub namespace: String, #[serde(default = "default_1577")] - pub supersedes_key: String, + pub actor: String, #[serde(default = "default_1578")] - pub supersedes: String, + pub supersedes_key: String, #[serde(default = "default_1579")] - pub supersedes_kind: MemoryForFileHitSupersedesKind, + pub supersedes: String, #[serde(default = "default_1580")] - pub matched_files: Vec, + pub supersedes_kind: MemoryForFileHitSupersedesKind, #[serde(default = "default_1581")] - pub source_resource_id: String, + pub matched_files: Vec, #[serde(default = "default_1582")] - pub verification: MemoryForFileHitVerification, + pub source_resource_id: String, #[serde(default = "default_1583")] - pub code_state: MemoryForFileHitCodeState, + pub verification: MemoryForFileHitVerification, #[serde(default = "default_1584")] + pub code_state: MemoryForFileHitCodeState, + #[serde(default = "default_1585")] pub code_moved: Vec, } @@ -34521,11 +34638,11 @@ pub struct MemoryForFileOutput { pub path: String, pub total: Integer, pub hits: Vec, - #[serde(default = "default_1585")] - pub rendered: String, #[serde(default = "default_1586")] - pub tokens_estimate: Integer, + pub rendered: String, #[serde(default = "default_1587")] + pub tokens_estimate: Integer, + #[serde(default = "default_1588")] pub truncated: bool, } @@ -34633,61 +34750,61 @@ impl MemoryForFileInput { #[non_exhaustive] pub struct MemoryGetByIdOutput { pub found: bool, - #[serde(default = "default_1588")] - pub memory_id: String, #[serde(default = "default_1589")] - pub namespace: String, + pub memory_id: String, #[serde(default = "default_1590")] - pub agent: String, + pub namespace: String, #[serde(default = "default_1591")] - pub user_id: String, + pub agent: String, #[serde(default = "default_1592")] - pub session_id: String, + pub user_id: String, #[serde(default = "default_1593")] - pub memory_key: String, + pub session_id: String, #[serde(default = "default_1594")] - pub memory_type: Option, + pub memory_key: String, #[serde(default = "default_1595")] - pub value: Value, + pub memory_type: Option, #[serde(default = "default_1596")] - pub confidence: Option, + pub value: Value, #[serde(default = "default_1597")] - pub version: Option, + pub confidence: Option, #[serde(default = "default_1598")] - pub created_at: Option, + pub version: Option, #[serde(default = "default_1599")] - pub expires_at: Option, + pub created_at: Option, #[serde(default = "default_1600")] - pub valid_at: Option, + pub expires_at: Option, #[serde(default = "default_1601")] - pub valid_to: Option, + pub valid_at: Option, #[serde(default = "default_1602")] - pub pinned: bool, + pub valid_to: Option, #[serde(default = "default_1603")] - pub content_sha256: String, + pub pinned: bool, #[serde(default = "default_1604")] - pub verified_by: String, + pub content_sha256: String, #[serde(default = "default_1605")] - pub verified_at: Option, + pub verified_by: String, #[serde(default = "default_1606")] - pub verification: String, + pub verified_at: Option, #[serde(default = "default_1607")] - pub sensitivity: String, + pub verification: String, #[serde(default = "default_1608")] - pub actor: String, + pub sensitivity: String, #[serde(default = "default_1609")] - pub source_class: String, + pub actor: String, #[serde(default = "default_1610")] - pub lock_mode: String, + pub source_class: String, #[serde(default = "default_1611")] - pub lock_reason: String, + pub lock_mode: String, #[serde(default = "default_1612")] - pub lock_until: Option, + pub lock_reason: String, #[serde(default = "default_1613")] - pub locked_by: String, + pub lock_until: Option, #[serde(default = "default_1614")] - pub on_expire: String, + pub locked_by: String, #[serde(default = "default_1615")] + pub on_expire: String, + #[serde(default = "default_1616")] pub expire_reason: String, } @@ -34763,41 +34880,41 @@ pub struct MemoryHealthTopRow { pub memory_type: String, pub recall_count: Integer, pub used_count: Integer, - #[serde(default = "default_1618")] - pub harm_count: Integer, #[serde(default = "default_1619")] + pub harm_count: Integer, + #[serde(default = "default_1620")] pub last_recalled_at: Option, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryHealthStaleness { - #[serde(default = "default_1621")] - pub by_age: std::collections::HashMap, #[serde(default = "default_1622")] - pub with_validity_end: Integer, + pub by_age: std::collections::HashMap, #[serde(default = "default_1623")] - pub with_validity_end_share: f64, + pub with_validity_end: Integer, #[serde(default = "default_1624")] - pub with_expiry: Integer, + pub with_validity_end_share: f64, #[serde(default = "default_1625")] - pub expiring_7d: Integer, + pub with_expiry: Integer, #[serde(default = "default_1626")] - pub pinned: Integer, + pub expiring_7d: Integer, #[serde(default = "default_1627")] - pub days_since_reinforced_p50: Integer, + pub pinned: Integer, #[serde(default = "default_1628")] + pub days_since_reinforced_p50: Integer, + #[serde(default = "default_1629")] pub days_since_reinforced_p90: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryHealthFootprint { - #[serde(default = "default_1630")] - pub value_chars: Integer, #[serde(default = "default_1631")] - pub value_tokens_est: Integer, + pub value_chars: Integer, #[serde(default = "default_1632")] + pub value_tokens_est: Integer, + #[serde(default = "default_1633")] pub tokens_per_row_est: f64, } @@ -34807,19 +34924,19 @@ pub struct MemoryHealthOutput { pub live: Integer, pub recalled_ever: Integer, pub used_ever: Integer, - #[serde(default = "default_1616")] + #[serde(default = "default_1617")] pub harmed_ever: Integer, pub silent: Integer, pub silent_older: Integer, pub silent_share: f64, pub silent_after_days: Integer, - #[serde(default = "default_1617")] + #[serde(default = "default_1618")] pub by_type: Vec, - #[serde(default = "default_1620")] + #[serde(default = "default_1621")] pub top_recalled: Vec, - #[serde(default = "default_1629")] + #[serde(default = "default_1630")] pub staleness: MemoryHealthStaleness, - #[serde(default = "default_1633")] + #[serde(default = "default_1634")] pub footprint: MemoryHealthFootprint, } @@ -34939,51 +35056,51 @@ impl MemoryHealthInput { pub struct MemoryHistoryRow { pub memory_id: String, pub version: Integer, - #[serde(default = "default_1634")] - pub version_text: String, #[serde(default = "default_1635")] + pub version_text: String, + #[serde(default = "default_1636")] pub value: Value, pub confidence: f64, - #[serde(default = "default_1636")] - pub source_trace: String, #[serde(default = "default_1637")] + pub source_trace: String, + #[serde(default = "default_1638")] pub pinned: bool, pub created_at: String, - #[serde(default = "default_1638")] - pub expires_at: Option, #[serde(default = "default_1639")] - pub tombstoned_at: Option, + pub expires_at: Option, #[serde(default = "default_1640")] - pub redacted_at: Option, + pub tombstoned_at: Option, #[serde(default = "default_1641")] - pub redaction_reason: String, + pub redacted_at: Option, #[serde(default = "default_1642")] - pub content_sha256: String, + pub redaction_reason: String, #[serde(default = "default_1643")] - pub actor: String, + pub content_sha256: String, #[serde(default = "default_1644")] - pub source_class: String, + pub actor: String, #[serde(default = "default_1645")] - pub agent: String, + pub source_class: String, #[serde(default = "default_1646")] - pub written_at: Option, + pub agent: String, #[serde(default = "default_1647")] - pub status: String, + pub written_at: Option, #[serde(default = "default_1648")] - pub conflict_with: Vec, + pub status: String, #[serde(default = "default_1649")] - pub tags: Vec, + pub conflict_with: Vec, #[serde(default = "default_1650")] - pub verified_at: Option, + pub tags: Vec, #[serde(default = "default_1651")] - pub verified_by: String, + pub verified_at: Option, #[serde(default = "default_1652")] - pub verified_sha256: String, + pub verified_by: String, #[serde(default = "default_1653")] - pub lock_mode: String, + pub verified_sha256: String, #[serde(default = "default_1654")] - pub lock_reason: String, + pub lock_mode: String, #[serde(default = "default_1655")] + pub lock_reason: String, + #[serde(default = "default_1656")] pub lock_until: Option, } @@ -35093,13 +35210,13 @@ impl MemoryHistoryInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryImportTotals { - #[serde(default = "default_1656")] - pub written: Integer, #[serde(default = "default_1657")] - pub held: Integer, + pub written: Integer, #[serde(default = "default_1658")] - pub skipped: Integer, + pub held: Integer, #[serde(default = "default_1659")] + pub skipped: Integer, + #[serde(default = "default_1660")] pub refused: Integer, } @@ -35182,11 +35299,11 @@ pub struct MemoryImportResult { pub index: Integer, pub key: String, pub outcome: MemoryImportResultOutcome, - #[serde(default = "default_1660")] - pub reason: MemoryImportResultReason, #[serde(default = "default_1661")] - pub held_by: String, + pub reason: MemoryImportResultReason, #[serde(default = "default_1662")] + pub held_by: String, + #[serde(default = "default_1663")] pub note: MemoryImportResultNote, } @@ -35195,7 +35312,7 @@ pub struct MemoryImportResult { pub struct MemoryImportOutput { pub totals: MemoryImportTotals, pub results: Vec, - #[serde(default = "default_1663")] + #[serde(default = "default_1664")] pub dry_run: bool, } @@ -35388,9 +35505,9 @@ pub struct MemoryImportCuratedRow { pub section_heading: String, pub bytes_written: Integer, pub verdict: String, - #[serde(default = "default_1664")] - pub rejection_reason: String, #[serde(default = "default_1665")] + pub rejection_reason: String, + #[serde(default = "default_1666")] pub pinned_blocker_id: Option, } @@ -35482,21 +35599,21 @@ impl MemoryImportCuratedInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryImportEvidenceOutput { - #[serde(default = "default_1666")] - pub chunks_written: Integer, #[serde(default = "default_1667")] - pub links_written: Integer, + pub chunks_written: Integer, #[serde(default = "default_1668")] - pub digests_written: Integer, + pub links_written: Integer, #[serde(default = "default_1669")] - pub embedding_model: String, + pub digests_written: Integer, #[serde(default = "default_1670")] - pub embedding_dim: Integer, + pub embedding_model: String, #[serde(default = "default_1671")] - pub edited: Vec, + pub embedding_dim: Integer, #[serde(default = "default_1672")] - pub skipped: Integer, + pub edited: Vec, #[serde(default = "default_1673")] + pub skipped: Integer, + #[serde(default = "default_1674")] pub unchecked: Integer, } @@ -35833,7 +35950,7 @@ pub struct InspectRow { pub memory_key: String, pub memory_id: String, pub version: Integer, - #[serde(default = "default_1683")] + #[serde(default = "default_1684")] pub content_sha256: String, pub memory_type: String, pub status: String, @@ -35844,9 +35961,9 @@ pub struct InspectRow { pub actor: String, pub updated_at: String, pub sensitivity: String, - #[serde(default = "default_1684")] - pub versions: Integer, #[serde(default = "default_1685")] + pub versions: Integer, + #[serde(default = "default_1686")] pub excerpt: String, } @@ -35854,27 +35971,27 @@ pub struct InspectRow { #[non_exhaustive] pub struct InspectView { pub definition: String, - #[serde(default = "default_1674")] - pub refs: Vec, #[serde(default = "default_1675")] - pub live_rows: Integer, + pub refs: Vec, #[serde(default = "default_1676")] - pub by_type: Vec, + pub live_rows: Integer, #[serde(default = "default_1677")] - pub by_status: Vec, + pub by_type: Vec, #[serde(default = "default_1678")] - pub by_source_class: Vec, + pub by_status: Vec, #[serde(default = "default_1679")] - pub top_tags: Vec, + pub by_source_class: Vec, #[serde(default = "default_1680")] - pub categories: Vec, + pub top_tags: Vec, #[serde(default = "default_1681")] - pub first_updated_at: Option, + pub categories: Vec, #[serde(default = "default_1682")] + pub first_updated_at: Option, + #[serde(default = "default_1683")] pub last_updated_at: Option, - #[serde(default = "default_1686")] - pub newest: Vec, #[serde(default = "default_1687")] + pub newest: Vec, + #[serde(default = "default_1688")] pub complete: bool, } @@ -35890,32 +36007,32 @@ pub struct InspectCall { #[non_exhaustive] pub struct InspectActivity { pub window_seconds: Integer, - #[serde(default = "default_1688")] - pub calls: Vec, #[serde(default = "default_1689")] - pub first_at: Option, + pub calls: Vec, #[serde(default = "default_1690")] - pub last_at: Option, + pub first_at: Option, #[serde(default = "default_1691")] + pub last_at: Option, + #[serde(default = "default_1692")] pub gap: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct InspectSettings { - #[serde(default = "default_1692")] - pub guide_revision: Integer, #[serde(default = "default_1693")] - pub guide_summary: String, + pub guide_revision: Integer, #[serde(default = "default_1694")] - pub categories_registered: Integer, + pub guide_summary: String, #[serde(default = "default_1695")] - pub extraction_policy: Option, + pub categories_registered: Integer, #[serde(default = "default_1696")] - pub extraction_policy_unavailable: String, + pub extraction_policy: Option, #[serde(default = "default_1697")] - pub extraction_instructions: String, + pub extraction_policy_unavailable: String, #[serde(default = "default_1698")] + pub extraction_instructions: String, + #[serde(default = "default_1699")] pub extraction_instructions_refs: Vec, } @@ -35931,7 +36048,7 @@ pub struct MemoryInspectOutput { pub others: InspectView, pub activity: InspectActivity, pub settings: InspectSettings, - #[serde(default = "default_1699")] + #[serde(default = "default_1700")] pub skipped: Vec, } @@ -36025,7 +36142,7 @@ pub struct MemoryKeyRef { #[non_exhaustive] pub struct MemoryKeysOutput { pub keys: Vec, - #[serde(default = "default_1700")] + #[serde(default = "default_1701")] pub truncated: bool, } @@ -36128,9 +36245,9 @@ pub struct LineageCandidate { pub decided_at: String, pub decided_by: String, pub match_confidence: LineageCandidateMatchConfidence, - #[serde(default = "default_1709")] - pub seeded_from_thread_id: String, #[serde(default = "default_1710")] + pub seeded_from_thread_id: String, + #[serde(default = "default_1711")] pub seeded_from_msg_id: String, } @@ -36148,25 +36265,25 @@ pub struct LineageAuditEvent { pub struct MemoryLineageOutput { pub found: bool, pub memory_key: String, - #[serde(default = "default_1701")] - pub promotion_event: String, #[serde(default = "default_1702")] - pub promoted_by: String, + pub promotion_event: String, #[serde(default = "default_1703")] - pub promoted_at: Option, + pub promoted_by: String, #[serde(default = "default_1704")] - pub rationale: String, + pub promoted_at: Option, #[serde(default = "default_1705")] - pub source_trace: String, + pub rationale: String, #[serde(default = "default_1706")] - pub source_resource_id: String, + pub source_trace: String, #[serde(default = "default_1707")] - pub mechanism: MemoryLineageOutputMechanism, + pub source_resource_id: String, #[serde(default = "default_1708")] + pub mechanism: MemoryLineageOutputMechanism, + #[serde(default = "default_1709")] pub supporters: Vec, - #[serde(default = "default_1711")] - pub candidate: Option, #[serde(default = "default_1712")] + pub candidate: Option, + #[serde(default = "default_1713")] pub audit_chain: Vec, } @@ -36295,11 +36412,11 @@ pub struct MemoryLinkOutput { pub from_key: String, pub to_key: String, pub relation: String, - #[serde(default = "default_1713")] - pub confidence: f64, #[serde(default = "default_1714")] - pub conflict_opened: bool, + pub confidence: f64, #[serde(default = "default_1715")] + pub conflict_opened: bool, + #[serde(default = "default_1716")] pub relation_defaulted: bool, } @@ -36613,17 +36730,17 @@ pub struct MemoryListEntry { pub struct MemoryListOutput { pub entries: Vec, pub truncated: bool, - #[serde(default = "default_1716")] - pub total: Integer, #[serde(default = "default_1717")] - pub today: Integer, + pub total: Integer, #[serde(default = "default_1718")] - pub namespace_version: String, + pub today: Integer, #[serde(default = "default_1719")] - pub unchanged: bool, + pub namespace_version: String, #[serde(default = "default_1720")] - pub hidden: Integer, + pub unchanged: bool, #[serde(default = "default_1721")] + pub hidden: Integer, + #[serde(default = "default_1722")] pub hidden_hint: String, } @@ -37009,19 +37126,19 @@ impl MemoryListInput { #[non_exhaustive] pub struct MemoryLockOutput { pub locked: bool, - #[serde(default = "default_1722")] - pub reason: String, #[serde(default = "default_1723")] - pub memory_id: String, + pub reason: String, #[serde(default = "default_1724")] - pub version: Option, + pub memory_id: String, #[serde(default = "default_1725")] - pub lock_mode: String, + pub version: Option, #[serde(default = "default_1726")] - pub lock_until: Option, + pub lock_mode: String, #[serde(default = "default_1727")] - pub locked_by: String, + pub lock_until: Option, #[serde(default = "default_1728")] + pub locked_by: String, + #[serde(default = "default_1729")] pub previous_mode: String, } @@ -37180,21 +37297,21 @@ pub struct MemoryMoveOutput { pub from_key: String, pub to_key: String, pub redirected: bool, - #[serde(default = "default_1729")] - pub memory_id: String, #[serde(default = "default_1730")] - pub version: Integer, + pub memory_id: String, #[serde(default = "default_1731")] - pub content_sha256: String, + pub version: Integer, #[serde(default = "default_1732")] - pub advisories: Vec, + pub content_sha256: String, #[serde(default = "default_1733")] - pub dry_run: bool, + pub advisories: Vec, #[serde(default = "default_1734")] - pub memory_type: String, + pub dry_run: bool, #[serde(default = "default_1735")] - pub value_preview: String, + pub memory_type: String, #[serde(default = "default_1736")] + pub value_preview: String, + #[serde(default = "default_1737")] pub sensitivity: String, } @@ -37406,7 +37523,7 @@ impl MemoryMoveInput { pub struct MemoryOutcomeOutput { pub recorded: bool, pub evidence_count_after: Integer, - #[serde(default = "default_1737")] + #[serde(default = "default_1738")] pub quarantined: bool, } @@ -37649,13 +37766,13 @@ impl MemoryOutcomeRunInput { #[non_exhaustive] pub struct OutlineSession { pub session_id: String, - #[serde(default = "default_1739")] - pub date: String, #[serde(default = "default_1740")] - pub headline: String, + pub date: String, #[serde(default = "default_1741")] - pub key_facts: Integer, + pub headline: String, #[serde(default = "default_1742")] + pub key_facts: Integer, + #[serde(default = "default_1743")] pub rows: Integer, } @@ -37663,7 +37780,7 @@ pub struct OutlineSession { #[non_exhaustive] pub struct OutlineHub { pub entity: String, - #[serde(default = "default_1745")] + #[serde(default = "default_1746")] pub degree: Integer, } @@ -37671,28 +37788,28 @@ pub struct OutlineHub { #[non_exhaustive] pub struct OutlineCommunity { pub community_id: Integer, - #[serde(default = "default_1747")] - pub label: String, #[serde(default = "default_1748")] - pub size: Integer, + pub label: String, #[serde(default = "default_1749")] + pub size: Integer, + #[serde(default = "default_1750")] pub computed_at: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryOutlineOutput { - #[serde(default = "default_1738")] + #[serde(default = "default_1739")] pub rows_by_type: std::collections::HashMap, - #[serde(default = "default_1743")] - pub sessions: Vec, #[serde(default = "default_1744")] + pub sessions: Vec, + #[serde(default = "default_1745")] pub sessions_total: Integer, - #[serde(default = "default_1746")] + #[serde(default = "default_1747")] pub hubs: Vec, - #[serde(default = "default_1750")] - pub communities: Vec, #[serde(default = "default_1751")] + pub communities: Vec, + #[serde(default = "default_1752")] pub profile_chars: Integer, } @@ -37844,7 +37961,7 @@ pub struct OwnerUsageRow { pub recalls: Integer, pub used: Integer, pub harm: Integer, - #[serde(default = "default_1752")] + #[serde(default = "default_1753")] pub last_recalled: Option, } @@ -38331,7 +38448,7 @@ pub struct MemoryPromoteOutput { pub shared_memory_key: String, pub promotion_event: String, pub reversible_until: String, - #[serde(default = "default_1753")] + #[serde(default = "default_1754")] pub ignored_args: Vec, } @@ -38500,18 +38617,18 @@ impl MemoryPromoteInput { pub struct MemoryProposalDecision { pub memory_key: String, pub decided: bool, - #[serde(default = "default_1755")] - pub status: String, #[serde(default = "default_1756")] + pub status: String, + #[serde(default = "default_1757")] pub reason: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryProposalDecideOutput { - #[serde(default = "default_1754")] + #[serde(default = "default_1755")] pub decided: Integer, - #[serde(default = "default_1757")] + #[serde(default = "default_1758")] pub results: Vec, } @@ -38612,33 +38729,33 @@ pub enum MemoryProposalReady { pub struct MemoryProposal { pub memory_key: String, pub memory_id: String, - #[serde(default = "default_1758")] - pub content_sha256: String, #[serde(default = "default_1759")] - pub agent: String, + pub content_sha256: String, #[serde(default = "default_1760")] - pub memory_type: String, + pub agent: String, #[serde(default = "default_1761")] - pub value_preview: String, + pub memory_type: String, #[serde(default = "default_1762")] - pub sensitivity: String, + pub value_preview: String, #[serde(default = "default_1763")] - pub tags: Vec, + pub sensitivity: String, #[serde(default = "default_1764")] - pub created_at: String, + pub tags: Vec, #[serde(default = "default_1765")] - pub graded_passes: Integer, + pub created_at: String, #[serde(default = "default_1766")] - pub graded_fails: Integer, + pub graded_passes: Integer, #[serde(default = "default_1767")] - pub last_graded_at: String, + pub graded_fails: Integer, #[serde(default = "default_1768")] - pub used_count: Integer, + pub last_graded_at: String, #[serde(default = "default_1769")] - pub harm_count: Integer, + pub used_count: Integer, #[serde(default = "default_1770")] - pub ready: MemoryProposalReady, + pub harm_count: Integer, #[serde(default = "default_1771")] + pub ready: MemoryProposalReady, + #[serde(default = "default_1772")] pub conflict_with: Vec, } @@ -38654,24 +38771,24 @@ pub enum ProposalPolicyMode { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProposalPolicy { - #[serde(default = "default_1774")] - pub mode: ProposalPolicyMode, #[serde(default = "default_1775")] - pub min_passes: Integer, + pub mode: ProposalPolicyMode, #[serde(default = "default_1776")] - pub max_fails: Integer, + pub min_passes: Integer, #[serde(default = "default_1777")] + pub max_fails: Integer, + #[serde(default = "default_1778")] pub reject_after_fails: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryProposalsOutput { - #[serde(default = "default_1772")] - pub proposals: Vec, #[serde(default = "default_1773")] + pub proposals: Vec, + #[serde(default = "default_1774")] pub total: Integer, - #[serde(default = "default_1778")] + #[serde(default = "default_1779")] pub policy: ProposalPolicy, } @@ -38789,19 +38906,19 @@ impl MemoryProposalsInput { pub struct MemoryProvenanceLink { pub direction: String, pub memory_key: String, - #[serde(default = "default_1792")] - pub relation: String, #[serde(default = "default_1793")] - pub label: String, + pub relation: String, #[serde(default = "default_1794")] - pub explanation: String, + pub label: String, #[serde(default = "default_1795")] - pub evidence: Vec, + pub explanation: String, #[serde(default = "default_1796")] - pub confidence: f64, + pub evidence: Vec, #[serde(default = "default_1797")] - pub author: String, + pub confidence: f64, #[serde(default = "default_1798")] + pub author: String, + #[serde(default = "default_1799")] pub run_id: String, } @@ -38809,33 +38926,33 @@ pub struct MemoryProvenanceLink { #[non_exhaustive] pub struct MemoryProvenanceOutput { pub found: bool, - #[serde(default = "default_1779")] - pub source_trace: String, #[serde(default = "default_1780")] - pub source_kind: String, + pub source_trace: String, #[serde(default = "default_1781")] - pub actor: String, + pub source_kind: String, #[serde(default = "default_1782")] - pub source_class: String, + pub actor: String, #[serde(default = "default_1783")] - pub source_label: String, + pub source_class: String, #[serde(default = "default_1784")] - pub thread_id: String, + pub source_label: String, #[serde(default = "default_1785")] - pub thread_exists: bool, + pub thread_id: String, #[serde(default = "default_1786")] - pub thread_title: String, + pub thread_exists: bool, #[serde(default = "default_1787")] - pub agent: String, + pub thread_title: String, #[serde(default = "default_1788")] - pub session_id: String, + pub agent: String, #[serde(default = "default_1789")] - pub run_id: String, + pub session_id: String, #[serde(default = "default_1790")] - pub written_at: String, + pub run_id: String, #[serde(default = "default_1791")] + pub written_at: String, + #[serde(default = "default_1792")] pub source_resource_id: String, - #[serde(default = "default_1799")] + #[serde(default = "default_1800")] pub links: Vec, } @@ -38930,17 +39047,17 @@ impl MemoryProvenanceInput { pub struct RecallTurn { pub evidence_id: String, pub session_id: String, - #[serde(default = "default_1800")] - pub role: String, #[serde(default = "default_1801")] - pub actor: String, + pub role: String, #[serde(default = "default_1802")] - pub observed_at: String, + pub actor: String, #[serde(default = "default_1803")] - pub content: String, + pub observed_at: String, #[serde(default = "default_1804")] - pub truncated: bool, + pub content: String, #[serde(default = "default_1805")] + pub truncated: bool, + #[serde(default = "default_1806")] pub matched_tokens: Integer, } @@ -38957,21 +39074,21 @@ pub enum MemoryRecallOutputOrder { #[non_exhaustive] pub struct MemoryRecallOutput { pub turns: Vec, - #[serde(default = "default_1806")] - pub total_matched: Integer, #[serde(default = "default_1807")] - pub returned: Integer, + pub total_matched: Integer, #[serde(default = "default_1808")] - pub has_more: bool, + pub returned: Integer, #[serde(default = "default_1809")] - pub next_cursor: String, + pub has_more: bool, #[serde(default = "default_1810")] - pub next_offset: Integer, + pub next_cursor: String, #[serde(default = "default_1811")] - pub order: MemoryRecallOutputOrder, + pub next_offset: Integer, #[serde(default = "default_1812")] - pub query_tokens: Vec, + pub order: MemoryRecallOutputOrder, #[serde(default = "default_1813")] + pub query_tokens: Vec, + #[serde(default = "default_1814")] pub tokens_returned: Integer, } @@ -39253,19 +39370,19 @@ pub struct MemoryRecordConflictRow { pub schema_name: String, pub memory_key: String, pub field_name: String, - #[serde(default = "default_1814")] - pub prior_value: Value, #[serde(default = "default_1815")] + pub prior_value: Value, + #[serde(default = "default_1816")] pub incoming_value: Value, pub prior_record_id: String, pub incoming_record_id: String, - #[serde(default = "default_1816")] - pub prior_memory_id: String, #[serde(default = "default_1817")] - pub incoming_memory_id: String, + pub prior_memory_id: String, #[serde(default = "default_1818")] - pub detected_at: Option, + pub incoming_memory_id: String, #[serde(default = "default_1819")] + pub detected_at: Option, + #[serde(default = "default_1820")] pub resolved_at: Option, } @@ -39273,7 +39390,7 @@ pub struct MemoryRecordConflictRow { #[non_exhaustive] pub struct MemoryRecordConflictsOutput { pub rows: Vec, - #[serde(default = "default_1820")] + #[serde(default = "default_1821")] pub truncated: bool, } @@ -39383,19 +39500,19 @@ pub enum MemoryRecordRowStatus { #[non_exhaustive] pub struct MemoryRecordRow { pub record_id: String, - #[serde(default = "default_1821")] - pub memory_key: String, #[serde(default = "default_1822")] - pub memory_id: String, + pub memory_key: String, #[serde(default = "default_1823")] - pub record: std::collections::HashMap, + pub memory_id: String, #[serde(default = "default_1824")] - pub field_states: std::collections::HashMap, + pub record: std::collections::HashMap, #[serde(default = "default_1825")] - pub status: MemoryRecordRowStatus, + pub field_states: std::collections::HashMap, #[serde(default = "default_1826")] - pub valid_at: Option, + pub status: MemoryRecordRowStatus, #[serde(default = "default_1827")] + pub valid_at: Option, + #[serde(default = "default_1828")] pub valid_to: Option, } @@ -39462,7 +39579,7 @@ impl MemoryRecordHistoryInput { #[non_exhaustive] pub struct MemoryRecordQueryOutput { pub rows: Vec, - #[serde(default = "default_1828")] + #[serde(default = "default_1829")] pub truncated: bool, } @@ -39686,15 +39803,15 @@ pub enum MemoryRecordWriteOutputKeySource { pub struct MemoryRecordWriteOutput { pub record_id: String, pub field_count: Integer, - #[serde(default = "default_1829")] - pub memory_key: String, #[serde(default = "default_1830")] - pub key_source: MemoryRecordWriteOutputKeySource, + pub memory_key: String, #[serde(default = "default_1831")] - pub fold: std::collections::HashMap, + pub key_source: MemoryRecordWriteOutputKeySource, #[serde(default = "default_1832")] - pub superseded_record_id: String, + pub fold: std::collections::HashMap, #[serde(default = "default_1833")] + pub superseded_record_id: String, + #[serde(default = "default_1834")] pub conflicts: Integer, } @@ -39937,13 +40054,13 @@ impl MemoryRecordWriteInput { #[non_exhaustive] pub struct MemoryRedactOutput { pub redacted: bool, - #[serde(default = "default_1834")] - pub refused_head: bool, #[serde(default = "default_1835")] - pub redacted_at: Option, + pub refused_head: bool, #[serde(default = "default_1836")] - pub cache_rows_deleted: Integer, + pub redacted_at: Option, #[serde(default = "default_1837")] + pub cache_rows_deleted: Integer, + #[serde(default = "default_1838")] pub precedent_rows_deleted: Integer, } @@ -40103,7 +40220,7 @@ impl MemoryReindexInput { #[non_exhaustive] pub struct MemoryRejectOutput { pub rejected: bool, - #[serde(default = "default_1838")] + #[serde(default = "default_1839")] pub rejected_at: Option, } @@ -40219,7 +40336,7 @@ pub struct MemoryRelatedHit { pub struct MemoryRelatedOutput { pub results: Vec, pub source_entities: Vec, - #[serde(default = "default_1839")] + #[serde(default = "default_1840")] pub reason: String, } @@ -40334,13 +40451,13 @@ impl MemoryRelatedInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryResolveOrphanDuplicatesOutput { - #[serde(default = "default_1840")] - pub candidates: Integer, #[serde(default = "default_1841")] - pub reactivated: Integer, + pub candidates: Integer, #[serde(default = "default_1842")] - pub dry_run: bool, + pub reactivated: Integer, #[serde(default = "default_1843")] + pub dry_run: bool, + #[serde(default = "default_1844")] pub memory_ids: Vec, } @@ -40417,15 +40534,15 @@ impl MemoryResolveOrphanDuplicatesInput { #[non_exhaustive] pub struct MemoryRestoreOutput { pub restored: bool, - #[serde(default = "default_1844")] - pub memory_id: Option, #[serde(default = "default_1845")] - pub version: Option, + pub memory_id: Option, #[serde(default = "default_1846")] - pub expired: bool, + pub version: Option, #[serde(default = "default_1847")] - pub redacted: bool, + pub expired: bool, #[serde(default = "default_1848")] + pub redacted: bool, + #[serde(default = "default_1849")] pub from_status: String, } @@ -40545,13 +40662,13 @@ pub struct SearchTraceHit { pub content_excerpt: String, pub distance: f64, pub similarity: f64, - #[serde(default = "default_1849")] + #[serde(default = "default_1850")] pub entity_boost: f64, pub rank_score: f64, pub rank: Integer, - #[serde(default = "default_1850")] - pub source: String, #[serde(default = "default_1851")] + pub source: String, + #[serde(default = "default_1852")] pub parent_memory_key: String, } @@ -40561,11 +40678,11 @@ pub struct MemorySearchTraceOutput { pub results: Vec, pub embedding_model: String, pub entity_filter: Vec, - #[serde(default = "default_1852")] - pub query_spellings: std::collections::HashMap, #[serde(default = "default_1853")] - pub query_spellings_skipped: bool, + pub query_spellings: std::collections::HashMap, #[serde(default = "default_1854")] + pub query_spellings_skipped: bool, + #[serde(default = "default_1855")] pub stale_dropped: Integer, } @@ -41746,7 +41863,7 @@ pub struct SearchTraceLogRow { pub embedding_model: String, pub latency_ms: Integer, pub run_id: String, - #[serde(default = "default_1855")] + #[serde(default = "default_1856")] pub operation: String, } @@ -41855,71 +41972,71 @@ pub struct RefusedFact { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemorySetFromMessagesOutput { - #[serde(default = "default_1856")] - pub written: Vec, #[serde(default = "default_1857")] - pub refused: Vec, + pub written: Vec, #[serde(default = "default_1858")] - pub tokens_in: Integer, + pub refused: Vec, #[serde(default = "default_1859")] - pub tokens_out: Integer, + pub tokens_in: Integer, #[serde(default = "default_1860")] - pub llm_provider: String, + pub tokens_out: Integer, #[serde(default = "default_1861")] - pub llm_model: String, + pub llm_provider: String, #[serde(default = "default_1862")] - pub segments: Integer, + pub llm_model: String, #[serde(default = "default_1863")] - pub foresight: Integer, + pub segments: Integer, #[serde(default = "default_1864")] - pub forgotten: Integer, + pub foresight: Integer, #[serde(default = "default_1865")] - pub forgotten_keys: Vec, + pub forgotten: Integer, #[serde(default = "default_1866")] - pub forget_requests: Integer, + pub forgotten_keys: Vec, #[serde(default = "default_1867")] - pub about_other: Integer, + pub forget_requests: Integer, #[serde(default = "default_1868")] - pub premise_facts: Integer, + pub about_other: Integer, #[serde(default = "default_1869")] - pub learning_candidates: Integer, + pub premise_facts: Integer, #[serde(default = "default_1870")] - pub ignored_args: Vec, + pub learning_candidates: Integer, #[serde(default = "default_1871")] - pub segmenter: String, + pub ignored_args: Vec, #[serde(default = "default_1872")] - pub cached_tokens_in: Integer, + pub segmenter: String, #[serde(default = "default_1873")] - pub ontology_warnings: Vec, + pub cached_tokens_in: Integer, #[serde(default = "default_1874")] - pub evidence_ids: Vec, + pub ontology_warnings: Vec, #[serde(default = "default_1875")] - pub belief_source_links: Integer, + pub evidence_ids: Vec, #[serde(default = "default_1876")] - pub pipeline_errors: Vec, + pub belief_source_links: Integer, #[serde(default = "default_1877")] - pub value_updates_linked: Integer, + pub pipeline_errors: Vec, #[serde(default = "default_1878")] - pub stubbed_fields: Vec, + pub value_updates_linked: Integer, #[serde(default = "default_1879")] - pub degraded: Vec, + pub stubbed_fields: Vec, #[serde(default = "default_1880")] - pub deferred: bool, + pub degraded: Vec, #[serde(default = "default_1881")] - pub queue_id: String, + pub deferred: bool, #[serde(default = "default_1882")] - pub deferred_by: String, + pub queue_id: String, #[serde(default = "default_1883")] - pub stage_ms: std::collections::HashMap, + pub deferred_by: String, #[serde(default = "default_1884")] - pub observation_date_source: String, + pub stage_ms: std::collections::HashMap, #[serde(default = "default_1885")] - pub under_operator_policy: bool, + pub observation_date_source: String, #[serde(default = "default_1886")] - pub extract_prompt_keys: Vec, + pub under_operator_policy: bool, #[serde(default = "default_1887")] - pub llm_cache_hits: Integer, + pub extract_prompt_keys: Vec, #[serde(default = "default_1888")] + pub llm_cache_hits: Integer, + #[serde(default = "default_1889")] pub llm_cache_misses: Integer, } @@ -42374,22 +42491,22 @@ pub enum StackEntrySection { #[non_exhaustive] pub struct StackEntry { pub section: StackEntrySection, - #[serde(default = "default_1889")] - pub memory_key: String, #[serde(default = "default_1890")] - pub memory_type: String, + pub memory_key: String, #[serde(default = "default_1891")] + pub memory_type: String, + #[serde(default = "default_1892")] pub value: String, pub tokens: Integer, - #[serde(default = "default_1892")] - pub pinned: bool, #[serde(default = "default_1893")] - pub recall_count: Integer, + pub pinned: bool, #[serde(default = "default_1894")] - pub last_recalled_at: Option, + pub recall_count: Integer, #[serde(default = "default_1895")] - pub actor: String, + pub last_recalled_at: Option, #[serde(default = "default_1896")] + pub actor: String, + #[serde(default = "default_1897")] pub namespace: String, } @@ -42574,14 +42691,14 @@ impl MemoryStackInput { pub struct MemoryStatus { pub memory_id: String, pub status: String, - #[serde(default = "default_1897")] + #[serde(default = "default_1898")] pub superseded_by: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemoryStatusesOutput { - #[serde(default = "default_1898")] + #[serde(default = "default_1899")] pub rows: Vec, } @@ -42630,23 +42747,23 @@ impl MemoryStatusesInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct MemorySweepExpiredOutput { - #[serde(default = "default_1899")] - pub scanned: Integer, #[serde(default = "default_1900")] - pub tombstoned: Integer, + pub scanned: Integer, #[serde(default = "default_1901")] - pub demoted: Integer, + pub tombstoned: Integer, #[serde(default = "default_1902")] - pub anonymized: Integer, + pub demoted: Integer, #[serde(default = "default_1903")] - pub locked_skipped: Integer, + pub anonymized: Integer, #[serde(default = "default_1904")] - pub moved_skipped: Integer, + pub locked_skipped: Integer, #[serde(default = "default_1905")] - pub dry_run: bool, + pub moved_skipped: Integer, #[serde(default = "default_1906")] - pub sample: Vec>, + pub dry_run: bool, #[serde(default = "default_1907")] + pub sample: Vec>, + #[serde(default = "default_1908")] pub failures: Vec, } @@ -42723,10 +42840,10 @@ pub struct MemoryTimelineEntry { pub memory_key: String, pub memory_type: String, pub content_excerpt: String, - #[serde(default = "default_1908")] + #[serde(default = "default_1909")] pub valid_at: Option, pub created_at: String, - #[serde(default = "default_1909")] + #[serde(default = "default_1910")] pub namespace: String, } @@ -42734,7 +42851,7 @@ pub struct MemoryTimelineEntry { #[non_exhaustive] pub struct MemoryTimelineOutput { pub events: Vec, - #[serde(default = "default_1910")] + #[serde(default = "default_1911")] pub total_matching: Integer, } @@ -42926,9 +43043,9 @@ impl MemoryTimelineInput { pub struct MemoryTouchResult { pub memory_key: String, pub touched: bool, - #[serde(default = "default_1913")] - pub version: Option, #[serde(default = "default_1914")] + pub version: Option, + #[serde(default = "default_1915")] pub expires_at: Option, } @@ -42936,13 +43053,13 @@ pub struct MemoryTouchResult { #[non_exhaustive] pub struct MemoryTouchOutput { pub touched: bool, - #[serde(default = "default_1911")] - pub version: Option, #[serde(default = "default_1912")] + pub version: Option, + #[serde(default = "default_1913")] pub expires_at: Option, - #[serde(default = "default_1915")] - pub results: Vec, #[serde(default = "default_1916")] + pub results: Vec, + #[serde(default = "default_1917")] pub touched_count: Integer, } @@ -43122,15 +43239,15 @@ impl MemoryTouchInput { #[non_exhaustive] pub struct MemoryUnlockOutput { pub unlocked: bool, - #[serde(default = "default_1917")] - pub reason: String, #[serde(default = "default_1918")] - pub memory_id: String, + pub reason: String, #[serde(default = "default_1919")] - pub version: Option, + pub memory_id: String, #[serde(default = "default_1920")] - pub previous_mode: String, + pub version: Option, #[serde(default = "default_1921")] + pub previous_mode: String, + #[serde(default = "default_1922")] pub unlocked_by: String, } @@ -43235,11 +43352,11 @@ impl MemoryUnlockInput { #[non_exhaustive] pub struct MemoryUnpinOutput { pub unpinned: bool, - #[serde(default = "default_1922")] - pub reason: String, #[serde(default = "default_1923")] - pub memory_id: String, + pub reason: String, #[serde(default = "default_1924")] + pub memory_id: String, + #[serde(default = "default_1925")] pub version: Option, } @@ -43333,15 +43450,15 @@ impl MemoryUnpinInput { #[non_exhaustive] pub struct MemoryUpdateCandidate { pub memory_id: String, - #[serde(default = "default_1930")] - pub agent: String, #[serde(default = "default_1931")] - pub user_id: String, + pub agent: String, #[serde(default = "default_1932")] - pub session_id: String, + pub user_id: String, #[serde(default = "default_1933")] - pub version: Integer, + pub session_id: String, #[serde(default = "default_1934")] + pub version: Integer, + #[serde(default = "default_1935")] pub status: String, } @@ -43349,23 +43466,23 @@ pub struct MemoryUpdateCandidate { #[non_exhaustive] pub struct MemoryUpdateOutput { pub updated: bool, - #[serde(default = "default_1925")] - pub memory_id: String, #[serde(default = "default_1926")] - pub memory_key: String, + pub memory_id: String, #[serde(default = "default_1927")] - pub new_version: Integer, + pub memory_key: String, #[serde(default = "default_1928")] - pub content_sha256: String, + pub new_version: Integer, #[serde(default = "default_1929")] + pub content_sha256: String, + #[serde(default = "default_1930")] pub reason: String, - #[serde(default = "default_1935")] - pub candidates: Vec, #[serde(default = "default_1936")] - pub conflict_verdict: String, + pub candidates: Vec, #[serde(default = "default_1937")] - pub conflict_peers: Integer, + pub conflict_verdict: String, #[serde(default = "default_1938")] + pub conflict_peers: Integer, + #[serde(default = "default_1939")] pub duplicate_of: String, } @@ -43574,15 +43691,15 @@ impl MemoryUpdateInput { #[non_exhaustive] pub struct MemoryUpdateByIdOutput { pub updated: bool, - #[serde(default = "default_1939")] - pub new_version: Integer, #[serde(default = "default_1940")] - pub content_sha256: String, + pub new_version: Integer, #[serde(default = "default_1941")] - pub conflict_verdict: String, + pub content_sha256: String, #[serde(default = "default_1942")] - pub conflict_peers: Integer, + pub conflict_verdict: String, #[serde(default = "default_1943")] + pub conflict_peers: Integer, + #[serde(default = "default_1944")] pub duplicate_of: String, } @@ -43710,23 +43827,23 @@ impl MemoryUpdateByIdInput { #[non_exhaustive] pub struct MemoryVerifyOutput { pub found: bool, - #[serde(default = "default_1944")] - pub changed: bool, #[serde(default = "default_1945")] - pub memory_id: String, + pub changed: bool, #[serde(default = "default_1946")] - pub memory_key: String, + pub memory_id: String, #[serde(default = "default_1947")] - pub namespace: String, + pub memory_key: String, #[serde(default = "default_1948")] - pub verified_by: String, + pub namespace: String, #[serde(default = "default_1949")] - pub verified_at: Option, + pub verified_by: String, #[serde(default = "default_1950")] - pub verification: String, + pub verified_at: Option, #[serde(default = "default_1951")] - pub version: Integer, + pub verification: String, #[serde(default = "default_1952")] + pub version: Integer, + #[serde(default = "default_1953")] pub content_sha256: String, } @@ -43931,13 +44048,13 @@ pub struct SchemaFieldOutput { #[serde(rename = "type")] pub r#type: String, pub required: bool, - #[serde(default = "default_1955")] - pub identity: bool, #[serde(default = "default_1956")] - pub enum_values: Vec, + pub identity: bool, #[serde(default = "default_1957")] - pub constraints: std::collections::HashMap, + pub enum_values: Vec, #[serde(default = "default_1958")] + pub constraints: std::collections::HashMap, + #[serde(default = "default_1959")] pub description: String, } @@ -43946,11 +44063,11 @@ pub struct SchemaFieldOutput { pub struct MemorySchemaSummary { pub schema_id: String, pub name: String, - #[serde(default = "default_1953")] - pub description: String, #[serde(default = "default_1954")] + pub description: String, + #[serde(default = "default_1955")] pub status: String, - #[serde(default = "default_1959")] + #[serde(default = "default_1960")] pub fields: Vec, } @@ -44365,13 +44482,13 @@ impl MemorySchemaRegisterInput { #[non_exhaustive] pub struct MentorPlane { pub plane: String, - #[serde(default = "default_1961")] - pub calls: Integer, #[serde(default = "default_1962")] - pub available: Option, + pub calls: Integer, #[serde(default = "default_1963")] - pub when: String, + pub available: Option, #[serde(default = "default_1964")] + pub when: String, + #[serde(default = "default_1965")] pub mentored: bool, } @@ -44381,11 +44498,11 @@ pub struct MentorHint { pub code: String, pub severity: String, pub text: String, - #[serde(default = "default_1966")] - pub ops: Vec, #[serde(default = "default_1967")] - pub evidence: std::collections::HashMap, + pub ops: Vec, #[serde(default = "default_1968")] + pub evidence: std::collections::HashMap, + #[serde(default = "default_1969")] pub plane: Option, } @@ -44393,9 +44510,9 @@ pub struct MentorHint { #[non_exhaustive] pub struct MentorAdoption { pub code: String, - #[serde(default = "default_1970")] - pub shown_sessions: Integer, #[serde(default = "default_1971")] + pub shown_sessions: Integer, + #[serde(default = "default_1972")] pub followed_sessions: Integer, } @@ -44431,7 +44548,7 @@ pub enum UsageRungSource { #[non_exhaustive] pub struct UsageRung { pub rung: UsageRungRung, - #[serde(default = "default_1973")] + #[serde(default = "default_1974")] pub count: Option, pub source: UsageRungSource, pub meaning: String, @@ -44446,27 +44563,27 @@ pub struct MentorBriefOutput { pub window_seconds: Integer, pub computed_at: String, pub sessions: Integer, - #[serde(default = "default_1960")] + #[serde(default = "default_1961")] pub usage: std::collections::HashMap, - #[serde(default = "default_1965")] + #[serde(default = "default_1966")] pub planes: Vec, - #[serde(default = "default_1969")] + #[serde(default = "default_1970")] pub hints: Vec, - #[serde(default = "default_1972")] + #[serde(default = "default_1973")] pub adoption: Vec, - #[serde(default = "default_1974")] - pub usage_evidence: Vec, #[serde(default = "default_1975")] - pub ledger_from: Option, + pub usage_evidence: Vec, #[serde(default = "default_1976")] - pub ledger_retention_days: Option, + pub ledger_from: Option, #[serde(default = "default_1977")] - pub agents: Vec, + pub ledger_retention_days: Option, #[serde(default = "default_1978")] - pub agent_defaulted: bool, + pub agents: Vec, #[serde(default = "default_1979")] - pub skipped: Vec, + pub agent_defaulted: bool, #[serde(default = "default_1980")] + pub skipped: Vec, + #[serde(default = "default_1981")] pub healthy: bool, } @@ -44615,33 +44732,33 @@ impl MentorGuideInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct NamespaceAuditSummary { - #[serde(default = "default_1981")] - pub live_rows: Integer, #[serde(default = "default_1982")] - pub live_bytes: Integer, + pub live_rows: Integer, #[serde(default = "default_1983")] - pub excerpt_bytes: Integer, + pub live_bytes: Integer, #[serde(default = "default_1984")] - pub version_rows: Integer, + pub excerpt_bytes: Integer, #[serde(default = "default_1985")] - pub version_bytes: Integer, + pub version_rows: Integer, #[serde(default = "default_1986")] - pub unembedded_rows: Integer, + pub version_bytes: Integer, #[serde(default = "default_1987")] - pub gets: Integer, + pub unembedded_rows: Integer, #[serde(default = "default_1988")] - pub searches: Integer, + pub gets: Integer, #[serde(default = "default_1989")] - pub sets: Integer, + pub searches: Integer, #[serde(default = "default_1990")] - pub get_search_ratio: f64, + pub sets: Integer, #[serde(default = "default_1991")] - pub inspector_calls: Integer, + pub get_search_ratio: f64, #[serde(default = "default_1992")] - pub typed_gets: Integer, + pub inspector_calls: Integer, #[serde(default = "default_1993")] - pub written_in_window: Integer, + pub typed_gets: Integer, #[serde(default = "default_1994")] + pub written_in_window: Integer, + #[serde(default = "default_1995")] pub ledger_calls: Integer, } @@ -44673,25 +44790,25 @@ pub struct NamespaceAuditFinding { pub kind: NamespaceAuditFindingKind, pub rule_version: Integer, pub source_op: String, - #[serde(default = "default_1995")] - pub window_seconds: Option, #[serde(default = "default_1996")] + pub window_seconds: Option, + #[serde(default = "default_1997")] pub population: Option, pub sample_limit: Integer, pub samples_complete: bool, - #[serde(default = "default_1997")] - pub evidence: Vec, #[serde(default = "default_1998")] - pub exceptions: String, + pub evidence: Vec, #[serde(default = "default_1999")] + pub exceptions: String, + #[serde(default = "default_2000")] pub uncertainty: String, pub code: String, pub severity: NamespaceAuditFindingSeverity, pub count: Integer, pub share: f64, - #[serde(default = "default_2000")] - pub bytes: Integer, #[serde(default = "default_2001")] + pub bytes: Integer, + #[serde(default = "default_2002")] pub samples: Vec>, pub detail: String, pub remedy: String, @@ -44706,7 +44823,7 @@ pub struct NamespaceAuditOutput { pub window_seconds: Integer, pub summary: NamespaceAuditSummary, pub findings: Vec, - #[serde(default = "default_2002")] + #[serde(default = "default_2003")] pub skipped: Vec, pub coverage: ReportCoverage, pub healthy: bool, @@ -44797,29 +44914,29 @@ pub enum BrowseEntryMyStatus { #[non_exhaustive] pub struct BrowseEntry { pub namespace: String, - #[serde(default = "default_2003")] + #[serde(default = "default_2004")] pub kind: String, pub description: String, pub owner_email: String, pub member_count: Integer, - #[serde(default = "default_2004")] + #[serde(default = "default_2005")] pub requires_approval: bool, pub created_at: String, - #[serde(default = "default_2005")] - pub join_policy: String, #[serde(default = "default_2006")] - pub visibility: String, + pub join_policy: String, #[serde(default = "default_2007")] - pub my_status: BrowseEntryMyStatus, + pub visibility: String, #[serde(default = "default_2008")] - pub my_role: String, + pub my_status: BrowseEntryMyStatus, #[serde(default = "default_2009")] - pub repo: String, + pub my_role: String, #[serde(default = "default_2010")] - pub branch: String, + pub repo: String, #[serde(default = "default_2011")] - pub guide_revision: Integer, + pub branch: String, #[serde(default = "default_2012")] + pub guide_revision: Integer, + #[serde(default = "default_2013")] pub guide_summary: String, } @@ -44923,9 +45040,9 @@ pub enum NamespaceCancelRequestOutputClearedRole { pub struct NamespaceCancelRequestOutput { pub cancelled: bool, pub namespace: String, - #[serde(default = "default_2013")] - pub cleared_role: Option, #[serde(default = "default_2014")] + pub cleared_role: Option, + #[serde(default = "default_2015")] pub cancelled_at: Option, } @@ -44997,7 +45114,7 @@ pub struct NamespaceDeleteOutput { pub deleted: bool, pub namespace: String, pub updated_at: String, - #[serde(default = "default_2015")] + #[serde(default = "default_2016")] pub sources_retired: Vec, } @@ -45066,67 +45183,67 @@ pub enum NamespaceGetOutputClassification { pub struct NamespaceGetOutput { pub found: bool, pub namespace: String, - #[serde(default = "default_2016")] - pub kind: Option, #[serde(default = "default_2017")] - pub owner_email: Option, + pub kind: Option, #[serde(default = "default_2018")] - pub description: Option, + pub owner_email: Option, #[serde(default = "default_2019")] - pub tags: Option>, + pub description: Option, #[serde(default = "default_2020")] - pub active: Option, + pub tags: Option>, #[serde(default = "default_2021")] - pub conversation_logging_enabled: Option, + pub active: Option, #[serde(default = "default_2022")] - pub capture_generation_io: Option, + pub conversation_logging_enabled: Option, #[serde(default = "default_2023")] - pub coverage_sweep: Option, + pub capture_generation_io: Option, #[serde(default = "default_2024")] - pub consolidation_enabled: Option, + pub coverage_sweep: Option, #[serde(default = "default_2025")] - pub daily_cost_cap_usd: Option, + pub consolidation_enabled: Option, #[serde(default = "default_2026")] - pub daily_user_cost_cap_usd: Option, + pub daily_cost_cap_usd: Option, #[serde(default = "default_2027")] - pub budget_alert_inbox: Option, + pub daily_user_cost_cap_usd: Option, #[serde(default = "default_2028")] - pub conflict_threshold: Option, + pub budget_alert_inbox: Option, #[serde(default = "default_2029")] - pub retention_days: Option, + pub conflict_threshold: Option, #[serde(default = "default_2030")] - pub warm_days: Option, + pub retention_days: Option, #[serde(default = "default_2031")] - pub visibility: Option, + pub warm_days: Option, #[serde(default = "default_2032")] - pub requires_approval: Option, + pub visibility: Option, #[serde(default = "default_2033")] - pub join_policy: Option, + pub requires_approval: Option, #[serde(default = "default_2034")] - pub effective_join_policy: Option, + pub join_policy: Option, #[serde(default = "default_2035")] - pub retrieval_defaults: Option>, + pub effective_join_policy: Option, #[serde(default = "default_2036")] - pub rerank_endpoint: Option, + pub retrieval_defaults: Option>, #[serde(default = "default_2037")] - pub classify_endpoint: Option, + pub rerank_endpoint: Option, #[serde(default = "default_2038")] - pub default_conflict_policy: Option, + pub classify_endpoint: Option, #[serde(default = "default_2039")] - pub proposal_policy: Option, + pub default_conflict_policy: Option, #[serde(default = "default_2040")] - pub code_change_policy: Option, + pub proposal_policy: Option, #[serde(default = "default_2041")] - pub tag_registry: Option>>, + pub code_change_policy: Option, #[serde(default = "default_2042")] - pub classification: Option, + pub tag_registry: Option>>, #[serde(default = "default_2043")] - pub guide_revision: Option, + pub classification: Option, #[serde(default = "default_2044")] - pub guide_summary: Option, + pub guide_revision: Option, #[serde(default = "default_2045")] - pub created_at: Option, + pub guide_summary: Option, #[serde(default = "default_2046")] + pub created_at: Option, + #[serde(default = "default_2047")] pub updated_at: Option, } @@ -45179,17 +45296,17 @@ impl NamespaceGetInput { #[non_exhaustive] pub struct NamespaceGuideGetOutput { pub found: bool, - #[serde(default = "default_2047")] - pub revision: Integer, #[serde(default = "default_2048")] - pub content: String, + pub revision: Integer, #[serde(default = "default_2049")] - pub summary: String, + pub content: String, #[serde(default = "default_2050")] - pub note: String, + pub summary: String, #[serde(default = "default_2051")] - pub updated_by: String, + pub note: String, #[serde(default = "default_2052")] + pub updated_by: String, + #[serde(default = "default_2053")] pub updated_at: Option, } @@ -45326,17 +45443,17 @@ impl NamespaceGuideHistoryInput { #[non_exhaustive] pub struct NamespaceGuideSetOutputNamespaceGuideGetOutput { pub found: bool, - #[serde(default = "default_2054")] - pub revision: Integer, #[serde(default = "default_2055")] - pub content: String, + pub revision: Integer, #[serde(default = "default_2056")] - pub summary: String, + pub content: String, #[serde(default = "default_2057")] - pub note: String, + pub summary: String, #[serde(default = "default_2058")] - pub updated_by: String, + pub note: String, #[serde(default = "default_2059")] + pub updated_by: String, + #[serde(default = "default_2060")] pub updated_at: Option, } @@ -45344,10 +45461,10 @@ pub struct NamespaceGuideSetOutputNamespaceGuideGetOutput { #[non_exhaustive] pub struct NamespaceGuideSetOutput { pub written: bool, - #[serde(default = "default_2053")] + #[serde(default = "default_2054")] pub conflict: bool, pub revision: Integer, - #[serde(default = "default_2060")] + #[serde(default = "default_2061")] pub current: Option, } @@ -45468,7 +45585,7 @@ pub struct InventorySection { #[serde(deserialize_with = "required_nullable")] pub latest_at: Option, pub complete: bool, - #[serde(default = "default_2061")] + #[serde(default = "default_2062")] pub reason: String, } @@ -45498,10 +45615,10 @@ pub struct InventoryPopulation { pub population: InventoryPopulationPopulation, #[serde(deserialize_with = "required_nullable")] pub total: Option, - #[serde(default = "default_2062")] + #[serde(default = "default_2063")] pub top: Vec, pub complete: bool, - #[serde(default = "default_2063")] + #[serde(default = "default_2064")] pub reason: String, } @@ -45667,11 +45784,11 @@ pub struct NamespaceJoinOutput { pub joined: bool, pub namespace: String, pub role: NamespaceJoinOutputRole, - #[serde(default = "default_2064")] - pub status: String, #[serde(default = "default_2065")] - pub requested_role: Option, + pub status: String, #[serde(default = "default_2066")] + pub requested_role: Option, + #[serde(default = "default_2067")] pub pending_admins: Vec, pub joined_at: String, } @@ -45763,7 +45880,7 @@ impl NamespaceJoinInput { pub struct NamespaceLeaveOutput { pub left: bool, pub namespace: String, - #[serde(default = "default_2067")] + #[serde(default = "default_2068")] pub left_at: Option, } @@ -45840,27 +45957,27 @@ pub enum NamespaceEntryVisibility { #[non_exhaustive] pub struct NamespaceEntry { pub namespace: String, - #[serde(default = "default_2068")] + #[serde(default = "default_2069")] pub kind: String, pub owner_email: String, pub description: String, pub tags: Vec, pub active: bool, - #[serde(default = "default_2069")] - pub consolidation_enabled: bool, #[serde(default = "default_2070")] - pub daily_cost_cap_usd: f64, + pub consolidation_enabled: bool, #[serde(default = "default_2071")] - pub daily_user_cost_cap_usd: f64, + pub daily_cost_cap_usd: f64, #[serde(default = "default_2072")] - pub budget_alert_inbox: String, + pub daily_user_cost_cap_usd: f64, #[serde(default = "default_2073")] - pub conflict_threshold: Option, + pub budget_alert_inbox: String, #[serde(default = "default_2074")] - pub retention_days: Integer, + pub conflict_threshold: Option, #[serde(default = "default_2075")] - pub warm_days: Integer, + pub retention_days: Integer, #[serde(default = "default_2076")] + pub warm_days: Integer, + #[serde(default = "default_2077")] pub visibility: NamespaceEntryVisibility, pub created_at: String, pub updated_at: String, @@ -46015,27 +46132,27 @@ pub enum MineEntryVisibility { pub struct MineEntry { pub namespace: String, pub role: String, - #[serde(default = "default_2077")] - pub status: String, #[serde(default = "default_2078")] - pub pending_role: Option, + pub status: String, #[serde(default = "default_2079")] - pub pending_since: Option, + pub pending_role: Option, #[serde(default = "default_2080")] - pub pending_admins: Vec, + pub pending_since: Option, #[serde(default = "default_2081")] - pub visibility: MineEntryVisibility, + pub pending_admins: Vec, #[serde(default = "default_2082")] - pub kind: String, + pub visibility: MineEntryVisibility, #[serde(default = "default_2083")] - pub title: String, + pub kind: String, #[serde(default = "default_2084")] - pub description: String, + pub title: String, #[serde(default = "default_2085")] - pub joined_at: Option, + pub description: String, #[serde(default = "default_2086")] - pub is_new: bool, + pub joined_at: Option, #[serde(default = "default_2087")] + pub is_new: bool, + #[serde(default = "default_2088")] pub inherited: bool, } @@ -46101,7 +46218,7 @@ pub struct OntologyEntry { pub name: String, pub status: String, pub description: String, - #[serde(default = "default_2088")] + #[serde(default = "default_2089")] pub cardinality: String, pub created_by: String, pub updated_at: String, @@ -46294,7 +46411,7 @@ pub struct NamespaceRegisterOutput { pub registered: bool, pub namespace: String, pub updated_at: String, - #[serde(default = "default_2089")] + #[serde(default = "default_2090")] pub visibility: NamespaceRegisterOutputVisibility, } @@ -47374,7 +47491,7 @@ impl NamespaceRegisterOntologyInput { #[non_exhaustive] pub struct NamespaceRestoreOutput { pub restored: bool, - #[serde(default = "default_2090")] + #[serde(default = "default_2091")] pub publication_pending: bool, pub target_namespace: String, pub snapshot_id: String, @@ -48261,15 +48378,15 @@ pub struct NamespaceRollbackOutput { pub version_at: Integer, pub reinstate: Integer, pub remove: Integer, - #[serde(default = "default_2091")] - pub skipped_no_head: Integer, #[serde(default = "default_2092")] - pub skipped_already_gone: Integer, + pub skipped_no_head: Integer, #[serde(default = "default_2093")] - pub truncated: bool, + pub skipped_already_gone: Integer, #[serde(default = "default_2094")] - pub sample: Vec>, + pub truncated: bool, #[serde(default = "default_2095")] + pub sample: Vec>, + #[serde(default = "default_2096")] pub applied_at: Option, } @@ -48448,101 +48565,101 @@ pub struct NamespaceSnapshotOutputSnapshotMemoryRow { pub confidence: f64, pub source_trace: String, pub pinned: bool, - #[serde(default = "default_2096")] - pub expires_at: Option, #[serde(default = "default_2097")] - pub entities: Vec, + pub expires_at: Option, #[serde(default = "default_2098")] - pub version: Integer, + pub entities: Vec, #[serde(default = "default_2099")] - pub content_sha256: String, + pub version: Integer, #[serde(default = "default_2100")] - pub actor: String, + pub content_sha256: String, #[serde(default = "default_2101")] - pub source_class: String, + pub actor: String, #[serde(default = "default_2102")] - pub source_resource_id: String, + pub source_class: String, #[serde(default = "default_2103")] - pub verified_by: String, + pub source_resource_id: String, #[serde(default = "default_2104")] - pub verified_at: Option, + pub verified_by: String, #[serde(default = "default_2105")] - pub verified_sha256: String, + pub verified_at: Option, #[serde(default = "default_2106")] - pub grounding: String, + pub verified_sha256: String, #[serde(default = "default_2107")] - pub evidence: String, + pub grounding: String, #[serde(default = "default_2108")] - pub tags: Vec, + pub evidence: String, #[serde(default = "default_2109")] - pub valid_at: Option, + pub tags: Vec, #[serde(default = "default_2110")] - pub valid_to: Option, + pub valid_at: Option, #[serde(default = "default_2111")] - pub created_at: Option, + pub valid_to: Option, #[serde(default = "default_2112")] - pub updated_at: Option, + pub created_at: Option, #[serde(default = "default_2113")] - pub value_json: String, + pub updated_at: Option, #[serde(default = "default_2114")] - pub status: NamespaceSnapshotOutputSnapshotMemoryRowStatus, + pub value_json: String, #[serde(default = "default_2115")] - pub requires_review: Option, + pub status: NamespaceSnapshotOutputSnapshotMemoryRowStatus, #[serde(default = "default_2116")] - pub conflict_with: Vec, + pub requires_review: Option, #[serde(default = "default_2117")] - pub duplicate_of: String, + pub conflict_with: Vec, #[serde(default = "default_2118")] - pub evidence_count: Integer, + pub duplicate_of: String, #[serde(default = "default_2119")] - pub recall_count: Integer, + pub evidence_count: Integer, #[serde(default = "default_2120")] - pub last_recalled_at: Option, + pub recall_count: Integer, #[serde(default = "default_2121")] - pub cross_promoted_from_memory_id: String, + pub last_recalled_at: Option, #[serde(default = "default_2122")] - pub cross_promoted_from_namespace: String, + pub cross_promoted_from_memory_id: String, #[serde(default = "default_2123")] - pub superseded_by: String, + pub cross_promoted_from_namespace: String, #[serde(default = "default_2124")] - pub rejection_reason: String, + pub superseded_by: String, #[serde(default = "default_2125")] - pub temporal_anchor: Option, + pub rejection_reason: String, #[serde(default = "default_2126")] - pub temporal_confidence: f64, + pub temporal_anchor: Option, #[serde(default = "default_2127")] - pub invalid_at: Option, + pub temporal_confidence: f64, #[serde(default = "default_2128")] - pub char_limit: Option, + pub invalid_at: Option, #[serde(default = "default_2129")] - pub reinforcement_count: Integer, + pub char_limit: Option, #[serde(default = "default_2130")] - pub last_reinforced_at: Option, + pub reinforcement_count: Integer, #[serde(default = "default_2131")] - pub mentioned_at: Option, + pub last_reinforced_at: Option, #[serde(default = "default_2132")] - pub sensitivity: String, + pub mentioned_at: Option, #[serde(default = "default_2133")] - pub redacted_at: Option, + pub sensitivity: String, #[serde(default = "default_2134")] - pub redaction_reason: String, + pub redacted_at: Option, #[serde(default = "default_2135")] - pub lock_mode: String, + pub redaction_reason: String, #[serde(default = "default_2136")] - pub lock_reason: String, + pub lock_mode: String, #[serde(default = "default_2137")] - pub lock_until: Option, + pub lock_reason: String, #[serde(default = "default_2138")] - pub locked_by: String, + pub lock_until: Option, #[serde(default = "default_2139")] - pub locked_at: Option, + pub locked_by: String, #[serde(default = "default_2140")] - pub on_expire: String, + pub locked_at: Option, #[serde(default = "default_2141")] - pub expire_reason: String, + pub on_expire: String, #[serde(default = "default_2142")] - pub files: Vec, + pub expire_reason: String, #[serde(default = "default_2143")] + pub files: Vec, + #[serde(default = "default_2144")] pub concepts: Vec, } @@ -48551,11 +48668,11 @@ pub struct NamespaceSnapshotOutputSnapshotMemoryRow { pub struct NamespaceSnapshotOutputSnapshotTypeRow { pub memory_type: String, pub retention_days: Integer, - #[serde(default = "default_2144")] - pub dedup_threshold: Option, #[serde(default = "default_2145")] - pub hot_quota: Integer, + pub dedup_threshold: Option, #[serde(default = "default_2146")] + pub hot_quota: Integer, + #[serde(default = "default_2147")] pub conflict_policy: String, } @@ -48770,7 +48887,7 @@ pub struct TaxonomyCommunity { pub community_id: Integer, pub label: String, pub size: Integer, - #[serde(default = "default_2147")] + #[serde(default = "default_2148")] pub top_entities: Vec, } @@ -48781,9 +48898,9 @@ pub struct NamespaceTaxonomyOutput { pub entities: Vec, pub memory_count: Integer, pub memory_types: Vec, - #[serde(default = "default_2148")] - pub communities: Vec, #[serde(default = "default_2149")] + pub communities: Vec, + #[serde(default = "default_2150")] pub communities_computed_at: String, } @@ -48883,15 +49000,15 @@ pub enum TuneProposalTarget { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TuneEvidence { - #[serde(default = "default_2151")] - pub finding_codes: Vec, #[serde(default = "default_2152")] - pub supporting_count: Integer, + pub finding_codes: Vec, #[serde(default = "default_2153")] - pub supporting: Vec, + pub supporting_count: Integer, #[serde(default = "default_2154")] - pub counter_count: Option, + pub supporting: Vec, #[serde(default = "default_2155")] + pub counter_count: Option, + #[serde(default = "default_2156")] pub documents: Vec, } @@ -48917,10 +49034,10 @@ pub enum TuneApplyVia { #[non_exhaustive] pub struct TuneApply { pub op: String, - #[serde(default = "default_2159")] + #[serde(default = "default_2160")] pub via: TuneApplyVia, pub args: std::collections::HashMap, - #[serde(default = "default_2160")] + #[serde(default = "default_2161")] pub args_complete: bool, pub required_role: String, pub guard: String, @@ -48939,7 +49056,7 @@ pub struct ChunkStats { pub sections: Integer, pub sections_cut: Integer, pub max_input_tokens: Integer, - #[serde(default = "default_2162")] + #[serde(default = "default_2163")] pub over_input_limit: Option, } @@ -48959,25 +49076,25 @@ pub struct TuneProposal { pub title: String, pub rationale: String, pub current: String, - #[serde(default = "default_2150")] + #[serde(default = "default_2151")] pub current_revision: Option, pub proposed: String, pub evidence: TuneEvidence, - #[serde(default = "default_2156")] - pub affected_agents: Vec, #[serde(default = "default_2157")] - pub affected_agents_total: Option, + pub affected_agents: Vec, #[serde(default = "default_2158")] + pub affected_agents_total: Option, + #[serde(default = "default_2159")] pub effect: TuneProposalEffect, pub historical: String, pub apply: TuneApply, - #[serde(default = "default_2161")] + #[serde(default = "default_2162")] pub apply_also: Vec, - #[serde(default = "default_2163")] - pub preview: Option, #[serde(default = "default_2164")] - pub limits: String, + pub preview: Option, #[serde(default = "default_2165")] + pub limits: String, + #[serde(default = "default_2166")] pub refs: Vec, } @@ -48985,13 +49102,13 @@ pub struct TuneProposal { #[non_exhaustive] pub struct ChunkingSample { pub cap: Integer, - #[serde(default = "default_2171")] + #[serde(default = "default_2172")] pub population: Option, pub documents: Integer, pub unread: Integer, pub load_cap: Integer, pub embedder_model: String, - #[serde(default = "default_2172")] + #[serde(default = "default_2173")] pub input_token_limit: Option, pub current: ChunkStats, } @@ -49002,21 +49119,21 @@ pub struct NamespaceTuneOutput { pub org: String, pub namespace: String, pub computed_at: String, - #[serde(default = "default_2166")] - pub proposals: Vec, #[serde(default = "default_2167")] - pub guide_revision: Option, + pub proposals: Vec, #[serde(default = "default_2168")] - pub categories_registered: Option, + pub guide_revision: Option, #[serde(default = "default_2169")] - pub extraction_policy: Option, + pub categories_registered: Option, #[serde(default = "default_2170")] + pub extraction_policy: Option, + #[serde(default = "default_2171")] pub extraction_policy_unavailable: String, - #[serde(default = "default_2173")] - pub chunking: Option, #[serde(default = "default_2174")] - pub skipped: Vec, + pub chunking: Option, #[serde(default = "default_2175")] + pub skipped: Vec, + #[serde(default = "default_2176")] pub model_used: bool, } @@ -49137,25 +49254,25 @@ pub struct NamespaceValidateFinding { pub kind: NamespaceValidateFindingKind, pub rule_version: Integer, pub source_op: String, - #[serde(default = "default_2176")] - pub window_seconds: Option, #[serde(default = "default_2177")] + pub window_seconds: Option, + #[serde(default = "default_2178")] pub population: Option, pub sample_limit: Integer, pub samples_complete: bool, - #[serde(default = "default_2178")] - pub evidence: Vec, #[serde(default = "default_2179")] - pub exceptions: String, + pub evidence: Vec, #[serde(default = "default_2180")] + pub exceptions: String, + #[serde(default = "default_2181")] pub uncertainty: String, pub check: String, pub severity: NamespaceValidateFindingSeverity, pub count: Integer, - #[serde(default = "default_2181")] + #[serde(default = "default_2182")] pub samples: Vec>, pub detail: String, - #[serde(default = "default_2182")] + #[serde(default = "default_2183")] pub totals: std::collections::HashMap, } @@ -49169,9 +49286,9 @@ pub struct NamespaceValidateOutput { pub warnings: Integer, pub infos: Integer, pub findings: Vec, - #[serde(default = "default_2183")] - pub skipped: Vec, #[serde(default = "default_2184")] + pub skipped: Vec, + #[serde(default = "default_2185")] pub keys_scoped: Integer, pub coverage: ReportCoverage, pub checked_at: String, @@ -49291,9 +49408,9 @@ impl NamespaceValidateInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ObserveCrystallizeOutput { - #[serde(default = "default_2185")] - pub enqueued: Integer, #[serde(default = "default_2186")] + pub enqueued: Integer, + #[serde(default = "default_2187")] pub session_id: String, } @@ -49390,23 +49507,23 @@ impl ObserveCrystallizeInput { #[non_exhaustive] pub struct ObserveRecordOutput { pub memory_key: String, - #[serde(default = "default_2187")] - pub memory_id: String, #[serde(default = "default_2188")] - pub kind: String, + pub memory_id: String, #[serde(default = "default_2189")] - pub tags: Vec, + pub kind: String, #[serde(default = "default_2190")] - pub file_paths: Vec, + pub tags: Vec, #[serde(default = "default_2191")] - pub content_sha256: String, + pub file_paths: Vec, #[serde(default = "default_2192")] - pub tool_name: String, + pub content_sha256: String, #[serde(default = "default_2193")] - pub has_error: bool, + pub tool_name: String, #[serde(default = "default_2194")] - pub narrative_chars: Integer, + pub has_error: bool, #[serde(default = "default_2195")] + pub narrative_chars: Integer, + #[serde(default = "default_2196")] pub skipped_reason: String, } @@ -49605,26 +49722,26 @@ pub struct ProjectionFailureRow { pub failure_id: String, pub org: String, pub namespace: String, - #[serde(default = "default_2196")] + #[serde(default = "default_2197")] pub agent: String, pub projection: String, - #[serde(default = "default_2197")] - pub source_operation: String, #[serde(default = "default_2198")] - pub source_resource_id: String, + pub source_operation: String, #[serde(default = "default_2199")] - pub memory_keys: Vec, + pub source_resource_id: String, #[serde(default = "default_2200")] - pub error_type: String, + pub memory_keys: Vec, #[serde(default = "default_2201")] - pub error_message: String, + pub error_type: String, #[serde(default = "default_2202")] - pub payload: std::collections::HashMap, + pub error_message: String, #[serde(default = "default_2203")] - pub status: String, + pub payload: std::collections::HashMap, #[serde(default = "default_2204")] - pub created_at: Option, + pub status: String, #[serde(default = "default_2205")] + pub created_at: Option, + #[serde(default = "default_2206")] pub resolved_at: Option, } @@ -49778,22 +49895,22 @@ pub struct ProjectionFailureRetryRow { pub projection: String, pub retried: bool, pub resolved: bool, - #[serde(default = "default_2206")] - pub abandoned: bool, #[serde(default = "default_2207")] - pub reason: String, + pub abandoned: bool, #[serde(default = "default_2208")] + pub reason: String, + #[serde(default = "default_2209")] pub error: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProjectionFailureRetryOutput { - #[serde(default = "default_2209")] + #[serde(default = "default_2210")] pub results: Vec, pub retried: Integer, pub resolved: Integer, - #[serde(default = "default_2210")] + #[serde(default = "default_2211")] pub abandoned: Integer, } @@ -49875,15 +49992,15 @@ impl ProjectionFailureRetryInput { pub struct OrgModelCallsOutput { pub org: String, pub enabled: bool, - #[serde(default = "default_2211")] - pub reason: String, #[serde(default = "default_2212")] - pub updated_by: String, + pub reason: String, #[serde(default = "default_2213")] - pub updated_at: Option, + pub updated_by: String, #[serde(default = "default_2214")] - pub locked: bool, + pub updated_at: Option, #[serde(default = "default_2215")] + pub locked: bool, + #[serde(default = "default_2216")] pub locked_by: String, } @@ -50222,7 +50339,7 @@ impl PolicyDecisionsInput { #[non_exhaustive] pub struct PolicyDeleteOutput { pub removed: bool, - #[serde(default = "default_2216")] + #[serde(default = "default_2217")] pub widening: bool, } @@ -50288,12 +50405,12 @@ pub struct PolicyRuleOut { pub condition: std::collections::HashMap, pub description: String, pub enabled: bool, - #[serde(default = "default_2217")] + #[serde(default = "default_2218")] pub mode: String, pub created_by: String, - #[serde(default = "default_2218")] - pub created_at: Option, #[serde(default = "default_2219")] + pub created_at: Option, + #[serde(default = "default_2220")] pub updated_at: Option, } @@ -50365,9 +50482,9 @@ impl PolicyListInput { pub struct PolicySetOutput { pub rule: PolicyRuleOut, pub leaf_count: Integer, - #[serde(default = "default_2220")] - pub widening: bool, #[serde(default = "default_2221")] + pub widening: bool, + #[serde(default = "default_2222")] pub change: Vec, } @@ -50637,37 +50754,37 @@ pub struct ProcedureEvolveOutput { pub revision: Integer, pub changed: bool, pub template: bool, - #[serde(default = "default_2222")] - pub folded_runs: Integer, #[serde(default = "default_2223")] - pub gate: ProcedureEvolveOutputGate, + pub folded_runs: Integer, #[serde(default = "default_2224")] - pub gate_mode: String, + pub gate: ProcedureEvolveOutputGate, #[serde(default = "default_2225")] - pub gate_llr: f64, + pub gate_mode: String, #[serde(default = "default_2226")] - pub gate_before: std::collections::HashMap, + pub gate_llr: f64, #[serde(default = "default_2227")] - pub gate_after: std::collections::HashMap, + pub gate_before: std::collections::HashMap, #[serde(default = "default_2228")] - pub gate_cost_before: std::collections::HashMap, + pub gate_after: std::collections::HashMap, #[serde(default = "default_2229")] - pub gate_cost_after: std::collections::HashMap, + pub gate_cost_before: std::collections::HashMap, #[serde(default = "default_2230")] - pub gate_reason: String, + pub gate_cost_after: std::collections::HashMap, #[serde(default = "default_2231")] - pub dead_end_steps: Vec, + pub gate_reason: String, #[serde(default = "default_2232")] - pub fail_prone_steps: Vec, + pub dead_end_steps: Vec, #[serde(default = "default_2233")] - pub fail_prone_transitions: Vec, + pub fail_prone_steps: Vec, #[serde(default = "default_2234")] - pub run_stats: std::collections::HashMap, + pub fail_prone_transitions: Vec, #[serde(default = "default_2235")] - pub strikes: Integer, + pub run_stats: std::collections::HashMap, #[serde(default = "default_2236")] - pub quarantined: bool, + pub strikes: Integer, #[serde(default = "default_2237")] + pub quarantined: bool, + #[serde(default = "default_2238")] pub retention: std::collections::HashMap, } @@ -50890,9 +51007,9 @@ pub struct ProcedureForkOutput { pub memory_key: String, pub version: Integer, pub name: String, - #[serde(default = "default_2238")] - pub steps: Vec, #[serde(default = "default_2239")] + pub steps: Vec, + #[serde(default = "default_2240")] pub forked_from: std::collections::HashMap, } @@ -51152,32 +51269,32 @@ pub enum ProcedureLocateOutputStatus { #[non_exhaustive] pub struct ProcedureLocateOutput { pub memory_key: String, - #[serde(default = "default_2240")] - pub name: String, #[serde(default = "default_2241")] + pub name: String, + #[serde(default = "default_2242")] pub status: ProcedureLocateOutputStatus, pub matched: bool, - #[serde(default = "default_2242")] - pub active: Option>, #[serde(default = "default_2243")] - pub hops: Vec>>, + pub active: Option>, #[serde(default = "default_2244")] - pub entry_nodes: Vec, + pub hops: Vec>>, #[serde(default = "default_2245")] - pub dominant_next: Vec, + pub entry_nodes: Vec, #[serde(default = "default_2246")] - pub revisits: std::collections::HashMap, + pub dominant_next: Vec, #[serde(default = "default_2247")] - pub looping: bool, + pub revisits: std::collections::HashMap, #[serde(default = "default_2248")] - pub exits: Vec, + pub looping: bool, #[serde(default = "default_2249")] - pub failure_notes: Vec>, + pub exits: Vec, #[serde(default = "default_2250")] - pub rendered: String, + pub failure_notes: Vec>, #[serde(default = "default_2251")] - pub run_stats: std::collections::HashMap, + pub rendered: String, #[serde(default = "default_2252")] + pub run_stats: std::collections::HashMap, + #[serde(default = "default_2253")] pub for_agent: std::collections::HashMap, } @@ -51332,43 +51449,43 @@ pub struct ProcedureMatch { pub name: String, pub situation: String, pub steps: Vec, - #[serde(default = "default_2253")] - pub tags: Vec, #[serde(default = "default_2254")] + pub tags: Vec, + #[serde(default = "default_2255")] pub metadata: std::collections::HashMap, pub similarity: f64, pub memory_key: String, pub namespace: String, - #[serde(default = "default_2255")] - pub graph: Option>, #[serde(default = "default_2256")] - pub template: bool, + pub graph: Option>, #[serde(default = "default_2257")] - pub run_stats: std::collections::HashMap, + pub template: bool, #[serde(default = "default_2258")] - pub status: ProcedureMatchStatus, + pub run_stats: std::collections::HashMap, #[serde(default = "default_2259")] - pub quarantined: Option>, + pub status: ProcedureMatchStatus, #[serde(default = "default_2260")] - pub fail_prone_steps: Vec, + pub quarantined: Option>, #[serde(default = "default_2261")] - pub revision: Integer, + pub fail_prone_steps: Vec, #[serde(default = "default_2262")] - pub rejected_revisions: Vec>, + pub revision: Integer, #[serde(default = "default_2263")] - pub tool_overlap: f64, + pub rejected_revisions: Vec>, #[serde(default = "default_2264")] - pub score: f64, + pub tool_overlap: f64, #[serde(default = "default_2265")] - pub utility: f64, + pub score: f64, #[serde(default = "default_2266")] - pub goal_similarity: Option, + pub utility: f64, #[serde(default = "default_2267")] - pub for_agent: std::collections::HashMap, + pub goal_similarity: Option, #[serde(default = "default_2268")] + pub for_agent: std::collections::HashMap, + #[serde(default = "default_2269")] pub run_stats_by_agent: std::collections::HashMap>, - #[serde(default = "default_2269")] + #[serde(default = "default_2270")] pub actor: String, } @@ -51376,11 +51493,11 @@ pub struct ProcedureMatch { #[non_exhaustive] pub struct ProcedureMatchOutput { pub matches: Vec, - #[serde(default = "default_2270")] - pub matched: Integer, #[serde(default = "default_2271")] - pub procedure_key: String, + pub matched: Integer, #[serde(default = "default_2272")] + pub procedure_key: String, + #[serde(default = "default_2273")] pub score: f64, } @@ -51772,9 +51889,9 @@ pub struct ProcedureReviseOutput { pub revision: Integer, pub prior_revision: Integer, pub digest: String, - #[serde(default = "default_2273")] - pub steps: Vec, #[serde(default = "default_2274")] + pub steps: Vec, + #[serde(default = "default_2275")] pub outcome: ProcedureReviseOutputOutcome, } @@ -51886,14 +52003,14 @@ pub struct ProfileActivityEntry { pub agent: String, pub last_activated_at: String, pub event_count: Integer, - #[serde(default = "default_2275")] + #[serde(default = "default_2276")] pub operations: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct ProfileActivityOutput { - #[serde(default = "default_2276")] + #[serde(default = "default_2277")] pub entries: Vec, } @@ -52001,17 +52118,17 @@ impl ProfileActivityInput { #[non_exhaustive] pub struct ProfileMutationOutput { pub version: Integer, - #[serde(default = "default_2277")] - pub memory_id: String, #[serde(default = "default_2278")] - pub content_sha256: String, + pub memory_id: String, #[serde(default = "default_2279")] - pub namespace: String, + pub content_sha256: String, #[serde(default = "default_2280")] - pub label: String, + pub namespace: String, #[serde(default = "default_2281")] - pub char_limit: Option, + pub label: String, #[serde(default = "default_2282")] + pub char_limit: Option, + #[serde(default = "default_2283")] pub value_length: Integer, } @@ -52120,7 +52237,7 @@ pub struct ProfileRenderOutput { pub rendered: String, pub section_count: Integer, pub total_chars: Integer, - #[serde(default = "default_2283")] + #[serde(default = "default_2284")] pub labels: Vec, } @@ -52505,17 +52622,17 @@ pub enum ProfileStructuredOutputStatus { #[non_exhaustive] pub struct ProfileStructuredOutput { pub status: ProfileStructuredOutputStatus, - #[serde(default = "default_2284")] - pub profile: std::collections::HashMap, #[serde(default = "default_2285")] - pub built_at: Option, + pub profile: std::collections::HashMap, #[serde(default = "default_2286")] - pub memory_id: String, + pub built_at: Option, #[serde(default = "default_2287")] - pub version: Integer, + pub memory_id: String, #[serde(default = "default_2288")] - pub version_text: String, + pub version: Integer, #[serde(default = "default_2289")] + pub version_text: String, + #[serde(default = "default_2290")] pub schema_sha256: String, } @@ -52632,13 +52749,13 @@ impl ProfileStructuredInput { #[non_exhaustive] pub struct ProfileSchemaOutput { pub found: bool, - #[serde(default = "default_2290")] - pub json_schema: std::collections::HashMap, #[serde(default = "default_2291")] - pub schema_sha256: String, + pub json_schema: std::collections::HashMap, #[serde(default = "default_2292")] - pub updated_by: String, + pub schema_sha256: String, #[serde(default = "default_2293")] + pub updated_by: String, + #[serde(default = "default_2294")] pub updated_at: Option, } @@ -52791,10 +52908,10 @@ pub enum RunBeginOutputStatus { #[non_exhaustive] pub struct RunBeginOutput { pub run_id: String, - #[serde(default = "default_2294")] + #[serde(default = "default_2295")] pub status: RunBeginOutputStatus, pub started_at: String, - #[serde(default = "default_2295")] + #[serde(default = "default_2296")] pub next: String, } @@ -53002,29 +53119,29 @@ pub struct RunCompleteOutput { pub run_id: String, pub status: RunCompleteOutputStatus, pub duration_ms: Integer, - #[serde(default = "default_2296")] - pub used_applied: Integer, #[serde(default = "default_2297")] - pub evidence_applied: Integer, + pub used_applied: Integer, #[serde(default = "default_2298")] - pub harm_applied: Integer, + pub evidence_applied: Integer, #[serde(default = "default_2299")] - pub memories_written: Vec, + pub harm_applied: Integer, #[serde(default = "default_2300")] - pub recalled: Integer, + pub memories_written: Vec, #[serde(default = "default_2301")] - pub observations: Integer, + pub recalled: Integer, #[serde(default = "default_2302")] - pub procedure_runs_recorded: Integer, + pub observations: Integer, #[serde(default = "default_2303")] - pub reflection_key: String, + pub procedure_runs_recorded: Integer, #[serde(default = "default_2304")] - pub retain: String, + pub reflection_key: String, #[serde(default = "default_2305")] - pub retained: Integer, + pub retain: String, #[serde(default = "default_2306")] - pub demoted: Integer, + pub retained: Integer, #[serde(default = "default_2307")] + pub demoted: Integer, + #[serde(default = "default_2308")] pub expiring: Integer, } @@ -53545,25 +53662,25 @@ pub enum RunGetOutputOverBudgetItem { #[non_exhaustive] pub struct RunGetOutput { pub found: bool, - #[serde(default = "default_2308")] - pub run: Option, #[serde(default = "default_2309")] - pub recalled: Integer, + pub run: Option, #[serde(default = "default_2310")] - pub recalled_keys: Vec, + pub recalled: Integer, #[serde(default = "default_2311")] - pub memories_written: Vec, + pub recalled_keys: Vec, #[serde(default = "default_2312")] - pub observations: Integer, + pub memories_written: Vec, #[serde(default = "default_2313")] - pub turns: Integer, + pub observations: Integer, #[serde(default = "default_2314")] - pub unpriced_turns: Integer, + pub turns: Integer, #[serde(default = "default_2315")] - pub cost_usd: f64, + pub unpriced_turns: Integer, #[serde(default = "default_2316")] - pub elapsed_seconds: Integer, + pub cost_usd: f64, #[serde(default = "default_2317")] + pub elapsed_seconds: Integer, + #[serde(default = "default_2318")] pub over_budget: Vec, } @@ -53630,17 +53747,17 @@ pub struct RunGradeProposal { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct RunGradeOutput { - #[serde(default = "default_2318")] - pub graded: Integer, #[serde(default = "default_2319")] - pub run_ids: Vec, + pub graded: Integer, #[serde(default = "default_2320")] - pub skipped_active: Integer, + pub run_ids: Vec, #[serde(default = "default_2321")] - pub unchanged: Integer, + pub skipped_active: Integer, #[serde(default = "default_2322")] - pub memories_counted: Integer, + pub unchanged: Integer, #[serde(default = "default_2323")] + pub memories_counted: Integer, + #[serde(default = "default_2324")] pub proposals_decided: Vec, } @@ -53755,7 +53872,7 @@ impl RunGradeInput { #[non_exhaustive] pub struct RunListOutput { pub runs: Vec, - #[serde(default = "default_2324")] + #[serde(default = "default_2325")] pub total: Option, } @@ -54032,39 +54149,39 @@ pub struct LiveSearchHit { pub title: String, pub url: String, pub provider: LiveSearchHitProvider, - #[serde(default = "default_2327")] - pub content: String, #[serde(default = "default_2328")] + pub content: String, + #[serde(default = "default_2329")] pub live: LiveSearchHitLive, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct LiveSearchResults { - #[serde(default = "default_2326")] + #[serde(default = "default_2327")] pub live: LiveSearchResultsLive, - #[serde(default = "default_2329")] + #[serde(default = "default_2330")] pub results: Vec, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SearchOutput { - #[serde(default = "default_2325")] + #[serde(default = "default_2326")] pub tracker: Option>, - #[serde(default = "default_2330")] - pub live: Option, #[serde(default = "default_2331")] - pub memory: std::collections::HashMap, + pub live: Option, #[serde(default = "default_2332")] - pub knowledge: std::collections::HashMap, + pub memory: std::collections::HashMap, #[serde(default = "default_2333")] - pub profile: std::collections::HashMap, + pub knowledge: std::collections::HashMap, #[serde(default = "default_2334")] - pub conversations: std::collections::HashMap, + pub profile: std::collections::HashMap, #[serde(default = "default_2335")] - pub withheld: Option>, + pub conversations: std::collections::HashMap, #[serde(default = "default_2336")] + pub withheld: Option>, + #[serde(default = "default_2337")] pub namespaces_skipped: Vec, } @@ -54257,7 +54374,7 @@ impl SearchInput { pub struct SessionBriefDeleteOutput { pub deleted: bool, pub brief_key: String, - #[serde(default = "default_2337")] + #[serde(default = "default_2338")] pub revision: Integer, } @@ -54350,67 +54467,67 @@ impl SessionBriefDeleteInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDecision { - #[serde(default = "default_2346")] - pub what: String, #[serde(default = "default_2347")] + pub what: String, + #[serde(default = "default_2348")] pub why: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDeadEnd { - #[serde(default = "default_2349")] - pub tried: String, #[serde(default = "default_2350")] + pub tried: String, + #[serde(default = "default_2351")] pub why_not: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefDone { - #[serde(default = "default_2352")] + #[serde(default = "default_2353")] pub what: String, - #[serde(rename = "ref", default = "default_2353")] + #[serde(rename = "ref", default = "default_2354")] pub r#ref: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefFile { - #[serde(default = "default_2357")] - pub path: String, #[serde(default = "default_2358")] + pub path: String, + #[serde(default = "default_2359")] pub role: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct BriefSections { - #[serde(default = "default_2343")] - pub goal: String, #[serde(default = "default_2344")] - pub status: String, + pub goal: String, #[serde(default = "default_2345")] + pub status: String, + #[serde(default = "default_2346")] pub verification: String, - #[serde(default = "default_2348")] + #[serde(default = "default_2349")] pub decisions: Vec, - #[serde(default = "default_2351")] + #[serde(default = "default_2352")] pub dead_ends: Vec, - #[serde(default = "default_2354")] - pub done: Vec, #[serde(default = "default_2355")] - pub open_questions: Vec, + pub done: Vec, #[serde(default = "default_2356")] + pub open_questions: Vec, + #[serde(default = "default_2357")] pub next_steps: Vec, - #[serde(default = "default_2359")] - pub files: Vec, #[serde(default = "default_2360")] - pub constraints: Vec, + pub files: Vec, #[serde(default = "default_2361")] - pub pointers: Vec, + pub constraints: Vec, #[serde(default = "default_2362")] - pub client_summary: String, + pub pointers: Vec, #[serde(default = "default_2363")] + pub client_summary: String, + #[serde(default = "default_2364")] pub client_summary_at: String, } @@ -54418,45 +54535,45 @@ pub struct BriefSections { #[non_exhaustive] pub struct SessionBriefGetOutput { pub found: bool, - #[serde(default = "default_2338")] - pub brief_key: String, #[serde(default = "default_2339")] - pub revision: Integer, + pub brief_key: String, #[serde(default = "default_2340")] - pub snapshot_id: String, + pub revision: Integer, #[serde(default = "default_2341")] - pub snapshot_key: String, + pub snapshot_id: String, #[serde(default = "default_2342")] + pub snapshot_key: String, + #[serde(default = "default_2343")] pub rendered: String, - #[serde(default = "default_2364")] - pub sections: Option, #[serde(default = "default_2365")] - pub project: String, + pub sections: Option, #[serde(default = "default_2366")] - pub branch: String, + pub project: String, #[serde(default = "default_2367")] - pub head_sha: String, + pub branch: String, #[serde(default = "default_2368")] - pub author: String, + pub head_sha: String, #[serde(default = "default_2369")] - pub trigger: String, + pub author: String, #[serde(default = "default_2370")] - pub actor: String, + pub trigger: String, #[serde(default = "default_2371")] - pub source_sessions: Vec, + pub actor: String, #[serde(default = "default_2372")] - pub updated_at: Option, + pub source_sessions: Vec, #[serde(default = "default_2373")] - pub age_seconds: Integer, + pub updated_at: Option, #[serde(default = "default_2374")] - pub revisions: Integer, + pub age_seconds: Integer, #[serde(default = "default_2375")] - pub events_total: Integer, + pub revisions: Integer, #[serde(default = "default_2376")] - pub source_chars: Integer, + pub events_total: Integer, #[serde(default = "default_2377")] - pub brief_chars: Integer, + pub source_chars: Integer, #[serde(default = "default_2378")] + pub brief_chars: Integer, + #[serde(default = "default_2379")] pub deleted: bool, } @@ -54631,34 +54748,34 @@ impl SessionBriefGetInput { pub struct SessionBriefSummary { pub brief_key: String, pub revision: Integer, - #[serde(default = "default_2379")] - pub project: String, #[serde(default = "default_2380")] - pub branch: String, + pub project: String, #[serde(default = "default_2381")] - pub agent: String, + pub branch: String, #[serde(default = "default_2382")] - pub goal: String, + pub agent: String, #[serde(default = "default_2383")] - pub status: String, + pub goal: String, #[serde(default = "default_2384")] - pub author: String, + pub status: String, #[serde(default = "default_2385")] - pub actor: String, + pub author: String, #[serde(default = "default_2386")] - pub updated_at: Option, + pub actor: String, #[serde(default = "default_2387")] - pub age_seconds: Integer, + pub updated_at: Option, #[serde(default = "default_2388")] + pub age_seconds: Integer, + #[serde(default = "default_2389")] pub brief_chars: Integer, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefListOutput { - #[serde(default = "default_2389")] - pub briefs: Vec, #[serde(default = "default_2390")] + pub briefs: Vec, + #[serde(default = "default_2391")] pub rendered: String, } @@ -54798,25 +54915,25 @@ impl SessionBriefListInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct SessionBriefStats { - #[serde(default = "default_2394")] - pub events_in: Integer, #[serde(default = "default_2395")] - pub windows: Integer, + pub events_in: Integer, #[serde(default = "default_2396")] - pub events_total: Integer, + pub windows: Integer, #[serde(default = "default_2397")] - pub source_chars: Integer, + pub events_total: Integer, #[serde(default = "default_2398")] - pub brief_chars: Integer, + pub source_chars: Integer, #[serde(default = "default_2399")] - pub compression_ratio: f64, + pub brief_chars: Integer, #[serde(default = "default_2400")] - pub dropped_ungrounded: Integer, + pub compression_ratio: f64, #[serde(default = "default_2401")] - pub tokens_in: Integer, + pub dropped_ungrounded: Integer, #[serde(default = "default_2402")] - pub tokens_out: Integer, + pub tokens_in: Integer, #[serde(default = "default_2403")] + pub tokens_out: Integer, + #[serde(default = "default_2404")] pub llm_model: String, } @@ -54826,13 +54943,13 @@ pub struct SessionBriefSaveOutput { pub brief_key: String, pub revision: Integer, pub changed: bool, - #[serde(default = "default_2391")] - pub author: String, #[serde(default = "default_2392")] - pub reason: String, + pub author: String, #[serde(default = "default_2393")] + pub reason: String, + #[serde(default = "default_2394")] pub rendered: String, - #[serde(default = "default_2404")] + #[serde(default = "default_2405")] pub stats: SessionBriefStats, } @@ -55577,39 +55694,39 @@ pub struct TaskPayload { pub priority: Integer, pub disclosure: TaskPayloadDisclosure, pub status: TaskPayloadStatus, - #[serde(default = "default_2405")] - pub reason: String, #[serde(default = "default_2406")] - pub blocked_on: String, + pub reason: String, #[serde(default = "default_2407")] - pub not_before: Option, + pub blocked_on: String, #[serde(default = "default_2408")] - pub resume_at: Option, + pub not_before: Option, #[serde(default = "default_2409")] - pub deadline: Option, + pub resume_at: Option, #[serde(default = "default_2410")] + pub deadline: Option, + #[serde(default = "default_2411")] pub defer_count: Integer, pub title: String, - #[serde(default = "default_2411")] + #[serde(default = "default_2412")] pub brief: std::collections::HashMap, pub from_agent: String, - #[serde(default = "default_2412")] - pub from_subject: String, #[serde(default = "default_2413")] - pub origin: String, + pub from_subject: String, #[serde(default = "default_2414")] - pub parent_task_id: Option, + pub origin: String, #[serde(default = "default_2415")] - pub owner: String, + pub parent_task_id: Option, #[serde(default = "default_2416")] - pub attempt: Integer, + pub owner: String, #[serde(default = "default_2417")] - pub fence: Integer, + pub attempt: Integer, #[serde(default = "default_2418")] - pub lease_until: Option, + pub fence: Integer, #[serde(default = "default_2419")] - pub outcome: std::collections::HashMap, + pub lease_until: Option, #[serde(default = "default_2420")] + pub outcome: std::collections::HashMap, + #[serde(default = "default_2421")] pub last_actor: String, pub created_at: String, pub updated_at: String, @@ -55620,7 +55737,7 @@ pub struct TaskPayload { #[non_exhaustive] pub struct TaskOutput { pub task: TaskPayload, - #[serde(default = "default_2421")] + #[serde(default = "default_2422")] pub seq: Integer, } @@ -56021,10 +56138,10 @@ impl TaskCompleteInput { pub struct InboxCount { pub inbox: String, pub status: String, - #[serde(default = "default_2422")] + #[serde(default = "default_2423")] pub blocked_on: String, pub n: Integer, - #[serde(default = "default_2423")] + #[serde(default = "default_2424")] pub oldest: Option, } @@ -56111,7 +56228,7 @@ pub struct TaskCreateOutput { pub task: TaskPayload, pub created: bool, pub seq: Integer, - #[serde(default = "default_2424")] + #[serde(default = "default_2425")] pub next: String, } @@ -56450,7 +56567,7 @@ impl TaskFailInput { #[non_exhaustive] pub struct TaskGetOutput { pub found: bool, - #[serde(default = "default_2425")] + #[serde(default = "default_2426")] pub task: Option, } @@ -56584,23 +56701,23 @@ pub struct TaskEventPayload { pub task_id: String, pub inbox: String, pub event: String, - #[serde(default = "default_2426")] - pub from_status: String, #[serde(default = "default_2427")] - pub to_status: String, + pub from_status: String, #[serde(default = "default_2428")] - pub actor: String, + pub to_status: String, #[serde(default = "default_2429")] - pub agent: String, + pub actor: String, #[serde(default = "default_2430")] - pub fence: Integer, + pub agent: String, #[serde(default = "default_2431")] - pub version: Integer, + pub fence: Integer, #[serde(default = "default_2432")] - pub reason: String, + pub version: Integer, #[serde(default = "default_2433")] - pub patch: std::collections::HashMap, + pub reason: String, #[serde(default = "default_2434")] + pub patch: std::collections::HashMap, + #[serde(default = "default_2435")] pub note: String, pub ts: String, } @@ -56940,7 +57057,7 @@ pub struct TaskPullOutput { pub tasks: Vec, pub waited_ms: Integer, pub backend: String, - #[serde(default = "default_2435")] + #[serde(default = "default_2436")] pub note: String, } @@ -57336,7 +57453,7 @@ impl TaskUnblockInput { pub struct TaskUpdateOutput { pub task: TaskPayload, pub seq: Integer, - #[serde(default = "default_2436")] + #[serde(default = "default_2437")] pub conflict: bool, } @@ -57699,19 +57816,19 @@ impl TaskReasonInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerAnswerOutput { - #[serde(default = "default_2437")] - pub intent: String, #[serde(default = "default_2438")] - pub anchors: std::collections::HashMap, + pub intent: String, #[serde(default = "default_2439")] - pub sections: Vec>, + pub anchors: std::collections::HashMap, #[serde(default = "default_2440")] - pub searched: Vec, + pub sections: Vec>, #[serde(default = "default_2441")] - pub lines: Vec, + pub searched: Vec, #[serde(default = "default_2442")] - pub restricted: bool, + pub lines: Vec, #[serde(default = "default_2443")] + pub restricted: bool, + #[serde(default = "default_2444")] pub verdict: String, } @@ -57807,17 +57924,17 @@ impl TrackerAnswerInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerBindingOutput { - #[serde(default = "default_2444")] - pub tracker_namespace: String, #[serde(default = "default_2445")] - pub tracker_namespaces: Vec, + pub tracker_namespace: String, #[serde(default = "default_2446")] - pub restricted: bool, + pub tracker_namespaces: Vec, #[serde(default = "default_2447")] - pub kind: String, + pub restricted: bool, #[serde(default = "default_2448")] - pub authorized: bool, + pub kind: String, #[serde(default = "default_2449")] + pub authorized: bool, + #[serde(default = "default_2450")] pub templates: Vec, } @@ -57870,13 +57987,13 @@ impl TrackerBindingInput { #[non_exhaustive] pub struct TrackerComponentOutput { pub component: String, - #[serde(default = "default_2450")] - pub risk: std::collections::HashMap, #[serde(default = "default_2451")] - pub open_issues: Vec>, + pub risk: std::collections::HashMap, #[serde(default = "default_2452")] - pub known: bool, + pub open_issues: Vec>, #[serde(default = "default_2453")] + pub known: bool, + #[serde(default = "default_2454")] pub tracker_unavailable: bool, } @@ -57937,9 +58054,9 @@ impl TrackerComponentInput { #[non_exhaustive] pub struct TrackerContractOutput { pub database: String, - #[serde(default = "default_2454")] - pub tables: Vec>, #[serde(default = "default_2455")] + pub tables: Vec>, + #[serde(default = "default_2456")] pub templates: std::collections::HashMap, } @@ -57992,66 +58109,66 @@ impl TrackerContractInput { #[non_exhaustive] pub struct TrackerLegStatus { pub name: String, - #[serde(default = "default_2466")] - pub status: String, #[serde(default = "default_2467")] - pub reason: String, + pub status: String, #[serde(default = "default_2468")] - pub message: String, + pub reason: String, #[serde(default = "default_2469")] - pub retried: bool, + pub message: String, #[serde(default = "default_2470")] - pub ms: Integer, + pub retried: bool, #[serde(default = "default_2471")] - pub cause: String, + pub ms: Integer, #[serde(default = "default_2472")] + pub cause: String, + #[serde(default = "default_2473")] pub namespace: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerDuplicateCheckOutput { - #[serde(default = "default_2456")] - pub verdict: String, #[serde(default = "default_2457")] - pub items: Vec>, + pub verdict: String, #[serde(default = "default_2458")] - pub undecided: bool, + pub items: Vec>, #[serde(default = "default_2459")] - pub epistemic: String, + pub undecided: bool, #[serde(default = "default_2460")] - pub thresholds: std::collections::HashMap, + pub epistemic: String, #[serde(default = "default_2461")] - pub judge: std::collections::HashMap, + pub thresholds: std::collections::HashMap, #[serde(default = "default_2462")] - pub fit_at: String, + pub judge: std::collections::HashMap, #[serde(default = "default_2463")] - pub fit: std::collections::HashMap, + pub fit_at: String, #[serde(default = "default_2464")] - pub query: std::collections::HashMap, + pub fit: std::collections::HashMap, #[serde(default = "default_2465")] + pub query: std::collections::HashMap, + #[serde(default = "default_2466")] pub legs: std::collections::HashMap, - #[serde(default = "default_2473")] - pub leg_status: Vec, #[serde(default = "default_2474")] - pub tracker_unavailable: bool, + pub leg_status: Vec, #[serde(default = "default_2475")] - pub namespaces: Vec, + pub tracker_unavailable: bool, #[serde(default = "default_2476")] - pub by_namespace: std::collections::HashMap>, + pub namespaces: Vec, #[serde(default = "default_2477")] - pub closest: Vec>, + pub by_namespace: std::collections::HashMap>, #[serde(default = "default_2478")] - pub needs: Vec>, + pub closest: Vec>, #[serde(default = "default_2479")] - pub closest_note: String, + pub needs: Vec>, #[serde(default = "default_2480")] - pub nearest: Vec>, + pub closest_note: String, #[serde(default = "default_2481")] - pub rerank: std::collections::HashMap, + pub nearest: Vec>, #[serde(default = "default_2482")] - pub answer: String, + pub rerank: std::collections::HashMap, #[serde(default = "default_2483")] + pub answer: String, + #[serde(default = "default_2484")] pub related_prs: Vec>, } @@ -58258,17 +58375,17 @@ impl TrackerDuplicateCheckInput { #[non_exhaustive] pub struct TrackerFlakyOutput { pub test_name: String, - #[serde(default = "default_2484")] - pub known_flaky: bool, #[serde(default = "default_2485")] - pub open_issues: Integer, + pub known_flaky: bool, #[serde(default = "default_2486")] - pub issues: Vec>, + pub open_issues: Integer, #[serde(default = "default_2487")] - pub verdict: String, + pub issues: Vec>, #[serde(default = "default_2488")] - pub tracker_unavailable: bool, + pub verdict: String, #[serde(default = "default_2489")] + pub tracker_unavailable: bool, + #[serde(default = "default_2490")] pub signal: Option>, } @@ -58351,9 +58468,9 @@ impl TrackerFlakyInput { #[non_exhaustive] pub struct TrackerItemOutput { pub items: Vec>, - #[serde(default = "default_2490")] - pub unknown: Vec, #[serde(default = "default_2491")] + pub unknown: Vec, + #[serde(default = "default_2492")] pub tracker_unavailable: bool, } @@ -58402,19 +58519,19 @@ impl TrackerItemInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerLinksOutput { - #[serde(default = "default_2492")] - pub subject: std::collections::HashMap, #[serde(default = "default_2493")] - pub verdict: String, + pub subject: std::collections::HashMap, #[serde(default = "default_2494")] - pub items: Vec>, + pub verdict: String, #[serde(default = "default_2495")] - pub epistemic: String, + pub items: Vec>, #[serde(default = "default_2496")] - pub record: std::collections::HashMap, + pub epistemic: String, #[serde(default = "default_2497")] - pub computed_at: String, + pub record: std::collections::HashMap, #[serde(default = "default_2498")] + pub computed_at: String, + #[serde(default = "default_2499")] pub tracker_unavailable: bool, } @@ -58512,11 +58629,11 @@ impl TrackerLinksInput { pub struct TrackerReleaseOutput { pub version: String, pub blockers: Vec>, - #[serde(default = "default_2499")] - pub active_blockers: Integer, #[serde(default = "default_2500")] - pub health: std::collections::HashMap, + pub active_blockers: Integer, #[serde(default = "default_2501")] + pub health: std::collections::HashMap, + #[serde(default = "default_2502")] pub tracker_unavailable: bool, } @@ -58565,17 +58682,17 @@ impl TrackerReleaseInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSimilarOutput { - #[serde(default = "default_2502")] - pub items: Vec>, #[serde(default = "default_2503")] - pub query: std::collections::HashMap, + pub items: Vec>, #[serde(default = "default_2504")] - pub legs: std::collections::HashMap, + pub query: std::collections::HashMap, #[serde(default = "default_2505")] - pub epistemic: String, + pub legs: std::collections::HashMap, #[serde(default = "default_2506")] - pub tracker_unavailable: bool, + pub epistemic: String, #[serde(default = "default_2507")] + pub tracker_unavailable: bool, + #[serde(default = "default_2508")] pub namespaces: Vec, } @@ -58696,19 +58813,19 @@ pub struct TrackerSourceAddOutput { pub name: String, pub host: String, pub database: String, - #[serde(default = "default_2508")] - pub namespaces: Vec>, #[serde(default = "default_2509")] - pub contract: std::collections::HashMap, + pub namespaces: Vec>, #[serde(default = "default_2510")] - pub roles: Vec, + pub contract: std::collections::HashMap, #[serde(default = "default_2511")] - pub my_role: String, + pub roles: Vec, #[serde(default = "default_2512")] - pub dry_run: bool, + pub my_role: String, #[serde(default = "default_2513")] - pub written: bool, + pub dry_run: bool, #[serde(default = "default_2514")] + pub written: bool, + #[serde(default = "default_2515")] pub view_templates: std::collections::HashMap, } @@ -58871,13 +58988,13 @@ impl TrackerSourceAddInput { #[non_exhaustive] pub struct TrackerSourceCheckOutput { pub name: String, - #[serde(default = "default_2515")] - pub database: String, #[serde(default = "default_2516")] - pub reachable: bool, + pub database: String, #[serde(default = "default_2517")] - pub contract: std::collections::HashMap, + pub reachable: bool, #[serde(default = "default_2518")] + pub contract: std::collections::HashMap, + #[serde(default = "default_2519")] pub view_templates: std::collections::HashMap, } @@ -58917,11 +59034,11 @@ impl TrackerSourceCheckInput { pub struct TrackerSourceInspectOutput { pub host: String, pub database: String, - #[serde(default = "default_2519")] - pub tables: Vec>, #[serde(default = "default_2520")] - pub roles: Vec, + pub tables: Vec>, #[serde(default = "default_2521")] + pub roles: Vec, + #[serde(default = "default_2522")] pub proposal: std::collections::HashMap, } @@ -59050,9 +59167,9 @@ impl TrackerSourceInspectInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct TrackerSourceListOutput { - #[serde(default = "default_2522")] - pub sources: Vec>, #[serde(default = "default_2523")] + pub sources: Vec>, + #[serde(default = "default_2524")] pub self_service: bool, } @@ -59105,9 +59222,9 @@ impl TrackerSourceListInput { #[non_exhaustive] pub struct TrackerSourceRemoveOutput { pub name: String, - #[serde(default = "default_2524")] - pub deactivated: bool, #[serde(default = "default_2525")] + pub deactivated: bool, + #[serde(default = "default_2526")] pub namespaces_retired: Vec, } @@ -59148,9 +59265,9 @@ impl TrackerSourceRemoveInput { #[non_exhaustive] pub struct TrackerSourceRotateOutput { pub name: String, - #[serde(default = "default_2526")] - pub contract: std::collections::HashMap, #[serde(default = "default_2527")] + pub contract: std::collections::HashMap, + #[serde(default = "default_2528")] pub rotated_at: String, } @@ -59197,11 +59314,11 @@ impl TrackerSourceRotateInput { #[non_exhaustive] pub struct TrackerSourceSetMappingOutput { pub name: String, - #[serde(default = "default_2528")] - pub contract: std::collections::HashMap, #[serde(default = "default_2529")] - pub dry_run: bool, + pub contract: std::collections::HashMap, #[serde(default = "default_2530")] + pub dry_run: bool, + #[serde(default = "default_2531")] pub written: bool, } @@ -59268,45 +59385,45 @@ impl TrackerSourceSetMappingInput { #[non_exhaustive] pub struct TrackerTestSignalOutput { pub test_name: String, - #[serde(default = "default_2531")] - pub verdict: String, #[serde(default = "default_2532")] - pub why: Vec, + pub verdict: String, #[serde(default = "default_2533")] - pub lower_bound: f64, + pub why: Vec, #[serde(default = "default_2534")] - pub window_days: Integer, + pub lower_bound: f64, #[serde(default = "default_2535")] - pub since: String, + pub window_days: Integer, #[serde(default = "default_2536")] - pub features: std::collections::HashMap, + pub since: String, #[serde(default = "default_2537")] - pub infra: std::collections::HashMap, + pub features: std::collections::HashMap, #[serde(default = "default_2538")] - pub churn: std::collections::HashMap, + pub infra: std::collections::HashMap, #[serde(default = "default_2539")] - pub thresholds: std::collections::HashMap, + pub churn: std::collections::HashMap, #[serde(default = "default_2540")] - pub source: String, + pub thresholds: std::collections::HashMap, #[serde(default = "default_2541")] - pub timings_ms: std::collections::HashMap, + pub source: String, #[serde(default = "default_2542")] - pub tracker_unavailable: bool, + pub timings_ms: std::collections::HashMap, #[serde(default = "default_2543")] - pub rollup: std::collections::HashMap, + pub tracker_unavailable: bool, #[serde(default = "default_2544")] - pub streak: std::collections::HashMap, + pub rollup: std::collections::HashMap, #[serde(default = "default_2545")] - pub smells: std::collections::HashMap, + pub streak: std::collections::HashMap, #[serde(default = "default_2546")] - pub prior: std::collections::HashMap, + pub smells: std::collections::HashMap, #[serde(default = "default_2547")] - pub unavailable_reason: String, + pub prior: std::collections::HashMap, #[serde(default = "default_2548")] - pub candidates: Vec>, + pub unavailable_reason: String, #[serde(default = "default_2549")] - pub candidate_matches: Integer, + pub candidates: Vec>, #[serde(default = "default_2550")] + pub candidate_matches: Integer, + #[serde(default = "default_2551")] pub resolved_from: String, } @@ -59410,9 +59527,9 @@ impl TrackerTestSignalInput { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct UiVitalsOutput { - #[serde(default = "default_2551")] - pub recorded: bool, #[serde(default = "default_2552")] + pub recorded: bool, + #[serde(default = "default_2553")] pub route: String, } @@ -59596,7 +59713,7 @@ pub struct WebhookDelivery { #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookDeliveriesOutput { - #[serde(default = "default_2553")] + #[serde(default = "default_2554")] pub deliveries: Vec, } @@ -59718,14 +59835,14 @@ pub struct WebhookInfo { pub secret_ref: String, pub events: Vec, pub created_at: String, - #[serde(default = "default_2554")] + #[serde(default = "default_2555")] pub secret_present: bool, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[non_exhaustive] pub struct WebhookListOutput { - #[serde(default = "default_2555")] + #[serde(default = "default_2556")] pub webhooks: Vec, } @@ -59907,7 +60024,7 @@ pub struct WorkingMemoryMutationOutput { pub version: Integer, pub char_limit: Integer, pub value_length: Integer, - #[serde(default = "default_2556")] + #[serde(default = "default_2557")] pub fill_ratio: f64, } @@ -60131,15 +60248,15 @@ impl WorkingMemoryDeleteInput { pub struct WorkingMemoryGetOutput { pub found: bool, pub block_key: String, - #[serde(default = "default_2557")] - pub content: String, #[serde(default = "default_2558")] - pub char_limit: Integer, + pub content: String, #[serde(default = "default_2559")] - pub version: Integer, + pub char_limit: Integer, #[serde(default = "default_2560")] - pub updated_at: Option, + pub version: Integer, #[serde(default = "default_2561")] + pub updated_at: Option, + #[serde(default = "default_2562")] pub fill_ratio: f64, } @@ -60250,7 +60367,7 @@ pub struct WorkingMemoryBlock { pub content: String, pub char_limit: Integer, pub version: Integer, - #[serde(default = "default_2562")] + #[serde(default = "default_2563")] pub updated_at: Option, } @@ -60258,7 +60375,7 @@ pub struct WorkingMemoryBlock { #[non_exhaustive] pub struct WorkingMemoryRenderOutput { pub rendered: String, - #[serde(default = "default_2563")] + #[serde(default = "default_2564")] pub blocks: Vec, pub block_count: Integer, pub total_chars: Integer, @@ -64416,26 +64533,26 @@ fn default_1260() -> bool { fn default_1261() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1262() -> String { +fn default_1262() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1263() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1263() -> std::collections::HashMap { +fn default_1264() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1264() -> String { +fn default_1265() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1265() -> Vec { +fn default_1266() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1266() -> bool { +fn default_1267() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1267() -> String { - serde_json::from_str("\"disabled\"").expect("schema default") -} fn default_1268() -> String { - serde_json::from_str("\"\"").expect("schema default") + serde_json::from_str("\"disabled\"").expect("schema default") } fn default_1269() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -64452,173 +64569,173 @@ fn default_1272() -> String { fn default_1273() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1274() -> Integer { +fn default_1274() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1275() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1275() -> f64 { +fn default_1276() -> f64 { serde_json::from_str("0").expect("schema default") } -fn default_1276() -> Integer { +fn default_1277() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1277() -> KnowledgeSourceProbe { +fn default_1278() -> KnowledgeSourceProbe { serde_json::from_str( "{\"documents\":0,\"more\":false,\"sample\":[],\"checked\":0,\"sampled\":false}", ) .expect("schema default") } -fn default_1278() -> String { +fn default_1279() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1279() -> bool { +fn default_1280() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1280() -> Vec> { +fn default_1281() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1281() -> Vec { +fn default_1282() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1282() -> std::collections::HashMap { +fn default_1283() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1283() -> Vec> { +fn default_1284() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1284() -> Vec> { +fn default_1285() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1285() -> KnowledgeSourceProbe { +fn default_1286() -> KnowledgeSourceProbe { serde_json::from_str( "{\"documents\":0,\"more\":false,\"sample\":[],\"checked\":0,\"sampled\":false}", ) .expect("schema default") } -fn default_1286() -> Vec { +fn default_1287() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1287() -> Integer { +fn default_1288() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1288() -> Option> { +fn default_1289() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_1289() -> Vec { +fn default_1290() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1290() -> Vec { +fn default_1291() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1291() -> bool { +fn default_1292() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1292() -> bool { +fn default_1293() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1293() -> String { +fn default_1294() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1294() -> String { +fn default_1295() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1295() -> Vec> { +fn default_1296() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1296() -> bool { +fn default_1297() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1297() -> Vec { +fn default_1298() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1298() -> Vec { +fn default_1299() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1299() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1300() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1301() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1302() -> Vec { +fn default_1302() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1303() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1303() -> Integer { +fn default_1304() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1304() -> String { +fn default_1305() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1305() -> Integer { +fn default_1306() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1306() -> String { +fn default_1307() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1307() -> String { +fn default_1308() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1308() -> Integer { +fn default_1309() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1309() -> Integer { +fn default_1310() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1310() -> String { +fn default_1311() -> String { serde_json::from_str("\"memory_supporters\"").expect("schema default") } -fn default_1311() -> String { +fn default_1312() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1312() -> String { +fn default_1313() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1313() -> Option { +fn default_1314() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1314() -> String { +fn default_1315() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1315() -> String { +fn default_1316() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1316() -> bool { +fn default_1317() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1317() -> bool { +fn default_1318() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1318() -> String { +fn default_1319() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1319() -> std::collections::HashMap { +fn default_1320() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1320() -> Vec { +fn default_1321() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1321() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1322() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1323() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1324() -> Vec { - serde_json::from_str("[]").expect("schema default") -} -fn default_1325() -> String { +fn default_1324() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_1325() -> Vec { + serde_json::from_str("[]").expect("schema default") +} fn default_1326() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1327() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_1327() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_1328() -> Vec { serde_json::from_str("[]").expect("schema default") @@ -64629,33 +64746,33 @@ fn default_1329() -> Vec { fn default_1330() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1331() -> Integer { - serde_json::from_str("0").expect("schema default") -} -fn default_1332() -> Vec { +fn default_1331() -> Vec { serde_json::from_str("[]").expect("schema default") } +fn default_1332() -> Integer { + serde_json::from_str("0").expect("schema default") +} fn default_1333() -> Vec { serde_json::from_str("[]").expect("schema default") } fn default_1334() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1335() -> Integer { +fn default_1335() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_1336() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1336() -> Vec { +fn default_1337() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1337() -> std::collections::HashMap { +fn default_1338() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1338() -> std::collections::HashMap { +fn default_1339() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1339() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1340() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -64671,11 +64788,11 @@ fn default_1343() -> Integer { fn default_1344() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1345() -> bool { - serde_json::from_str("false").expect("schema default") +fn default_1345() -> Integer { + serde_json::from_str("0").expect("schema default") } -fn default_1346() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_1346() -> bool { + serde_json::from_str("false").expect("schema default") } fn default_1347() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -64686,75 +64803,75 @@ fn default_1348() -> String { fn default_1349() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1350() -> Option { +fn default_1350() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1351() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1351() -> String { +fn default_1352() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1352() -> Vec { +fn default_1353() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1353() -> String { +fn default_1354() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1354() -> MemoryAskOutputSource { +fn default_1355() -> MemoryAskOutputSource { serde_json::from_str("\"synthesized\"").expect("schema default") } -fn default_1355() -> bool { +fn default_1356() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1356() -> String { +fn default_1357() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1357() -> Vec { +fn default_1358() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1358() -> Vec { +fn default_1359() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1359() -> Vec { +fn default_1360() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1360() -> String { +fn default_1361() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1361() -> String { +fn default_1362() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1362() -> MemoryAskOutputRouteTier { +fn default_1363() -> MemoryAskOutputRouteTier { serde_json::from_str("\"\"").expect("schema default") } -fn default_1363() -> String { +fn default_1364() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1364() -> Integer { +fn default_1365() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1365() -> Integer { +fn default_1366() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1366() -> bool { +fn default_1367() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1367() -> f64 { +fn default_1368() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1368() -> Option { +fn default_1369() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1369() -> Option { +fn default_1370() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1370() -> bool { +fn default_1371() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1371() -> String { +fn default_1372() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1372() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1373() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -64764,32 +64881,32 @@ fn default_1374() -> Integer { fn default_1375() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1376() -> String { +fn default_1376() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1377() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1377() -> Vec { +fn default_1378() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1378() -> Integer { +fn default_1379() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1379() -> MemoryAskOutputConsistency { +fn default_1380() -> MemoryAskOutputConsistency { serde_json::from_str("\"\"").expect("schema default") } -fn default_1380() -> f64 { +fn default_1381() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1381() -> String { +fn default_1382() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1382() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1383() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1384() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_1384() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_1385() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -64800,48 +64917,48 @@ fn default_1386() -> String { fn default_1387() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1388() -> MemoryAskOutputDepth { +fn default_1388() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1389() -> bool { +fn default_1389() -> MemoryAskOutputDepth { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1390() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1390() -> Vec { +fn default_1391() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1391() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1392() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_1393() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1394() -> Vec { - serde_json::from_str("[]").expect("schema default") -} -fn default_1395() -> Integer { +fn default_1394() -> Integer { serde_json::from_str("0").expect("schema default") } +fn default_1395() -> Vec { + serde_json::from_str("[]").expect("schema default") +} fn default_1396() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_1397() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1398() -> MemoryAskOutputGrounding { +fn default_1398() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1399() -> MemoryAskOutputGrounding { serde_json::from_str("\"\"").expect("schema default") } -fn default_1399() -> String { +fn default_1400() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1400() -> Vec { +fn default_1401() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1401() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1402() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -64851,18 +64968,18 @@ fn default_1403() -> Integer { fn default_1404() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1405() -> std::collections::HashMap { +fn default_1405() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1406() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1406() -> MemoryAskOutputDeepSelector { +fn default_1407() -> MemoryAskOutputDeepSelector { serde_json::from_str("\"\"").expect("schema default") } -fn default_1407() -> MemoryAskOutputDeepFirst { +fn default_1408() -> MemoryAskOutputDeepFirst { serde_json::from_str("\"\"").expect("schema default") } -fn default_1408() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1409() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -64872,12 +64989,12 @@ fn default_1410() -> Integer { fn default_1411() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1412() -> f64 { - serde_json::from_str("0.0").expect("schema default") -} -fn default_1413() -> Integer { +fn default_1412() -> Integer { serde_json::from_str("0").expect("schema default") } +fn default_1413() -> f64 { + serde_json::from_str("0.0").expect("schema default") +} fn default_1414() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -64890,11 +65007,11 @@ fn default_1416() -> Integer { fn default_1417() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1418() -> bool { - serde_json::from_str("false").expect("schema default") +fn default_1418() -> Integer { + serde_json::from_str("0").expect("schema default") } -fn default_1419() -> String { - serde_json::from_str("\"-\"").expect("schema default") +fn default_1419() -> bool { + serde_json::from_str("false").expect("schema default") } fn default_1420() -> String { serde_json::from_str("\"-\"").expect("schema default") @@ -64903,7 +65020,7 @@ fn default_1421() -> String { serde_json::from_str("\"-\"").expect("schema default") } fn default_1422() -> String { - serde_json::from_str("\"\"").expect("schema default") + serde_json::from_str("\"-\"").expect("schema default") } fn default_1423() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -64911,120 +65028,120 @@ fn default_1423() -> String { fn default_1424() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1425() -> bool { +fn default_1425() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1426() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1426() -> String { +fn default_1427() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1427() -> Option { +fn default_1428() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1428() -> String { +fn default_1429() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1429() -> String { +fn default_1430() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1430() -> Vec { +fn default_1431() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1431() -> Option { +fn default_1432() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1432() -> bool { +fn default_1433() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1433() -> String { +fn default_1434() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1434() -> String { +fn default_1435() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1435() -> Vec { +fn default_1436() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1436() -> String { +fn default_1437() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1437() -> Vec { +fn default_1438() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1438() -> String { +fn default_1439() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1439() -> String { +fn default_1440() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1440() -> Vec { +fn default_1441() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1441() -> Vec { +fn default_1442() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1442() -> Integer { +fn default_1443() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1443() -> Vec { +fn default_1444() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1444() -> Vec { +fn default_1445() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1445() -> String { +fn default_1446() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1446() -> String { +fn default_1447() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1447() -> bool { +fn default_1448() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1448() -> String { +fn default_1449() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1449() -> String { +fn default_1450() -> String { serde_json::from_str("\"fact\"").expect("schema default") } -fn default_1450() -> String { +fn default_1451() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1451() -> bool { +fn default_1452() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1452() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1453() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1454() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1455() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_1455() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_1456() -> Vec { +fn default_1456() -> Vec { serde_json::from_str("[]").expect("schema default") } fn default_1457() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1458() -> std::collections::HashMap { +fn default_1458() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_1459() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1459() -> Vec { +fn default_1460() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1460() -> Integer { +fn default_1461() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1461() -> Vec { +fn default_1462() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1462() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1463() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -65043,8 +65160,8 @@ fn default_1467() -> Integer { fn default_1468() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1469() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_1469() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_1470() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -65055,11 +65172,11 @@ fn default_1471() -> String { fn default_1472() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1473() -> bool { - serde_json::from_str("true").expect("schema default") +fn default_1473() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_1474() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_1474() -> bool { + serde_json::from_str("true").expect("schema default") } fn default_1475() -> Integer { serde_json::from_str("0").expect("schema default") @@ -65073,114 +65190,114 @@ fn default_1477() -> Integer { fn default_1478() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1479() -> bool { +fn default_1479() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1480() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1480() -> Vec { +fn default_1481() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1481() -> String { +fn default_1482() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1482() -> String { +fn default_1483() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1483() -> Option { +fn default_1484() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1484() -> Vec { +fn default_1485() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1485() -> bool { +fn default_1486() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1486() -> bool { +fn default_1487() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1487() -> Vec { +fn default_1488() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1488() -> bool { +fn default_1489() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1489() -> Option { +fn default_1490() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1490() -> Vec { +fn default_1491() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1491() -> Option { +fn default_1492() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1492() -> Option { +fn default_1493() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1493() -> Vec { +fn default_1494() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1494() -> Integer { +fn default_1495() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1495() -> bool { +fn default_1496() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1496() -> String { +fn default_1497() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1497() -> Integer { +fn default_1498() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1498() -> Integer { +fn default_1499() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1499() -> std::collections::HashMap { +fn default_1500() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1500() -> String { +fn default_1501() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1501() -> f64 { +fn default_1502() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1502() -> bool { +fn default_1503() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1503() -> String { +fn default_1504() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1504() -> String { +fn default_1505() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1505() -> Integer { +fn default_1506() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1506() -> Integer { +fn default_1507() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1507() -> Option { +fn default_1508() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1508() -> Vec { +fn default_1509() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1509() -> Vec { +fn default_1510() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1510() -> Option { +fn default_1511() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1511() -> Option { +fn default_1512() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1512() -> Integer { +fn default_1513() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1513() -> bool { +fn default_1514() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1514() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1515() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -65190,30 +65307,30 @@ fn default_1516() -> String { fn default_1517() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1518() -> Option { +fn default_1518() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1519() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1519() -> String { +fn default_1520() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1520() -> Integer { +fn default_1521() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1521() -> Integer { +fn default_1522() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1522() -> String { +fn default_1523() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1523() -> Vec { +fn default_1524() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1524() -> bool { +fn default_1525() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1525() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1526() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -65226,81 +65343,81 @@ fn default_1528() -> Integer { fn default_1529() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1530() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_1530() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_1531() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1532() -> String { - serde_json::from_str("\"-\"").expect("schema default") + serde_json::from_str("\"\"").expect("schema default") } fn default_1533() -> String { + serde_json::from_str("\"-\"").expect("schema default") +} +fn default_1534() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1534() -> Vec { +fn default_1535() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1535() -> Integer { +fn default_1536() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1536() -> Integer { +fn default_1537() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1537() -> String { +fn default_1538() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1538() -> String { +fn default_1539() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1539() -> Vec { +fn default_1540() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1540() -> String { +fn default_1541() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1541() -> String { +fn default_1542() -> String { serde_json::from_str("\"-\"").expect("schema default") } -fn default_1542() -> Vec { +fn default_1543() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1543() -> Vec { +fn default_1544() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1544() -> String { +fn default_1545() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1545() -> String { +fn default_1546() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1546() -> Vec { +fn default_1547() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1547() -> f64 { +fn default_1548() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1548() -> String { +fn default_1549() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1549() -> String { +fn default_1550() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1550() -> Vec { +fn default_1551() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1551() -> bool { +fn default_1552() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1552() -> String { +fn default_1553() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1553() -> Integer { +fn default_1554() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1554() -> Vec { - serde_json::from_str("[]").expect("schema default") -} fn default_1555() -> Vec { serde_json::from_str("[]").expect("schema default") } @@ -65313,57 +65430,57 @@ fn default_1557() -> Vec { fn default_1558() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1559() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_1559() -> Vec { + serde_json::from_str("[]").expect("schema default") } fn default_1560() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1561() -> Vec { +fn default_1561() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1562() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1562() -> Integer { +fn default_1563() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1563() -> Integer { +fn default_1564() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1564() -> Vec { +fn default_1565() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1565() -> Vec { +fn default_1566() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1566() -> Integer { +fn default_1567() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1567() -> Integer { +fn default_1568() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1568() -> bool { +fn default_1569() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1569() -> Vec { +fn default_1570() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1570() -> f64 { +fn default_1571() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1571() -> bool { +fn default_1572() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1572() -> String { +fn default_1573() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1573() -> String { +fn default_1574() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1574() -> Option { +fn default_1575() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1575() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1576() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -65373,36 +65490,36 @@ fn default_1577() -> String { fn default_1578() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1579() -> MemoryForFileHitSupersedesKind { +fn default_1579() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1580() -> Vec { +fn default_1580() -> MemoryForFileHitSupersedesKind { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1581() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1581() -> String { +fn default_1582() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1582() -> MemoryForFileHitVerification { +fn default_1583() -> MemoryForFileHitVerification { serde_json::from_str("\"none\"").expect("schema default") } -fn default_1583() -> MemoryForFileHitCodeState { +fn default_1584() -> MemoryForFileHitCodeState { serde_json::from_str("\"\"").expect("schema default") } -fn default_1584() -> Vec { +fn default_1585() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1585() -> String { +fn default_1586() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1586() -> Integer { +fn default_1587() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1587() -> bool { +fn default_1588() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1588() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1589() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -65418,19 +65535,19 @@ fn default_1592() -> String { fn default_1593() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1594() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_1594() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_1595() -> Value { +fn default_1595() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1596() -> Option { +fn default_1596() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1597() -> Option { +fn default_1597() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1598() -> Option { +fn default_1598() -> Option { serde_json::from_str("null").expect("schema default") } fn default_1599() -> Option { @@ -65442,23 +65559,23 @@ fn default_1600() -> Option { fn default_1601() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1602() -> bool { +fn default_1602() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1603() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1603() -> String { +fn default_1604() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1604() -> String { +fn default_1605() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1605() -> Option { +fn default_1606() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1606() -> String { - serde_json::from_str("\"none\"").expect("schema default") -} fn default_1607() -> String { - serde_json::from_str("\"\"").expect("schema default") + serde_json::from_str("\"none\"").expect("schema default") } fn default_1608() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -65472,45 +65589,45 @@ fn default_1610() -> String { fn default_1611() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1612() -> Option { - serde_json::from_str("null").expect("schema default") -} -fn default_1613() -> String { +fn default_1612() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_1613() -> Option { + serde_json::from_str("null").expect("schema default") +} fn default_1614() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1615() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1616() -> Integer { +fn default_1616() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1617() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1617() -> Vec { +fn default_1618() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1618() -> Integer { +fn default_1619() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1619() -> Option { +fn default_1620() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1620() -> Vec { +fn default_1621() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1621() -> std::collections::HashMap { +fn default_1622() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1622() -> Integer { +fn default_1623() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1623() -> f64 { +fn default_1624() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1624() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1625() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -65523,45 +65640,45 @@ fn default_1627() -> Integer { fn default_1628() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1629() -> MemoryHealthStaleness { +fn default_1629() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1630() -> MemoryHealthStaleness { serde_json::from_str("{\"by_age\":{},\"with_validity_end\":0,\"with_validity_end_share\":0.0,\"with_expiry\":0,\"expiring_7d\":0,\"pinned\":0,\"days_since_reinforced_p50\":0,\"days_since_reinforced_p90\":0}").expect("schema default") } -fn default_1630() -> Integer { +fn default_1631() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1631() -> Integer { +fn default_1632() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1632() -> f64 { +fn default_1633() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1633() -> MemoryHealthFootprint { +fn default_1634() -> MemoryHealthFootprint { serde_json::from_str("{\"value_chars\":0,\"value_tokens_est\":0,\"tokens_per_row_est\":0.0}") .expect("schema default") } -fn default_1634() -> String { +fn default_1635() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1635() -> Value { +fn default_1636() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1636() -> String { +fn default_1637() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1637() -> bool { +fn default_1638() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1638() -> Option { - serde_json::from_str("null").expect("schema default") -} fn default_1639() -> Option { serde_json::from_str("null").expect("schema default") } fn default_1640() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1641() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_1641() -> Option { + serde_json::from_str("null").expect("schema default") } fn default_1642() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -65575,24 +65692,24 @@ fn default_1644() -> String { fn default_1645() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1646() -> Option { +fn default_1646() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1647() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1647() -> String { +fn default_1648() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1648() -> Vec { +fn default_1649() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1649() -> Vec { +fn default_1650() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1650() -> Option { +fn default_1651() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1651() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1652() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -65602,11 +65719,11 @@ fn default_1653() -> String { fn default_1654() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1655() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_1655() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_1656() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_1656() -> Option { + serde_json::from_str("null").expect("schema default") } fn default_1657() -> Integer { serde_json::from_str("0").expect("schema default") @@ -65617,57 +65734,57 @@ fn default_1658() -> Integer { fn default_1659() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1660() -> MemoryImportResultReason { +fn default_1660() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1661() -> MemoryImportResultReason { serde_json::from_str("\"\"").expect("schema default") } -fn default_1661() -> String { +fn default_1662() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1662() -> MemoryImportResultNote { +fn default_1663() -> MemoryImportResultNote { serde_json::from_str("\"\"").expect("schema default") } -fn default_1663() -> bool { +fn default_1664() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1664() -> String { +fn default_1665() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1665() -> Option { +fn default_1666() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1666() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1667() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_1668() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1669() -> String { +fn default_1669() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1670() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1670() -> Integer { +fn default_1671() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1671() -> Vec { +fn default_1672() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1672() -> Integer { +fn default_1673() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1673() -> Integer { +fn default_1674() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1674() -> Vec { +fn default_1675() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1675() -> Integer { +fn default_1676() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1676() -> Vec { - serde_json::from_str("[]").expect("schema default") -} fn default_1677() -> Vec { serde_json::from_str("[]").expect("schema default") } @@ -65680,241 +65797,241 @@ fn default_1679() -> Vec { fn default_1680() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1681() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_1681() -> Vec { + serde_json::from_str("[]").expect("schema default") } fn default_1682() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1683() -> String { +fn default_1683() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1684() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1684() -> Integer { +fn default_1685() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1685() -> String { +fn default_1686() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1686() -> Vec { +fn default_1687() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1687() -> bool { +fn default_1688() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1688() -> Vec { +fn default_1689() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1689() -> Option { +fn default_1690() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1690() -> Option { +fn default_1691() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1691() -> String { +fn default_1692() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1692() -> Integer { +fn default_1693() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1693() -> String { +fn default_1694() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1694() -> Integer { +fn default_1695() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1695() -> Option { +fn default_1696() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1696() -> String { +fn default_1697() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1697() -> String { +fn default_1698() -> String { serde_json::from_str("\"Each request that extracts memories from messages may send extraction instructions; no user, agent or session setting stores them.\"").expect("schema default") } -fn default_1698() -> Vec { +fn default_1699() -> Vec { serde_json::from_str("[\"memory.set_from_messages\",\"extraction_instructions\"]") .expect("schema default") } -fn default_1699() -> Vec { +fn default_1700() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1700() -> bool { +fn default_1701() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1701() -> String { +fn default_1702() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1702() -> String { +fn default_1703() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1703() -> Option { +fn default_1704() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1704() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1705() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1706() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1707() -> MemoryLineageOutputMechanism { +fn default_1707() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1708() -> MemoryLineageOutputMechanism { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_1708() -> Vec { +fn default_1709() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1709() -> String { +fn default_1710() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1710() -> String { +fn default_1711() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1711() -> Option { +fn default_1712() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1712() -> Vec { +fn default_1713() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1713() -> f64 { +fn default_1714() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1714() -> bool { +fn default_1715() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1715() -> bool { +fn default_1716() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1716() -> Integer { +fn default_1717() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1717() -> Integer { +fn default_1718() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1718() -> String { +fn default_1719() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1719() -> bool { +fn default_1720() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1720() -> Integer { +fn default_1721() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1721() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1722() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1723() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1724() -> Option { - serde_json::from_str("null").expect("schema default") -} -fn default_1725() -> String { +fn default_1724() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1726() -> Option { +fn default_1725() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1727() -> String { +fn default_1726() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_1727() -> Option { + serde_json::from_str("null").expect("schema default") +} fn default_1728() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1729() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1730() -> Integer { +fn default_1730() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1731() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1731() -> String { +fn default_1732() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1732() -> Vec { +fn default_1733() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1733() -> bool { +fn default_1734() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1734() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1735() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1736() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1737() -> bool { +fn default_1737() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1738() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1738() -> std::collections::HashMap { +fn default_1739() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1739() -> String { +fn default_1740() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1740() -> String { +fn default_1741() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1741() -> Integer { +fn default_1742() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1742() -> Integer { +fn default_1743() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1743() -> Vec { +fn default_1744() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1744() -> Integer { +fn default_1745() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1745() -> Integer { +fn default_1746() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1746() -> Vec { +fn default_1747() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1747() -> String { +fn default_1748() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1748() -> Integer { +fn default_1749() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1749() -> String { +fn default_1750() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1750() -> Vec { +fn default_1751() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1751() -> Integer { +fn default_1752() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1752() -> Option { +fn default_1753() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1753() -> Vec { +fn default_1754() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1754() -> Integer { +fn default_1755() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1755() -> String { +fn default_1756() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1756() -> String { +fn default_1757() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1757() -> Vec { +fn default_1758() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1758() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1759() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -65927,60 +66044,60 @@ fn default_1761() -> String { fn default_1762() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1763() -> Vec { +fn default_1763() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1764() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1764() -> String { +fn default_1765() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1765() -> Integer { +fn default_1766() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1766() -> Integer { +fn default_1767() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1767() -> String { +fn default_1768() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1768() -> Integer { +fn default_1769() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1769() -> Integer { +fn default_1770() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1770() -> MemoryProposalReady { +fn default_1771() -> MemoryProposalReady { serde_json::from_str("\"\"").expect("schema default") } -fn default_1771() -> Vec { +fn default_1772() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1772() -> Vec { +fn default_1773() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1773() -> Integer { +fn default_1774() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1774() -> ProposalPolicyMode { +fn default_1775() -> ProposalPolicyMode { serde_json::from_str("\"manual\"").expect("schema default") } -fn default_1775() -> Integer { +fn default_1776() -> Integer { serde_json::from_str("2").expect("schema default") } -fn default_1776() -> Integer { +fn default_1777() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1777() -> Integer { +fn default_1778() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1778() -> ProposalPolicy { +fn default_1779() -> ProposalPolicy { serde_json::from_str( "{\"mode\":\"manual\",\"min_passes\":2,\"max_fails\":0,\"reject_after_fails\":0}", ) .expect("schema default") } -fn default_1779() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1780() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -65996,12 +66113,12 @@ fn default_1783() -> String { fn default_1784() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1785() -> bool { - serde_json::from_str("false").expect("schema default") -} -fn default_1786() -> String { +fn default_1785() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_1786() -> bool { + serde_json::from_str("false").expect("schema default") +} fn default_1787() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -66026,24 +66143,24 @@ fn default_1793() -> String { fn default_1794() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1795() -> Vec { +fn default_1795() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1796() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1796() -> f64 { +fn default_1797() -> f64 { serde_json::from_str("1.0").expect("schema default") } -fn default_1797() -> String { +fn default_1798() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1798() -> String { +fn default_1799() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1799() -> Vec { +fn default_1800() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1800() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1801() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -66053,11 +66170,11 @@ fn default_1802() -> String { fn default_1803() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1804() -> bool { - serde_json::from_str("false").expect("schema default") +fn default_1804() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_1805() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_1805() -> bool { + serde_json::from_str("false").expect("schema default") } fn default_1806() -> Integer { serde_json::from_str("0").expect("schema default") @@ -66065,183 +66182,183 @@ fn default_1806() -> Integer { fn default_1807() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1808() -> bool { +fn default_1808() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1809() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1809() -> String { +fn default_1810() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1810() -> Integer { +fn default_1811() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_1811() -> MemoryRecallOutputOrder { +fn default_1812() -> MemoryRecallOutputOrder { serde_json::from_str("\"recent\"").expect("schema default") } -fn default_1812() -> Vec { +fn default_1813() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1813() -> Integer { +fn default_1814() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1814() -> Value { +fn default_1815() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1815() -> Value { +fn default_1816() -> Value { serde_json::from_str("null").expect("schema default") } -fn default_1816() -> String { +fn default_1817() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1817() -> String { +fn default_1818() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1818() -> Option { +fn default_1819() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1819() -> Option { +fn default_1820() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1820() -> bool { +fn default_1821() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1821() -> String { +fn default_1822() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1822() -> String { +fn default_1823() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1823() -> std::collections::HashMap { +fn default_1824() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1824() -> std::collections::HashMap { +fn default_1825() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1825() -> MemoryRecordRowStatus { +fn default_1826() -> MemoryRecordRowStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1826() -> Option { +fn default_1827() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1827() -> Option { +fn default_1828() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1828() -> bool { +fn default_1829() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1829() -> String { +fn default_1830() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1830() -> MemoryRecordWriteOutputKeySource { +fn default_1831() -> MemoryRecordWriteOutputKeySource { serde_json::from_str("\"anonymous\"").expect("schema default") } -fn default_1831() -> std::collections::HashMap { +fn default_1832() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1832() -> String { +fn default_1833() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1833() -> Integer { +fn default_1834() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1834() -> bool { +fn default_1835() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1835() -> Option { +fn default_1836() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1836() -> Integer { +fn default_1837() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1837() -> Integer { +fn default_1838() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1838() -> Option { +fn default_1839() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1839() -> String { +fn default_1840() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1840() -> Integer { +fn default_1841() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1841() -> Integer { +fn default_1842() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1842() -> bool { +fn default_1843() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1843() -> Vec { +fn default_1844() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1844() -> Option { +fn default_1845() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1845() -> Option { +fn default_1846() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1846() -> bool { +fn default_1847() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1847() -> bool { +fn default_1848() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1848() -> String { +fn default_1849() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1849() -> f64 { +fn default_1850() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_1850() -> String { +fn default_1851() -> String { serde_json::from_str("\"fact\"").expect("schema default") } -fn default_1851() -> String { +fn default_1852() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1852() -> std::collections::HashMap { +fn default_1853() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1853() -> bool { +fn default_1854() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1854() -> Integer { +fn default_1855() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1855() -> String { +fn default_1856() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1856() -> Vec { +fn default_1857() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1857() -> Vec { +fn default_1858() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1858() -> Integer { +fn default_1859() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1859() -> Integer { +fn default_1860() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1860() -> String { +fn default_1861() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1861() -> String { +fn default_1862() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1862() -> Integer { +fn default_1863() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_1863() -> Integer { +fn default_1864() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1864() -> Integer { +fn default_1865() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1865() -> Vec { +fn default_1866() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1866() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1867() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -66251,65 +66368,65 @@ fn default_1868() -> Integer { fn default_1869() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1870() -> Vec { +fn default_1870() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1871() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1871() -> String { +fn default_1872() -> String { serde_json::from_str("\"whole\"").expect("schema default") } -fn default_1872() -> Integer { +fn default_1873() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1873() -> Vec { +fn default_1874() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1874() -> Vec { +fn default_1875() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1875() -> Integer { +fn default_1876() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1876() -> Vec { +fn default_1877() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1877() -> Integer { +fn default_1878() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1878() -> Vec { +fn default_1879() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1879() -> Vec { +fn default_1880() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1880() -> bool { +fn default_1881() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1881() -> String { +fn default_1882() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1882() -> String { +fn default_1883() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1883() -> std::collections::HashMap { +fn default_1884() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1884() -> String { +fn default_1885() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1885() -> bool { +fn default_1886() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1886() -> Vec { +fn default_1887() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1887() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1888() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1889() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_1889() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_1890() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -66317,29 +66434,29 @@ fn default_1890() -> String { fn default_1891() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1892() -> bool { +fn default_1892() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1893() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1893() -> Integer { +fn default_1894() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1894() -> Option { +fn default_1895() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1895() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1896() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1897() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1898() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_1898() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_1899() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_1899() -> Vec { + serde_json::from_str("[]").expect("schema default") } fn default_1900() -> Integer { serde_json::from_str("0").expect("schema default") @@ -66356,54 +66473,54 @@ fn default_1903() -> Integer { fn default_1904() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1905() -> bool { +fn default_1905() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_1906() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1906() -> Vec> { +fn default_1907() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_1907() -> Vec { +fn default_1908() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1908() -> Option { +fn default_1909() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1909() -> String { +fn default_1910() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1910() -> Integer { +fn default_1911() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1911() -> Option { +fn default_1912() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1912() -> Option { +fn default_1913() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1913() -> Option { +fn default_1914() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1914() -> Option { +fn default_1915() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1915() -> Vec { +fn default_1916() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1916() -> Integer { +fn default_1917() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1917() -> String { +fn default_1918() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1918() -> String { +fn default_1919() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1919() -> Option { +fn default_1920() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1920() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1921() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -66413,21 +66530,21 @@ fn default_1922() -> String { fn default_1923() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1924() -> Option { +fn default_1924() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1925() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1925() -> String { +fn default_1926() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1926() -> String { +fn default_1927() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1927() -> Integer { +fn default_1928() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1928() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1929() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -66440,45 +66557,45 @@ fn default_1931() -> String { fn default_1932() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1933() -> Integer { +fn default_1933() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1934() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1934() -> String { +fn default_1935() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1935() -> Vec { +fn default_1936() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1936() -> String { +fn default_1937() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1937() -> Integer { +fn default_1938() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1938() -> String { +fn default_1939() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1939() -> Integer { +fn default_1940() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1940() -> String { +fn default_1941() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1941() -> String { +fn default_1942() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1942() -> Integer { +fn default_1943() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1943() -> String { +fn default_1944() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1944() -> bool { +fn default_1945() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1945() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1946() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -66488,105 +66605,105 @@ fn default_1947() -> String { fn default_1948() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1949() -> Option { +fn default_1949() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1950() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1950() -> String { +fn default_1951() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_1951() -> Integer { +fn default_1952() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1952() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_1953() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_1954() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_1955() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_1955() -> bool { +fn default_1956() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1956() -> Vec { +fn default_1957() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1957() -> std::collections::HashMap { +fn default_1958() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1958() -> String { +fn default_1959() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1959() -> Vec { +fn default_1960() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1960() -> std::collections::HashMap { +fn default_1961() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1961() -> Integer { +fn default_1962() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1962() -> Option { +fn default_1963() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1963() -> String { +fn default_1964() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1964() -> bool { +fn default_1965() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1965() -> Vec { +fn default_1966() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1966() -> Vec { +fn default_1967() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1967() -> std::collections::HashMap { +fn default_1968() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_1968() -> Option { +fn default_1969() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1969() -> Vec { +fn default_1970() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1970() -> Integer { +fn default_1971() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1971() -> Integer { +fn default_1972() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1972() -> Vec { +fn default_1973() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1973() -> Option { +fn default_1974() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1974() -> Vec { +fn default_1975() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1975() -> Option { +fn default_1976() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1976() -> Option { +fn default_1977() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1977() -> Vec { +fn default_1978() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1978() -> bool { +fn default_1979() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_1979() -> Vec { +fn default_1980() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1980() -> bool { +fn default_1981() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_1981() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_1982() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -66611,12 +66728,12 @@ fn default_1988() -> Integer { fn default_1989() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1990() -> f64 { - serde_json::from_str("0.0").expect("schema default") -} -fn default_1991() -> Integer { +fn default_1990() -> Integer { serde_json::from_str("0").expect("schema default") } +fn default_1991() -> f64 { + serde_json::from_str("0.0").expect("schema default") +} fn default_1992() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -66626,82 +66743,82 @@ fn default_1993() -> Integer { fn default_1994() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_1995() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_1995() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_1996() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_1997() -> Vec { +fn default_1997() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_1998() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_1998() -> String { +fn default_1999() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_1999() -> String { +fn default_2000() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2000() -> Integer { +fn default_2001() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2001() -> Vec> { +fn default_2002() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2002() -> Vec { +fn default_2003() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2003() -> String { +fn default_2004() -> String { serde_json::from_str("\"memory\"").expect("schema default") } -fn default_2004() -> bool { +fn default_2005() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2005() -> String { +fn default_2006() -> String { serde_json::from_str("\"approval\"").expect("schema default") } -fn default_2006() -> String { +fn default_2007() -> String { serde_json::from_str("\"public\"").expect("schema default") } -fn default_2007() -> BrowseEntryMyStatus { +fn default_2008() -> BrowseEntryMyStatus { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2008() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2009() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_2010() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2011() -> Integer { +fn default_2011() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2012() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2012() -> String { +fn default_2013() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2013() -> Option { +fn default_2014() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2014() -> Option { +fn default_2015() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2015() -> Vec { +fn default_2016() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2016() -> Option { - serde_json::from_str("null").expect("schema default") -} fn default_2017() -> Option { serde_json::from_str("null").expect("schema default") } fn default_2018() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2019() -> Option> { +fn default_2019() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2020() -> Option { +fn default_2020() -> Option> { serde_json::from_str("null").expect("schema default") } fn default_2021() -> Option { @@ -66716,40 +66833,40 @@ fn default_2023() -> Option { fn default_2024() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2025() -> Option { +fn default_2025() -> Option { serde_json::from_str("null").expect("schema default") } fn default_2026() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2027() -> Option { +fn default_2027() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2028() -> Option { +fn default_2028() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2029() -> Option { +fn default_2029() -> Option { serde_json::from_str("null").expect("schema default") } fn default_2030() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2031() -> Option { +fn default_2031() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2032() -> Option { +fn default_2032() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2033() -> Option { +fn default_2033() -> Option { serde_json::from_str("null").expect("schema default") } fn default_2034() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2035() -> Option> { +fn default_2035() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2036() -> Option { +fn default_2036() -> Option> { serde_json::from_str("null").expect("schema default") } fn default_2037() -> Option { @@ -66758,22 +66875,22 @@ fn default_2037() -> Option { fn default_2038() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2039() -> Option { +fn default_2039() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2040() -> Option { +fn default_2040() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2041() -> Option>> { +fn default_2041() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2042() -> Option { +fn default_2042() -> Option>> { serde_json::from_str("null").expect("schema default") } -fn default_2043() -> Option { +fn default_2043() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2044() -> Option { +fn default_2044() -> Option { serde_json::from_str("null").expect("schema default") } fn default_2045() -> Option { @@ -66782,11 +66899,11 @@ fn default_2045() -> Option { fn default_2046() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2047() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_2047() -> Option { + serde_json::from_str("null").expect("schema default") } -fn default_2048() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2048() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_2049() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -66797,18 +66914,18 @@ fn default_2050() -> String { fn default_2051() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2052() -> Option { +fn default_2052() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2053() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2053() -> bool { +fn default_2054() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2054() -> Integer { +fn default_2055() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2055() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2056() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -66818,129 +66935,129 @@ fn default_2057() -> String { fn default_2058() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2059() -> Option { +fn default_2059() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2060() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2060() -> Option { +fn default_2061() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2061() -> String { +fn default_2062() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2062() -> Vec { +fn default_2063() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2063() -> String { +fn default_2064() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2064() -> String { +fn default_2065() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2065() -> Option { +fn default_2066() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2066() -> Vec { +fn default_2067() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2067() -> Option { +fn default_2068() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2068() -> String { +fn default_2069() -> String { serde_json::from_str("\"memory\"").expect("schema default") } -fn default_2069() -> bool { +fn default_2070() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2070() -> f64 { +fn default_2071() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2071() -> f64 { +fn default_2072() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2072() -> String { +fn default_2073() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2073() -> Option { +fn default_2074() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2074() -> Integer { +fn default_2075() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2075() -> Integer { +fn default_2076() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2076() -> NamespaceEntryVisibility { +fn default_2077() -> NamespaceEntryVisibility { serde_json::from_str("\"private\"").expect("schema default") } -fn default_2077() -> String { +fn default_2078() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2078() -> Option { +fn default_2079() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2079() -> Option { +fn default_2080() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2080() -> Vec { +fn default_2081() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2081() -> MineEntryVisibility { +fn default_2082() -> MineEntryVisibility { serde_json::from_str("\"private\"").expect("schema default") } -fn default_2082() -> String { +fn default_2083() -> String { serde_json::from_str("\"memory\"").expect("schema default") } -fn default_2083() -> String { +fn default_2084() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2084() -> String { +fn default_2085() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2085() -> Option { +fn default_2086() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2086() -> bool { +fn default_2087() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2087() -> bool { +fn default_2088() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2088() -> String { +fn default_2089() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2089() -> NamespaceRegisterOutputVisibility { +fn default_2090() -> NamespaceRegisterOutputVisibility { serde_json::from_str("\"private\"").expect("schema default") } -fn default_2090() -> bool { +fn default_2091() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2091() -> Integer { +fn default_2092() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2092() -> Integer { +fn default_2093() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2093() -> bool { +fn default_2094() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2094() -> Vec> { +fn default_2095() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2095() -> Option { +fn default_2096() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2096() -> Option { +fn default_2097() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2097() -> Vec { +fn default_2098() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2098() -> Integer { +fn default_2099() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2099() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2100() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -66953,23 +67070,23 @@ fn default_2102() -> String { fn default_2103() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2104() -> Option { - serde_json::from_str("null").expect("schema default") -} -fn default_2105() -> String { +fn default_2104() -> String { serde_json::from_str("\"\"").expect("schema default") } +fn default_2105() -> Option { + serde_json::from_str("null").expect("schema default") +} fn default_2106() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_2107() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2108() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_2108() -> String { + serde_json::from_str("\"\"").expect("schema default") } -fn default_2109() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_2109() -> Vec { + serde_json::from_str("[]").expect("schema default") } fn default_2110() -> Option { serde_json::from_str("null").expect("schema default") @@ -66980,33 +67097,33 @@ fn default_2111() -> Option { fn default_2112() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2113() -> String { +fn default_2113() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_2114() -> String { serde_json::from_str("\"{}\"").expect("schema default") } -fn default_2114() -> NamespaceSnapshotOutputSnapshotMemoryRowStatus { +fn default_2115() -> NamespaceSnapshotOutputSnapshotMemoryRowStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2115() -> Option { +fn default_2116() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2116() -> Vec { +fn default_2117() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2117() -> String { +fn default_2118() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2118() -> Integer { +fn default_2119() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2119() -> Integer { +fn default_2120() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2120() -> Option { +fn default_2121() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2121() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2122() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -67016,191 +67133,191 @@ fn default_2123() -> String { fn default_2124() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2125() -> Option { +fn default_2125() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2126() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2126() -> f64 { +fn default_2127() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2127() -> Option { +fn default_2128() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2128() -> Option { +fn default_2129() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2129() -> Integer { +fn default_2130() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2130() -> Option { +fn default_2131() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2131() -> Option { +fn default_2132() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2132() -> String { +fn default_2133() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2133() -> Option { +fn default_2134() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2134() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2135() -> String { serde_json::from_str("\"\"").expect("schema default") } fn default_2136() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2137() -> Option { +fn default_2137() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2138() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2138() -> String { +fn default_2139() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2139() -> Option { +fn default_2140() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2140() -> String { +fn default_2141() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2141() -> String { +fn default_2142() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2142() -> Vec { +fn default_2143() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2143() -> Vec { +fn default_2144() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2144() -> Option { +fn default_2145() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2145() -> Integer { +fn default_2146() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2146() -> String { +fn default_2147() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2147() -> Vec { +fn default_2148() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2148() -> Vec { +fn default_2149() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2149() -> String { +fn default_2150() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2150() -> Option { +fn default_2151() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2151() -> Vec { +fn default_2152() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2152() -> Integer { +fn default_2153() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2153() -> Vec { +fn default_2154() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2154() -> Option { +fn default_2155() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2155() -> Vec { +fn default_2156() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2156() -> Vec { +fn default_2157() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2157() -> Option { +fn default_2158() -> Option { serde_json::from_str("0").expect("schema default") } -fn default_2158() -> TuneProposalEffect { +fn default_2159() -> TuneProposalEffect { serde_json::from_str("\"future\"").expect("schema default") } -fn default_2159() -> TuneApplyVia { +fn default_2160() -> TuneApplyVia { serde_json::from_str("\"op\"").expect("schema default") } -fn default_2160() -> bool { +fn default_2161() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2161() -> Vec { +fn default_2162() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2162() -> Option { +fn default_2163() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2163() -> Option { +fn default_2164() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2164() -> String { +fn default_2165() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2165() -> Vec { +fn default_2166() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2166() -> Vec { +fn default_2167() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2167() -> Option { +fn default_2168() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2168() -> Option { +fn default_2169() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2169() -> Option { +fn default_2170() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2170() -> String { +fn default_2171() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2171() -> Option { +fn default_2172() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2172() -> Option { +fn default_2173() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2173() -> Option { +fn default_2174() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2174() -> Vec { +fn default_2175() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2175() -> bool { +fn default_2176() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2176() -> Option { +fn default_2177() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2177() -> Option { +fn default_2178() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2178() -> Vec { +fn default_2179() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2179() -> String { +fn default_2180() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2180() -> String { +fn default_2181() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2181() -> Vec> { +fn default_2182() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2182() -> std::collections::HashMap { +fn default_2183() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2183() -> Vec { +fn default_2184() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2184() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_2185() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2186() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2186() -> Integer { + serde_json::from_str("0").expect("schema default") } fn default_2187() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -67208,27 +67325,27 @@ fn default_2187() -> String { fn default_2188() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2189() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_2189() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_2190() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2191() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2191() -> Vec { + serde_json::from_str("[]").expect("schema default") } fn default_2192() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2193() -> bool { +fn default_2193() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2194() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2194() -> Integer { +fn default_2195() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2195() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2196() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -67238,104 +67355,104 @@ fn default_2197() -> String { fn default_2198() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2199() -> Vec { +fn default_2199() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2200() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2200() -> String { +fn default_2201() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2201() -> String { +fn default_2202() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2202() -> std::collections::HashMap { +fn default_2203() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2203() -> String { +fn default_2204() -> String { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2204() -> Option { +fn default_2205() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2205() -> Option { +fn default_2206() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2206() -> bool { +fn default_2207() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2207() -> String { +fn default_2208() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2208() -> String { +fn default_2209() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2209() -> Vec { +fn default_2210() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2210() -> Integer { +fn default_2211() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2211() -> String { +fn default_2212() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2212() -> String { +fn default_2213() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2213() -> Option { +fn default_2214() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2214() -> bool { +fn default_2215() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2215() -> String { +fn default_2216() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2216() -> bool { +fn default_2217() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2217() -> String { +fn default_2218() -> String { serde_json::from_str("\"inherit\"").expect("schema default") } -fn default_2218() -> Option { +fn default_2219() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2219() -> Option { +fn default_2220() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2220() -> bool { +fn default_2221() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2221() -> Vec { +fn default_2222() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2222() -> Integer { +fn default_2223() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2223() -> ProcedureEvolveOutputGate { +fn default_2224() -> ProcedureEvolveOutputGate { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2224() -> String { +fn default_2225() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2225() -> f64 { +fn default_2226() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2226() -> std::collections::HashMap { - serde_json::from_str("{}").expect("schema default") -} fn default_2227() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2228() -> std::collections::HashMap { +fn default_2228() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } fn default_2229() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2230() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2230() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") } -fn default_2231() -> Vec { - serde_json::from_str("[]").expect("schema default") +fn default_2231() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_2232() -> Vec { serde_json::from_str("[]").expect("schema default") @@ -67343,138 +67460,138 @@ fn default_2232() -> Vec { fn default_2233() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2234() -> std::collections::HashMap { +fn default_2234() -> Vec { + serde_json::from_str("[]").expect("schema default") +} +fn default_2235() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2235() -> Integer { +fn default_2236() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2236() -> bool { +fn default_2237() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2237() -> std::collections::HashMap { +fn default_2238() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2238() -> Vec { +fn default_2239() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2239() -> std::collections::HashMap { +fn default_2240() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2240() -> String { +fn default_2241() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2241() -> ProcedureLocateOutputStatus { +fn default_2242() -> ProcedureLocateOutputStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2242() -> Option> { +fn default_2243() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2243() -> Vec>> { +fn default_2244() -> Vec>> { serde_json::from_str("[]").expect("schema default") } -fn default_2244() -> Vec { +fn default_2245() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2245() -> Vec { +fn default_2246() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2246() -> std::collections::HashMap { +fn default_2247() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2247() -> bool { +fn default_2248() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2248() -> Vec { +fn default_2249() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2249() -> Vec> { +fn default_2250() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2250() -> String { +fn default_2251() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2251() -> std::collections::HashMap { +fn default_2252() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2252() -> std::collections::HashMap { +fn default_2253() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2253() -> Vec { +fn default_2254() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2254() -> std::collections::HashMap { +fn default_2255() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2255() -> Option> { +fn default_2256() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2256() -> bool { +fn default_2257() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2257() -> std::collections::HashMap { +fn default_2258() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2258() -> ProcedureMatchStatus { +fn default_2259() -> ProcedureMatchStatus { serde_json::from_str("\"authored\"").expect("schema default") } -fn default_2259() -> Option> { +fn default_2260() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2260() -> Vec { +fn default_2261() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2261() -> Integer { +fn default_2262() -> Integer { serde_json::from_str("1").expect("schema default") } -fn default_2262() -> Vec> { +fn default_2263() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2263() -> f64 { - serde_json::from_str("0.0").expect("schema default") -} fn default_2264() -> f64 { serde_json::from_str("0.0").expect("schema default") } fn default_2265() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2266() -> Option { +fn default_2266() -> f64 { + serde_json::from_str("0.0").expect("schema default") +} +fn default_2267() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2267() -> std::collections::HashMap { +fn default_2268() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2268() -> std::collections::HashMap> { +fn default_2269() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2269() -> String { +fn default_2270() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2270() -> Integer { +fn default_2271() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2271() -> String { +fn default_2272() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2272() -> f64 { +fn default_2273() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2273() -> Vec { +fn default_2274() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2274() -> ProcedureReviseOutputOutcome { +fn default_2275() -> ProcedureReviseOutputOutcome { serde_json::from_str("\"opened\"").expect("schema default") } -fn default_2275() -> Vec { +fn default_2276() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2276() -> Vec { +fn default_2277() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2277() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2278() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -67484,101 +67601,101 @@ fn default_2279() -> String { fn default_2280() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2281() -> Option { +fn default_2281() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2282() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2282() -> Integer { +fn default_2283() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2283() -> Vec { +fn default_2284() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2284() -> std::collections::HashMap { +fn default_2285() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2285() -> Option { +fn default_2286() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2286() -> String { +fn default_2287() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2287() -> Integer { +fn default_2288() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2288() -> String { +fn default_2289() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2289() -> String { +fn default_2290() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2290() -> std::collections::HashMap { +fn default_2291() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2291() -> String { +fn default_2292() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2292() -> String { +fn default_2293() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2293() -> Option { +fn default_2294() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2294() -> RunBeginOutputStatus { +fn default_2295() -> RunBeginOutputStatus { serde_json::from_str("\"active\"").expect("schema default") } -fn default_2295() -> String { +fn default_2296() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2296() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_2297() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_2298() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2299() -> Vec { +fn default_2299() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_2300() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2300() -> Integer { +fn default_2301() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2301() -> Integer { +fn default_2302() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2302() -> Integer { +fn default_2303() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2303() -> String { +fn default_2304() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2304() -> String { +fn default_2305() -> String { serde_json::from_str("\"keep\"").expect("schema default") } -fn default_2305() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_2306() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_2307() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2308() -> Option { +fn default_2308() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_2309() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2309() -> Integer { +fn default_2310() -> Integer { serde_json::from_str("-1").expect("schema default") } -fn default_2310() -> Vec { - serde_json::from_str("[]").expect("schema default") -} fn default_2311() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2312() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_2312() -> Vec { + serde_json::from_str("[]").expect("schema default") } fn default_2313() -> Integer { serde_json::from_str("0").expect("schema default") @@ -67586,57 +67703,57 @@ fn default_2313() -> Integer { fn default_2314() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2315() -> f64 { +fn default_2315() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_2316() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2316() -> Integer { +fn default_2317() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2317() -> Vec { +fn default_2318() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2318() -> Integer { +fn default_2319() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2319() -> Vec { +fn default_2320() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2320() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_2321() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_2322() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2323() -> Vec { +fn default_2323() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_2324() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2324() -> Option { +fn default_2325() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2325() -> Option> { +fn default_2326() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2326() -> LiveSearchResultsLive { +fn default_2327() -> LiveSearchResultsLive { serde_json::from_str("true").expect("schema default") } -fn default_2327() -> String { +fn default_2328() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2328() -> LiveSearchHitLive { +fn default_2329() -> LiveSearchHitLive { serde_json::from_str("true").expect("schema default") } -fn default_2329() -> Vec { +fn default_2330() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2330() -> Option { +fn default_2331() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2331() -> std::collections::HashMap { - serde_json::from_str("{}").expect("schema default") -} fn default_2332() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } @@ -67646,24 +67763,24 @@ fn default_2333() -> std::collections::HashMap { fn default_2334() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2335() -> Option> { +fn default_2335() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") +} +fn default_2336() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2336() -> Vec { +fn default_2337() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2337() -> Integer { +fn default_2338() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2338() -> String { +fn default_2339() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2339() -> Integer { +fn default_2340() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2340() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2341() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -67685,60 +67802,60 @@ fn default_2346() -> String { fn default_2347() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2348() -> Vec { +fn default_2348() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2349() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2349() -> String { +fn default_2350() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2350() -> String { +fn default_2351() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2351() -> Vec { +fn default_2352() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2352() -> String { +fn default_2353() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2353() -> String { +fn default_2354() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2354() -> Vec { +fn default_2355() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2355() -> Vec { +fn default_2356() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2356() -> Vec { +fn default_2357() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2357() -> String { +fn default_2358() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2358() -> String { +fn default_2359() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2359() -> Vec { +fn default_2360() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2360() -> Vec { +fn default_2361() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2361() -> Vec { +fn default_2362() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2362() -> String { +fn default_2363() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2363() -> String { +fn default_2364() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2364() -> Option { +fn default_2365() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2365() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2366() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -67754,15 +67871,15 @@ fn default_2369() -> String { fn default_2370() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2371() -> Vec { +fn default_2371() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2372() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2372() -> Option { +fn default_2373() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2373() -> Integer { - serde_json::from_str("0").expect("schema default") -} fn default_2374() -> Integer { serde_json::from_str("0").expect("schema default") } @@ -67775,11 +67892,11 @@ fn default_2376() -> Integer { fn default_2377() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2378() -> bool { - serde_json::from_str("false").expect("schema default") +fn default_2378() -> Integer { + serde_json::from_str("0").expect("schema default") } -fn default_2379() -> String { - serde_json::from_str("\"\"").expect("schema default") +fn default_2379() -> bool { + serde_json::from_str("false").expect("schema default") } fn default_2380() -> String { serde_json::from_str("\"\"").expect("schema default") @@ -67799,21 +67916,21 @@ fn default_2384() -> String { fn default_2385() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2386() -> Option { +fn default_2386() -> String { + serde_json::from_str("\"\"").expect("schema default") +} +fn default_2387() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2387() -> Integer { +fn default_2388() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2388() -> Integer { +fn default_2389() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2389() -> Vec { +fn default_2390() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2390() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2391() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -67823,8 +67940,8 @@ fn default_2392() -> String { fn default_2393() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2394() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_2394() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_2395() -> Integer { serde_json::from_str("0").expect("schema default") @@ -67838,32 +67955,32 @@ fn default_2397() -> Integer { fn default_2398() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2399() -> f64 { - serde_json::from_str("0.0").expect("schema default") -} -fn default_2400() -> Integer { +fn default_2399() -> Integer { serde_json::from_str("0").expect("schema default") } +fn default_2400() -> f64 { + serde_json::from_str("0.0").expect("schema default") +} fn default_2401() -> Integer { serde_json::from_str("0").expect("schema default") } fn default_2402() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2403() -> String { +fn default_2403() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_2404() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2404() -> SessionBriefStats { +fn default_2405() -> SessionBriefStats { serde_json::from_str("{\"events_in\":0,\"windows\":0,\"events_total\":0,\"source_chars\":0,\"brief_chars\":0,\"compression_ratio\":0.0,\"dropped_ungrounded\":0,\"tokens_in\":0,\"tokens_out\":0,\"llm_model\":\"\"}").expect("schema default") } -fn default_2405() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2406() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2407() -> Option { - serde_json::from_str("null").expect("schema default") +fn default_2407() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_2408() -> Option { serde_json::from_str("null").expect("schema default") @@ -67871,57 +67988,57 @@ fn default_2408() -> Option { fn default_2409() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2410() -> Integer { +fn default_2410() -> Option { + serde_json::from_str("null").expect("schema default") +} +fn default_2411() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2411() -> std::collections::HashMap { +fn default_2412() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2412() -> String { +fn default_2413() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2413() -> String { +fn default_2414() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2414() -> Option { +fn default_2415() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2415() -> String { +fn default_2416() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2416() -> Integer { +fn default_2417() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2417() -> Integer { +fn default_2418() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2418() -> Option { +fn default_2419() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2419() -> std::collections::HashMap { +fn default_2420() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2420() -> String { +fn default_2421() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2421() -> Integer { +fn default_2422() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2422() -> String { +fn default_2423() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2423() -> Option { +fn default_2424() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2424() -> String { +fn default_2425() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2425() -> Option { +fn default_2426() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2426() -> String { - serde_json::from_str("\"\"").expect("schema default") -} fn default_2427() -> String { serde_json::from_str("\"\"").expect("schema default") } @@ -67931,327 +68048,327 @@ fn default_2428() -> String { fn default_2429() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2430() -> Integer { - serde_json::from_str("0").expect("schema default") +fn default_2430() -> String { + serde_json::from_str("\"\"").expect("schema default") } fn default_2431() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2432() -> String { +fn default_2432() -> Integer { + serde_json::from_str("0").expect("schema default") +} +fn default_2433() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2433() -> std::collections::HashMap { +fn default_2434() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2434() -> String { +fn default_2435() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2435() -> String { +fn default_2436() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2436() -> bool { +fn default_2437() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2437() -> String { +fn default_2438() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2438() -> std::collections::HashMap { +fn default_2439() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2439() -> Vec> { +fn default_2440() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2440() -> Vec { +fn default_2441() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2441() -> Vec { +fn default_2442() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2442() -> bool { +fn default_2443() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2443() -> String { +fn default_2444() -> String { serde_json::from_str("\"unknown\"").expect("schema default") } -fn default_2444() -> String { +fn default_2445() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2445() -> Vec { +fn default_2446() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2446() -> bool { +fn default_2447() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2447() -> String { +fn default_2448() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2448() -> bool { +fn default_2449() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2449() -> Vec { +fn default_2450() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2450() -> std::collections::HashMap { +fn default_2451() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2451() -> Vec> { +fn default_2452() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2452() -> bool { +fn default_2453() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2453() -> bool { +fn default_2454() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2454() -> Vec> { +fn default_2455() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2455() -> std::collections::HashMap { +fn default_2456() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2456() -> String { +fn default_2457() -> String { serde_json::from_str("\"none\"").expect("schema default") } -fn default_2457() -> Vec> { +fn default_2458() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2458() -> bool { +fn default_2459() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2459() -> String { +fn default_2460() -> String { serde_json::from_str("\"calibrated\"").expect("schema default") } -fn default_2460() -> std::collections::HashMap { +fn default_2461() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2461() -> std::collections::HashMap { +fn default_2462() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2462() -> String { +fn default_2463() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2463() -> std::collections::HashMap { +fn default_2464() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2464() -> std::collections::HashMap { +fn default_2465() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2465() -> std::collections::HashMap { +fn default_2466() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2466() -> String { +fn default_2467() -> String { serde_json::from_str("\"ok\"").expect("schema default") } -fn default_2467() -> String { +fn default_2468() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2468() -> String { +fn default_2469() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2469() -> bool { +fn default_2470() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2470() -> Integer { +fn default_2471() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2471() -> String { +fn default_2472() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2472() -> String { +fn default_2473() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2473() -> Vec { +fn default_2474() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2474() -> bool { +fn default_2475() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2475() -> Vec { +fn default_2476() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2476() -> std::collections::HashMap> { +fn default_2477() -> std::collections::HashMap> { serde_json::from_str("{}").expect("schema default") } -fn default_2477() -> Vec> { +fn default_2478() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2478() -> Vec> { +fn default_2479() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2479() -> String { +fn default_2480() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2480() -> Vec> { +fn default_2481() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2481() -> std::collections::HashMap { +fn default_2482() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2482() -> String { +fn default_2483() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2483() -> Vec> { +fn default_2484() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2484() -> bool { +fn default_2485() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2485() -> Integer { +fn default_2486() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2486() -> Vec> { +fn default_2487() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2487() -> String { +fn default_2488() -> String { serde_json::from_str("\"no_flaky_signal\"").expect("schema default") } -fn default_2488() -> bool { +fn default_2489() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2489() -> Option> { +fn default_2490() -> Option> { serde_json::from_str("null").expect("schema default") } -fn default_2490() -> Vec { +fn default_2491() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2491() -> bool { +fn default_2492() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2492() -> std::collections::HashMap { +fn default_2493() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2493() -> String { +fn default_2494() -> String { serde_json::from_str("\"not_computed\"").expect("schema default") } -fn default_2494() -> Vec> { +fn default_2495() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2495() -> String { +fn default_2496() -> String { serde_json::from_str("\"candidate\"").expect("schema default") } -fn default_2496() -> std::collections::HashMap { +fn default_2497() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2497() -> String { +fn default_2498() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2498() -> bool { +fn default_2499() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2499() -> Integer { +fn default_2500() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2500() -> std::collections::HashMap { +fn default_2501() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2501() -> bool { +fn default_2502() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2502() -> Vec> { +fn default_2503() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2503() -> std::collections::HashMap { +fn default_2504() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2504() -> std::collections::HashMap { +fn default_2505() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2505() -> String { +fn default_2506() -> String { serde_json::from_str("\"lower_bound\"").expect("schema default") } -fn default_2506() -> bool { +fn default_2507() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2507() -> Vec { +fn default_2508() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2508() -> Vec> { +fn default_2509() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2509() -> std::collections::HashMap { +fn default_2510() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2510() -> Vec { +fn default_2511() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2511() -> String { +fn default_2512() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2512() -> bool { +fn default_2513() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2513() -> bool { +fn default_2514() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2514() -> std::collections::HashMap { +fn default_2515() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2515() -> String { +fn default_2516() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2516() -> bool { +fn default_2517() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2517() -> std::collections::HashMap { +fn default_2518() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2518() -> std::collections::HashMap { +fn default_2519() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2519() -> Vec> { +fn default_2520() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2520() -> Vec { +fn default_2521() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2521() -> std::collections::HashMap { +fn default_2522() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2522() -> Vec> { +fn default_2523() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2523() -> bool { +fn default_2524() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2524() -> bool { +fn default_2525() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2525() -> Vec { +fn default_2526() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2526() -> std::collections::HashMap { +fn default_2527() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2527() -> String { +fn default_2528() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2528() -> std::collections::HashMap { +fn default_2529() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2529() -> bool { +fn default_2530() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2530() -> bool { +fn default_2531() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2531() -> String { +fn default_2532() -> String { serde_json::from_str("\"no_signal\"").expect("schema default") } -fn default_2532() -> Vec { +fn default_2533() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2533() -> f64 { +fn default_2534() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2534() -> Integer { +fn default_2535() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2535() -> String { +fn default_2536() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2536() -> std::collections::HashMap { - serde_json::from_str("{}").expect("schema default") -} fn default_2537() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } @@ -68261,18 +68378,18 @@ fn default_2538() -> std::collections::HashMap { fn default_2539() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2540() -> String { +fn default_2540() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") +} +fn default_2541() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2541() -> std::collections::HashMap { +fn default_2542() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2542() -> bool { +fn default_2543() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2543() -> std::collections::HashMap { - serde_json::from_str("{}").expect("schema default") -} fn default_2544() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } @@ -68282,54 +68399,57 @@ fn default_2545() -> std::collections::HashMap { fn default_2546() -> std::collections::HashMap { serde_json::from_str("{}").expect("schema default") } -fn default_2547() -> String { +fn default_2547() -> std::collections::HashMap { + serde_json::from_str("{}").expect("schema default") +} +fn default_2548() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2548() -> Vec> { +fn default_2549() -> Vec> { serde_json::from_str("[]").expect("schema default") } -fn default_2549() -> Integer { +fn default_2550() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2550() -> String { +fn default_2551() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2551() -> bool { +fn default_2552() -> bool { serde_json::from_str("true").expect("schema default") } -fn default_2552() -> String { +fn default_2553() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2553() -> Vec { +fn default_2554() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2554() -> bool { +fn default_2555() -> bool { serde_json::from_str("false").expect("schema default") } -fn default_2555() -> Vec { +fn default_2556() -> Vec { serde_json::from_str("[]").expect("schema default") } -fn default_2556() -> f64 { +fn default_2557() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2557() -> String { +fn default_2558() -> String { serde_json::from_str("\"\"").expect("schema default") } -fn default_2558() -> Integer { +fn default_2559() -> Integer { serde_json::from_str("4096").expect("schema default") } -fn default_2559() -> Integer { +fn default_2560() -> Integer { serde_json::from_str("0").expect("schema default") } -fn default_2560() -> Option { +fn default_2561() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2561() -> f64 { +fn default_2562() -> f64 { serde_json::from_str("0.0").expect("schema default") } -fn default_2562() -> Option { +fn default_2563() -> Option { serde_json::from_str("null").expect("schema default") } -fn default_2563() -> Vec { +fn default_2564() -> Vec { serde_json::from_str("[]").expect("schema default") } diff --git a/sdk/rust/tests/registry_contracts.rs b/sdk/rust/tests/registry_contracts.rs index a973cf94d9a..0ea0b0ca643 100644 --- a/sdk/rust/tests/registry_contracts.rs +++ b/sdk/rust/tests/registry_contracts.rs @@ -4347,6 +4347,21 @@ fn knowledge_source_sync_now() { ); } #[test] +fn knowledge_source_live() { + let value: clickhouse_loom::KnowledgeSourceLiveInput = serde_json::from_str("{\"org\":\"sample\",\"namespace\":\"sample\",\"name\":\"sample\",\"resource_id\":\"sample\"}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + let value: clickhouse_loom::KnowledgeSourceLiveOutput = + serde_json::from_str("{\"status\":\"ok\"}").unwrap(); + let encoded = serde_json::to_value(value).unwrap(); + assert!(encoded.is_object()); + assert_eq!( + encoded["document"], + serde_json::from_str::("null").unwrap(), + "knowledge.source.live:document" + ); +} +#[test] fn connection_list() { let value: clickhouse_loom::ConnectionListInput = serde_json::from_str("{\"org\":\"sample\"}").unwrap(); diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index c99a865a9e7..5e9e71a433d 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4619,6 +4619,43 @@ export interface KnowledgeSourceListOutput { self_service?: boolean; } +export interface KnowledgeSourceLiveInput { + /** Organization that owns the collection. */ + org: string; + /** Collection that owns the source. */ + namespace: string; + /** Name of the registered source in the collection. */ + name: string; + /** Exact selected resource identifier returned by source setup. */ + resource_id: string; +} + +export interface KnowledgeSourceLiveDocument { + /** Registered source that served the read. */ + source_id: string; + /** The selected resource identifier. */ + resource_id: string; + /** Stable source URI to cite; never fetched. */ + uri: string; + /** Upstream display link, when the worker supplied one. */ + source_link: string | null; + /** Unix seconds when the worker read the document. */ + fetched_at: number; + /** Document title. */ + title: string; + /** Current document text, up to 4,000,000 bytes. */ + text: string; + /** Media type of the text. */ + mime_type: string; +} + +export interface KnowledgeSourceLiveOutput { + /** One of ok, denied, reconnect, overloaded, timeout, unavailable or unsupported; only ok carries a document, and only overloaded and timeout are worth retrying. */ + status: "ok" | "denied" | "reconnect" | "overloaded" | "timeout" | "unavailable" | "unsupported"; + /** The document when `status` is `ok`. */ + document?: KnowledgeSourceLiveDocument | null; +} + export interface KnowledgeSourceParseLinksInput { /** The org. */ org: string; @@ -10882,6 +10919,7 @@ export type OpName = | "knowledge.source.check" | "knowledge.source.inspect" | "knowledge.source.list" + | "knowledge.source.live" | "knowledge.source.parse_links" | "knowledge.source.push_configure" | "knowledge.source.push_confirm" @@ -11264,6 +11302,7 @@ export interface OpMap { "knowledge.source.check": { input: KnowledgeSourceCheckInput; output: KnowledgeSourceCheckOutput }; "knowledge.source.inspect": { input: KnowledgeSourceInspectInput; output: KnowledgeSourceInspectOutput }; "knowledge.source.list": { input: KnowledgeSourceListInput; output: KnowledgeSourceListOutput }; + "knowledge.source.live": { input: KnowledgeSourceLiveInput; output: KnowledgeSourceLiveOutput }; "knowledge.source.parse_links": { input: KnowledgeSourceParseLinksInput; output: KnowledgeSourceParseLinksOutput }; "knowledge.source.push_configure": { input: KnowledgeSourcePushConfigureInput; output: PushStatusOutput }; "knowledge.source.push_confirm": { input: KnowledgeSourcePushConfirmInput; output: PushStatusOutput }; @@ -11646,6 +11685,7 @@ export const OPS: readonly OpSpec[] = [ { name: "knowledge.source.check", group: "knowledge", method: "sourceCheck", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 30000, audit: false, readOnly: false }, { name: "knowledge.source.inspect", group: "knowledge", method: "sourceInspect", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 400, audit: false, readOnly: true }, { name: "knowledge.source.list", group: "knowledge", method: "sourceList", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 300, audit: false, readOnly: true }, + { name: "knowledge.source.live", group: "knowledge", method: "sourceLive", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 8000, audit: false, readOnly: true }, { name: "knowledge.source.parse_links", group: "knowledge", method: "sourceParseLinks", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 50, audit: false, readOnly: true }, { name: "knowledge.source.push_configure", group: "knowledge", method: "sourcePushConfigure", idempotent: false, role: "admin", maturity: "experimental", budgetP99Ms: 60000, audit: true, readOnly: false }, { name: "knowledge.source.push_confirm", group: "knowledge", method: "sourcePushConfirm", idempotent: false, role: "admin", maturity: "experimental", budgetP99Ms: 1000, audit: true, readOnly: false }, @@ -11871,4 +11911,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 379; +export const GENERATED_OP_COUNT = 380; diff --git a/server/core/operation_privacy.py b/server/core/operation_privacy.py new file mode 100644 index 00000000000..741f1299751 --- /dev/null +++ b/server/core/operation_privacy.py @@ -0,0 +1,7 @@ +"""Payloads kept out of diagnostics even when the caller opts into capture.""" + +KNOWLEDGE_SOURCE_LIVE = "knowledge.source.live" + + +def retains_no_payload(operation: str) -> bool: + return operation == KNOWLEDGE_SOURCE_LIVE diff --git a/server/core/pg.py b/server/core/pg.py index 725200e6f4b..214fba86cc1 100644 --- a/server/core/pg.py +++ b/server/core/pg.py @@ -986,6 +986,11 @@ async def fence_lock(conn: Any, org: str) -> None: # documents alone, so no commit lands between the erasure's read and its delete. KNOWLEDGE_LOCK_KEY = "hashtextextended('loom.knowledge/' || $1::text || '/' || $2::text, 0)" +# The advisory lock of a namespace's source registry (`$1` the org, `$2` the namespace): +# a source write holds it for the length of `sources_lease`, and a live source frame +# holds it shared, so no source change commits while a frame is handed off. +SOURCES_LOCK_KEY = "hashtextextended('loom.sources/' || $1::text || '/' || $2::text, 0)" + # The advisory lock of a policy scope (`k.org`, `k.scope`), one key per scope. POLICY_LOCK_KEY = "hashtextextended('loom.policy/' || k.org || '/' || k.scope, 0)" diff --git a/server/core/ratelimit.py b/server/core/ratelimit.py index 8951361253d..2761771fe22 100644 --- a/server/core/ratelimit.py +++ b/server/core/ratelimit.py @@ -95,6 +95,7 @@ "knowledge.outline", "knowledge.reads", "knowledge.source.inspect", + "knowledge.source.live", "knowledge.source.list", "knowledge.source.parse_links", } diff --git a/server/core/request_tail.py b/server/core/request_tail.py index 207b6042de3..3223979abcc 100644 --- a/server/core/request_tail.py +++ b/server/core/request_tail.py @@ -7,6 +7,7 @@ from collections.abc import AsyncIterator, Awaitable, Callable, Iterator from contextlib import asynccontextmanager, contextmanager from contextvars import Context, ContextVar, copy_context +from functools import partial from typing import Any import anyio @@ -16,6 +17,8 @@ log = logging.getLogger("loom.request_tail") # not a setting: one required publication attempt has a fixed cleanup safety ceiling. REQUIRED_STEP_TIMEOUT_S = 60.0 +# not a setting: each chunk is one lock hold, sized to amortize the authority check. +_FENCED_BODY_CHUNK_BYTES = 512 * 1024 class RequiredTailError(RuntimeError): @@ -23,7 +26,10 @@ def __init__(self) -> None: super().__init__("Required request work was not confirmed") -_Publication = tuple[object, Context, Callable[[], Awaitable[Any]], Callable[[], bool]] +PublicationFence = Callable[[Callable[[], Awaitable[None]]], Awaitable[None]] +_Publication = tuple[ + object, Context, Callable[[], Awaitable[Any]], Callable[[], bool], PublicationFence | None +] _publication_group: ContextVar[dict[int, _Publication] | None] = ContextVar( "loom_publication_group", default=None ) @@ -140,7 +146,11 @@ def publication_group() -> Iterator[_PublicationGroup]: def retain_publication( - owner: object, check: Callable[[], Awaitable[Any]], fresh: Callable[[], bool] + owner: object, + check: Callable[[], Awaitable[Any]], + fresh: Callable[[], bool], + *, + fence: PublicationFence | None = None, ) -> bool: """Retain strict final-response evidence in its original authorization context.""" tail = _tail.get() @@ -151,7 +161,7 @@ def retain_publication( target = _publication_group.get() if target is None: target = tail.publications - target[id(owner)] = (owner, copy_context(), check, fresh) + target[id(owner)] = (owner, copy_context(), check, fresh, fence) return True @@ -196,14 +206,12 @@ async def renew() -> None: async def _publication_barrier(tail: _Tail) -> None: """Renew retained inputs after accounting and after each awaited send boundary.""" - if not tail.publications: - return checks = tuple(tail.publications.values()) try: - for _owner, context, check, _fresh in checks: + for _owner, context, check, _fresh, _fence in checks: await _publication_check(context, check) # A later renewal can outlive an earlier proof's deadline. - if not all(context.run(fresh) for _owner, context, _check, fresh in checks): + if not all(context.run(fresh) for _owner, context, _check, fresh, _fence in checks): raise RequiredTailError() except Exception: # noqa: BLE001 — publication failures expose only a constant refusal tail.required_failed = True @@ -213,6 +221,64 @@ async def _publication_barrier(tail: _Tail) -> None: raise +async def _publish(tail: _Tail, deliver: Callable[[], Awaitable[None]]) -> None: + await _publication_barrier(tail) + checks = tuple(tail.publications.values()) + if not any(fence is not None for _owner, _context, _check, _fresh, fence in checks): + await deliver() + return + + async def checked_delivery() -> None: + if not all(context.run(fresh) for _owner, context, _check, fresh, _fence in checks): + raise RequiredTailError() + await deliver() + + guarded: Callable[[], Awaitable[None]] = checked_delivery + for _owner, context, _check, _fresh, fence in reversed(checks): + if fence is not None: + guarded = _guarded_delivery(context, fence, guarded) + try: + await guarded() + except BaseException: + tail.required_failed = True + raise + + +async def _publish_body( + tail: _Tail, + message: dict[str, Any], + send: Callable[[dict[str, Any]], Awaitable[None]], +) -> None: + body = message["body"] + size = len(body) + if size <= _FENCED_BODY_CHUNK_BYTES or not any( + fence is not None for _owner, _context, _check, _fresh, fence in tail.publications.values() + ): + await _publish(tail, partial(send, message)) + return + + # Bound the bytes handed off by each lock acquisition. Renew access between chunks. + for offset in range(0, size, _FENCED_BODY_CHUNK_BYTES): + end = offset + _FENCED_BODY_CHUNK_BYTES + chunk = { + **message, + "body": body[offset:end], + "more_body": end < size or message.get("more_body", False), + } + await _publish(tail, partial(send, chunk)) + + +def _guarded_delivery( + context: Context, + fence: PublicationFence, + deliver: Callable[[], Awaitable[None]], +) -> Callable[[], Awaitable[None]]: + async def publication() -> None: + await _publication_check(context, lambda: fence(deliver)) + + return publication + + async def _required_step(tail: _Tail, tag: str, step: Callable[[], Awaitable[Any]]) -> None: succeeded = False try: @@ -410,12 +476,13 @@ async def __call__(self, scope: dict[str, Any], receive: Any, send: Any) -> None async def _send(message: dict[str, Any]) -> None: if message.get("type") == "http.response.start": await settle(tail) - await _publication_barrier(tail) + await _publish(tail, lambda: send(message)) elif message.get("type") == "http.response.body" and message.get("body"): # Empty completion frames publish no bytes; the client may already # have consumed Content-Length and started its next request. - await _publication_barrier(tail) - await send(message) + await _publish_body(tail, message, send) + else: + await send(message) try: await self.app(scope, receive, _send) diff --git a/server/erasure/store/steps_pg.py b/server/erasure/store/steps_pg.py index 410065db0e4..e9b003ed533 100644 --- a/server/erasure/store/steps_pg.py +++ b/server/erasure/store/steps_pg.py @@ -384,8 +384,31 @@ async def _erase_knowledge_once( org, arg, ) + worker_metadata = await _delete_worker_metadata(conn, where, org, arg) await _mark_step(conn, org) - return len(heads) + len(leases) + int(jobs) + int(catalog), [*left, *earlier] + count = len(heads) + len(leases) + int(jobs) + int(catalog) + worker_metadata + return count, [*left, *earlier] + + +_PG_WORKER_METADATA = ( + "loom.mcp_worker_enrollment_challenges", + "loom.mcp_worker_accounts", + "loom.mcp_worker_approvals", + "loom.mcp_worker_source_readers", +) + + +async def _delete_worker_metadata(conn: Any, where: str, org: str, arg: Any) -> int: + removed = 0 + for table in _PG_WORKER_METADATA: + count = await conn.fetchval( + f"WITH gone AS (DELETE FROM {table} WHERE {where} RETURNING 1)" + " SELECT count(*) FROM gone", + org, + arg, + ) + removed += int(count) + return removed async def documents_in_clickhouse( @@ -493,6 +516,14 @@ async def _lock_user_knowledge(conn: Any, org: str, user_id: str) -> None: "UNION SELECT namespace FROM loom.knowledge_deliveries " "WHERE org = $1 AND user_id = $2 " "UNION SELECT namespace FROM loom.knowledge_datasets " + "WHERE org = $1 AND user_id = $2 " + "UNION SELECT namespace FROM loom.mcp_worker_enrollment_challenges " + "WHERE org = $1 AND user_id = $2 " + "UNION SELECT namespace FROM loom.mcp_worker_accounts " + "WHERE org = $1 AND user_id = $2 " + "UNION SELECT namespace FROM loom.mcp_worker_approvals " + "WHERE org = $1 AND user_id = $2 " + "UNION SELECT namespace FROM loom.mcp_worker_source_readers " "WHERE org = $1 AND user_id = $2", org, user_id, @@ -566,6 +597,10 @@ async def delete_pg_idempotency(org: str) -> int: "pg:loom.knowledge_heads": "pg_knowledge.delete", "pg:loom.knowledge_deliveries": "pg_knowledge.delete", "pg:loom.knowledge_jobs": "pg_knowledge.delete", + "pg:loom.mcp_worker_enrollment_challenges": "pg_knowledge.delete", + "pg:loom.mcp_worker_accounts": "pg_knowledge.delete", + "pg:loom.mcp_worker_approvals": "pg_knowledge.delete", + "pg:loom.mcp_worker_source_readers": "pg_knowledge.delete", "pg:loom.knowledge_datasets": "pg_knowledge.delete", } # The Postgres tables that hold none, with the reason. @@ -620,6 +655,7 @@ async def delete_pg_idempotency(org: str) -> int: "loom.knowledge_heads", "loom.knowledge_deliveries", "loom.knowledge_jobs", + *_PG_WORKER_METADATA, "loom.knowledge_datasets", ) diff --git a/server/identity/domain/read_scope.py b/server/identity/domain/read_scope.py index 36db3b4d644..15569b49426 100644 --- a/server/identity/domain/read_scope.py +++ b/server/identity/domain/read_scope.py @@ -23,6 +23,7 @@ from server.core.errors import AuthInsufficientError, IdentityIncompleteError from server.core.naming import named +from server.core.operation_privacy import KNOWLEDGE_SOURCE_LIVE # Higher = narrower. The effective scope is the narrowest of the request and # the token's ceiling. The keys are the token claim's values @@ -512,7 +513,7 @@ def with_read_identity[M: BaseModel](input: M, scope: ReadFilters) -> M: def honours_read_scope(op_name: str) -> bool: """Whether `op_name` may be served to a token bounded below the namespace.""" - if op_name.startswith(NARROW_REFUSED_PREFIXES): + if op_name == KNOWLEDGE_SOURCE_LIVE or op_name.startswith(NARROW_REFUSED_PREFIXES): return False if op_name in SCOPED_OPS or op_name in NARROW_SAFE_OPS: return True diff --git a/server/knowledge/api/models_source_live.py b/server/knowledge/api/models_source_live.py new file mode 100644 index 00000000000..6d8894a4e7f --- /dev/null +++ b/server/knowledge/api/models_source_live.py @@ -0,0 +1,58 @@ +"""Read a selected resource now through its approved worker.""" + +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, StringConstraints + +_ScopeName = Annotated[str, StringConstraints(min_length=1, max_length=255)] +_ResourceId = Annotated[str, StringConstraints(min_length=1, max_length=2048)] + + +class KnowledgeSourceLiveInput(BaseModel): + """Read one selected resource through the caller's current worker connection.""" + + model_config = ConfigDict(hide_input_in_errors=True) + + org: _ScopeName = Field(description="Organization that owns the collection.") + namespace: _ScopeName = Field(description="Collection that owns the source.") + name: _ScopeName = Field(description="Name of the registered source in the collection.") + resource_id: _ResourceId = Field( + repr=False, description="Exact selected resource identifier returned by source setup." + ) + + +class KnowledgeSourceLiveDocument(BaseModel): + """The current selected document. It is not written to the index.""" + + model_config = ConfigDict(frozen=True) + + source_id: UUID = Field(description="Registered source that served the read.") + resource_id: str = Field(repr=False, description="The selected resource identifier.") + uri: str = Field(repr=False, description="Stable source URI to cite; never fetched.") + source_link: str | None = Field( + repr=False, description="Upstream display link, when the worker supplied one." + ) + fetched_at: int = Field(description="Unix seconds when the worker read the document.") + title: str = Field(repr=False, description="Document title.") + text: str = Field(repr=False, description="Current document text, up to 4,000,000 bytes.") + mime_type: str = Field(description="Media type of the text.") + + +class KnowledgeSourceLiveOutput(BaseModel): + status: Literal[ + "ok", "denied", "reconnect", "overloaded", "timeout", "unavailable", "unsupported" + ] = Field( + description=( + "One of ok, denied, reconnect, overloaded, timeout, unavailable or unsupported;" + " only ok carries a document, and only overloaded and timeout are worth retrying.\n" + "denied: no current access to this selected resource. reconnect: the" + " caller's upstream connection must be re-authorized. overloaded: live read" + " capacity is full. timeout: the read or publication deadline passed." + " unavailable: the worker or source cannot be reached. unsupported: the" + " document exceeds the live size limits or the source cannot serve it." + ) + ) + document: KnowledgeSourceLiveDocument | None = Field( + default=None, repr=False, description="The document when `status` is `ok`." + ) diff --git a/server/knowledge/api/ops_worker_source.py b/server/knowledge/api/ops_worker_source.py new file mode 100644 index 00000000000..96a326cf242 --- /dev/null +++ b/server/knowledge/api/ops_worker_source.py @@ -0,0 +1,22 @@ +"""Operations on selected resources at an approved document source worker.""" + +from server.core.operation_privacy import KNOWLEDGE_SOURCE_LIVE +from server.knowledge.api.models_source_live import ( + KnowledgeSourceLiveInput, + KnowledgeSourceLiveOutput, +) +from server.knowledge.app.mcp_worker_live_op import handle_knowledge_source_live +from server.operations.base import Operation, Role + +knowledge_source_live = Operation( + name=KNOWLEDGE_SOURCE_LIVE, + input_model=KnowledgeSourceLiveInput, + output_model=KnowledgeSourceLiveOutput, + handler=handle_knowledge_source_live, + idempotent=True, + required_role=Role.VIEWER, + audit=False, + maturity="experimental", +) + +OPERATIONS = [knowledge_source_live] diff --git a/server/knowledge/app/mcp_worker_approval.py b/server/knowledge/app/mcp_worker_approval.py new file mode 100644 index 00000000000..46c07574510 --- /dev/null +++ b/server/knowledge/app/mcp_worker_approval.py @@ -0,0 +1,123 @@ +"""Apply an administrator's approval within the deployment's worker provision.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from server.auth import authz +from server.auth.answer_tokens import is_answer_token +from server.auth.context import current_auth +from server.auth.session_protection import protected_for +from server.core.diagnostics import private_work +from server.knowledge.app import connected_accounts, session_admission +from server.knowledge.store import pg_mcp_worker_approvals as approvals +from server.knowledge.store.pg_mcp_worker_enrollment import WriteOrigin +from server.memory.app.provenance import writer_actor +from server.memory.domain.provenance import source_class_for +from server.operations.base import Role +from server.settings import settings + +if TYPE_CHECKING: + from asyncpg import Connection + + from server.auth.jwt import AuthInfo + + +class WorkerApprovalRefused(ValueError): + def __init__(self) -> None: + super().__init__("source worker approval unavailable") + + +@dataclass(frozen=True, repr=False) +class WorkerProvision: + key: approvals.ApprovalKey + modes: int + exact_team_checks: bool + + +@dataclass(frozen=True, repr=False) +class ApprovalChange: + key: approvals.ApprovalKey + expected_generation: int + modes: int + team_access: bool + + +# The provision is deployment-owned. Its lookup and the erasure fence must +# participate in the same authority transaction as an approval mutation. +type GetProvision = Callable[[approvals.ApprovalKey, Connection], Awaitable[WorkerProvision | None]] +type CheckErasure = Callable[[str, str, str, Connection], Awaitable[bool]] + + +def _can_approve(change: ApprovalChange, provision: WorkerProvision | None) -> bool: + if type(change.modes) is not int or change.modes < 0 or type(change.team_access) is not bool: + return False + if change.modes == 0: + return not change.team_access + return ( + provision is not None + and provision.key == change.key + and change.modes & provision.modes == change.modes + and (not change.team_access or provision.exact_team_checks is True) + ) + + +async def _admin(auth: AuthInfo, key: approvals.ApprovalKey) -> str: + if ( + current_auth() is not auth + or auth.org != key.org + or auth.impersonated_by + or is_answer_token(auth) + or (auth.write_namespaces and not auth.can_write(key.org, key.namespace)) + or not settings.auth_actually_required() + or not settings.knowledge_mirrored_sources_enabled + or not protected_for(auth) + ): + raise WorkerApprovalRefused() + await session_admission.require(auth) + if not await authz.row_in_scope(key.org, key.namespace, Role.ADMIN): + raise WorkerApprovalRefused() + org, subject = await connected_accounts.own_subject(auth) + if org != key.org: + raise WorkerApprovalRefused() + return subject + + +async def apply_worker_approval( + change: ApprovalChange, *, provision: GetProvision, not_erasing: CheckErasure +) -> approvals.WorkerApproval: + with private_work(): + auth = current_auth() + if auth is None: + raise WorkerApprovalRefused() + subject = await _admin(auth, change.key) + async with approvals.scope_transaction(change.key) as conn: + if await _admin(auth, change.key) != subject or not await not_erasing( + change.key.org, change.key.namespace, subject, conn + ): + raise WorkerApprovalRefused() + bound = await provision(change.key, conn) if change.modes else None + if not _can_approve(change, bound): + raise WorkerApprovalRefused() + who = approvals.ApprovalOwner( + subject, + WriteOrigin( + auth.agent_principal.removeprefix("agent:") or "-", + auth.session_id or "-", + writer_actor(), + source_class_for(default="asserted"), + ), + ) + saved = await approvals.replace_on( + conn, + change.key, + expected_generation=change.expected_generation, + modes=change.modes, + team_access=change.team_access, + owner=who, + ) + if saved is None: + raise WorkerApprovalRefused() + return saved diff --git a/server/knowledge/app/mcp_worker_authority.py b/server/knowledge/app/mcp_worker_authority.py new file mode 100644 index 00000000000..cef46e73ad7 --- /dev/null +++ b/server/knowledge/app/mcp_worker_authority.py @@ -0,0 +1,220 @@ +"""Resolve a worker read from current Loom authority, before and after I/O.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING, Literal +from uuid import UUID + +from server.knowledge.app.mcp_worker_read import WorkerReadRefused, WorkerReadScope +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection +from server.knowledge.domain.mcp_worker_setup import WorkerMode +from server.knowledge.domain.mcp_worker_source import ( + WorkerSourceRefused, + decode_worker_source, +) +from server.knowledge.domain.sources import KnowledgeSource + +if TYPE_CHECKING: + from server.knowledge.domain.mcp_identity import ResourceIdentity + from server.knowledge.domain.mcp_worker_source import WorkerSourceConfig + + +@dataclass(frozen=True, repr=False) +class RequestedResource: + org: str + namespace: str + source_name: str + resource_id: str + + +@dataclass(frozen=True, repr=False) +class CurrentConnection: + org: str + binding: ReaderConnection + active: bool + resource_space: str | None = None + + +@dataclass(frozen=True, repr=False) +class ReaderStanding: + org: str + subject: str + grant_namespace: str + + +@dataclass(frozen=True, repr=False) +class ReaderEnrollment: + org: str + namespace: str + source_id: UUID + selection_generation: int + requester: str + connection_id: UUID + connection_generation: int + link_generation: int + + +GetStanding = Callable[[RequestedResource], Awaitable[ReaderStanding | None]] +GetSource = Callable[[str, str, str], Awaitable[KnowledgeSource | None]] +GetWorkerApproval = Callable[[str, str, UUID, str, WorkerMode, bool], Awaitable[int | None]] +GetConnection = Callable[[str, str, UUID, UUID], Awaitable[CurrentConnection | None]] +GetEnrollment = Callable[[str, str, UUID, str], Awaitable[ReaderEnrollment | None]] + + +@dataclass(frozen=True, repr=False) +class CurrentRead: + request: RequestedResource + standing: GetStanding + source: GetSource + connection: GetConnection + enrollment: GetEnrollment + worker_approval: GetWorkerApproval + purpose: Literal["live", "stored"] + + async def _registration( + self, + ) -> tuple[KnowledgeSource, WorkerSourceConfig, tuple[ResourceIdentity, ...], str]: + requested = self.request + standing = await self.standing(requested) + if ( + standing is None + or standing.org != requested.org + or standing.grant_namespace != requested.namespace + or not standing.subject + or standing.subject == "-" + ): + raise WorkerReadRefused("denied") + source = await self.source(requested.org, requested.namespace, requested.source_name) + if source is None or (source.org, source.namespace, source.name) != ( + requested.org, + requested.namespace, + requested.source_name, + ): + raise WorkerReadRefused("denied") + try: + config, selected = decode_worker_source(source) + except WorkerSourceRefused: + raise WorkerReadRefused("denied") from None + if config.paused: + raise WorkerReadRefused("denied") + return source, config, selected, standing.subject + + async def _current_connection( + self, + config: WorkerSourceConfig, + owner: str, + connection_id: UUID, + generation: int, + *, + refusal: Literal["denied", "reconnect"], + ) -> CurrentConnection: + org = self.request.org + record = await self.connection(org, owner, config.worker_id, connection_id) + if ( + record is None + or record.active is not True + or record.org != org + or record.binding.owner != owner + or record.binding.connection_id != connection_id + or record.binding.connection_generation != generation + or record.binding.worker_id != config.worker_id + or record.binding.profile_digest != config.profile_digest + ): + raise WorkerReadRefused(refusal) + return record + + async def _team_reader( + self, + config: WorkerSourceConfig, + source_id: UUID, + requester: str, + ) -> tuple[CurrentConnection, int]: + requested = self.request + enrollment = await self.enrollment(requested.org, requested.namespace, source_id, requester) + if ( + enrollment is None + or enrollment.org != requested.org + or enrollment.namespace != requested.namespace + or enrollment.source_id != source_id + or enrollment.requester != requester + or enrollment.selection_generation != config.selection_generation + or type(enrollment.link_generation) is not int + or enrollment.link_generation <= 0 + ): + raise WorkerReadRefused("denied") + reader = await self._current_connection( + config, + requester, + enrollment.connection_id, + enrollment.connection_generation, + refusal="denied", + ) + return reader, enrollment.link_generation + + async def _approval_generation(self, config: WorkerSourceConfig, *, team: bool) -> int: + requested = self.request + approval = await self.worker_approval( + requested.org, + requested.namespace, + config.worker_id, + config.profile_digest, + "live" if self.purpose == "live" else config.mode, + team, + ) + if type(approval) is not int or approval != config.approval_generation: + raise WorkerReadRefused("denied") + return approval + + async def resolve(self) -> WorkerReadScope: + requested = self.request + source, config, selected, requester = await self._registration() + source_id = UUID(source.source_id) + is_owner = requester == source.owner_subject + if self.purpose == "stored" and config.mode == "live": + raise WorkerReadRefused("denied") + if is_owner: + if not any(item.id == requested.resource_id for item in selected): + raise WorkerReadRefused("denied") + approval = await self._approval_generation(config, team=False) + owner_account = await self._current_connection( + config, + source.owner_subject, + config.owner_connection_id, + config.owner_connection_generation, + refusal="reconnect", + ) + reader, enrollment_generation = owner_account, 0 + else: + if config.reader_policy != "current_team_access": + raise WorkerReadRefused("denied") + reader, enrollment_generation = await self._team_reader(config, source_id, requester) + owner_account = await self._current_connection( + config, + source.owner_subject, + config.owner_connection_id, + config.owner_connection_generation, + refusal="denied", + ) + if not reader.resource_space or reader.resource_space != owner_account.resource_space: + raise WorkerReadRefused("denied") + # An approval lookup failure must not reveal whether a team resource was selected. + approval = await self._approval_generation(config, team=True) + if not any(item.id == requested.resource_id for item in selected): + raise WorkerReadRefused("denied") + return WorkerReadScope( + worker_id=reader.binding.worker_id, + org=requested.org, + namespace=requested.namespace, + source_id=source_id, + selection_generation=config.selection_generation, + requester=requester, + connection_id=reader.binding.connection_id, + connection_generation=reader.binding.connection_generation, + profile_digest=reader.binding.profile_digest, + approval_generation=approval, + enrollment_generation=enrollment_generation, + resource_id=requested.resource_id, + source_owner=owner_account.binding, + ) diff --git a/server/knowledge/app/mcp_worker_enrollment.py b/server/knowledge/app/mcp_worker_enrollment.py new file mode 100644 index 00000000000..78fb94171f6 --- /dev/null +++ b/server/knowledge/app/mcp_worker_enrollment.py @@ -0,0 +1,222 @@ +"""Verify an approved host's credential-free account enrollment statement.""" + +from __future__ import annotations + +import asyncio +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import Annotated +from uuid import UUID + +import jwt +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from pydantic import BaseModel, ConfigDict, Field, StringConstraints, ValidationError + +from server.core.diagnostics import private_work +from server.knowledge.app.mcp_worker_authority import CurrentConnection +from server.knowledge.app.mcp_worker_read import WorkerReadRefused +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection + +_Identity = Annotated[str, StringConstraints(min_length=1, max_length=255)] +_Digest = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] +_Counter = Annotated[int, Field(ge=1, le=2**63 - 1)] +# not a setting: the maximum age of an enrollment challenge across core and worker +_MAX_LIFETIME = 120 + + +class EnrollmentRefused(ValueError): + def __init__(self) -> None: + super().__init__("source connection enrollment unavailable") + + +@dataclass(frozen=True, repr=False) +class EnrollmentChallenge: + """Resolved from Loom's authenticated account and current worker approval.""" + + org: str + requester: str + worker_id: UUID + profile_digest: str + nonce: UUID + issued_at: int + expires_at: int + audience: str + connection_id: UUID + connection_generation: int + + +class _Binding(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) + + org: _Identity = Field(strict=True) + requester: _Identity = Field(strict=True) + worker_id: UUID + profile_digest: _Digest = Field(strict=True) + nonce: UUID + connection_id: UUID + generation: _Counter = Field(strict=True) + resource_space: _Digest | None = Field(default=None, strict=True) + + +def issue_enrollment_grant( + challenge: EnrollmentChallenge, *, issuer: str, key: Ed25519PrivateKey +) -> str: + """The caller holds current approval for the challenge's authenticated owner.""" + now = int(time.time()) + if not ( + challenge.issued_at <= now < challenge.expires_at + and 0 < challenge.expires_at - challenge.issued_at <= _MAX_LIFETIME + and challenge.requester != "-" + and challenge.worker_id.int + and challenge.nonce.int + and challenge.connection_id.int + and 1 <= len(issuer) <= 255 + and 1 <= len(challenge.audience) <= 255 + ): + raise EnrollmentRefused() + with private_work(): + try: + binding = _Binding( + org=challenge.org, + requester=challenge.requester, + worker_id=challenge.worker_id, + profile_digest=challenge.profile_digest, + nonce=challenge.nonce, + connection_id=challenge.connection_id, + generation=challenge.connection_generation, + ) + return jwt.encode( + { + "iss": issuer, + "aud": challenge.audience, + "iat": now, + "exp": min(challenge.expires_at, now + 30), + "operation": "enroll", + "binding": binding.model_dump(mode="json", exclude_none=True), + }, + key, + algorithm="EdDSA", + ) + except (ValidationError, jwt.PyJWTError): + raise EnrollmentRefused() from None + + +def verify_enrollment( + challenge: EnrollmentChallenge, statement: str, *, verifier: Ed25519PublicKey +) -> CurrentConnection: + """A matching statement attests metadata; the caller consumes the challenge once.""" + with private_work(): + if not statement.isascii() or not 1 <= len(statement) <= 8192: + raise EnrollmentRefused() + try: + claims = jwt.decode( + statement, + verifier, + algorithms=["EdDSA"], + issuer=f"urn:loom:source-worker:{challenge.worker_id}", + audience=challenge.audience, + options={"require": ["iss", "aud", "iat", "exp", "binding"], "strict_aud": True}, + ) + if set(claims) != {"iss", "aud", "iat", "exp", "binding"}: + raise EnrollmentRefused() + binding = _Binding.model_validate(claims["binding"]) + issued, expires, now = claims["iat"], claims["exp"], int(time.time()) + if not ( + type(issued) is type(expires) is int + and challenge.issued_at <= issued <= now < expires <= challenge.expires_at + and 0 < challenge.expires_at - challenge.issued_at <= _MAX_LIFETIME + and challenge.requester != "-" + and challenge.worker_id.int != 0 + and challenge.nonce.int != 0 + and binding.connection_id.int != 0 + and binding.connection_id == challenge.connection_id + and binding.generation == challenge.connection_generation + and ( + binding.org, + binding.requester, + binding.worker_id, + binding.profile_digest, + binding.nonce, + ) + == ( + challenge.org, + challenge.requester, + challenge.worker_id, + challenge.profile_digest, + challenge.nonce, + ) + ): + raise EnrollmentRefused() + except (jwt.PyJWTError, ValidationError, TypeError, RecursionError): + raise EnrollmentRefused() from None + return CurrentConnection( + org=binding.org, + binding=ReaderConnection( + binding.requester, + binding.worker_id, + binding.connection_id, + binding.generation, + binding.profile_digest, + ), + active=True, + resource_space=binding.resource_space, + ) + + +def check_enrollment_write(previous: CurrentConnection | None, proposed: CurrentConnection) -> bool: + """Decide under the challenge and connection locks; return true for a new version.""" + if proposed.active is not True: + raise EnrollmentRefused() + if previous is None: + return True + before, after = previous.binding, proposed.binding + if (previous.org, previous.resource_space) != (proposed.org, proposed.resource_space) or ( + before.worker_id, + before.owner, + before.connection_id, + before.profile_digest, + ) != (after.worker_id, after.owner, after.connection_id, after.profile_digest): + raise EnrollmentRefused() + if after.connection_generation <= before.connection_generation: + if proposed == previous: + return False + raise EnrollmentRefused() + return True + + +class _EnrollmentResponse(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True, hide_input_in_errors=True) + + statement: Annotated[str, StringConstraints(min_length=1, max_length=8192)] = Field(repr=False) + + +async def enroll_worker_connection( + challenge: EnrollmentChallenge, + *, + issuer: str, + key: Ed25519PrivateKey, + verifier: Ed25519PublicKey, + require_current: Callable[[], Awaitable[EnrollmentChallenge | None]], + request_statement: Callable[[UUID, str], Awaitable[bytearray]], + consume: Callable[[EnrollmentChallenge, CurrentConnection], Awaitable[None]], + deadline: float, +) -> CurrentConnection: + """Consume a verified challenge under durable approval and account locks.""" + if key.public_key().public_bytes_raw() == verifier.public_bytes_raw(): + raise EnrollmentRefused() + with private_work(): + try: + async with asyncio.timeout_at(deadline): + if await require_current() != challenge: + raise EnrollmentRefused() + grant = issue_enrollment_grant(challenge, issuer=issuer, key=key) + response = await request_statement(challenge.worker_id, grant) + if len(response) > 8192 + 64 or await require_current() != challenge: + raise EnrollmentRefused() + statement = _EnrollmentResponse.model_validate_json(response).statement + connection = verify_enrollment(challenge, statement, verifier=verifier) + await consume(challenge, connection) + return connection + except (ValidationError, WorkerReadRefused, TimeoutError): + raise EnrollmentRefused() from None diff --git a/server/knowledge/app/mcp_worker_enrollment_flow.py b/server/knowledge/app/mcp_worker_enrollment_flow.py new file mode 100644 index 00000000000..2d4ece0f1bf --- /dev/null +++ b/server/knowledge/app/mcp_worker_enrollment_flow.py @@ -0,0 +1,169 @@ +"""Link a worker account under current Loom ownership and approval exactly once.""" + +from __future__ import annotations + +import asyncio +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING +from uuid import UUID, uuid4 + +from server.core.diagnostics import private_work +from server.knowledge.app.mcp_worker_enrollment import ( + EnrollmentChallenge, + EnrollmentRefused, + enroll_worker_connection, +) +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection +from server.knowledge.store import pg_mcp_worker_enrollment as enrollment + +if TYPE_CHECKING: + from asyncpg import Connection + from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey, + Ed25519PublicKey, + ) + + from server.knowledge.app.mcp_worker_authority import CurrentConnection + from server.knowledge.app.mcp_worker_read import WorkerReadChannel + + +@dataclass(frozen=True, repr=False) +class EnrollmentRoute: + """The admin's current approval and the deployment's registered channel.""" + + approval_org: str + approval_namespace: str + worker_id: UUID + profile_digest: str + approval_generation: int + issuer: str + grant_key: Ed25519PrivateKey + worker_key: Ed25519PublicKey + channel: WorkerReadChannel + + +@dataclass(frozen=True, repr=False) +class EnrollmentAuthority: + """Server-resolved identity and owner scope; none originates from submitted wire fields.""" + + org: str + owner_namespace: str + owner: str + origin: enrollment.WriteOrigin + route: EnrollmentRoute + # Obtain current actor, membership, worker approval and erasure standing. On + # writes, use the supplied transaction and participate in its authority fences. + current_generation: Callable[[Connection | None], Awaitable[int | None]] + + async def is_current(self, conn: Connection | None) -> bool: + current = await self.current_generation(conn) + return type(current) is int and current == self.route.approval_generation + + +async def link_worker_account( + authority: EnrollmentAuthority, *, connection_id: UUID, generation: int, deadline: float +) -> CurrentConnection: + with private_work(): + try: + async with asyncio.timeout_at(deadline): + return await _link( + authority, connection_id=connection_id, generation=generation, deadline=deadline + ) + except TimeoutError: + raise EnrollmentRefused() from None + + +def _challenge( + authority: EnrollmentAuthority, connection_id: UUID, generation: int +) -> tuple[enrollment.Challenge, EnrollmentChallenge]: + route = authority.route + if ( + authority.org != route.approval_org + or not authority.owner_namespace + or not route.approval_namespace + or not authority.owner + or authority.owner == "-" + or type(route.approval_generation) is not int + or route.approval_generation <= 0 + or route.worker_id.int == 0 + or connection_id.int == 0 + or type(generation) is not int + or not 0 < generation < 2**63 + ): + raise EnrollmentRefused() + account = enrollment.AccountKey( + authority.org, + authority.owner_namespace, + authority.owner, + route.worker_id, + route.profile_digest, + connection_id, + ) + now = int(time.time()) + challenge = enrollment.Challenge(account, generation, uuid4(), now, now + 30) + wire = EnrollmentChallenge( + org=account.org, + requester=account.requester, + worker_id=account.worker_id, + profile_digest=account.profile_digest, + nonce=challenge.nonce, + issued_at=challenge.issued_at, + expires_at=challenge.expires_at, + audience=f"urn:loom:source-worker:{account.worker_id}:enrollment", + connection_id=account.connection_id, + connection_generation=challenge.generation, + ) + + return challenge, wire + + +async def _link( + authority: EnrollmentAuthority, *, connection_id: UUID, generation: int, deadline: float +) -> CurrentConnection: + route = authority.route + challenge, wire = _challenge(authority, connection_id, generation) + account = challenge.account + async with enrollment.owner_transaction(account) as conn: + if not await authority.is_current(conn) or not await enrollment.issue_challenge( + conn, challenge, authority.origin + ): + raise EnrollmentRefused() + + async def current() -> EnrollmentChallenge | None: + return wire if await authority.is_current(None) else None + + async def consume(expected: EnrollmentChallenge, proposed: CurrentConnection) -> None: + if ( + expected != wire + or proposed.org != account.org + or proposed.binding + != ReaderConnection( + account.requester, + account.worker_id, + account.connection_id, + generation, + account.profile_digest, + ) + ): + raise EnrollmentRefused() + async with enrollment.owner_transaction(account) as conn: + if not await authority.is_current(conn): + raise EnrollmentRefused() + accepted = await enrollment.consume_challenge( + conn, challenge, resource_space=proposed.resource_space + ) + if not accepted: + raise EnrollmentRefused() + + return await enroll_worker_connection( + wire, + issuer=route.issuer, + key=route.grant_key, + verifier=route.worker_key, + require_current=current, + request_statement=route.channel.request_enrollment, + consume=consume, + deadline=deadline, + ) diff --git a/server/knowledge/app/mcp_worker_live.py b/server/knowledge/app/mcp_worker_live.py new file mode 100644 index 00000000000..6d23b488138 --- /dev/null +++ b/server/knowledge/app/mcp_worker_live.py @@ -0,0 +1,103 @@ +"""Transient selected reads and their publication check.""" + +import asyncio +import json +from collections.abc import Awaitable, Callable +from dataclasses import asdict, dataclass +from urllib.parse import urlsplit +from uuid import UUID + +from server.core.diagnostics import private_work +from server.knowledge.app.mcp_worker_read import ( + WorkerReadChannel, + WorkerReadRefused, + WorkerReadScope, +) +from server.knowledge.domain.mcp_identity import resource_uri + +# not a setting: the fixed document ceiling leaves room for the transport envelope. +_MAX_LIVE_DOCUMENT_WIRE_BYTES = 16 * 1024 * 1024 + +ResolveScope = Callable[[], Awaitable[WorkerReadScope]] +ResolveWorker = Callable[[UUID], WorkerReadChannel | None] +RetainPublication = Callable[ + [WorkerReadScope, Callable[[], Awaitable[None]], float], Awaitable[None] +] + + +@dataclass(frozen=True, repr=False) +class LiveDocument: + source_id: UUID + resource_id: str + uri: str + source_link: str | None + fetched_at: int + title: str + text: str + mime_type: str + + +def _display_link(uri: str | None) -> str | None: + if not uri or "\\" in uri or any(c.isspace() or ord(c) < 32 or ord(c) == 127 for c in uri): + return None + try: + parsed = urlsplit(uri) + if parsed.scheme == "https" and parsed.hostname and parsed.username is None: + return uri + except ValueError: + pass + return None + + +def _check_publication_size(document: LiveDocument) -> None: + fields = asdict(document) + fields["source_id"] = str(document.source_id) + # MCP sends a JSON value and an escaped copy as text. ASCII escaping + # bounds the larger of the HTTP and MCP document encodings. + value = json.dumps(fields, ensure_ascii=True) + size = len(value) + if size > _MAX_LIVE_DOCUMENT_WIRE_BYTES or ( + size + len(json.dumps(value)) > _MAX_LIVE_DOCUMENT_WIRE_BYTES + ): + raise WorkerReadRefused("unsupported") + + +async def read_selected_live( + *, + resolve: ResolveScope, + worker: ResolveWorker, + retain: RetainPublication, + deadline: float, +) -> LiveDocument: + """Return to the protected transport. The caller installs its publication barrier.""" + try: + with private_work(): + async with asyncio.timeout_at(deadline): + scope = await resolve() + channel = worker(scope.worker_id) + if channel is None: + raise WorkerReadRefused("unavailable") + read = await channel.run(scope, "live", require_current=resolve) + if read.document is None: + raise WorkerReadRefused("denied") + + async def validate() -> None: + if await resolve() != scope: + raise WorkerReadRefused("denied") + + document = LiveDocument( + scope.source_id, + scope.resource_id, + resource_uri(str(scope.source_id), scope.resource_id), + _display_link(read.document.source_link), + read.fetched_at, + read.document.title, + read.document.text, + read.document.mime_type, + ) + # Check the wire size after the read and before retaining the publication fence. + _check_publication_size(document) + await retain(scope, validate, deadline) + return document + except TimeoutError: + raise WorkerReadRefused("timeout") from None diff --git a/server/knowledge/app/mcp_worker_live_op.py b/server/knowledge/app/mcp_worker_live_op.py new file mode 100644 index 00000000000..afd6b067fba --- /dev/null +++ b/server/knowledge/app/mcp_worker_live_op.py @@ -0,0 +1,51 @@ +"""Present the result of the protected read without a stored fallback.""" + +import asyncio + +from server.core.diagnostics import private_work +from server.knowledge.api.models_source_live import ( + KnowledgeSourceLiveDocument, + KnowledgeSourceLiveInput, + KnowledgeSourceLiveOutput, +) +from server.knowledge.app.mcp_worker_authority import RequestedResource +from server.knowledge.app.mcp_worker_protected import LiveSourceDirectory, protected_live_read +from server.knowledge.app.mcp_worker_read import WorkerReadRefused +from server.knowledge.app.mcp_worker_runtime import current_directory +from server.settings import settings + + +async def read_source_live( + input: KnowledgeSourceLiveInput, directory: LiveSourceDirectory +) -> KnowledgeSourceLiveOutput: + with private_work(): + try: + target = RequestedResource(input.org, input.namespace, input.name, input.resource_id) + deadline = ( + asyncio.get_running_loop().time() + settings.knowledge_source_worker_live_timeout_s + ) + document = await protected_live_read(target, directory, deadline=deadline) + except WorkerReadRefused as error: + return KnowledgeSourceLiveOutput(status=error.reason) + return KnowledgeSourceLiveOutput( + status="ok", + document=KnowledgeSourceLiveDocument( + source_id=document.source_id, + resource_id=document.resource_id, + uri=document.uri, + source_link=document.source_link, + fetched_at=document.fetched_at, + title=document.title, + text=document.text, + mime_type=document.mime_type, + ), + ) + + +async def handle_knowledge_source_live( + input: KnowledgeSourceLiveInput, +) -> KnowledgeSourceLiveOutput: + directory = current_directory() + if directory is None: + return KnowledgeSourceLiveOutput(status="unavailable") + return await read_source_live(input, directory) diff --git a/server/knowledge/app/mcp_worker_pg_directory.py b/server/knowledge/app/mcp_worker_pg_directory.py new file mode 100644 index 00000000000..c41fee34521 --- /dev/null +++ b/server/knowledge/app/mcp_worker_pg_directory.py @@ -0,0 +1,146 @@ +"""Read opaque source worker authority from the deployment's Postgres store.""" + +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING +from uuid import UUID + +from server.knowledge.app.mcp_worker_authority import CurrentConnection, ReaderEnrollment +from server.knowledge.app.mcp_worker_protected import Deliver, LiveSourceDirectory +from server.knowledge.app.mcp_worker_read import WorkerReadRefused, WorkerReadScope +from server.knowledge.app.mcp_worker_routes import WorkerRoutes +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection +from server.knowledge.domain.mcp_worker_setup import WorkerMode +from server.knowledge.store import pg_mcp_worker_approvals as approvals +from server.knowledge.store import pg_mcp_worker_enrollment as accounts +from server.knowledge.store import pg_mcp_worker_readers as readers +from server.knowledge.store.sources import get_source + +if TYPE_CHECKING: + from asyncpg import Connection + + +async def current_connection( + org: str, owner: str, worker_id: UUID, connection_id: UUID +) -> CurrentConnection | None: + row = await accounts.current_reader_account(org, owner, worker_id, connection_id) + if row is None: + return None + profile_digest, state = row + binding = ReaderConnection(owner, worker_id, connection_id, state.generation, profile_digest) + return CurrentConnection(org, binding, state.active, state.resource_space) + + +async def current_enrollment( + org: str, namespace: str, source_id: UUID, requester: str +) -> ReaderEnrollment | None: + row = await readers.current(readers.LinkKey(org, namespace, source_id, requester)) + if row is None or row.active is not True: + return None + return ReaderEnrollment( + org, + namespace, + source_id, + row.selection_generation, + requester, + row.connection_id, + row.connection_generation, + row.link_generation, + ) + + +async def _account_space( + conn: Connection, scope: WorkerReadScope, subject: str, connection: UUID, generation: int +) -> str | None: + row = await accounts.reader_account_on( + conn, scope.org, subject, scope.worker_id, connection, lock=True + ) + if row is None: + raise WorkerReadRefused("denied") + profile, account = row + if profile != scope.profile_digest or not account.active or account.generation != generation: + raise WorkerReadRefused("denied") + return account.resource_space + + +async def fence_live_delivery( + scope: WorkerReadScope, deliver: Deliver, deadline: float, recheck_source: Deliver +) -> None: + """Keep revocation, erasure and source changes fenced until this frame has been + handed off. `recheck_source` reads the source again under the source lock.""" + owner = scope.source_owner + if ( + owner is None + or owner.worker_id != scope.worker_id + or owner.profile_digest != scope.profile_digest + ): + raise WorkerReadRefused("denied") + key = approvals.ApprovalKey(scope.org, scope.namespace, scope.worker_id, scope.profile_digest) + async with ( + asyncio.timeout_at(deadline), + approvals.scope_transaction(key, sources=True) as conn, + ): + await recheck_source() + approval = await approvals.current_on(conn, key, lock=True) + team = owner.owner != scope.requester + if ( + approval is None + or not approval.active + or not approval.modes & approvals.LIVE + or approval.generation != scope.approval_generation + or (team and not approval.team_access) + ): + raise WorkerReadRefused("denied") + if team: + link_key = readers.LinkKey(scope.org, scope.namespace, scope.source_id, scope.requester) + link = await readers.current_on(conn, link_key, lock=True) + if link != readers.Link( + scope.selection_generation, + scope.connection_id, + scope.connection_generation, + scope.enrollment_generation, + True, + ): + raise WorkerReadRefused("denied") + elif (scope.connection_id, scope.connection_generation, scope.enrollment_generation) != ( + owner.connection_id, + owner.connection_generation, + 0, + ): + raise WorkerReadRefused("denied") + + space = await _account_space( + conn, scope, owner.owner, owner.connection_id, owner.connection_generation + ) + if team and ( + not space + or space + != await _account_space( + conn, scope, scope.requester, scope.connection_id, scope.connection_generation + ) + ): + raise WorkerReadRefused("denied") + if asyncio.get_running_loop().time() >= deadline: + raise WorkerReadRefused("denied") + await deliver() + + +def live_directory(routes: WorkerRoutes) -> LiveSourceDirectory: + """Compose the canonical source and account stores with a provisioned route registry.""" + + async def approval( + org: str, namespace: str, worker: UUID, profile: str, mode: WorkerMode, team: bool + ) -> int | None: + if not routes.permits(worker, org, profile, mode, team): + return None + return await approvals.current_generation(org, namespace, worker, profile, mode, team) + + return LiveSourceDirectory( + source=get_source, + connection=current_connection, + enrollment=current_enrollment, + worker=routes.get, + worker_approval=approval, + fence_delivery=fence_live_delivery, + ) diff --git a/server/knowledge/app/mcp_worker_proof.py b/server/knowledge/app/mcp_worker_proof.py new file mode 100644 index 00000000000..cb837df798b --- /dev/null +++ b/server/knowledge/app/mcp_worker_proof.py @@ -0,0 +1,74 @@ +"""Confirm current upstream access to the exact bytes of a stored source copy.""" + +from __future__ import annotations + +import hashlib +import time +from collections.abc import Awaitable, Callable + +from server.knowledge.app.mcp_worker_authority import CurrentRead +from server.knowledge.app.mcp_worker_read import WorkerReadChannel, WorkerReadRefused +from server.knowledge.domain.mcp_worker_permissions import ( + ReaderConnection, + StoredCopyRevision, + VerifiedWorkerReadEvidence, + can_read_stored_copy, +) + + +def _epoch_seconds() -> int: + return int(time.time()) + + +async def confirm_stored_read( + *, + channel: WorkerReadChannel, + current: CurrentRead, + revision: Callable[[], Awaitable[StoredCopyRevision | None]], + max_age_seconds: int, + now: Callable[[], int] = _epoch_seconds, +) -> VerifiedWorkerReadEvidence: + if type(max_age_seconds) is not int or not 1 <= max_age_seconds <= 300: + raise ValueError("invalid upstream access evidence lifetime") + if current.purpose != "stored": + raise WorkerReadRefused("denied") + scope = await current.resolve() + accepted = await revision() + resource_digest = hashlib.sha256(scope.resource_id.encode()).hexdigest() + if ( + accepted is None + or (accepted.org, accepted.namespace) != (scope.org, scope.namespace) + or accepted.source_id != scope.source_id + or accepted.selection_generation != scope.selection_generation + or accepted.resource_id_sha256 != resource_digest + ): + raise WorkerReadRefused("denied") + started = now() + reading = await channel.run(scope, "check_access", require_current=current.resolve) + if reading.content_sha256 != accepted.content_sha256 or await revision() != accepted: + raise WorkerReadRefused("denied") + reader = ReaderConnection( + scope.requester, + scope.worker_id, + scope.connection_id, + scope.connection_generation, + scope.profile_digest, + ) + proof = VerifiedWorkerReadEvidence( + confirmed_revision=accepted, + connection=reader, + issued_at=started, + confirmed_at=reading.fetched_at, + expires_at=started + max_age_seconds, + ) + if await current.resolve() != scope or not can_read_stored_copy( + collection_granted=True, + requester=scope.requester, + current_revision=accepted, + active_connection=reader, + evidence=proof, + now=now(), + max_evidence_age_seconds=max_age_seconds, + ): + raise WorkerReadRefused("denied") + return proof diff --git a/server/knowledge/app/mcp_worker_protected.py b/server/knowledge/app/mcp_worker_protected.py new file mode 100644 index 00000000000..437772ba06c --- /dev/null +++ b/server/knowledge/app/mcp_worker_protected.py @@ -0,0 +1,162 @@ +"""Apply the Loom collection and session publication gates to a live source read.""" + +import asyncio +from collections.abc import Awaitable, Callable +from dataclasses import dataclass + +from server.auth import authz +from server.auth.answer_tokens import is_answer_token +from server.auth.context import current_auth +from server.auth.jwt import AuthInfo +from server.auth.session_protection import protected_for +from server.core import request_tail, request_work +from server.core.ch import sequential_reads +from server.core.diagnostics import private_work +from server.identity.domain.read_scope import effective_read_scope +from server.knowledge.app import connected_accounts, session_admission +from server.knowledge.app.mcp_worker_authority import ( + CurrentRead, + GetConnection, + GetEnrollment, + GetSource, + GetWorkerApproval, + ReaderStanding, + RequestedResource, +) +from server.knowledge.app.mcp_worker_live import LiveDocument, ResolveWorker, read_selected_live +from server.knowledge.app.mcp_worker_read import WorkerReadRefused, WorkerReadScope +from server.knowledge.domain.sources import KnowledgeSource +from server.operations.base import Role +from server.settings import settings + +Deliver = Callable[[], Awaitable[None]] +FenceDelivery = Callable[[WorkerReadScope, Deliver, float, Deliver], Awaitable[None]] + + +@dataclass(frozen=True, repr=False) +class LiveSourceDirectory: + source: GetSource + connection: GetConnection + enrollment: GetEnrollment + worker: ResolveWorker + worker_approval: GetWorkerApproval + fence_delivery: FenceDelivery | None = None + + +def _require_context(org: str, auth: AuthInfo) -> None: + if ( + current_auth() is not auth + or auth.org != org + or not settings.auth_actually_required() + or not settings.knowledge_mirrored_sources_enabled + or not protected_for(auth) + or is_answer_token(auth) + or effective_read_scope(None, auth) != "namespace" + or bool(auth.read_user_id) + ): + raise WorkerReadRefused("denied") + + +async def _retain(auth: AuthInfo, fence: request_tail.PublicationFence, deadline: float) -> None: + loop = asyncio.get_running_loop() + checked = False + + async def validate() -> None: + nonlocal checked + checked = False + with private_work(): + async with asyncio.timeout_at(deadline): + _require_context(auth.org, auth) + await session_admission.require(auth) + _require_context(auth.org, auth) + checked = True + + def fresh() -> bool: + return checked and loop.time() < deadline + + # The fence rechecks source and worker authority under the publication locks. + await validate() + if not fresh() or not request_tail.retain_publication(validate, validate, fresh, fence=fence): + raise WorkerReadRefused("timeout" if loop.time() >= deadline else "denied") + + +async def protected_live_read( + request: RequestedResource, directory: LiveSourceDirectory, *, deadline: float +) -> LiveDocument: + with private_work(): + auth = current_auth() + if auth is None or not request_tail.required_active(): + raise WorkerReadRefused("denied") + _require_context(request.org, auth) + fence_delivery = directory.fence_delivery + if fence_delivery is None: + raise WorkerReadRefused("unavailable") + if not request_work.mark_mirrored(): + raise WorkerReadRefused("denied") + + async def standing(target: RequestedResource) -> ReaderStanding | None: + _require_context(target.org, auth) + await session_admission.require(auth) + if not await authz.row_in_scope(target.org, target.namespace, Role.VIEWER): + return None + org, subject = await connected_accounts.own_subject(auth) + return ReaderStanding(org, subject, target.namespace) + + # The source row the latest authority check saw, which the fence compares. + checked_source: list[KnowledgeSource] = [] + + async def source(org: str, namespace: str, name: str) -> KnowledgeSource | None: + row = await directory.source(org, namespace, name) + checked_source[:] = [] if row is None else [row] + return row + + current = CurrentRead( + request, + standing, + source, + directory.connection, + directory.enrollment, + directory.worker_approval, + "live", + ) + + async def retain(scope: WorkerReadScope, check: Deliver, read_until: float) -> None: + # A completed worker read gets its own bounded time for accounting and send. + loop = asyncio.get_running_loop() + retain_until = ( + min(read_until, loop.time()) + + settings.knowledge_source_worker_publication_timeout_s + ) + + async def recheck_source() -> None: + # Any change to the row since this frame's check, a rewrite included, + # withholds the frame; the read must see every replica's commits. + with sequential_reads(): + row = await directory.source( + request.org, request.namespace, request.source_name + ) + if checked_source != [row]: + raise WorkerReadRefused("denied") + + async def fence(deliver: Deliver) -> None: + _require_context(scope.org, auth) + with private_work(): + start = loop.time() + end = min( + retain_until, start + settings.knowledge_source_worker_frame_timeout_s + ) + if start >= end: + raise WorkerReadRefused("timeout") + async with asyncio.timeout_at(end): + with sequential_reads(): + await check() + # The fence rereads the source under the source lock that + # source writes hold exclusively, so a change committed after + # this check still stops the frame. + await fence_delivery(scope, deliver, end, recheck_source) + + await _retain(auth, fence, retain_until) + + return await read_selected_live( + resolve=current.resolve, worker=directory.worker, retain=retain, deadline=deadline + ) diff --git a/server/knowledge/app/mcp_worker_read.py b/server/knowledge/app/mcp_worker_read.py new file mode 100644 index 00000000000..99671808985 --- /dev/null +++ b/server/knowledge/app/mcp_worker_read.py @@ -0,0 +1,312 @@ +"""Call an approved worker without resolving an upstream connection in Loom.""" + +from __future__ import annotations + +import asyncio +import hashlib +import math +import ssl +import time +from collections.abc import Awaitable, Callable +from dataclasses import asdict, dataclass +from typing import Annotated, Literal +from uuid import UUID, uuid4 + +import httpx +import jwt +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from pydantic import BaseModel, ConfigDict, Field, StringConstraints, ValidationError + +from server.core.diagnostics import private_work +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection + +WorkerOperation = Literal["live", "check_access"] +WorkerFailure = Literal[ + "denied", "reconnect", "overloaded", "timeout", "unavailable", "unsupported" +] +_ENROLLMENT_PATH = "/v1/enroll" +# not a setting: bounds the signed enrollment response and its JSON envelope +_MAX_ENROLLMENT_BODY = 8192 + 64 +# not a setting: enrollment is a rare setup step; two in flight per worker bound its pool share +_ENROLLMENT_CAPACITY = 2 +# not a setting: worker and Loom clocks count whole seconds and may differ by one. +_CLOCK_SKEW_S = 1 + + +def live_grant_seconds(live_timeout_s: float) -> int: + """A grant lifetime that outlasts a live read of `live_timeout_s`: the grant is + stamped in whole seconds, which can cost up to one, and the worker's clock may be + `_CLOCK_SKEW_S` ahead.""" + return math.ceil(live_timeout_s) + 1 + _CLOCK_SKEW_S + + +_Paths: dict[WorkerOperation, str] = {"live": "/v1/live", "check_access": "/v1/check-access"} +_Statuses: dict[int, WorkerFailure] = { + 401: "denied", + 403: "denied", + 409: "reconnect", + 422: "unsupported", + 429: "overloaded", + 503: "unavailable", + 504: "timeout", +} + + +class WorkerReadRefused(Exception): + def __init__(self, reason: WorkerFailure) -> None: + super().__init__(reason) + self.reason = reason + + +@dataclass(frozen=True, repr=False) +class WorkerReadScope: + worker_id: UUID + org: str + namespace: str + source_id: UUID + selection_generation: int + requester: str + connection_id: UUID + connection_generation: int + profile_digest: str + approval_generation: int + resource_id: str + enrollment_generation: int = 0 + source_owner: ReaderConnection | None = None + + +@dataclass(frozen=True, repr=False) +class _Issued: + token: str + request_id: UUID + issued_at: int + expires_at: int + + +def _issue( + scope: WorkerReadScope, + operation: WorkerOperation, + *, + issuer: str, + signing_key: Ed25519PrivateKey, + lifetime_seconds: int, +) -> _Issued: + if type(lifetime_seconds) is not int or not 1 <= lifetime_seconds <= 30: + raise ValueError("invalid source worker grant lifetime") + request_id = uuid4() + issued_at = int(time.time()) + expires_at = issued_at + lifetime_seconds + binding = asdict(scope) + # Loom rechecks these local authority generations before delivery. + del binding["approval_generation"], binding["enrollment_generation"], binding["source_owner"] + for field in ("worker_id", "source_id", "connection_id"): + binding[field] = str(binding[field]) + token = jwt.encode( + { + "iss": issuer, + "aud": f"urn:loom:source-worker:{scope.worker_id}", + "iat": issued_at, + "exp": expires_at, + "grant": { + "version": 1, + "operation": operation, + "request_id": str(request_id), + "binding": binding, + }, + }, + signing_key, + algorithm="EdDSA", + ) + if len(token) > 24_576: + raise WorkerReadRefused("denied") + return _Issued(token, request_id, issued_at, expires_at) + + +class WorkerDocument(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True, frozen=True, hide_input_in_errors=True) + + resource_id: Annotated[str, StringConstraints(min_length=1, max_length=2048)] = Field( + repr=False + ) + title: Annotated[str, StringConstraints(max_length=4096)] = Field(repr=False) + # The UTF-8 byte budget is checked after the digest, so oversize reads are unsupported. + text: Annotated[str, StringConstraints(min_length=1)] = Field(repr=False) + revision: Annotated[str, StringConstraints(max_length=2048)] | None = Field(repr=False) + source_link: Annotated[str, StringConstraints(max_length=2048)] | None = Field(repr=False) + mime_type: Annotated[str, StringConstraints(min_length=1, max_length=128)] + + +class WorkerReading(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True, frozen=True, hide_input_in_errors=True) + + status: Literal["ok"] + request_id: UUID + fetched_at: int + content_sha256: Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] = Field(repr=False) + document: WorkerDocument | None = Field(repr=False) + + +def _validate_reading( + payload: bytearray, scope: WorkerReadScope, issued: _Issued, operation: WorkerOperation +) -> WorkerReading: + try: + reading = WorkerReading.model_validate_json(payload) + if reading.request_id != issued.request_id or not ( + issued.issued_at - _CLOCK_SKEW_S <= reading.fetched_at < issued.expires_at + ): + raise WorkerReadRefused("denied") + if operation == "check_access": + if reading.document is not None: + raise WorkerReadRefused("denied") + return reading + if reading.document is None or reading.document.resource_id != scope.resource_id: + raise WorkerReadRefused("denied") + content = reading.document.text.encode("utf-8") + digest = hashlib.sha256(content).hexdigest() + if digest != reading.content_sha256: + raise WorkerReadRefused("denied") + if len(content) > 4_000_000: + raise WorkerReadRefused("unsupported") + return reading + except (ValidationError, UnicodeError): + raise WorkerReadRefused("denied") from None + + +class WorkerReadChannel: + def __init__( + self, + *, + worker_id: UUID, + origin: str, + issuer: str, + signing_key: Ed25519PrivateKey, + grant_seconds: int, + max_response_bytes: int, + max_inflight: int = 8, + tls: ssl.SSLContext | None = None, + _transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + url = httpx.URL(origin) + if ( + not origin.isascii() + or url.scheme != "https" + or not url.host + or url.userinfo + or url.raw_path != b"/" + or url.fragment + ): + raise ValueError("worker must have an approved TLS origin") + if ( + type(grant_seconds) is not int + or not 1 <= grant_seconds <= 30 + or type(max_response_bytes) is not int + or not 1 <= max_response_bytes <= 25_000_000 + or type(max_inflight) is not int + or not 1 <= max_inflight <= 256 + ): + raise ValueError("invalid source worker channel limits") + if tls is not None and (tls.verify_mode != ssl.CERT_REQUIRED or not tls.check_hostname): + raise ValueError("worker channel TLS verification is required") + self._worker_id = worker_id + self._origin = url + self._issuer = issuer + self._key = signing_key + self._seconds = grant_seconds + self._maximum = max_response_bytes + self._max_inflight = max_inflight + self._inflight = 0 + self._enrolling = 0 + self._client = httpx.AsyncClient( + trust_env=False, + follow_redirects=False, + transport=_transport, + timeout=grant_seconds, + verify=tls or True, + limits=httpx.Limits( + max_connections=max_inflight + _ENROLLMENT_CAPACITY, + max_keepalive_connections=max_inflight, + ), + ) + + async def close(self) -> None: + await self._client.aclose() + + async def _post( + self, path: str, token: str, *, maximum: int, json_object: bool = False + ) -> bytearray: + url = self._origin.copy_with(path=path) + headers = {"Authorization": f"Bearer {token}", "Accept-Encoding": "identity"} + body = b"{}" if json_object else None + if json_object: + headers["Content-Type"] = "application/json" + data = bytearray() + async with self._client.stream("POST", url, headers=headers, content=body) as response: + if response.status_code != 200: + raise WorkerReadRefused(_Statuses.get(response.status_code, "denied")) + if ( + response.headers.get("content-encoding", "identity") != "identity" + or response.headers.get("content-type", "").partition(";")[0] != "application/json" + ): + raise WorkerReadRefused("denied") + async for chunk in response.aiter_raw(): + if len(data) + len(chunk) > maximum: + raise WorkerReadRefused("unsupported") + data.extend(chunk) + return data + + async def request_enrollment(self, worker_id: UUID, token: str) -> bytearray: + if worker_id != self._worker_id or not token.isascii() or not 1 <= len(token) <= 8192: + raise WorkerReadRefused("denied") + if self._enrolling >= _ENROLLMENT_CAPACITY: + raise WorkerReadRefused("overloaded") + self._enrolling += 1 + try: + with private_work(): + async with asyncio.timeout(self._seconds): + return await self._post( + _ENROLLMENT_PATH, token, maximum=_MAX_ENROLLMENT_BODY, json_object=True + ) + except (TimeoutError, httpx.TimeoutException): + raise WorkerReadRefused("timeout") from None + except httpx.HTTPError: + raise WorkerReadRefused("unavailable") from None + finally: + self._enrolling -= 1 + + async def run( + self, + scope: WorkerReadScope, + operation: WorkerOperation, + *, + require_current: Callable[[], Awaitable[WorkerReadScope]], + ) -> WorkerReading: + if self._inflight >= self._max_inflight: + raise WorkerReadRefused("overloaded") + self._inflight += 1 + try: + with private_work(): + async with asyncio.timeout(self._seconds): + if scope.worker_id != self._worker_id or await require_current() != scope: + raise WorkerReadRefused("denied") + issued = _issue( + scope, + operation, + issuer=self._issuer, + signing_key=self._key, + lifetime_seconds=self._seconds, + ) + payload = await self._post( + _Paths[operation], issued.token, maximum=self._maximum + ) + reading = _validate_reading(payload, scope, issued, operation) + if await require_current() != scope: + raise WorkerReadRefused("denied") + if time.time() >= issued.expires_at: + raise WorkerReadRefused("timeout") + return reading + except (TimeoutError, httpx.TimeoutException): + raise WorkerReadRefused("timeout") from None + except httpx.HTTPError: + raise WorkerReadRefused("unavailable") from None + finally: + self._inflight -= 1 diff --git a/server/knowledge/app/mcp_worker_route_config.py b/server/knowledge/app/mcp_worker_route_config.py new file mode 100644 index 00000000000..1b305f0b648 --- /dev/null +++ b/server/knowledge/app/mcp_worker_route_config.py @@ -0,0 +1,112 @@ +"""Load the operator-managed allowlist for remote source workers.""" + +from __future__ import annotations + +import ssl +from pathlib import Path +from typing import Annotated +from uuid import UUID + +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey +from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key +from pydantic import BaseModel, ConfigDict, Field, StringConstraints, ValidationError + +from server.knowledge.app.mcp_worker_routes import WorkerProfile, WorkerRoute +from server.knowledge.domain.mcp_worker_setup import WorkerMode + +_MAX_CONFIG_BYTES = 262_144 # not a setting: bounds input to the routes file parser +_MAX_KEY_BYTES = 8192 # not a setting: bounds input to the signing key parser +_Org = Annotated[str, StringConstraints(min_length=1, max_length=255)] +_Digest = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] + + +class _ProfileFile(BaseModel): + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True, strict=True) + + digest: _Digest + modes: Annotated[list[WorkerMode], Field(min_length=1, max_length=3)] + team_access: bool = False + + +_Profiles = Annotated[list[_ProfileFile], Field(min_length=1, max_length=4096)] + + +class _WorkerFile(BaseModel): + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True, strict=True) + + worker_id: UUID + origin: Annotated[str, StringConstraints(min_length=1, max_length=2048)] + issuer: Annotated[str, StringConstraints(min_length=1, max_length=255)] + trust_ca_file: Path + client_certificate_file: Path + client_key_file: Path + grant_key_file: Path + enrollment_verifier_file: Path | None = None + profiles: Annotated[dict[_Org, _Profiles], Field(min_length=1, max_length=256)] + max_live_requests: Annotated[int, Field(ge=1, le=64)] = 8 + + +class _RoutesFile(BaseModel): + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True, strict=True) + + version: Annotated[int, Field(ge=1, le=1)] + workers: Annotated[list[_WorkerFile], Field(max_length=256)] + + +def _read_file(path: Path, limit: int) -> bytes: + with path.open("rb") as stream: + data = stream.read(limit + 1) + if not data or len(data) > limit: + raise ValueError("invalid source worker file size") + return data + + +def _grant_key(path: Path) -> Ed25519PrivateKey: + key = load_pem_private_key(_read_file(path, _MAX_KEY_BYTES), password=None) + if not isinstance(key, Ed25519PrivateKey): + raise ValueError("invalid source worker key type") + return key + + +def _verifier(path: Path) -> Ed25519PublicKey: + key = load_pem_public_key(_read_file(path, _MAX_KEY_BYTES)) + if not isinstance(key, Ed25519PublicKey): + raise ValueError("invalid source worker key type") + return key + + +def _build(root: Path, worker: _WorkerFile) -> WorkerRoute: + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + tls.minimum_version = ssl.TLSVersion.TLSv1_2 + tls.load_verify_locations(cafile=root / worker.trust_ca_file) + tls.load_cert_chain( + root / worker.client_certificate_file, root / worker.client_key_file, password=lambda: b"" + ) + enrollment = ( + _verifier(root / worker.enrollment_verifier_file) + if worker.enrollment_verifier_file is not None + else None + ) + return WorkerRoute( + worker.worker_id, + worker.origin, + tls, + worker.issuer, + _grant_key(root / worker.grant_key_file), + enrollment, + tuple( + WorkerProfile(org, profile.digest, frozenset(profile.modes), profile.team_access) + for org, profiles in worker.profiles.items() + for profile in profiles + ), + worker.max_live_requests, + ) + + +def load_worker_routes(path: Path) -> tuple[WorkerRoute, ...]: + try: + config = _RoutesFile.model_validate_json(_read_file(path, _MAX_CONFIG_BYTES)) + return tuple(_build(path.parent, worker) for worker in config.workers) + except (OSError, ValidationError, ValueError, TypeError, UnsupportedAlgorithm): + raise ValueError("invalid source worker route configuration") from None diff --git a/server/knowledge/app/mcp_worker_routes.py b/server/knowledge/app/mcp_worker_routes.py new file mode 100644 index 00000000000..71b56ca4868 --- /dev/null +++ b/server/knowledge/app/mcp_worker_routes.py @@ -0,0 +1,172 @@ +"""Own connections to deployment provisioned source workers, never their upstreams.""" + +from __future__ import annotations + +import re +import ssl +from contextlib import AsyncExitStack, asynccontextmanager +from dataclasses import dataclass +from types import MappingProxyType +from typing import TYPE_CHECKING + +from server.knowledge.app.mcp_worker_enrollment_flow import EnrollmentRoute +from server.knowledge.app.mcp_worker_read import WorkerReadChannel, live_grant_seconds +from server.settings import settings + +if TYPE_CHECKING: + from collections.abc import AsyncIterator, Mapping + from uuid import UUID + + from cryptography.hazmat.primitives.asymmetric.ed25519 import ( + Ed25519PrivateKey, + Ed25519PublicKey, + ) + + from server.knowledge.domain.mcp_worker_setup import WorkerMode + +_MAX_WORKERS = 256 # not a setting: bounds the in-memory route directory +_MAX_PROFILES_PER_WORKER = 4096 # not a setting: bounds profile lookup for one worker +# not a setting: a 4,000,000-byte document at worst-case JSON escaping, plus its envelope +_MAX_WORKER_RESPONSE_BYTES = 25_000_000 +_DIGEST = re.compile(r"[0-9a-f]{64}") + + +_MODES = frozenset({"live", "snapshot", "selected_refresh"}) + + +@dataclass(frozen=True, repr=False) +class WorkerProfile: + org: str + digest: str + modes: frozenset[WorkerMode] + team_access: bool = False + + def _validate(self) -> None: + if not ( + 0 < len(self.org) <= 255 + and self.org != "*" + and _DIGEST.fullmatch(self.digest) + and self.modes + and self.modes <= _MODES + and type(self.team_access) is bool + ): + raise ValueError("invalid source worker profile") + + +@dataclass(frozen=True, repr=False) +class WorkerRoute: + worker_id: UUID + tls_origin: str + tls: ssl.SSLContext + issuer: str + grant_key: Ed25519PrivateKey + enrollment_verifier: Ed25519PublicKey | None + profiles: tuple[WorkerProfile, ...] + max_live_requests: int + + def _validate(self) -> None: + if not ( + self.worker_id.int + and isinstance(self.tls, ssl.SSLContext) + and self.tls.check_hostname + and self.tls.verify_mode == ssl.CERT_REQUIRED + and self.issuer.isascii() + and 0 < len(self.issuer) <= 255 + and 0 < len(self.profiles) <= _MAX_PROFILES_PER_WORKER + and len({(profile.org, profile.digest) for profile in self.profiles}) + == len(self.profiles) + and ( + self.enrollment_verifier is None + or self.enrollment_verifier.public_bytes_raw() + != self.grant_key.public_key().public_bytes_raw() + ) + ): + raise ValueError("invalid source worker route") + for profile in self.profiles: + profile._validate() + + +@dataclass(frozen=True, repr=False) +class _EnrollmentIdentity: + issuer: str + request_signer: Ed25519PrivateKey + statement_verifier: Ed25519PublicKey + + +@dataclass(frozen=True, repr=False) +class WorkerRoutes: + _channels: Mapping[UUID, WorkerReadChannel] + _profiles: Mapping[tuple[UUID, str, str], WorkerProfile] + _enrollment: Mapping[UUID, _EnrollmentIdentity] + + def get(self, worker_id: UUID) -> WorkerReadChannel | None: + return self._channels.get(worker_id) + + def profile(self, worker_id: UUID, org: str, profile_digest: str) -> WorkerProfile | None: + return self._profiles.get((worker_id, org, profile_digest)) + + def permits( + self, worker_id: UUID, org: str, profile_digest: str, mode: WorkerMode, team: bool + ) -> bool: + profile = self.profile(worker_id, org, profile_digest) + return profile is not None and mode in profile.modes and (not team or profile.team_access) + + def enrollment_route( + self, worker_id: UUID, org: str, namespace: str, profile_digest: str, generation: int + ) -> EnrollmentRoute | None: + identity = self._enrollment.get(worker_id) + channel = self.get(worker_id) + if ( + identity is None + or channel is None + or self.profile(worker_id, org, profile_digest) is None + or type(generation) is not int + or generation <= 0 + ): + return None + return EnrollmentRoute( + org, + namespace, + worker_id, + profile_digest, + generation, + identity.issuer, + identity.request_signer, + identity.statement_verifier, + channel, + ) + + +@asynccontextmanager +async def open_worker_routes(routes: tuple[WorkerRoute, ...]) -> AsyncIterator[WorkerRoutes]: + """Create one bounded client pool per configured worker and close them on shutdown.""" + if len(routes) > _MAX_WORKERS or len({route.worker_id for route in routes}) != len(routes): + raise ValueError("invalid source worker route count") + for route in routes: + route._validate() + async with AsyncExitStack() as stack: + channels = {} + profiles = {} + enrollment = {} + for route in routes: + channel = WorkerReadChannel( + worker_id=route.worker_id, + origin=route.tls_origin, + issuer=route.issuer, + signing_key=route.grant_key, + grant_seconds=live_grant_seconds(settings.knowledge_source_worker_live_timeout_s), + max_response_bytes=_MAX_WORKER_RESPONSE_BYTES, + max_inflight=route.max_live_requests, + tls=route.tls, + ) + stack.push_async_callback(channel.close) + channels[route.worker_id] = channel + for profile in route.profiles: + profiles[(route.worker_id, profile.org, profile.digest)] = profile + if route.enrollment_verifier is not None: + enrollment[route.worker_id] = _EnrollmentIdentity( + route.issuer, route.grant_key, route.enrollment_verifier + ) + yield WorkerRoutes( + MappingProxyType(channels), MappingProxyType(profiles), MappingProxyType(enrollment) + ) diff --git a/server/knowledge/app/mcp_worker_runtime.py b/server/knowledge/app/mcp_worker_runtime.py new file mode 100644 index 00000000000..bb7eccafacc --- /dev/null +++ b/server/knowledge/app/mcp_worker_runtime.py @@ -0,0 +1,45 @@ +"""Start and stop the process-owned directory for provisioned source workers.""" + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass +from pathlib import Path + +from server.core import pg +from server.knowledge.app.mcp_worker_pg_directory import live_directory +from server.knowledge.app.mcp_worker_protected import LiveSourceDirectory +from server.knowledge.app.mcp_worker_route_config import load_worker_routes +from server.knowledge.app.mcp_worker_routes import WorkerRoutes, open_worker_routes + + +@dataclass(frozen=True, repr=False) +class _SourceWorkerRuntime: + routes: WorkerRoutes + directory: LiveSourceDirectory + + +_runtime: _SourceWorkerRuntime | None = None + + +def current_directory() -> LiveSourceDirectory | None: + return _runtime.directory if pg.enabled() and _runtime is not None else None + + +def current_routes() -> WorkerRoutes | None: + return _runtime.routes if pg.enabled() and _runtime is not None else None + + +@asynccontextmanager +async def source_worker_runtime(path: str) -> AsyncIterator[None]: + global _runtime + if not path or not pg.enabled(): + yield + return + async with open_worker_routes(load_worker_routes(Path(path))) as routes: + if _runtime is not None: + raise RuntimeError("source worker directory already running") + _runtime = _SourceWorkerRuntime(routes, live_directory(routes)) + try: + yield + finally: + _runtime = None diff --git a/server/knowledge/app/mcp_worker_selection.py b/server/knowledge/app/mcp_worker_selection.py new file mode 100644 index 00000000000..7ef39c2dbf9 --- /dev/null +++ b/server/knowledge/app/mcp_worker_selection.py @@ -0,0 +1,122 @@ +"""Verify access to every chosen identity without importing its content.""" + +from __future__ import annotations + +import asyncio +import time +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from typing import TYPE_CHECKING +from uuid import UUID + +from server.core.diagnostics import private_work +from server.knowledge.app.mcp_worker_read import WorkerReadRefused, WorkerReadScope +from server.knowledge.domain.mcp_identity import ResourceIdentity, selection_sha256 +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection +from server.knowledge.domain.mcp_worker_setup import ( + VerifiedSelectionGrant, + WorkerMode, + WorkerSetupRejected, + checked_worker_selection, +) +from server.settings import settings + +if TYPE_CHECKING: + from server.knowledge.app.mcp_worker_read import WorkerReadChannel + +# not a setting: a selection proof can authorize setup only in its issuance window +_EVIDENCE_SECONDS = 30 + + +@dataclass(frozen=True, repr=False) +class SelectionAuthority: + org: str + namespace: str + destination_id: UUID + source_id: UUID + selection_generation: int + approval_generation: int + connection: ReaderConnection + + def scope(self, item: ResourceIdentity) -> WorkerReadScope: + account = self.connection + return WorkerReadScope( + worker_id=account.worker_id, + org=self.org, + namespace=self.namespace, + source_id=self.source_id, + selection_generation=self.selection_generation, + requester=account.owner, + connection_id=account.connection_id, + connection_generation=account.connection_generation, + profile_digest=account.profile_digest, + approval_generation=self.approval_generation, + resource_id=item.id, + ) + + +async def verify_worker_selection( + authority: SelectionAuthority, + items: tuple[ResourceIdentity, ...], + *, + mode: WorkerMode, + channel: WorkerReadChannel, + current: Callable[[], Awaitable[SelectionAuthority | None]], + deadline: float, +) -> VerifiedSelectionGrant: + try: + items = checked_worker_selection(items, mode) + except WorkerSetupRejected: + raise WorkerReadRefused("denied") from None + started = int(time.time()) + with private_work(): + try: + async with asyncio.timeout_at(deadline): + confirmed = await _check_all(authority, items, channel, current) + except TimeoutError: + raise WorkerReadRefused("timeout") from None + if confirmed >= started + _EVIDENCE_SECONDS: + raise WorkerReadRefused("timeout") + return VerifiedSelectionGrant( + authority.org, + authority.connection, + authority.approval_generation, + selection_sha256(items), + confirmed, + started + _EVIDENCE_SECONDS, + authority.namespace, + authority.destination_id, + authority.source_id, + authority.selection_generation, + ) + + +async def _check_all( + expected: SelectionAuthority, + items: tuple[ResourceIdentity, ...], + channel: WorkerReadChannel, + current: Callable[[], Awaitable[SelectionAuthority | None]], +) -> int: + async def verify(item: ResourceIdentity) -> None: + scope = expected.scope(item) + + async def require_current() -> WorkerReadScope: + if await current() != expected: + raise WorkerReadRefused("denied") + return scope + + await channel.run(scope, "check_access", require_current=require_current) + + parallelism = settings.knowledge_source_worker_selection_parallelism + for start in range(0, len(items), parallelism): + pending = [asyncio.create_task(verify(item)) for item in items[start : start + parallelism]] + try: + await asyncio.gather(*pending) + finally: + for task in pending: + if not task.done(): + task.cancel() + await asyncio.gather(*pending, return_exceptions=True) + if await current() != expected: + raise WorkerReadRefused("denied") + return int(time.time()) diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index 8fee1583e68..d168e0e7cda 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -39,7 +39,7 @@ from server.auth.personal_namespace import is_own_namespace from server.auth.sharing import is_collection from server.clients._checked_access import Credential -from server.core import ch, leases, request_work +from server.core import ch, leases, pg, request_work from server.core.ch import sequential_reads from server.core.datetimes import as_aware_utc from server.core.diagnostics import private_work @@ -82,6 +82,7 @@ from server.knowledge.domain import sources as domain from server.knowledge.domain.source_links import parse_links from server.knowledge.domain.sources import KnowledgeSource +from server.knowledge.store import pg_source_lock from server.knowledge.store import sources as store from server.operations.base import Role from server.settings import settings @@ -603,6 +604,7 @@ async def sources_lease( (LeaseUnavailable), never writes unlocked.""" # The TTL outlives the few reads and inserts of one write with room to spare (a # holder that dies is taken over after it). + end = time.monotonic() + wait_s async with leases.holding( _sources_lease_name(org, namespace), ttl_s=60.0, wait_s=wait_s, ch=ch ) as held: @@ -610,7 +612,14 @@ async def sources_lease( raise OverloadedError( f"another change to the document sources of {namespace!r} is running; retry" ) - yield + if not pg.enabled(): + yield + return + # Live source frames hold this lock shared while they hand off a source's bytes. + # The lease wait and the lock wait share one wait_s (see pg_source_lock). + remaining = max(0.0, end - time.monotonic()) + async with pg_source_lock.exclusive(org, namespace, wait_s=remaining): + yield async def _require_free(org: str, namespace: str, name: str, *, owner_subject: str = "") -> None: diff --git a/server/knowledge/domain/mcp_identity.py b/server/knowledge/domain/mcp_identity.py new file mode 100644 index 00000000000..7d50eb16204 --- /dev/null +++ b/server/knowledge/domain/mcp_identity.py @@ -0,0 +1,68 @@ +"""Stable document addresses for opaque selected identities; no fetching or authority.""" + +from __future__ import annotations + +import hashlib +import json +import unicodedata +from typing import Annotated, Literal +from uuid import UUID + +from pydantic import AfterValidator, BaseModel, ConfigDict, Field + +from server.knowledge.domain.sources import mirror_uri + + +def _identifier(value: str) -> str: + if ( + not value.strip() + or len(value.encode("utf-8")) > 2048 + or any(unicodedata.category(char) == "Cc" for char in value) + ): + raise ValueError("invalid resource identifier") + return value + + +class ResourceIdentity(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True, strict=True, hide_input_in_errors=True) + + type: Literal["resource"] + id: Annotated[str, Field(min_length=1, max_length=2048), AfterValidator(_identifier)] + + +def selection_sha256(resources: tuple[ResourceIdentity, ...]) -> str: + """Hash ordered exact resource IDs without URL or Unicode normalization.""" + payload = json.dumps( + [resource.id for resource in resources], ensure_ascii=False, separators=(",", ":") + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +class MCPIdentityError(ValueError): + """Invalid identity input is never included in the public error.""" + + def __init__(self) -> None: + super().__init__("MCP_RESOURCE_IDENTITY_INVALID") + + +def resource_digest(resource_id: str) -> str: + """Hash exact UTF-8 identity bytes, without interpreting URLs or normalizing text.""" + try: + identity = ResourceIdentity(type="resource", id=resource_id) + return hashlib.sha256(identity.id.encode("utf-8")).hexdigest() + except (ValueError, TypeError, UnicodeError): + raise MCPIdentityError() from None + + +def resource_uri(source_id: str, resource_id: str) -> str: + """Use the existing source-copy suffix; the source registration binds the account. + + A connection reconfiguration must allocate a new source ID. This address grants + no read access and is never an outbound fetch target or an upstream citation. + """ + try: + if not isinstance(source_id, str) or str(UUID(source_id)) != source_id: + raise MCPIdentityError() + return mirror_uri("mcp-resource:" + resource_digest(resource_id), source_id) + except (ValueError, TypeError, AttributeError): + raise MCPIdentityError() from None diff --git a/server/knowledge/domain/mcp_worker_permissions.py b/server/knowledge/domain/mcp_worker_permissions.py new file mode 100644 index 00000000000..99fae63fae4 --- /dev/null +++ b/server/knowledge/domain/mcp_worker_permissions.py @@ -0,0 +1,115 @@ +"""Read policy for stored MCP copies, separate from worker I/O and signature verification.""" + +import re +from dataclasses import dataclass +from uuid import UUID + +_SHA256 = re.compile(r"[0-9a-f]{64}") + + +@dataclass(frozen=True, repr=False) +class StoredCopyRevision: + org: str + namespace: str + source_id: UUID + selection_generation: int + resource_id_sha256: str + revision_id: UUID + content_sha256: str + + +@dataclass(frozen=True, repr=False) +class ReaderConnection: + owner: str + worker_id: UUID + connection_id: UUID + connection_generation: int + profile_digest: str + + +@dataclass(frozen=True, repr=False) +class VerifiedWorkerReadEvidence: + """Internal receipt minted by core, never decoded from public request data. + + Core authenticates the approved worker's response and binds it to the + read challenge for this requester, connection, and stored revision. The + content digest comes from the confirmed result, not from the challenge. + """ + + confirmed_revision: StoredCopyRevision + connection: ReaderConnection + issued_at: int + confirmed_at: int + expires_at: int + + +def _known_identity(value: str) -> bool: + return isinstance(value, str) and value not in ("", "-") and value == value.strip() + + +def _known_uuid(value: UUID) -> bool: + return isinstance(value, UUID) and value.int != 0 + + +def _positive_int(value: int) -> bool: + return type(value) is int and value > 0 + + +def _known_digest(value: str) -> bool: + return isinstance(value, str) and _SHA256.fullmatch(value) is not None + + +def can_read_stored_copy( + *, + collection_granted: bool | None, + requester: str | None, + current_revision: StoredCopyRevision | None, + active_connection: ReaderConnection | None, + evidence: VerifiedWorkerReadEvidence | None, + now: int, + max_evidence_age_seconds: int, +) -> bool: + """Authorize only the current copy and only for the authenticated requester. + + Core supplies current authority: a selected and readable revision, the + requester's own approved active connection for the source, and evidence + not superseded by a denial or revocation. Unknown state is passed as None. + Times are UTC epoch seconds. False must exclude the copy, not change its mode. + """ + if ( + collection_granted is not True + or requester is None + or not _known_identity(requester) + or current_revision is None + or active_connection is None + or not isinstance(evidence, VerifiedWorkerReadEvidence) + or active_connection.owner != requester + or current_revision != evidence.confirmed_revision + or active_connection != evidence.connection + ): + return False + + if not ( + _known_identity(current_revision.org) + and _known_identity(current_revision.namespace) + and _known_uuid(current_revision.source_id) + and _positive_int(current_revision.selection_generation) + and _known_digest(current_revision.resource_id_sha256) + and _known_uuid(current_revision.revision_id) + and _known_digest(current_revision.content_sha256) + and _known_uuid(active_connection.worker_id) + and _known_uuid(active_connection.connection_id) + and _positive_int(active_connection.connection_generation) + and _known_digest(active_connection.profile_digest) + ): + return False + + return ( + _positive_int(max_evidence_age_seconds) + and _positive_int(now) + and _positive_int(evidence.issued_at) + and _positive_int(evidence.confirmed_at) + and _positive_int(evidence.expires_at) + and evidence.issued_at <= evidence.confirmed_at <= now < evidence.expires_at + and evidence.expires_at - evidence.issued_at <= max_evidence_age_seconds + ) diff --git a/server/knowledge/domain/mcp_worker_setup.py b/server/knowledge/domain/mcp_worker_setup.py new file mode 100644 index 00000000000..4e960c064af --- /dev/null +++ b/server/knowledge/domain/mcp_worker_setup.py @@ -0,0 +1,333 @@ +"""Plan external worker setup from current core authority, without I/O.""" + +from dataclasses import dataclass +from hashlib import sha256 +from hmac import compare_digest +from json import dumps +from typing import Literal +from uuid import UUID + +from server.knowledge.domain.mcp_identity import ResourceIdentity, selection_sha256 +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection +from server.knowledge.domain.mcp_worker_source import WORKER_SOURCE_VERSION, WorkerSourceConfig + +MAX_SETUP_RESOURCES = 1000 # not a setting: bounds one source selection across modes +_MAX_SETUP_ID_BYTES = 1024 # not a setting: bounds the encoded identity in a selection +MAX_SETUP_SELECTION_BYTES = 128 * 1024 # not a setting: bounds the stored selection payload +# not a setting: the verifier never accepts a setup proof older than this +MAX_SELECTION_GRANT_AGE_SECONDS = 300 + +type WorkerMode = Literal["live", "snapshot", "selected_refresh"] +type ReaderPolicy = Literal["owner_only", "current_team_access"] + + +class WorkerSetupRejected(ValueError): + """A setup input or current authority does not allow this plan.""" + + +@dataclass(frozen=True, slots=True, repr=False) +class SetupCaller: + org: str + subject: str + agent: str + + +@dataclass(frozen=True, slots=True, repr=False) +class SetupDestination: + """Current ordinary destination and resolved, inherited-or-direct grants.""" + + org: str + namespace: str + destination_id: UUID + kind: Literal["automatic_personal", "private", "team"] + generation: int + grant_generation: int + grantee: SetupCaller + ordinary: bool + can_write: bool + team_approved: bool = False + personal_owner: str | None = None + + +@dataclass(frozen=True, slots=True, repr=False) +class ApprovedWorkerAccount: + """Core's account and current worker/profile approval, not discovery claims. + + Approved modes cover owner reads; team checks cover a separate reader's account. + """ + + org: str + connection: ReaderConnection + approval_generation: int + active: bool + modes: frozenset[WorkerMode] + verified_resource_space: str | None = None + exact_reader_checks: bool = False + explicit_deletion_checks: bool = False + + +@dataclass(frozen=True, slots=True, repr=False) +class VerifiedSelectionGrant: + """Core-verified current access to every exact item via the owner's account.""" + + org: str + connection: ReaderConnection + approval_generation: int + resources_sha256: str + confirmed_at: int + expires_at: int + namespace: str + destination_id: UUID + source_id: UUID + selection_generation: int + + +@dataclass(frozen=True, slots=True, repr=False) +class SetupState: + """Resolve afresh in core; generations must advance even on revoke and restore. + + Resolve the source ID and selection generation for this owner and destination. + Pass no grant if its evidence is absent or superseded by denial or revocation. + """ + + caller: SetupCaller + destination: SetupDestination + account: ApprovedWorkerAccount + selection_grant: VerifiedSelectionGrant | None + source_id: UUID + selection_generation: int + policy_generation: int + now: int + store_qualified: bool = False + erasure_qualified: bool = False + + +@dataclass(frozen=True, slots=True, repr=False) +class SetupIntent: + selection: tuple[ResourceIdentity, ...] + mode: WorkerMode + interval_seconds: int | None = None + share_with_team: bool = False + + +@dataclass(frozen=True, slots=True) +class SetupPreview: + """Team reads use each reader's own approved account in the verified realm.""" + + reader_policy: ReaderPolicy + stores_copy: bool + scheduled_refresh: bool + checks_explicit_deletion: bool + expires_at: int + requires_collection_grant: Literal[True] = True + requires_exact_reader_evidence: Literal[True] = True + syncs_upstream_acls: Literal[False] = False + writes_memory: Literal[False] = False + + +@dataclass(frozen=True, slots=True, repr=False) +class WorkerSetupPlan: + caller: SetupCaller + namespace: str + destination_id: UUID + source_id: UUID + config: WorkerSourceConfig + selection: tuple[ResourceIdentity, ...] + preview: SetupPreview + fingerprint: str + + +def _known(value: str | None) -> bool: + return isinstance(value, str) and value not in ("", "-") and value == value.strip() + + +def _positive(value: int) -> bool: + return type(value) is int and value > 0 + + +def _nonzero(value: UUID) -> bool: + return isinstance(value, UUID) and value.int != 0 + + +def _require_authority(state: SetupState) -> None: + caller, destination, account = state.caller, state.destination, state.account + if not ( + _known(caller.org) + and _known(caller.subject) + and _known(caller.agent) + and caller.org == destination.org == account.org + and caller.subject == account.connection.owner + and destination.grantee == caller + and _known(destination.namespace) + and _nonzero(destination.destination_id) + and _nonzero(state.source_id) + and destination.ordinary is True + and destination.can_write is True + and destination.kind in ("automatic_personal", "private", "team") + and ( + destination.kind != "automatic_personal" or destination.personal_owner == caller.subject + ) + and account.active is True + and _positive(destination.generation) + and _positive(destination.grant_generation) + and _positive(account.approval_generation) + and _positive(state.policy_generation) + ): + raise WorkerSetupRejected("authority_unavailable") + + +def checked_worker_selection( + selection: tuple[ResourceIdentity, ...], mode: WorkerMode +) -> tuple[ResourceIdentity, ...]: + if not isinstance(selection, tuple) or not 0 < len(selection) <= MAX_SETUP_RESOURCES: + raise WorkerSetupRejected("invalid_selection") + try: + items = tuple(ResourceIdentity.model_validate(resource) for resource in selection) + if len({item.id for item in items}) != len(items) or ( + 1 + len(items) + sum(len(item.model_dump_json().encode()) for item in items) + > MAX_SETUP_SELECTION_BYTES + ): + raise WorkerSetupRejected("invalid_selection") + if mode == "selected_refresh" and any( + not item.id.isprintable() or len(item.id.encode()) > _MAX_SETUP_ID_BYTES + for item in items + ): + raise WorkerSetupRejected("invalid_selection") + except ValueError: + raise WorkerSetupRejected("invalid_selection") from None + return items + + +def _require_selection_grant(state: SetupState, resources_digest: str) -> VerifiedSelectionGrant: + grant = state.selection_grant + if not ( + isinstance(grant, VerifiedSelectionGrant) + and grant.org == state.caller.org + and grant.connection == state.account.connection + and grant.approval_generation == state.account.approval_generation + and grant.resources_sha256 == resources_digest + and grant.namespace == state.destination.namespace + and grant.destination_id == state.destination.destination_id + and grant.source_id == state.source_id + and grant.selection_generation == state.selection_generation + and _positive(state.now) + and _positive(grant.confirmed_at) + and _positive(grant.expires_at) + and grant.confirmed_at <= state.now < grant.expires_at + and grant.expires_at - grant.confirmed_at <= MAX_SELECTION_GRANT_AGE_SECONDS + ): + raise WorkerSetupRejected("selection_unverified") + return grant + + +def _reader_policy(state: SetupState, intent: SetupIntent) -> ReaderPolicy: + if type(intent.share_with_team) is not bool: + raise WorkerSetupRejected("invalid_setup") + if not intent.share_with_team or state.destination.kind == "automatic_personal": + return "owner_only" + if not ( + state.destination.kind == "team" + and state.destination.team_approved is True + and state.account.exact_reader_checks is True + and _known(state.account.verified_resource_space) + ): + raise WorkerSetupRejected("team_unavailable") + return "current_team_access" + + +def plan_worker_setup(state: SetupState, intent: SetupIntent) -> WorkerSetupPlan: + """Preview requirements, not a grant to a collection reader or a write.""" + _require_authority(state) + if ( + intent.mode not in ("live", "snapshot", "selected_refresh") + or intent.mode not in state.account.modes + ): + raise WorkerSetupRejected("unsupported_mode") + stores_copy = intent.mode != "live" + if stores_copy and not (state.store_qualified is True and state.erasure_qualified is True): + raise WorkerSetupRejected("storage_unqualified") + reader_policy = _reader_policy(state, intent) + items = checked_worker_selection(intent.selection, intent.mode) + resources_digest = selection_sha256(items) + grant = _require_selection_grant(state, resources_digest) + binding = state.account.connection + try: + config = WorkerSourceConfig( + version=WORKER_SOURCE_VERSION, + worker_id=binding.worker_id, + profile_digest=binding.profile_digest, + approval_generation=state.account.approval_generation, + owner_connection_id=binding.connection_id, + owner_connection_generation=binding.connection_generation, + selection_generation=state.selection_generation, + mode=intent.mode, + reader_policy=reader_policy, + interval_seconds=intent.interval_seconds, + ) + except ValueError: + raise WorkerSetupRejected("invalid_setup") from None + scheduled = intent.mode == "selected_refresh" + preview = SetupPreview( + reader_policy=reader_policy, + stores_copy=stores_copy, + scheduled_refresh=scheduled, + checks_explicit_deletion=scheduled and state.account.explicit_deletion_checks is True, + expires_at=grant.expires_at, + ) + caller, destination = state.caller, state.destination + fingerprint = sha256( + dumps( + ( + "mcp-worker-setup-v1", + caller.org, + caller.subject, + caller.agent, + destination.namespace, + str(destination.destination_id), + destination.kind, + destination.generation, + destination.grant_generation, + str(state.source_id), + state.policy_generation, + state.account.approval_generation, + state.account.verified_resource_space, + config.model_dump(mode="json"), + resources_digest, + intent.share_with_team, + preview.checks_explicit_deletion, + grant.confirmed_at, + grant.expires_at, + ), + separators=(",", ":"), + sort_keys=True, + ).encode() + ).hexdigest() + return WorkerSetupPlan( + caller, + destination.namespace, + destination.destination_id, + state.source_id, + config, + items, + preview, + fingerprint, + ) + + +def confirm_worker_setup( + expected_fingerprint: str, *, state: SetupState, intent: SetupIntent +) -> WorkerSetupPlan: + """Revalidate before mutation; the fingerprint is only an equality precondition. + + Use the returned plan, not submitted preview fields. The mutation must be + fenced against changes to the current inputs used here. + """ + plan = plan_worker_setup(state, intent) + if not ( + isinstance(expected_fingerprint, str) + and len(expected_fingerprint) == 64 + and expected_fingerprint.isascii() + and compare_digest(plan.fingerprint, expected_fingerprint) + ): + raise WorkerSetupRejected("stale_preview") + return plan diff --git a/server/knowledge/domain/mcp_worker_source.py b/server/knowledge/domain/mcp_worker_source.py new file mode 100644 index 00000000000..76a755c9eda --- /dev/null +++ b/server/knowledge/domain/mcp_worker_source.py @@ -0,0 +1,130 @@ +"""Opaque worker registrations in the existing source registry.""" + +from __future__ import annotations + +from typing import Annotated, Literal, Self +from uuid import UUID + +from pydantic import BaseModel, ConfigDict, Field, StringConstraints, TypeAdapter, model_validator + +from server.knowledge.domain.mcp_identity import ResourceIdentity +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource + +WORKER_SOURCE_VERSION = 2 +WORKER_REGISTRATION = "worker_registration" +_MAX_CONFIG_BYTES = 16_384 # not a setting: bounds a stored worker source registration +_MAX_SELECTION_BYTES = 131_072 # not a setting: bounds a stored worker source selection +_Generation = Annotated[int, Field(ge=1, le=2**63 - 1)] +_Digest = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] +_Items: TypeAdapter[tuple[ResourceIdentity, ...]] = TypeAdapter( + Annotated[tuple[ResourceIdentity, ...], Field(min_length=1, max_length=1000)] +) + + +class WorkerSourceRefused(ValueError): + """A source is not a supported current worker registration.""" + + +class WorkerSourceConfig(BaseModel): + model_config = ConfigDict(extra="forbid", strict=True, frozen=True, hide_input_in_errors=True) + + version: Annotated[int, Field(ge=2, le=2)] + worker_id: UUID + profile_digest: _Digest + approval_generation: _Generation + owner_connection_id: UUID + owner_connection_generation: _Generation + selection_generation: _Generation + mode: Literal["live", "snapshot", "selected_refresh"] + reader_policy: Literal["owner_only", "current_team_access"] + interval_seconds: Annotated[int, Field(ge=300, le=86_400)] | None = None + paused: bool = False + + @model_validator(mode="after") + def _check_mode(self) -> Self: + if ( + (self.interval_seconds is None) == (self.mode == "selected_refresh") + or self.worker_id.int == 0 + or self.owner_connection_id.int == 0 + ): + raise ValueError("invalid worker source mode or binding") + return self + + +def _matches_row(source: KnowledgeSource, config: WorkerSourceConfig) -> bool: + try: + return ( + UUID(source.source_id).int != 0 + and str(UUID(source.source_id)) == source.source_id + and source.connection_id == str(config.owner_connection_id) + ) + except (ValueError, AttributeError): + return False + + +def encode_worker_source( + *, + org: str, + namespace: str, + name: str, + source_id: UUID, + owner: str, + config: WorkerSourceConfig, + selection: tuple[ResourceIdentity, ...], +) -> KnowledgeSource: + """Encode an authorized registration without an upstream credential or endpoint.""" + if not org or not namespace or not owner or owner == "-" or not name: + raise WorkerSourceRefused("worker source unavailable") + if source_id.int == 0: + raise WorkerSourceRefused("worker source unavailable") + try: + items = _Items.validate_python(selection, strict=True) + row = KnowledgeSource( + org=org, + namespace=namespace, + name=name, + kind="mcp", + source_id=str(source_id), + access=MIRRORED_ACCESS, + credential_mode="worker", + owner_subject=owner, + created_by=owner, + connection_id=str(config.owner_connection_id), + config={WORKER_REGISTRATION: config.model_dump_json()}, + items=[item.model_dump(mode="json") for item in items], + ) + decode_worker_source(row) + return row + except (ValueError, TypeError, RecursionError): + raise WorkerSourceRefused("worker source unavailable") from None + + +def decode_worker_source( + source: KnowledgeSource, +) -> tuple[WorkerSourceConfig, tuple[ResourceIdentity, ...]]: + if ( + source.kind != "mcp" + or source.credential_mode != "worker" + or source.access != MIRRORED_ACCESS + or source.active is not True + or source.pending_delete + or not source.owner_subject + or source.credential_enc + or source.secret_enc + or set(source.config) != {WORKER_REGISTRATION} + or not 0 < len(source.items) <= 1000 + ): + raise WorkerSourceRefused("worker source unavailable") + try: + payload = source.config[WORKER_REGISTRATION] + if not isinstance(payload, str) or len(payload.encode("utf-8")) > _MAX_CONFIG_BYTES: + raise WorkerSourceRefused("worker source unavailable") + config = WorkerSourceConfig.model_validate_json(payload) + items = _Items.validate_python(tuple(source.items), strict=True) + if len(_Items.dump_json(items)) > _MAX_SELECTION_BYTES: + raise WorkerSourceRefused("worker source unavailable") + if not _matches_row(source, config) or len({item.id for item in items}) != len(items): + raise WorkerSourceRefused("worker source unavailable") + return config, items + except (ValueError, TypeError, RecursionError): + raise WorkerSourceRefused("worker source unavailable") from None diff --git a/server/knowledge/domain/sources.py b/server/knowledge/domain/sources.py index 7686cb3b06f..e7735239b07 100644 --- a/server/knowledge/domain/sources.py +++ b/server/knowledge/domain/sources.py @@ -557,7 +557,7 @@ def include_in(config: dict[str, Any]) -> list[str]: def options_in(kind: str, config: dict[str, Any]) -> dict[str, Any]: """The options alone of a config, without the ids its items came from.""" - if kind == "recording": + if kind in {"recording", "mcp"}: return config return {"include": include_in(config)} if kind == "gdrive" else {} diff --git a/server/knowledge/store/pg_mcp_worker_approvals.py b/server/knowledge/store/pg_mcp_worker_approvals.py new file mode 100644 index 00000000000..b39685277dc --- /dev/null +++ b/server/knowledge/store/pg_mcp_worker_approvals.py @@ -0,0 +1,164 @@ +"""Store approvals of opaque worker profiles on one collection scope.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from server.core import pg + +if TYPE_CHECKING: + from collections.abc import AsyncIterator + from uuid import UUID + + from asyncpg import Connection, Record + + from server.knowledge.domain.mcp_worker_setup import WorkerMode + from server.knowledge.store.pg_mcp_worker_enrollment import WriteOrigin + +LIVE = 1 +SNAPSHOT = 2 +REFRESH = 4 +_ALL_MODES = LIVE | SNAPSHOT | REFRESH + + +@dataclass(frozen=True, repr=False) +class ApprovalKey: + org: str + namespace: str + worker_id: UUID + profile_digest: str + + def arguments(self) -> tuple[str, str, UUID, str]: + return self.org, self.namespace, self.worker_id, self.profile_digest + + +@dataclass(frozen=True, repr=False) +class ApprovalOwner: + user_id: str + origin: WriteOrigin + + +@dataclass(frozen=True, repr=False) +class WorkerApproval: + generation: int + modes: int + team_access: bool + active: bool + + +_SCOPE = "org = $1 AND namespace = $2 AND worker_id = $3 AND profile_digest = $4" +_FIELDS = "generation, modes, team_access, active" +_CURRENT = f"SELECT {_FIELDS} FROM loom.mcp_worker_approvals WHERE {_SCOPE}" +_CREATE = """ +INSERT INTO loom.mcp_worker_approvals + (org, namespace, worker_id, profile_digest, modes, team_access, + user_id, agent, session_id, actor, source_class, active, generation) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, true, + nextval('loom.mcp_worker_approval_generations')) +ON CONFLICT (org, namespace, worker_id, profile_digest) DO NOTHING +RETURNING generation, modes, team_access, active +""" +_REPLACE = f""" +UPDATE loom.mcp_worker_approvals +SET modes = $5::smallint, team_access = $6, user_id = $7, agent = $8, session_id = $9, + actor = $10, source_class = $11, active = ($5::smallint > 0), + generation = nextval('loom.mcp_worker_approval_generations') +WHERE {_SCOPE} AND generation = $12 +RETURNING {_FIELDS} +""" + + +def _result(row: Record | None) -> WorkerApproval | None: + if row is None: + return None + return WorkerApproval(row["generation"], row["modes"], row["team_access"], row["active"]) + + +async def current_on( + conn: Connection, key: ApprovalKey, *, lock: bool = False +) -> WorkerApproval | None: + """The caller uses a transaction for a read it will rely on during a write.""" + if not pg.enabled(): + return None + if lock and not conn.is_in_transaction(): + raise RuntimeError("worker approval lock requires an authority transaction") + query = _CURRENT + " FOR SHARE" if lock else _CURRENT + return _result(await conn.fetchrow(query, *key.arguments())) + + +async def current_generation( + org: str, namespace: str, worker_id: UUID, digest: str, mode: WorkerMode, team_reader: bool +) -> int | None: + if not pg.enabled(): + return None + key = ApprovalKey(org, namespace, worker_id, digest) + approval = _result(await pg.fetchrow(_CURRENT, *key.arguments())) + required = {"live": LIVE, "snapshot": SNAPSHOT, "selected_refresh": REFRESH}.get(mode, 0) + if ( + approval is None + or not approval.active + or not (approval.modes & required) + or (team_reader and not approval.team_access) + ): + return None + return approval.generation + + +async def replace_on( + conn: Connection, + key: ApprovalKey, + *, + expected_generation: int, + modes: int, + team_access: bool, + owner: ApprovalOwner, +) -> WorkerApproval | None: + """Change only the exact approval the authorized admin observed.""" + if not pg.enabled() or not conn.is_in_transaction(): + raise RuntimeError("worker approval requires an authority transaction") + if ( + type(modes) is not int + or not 0 <= modes <= _ALL_MODES + or type(expected_generation) is not int + or expected_generation < 0 + or (expected_generation == 0 and modes == 0) + or type(team_access) is not bool + or (not modes and team_access) + ): + return None + args = ( + *key.arguments(), + modes, + team_access, + owner.user_id, + owner.origin.agent, + owner.origin.session_id, + owner.origin.actor, + owner.origin.source_class, + ) + if expected_generation == 0: + return _result(await conn.fetchrow(_CREATE, *args)) + return _result(await conn.fetchrow(_REPLACE, *args, expected_generation)) + + +@asynccontextmanager +async def scope_transaction( + key: ApprovalKey, *, sources: bool = False +) -> AsyncIterator[Connection]: + """`sources` also holds the namespace's source lock shared, before the knowledge + lock, in the order source writes take them (`pg_source_lock`).""" + if not pg.enabled(): + raise RuntimeError("worker approval requires Postgres authority") + async with pg.transaction() as conn: + if sources: + await conn.execute( + f"SELECT pg_advisory_xact_lock_shared({pg.SOURCES_LOCK_KEY})", + key.org, + key.namespace, + ) + await conn.execute( + f"SELECT pg_advisory_xact_lock_shared({pg.KNOWLEDGE_LOCK_KEY})", key.org, key.namespace + ) + yield conn diff --git a/server/knowledge/store/pg_mcp_worker_enrollment.py b/server/knowledge/store/pg_mcp_worker_enrollment.py new file mode 100644 index 00000000000..a851be896e3 --- /dev/null +++ b/server/knowledge/store/pg_mcp_worker_enrollment.py @@ -0,0 +1,274 @@ +"""Opaque account enrollment under the caller's Postgres authority transaction.""" + +from __future__ import annotations + +from contextlib import asynccontextmanager +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from server.core import pg + +if TYPE_CHECKING: + from collections.abc import AsyncIterator + from uuid import UUID + + from asyncpg import Connection, Record + + +@dataclass(frozen=True, repr=False) +class AccountKey: + org: str + namespace: str + requester: str + worker_id: UUID + profile_digest: str + connection_id: UUID + + +@dataclass(frozen=True, repr=False) +class Challenge: + account: AccountKey + generation: int + nonce: UUID + issued_at: int + expires_at: int + + +@dataclass(frozen=True, repr=False) +class WriteOrigin: + agent: str + session_id: str + actor: str + source_class: str + + +@dataclass(frozen=True, repr=False) +class AccountState: + generation: int + active: bool + resource_space: str | None + + +_ACCOUNT_SCOPE = ( + "org = $1 AND namespace = $2 AND user_id = $3 AND worker_id = $4 " + "AND profile_digest = $5 AND connection_id = $6" +) + +_ISSUE = """ +INSERT INTO loom.mcp_worker_enrollment_challenges + (org, namespace, user_id, worker_id, profile_digest, connection_id, + generation, nonce, issued_at, expires_at, agent, session_id, actor, source_class) +SELECT $1::text, $2::text, $3::text, $4::uuid, $5::text, $6::uuid, $7::bigint, $8::uuid, + $9::bigint, $10::bigint, $11::text, $12::text, $13::text, $14::text +WHERE $9::bigint <= extract(epoch FROM statement_timestamp()) + AND $10::bigint > extract(epoch FROM statement_timestamp()) + AND NOT EXISTS ( + SELECT 1 FROM loom.mcp_worker_enrollment_challenges + WHERE org = $1 AND connection_id = $6 AND NOT consumed + AND expires_at > extract(epoch FROM statement_timestamp()) + ) +ON CONFLICT (org, nonce) DO NOTHING +RETURNING true +""" + +_LOCK = """ +SELECT pg_advisory_xact_lock(hashtextextended( + jsonb_build_array('mcp_worker_account'::text, $1::text, $2::uuid)::text, 0)) +""" + +_CONSUME = f""" +WITH claimed AS ( + UPDATE loom.mcp_worker_enrollment_challenges + SET consumed = true + WHERE {_ACCOUNT_SCOPE} AND generation = $7 AND nonce = $8 + AND issued_at = $9 AND expires_at = $10 AND NOT consumed + AND issued_at <= extract(epoch FROM statement_timestamp()) + AND expires_at > extract(epoch FROM statement_timestamp()) + RETURNING org, namespace, user_id, worker_id, profile_digest, connection_id, + generation, agent, session_id, actor, source_class +), written AS ( + INSERT INTO loom.mcp_worker_accounts AS account + (org, namespace, user_id, worker_id, profile_digest, connection_id, + generation, agent, session_id, actor, source_class, resource_space, active) + SELECT org, namespace, user_id, worker_id, profile_digest, connection_id, + generation, agent, session_id, actor, source_class, $11::text, true + FROM claimed + ON CONFLICT (org, connection_id) DO UPDATE SET + generation = EXCLUDED.generation, active = true, updated_at = clock_timestamp(), + agent = EXCLUDED.agent, session_id = EXCLUDED.session_id, + actor = EXCLUDED.actor, source_class = EXCLUDED.source_class + WHERE account.namespace = EXCLUDED.namespace AND account.user_id = EXCLUDED.user_id + AND account.worker_id = EXCLUDED.worker_id + AND account.profile_digest = EXCLUDED.profile_digest + AND account.resource_space IS NOT DISTINCT FROM EXCLUDED.resource_space + AND account.generation < EXCLUDED.generation + RETURNING true +) +SELECT EXISTS (SELECT FROM written) OR EXISTS ( + SELECT FROM loom.mcp_worker_accounts + WHERE {_ACCOUNT_SCOPE} AND generation = $7 AND active + AND resource_space IS NOT DISTINCT FROM $11 AND EXISTS (SELECT FROM claimed) +) +""" + +_GET = f""" +SELECT generation, active, resource_space FROM loom.mcp_worker_accounts +WHERE {_ACCOUNT_SCOPE} +""" + +_CURRENT_READER = """ +SELECT profile_digest, generation, active, resource_space FROM loom.mcp_worker_accounts +WHERE org = $1 AND user_id = $2 AND worker_id = $3 AND connection_id = $4 +""" + +_REVOKE = f""" +UPDATE loom.mcp_worker_accounts +SET active = false, updated_at = clock_timestamp(), + agent = $8, session_id = $9, actor = $10, source_class = $11 +WHERE {_ACCOUNT_SCOPE} AND generation = $7 AND active +RETURNING true +""" + +_PRUNE = """ +WITH expired AS ( + SELECT nonce FROM loom.mcp_worker_enrollment_challenges + WHERE org = $1 AND expires_at <= floor(extract(epoch FROM statement_timestamp()))::bigint + ORDER BY expires_at, nonce LIMIT 1000 FOR UPDATE SKIP LOCKED +), removed AS ( + DELETE FROM loom.mcp_worker_enrollment_challenges AS challenge USING expired + WHERE challenge.org = $1 AND challenge.nonce = expired.nonce RETURNING 1 +) +SELECT count(*) FROM removed +""" + + +def _account_args(account: AccountKey) -> tuple[str, str, str, UUID, str, UUID]: + return ( + account.org, + account.namespace, + account.requester, + account.worker_id, + account.profile_digest, + account.connection_id, + ) + + +def _challenge_args( + challenge: Challenge, +) -> tuple[str, str, str, UUID, str, UUID, int, UUID, int, int]: + return ( + *_account_args(challenge.account), + challenge.generation, + challenge.nonce, + challenge.issued_at, + challenge.expires_at, + ) + + +def _origin_args(origin: WriteOrigin) -> tuple[str, str, str, str]: + return origin.agent, origin.session_id, origin.actor, origin.source_class + + +def _require_transaction(conn: Connection) -> None: + if not pg.enabled() or not conn.is_in_transaction(): + raise RuntimeError("account enrollment requires an authority transaction") + + +async def lock_account(conn: Connection, account: AccountKey) -> None: + """Lock one account ID, including before its first write; use Read Committed.""" + _require_transaction(conn) + await conn.execute(_LOCK, account.org, account.connection_id) + + +async def issue_challenge(conn: Connection, challenge: Challenge, origin: WriteOrigin) -> bool: + """Insert a fresh server-generated nonce under current owner and approval fences.""" + _require_transaction(conn) + if not 0 < challenge.expires_at - challenge.issued_at <= 120 or challenge.issued_at < 0: + return False + await conn.execute(_LOCK, challenge.account.org, challenge.account.connection_id) + return (await conn.fetchval(_ISSUE, *_challenge_args(challenge), *_origin_args(origin))) is True + + +async def consume_challenge( + conn: Connection, challenge: Challenge, *, resource_space: str | None +) -> bool: + """Consume an authenticated binding and install its verified metadata atomically. + + The caller holds current owner, source and approval fences. A matched challenge + is spent even on an account conflict if the caller commits the refusal. + """ + await lock_account(conn, challenge.account) + return (await conn.fetchval(_CONSUME, *_challenge_args(challenge), resource_space)) is True + + +async def get_account(conn: Connection, account: AccountKey) -> AccountState | None: + """Read only the owner's exact account; inactive rows are generation fences.""" + if not pg.enabled(): + return None + row = await conn.fetchrow(_GET, *_account_args(account)) + if row is None: + return None + return AccountState(row["generation"], row["active"], row["resource_space"]) + + +async def current_reader_account( + org: str, owner: str, worker_id: UUID, connection_id: UUID +) -> tuple[str, AccountState] | None: + if not pg.enabled(): + return None + return _reader_account(await pg.fetchrow(_CURRENT_READER, org, owner, worker_id, connection_id)) + + +async def reader_account_on( + conn: Connection, + org: str, + owner: str, + worker_id: UUID, + connection_id: UUID, + *, + lock: bool = False, +) -> tuple[str, AccountState] | None: + if not pg.enabled(): + return None + if lock: + _require_transaction(conn) + query = _CURRENT_READER + " FOR SHARE NOWAIT" if lock else _CURRENT_READER + return _reader_account(await conn.fetchrow(query, org, owner, worker_id, connection_id)) + + +def _reader_account(row: Record | None) -> tuple[str, AccountState] | None: + if row is None: + return None + return row["profile_digest"], AccountState( + row["generation"], row["active"], row["resource_space"] + ) + + +async def revoke_account( + conn: Connection, account: AccountKey, *, generation: int, origin: WriteOrigin +) -> bool: + """Revoke the exact enrolled generation, retaining its fence against re-enrollment.""" + await lock_account(conn, account) + return ( + await conn.fetchval(_REVOKE, *_account_args(account), generation, *_origin_args(origin)) + ) is True + + +async def prune_expired_challenges(conn: Connection, org: str) -> int: + """Remove at most one org-scoped batch of expired challenges, never account fences.""" + _require_transaction(conn) + return int(await conn.fetchval(_PRUNE, org)) + + +@asynccontextmanager +async def owner_transaction(account: AccountKey) -> AsyncIterator[Connection]: + """Take the existing knowledge scope lock before the account enrollment lock.""" + if not pg.enabled(): + raise RuntimeError("account enrollment requires Postgres authority") + async with pg.transaction() as conn: + await conn.execute( + f"SELECT pg_advisory_xact_lock_shared({pg.KNOWLEDGE_LOCK_KEY})", + account.org, + account.namespace, + ) + yield conn diff --git a/server/knowledge/store/pg_mcp_worker_readers.py b/server/knowledge/store/pg_mcp_worker_readers.py new file mode 100644 index 00000000000..d35f01e0127 --- /dev/null +++ b/server/knowledge/store/pg_mcp_worker_readers.py @@ -0,0 +1,138 @@ +"""Keep each team reader's explicit enrollment tied to one source selection.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from server.core import pg +from server.knowledge.store.pg_mcp_worker_enrollment import WriteOrigin + +if TYPE_CHECKING: + from uuid import UUID + + from asyncpg import Connection, Record + + +@dataclass(frozen=True, repr=False) +class LinkKey: + org: str + namespace: str + source_id: UUID + requester: str + + def parameters(self) -> tuple[str, str, UUID, str]: + return self.org, self.namespace, self.source_id, self.requester + + +@dataclass(frozen=True, repr=False) +class Link: + selection_generation: int + connection_id: UUID + connection_generation: int + link_generation: int + active: bool + + +_SCOPE = "org = $1 AND namespace = $2 AND source_id = $3 AND user_id = $4" +_GET = f""" +SELECT selection_generation, connection_id, connection_generation, link_generation, active +FROM loom.mcp_worker_source_readers WHERE {_SCOPE} +""" +_INSERT = """ +INSERT INTO loom.mcp_worker_source_readers + (org, namespace, source_id, user_id, selection_generation, connection_id, + connection_generation, agent, session_id, actor, source_class, active, link_generation) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, true, + nextval('loom.mcp_worker_source_reader_generations')) +ON CONFLICT (org, namespace, source_id, user_id) DO NOTHING +RETURNING link_generation +""" +_REPLACE = f""" +UPDATE loom.mcp_worker_source_readers +SET selection_generation = $5, connection_id = $6, connection_generation = $7, + agent = $8, session_id = $9, actor = $10, source_class = $11, active = true, + link_generation = nextval('loom.mcp_worker_source_reader_generations') +WHERE {_SCOPE} AND link_generation = $12 AND selection_generation <= $5 +RETURNING link_generation +""" +_DISCONNECT = f""" +UPDATE loom.mcp_worker_source_readers +SET active = false, link_generation = nextval('loom.mcp_worker_source_reader_generations') +WHERE {_SCOPE} AND link_generation = $5 AND active +RETURNING link_generation +""" + + +async def current(key: LinkKey) -> Link | None: + if not pg.enabled(): + return None + return _link(await pg.fetchrow(_GET, *key.parameters())) + + +async def current_on(conn: Connection, key: LinkKey, *, lock: bool = False) -> Link | None: + if not pg.enabled(): + return None + if lock and not conn.is_in_transaction(): + raise RuntimeError("source reader lock requires an authority transaction") + query = _GET + " FOR SHARE NOWAIT" if lock else _GET + return _link(await conn.fetchrow(query, *key.parameters())) + + +def _link(row: Record | None) -> Link | None: + if row is None: + return None + return Link( + row["selection_generation"], + row["connection_id"], + row["connection_generation"], + row["link_generation"], + row["active"], + ) + + +async def set_on( + conn: Connection, + key: LinkKey, + *, + selection_generation: int, + connection_id: UUID, + connection_generation: int, + expected_link_generation: int, + origin: WriteOrigin, +) -> int | None: + """The caller holds the current source, worker profile, and account authorizations.""" + if not pg.enabled() or not conn.is_in_transaction(): + raise RuntimeError("source reader link requires an authority transaction") + generations = (selection_generation, connection_generation) + if not ( + all(type(value) is int and 0 < value < 2**63 for value in generations) + and type(expected_link_generation) is int + and 0 <= expected_link_generation < 2**63 + and connection_id.int != 0 + ): + return None + args = ( + *key.parameters(), + selection_generation, + connection_id, + connection_generation, + origin.agent, + origin.session_id, + origin.actor, + origin.source_class, + ) + if expected_link_generation == 0: + generation = await conn.fetchval(_INSERT, *args) + else: + generation = await conn.fetchval(_REPLACE, *args, expected_link_generation) + return int(generation) if type(generation) is int and generation > 0 else None + + +async def revoke_on(conn: Connection, key: LinkKey, *, expected_link_generation: int) -> bool: + if not pg.enabled() or not conn.is_in_transaction(): + raise RuntimeError("source reader unlink requires an authority transaction") + if type(expected_link_generation) is not int or not 0 < expected_link_generation < 2**63: + return False + generation = await conn.fetchval(_DISCONNECT, *key.parameters(), expected_link_generation) + return type(generation) is int diff --git a/server/knowledge/store/pg_source_lock.py b/server/knowledge/store/pg_source_lock.py new file mode 100644 index 00000000000..e132b82246f --- /dev/null +++ b/server/knowledge/store/pg_source_lock.py @@ -0,0 +1,58 @@ +"""The Postgres reader/writer lock of a namespace's source registry (`pg.SOURCES_LOCK_KEY`). + +Source writes hold it exclusively for as long as they hold `sources_lease`; a live +source frame holds it shared in its fence transaction while it rereads the source and +hands off its bytes. Postgres queues a new shared request behind a waiting exclusive +one, so a writer waits for the frames already running, never for a stream of new ones. +""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import asyncpg + +from server.core import pg +from server.core.errors import OverloadedError + + +@asynccontextmanager +async def exclusive(org: str, namespace: str, *, wait_s: float) -> AsyncIterator[None]: + """Hold the lock on one pooled connection for the block. Releasing the connection ends + it: the pool's reset unlocks every advisory lock and resets `lock_timeout`, + `statement_timeout` and the `tcp_keepalives_*` settings, so a cancelled block leaves + nothing held. Getting a pooled connection can wait up to the pool's own timeout on + top of `wait_s`.""" + wait_ms = max(1, int(wait_s * 1000)) + async with pg.connection() as conn: + try: + # The pool's statement timeout must not end the wait before lock_timeout does. + # The session holds the lock while it idles, so keepalives let Postgres drop it + # within about a minute if this replica's host disappears. + await conn.execute( + "SELECT set_config('lock_timeout', $1, false), " + "set_config('statement_timeout', $2, false), " + "set_config('tcp_keepalives_idle', '30', false), " + "set_config('tcp_keepalives_interval', '10', false), " + "set_config('tcp_keepalives_count', '3', false)", + f"{wait_ms}ms", + f"{wait_ms + 1000}ms", + ) + # The client timeout must outlast lock_timeout as well. + await conn.execute( + f"SELECT pg_advisory_lock({pg.SOURCES_LOCK_KEY})", + org, + namespace, + timeout=wait_ms / 1000 + 1, + ) + except asyncpg.LockNotAvailableError: + raise OverloadedError( + f"another change to the document sources of {namespace!r} is running; retry" + ) from None + except Exception as e: + # An outage answers 503, as pg.transaction does; anything else as it is. + if pg.is_outage(e): + raise pg.PostgresUnavailableError("Postgres did not answer") from e + raise + yield diff --git a/server/main.py b/server/main.py index 7de238e7476..60afb75bec5 100644 --- a/server/main.py +++ b/server/main.py @@ -33,7 +33,9 @@ from server.core.ch import get_client, probe_reader_user from server.core.errors import classified from server.core.logging_config import configure_logging +from server.core.operation_privacy import KNOWLEDGE_SOURCE_LIVE from server.insights.app.provider_barrier import participant_lifespan +from server.knowledge.app.mcp_worker_runtime import source_worker_runtime from server.memory.app import embedder_calibration from server.observability import get_emitter from server.operations.capabilities import operation_rows @@ -354,7 +356,10 @@ async def _with_repo_umask(target: FastAPI) -> AsyncIterator[None]: The previous umask comes back once the lifespan ends, after the inline workers stop or a failed start.""" with repo_umask(): - async with lifespan(target): + async with ( + source_worker_runtime(settings.knowledge_source_worker_routes_file), + lifespan(target), + ): yield @@ -481,6 +486,8 @@ async def _response_headers(request: Request, call_next: Any) -> Response: from server.storage.frontend_assets import cache_control_for response.headers["Cache-Control"] = cache_control_for(path) + if path == f"/v1/{KNOWLEDGE_SOURCE_LIVE}" or path == "/mcp" or path.startswith("/mcp/"): + response.headers["Cache-Control"] = "no-store" response.headers.setdefault("X-Content-Type-Options", "nosniff") response.headers.setdefault("X-Frame-Options", "DENY") response.headers.setdefault("Content-Security-Policy", "frame-ancestors 'none'") diff --git a/server/observability/ledger.py b/server/observability/ledger.py index 28b55ded131..f58cab2fc6f 100644 --- a/server/observability/ledger.py +++ b/server/observability/ledger.py @@ -17,6 +17,7 @@ from datetime import UTC, datetime from typing import Any +from server.core.operation_privacy import retains_no_payload from server.observability.event_args import redact_args from server.observability.events import AgentEvent, get_emitter @@ -206,18 +207,23 @@ class name and a bounded, quote-redacted first line ride the row as response_tokens_of, ) + # The status class still reads the error; only what is written leaves it out. + if retains_no_payload(op_name): + raw_args = result = None acc = cost_accumulator.current() - args: dict[str, str] = {} run_id = run_id_of(raw_args) - if raw_args: - # A request addressed at a restricted namespace - # leaves no text in the ledger — identifiers and the digest stay. - args = project_args( + # A request addressed at a restricted namespace + # leaves no text in the ledger — identifiers and the digest stay. + args = ( + project_args( redact_args( raw_args, str(identity.get("org") or ""), str(identity.get("namespace") or "") ) or {} ) + if raw_args + else {} + ) if acc is not None and acc.cost_estimated: args.update(out_cost_estimated="true", out_model_usage_status="unknown") # A row with no request arguments of its own still names what it @@ -253,7 +259,7 @@ class name and a bounded, quote-redacted first line ride the row as _hint = current_hint_code() if _hint and "out_hint_code" not in args: args["out_hint_code"] = _hint - if not success and error is not None: + if not success and error is not None and not retains_no_payload(op_name): _cls, _msg = bounded_error(error) args["error_class"] = _cls if _msg: diff --git a/server/operations/dashboard.py b/server/operations/dashboard.py index 05813a1f595..534c7aaa748 100644 --- a/server/operations/dashboard.py +++ b/server/operations/dashboard.py @@ -250,6 +250,9 @@ def _named_once(*groups: dict[str, str]) -> dict[str, str]: "the assistant agent's SQL tool; no dashboard page calls it until the Assistant " "page's chat" ), + "knowledge.source.live": ( + "Requires a protected live result view; the dashboard reads stored copies" + ), "knowledge.source.update": ( "agents and `loom knowledge source update` change a source's items; the source " "dialog registers a source with knowledge.source.add" diff --git a/server/operations/reach_manifest.py b/server/operations/reach_manifest.py index 72e78effd92..29e95526061 100644 --- a/server/operations/reach_manifest.py +++ b/server/operations/reach_manifest.py @@ -532,6 +532,7 @@ "sdk_method", "dashboard", ), + "knowledge.source.live": ("sdk_method",), "knowledge.source.parse_links": ("sdk_method",), "knowledge.source.push_configure": ( "sdk_method", diff --git a/server/operations/registry.py b/server/operations/registry.py index 4d06fc2e18b..364bca2a22c 100644 --- a/server/operations/registry.py +++ b/server/operations/registry.py @@ -35,6 +35,7 @@ from server.knowledge.api import ops_query_history as query_history from server.knowledge.api import ops_source_push as knowledge_source_push from server.knowledge.api import ops_sources as knowledge_sources +from server.knowledge.api import ops_worker_source as knowledge_worker_source from server.memory.api import ops_blacklist as blacklist from server.memory.api import ops_brief as memory_brief from server.memory.api import ops_calibration as calibration @@ -67,6 +68,7 @@ memory_records, knowledge, knowledge_sources, + knowledge_worker_source, connections, knowledge_source_push, knowledge_gaps, diff --git a/server/settings/catalog.py b/server/settings/catalog.py index da8d5fa3247..d491358d22c 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -2547,6 +2547,20 @@ class KnowledgeSettings(BaseModel): # Require protected automatic session capture and persist deployment privacy state. # Off does not lift protection while the deployment latch remains set. knowledge_mirrored_sources_enabled: bool = False + + # Path to the operator's source worker routes file. Empty disables the worker directory. + knowledge_source_worker_routes_file: str = "" + # Seconds a live read may spend on authority checks and its worker request. At most 8, + # the default: a value can only shorten it. + knowledge_source_worker_live_timeout_s: float = Field(default=8.0, gt=0, le=8.0) + # Seconds reserved after a live read for accounting and delivery. At most 2, the + # default: a value can only shorten it. + knowledge_source_worker_publication_timeout_s: float = Field(default=2.0, gt=0, le=2.0) + # Seconds one response frame may spend acquiring authority locks and sending. At most + # 1, the default; the remaining publication deadline can shorten it further. + knowledge_source_worker_frame_timeout_s: float = Field(default=1.0, gt=0, le=1.0) + # Concurrent worker access checks when proving a selection for setup. + knowledge_source_worker_selection_parallelism: int = Field(default=2, ge=1, le=2) # Mirrored reads require a complete listing and group observation within this # many seconds; missing or older evidence admits nobody. knowledge_source_acl_stale_seconds: int = Field(default=3600, ge=1) @@ -6538,6 +6552,7 @@ class TrackerSettings(BaseModel): "knowledge.source.check": 30000, "knowledge.source.inspect": 400, "knowledge.source.list": 300, + "knowledge.source.live": 8000, "knowledge.source.parse_links": 50, "knowledge.source.remove": 400, "knowledge.source.rotate": 30000, diff --git a/server/transport/arg_check.py b/server/transport/arg_check.py index edb8c8a2d0f..f4fa6f4e0a5 100644 --- a/server/transport/arg_check.py +++ b/server/transport/arg_check.py @@ -21,12 +21,15 @@ from __future__ import annotations import difflib +import json from functools import lru_cache from typing import Any from urllib.parse import quote from pydantic import AliasChoices, AliasPath, BaseModel +from server.core.operation_privacy import retains_no_payload + # Keys the transports read off the raw arguments themselves (consumer, # traffic class, explain for the MCP lean shape, and the idempotency key MCP # pops before validation). Never "ignored". @@ -86,6 +89,34 @@ def unknown_args(model: type[BaseModel], args: Any) -> list[str]: return sorted(k for k in args if isinstance(k, str) and k not in known and k not in skip) +# Reserve a fixed share of the live publication envelope for argument names. +_LIVE_IGNORED_ARGUMENT_BYTES = 1024 +LIVE_ARGUMENT_NAME_ERROR = "Ignored argument names are invalid or too large" + + +def bounded_json_string_size(value: str, budget: int) -> int | None: + """Conservative encoded JSON size, or None if the value cannot be echoed.""" + if len(value) > budget: + return None + try: + value.encode("utf-8") + except UnicodeEncodeError: + return None + size = len(json.dumps(value, ensure_ascii=True)) + return size if size <= budget else None + + +def live_argument_names_fit(model: type[BaseModel], args: dict[str, Any]) -> bool: + """Bound the unknown names echoed in live response bodies and headers.""" + budget = _LIVE_IGNORED_ARGUMENT_BYTES + for name in unknown_args(model, args): + size = bounded_json_string_size(name, budget - 2) + if size is None: + return False + budget -= size + 2 + return True + + # Synonyms models send for a field the op has (seen in session transcripts # and the `ignored_args` log). A synonym only counts where the op has the # target field. @@ -218,6 +249,8 @@ def _note(op_name: str, keys: list[str]) -> None: clients lose which fields without a line per call.""" import logging + if retains_no_payload(op_name): + return fresh = [k for k in keys if (op_name, k) not in _NOTED] if not fresh: return diff --git a/server/transport/http.py b/server/transport/http.py index 21491d3b587..81fb23ab43c 100644 --- a/server/transport/http.py +++ b/server/transport/http.py @@ -40,6 +40,7 @@ unverified_class, ) from server.core.naming import present +from server.core.operation_privacy import KNOWLEDGE_SOURCE_LIVE, retains_no_payload from server.observability.consumer import ( bind_current_consumer, explicit_consumer, @@ -74,8 +75,12 @@ validation_errors, validation_note, ) +from server.transport.arg_check import ( + LIVE_ARGUMENT_NAME_ERROR, + live_argument_names_fit, + named_argument_error, +) from server.transport.arg_check import header_value as arg_header_value -from server.transport.arg_check import named_argument_error from server.transport.arg_check import response_body as arg_response_body from server.transport.post_rows import post_handler_rows @@ -270,6 +275,12 @@ async def _read_body( raw_body: dict[str, Any] = parsed set_current_consumer(explicit_consumer(raw_body)) + if op.name == KNOWLEDGE_SOURCE_LIVE and not live_argument_names_fit(op.input_model, raw_body): + _emit_event(op, request_id, {}, 0, success=False, error_code="VALIDATION_FAILED") + raise HTTPException( + status_code=422, + detail={"code": "VALIDATION_FAILED", "message": LIVE_ARGUMENT_NAME_ERROR}, + ) # A write's misspelled argument is refused by name, not dropped. refused = named_argument_error(op, raw_body) if refused is not None: @@ -569,7 +580,11 @@ async def _start_telemetry(op: Operation, response: Response, call: _HttpCall) - try: from server.observability import capture_consent as _consent - _capture_level = await _consent.resolve(identity["org"], identity["namespace"]) + _capture_level = ( + "off" + if retains_no_payload(op.name) + else await _consent.resolve(identity["org"], identity["namespace"]) + ) except Exception: # noqa: BLE001 — fail closed, not open _capture_level = "off" diff --git a/server/transport/mcp.py b/server/transport/mcp.py index 3b96ed7131d..0e69f281986 100644 --- a/server/transport/mcp.py +++ b/server/transport/mcp.py @@ -84,6 +84,7 @@ _resolve_client_name, new_session_id, ) +from server.transport.mcp_op import invalid_live_request_id from server.transport.mcp_op import route as route_loom_op from server.transport.mcp_primer import ( _emit_initialize_event, @@ -454,8 +455,7 @@ async def mcp_endpoint(request: Request, response: Response) -> Any: e, ) auth = None - gated = _first_method_requiring_auth(payload, mode) if auth is None else None - if gated is not None: + if auth is None and (gated := _first_method_requiring_auth(payload, mode)) is not None: return _reject_unauthenticated( request, response, @@ -467,6 +467,12 @@ async def _dispatch(req: Any) -> dict[str, Any] | None: nonlocal session_id if not isinstance(req, dict): return await _handle_request(req) # Invalid Request, per entry + if invalid_live_request_id(req): + return _err( + _TRANSPORT_ERROR_ID, + INVALID_REQUEST, + "Live read request ID is invalid or too large", + ) method = req.get("method", "") # Capture the client's self-reported name from the initialize # handshake and cache it against this session so later diff --git a/server/transport/mcp_auth.py b/server/transport/mcp_auth.py index 37421cda5e3..e90c71026e2 100644 --- a/server/transport/mcp_auth.py +++ b/server/transport/mcp_auth.py @@ -30,6 +30,7 @@ _err, _ok, ) +from server.transport.mcp_op import invalid_live_request_id from server.transport.mcp_schemas import set_tool_loading if TYPE_CHECKING: @@ -301,9 +302,11 @@ def _echo_request_id(payload: Any) -> str | int: """ reqs = payload if isinstance(payload, list) else [payload] for req in reqs: - rid = req.get("id") if isinstance(req, dict) else None + if not isinstance(req, dict): + continue + rid = req.get("id") if isinstance(rid, (str, int)) and not isinstance(rid, bool): - return rid + return _TRANSPORT_ERROR_ID if invalid_live_request_id(req) else rid return _TRANSPORT_ERROR_ID diff --git a/server/transport/mcp_call.py b/server/transport/mcp_call.py index e3f300064f2..78979c66eac 100644 --- a/server/transport/mcp_call.py +++ b/server/transport/mcp_call.py @@ -31,6 +31,7 @@ ) from server.core.errors import ValidationError as LoomValidationError from server.core.naming import named, present +from server.core.operation_privacy import KNOWLEDGE_SOURCE_LIVE, retains_no_payload from server.identity.app.caller_home import home_namespace from server.observability import genai from server.observability.consumer import ASSISTANT_CONSUMER @@ -52,7 +53,12 @@ validation_note, ) from server.transport._common import validation_errors as _validation_errors -from server.transport.arg_check import IDENTITY_KEYS +from server.transport.arg_check import ( + IDENTITY_KEYS, + LIVE_ARGUMENT_NAME_ERROR, + live_argument_names_fit, + named_argument_error, +) from server.transport.arg_feedback import feedback, refused_result, tool_error from server.transport.assistant_call import answer_run, assistant_call, set_assistant_call from server.transport.lean_results import lean_result, search_reply_is_places @@ -239,6 +245,19 @@ def _forbidden_result( return {"content": [{"type": "text", "text": msg}], "isError": True, "structuredContent": body} +async def _capture_level(operation: str, identity: dict[str, Any]) -> str: + from server.observability import capture_consent + + if retains_no_payload(operation): + return "off" + try: + return await capture_consent.resolve( + str(identity.get("org") or ""), str(identity.get("namespace") or "") + ) + except Exception: # noqa: BLE001 — fail closed + return "off" + + async def _call_tool( req_id: Any, params: dict[str, Any], @@ -344,7 +363,6 @@ async def _call_tool( # task-scoped, so entry N's provider spans would carry entry N-1's tenant. # Setting it here, once per entry before any LLM call, prevents both. try: - from server.observability import capture_consent as _consent from server.observability import otel as _otel_pre _ident = _span_identity( @@ -352,12 +370,7 @@ async def _call_tool( ) # Same per-namespace consent resolution as the HTTP path: once per # request, from a 60s cache, never inside the provider call. - try: - _ident["capture_level"] = await _consent.resolve( - str(_ident.get("org") or ""), str(_ident.get("namespace") or "") - ) - except Exception: # noqa: BLE001 — fail closed - _ident["capture_level"] = "off" + _ident["capture_level"] = await _capture_level(op.name, _ident) _otel_pre.set_loom_attributes(**_ident) except Exception: # noqa: BLE001 — identity stamping must not fail a tool call # The identity could not be built: capture nothing, and name the op so its @@ -792,8 +805,12 @@ def _validated_input( """Phase 4 of `_call_tool`: the misspelled-argument refusal, then Pydantic validation. Returns the input model, or the refusal response (a dict) when the call ends here.""" - from server.transport.arg_check import named_argument_error - + if op.name == KNOWLEDGE_SOURCE_LIVE and not live_argument_names_fit(op.input_model, arguments): + _emit_refused(op.name, {}, error_code="VALIDATION_FAILED", request_id=request_id) + return _ok( + req_id, + tool_error(LIVE_ARGUMENT_NAME_ERROR, {"code": "VALIDATION_FAILED"}), + ) refused = named_argument_error(op, arguments) if refused is not None: _emit_refused( diff --git a/server/transport/mcp_descriptions.py b/server/transport/mcp_descriptions.py index 90c1b730bac..43eaa3f1743 100644 --- a/server/transport/mcp_descriptions.py +++ b/server/transport/mcp_descriptions.py @@ -1093,6 +1093,11 @@ def revision_policy(update: str) -> str: "(`namespaces`) as one list, each row naming its namespace. Use for inventory " "questions; for semantic recall use loom_search." ), + "knowledge.source.live": ( + "Read one exact selected document from an approved source worker in a protected " + "session. This experimental operation returns fresh content without storing it. " + "Use stored document search for indexed copies." + ), "knowledge.get": ( "WHAT: Fetch one whole document by `source_uri` (the latest version; " "`include_superseded=true` reads a soft-deleted one).\n" diff --git a/server/transport/mcp_op.py b/server/transport/mcp_op.py index f7153d94b8f..5722fd0b55d 100644 --- a/server/transport/mcp_op.py +++ b/server/transport/mcp_op.py @@ -31,9 +31,11 @@ from collections.abc import Set from typing import Any +from server.core.operation_privacy import KNOWLEDGE_SOURCE_LIVE from server.operations.base import Operation from server.operations.registry import ALL_OPERATIONS, OPERATIONS_BY_NAME from server.operations.toolsets import hidden_from_mcp, resolve_toolset +from server.transport.arg_check import bounded_json_string_size from server.transport.mcp_config import _ok from server.transport.mcp_ledger import emit_token_refusal @@ -344,6 +346,32 @@ def _result(req_id: Any, body: dict[str, Any], *, error: bool = False) -> dict[s ) +# not a setting: this is the fixed request ID allowance in the live publication envelope. +_MAX_LIVE_REQUEST_ID_BYTES = 4096 + + +def invalid_live_request_id(req: dict[str, Any]) -> bool: + """Check calls that need a bounded ID before routing or refusal.""" + params = req.get("params") + if req.get("method") != "tools/call" or not isinstance(params, dict): + return False + name = params.get("name") + if name == LOOM_OP_TOOL_NAME: + args = params.get("arguments") + op = args.get("op") if isinstance(args, dict) else None + if not isinstance(op, str) or op.strip().replace("_", ".", 1) != KNOWLEDGE_SOURCE_LIVE: + return False + elif name != OPERATIONS_BY_NAME[KNOWLEDGE_SOURCE_LIVE].mcp_tool_name: + return False + + request_id = req.get("id") + if isinstance(request_id, str): + return bounded_json_string_size(request_id, _MAX_LIVE_REQUEST_ID_BYTES) is None + if type(request_id) is int: + return request_id.bit_length() > 128 + return True + + def route( req: Any, *, toolset: str | None, auth: Any, schema_profile: str | None = None ) -> tuple[Any, dict[str, Any] | None]: diff --git a/tests/integration/test_mcp_worker_pg_fence.py b/tests/integration/test_mcp_worker_pg_fence.py new file mode 100644 index 00000000000..122bd025e35 --- /dev/null +++ b/tests/integration/test_mcp_worker_pg_fence.py @@ -0,0 +1,289 @@ +"""Check the source worker's frame handoff against real Postgres revocations.""" + +from __future__ import annotations + +import asyncio +from dataclasses import dataclass, replace +from typing import TYPE_CHECKING +from uuid import uuid4 + +import pytest + +from tests.integration._eventually import eventually +from tests.integration._resources import unique_org +from tests.integration.test_pg_authority import pg_authority as pg_authority +from tests.integration.test_pg_authority import pg_conn as pg_conn + +if TYPE_CHECKING: + from asyncpg import Connection + + from server.knowledge.app.mcp_worker_read import WorkerReadScope + from server.knowledge.store import pg_mcp_worker_approvals as approvals + from server.knowledge.store import pg_mcp_worker_enrollment as accounts + from server.knowledge.store import pg_mcp_worker_readers as readers + + +@dataclass(frozen=True) +class _Case: + scope: WorkerReadScope + approval_key: approvals.ApprovalKey + approver: approvals.ApprovalOwner + reader: accounts.AccountKey + link_key: readers.LinkKey + link: readers.Link + realm: str + + +async def _seed_accounts( + conn: Connection, + owner: accounts.AccountKey, + reader: accounts.AccountKey, + origin: accounts.WriteOrigin, + realm: str, +) -> None: + from server.knowledge.store import pg_mcp_worker_enrollment as accounts + + issued_at = await conn.fetchval( + "SELECT floor(extract(epoch FROM statement_timestamp()))::bigint" + ) + for account in (owner, reader): + challenge = accounts.Challenge(account, 1, uuid4(), issued_at, issued_at + 60) + assert await accounts.issue_challenge(conn, challenge, origin) + assert await accounts.consume_challenge(conn, challenge, resource_space=realm) + assert await accounts.get_account(conn, account) == accounts.AccountState(1, True, realm) + + +async def _seed_source(org: str) -> _Case: + from server.knowledge.app.mcp_worker_read import WorkerReadScope + from server.knowledge.domain.mcp_worker_permissions import ReaderConnection + from server.knowledge.store import pg_mcp_worker_approvals as approvals + from server.knowledge.store import pg_mcp_worker_enrollment as accounts + from server.knowledge.store import pg_mcp_worker_readers as readers + + namespace, worker_id, source_id = "team", uuid4(), uuid4() + profile, realm = "a" * 64, "b" * 64 + key = approvals.ApprovalKey(org, namespace, worker_id, profile) + owner = accounts.AccountKey(org, namespace, "owner", worker_id, profile, uuid4()) + reader = accounts.AccountKey(org, namespace, "reader", worker_id, profile, uuid4()) + link_key = readers.LinkKey(org, namespace, source_id, reader.requester) + origin = accounts.WriteOrigin("pg-fence", "-", "pg-fence", "asserted") + approver = approvals.ApprovalOwner(owner.requester, origin) + async with approvals.scope_transaction(key) as conn: + approval = await approvals.replace_on( + conn, key, expected_generation=0, modes=approvals.LIVE, team_access=True, owner=approver + ) + assert approval is not None + assert approval == approvals.WorkerApproval(approval.generation, approvals.LIVE, True, True) + await _seed_accounts(conn, owner, reader, origin, realm) + link_gen = await readers.set_on( + conn, + link_key, + selection_generation=1, + connection_id=reader.connection_id, + connection_generation=1, + expected_link_generation=0, + origin=origin, + ) + assert link_gen is not None + link = readers.Link(1, reader.connection_id, 1, link_gen, True) + assert await readers.current_on(conn, link_key) == link + scope = WorkerReadScope( + worker_id=worker_id, + org=org, + namespace=namespace, + source_id=source_id, + selection_generation=1, + requester=reader.requester, + connection_id=reader.connection_id, + connection_generation=1, + profile_digest=profile, + approval_generation=approval.generation, + resource_id="synthetic-resource", + enrollment_generation=link_gen, + source_owner=ReaderConnection(owner.requester, worker_id, owner.connection_id, 1, profile), + ) + return _Case(scope, key, approver, reader, link_key, link, realm) + + +async def _apply_revocation(conn: Connection, case: _Case, revocation: str) -> None: + from server.knowledge.store import pg_mcp_worker_approvals as approvals + from server.knowledge.store import pg_mcp_worker_enrollment as accounts + from server.knowledge.store import pg_mcp_worker_readers as readers + + if revocation == "unlink": + assert await readers.revoke_on( + conn, case.link_key, expected_link_generation=case.link.link_generation + ) + elif revocation == "account": + assert await accounts.revoke_account( + conn, case.reader, generation=1, origin=case.approver.origin + ) + else: + generation = case.scope.approval_generation + retired = await approvals.replace_on( + conn, + case.approval_key, + expected_generation=generation, + modes=0, + team_access=False, + owner=case.approver, + ) + assert retired is not None and retired.generation > generation + assert retired == approvals.WorkerApproval(retired.generation, 0, False, False) + + +async def _assert_revoked(pg_conn: Connection, case: _Case, revocation: str) -> None: + from server.knowledge.store import pg_mcp_worker_enrollment as accounts + from server.knowledge.store import pg_mcp_worker_readers as readers + + if revocation == "unlink": + unlinked = await readers.current_on(pg_conn, case.link_key) + assert unlinked is not None and unlinked.link_generation > case.link.link_generation + assert unlinked == replace( + case.link, active=False, link_generation=unlinked.link_generation + ) + elif revocation == "account": + assert await accounts.get_account(pg_conn, case.reader) == accounts.AccountState( + 1, False, case.realm + ) + + +async def _assert_publication_order(pg_conn: Connection, case: _Case, revocation: str) -> None: + from server.knowledge.app.mcp_worker_pg_directory import fence_live_delivery + from server.knowledge.app.mcp_worker_read import WorkerReadRefused + from server.knowledge.store import pg_mcp_worker_approvals as approvals + + loop = asyncio.get_running_loop() + frame_entered, release_frame = asyncio.Event(), asyncio.Event() + revoker_ready: asyncio.Future[int] = loop.create_future() + order: list[str] = [] + + async def deliver() -> None: + frame_entered.set() + await release_frame.wait() + order.append("frame") + + async def revoke() -> None: + async with approvals.scope_transaction(case.approval_key) as conn: + revoker_ready.set_result(conn.get_server_pid()) + await frame_entered.wait() + await _apply_revocation(conn, case, revocation) + order.append("revoked") + + async with asyncio.TaskGroup() as tasks: + tasks.create_task(revoke()) + revoker_pid = await revoker_ready + + async def revoker_blocked() -> bool: + return await pg_conn.fetchval( + "SELECT cardinality(pg_blocking_pids($1)) > 0", revoker_pid + ) + + tasks.create_task(fence_live_delivery(case.scope, deliver, loop.time() + 5, _current)) + await frame_entered.wait() + await eventually( + revoker_blocked, + max_wait=1, + interval=0.01, + description="Postgres blocks revocation behind the held frame", + ) + release_frame.set() + assert order == ["frame", "revoked"] + await _assert_revoked(pg_conn, case, revocation) + with pytest.raises(WorkerReadRefused, match="^denied$"): + await fence_live_delivery(case.scope, deliver, loop.time() + 5, _current) + assert order == ["frame", "revoked"] + + +async def _current() -> None: + """The source row is unchanged; these tests change Postgres authority alone.""" + + +async def _assert_writer_waits_for_running_frames_only(pg_conn: Connection, case: _Case) -> None: + from server.core import pg + from server.knowledge.app.mcp_worker_pg_directory import fence_live_delivery + from server.knowledge.store import pg_source_lock + + loop = asyncio.get_running_loop() + first_entered, release_first = asyncio.Event(), asyncio.Event() + order: list[str] = [] + + async def first() -> None: + first_entered.set() + await release_first.wait() + order.append("first frame") + + async def later() -> None: + order.append("later frame") + + async def write() -> None: + async with pg_source_lock.exclusive(case.scope.org, case.scope.namespace, wait_s=5): + order.append("write") + + async def waiting(count: int) -> bool: + # Waiters on this namespace's source lock alone (a bigint advisory key). + return await pg_conn.fetchval( + f"WITH k AS (SELECT {pg.SOURCES_LOCK_KEY} AS key) " + "SELECT count(*) = $3 FROM pg_locks, k WHERE locktype = 'advisory' " + "AND NOT granted AND objsubid = 1 " + "AND classid::bigint = (k.key >> 32) & 4294967295 " + "AND objid::bigint = k.key & 4294967295", + case.scope.org, + case.scope.namespace, + count, + ) + + async with asyncio.TaskGroup() as tasks: + tasks.create_task(fence_live_delivery(case.scope, first, loop.time() + 5, _current)) + await first_entered.wait() + tasks.create_task(write()) + await eventually( + lambda: waiting(1), max_wait=1, interval=0.01, description="the write waits" + ) + # A frame that starts after the write queued waits behind it, not ahead of it. + tasks.create_task(fence_live_delivery(case.scope, later, loop.time() + 5, _current)) + await eventually( + lambda: waiting(2), max_wait=1, interval=0.01, description="the later frame waits" + ) + release_first.set() + assert order == ["first frame", "write", "later frame"] + + +async def _cleanup(pg_conn: Connection, org: str) -> None: + from server.core import pg + + try: + async with asyncio.timeout(10), pg_conn.transaction(): + for statement in ( + "DELETE FROM loom.mcp_worker_source_readers WHERE org = $1", + "DELETE FROM loom.mcp_worker_enrollment_challenges WHERE org = $1", + "DELETE FROM loom.mcp_worker_accounts WHERE org = $1", + "DELETE FROM loom.mcp_worker_approvals WHERE org = $1", + ): + await pg_conn.execute(statement, org) + finally: + async with asyncio.timeout(10): + await pg.close_pool() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("revocation", ["unlink", "account", "approval"]) +async def test_live_delivery_serializes_with_revocation( + pg_conn: Connection, revocation: str +) -> None: + org = unique_org("worker-pg-fence") + try: + async with asyncio.timeout(15): + await _assert_publication_order(pg_conn, await _seed_source(org), revocation) + finally: + await _cleanup(pg_conn, org) + + +@pytest.mark.asyncio +async def test_source_write_waits_for_running_frames_only(pg_conn: Connection) -> None: + org = unique_org("worker-pg-source-lock") + try: + async with asyncio.timeout(15): + await _assert_writer_waits_for_running_frames_only(pg_conn, await _seed_source(org)) + finally: + await _cleanup(pg_conn, org) diff --git a/tests/unit/snapshots/sdk_public_api.json b/tests/unit/snapshots/sdk_public_api.json index f2930cb9cf5..2961f0ce719 100644 --- a/tests/unit/snapshots/sdk_public_api.json +++ b/tests/unit/snapshots/sdk_public_api.json @@ -987,6 +987,10 @@ "body", "options" ], + "source_live": [ + "body", + "options" + ], "source_parse_links": [ "body", "options" diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index e36eb72738b..74cae1ee83e 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -659,6 +659,11 @@ "knowledge_source_sync_interval_seconds": 900, "knowledge_source_sync_max_file_bytes": 67108864, "knowledge_source_sync_max_pass_seconds": 600, + "knowledge_source_worker_frame_timeout_s": 1.0, + "knowledge_source_worker_live_timeout_s": 8.0, + "knowledge_source_worker_publication_timeout_s": 2.0, + "knowledge_source_worker_routes_file": "", + "knowledge_source_worker_selection_parallelism": 2, "knowledge_sources_max_per_namespace": 8, "knowledge_upload_max_bytes": 67108864, "knowledge_upload_ttl_seconds": 86400, diff --git a/tests/unit/test_cell_control_census.py b/tests/unit/test_cell_control_census.py index f1334b129ae..23fa6243f96 100644 --- a/tests/unit/test_cell_control_census.py +++ b/tests/unit/test_cell_control_census.py @@ -187,6 +187,8 @@ def test_cell_control_migrations_are_classified(): ("run_keeper_delete", "ALTER TABLE", "{table}"): 1, }, "server/erasure/store/reclaim.py": {("apply_deleted_mask", "ALTER TABLE", "{table}"): 1}, + # Worker metadata erasure binds the scope and iterates a fixed list of worker metadata tables. + "server/erasure/store/steps_pg.py": {("_delete_worker_metadata", "DELETE FROM", "{table}"): 1}, "server/erasure/store/steps_memory.py": { ("_scrub_link_cursors", "DELETE FROM", "{_CURSORS}"): 1 }, diff --git a/tests/unit/test_mcp_worker_approval.py b/tests/unit/test_mcp_worker_approval.py new file mode 100644 index 00000000000..ae7f8c78a02 --- /dev/null +++ b/tests/unit/test_mcp_worker_approval.py @@ -0,0 +1,43 @@ +import unittest +from dataclasses import replace +from unittest.mock import AsyncMock +from uuid import UUID + +from server.knowledge.app.mcp_worker_approval import ( + ApprovalChange, + WorkerApprovalRefused, + WorkerProvision, + _can_approve, + apply_worker_approval, +) +from server.knowledge.store.pg_mcp_worker_approvals import LIVE, REFRESH, SNAPSHOT, ApprovalKey + + +class TestWorkerApproval(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.scope = ApprovalKey("org", "team", UUID(int=3), "b" * 64) + self.change = ApprovalChange(self.scope, 4, LIVE, False) + self.profile = WorkerProvision(self.scope, LIVE | SNAPSHOT, False) + + def test_cannot_approve_another_scope_or_unqualified_refresh_or_team_access(self) -> None: + self.assertTrue(_can_approve(self.change, self.profile)) + self.assertFalse(_can_approve(replace(self.change, modes=LIVE | REFRESH), self.profile)) + self.assertFalse(_can_approve(replace(self.change, team_access=True), self.profile)) + for key in ( + replace(self.scope, org="other"), + replace(self.scope, namespace="private"), + replace(self.scope, profile_digest="a" * 64), + replace(self.scope, worker_id=UUID(int=4)), + ): + self.assertFalse(_can_approve(self.change, replace(self.profile, key=key))) + + def test_removing_an_approval_does_not_require_live_provisioning(self) -> None: + self.assertTrue(_can_approve(replace(self.change, modes=0), None)) + self.assertFalse(_can_approve(replace(self.change, modes=0, team_access=True), None)) + + async def test_unprotected_request_cannot_look_up_worker_or_erasure_state(self) -> None: + provision, erasure = AsyncMock(), AsyncMock() + with self.assertRaises(WorkerApprovalRefused): + await apply_worker_approval(self.change, provision=provision, not_erasing=erasure) + provision.assert_not_awaited() + erasure.assert_not_awaited() diff --git a/tests/unit/test_mcp_worker_authority.py b/tests/unit/test_mcp_worker_authority.py new file mode 100644 index 00000000000..3b7a11bd900 --- /dev/null +++ b/tests/unit/test_mcp_worker_authority.py @@ -0,0 +1,631 @@ +import asyncio +import hashlib +import json +import time +import unittest +from dataclasses import asdict, replace +from datetime import UTC, datetime +from uuid import UUID, uuid4 + +import httpx +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from server.knowledge.app.mcp_worker_authority import ( + CurrentConnection, + CurrentRead, + ReaderEnrollment, + ReaderStanding, + RequestedResource, +) +from server.knowledge.app.mcp_worker_proof import confirm_stored_read +from server.knowledge.app.mcp_worker_read import WorkerReadChannel, WorkerReadRefused +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection, StoredCopyRevision +from server.knowledge.domain.mcp_worker_source import WORKER_REGISTRATION +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource + + +class TestCurrentRead(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.request = RequestedResource("org", "collection", "documents", "urn:exact:Résumé") + self.standing: ReaderStanding | None = ReaderStanding("org", "alice", "collection") + worker = uuid4() + alice = ReaderConnection("alice", worker, uuid4(), 2, "a" * 64) + bob = ReaderConnection("bob", worker, uuid4(), 5, "a" * 64) + self.connections = { + "alice": CurrentConnection("org", alice, True, "approved-realm"), + "bob": CurrentConnection("org", bob, True, "approved-realm"), + } + self.config = { + "version": 2, + "worker_id": str(worker), + "profile_digest": alice.profile_digest, + "owner_connection_id": str(alice.connection_id), + "owner_connection_generation": alice.connection_generation, + "approval_generation": 3, + "selection_generation": 1, + "mode": "live", + "reader_policy": "current_team_access", + } + self.row: KnowledgeSource | None = KnowledgeSource( + org="org", + namespace="collection", + name="documents", + kind="mcp", + source_id=str(uuid4()), + access=MIRRORED_ACCESS, + credential_mode="worker", + owner_subject="alice", + connection_id=str(alice.connection_id), + config={WORKER_REGISTRATION: json.dumps(self.config)}, + items=[{"id": self.request.resource_id, "type": "resource"}], + ) + self.approval: int | None = 3 + self.approval_reads = [] + self.sequential_source_reads: list[bool] = [] + self.connection_reads: list[str] = [] + self.bob_enrollment: ReaderEnrollment | None = ReaderEnrollment( + self.request.org, + self.request.namespace, + UUID(self.row.source_id), + 1, + "bob", + bob.connection_id, + bob.connection_generation, + 4, + ) + + async def _standing(self, request: RequestedResource) -> ReaderStanding | None: + return self.standing + + async def _source(self, org: str, namespace: str, name: str) -> KnowledgeSource | None: + from server.core.ch import sequential_reads_active + + self.sequential_source_reads.append(sequential_reads_active()) + return self.row + + async def _connection( + self, org: str, owner: str, worker_id: UUID, connection_id: UUID + ) -> CurrentConnection | None: + self.connection_reads.append(owner) + return self.connections.get(owner) + + async def _enrollment( + self, org: str, namespace: str, source_id: UUID, owner: str + ) -> ReaderEnrollment | None: + return self.bob_enrollment + + async def _approval(self, org, namespace, worker_id, profile, mode, team) -> int | None: + self.approval_reads.append((mode, team)) + return self.approval + + def _authority(self) -> CurrentRead: + return CurrentRead( + self.request, + self._standing, + self._source, + self._connection, + self._enrollment, + self._approval, + "live", + ) + + async def test_grant_and_exact_selection_precede_approval_lookup(self) -> None: + self.standing = None + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await self._authority().resolve() + self.standing = ReaderStanding("org", "alice", "collection") + self.request = replace(self.request, resource_id="urn:exact:Résumé") + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await self._authority().resolve() + self.assertEqual(self.connection_reads, []) + + async def test_current_worker_approval_generation_cannot_restore_old_selection(self) -> None: + read = self._authority() + self.assertEqual((await read.resolve()).approval_generation, 3) + for generation in (None, 5): + with self.subTest(generation=generation): + self.connection_reads.clear() + self.approval = generation + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await read.resolve() + self.assertEqual(self.connection_reads, []) + + async def test_stored_access_checks_the_approved_storage_mode_and_team_scope(self) -> None: + read = replace(self._authority(), purpose="stored") + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await read.resolve() + assert self.row is not None + self.row = replace( + self.row, config={WORKER_REGISTRATION: json.dumps({**self.config, "mode": "snapshot"})} + ) + self.standing = ReaderStanding("org", "bob", "collection") + self.assertEqual((await read.resolve()).requester, "bob") + self.assertEqual(self.approval_reads, [("snapshot", True)]) + + async def test_team_uses_only_bobs_current_connection(self) -> None: + self.standing = ReaderStanding("org", "bob", "collection") + scope = await self._authority().resolve() + self.assertEqual(scope.requester, "bob") + self.assertEqual(scope.connection_id, self.connections["bob"].binding.connection_id) + self.assertEqual(scope.connection_generation, 5) + self.assertEqual(scope.enrollment_generation, 4) + + async def test_team_needs_an_exact_current_source_enrollment(self) -> None: + self.standing = ReaderStanding("org", "bob", "collection") + original = self.bob_enrollment + assert original is not None + for enrollment in ( + None, + replace(original, connection_id=uuid4()), + replace(original, selection_generation=2), + replace(original, source_id=uuid4()), + replace(original, requester="alice"), + ): + self.bob_enrollment = enrollment + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await self._authority().resolve() + + async def test_team_refuses_unknown_or_mismatched_resource_space(self) -> None: + self.standing = ReaderStanding("org", "bob", "collection") + for space in (None, "other-realm"): + self.connections["bob"] = replace(self.connections["bob"], resource_space=space) + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await self._authority().resolve() + + async def test_owner_disconnect_and_generation_change_fence_existing_source(self) -> None: + self.standing = ReaderStanding("org", "bob", "collection") + authority = self._authority() + await authority.resolve() + prior = self.connections["alice"] + for current in ( + replace(prior, active=False), + replace(prior, binding=replace(prior.binding, connection_generation=3)), + ): + self.connections["alice"] = current + for viewer, status in (("bob", "denied"), ("alice", "reconnect")): + self.standing = ReaderStanding("org", viewer, "collection") + with self.assertRaisesRegex(WorkerReadRefused, f"^{status}$"): + await authority.resolve() + + async def test_scope_changes_even_if_selection_returns_to_the_same_item(self) -> None: + authority = self._authority() + prior = await authority.resolve() + assert self.row is not None + self.row = replace( + self.row, + config={WORKER_REGISTRATION: json.dumps({**self.config, "selection_generation": 3})}, + ) + self.assertNotEqual(await authority.resolve(), prior) + + async def test_reenrolling_the_same_connection_changes_inflight_authority(self) -> None: + self.standing = ReaderStanding("org", "bob", "collection") + read = self._authority() + before = await read.resolve() + assert self.bob_enrollment is not None + self.bob_enrollment = replace(self.bob_enrollment, link_generation=6) + self.assertNotEqual(await read.resolve(), before) + + async def test_check_receipt_matches_current_reader_revision_and_content(self) -> None: + self.standing = ReaderStanding("org", "bob", "collection") + assert self.row is not None + self.row = replace( + self.row, config={WORKER_REGISTRATION: json.dumps({**self.config, "mode": "snapshot"})} + ) + authority = replace(self._authority(), purpose="stored") + scope = await authority.resolve() + accepted = StoredCopyRevision( + org=scope.org, + namespace=scope.namespace, + source_id=scope.source_id, + selection_generation=scope.selection_generation, + resource_id_sha256=hashlib.sha256(scope.resource_id.encode()).hexdigest(), + revision_id=uuid4(), + content_sha256=hashlib.sha256(b"copy").hexdigest(), + ) + current = accepted + reply_sha256 = accepted.content_sha256 + change_during_read = False + signing_key = Ed25519PrivateKey.generate() + + async def answer(request: httpx.Request) -> httpx.Response: + nonlocal current + import jwt + + claims = jwt.decode( + request.headers["Authorization"].removeprefix("Bearer "), + signing_key.public_key(), + algorithms=["EdDSA"], + audience=f"urn:loom:source-worker:{scope.worker_id}", + issuer="loom", + ) + assert claims["grant"]["binding"]["requester"] == "bob" + assert claims["grant"]["operation"] == "check_access" + assert request.url.path == "/v1/check-access" + if change_during_read: + current = replace(accepted, revision_id=uuid4()) + body = httpx.ByteStream( + json.dumps( + { + "status": "ok", + "request_id": claims["grant"]["request_id"], + "content_sha256": reply_sha256, + "fetched_at": int(time.time()), + "document": None, + } + ).encode() + ) + return httpx.Response(200, stream=body, headers={"Content-Type": "application/json"}) + + async def revision() -> StoredCopyRevision: + return current + + channel = WorkerReadChannel( + worker_id=scope.worker_id, + origin="https://worker.example.test", + issuer="loom", + signing_key=signing_key, + grant_seconds=5, + max_response_bytes=4096, + _transport=httpx.MockTransport(answer), + ) + self.addAsyncCleanup(channel.close) + proof = await confirm_stored_read( + channel=channel, current=authority, revision=revision, max_age_seconds=15 + ) + self.assertEqual(proof.connection, self.connections["bob"].binding) + self.assertEqual(proof.confirmed_revision, accepted) + reply_sha256 = hashlib.sha256(b"other revision").hexdigest() + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await confirm_stored_read( + channel=channel, current=authority, revision=revision, max_age_seconds=15 + ) + reply_sha256 = accepted.content_sha256 + change_during_read = True + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await confirm_stored_read( + channel=channel, current=authority, revision=revision, max_age_seconds=15 + ) + + async def _live_publication( + self, + *, + revoke_for_publication: bool = False, + unlink_during_body: bool = False, + retire_during_body: bool = False, + rewrite_during_body: bool = False, + retire_during_delivery: bool = False, + concurrent_publication: bool = False, + settle_past_read_deadline: bool = False, + retain_past_read_deadline: bool = False, + ) -> tuple[list, list]: + from unittest.mock import AsyncMock, patch + + import jwt + + from server.auth.context import set_current_auth + from server.auth.jwt import AuthInfo + from server.auth.session_protection import request_declaration + from server.core import request_tail, request_work + from server.knowledge.app import mcp_worker_protected as protected + from server.operations.base import Role + + reader = self.connections["bob"].binding + signing_key = Ed25519PrivateKey.generate() + attempts = [] + published = [] + text = "synthetic live canary" + + async def answer(request: httpx.Request) -> httpx.Response: + claims = jwt.decode( + request.headers["Authorization"].removeprefix("Bearer "), + signing_key.public_key(), + algorithms=["EdDSA"], + audience=f"urn:loom:source-worker:{reader.worker_id}", + issuer="loom", + ) + grant = claims["grant"] + attempts.append(grant) + assert request.url.path == "/v1/live" + payload = { + "status": "ok", + "request_id": grant["request_id"], + "fetched_at": int(time.time()), + "content_sha256": hashlib.sha256(text.encode()).hexdigest(), + "document": { + "resource_id": self.request.resource_id, + "title": "Document", + "text": text, + "revision": "fixture-1", + "source_link": "https://source.example/document", + "mime_type": "text/plain", + }, + } + return httpx.Response( + 200, + stream=httpx.ByteStream(json.dumps(payload).encode()), + headers={"Content-Type": "application/json"}, + ) + + channel = WorkerReadChannel( + worker_id=reader.worker_id, + origin="https://worker.example.test", + issuer="loom", + signing_key=signing_key, + grant_seconds=5, + max_response_bytes=4096, + _transport=httpx.MockTransport(answer), + ) + self.addAsyncCleanup(channel.close) + + body = False + first_body = asyncio.Event() + second_claim = asyncio.Event() + # Frames inside the fence's shared source lock. + readers = 0 + + async def connection(org, owner, worker_id, connection_id): + record = await self._connection(org, owner, worker_id, connection_id) + if body and unlink_during_body and owner == "bob": + # The ordinary check already read the link and now sees a valid account. + self.bob_enrollment = None + return record + + async def fence_delivery(scope, deliver, deadline, recheck_source) -> None: + nonlocal readers + assert scope.requester == "bob" + if body and retire_during_body: + # Retirement commits under the exclusive lock before this frame takes it. + self.row = None + if body and rewrite_during_body and self.row is not None: + # A source write that changes no checked field still rewrites the row. + self.row = replace(self.row, updated_at=datetime.now(UTC)) + if readers: + second_claim.set() + readers += 1 + try: + await recheck_source() + await fenced(scope, deliver, deadline) + finally: + readers -= 1 + + async def fenced(scope, deliver, deadline) -> None: + assert deadline > asyncio.get_running_loop().time() + link = await self._enrollment( + scope.org, scope.namespace, scope.source_id, scope.requester + ) + if link is None or link.link_generation != scope.enrollment_generation: + raise WorkerReadRefused("denied") + await deliver() + + directory = protected.LiveSourceDirectory( + self._source, + connection, + self._enrollment, + lambda _: channel, + self._approval, + fence_delivery, + ) + auth = AuthInfo( + subject="bob", + org="org", + namespaces=("collection",), + roles=(Role.VIEWER,), + is_service_account=False, + ) + + retain = protected._retain + retention_started = False + retention_wait_until = None + + async def mark_retention(*args) -> None: + nonlocal retention_started + retention_started = True + await retain(*args) + + async def check_session(_auth) -> None: + nonlocal retention_wait_until + if retention_started and retention_wait_until is not None: + wait_until, retention_wait_until = retention_wait_until, None + await asyncio.sleep(max(0, wait_until - asyncio.get_running_loop().time()) + 0.01) + + async def downstream(scope, _receive, send) -> None: + nonlocal body, retention_wait_until + with request_declaration(scope), request_work.http_owner(scope): + set_current_auth(auth) + try: + request_work.begin() + loop = asyncio.get_running_loop() + short_read = settle_past_read_deadline or retain_past_read_deadline + deadline = loop.time() + (0.8 if short_read else 5) + if retain_past_read_deadline: + retention_wait_until = deadline + result = await protected.protected_live_read( + self.request, directory, deadline=deadline + ) + assert result.text == text + if settle_past_read_deadline: + await asyncio.sleep(max(0, deadline - loop.time()) + 0.01) + if revoke_for_publication: + self.connections["bob"] = replace(self.connections["bob"], active=False) + await send({"type": "http.response.start", "status": 200, "headers": []}) + body = True + await send( + { + "type": "http.response.body", + "body": json.dumps(asdict(result), default=str).encode(), + } + ) + finally: + set_current_auth(None) + + async def send(message) -> None: + if message["type"] == "http.response.body" and retire_during_delivery: + self.assertTrue(readers) + if concurrent_publication and message["type"] == "http.response.body": + if not first_body.is_set(): + first_body.set() + await second_claim.wait() + published.append(message) + + middleware = request_tail.RequestTailMiddleware(downstream) + + async def publish() -> None: + scope = {"type": "http", "headers": [(b"x-loom-session-protection", b"v1")]} + await middleware(scope, None, send) + + with ( + patch.object(type(protected.settings), "auth_actually_required", return_value=True), + patch.object(protected.settings, "knowledge_mirrored_sources_enabled", True), + patch.object(protected, "_retain", mark_retention), + patch.object(protected.session_admission, "require", check_session), + patch.object(protected.authz, "row_in_scope", AsyncMock(return_value=True)), + patch.object( + protected.connected_accounts, "own_subject", AsyncMock(return_value=("org", "bob")) + ), + ): + if ( + revoke_for_publication + or unlink_during_body + or retire_during_body + or rewrite_during_body + ): + with self.assertRaises(request_tail.RequiredTailError): + await publish() + elif concurrent_publication: + async with asyncio.TaskGroup() as group: + group.create_task(publish()) + await first_body.wait() + group.create_task(publish()) + else: + await publish() + return attempts, published + + async def test_two_live_reads_deliver_while_sharing_the_source_lease(self) -> None: + attempts, published = await self._live_publication(concurrent_publication=True) + self.assertEqual(len(attempts), 2) + bodies = [frame["body"] for frame in published if frame["type"] == "http.response.body"] + self.assertEqual(len(bodies), 2) + self.assertTrue(all(b"synthetic live canary" in body for body in bodies)) + + async def test_authorized_live_document_passes_publication_with_bobs_connection(self) -> None: + attempts, published = await self._live_publication(retire_during_delivery=True) + self.assertEqual(len(attempts), 1) + self.assertEqual(attempts[0]["binding"]["requester"], "bob") + self.assertEqual( + attempts[0]["binding"]["connection_id"], + str(self.connections["bob"].binding.connection_id), + ) + self.assertIn(b"synthetic live canary", published[-1]["body"]) + + async def test_revoked_live_document_is_withheld_even_after_the_worker_returns(self) -> None: + attempts, published = await self._live_publication(revoke_for_publication=True) + self.assertEqual(len(attempts), 1) + self.assertEqual(published, []) + + async def test_team_unlink_during_body_recheck_cannot_publish_document(self) -> None: + attempts, published = await self._live_publication(unlink_during_body=True) + self.assertEqual(len(attempts), 1) + self.assertNotIn("source_owner", attempts[0]["binding"]) + self.assertIsNone(self.bob_enrollment) + self.assertEqual([frame["type"] for frame in published], ["http.response.start"]) + + async def test_source_retirement_before_publication_takes_the_lease_withholds_document( + self, + ) -> None: + attempts, published = await self._live_publication(retire_during_body=True) + self.assertEqual(len(attempts), 1) + self.assertIsNone(self.row) + self.assertEqual([frame["type"] for frame in published], ["http.response.start"]) + + async def test_a_source_rewrite_after_the_frame_check_withholds_the_frame(self) -> None: + attempts, published = await self._live_publication(rewrite_during_body=True) + self.assertEqual(len(attempts), 1) + self.assertEqual([frame["type"] for frame in published], ["http.response.start"]) + + async def test_the_fenced_source_reread_sees_every_replica(self) -> None: + await self._live_publication() + # The reread under the source lock is the last source read of the response. + self.assertTrue(self.sequential_source_reads[-1]) + + async def test_live_document_remains_deliverable_after_read_budget_ends(self) -> None: + attempts, published = await self._live_publication(settle_past_read_deadline=True) + self.assertEqual(len(attempts), 1) + self.assertIn(b"synthetic live canary", published[-1]["body"]) + + async def test_initial_retention_can_finish_after_read_deadline(self) -> None: + attempts, published = await self._live_publication(retain_past_read_deadline=True) + self.assertEqual(len(attempts), 1) + self.assertIn(b"synthetic live canary", published[-1]["body"]) + + async def test_team_viewer_cannot_distinguish_selected_ids_without_current_authority( + self, + ) -> None: + enrollment = self.bob_enrollment + assert enrollment is not None + for enrolled, outage in ((False, False), (False, True), (True, True)): + with self.subTest(enrolled=enrolled, outage=outage): + self.bob_enrollment = enrollment if enrolled else None + await self._assert_team_refusal(enrolled=enrolled, outage=outage) + + async def _assert_team_refusal(self, *, enrolled: bool, outage: bool) -> None: + from unittest.mock import AsyncMock, patch + + from server.auth.context import set_current_auth + from server.auth.jwt import AuthInfo + from server.auth.session_protection import request_declaration + from server.core import request_tail, request_work + from server.knowledge.api.models_source_live import KnowledgeSourceLiveInput + from server.knowledge.app import mcp_worker_protected as protected + from server.knowledge.app.mcp_worker_live_op import read_source_live + from server.operations.base import Role + + worker = unittest.mock.Mock() + approval = ( + AsyncMock(side_effect=WorkerReadRefused("unavailable")) + if outage + else AsyncMock(wraps=self._approval) + ) + status = "unavailable" if enrolled else "denied" + directory = protected.LiveSourceDirectory( + self._source, self._connection, self._enrollment, worker, approval, AsyncMock() + ) + auth = AuthInfo( + subject="bob", + org="org", + namespaces=("collection",), + roles=(Role.VIEWER,), + is_service_account=False, + ) + scope = {"type": "http", "headers": [(b"x-loom-session-protection", b"v1")]} + + async def downstream(scope, _receive, _send) -> None: + with request_declaration(scope), request_work.http_owner(scope): + set_current_auth(auth) + try: + request_work.begin() + for resource in ("urn:other", self.request.resource_id): + result = await read_source_live( + KnowledgeSourceLiveInput( + org="org", + namespace="collection", + name="documents", + resource_id=resource, + ), + directory, + ) + self.assertEqual(result.model_dump(), {"status": status, "document": None}) + finally: + set_current_auth(None) + + with ( + patch.object(type(protected.settings), "auth_actually_required", return_value=True), + patch.object(protected.settings, "knowledge_mirrored_sources_enabled", True), + patch.object(protected.session_admission, "require", AsyncMock()), + patch.object(protected.authz, "row_in_scope", AsyncMock(return_value=True)), + patch.object( + protected.connected_accounts, "own_subject", AsyncMock(return_value=("org", "bob")) + ), + ): + await request_tail.RequestTailMiddleware(downstream)(scope, None, AsyncMock()) + self.assertEqual(approval.await_count, 2 if enrolled else 0) + worker.assert_not_called() diff --git a/tests/unit/test_mcp_worker_enrollment.py b/tests/unit/test_mcp_worker_enrollment.py new file mode 100644 index 00000000000..f66eeca1b73 --- /dev/null +++ b/tests/unit/test_mcp_worker_enrollment.py @@ -0,0 +1,126 @@ +import time +import unittest +from dataclasses import replace +from uuid import uuid4 + +import jwt +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from server.knowledge.app.mcp_worker_enrollment import ( + EnrollmentChallenge, + EnrollmentRefused, + check_enrollment_write, + issue_enrollment_grant, + verify_enrollment, +) + + +class TestWorkerEnrollment(unittest.TestCase): + def setUp(self) -> None: + now = int(time.time()) + self.key = Ed25519PrivateKey.generate() + self.connection = uuid4() + self.challenge = EnrollmentChallenge( + "org", + "alice", + uuid4(), + "a" * 64, + uuid4(), + now - 2, + now + 30, + "urn:loom:enroll:test", + self.connection, + 2, + ) + self.claims = { + "iss": f"urn:loom:source-worker:{self.challenge.worker_id}", + "aud": self.challenge.audience, + "iat": now - 1, + "exp": now + 15, + "binding": { + "org": self.challenge.org, + "requester": self.challenge.requester, + "worker_id": str(self.challenge.worker_id), + "profile_digest": self.challenge.profile_digest, + "nonce": str(self.challenge.nonce), + "connection_id": str(self.connection), + "generation": 2, + "resource_space": "b" * 64, + }, + } + + def _verify(self, claims, *, key=None): + return verify_enrollment( + self.challenge, + jwt.encode(claims, key or self.key, algorithm="EdDSA"), + verifier=self.key.public_key(), + ) + + def test_statement_yields_only_the_owned_opaque_connection(self) -> None: + approved = self._verify(self.claims) + self.assertEqual(approved.binding.connection_id, self.connection) + self.assertEqual(approved.binding.owner, "alice") + self.assertEqual(approved.binding.connection_generation, 2) + self.assertEqual(approved.resource_space, "b" * 64) + self.assertTrue(approved.active) + + def test_other_readers_workers_and_unapproved_metadata_are_refused(self) -> None: + for field, wrong in ( + ("requester", "bob"), + ("org", "other-org"), + ("worker_id", str(uuid4())), + ("profile_digest", "c" * 64), + ("nonce", str(uuid4())), + ("connection_id", str(uuid4())), + ("generation", 3), + ("generation", True), + ("token", "synthetic-unexpected-field"), + ): + binding = {**self.claims["binding"], field: wrong} + with self.subTest(field=field), self.assertRaises(EnrollmentRefused): + self._verify({**self.claims, "binding": binding}) + + def test_worker_key_audience_and_enrollment_window_are_pinned(self) -> None: + for claims in ( + {**self.claims, "aud": "urn:loom:enroll:other"}, + {**self.claims, "exp": self.challenge.expires_at + 1}, + {**self.claims, "iat": self.challenge.issued_at - 1}, + ): + with self.assertRaises(EnrollmentRefused): + self._verify(claims) + with self.assertRaises(EnrollmentRefused): + self._verify(self.claims, key=Ed25519PrivateKey.generate()) + + def test_link_retry_cannot_restore_a_revoked_or_different_account(self) -> None: + link = self._verify(self.claims) + self.assertTrue(check_enrollment_write(None, link)) + self.assertFalse(check_enrollment_write(link, link)) + revoked = replace(link, active=False) + with self.assertRaises(EnrollmentRefused): + check_enrollment_write(revoked, link) + rotated = replace(link, binding=replace(link.binding, connection_generation=3)) + self.assertTrue(check_enrollment_write(revoked, rotated)) + with self.assertRaises(EnrollmentRefused): + check_enrollment_write(rotated, link) + with self.assertRaises(EnrollmentRefused): + check_enrollment_write(link, replace(rotated, resource_space="c" * 64)) + + def test_grant_carries_exact_account_and_no_credential(self) -> None: + token = issue_enrollment_grant(self.challenge, issuer="loom", key=self.key) + claims = jwt.decode( + token, + self.key.public_key(), + algorithms=["EdDSA"], + issuer="loom", + audience=self.challenge.audience, + ) + self.assertEqual(claims["operation"], "enroll") + self.assertEqual( + claims["binding"], + { + key: value + for key, value in self.claims["binding"].items() + if key != "resource_space" + }, + ) + self.assertLessEqual(claims["exp"] - claims["iat"], 30) diff --git a/tests/unit/test_mcp_worker_live_privacy.py b/tests/unit/test_mcp_worker_live_privacy.py new file mode 100644 index 00000000000..0401416e959 --- /dev/null +++ b/tests/unit/test_mcp_worker_live_privacy.py @@ -0,0 +1,329 @@ +"""Live document telemetry retains request accounting without the payload.""" + +from unittest.mock import AsyncMock, Mock + +import pytest + +from server.core.operation_privacy import KNOWLEDGE_SOURCE_LIVE +from server.observability import ledger + + +@pytest.mark.parametrize("success", [True, False]) +def test_live_ledger_ignores_arguments_results_and_exception_text(monkeypatch, success) -> None: + dispatch = Mock(return_value=False) + project = Mock(side_effect=AssertionError("a live payload reached the diagnostic projector")) + monkeypatch.setattr(ledger, "_dispatch_event", dispatch) + monkeypatch.setattr("server.observability.event_args.project_args", project) + monkeypatch.setattr("server.observability.event_args.project_result", project) + monkeypatch.setattr("server.observability.event_args.bounded_error", project) + ledger.emit_agent_event( + op_name=KNOWLEDGE_SOURCE_LIVE, + identity={ + "org": "test-org", + "namespace": "docs", + "agent": "-", + "user_id": "-", + "session_id": "-", + }, + request_id="req-1", + latency_ms=22, + success=success, + error_code="" if success else "INTERNAL_ERROR", + raw_args={"query": "input-canary", "run_id": "unknown-canary"}, + result={"document": {"text": "result-canary"}} if success else None, + error=None if success else ValueError("exception-canary"), + ) + dispatch.assert_called_once() + event = dispatch.call_args.args[0] + assert event.request_id == "req-1" + assert event.operation == KNOWLEDGE_SOURCE_LIVE + assert event.success is success + assert event.latency_ms == 22 + assert not event.run_id + assert not event.response_tokens + assert "canary" not in str(event.args) + + +@pytest.mark.asyncio +async def test_live_mcp_capture_ignores_namespace_consent(monkeypatch) -> None: + from server.observability import capture_consent + from server.transport.mcp_call import _capture_level + + consent = AsyncMock(return_value="full") + monkeypatch.setattr(capture_consent, "resolve", consent) + identity = {"org": "test-org", "namespace": "docs"} + assert await _capture_level(KNOWLEDGE_SOURCE_LIVE, identity) == "off" + consent.assert_not_awaited() + assert await _capture_level("knowledge.search", identity) == "full" + consent.assert_awaited_once_with("test-org", "docs") + + +@pytest.mark.asyncio +async def test_registered_live_operation_is_read_only_and_disabled_without_a_directory() -> None: + from server.knowledge.api.models_source_live import KnowledgeSourceLiveInput + from server.operations.registry import OPERATIONS_BY_NAME + from server.transport.http import build_router + + operation = OPERATIONS_BY_NAME["knowledge.source.live"] + assert operation.read_only + assert operation.http_path in {route.path for route in build_router().routes} + response = await operation.handler( + KnowledgeSourceLiveInput( + org="test-org", namespace="docs", name="test", resource_id="mcp://example/test" + ) + ) + assert response.status == "unavailable" + assert response.document is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("scope", ["own_user", "own_session", "pinned"]) +async def test_live_read_scope_refuses_at_http_and_mcp_admission(monkeypatch, scope) -> None: + from types import SimpleNamespace + + from fastapi import HTTPException + + from server.auth.jwt import AuthInfo + from server.knowledge.api.models_source_live import KnowledgeSourceLiveInput + from server.operations.registry import OPERATIONS_BY_NAME + from server.transport import gates, http, mcp_call + + op = OPERATIONS_BY_NAME[KNOWLEDGE_SOURCE_LIVE] + claims = {"read_user_id": "alice"} if scope == "pinned" else {"read_scope": scope} + auth = AuthInfo( + subject="alice", + org="test-org", + namespaces=("docs",), + roles=(), + is_service_account=False, + **claims, + ) + body = KnowledgeSourceLiveInput( + org="test-org", namespace="docs", name="test", resource_id="mcp://example/test" + ) + target = gates.authz_target(op, org=body.org, namespace=body.namespace, auth=auth) + policy = AsyncMock(side_effect=AssertionError("live read went past read-scope admission")) + monkeypatch.setattr(gates, "policy", policy) + monkeypatch.setattr(gates, "traffic_class", AsyncMock(return_value=("agent", "fixture"))) + arguments = body.model_dump() + request = SimpleNamespace(state=SimpleNamespace(), headers={}) + http_call = http._HttpCall(request_id="r", raw_body=arguments, auth=auth) + with pytest.raises(HTTPException) as refusal: + await http._bind_context_and_policy(op, request, http_call, target, body) + assert refusal.value.status_code == 403 + + mcp_call_data = mcp_call._AdmittedCall( + 1, op, body, arguments, auth, "r", "", body.namespace, body.org, target + ) + response = await mcp_call._admission_refusal(mcp_call_data) + assert response is not None and response["result"]["isError"] is True + assert "read scope" in response["result"]["content"][0]["text"] + policy.assert_not_awaited() + + +def test_direct_live_call_still_refuses_a_narrow_protected_context(monkeypatch) -> None: + from server.auth.jwt import AuthInfo + from server.knowledge.app import mcp_worker_protected as protected + from server.knowledge.app.mcp_worker_read import WorkerReadRefused + + wide = AuthInfo( + subject="alice", org="test-org", namespaces=("docs",), roles=(), is_service_account=False + ) + narrow = AuthInfo( + subject="alice", + org="test-org", + namespaces=("docs",), + roles=(), + is_service_account=False, + read_scope="own_session", + ) + monkeypatch.setattr(type(protected.settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(protected.settings, "knowledge_mirrored_sources_enabled", True) + monkeypatch.setattr(protected, "protected_for", lambda auth: True) + monkeypatch.setattr(protected, "current_auth", lambda: wide) + protected._require_context("test-org", wide) + + monkeypatch.setattr(protected, "current_auth", lambda: narrow) + with pytest.raises(WorkerReadRefused, match="^denied$"): + protected._require_context("test-org", narrow) + + +@pytest.mark.parametrize( + "req_id, invalid", + [ + ("x" * 4094, False), + ("文書📄", False), + ("x" * 4095, True), + ("\x01" * 1024, True), + ([1], True), + ], + ids=["near_limit", "unicode", "large", "escaped", "array"], +) +def test_live_mcp_bounds_response_id(req_id, invalid) -> None: + from server.transport.mcp_op import invalid_live_request_id + + assert ( + invalid_live_request_id( + {"method": "tools/call", "id": req_id, "params": {"name": "loom_knowledge_source_live"}} + ) + is invalid + ) + + +@pytest.mark.asyncio +async def test_live_refuses_unbounded_ignored_argument_names_in_both_transports( + monkeypatch, +) -> None: + from fastapi import HTTPException + + from server.knowledge.api.ops_worker_source import knowledge_source_live + from server.transport import http, mcp_call + + arguments = {"extra-" + "x" * 8192: True} + monkeypatch.setattr(http, "_emit_event", Mock()) + monkeypatch.setattr(mcp_call, "_emit_refused", Mock()) + request = Mock(json=AsyncMock(return_value=arguments)) + with pytest.raises(HTTPException) as refused: + await http._read_body(knowledge_source_live, request, "r", None) + assert refused.value.status_code == 422 + assert len(str(refused.value.detail)) < 512 + response = mcp_call._validated_input(1, knowledge_source_live, arguments, "r") + assert len(str(response)) < 512 + assert response["result"]["isError"] + assert "argument names" in str(response) + + +def _json_request(body: bytes): + from starlette.requests import Request + + return Request({"type": "http"}, AsyncMock(return_value={"type": "http.request", "body": body})) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tool", ["direct", "loom_op"]) +@pytest.mark.parametrize("entry", ["single", "batch", "version", "surrogate", "null", "missing"]) +async def test_live_mcp_refuses_invalid_id_at_the_endpoint(monkeypatch, tool, entry) -> None: + import json + + import httpx + from fastapi import FastAPI + + from server.transport import mcp + from server.transport.mcp_config import ( + _TRANSPORT_ERROR_ID, + INVALID_REQUEST, + UNSUPPORTED_PROTOCOL_VERSION, + ) + + request_id = {"surrogate": "\ud800", "null": None, "missing": None}.get(entry, 1 << 128) + screen = AsyncMock(return_value={"jsonrpc": "2.0", "id": request_id, "result": {}}) + monkeypatch.setattr(mcp, "_verify_bearer", AsyncMock(return_value=object())) + monkeypatch.setattr(mcp, "_screen_tool_call", screen) + arguments = {"namespace": "docs"} + params = ( + {"name": "loom_knowledge_source_live", "arguments": arguments} + if tool == "direct" + else { + "name": "loom_op", + "arguments": {"op": "knowledge_source.live", "arguments": arguments}, + } + ) + request = {"jsonrpc": "2.0", "id": request_id, "method": "tools/call", "params": params} + if entry == "missing": + del request["id"] + ping = {"jsonrpc": "2.0", "id": 1, "method": "ping"} + headers = {"Content-Type": "application/json"} + if entry == "version": + headers["MCP-Protocol-Version"] = "2099-01-01" + app = FastAPI() + mcp.attach(app) + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app)) as client: + response = await client.post( + "http://test/mcp", + content=json.dumps([request, ping] if entry == "batch" else request, ensure_ascii=True), + headers=headers, + ) + + body = response.json() + if entry == "batch": + body, sibling = body + assert sibling == {"jsonrpc": "2.0", "id": 1, "result": {}} + assert body["id"] == _TRANSPORT_ERROR_ID + expected = UNSUPPORTED_PROTOCOL_VERSION if entry == "version" else INVALID_REQUEST + assert body["error"]["code"] == expected + screen.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_live_refuses_an_escaped_lone_surrogate_argument_name(monkeypatch) -> None: + from fastapi import HTTPException + from fastapi.responses import JSONResponse + + from server.knowledge.api.ops_worker_source import knowledge_source_live + from server.transport import http, mcp_call + + monkeypatch.setattr(http, "_emit_event", Mock()) + monkeypatch.setattr(mcp_call, "_emit_refused", Mock()) + request = _json_request( + rb'{"org":"test","namespace":"docs","name":"test",' + rb'"resource_id":"mcp://example/test","\ud800":true}' + ) + with pytest.raises(HTTPException) as refusal: + await http._read_body(knowledge_source_live, request, "r", None) + assert refusal.value.status_code == 422 + response = mcp_call._validated_input(1, knowledge_source_live, await request.json(), "r") + assert JSONResponse(response).status_code == 200 + assert response["result"]["isError"] + + +@pytest.mark.parametrize("transport", ["http", "mcp"]) +def test_live_reports_ignored_names_only_to_the_caller(monkeypatch, caplog, transport) -> None: + from fastapi.responses import JSONResponse + + from server.operations.registry import OPERATIONS_BY_NAME + from server.transport import arg_check, lean_results + + monkeypatch.setattr(arg_check, "_NOTED", set()) + caplog.set_level("INFO", logger="server.transport.arg_check") + op = OPERATIONS_BY_NAME[KNOWLEDGE_SOURCE_LIVE] + name = "private-note\n東京" + arguments = {name: True} + result = {"status": "unavailable"} + assert arg_check.live_argument_names_fit(op.input_model, arguments) + if transport == "http": + body = arg_check.response_body(op, arguments, result) + assert arg_check.header_value(op, arguments, result) == "private-note%0A%E6%9D%B1%E4%BA%AC" + else: + body = lean_results.mcp_op_result(op.name, result, arguments, None) + assert JSONResponse(body).status_code == 200 + assert body["ignored_args"] == [name] + assert not arg_check._NOTED + assert "private-note" not in caplog.text + + +def test_live_ledger_classifies_a_fail_closed_refusal_as_the_servers(monkeypatch) -> None: + dispatch = Mock(return_value=False) + monkeypatch.setattr(ledger, "_dispatch_event", dispatch) + refusal = PermissionError("grant read failed") + refusal.unverified = True # type: ignore[attr-defined] + ledger.emit_agent_event( + op_name=KNOWLEDGE_SOURCE_LIVE, + identity={ + "org": "test-org", + "namespace": "docs", + "agent": "-", + "user_id": "-", + "session_id": "-", + }, + request_id="req-2", + latency_ms=5, + success=False, + error_code="AUTH_INSUFFICIENT", + raw_args={"name": "docs"}, + error=refusal, + ) + event = dispatch.call_args.args[0] + # The payload is dropped, yet the outage still counts against the server. + assert event.status_class == "server" + assert "grant read failed" not in str(event.args) + assert "error_class" not in event.args and "error" not in event.args diff --git a/tests/unit/test_mcp_worker_permissions.py b/tests/unit/test_mcp_worker_permissions.py new file mode 100644 index 00000000000..c9324a77bc2 --- /dev/null +++ b/tests/unit/test_mcp_worker_permissions.py @@ -0,0 +1,175 @@ +from dataclasses import replace +from uuid import UUID + +import pytest + +from server.knowledge.domain.mcp_worker_permissions import ( + ReaderConnection, + StoredCopyRevision, + VerifiedWorkerReadEvidence, + can_read_stored_copy, +) + +NOW = 1_800_000_000 + + +@pytest.fixture +def revision(): + return StoredCopyRevision( + org="org", + namespace="team", + source_id=UUID(int=1), + selection_generation=7, + resource_id_sha256="1" * 64, + revision_id=UUID(int=2), + content_sha256="2" * 64, + ) + + +@pytest.fixture +def connection(): + return ReaderConnection( + owner="alice", + worker_id=UUID(int=3), + connection_id=UUID(int=4), + connection_generation=11, + profile_digest="3" * 64, + ) + + +@pytest.fixture +def evidence(revision, connection): + return VerifiedWorkerReadEvidence( + confirmed_revision=revision, + connection=connection, + issued_at=NOW - 5, + confirmed_at=NOW - 3, + expires_at=NOW + 5, + ) + + +@pytest.fixture +def check(revision, connection, evidence): + def evaluate(**overrides): + inputs = dict( + collection_granted=True, + requester="alice", + current_revision=revision, + active_connection=connection, + evidence=evidence, + now=NOW, + max_evidence_age_seconds=10, + ) + return can_read_stored_copy(**(inputs | overrides)) + + return evaluate + + +def test_current_collection_grant_and_matching_evidence_allow_read(check): + assert check() + + +def test_importers_evidence_does_not_authorize_another_collection_reader( + check, revision, connection, evidence +): + bob_connection = replace(connection, owner="bob", connection_id=UUID(int=5)) + assert not check(requester="bob", active_connection=bob_connection) + assert not check(requester="bob", active_connection=connection) + assert check( + requester="bob", + active_connection=bob_connection, + evidence=replace(evidence, confirmed_revision=revision, connection=bob_connection), + ) + + +@pytest.mark.parametrize( + "overrides", + [ + {"collection_granted": False}, + {"collection_granted": None}, + {"collection_granted": 1}, + {"requester": None}, + {"current_revision": None}, + {"active_connection": None}, + {"evidence": None}, + ], +) +def test_unknown_or_revoked_authority_denies(check, overrides): + assert not check(**overrides) + + +def test_wire_shaped_evidence_does_not_authorize(check, evidence): + assert not check(evidence=vars(evidence)) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("org", "other-org"), + ("namespace", "other-collection"), + ("source_id", UUID(int=6)), + ("selection_generation", 9), + ("resource_id_sha256", "4" * 64), + ("revision_id", UUID(int=7)), + ("content_sha256", "5" * 64), + ], +) +def test_scope_or_revision_mismatch_denies_even_after_scope_or_content_returns( + check, revision, field, value +): + assert not check(current_revision=replace(revision, **{field: value})) + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("owner", "bob"), + ("worker_id", UUID(int=6)), + ("connection_id", UUID(int=7)), + ("connection_generation", 13), + ("profile_digest", "4" * 64), + ], +) +def test_connection_mismatch_denies_even_after_the_same_profile_returns( + check, connection, field, value +): + assert not check(active_connection=replace(connection, **{field: value})) + + +@pytest.mark.parametrize("field", ["resource_id_sha256", "content_sha256"]) +def test_even_matching_unknown_digests_deny(check, revision, evidence, field): + unknown = replace(revision, **{field: ""}) + assert not check( + current_revision=unknown, evidence=replace(evidence, confirmed_revision=unknown) + ) + + +def test_even_matching_unknown_profile_denies(check, connection, evidence): + unknown = replace(connection, profile_digest="") + assert not check(active_connection=unknown, evidence=replace(evidence, connection=unknown)) + + +def test_expiry_is_exclusive_and_confirmation_is_inclusive(check, evidence): + assert not check(now=evidence.confirmed_at - 1) + assert check(now=evidence.confirmed_at) + assert check(now=evidence.expires_at - 1) + assert not check(now=evidence.expires_at) + + +@pytest.mark.parametrize( + "overrides", + [ + {"issued_at": NOW + 1, "confirmed_at": NOW + 1}, + {"issued_at": NOW - 4, "confirmed_at": NOW - 5}, + {"issued_at": NOW, "confirmed_at": NOW, "expires_at": NOW}, + {"expires_at": NOW + 6}, + {"issued_at": True}, + ], +) +def test_invalid_or_overlong_evidence_interval_denies(check, evidence, overrides): + assert not check(evidence=replace(evidence, **overrides)) + + +@pytest.mark.parametrize("max_age", [0, -1, None, True]) +def test_unknown_or_invalid_freshness_policy_denies(check, max_age): + assert not check(max_evidence_age_seconds=max_age) diff --git a/tests/unit/test_mcp_worker_read.py b/tests/unit/test_mcp_worker_read.py new file mode 100644 index 00000000000..832ba31686a --- /dev/null +++ b/tests/unit/test_mcp_worker_read.py @@ -0,0 +1,354 @@ +import asyncio +import hashlib +import json +import ssl +import unittest +from dataclasses import replace +from functools import partial +from unittest.mock import AsyncMock, Mock, patch +from uuid import uuid4 + +import httpx +import jwt +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from server.knowledge.app import mcp_worker_protected +from server.knowledge.app.mcp_worker_authority import RequestedResource +from server.knowledge.app.mcp_worker_live import _display_link, read_selected_live +from server.knowledge.app.mcp_worker_protected import LiveSourceDirectory, protected_live_read +from server.knowledge.app.mcp_worker_read import ( + _CLOCK_SKEW_S, + WorkerReadChannel, + WorkerReadRefused, + WorkerReadScope, + live_grant_seconds, +) + + +class TestWorkerReadChannel(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.key = Ed25519PrivateKey.generate() + self.scope = WorkerReadScope( + worker_id=uuid4(), + org="org", + namespace="team", + source_id=uuid4(), + selection_generation=3, + requester="alice", + connection_id=uuid4(), + connection_generation=2, + profile_digest="e" * 64, + approval_generation=4, + resource_id="urn:source:Résumé", + ) + + async def _wire_fixture( + self, + request: httpx.Request, + *, + text: str = "alpha", + digest: str | None = None, + ) -> httpx.Response: + grant = jwt.decode( + request.headers["authorization"].removeprefix("Bearer "), + self.key.public_key(), + algorithms=["EdDSA"], + audience=f"urn:loom:source-worker:{self.scope.worker_id}", + issuer="loom", + ) + claims = grant["grant"] + binding = claims["binding"] + self.assertEqual(claims["version"], 1) + self.assertEqual(request.method, "POST") + self.assertEqual(binding["org"], "org") + self.assertEqual(binding["namespace"], "team") + self.assertEqual(binding["connection_id"], str(self.scope.connection_id)) + if binding["requester"] != "alice": + return httpx.Response(403) + if request.url.path == "/v1/live": + self.assertEqual(claims["operation"], "live") + document = { + "resource_id": binding["resource_id"], + "title": "Unpublished", + "text": text, + "revision": None, + "source_link": None, + "mime_type": "text/plain", + } + else: + self.assertEqual( + (request.url.path, claims["operation"]), ("/v1/check-access", "check_access") + ) + document = None + + async def wire(): + yield json.dumps( + { + "status": "ok", + "request_id": claims["request_id"], + "fetched_at": grant["iat"], + "content_sha256": digest or hashlib.sha256(text.encode()).hexdigest(), + "document": document, + } + ).encode() + + return httpx.Response(200, headers={"Content-Type": "application/json"}, content=wire()) + + def _channel( + self, + transport: httpx.AsyncBaseTransport | None = None, + *, + max_inflight: int = 8, + max_response_bytes: int = 8192, + tls: ssl.SSLContext | None = None, + ) -> WorkerReadChannel: + if transport is None: + transport = httpx.MockTransport(self._wire_fixture) + channel = WorkerReadChannel( + worker_id=self.scope.worker_id, + origin="https://source-worker.example.test", + issuer="loom", + signing_key=self.key, + grant_seconds=5, + max_response_bytes=max_response_bytes, + max_inflight=max_inflight, + tls=tls, + _transport=transport, + ) + self.addAsyncCleanup(channel.close) + return channel + + async def _authorized(self) -> WorkerReadScope: + return self.scope + + async def test_channel_accepts_checked_live_and_proof_wire(self) -> None: + channel = self._channel() + result = await channel.run(self.scope, "live", require_current=self._authorized) + self.assertIsNotNone(result.document) + assert result.document is not None + self.assertEqual(result.document.resource_id, self.scope.resource_id) + self.assertEqual(result.document.text, "alpha") + proof = await channel.run(self.scope, "check_access", require_current=self._authorized) + self.assertIsNone(proof.document) + self.assertEqual(proof.content_sha256, result.content_sha256) + + async def test_channel_distinguishes_utf8_budget_from_digest_mismatch(self) -> None: + cases = ( + ("é" * 2_000_001, None, "unsupported"), + ("a" * 4_000_001, None, "unsupported"), + ("é" * 2_000_001, "0" * 64, "denied"), + ) + for too_large, digest, reason in cases: + with self.subTest(chars=len(too_large), reason=reason): + transport = httpx.MockTransport( + partial(self._wire_fixture, text=too_large, digest=digest) + ) + channel = self._channel(transport, max_response_bytes=13_000_000) + with self.assertRaisesRegex(WorkerReadRefused, f"^{reason}$"): + await channel.run(self.scope, "live", require_current=self._authorized) + + async def test_revoked_core_scope_blocks_a_successful_worker_reply(self) -> None: + validations = 0 + + async def still_current() -> WorkerReadScope: + nonlocal validations + validations += 1 + return self.scope if validations == 1 else replace(self.scope, selection_generation=4) + + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await self._channel().run(self.scope, "live", require_current=still_current) + self.assertEqual(validations, 2) + + async def test_different_requester_cannot_use_alices_connection(self) -> None: + self.scope = replace(self.scope, requester="bob") + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await self._channel().run(self.scope, "live", require_current=self._authorized) + + async def test_live_publication_rechecks_selection_after_fetch(self) -> None: + channel = self._channel() + tail = [] + + async def retain(scope, validate, deadline) -> None: + await validate() + tail.append(validate) + + result = await read_selected_live( + resolve=self._authorized, + worker=lambda worker_id: channel if worker_id == self.scope.worker_id else None, + retain=retain, + deadline=asyncio.get_running_loop().time() + 2, + ) + self.assertEqual(result.text, "alpha") + self.assertEqual(result.resource_id, self.scope.resource_id) + self.assertTrue(result.uri.endswith("#" + str(self.scope.source_id))) + self.assertGreater(result.fetched_at, 0) + self.assertEqual(len(tail), 1) + self.scope = replace(self.scope, selection_generation=4) + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await tail[0]() + + async def _encode_live(self, text: str, *, request_id: int | str = 1, extra: str = ""): + from types import SimpleNamespace + + from starlette.responses import JSONResponse + + from server.knowledge.api.models_source_live import KnowledgeSourceLiveInput + from server.knowledge.api.ops_worker_source import knowledge_source_live + from server.knowledge.app.mcp_worker_live_op import read_source_live + from server.transport.arg_check import response_body + from server.transport.mcp_outcome import _success_response + + channel = self._channel( + httpx.MockTransport(partial(self._wire_fixture, text=text)), + max_response_bytes=25_000_000, + ) + result = await channel.run(self.scope, "live", require_current=self._authorized) + assert result.document is not None + self.assertEqual(result.document.text, text) + retain = AsyncMock() + request = KnowledgeSourceLiveInput( + org=self.scope.org, + namespace=self.scope.namespace, + name="documents", + resource_id=self.scope.resource_id, + ) + + async def read(_target, _directory, *, deadline): + return await read_selected_live( + resolve=self._authorized, worker=lambda _: channel, retain=retain, deadline=deadline + ) + + arguments = request.model_dump() + if extra: + arguments[extra] = True + call = SimpleNamespace( + req_id=request_id, + op=knowledge_source_live, + input_obj=request, + arguments=arguments, + auth=None, + request_id="request", + rl_ns=request.namespace, + rl_org=request.org, + ) + with ( + patch("server.knowledge.app.mcp_worker_live_op.protected_live_read", read), + patch("server.transport.post_rows.post_handler_rows", AsyncMock()), + ): + output = await read_source_live(request, Mock(spec=LiveSourceDirectory)) + mcp = await _success_response(call, output, 0, (None, None), None) + http = response_body(knowledge_source_live, arguments, output) + return retain, JSONResponse(http).body, JSONResponse(mcp).body + + async def test_live_refuses_unpublishable_worker_content_before_retaining_it(self) -> None: + for size in (1_400_000, 4_000_000): + with self.subTest(size=size): + retain, http, mcp = await self._encode_live("\x01" * size) + retain.assert_not_awaited() + self.assertLess(len(http), 1_024) + self.assertLess(len(mcp), 1_024) + result = json.loads(mcp)["result"] + for payload in ( + json.loads(http), + result["structuredContent"], + json.loads(result["content"][0]["text"]), + ): + self.assertEqual(payload["status"], "unsupported") + self.assertIsNone(payload.get("document")) + + async def test_live_preserves_content_fitting_both_encodings(self) -> None: + text = "\x01" * 1_200_000 + request_id = "x" * 4094 + extra = "unknown-" + "y" * 1000 + retain, http, mcp = await self._encode_live(text, request_id=request_id, extra=extra) + retain.assert_awaited_once() + self.assertLess(len(mcp), 16 * 1024 * 1024) + envelope = json.loads(mcp) + self.assertEqual(envelope["id"], request_id) + result = envelope["result"] + for payload in ( + json.loads(http), + result["structuredContent"], + json.loads(result["content"][0]["text"]), + ): + self.assertEqual(payload["status"], "ok") + self.assertEqual(payload["document"]["text"], text) + self.assertEqual(payload["ignored_args"], [extra]) + + async def test_expired_publication_is_never_retained(self) -> None: + deadline = asyncio.get_running_loop().time() - 1 + with ( + patch.object(mcp_worker_protected, "_require_context"), + patch.object(mcp_worker_protected.session_admission, "require", AsyncMock()), + patch.object(mcp_worker_protected.request_tail, "retain_publication") as retain, + ): + with self.assertRaisesRegex(WorkerReadRefused, "^timeout$"): + await mcp_worker_protected._retain(Mock(org="org"), AsyncMock(), deadline) + retain.assert_not_called() + + async def test_unprotected_request_cannot_look_up_any_worker_or_source(self) -> None: + def refuse(*args): + self.fail("directory was used by an unprotected request") + + directory = LiveSourceDirectory(refuse, refuse, refuse, refuse, refuse) + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await protected_live_read( + RequestedResource("org", "team", "source", self.scope.resource_id), + directory, + deadline=asyncio.get_running_loop().time() + 2, + ) + + def test_only_https_document_links_are_rendered_as_links(self) -> None: + url = "https://source.example.test/document#section" + self.assertEqual(_display_link(url), url) + for untrusted in ("urn:ref", "https://name@source.example.test/doc", "https://[invalid"): + self.assertIsNone(_display_link(untrusted)) + + async def test_refuses_worker_redirect_without_forwarding_grant(self) -> None: + seen = [] + + async def redirect(request: httpx.Request) -> httpx.Response: + seen.append(request.url.host) + return httpx.Response(307, headers={"Location": "https://upstream.example.test/mcp"}) + + channel = self._channel(httpx.MockTransport(redirect)) + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await channel.run(self.scope, "live", require_current=self._authorized) + self.assertEqual(seen, ["source-worker.example.test"]) + + async def test_live_capacity_refuses_without_opening_another_request(self) -> None: + started = asyncio.Event() + + async def wait_for_cancel(request: httpx.Request) -> httpx.Response: + started.set() + await asyncio.Future[None]() + raise AssertionError("waiting request was not cancelled") + + channel = self._channel(httpx.MockTransport(wait_for_cancel), max_inflight=1) + blocked = asyncio.create_task( + channel.run(self.scope, "live", require_current=self._authorized) + ) + await started.wait() + try: + with self.assertRaisesRegex(WorkerReadRefused, "^overloaded$"): + await channel.run(self.scope, "live", require_current=self._authorized) + finally: + blocked.cancel() + with self.assertRaises(asyncio.CancelledError): + await blocked + + def test_cannot_disable_tls_peer_verification(self) -> None: + tls = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + tls.check_hostname = False + with self.assertRaisesRegex(ValueError, "TLS verification is required"): + self._channel(tls=tls) + + +class TestLiveGrantLifetime(unittest.TestCase): + def test_a_live_grant_outlasts_the_read_across_a_second_boundary(self) -> None: + # A grant issued at 10.9 s is stamped 10; the read may run until 10.9 + timeout and + # the worker may stamp its fetch a second ahead of Loom's clock. + for timeout in (1.0, 2.5, 8.0): + with self.subTest(timeout=timeout): + expires_at = 10 + live_grant_seconds(timeout) + self.assertLess(10.9 + timeout + _CLOCK_SKEW_S, expires_at) diff --git a/tests/unit/test_mcp_worker_route_config.py b/tests/unit/test_mcp_worker_route_config.py new file mode 100644 index 00000000000..bb9ef2fb6cb --- /dev/null +++ b/tests/unit/test_mcp_worker_route_config.py @@ -0,0 +1,113 @@ +"""Worker route provisioning consumes deployment-owned file references only.""" + +import json +from datetime import UTC, datetime, timedelta + +import pytest +from cryptography import x509 +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, PrivateFormat +from cryptography.x509.oid import NameOID +from pydantic import ValidationError + +from server.core import pg +from server.knowledge.app.mcp_worker_route_config import load_worker_routes +from server.knowledge.app.mcp_worker_routes import open_worker_routes +from server.knowledge.app.mcp_worker_runtime import current_directory, source_worker_runtime +from server.settings import Settings + +_ROUTE = { + "worker_id": "d59962ea-a918-497a-a284-984c5ddc7dfd", + "origin": "https://worker.example", + "issuer": "loom", + "trust_ca_file": "trust.pem", + "client_certificate_file": "trust.pem", + "client_key_file": "client.pem", + "grant_key_file": "grant.pem", + "profiles": {"org": [{"digest": "f" * 64, "modes": ["live"]}]}, +} + + +def _write_private_key(path, key) -> None: + path.write_bytes(key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption())) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("pg_authority", [True, False]) +async def test_provision_operator_pins_trust_and_loads_only_loom_keys( + tmp_path, monkeypatch, pg_authority +) -> None: + monkeypatch.setattr(pg, "enabled", lambda: pg_authority) + client = Ed25519PrivateKey.generate() + grant = Ed25519PrivateKey.generate() + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "fixture")]) + now = datetime.now(UTC) + cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(client.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(days=1)) + .not_valid_after(now + timedelta(days=1)) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .sign(client, algorithm=None) + ) + (tmp_path / "trust.pem").write_bytes(cert.public_bytes(Encoding.PEM)) + _write_private_key(tmp_path / "client.pem", client) + _write_private_key(tmp_path / "grant.pem", grant) + path = tmp_path / "routes.json" + path.write_text(json.dumps({"version": 1, "workers": [_ROUTE]})) + (route,) = load_worker_routes(path) + assert route.tls.cert_store_stats()["x509_ca"] == 1 + assert route.grant_key.public_key().public_bytes_raw() == grant.public_key().public_bytes_raw() + async with open_worker_routes((route,)) as routes: + assert routes.permits(route.worker_id, "org", "f" * 64, "live", False) + assert current_directory() is None + monkeypatch.setenv("LOOM_KNOWLEDGE_SOURCE_WORKER_ROUTES_FILE", str(path)) + async with source_worker_runtime(Settings().knowledge_source_worker_routes_file): + directory = current_directory() + if pg_authority: + assert directory is not None + assert directory.worker(route.worker_id) is not None + else: + assert directory is None + assert current_directory() is None + + +@pytest.mark.asyncio +async def test_runtime_without_configuration_leaves_directory_disabled() -> None: + async with source_worker_runtime(""): + assert current_directory() is None + + +def test_route_file_rejects_inline_upstream_credentials_without_echo(tmp_path) -> None: + path = tmp_path / "routes.json" + path.write_text( + json.dumps({"version": 1, "workers": [{**_ROUTE, "upstream_bearer": "not-a-real-token"}]}) + ) + with pytest.raises(ValueError, match="^invalid source worker route configuration$") as error: + load_worker_routes(path) + assert error.value.__suppress_context__ + + +@pytest.mark.parametrize( + ("field", "configured", "above_limit"), + [ + ("knowledge_source_worker_frame_timeout_s", 0.25, 1.01), + ("knowledge_source_worker_live_timeout_s", 4.0, 8.01), + ("knowledge_source_worker_publication_timeout_s", 1.0, 2.01), + ("knowledge_source_worker_selection_parallelism", 1, 3), + ], +) +def test_worker_limits_accept_lower_values_and_reject_out_of_range_values( + monkeypatch, field: str, configured: float, above_limit: float +) -> None: + env = f"LOOM_{field.upper()}" + monkeypatch.setenv(env, str(configured)) + assert getattr(Settings(), field) == configured + for invalid in (0, above_limit): + monkeypatch.setenv(env, str(invalid)) + with pytest.raises(ValidationError) as error: + Settings() + assert [item["loc"] for item in error.value.errors()] == [(field,)] diff --git a/tests/unit/test_mcp_worker_routes.py b/tests/unit/test_mcp_worker_routes.py new file mode 100644 index 00000000000..f6e1f2bf97d --- /dev/null +++ b/tests/unit/test_mcp_worker_routes.py @@ -0,0 +1,87 @@ +"""Operator provisioning cannot be substituted by a database approval.""" + +import ssl +from dataclasses import replace +from unittest.mock import AsyncMock +from uuid import uuid4 + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from server.knowledge.app import mcp_worker_pg_directory +from server.knowledge.app.mcp_worker_routes import WorkerProfile, WorkerRoute, open_worker_routes + +_PROFILE = "3" * 64 + + +def _route() -> WorkerRoute: + return WorkerRoute( + worker_id=uuid4(), + tls_origin="https://worker.example", + tls=ssl.create_default_context(), + issuer="loom", + grant_key=Ed25519PrivateKey.generate(), + enrollment_verifier=Ed25519PrivateKey.generate().public_key(), + profiles=(WorkerProfile("org", _PROFILE, frozenset({"live"})),), + max_live_requests=2, + ) + + +@pytest.mark.asyncio +async def test_database_approval_requires_exact_provisioned_route(monkeypatch) -> None: + route = _route() + current = AsyncMock(return_value=17) + monkeypatch.setattr(mcp_worker_pg_directory.approvals, "current_generation", current) + async with open_worker_routes((route,)) as routes: + directory = mcp_worker_pg_directory.live_directory(routes) + assert directory.worker(route.worker_id) is not None + assert directory.worker(uuid4()) is None + assert not await directory.worker_approval( + "other", "docs", route.worker_id, _PROFILE, "live", False + ) + assert not await directory.worker_approval( + "org", "docs", route.worker_id, "f" * 64, "live", False + ) + assert not await directory.worker_approval( + "org", "docs", route.worker_id, _PROFILE, "live", True + ) + assert not await directory.worker_approval( + "org", "docs", route.worker_id, _PROFILE, "snapshot", False + ) + current.assert_not_awaited() + assert ( + await directory.worker_approval("org", "docs", route.worker_id, _PROFILE, "live", False) + == 17 + ) + current.assert_awaited_once_with("org", "docs", route.worker_id, _PROFILE, "live", False) + + +@pytest.mark.asyncio +async def test_routes_reject_duplicate_workers_and_insecure_credentials() -> None: + route = _route() + insecure = ssl._create_unverified_context() + for entries in ( + (route, route), + (replace(route, tls=insecure),), + (replace(route, enrollment_verifier=route.grant_key.public_key()),), + (replace(route, profiles=(WorkerProfile("*", _PROFILE, frozenset({"live"})),)),), + ): + with pytest.raises(ValueError, match="invalid source worker (route|profile)"): + async with open_worker_routes(entries): + pytest.fail("invalid route opened") + + +@pytest.mark.asyncio +async def test_enrollment_keys_require_the_exact_provision_and_a_current_generation() -> None: + route = _route() + async with open_worker_routes((route,)) as routes: + assert routes.enrollment_route(route.worker_id, "other", "docs", _PROFILE, 1) is None + assert routes.enrollment_route(route.worker_id, "org", "docs", "9" * 64, 1) is None + assert routes.enrollment_route(route.worker_id, "org", "docs", _PROFILE, 0) is None + binding = routes.enrollment_route(route.worker_id, "org", "docs", _PROFILE, 17) + assert binding is not None + assert binding.approval_namespace == "docs" and binding.approval_generation == 17 + assert binding.worker_key is route.enrollment_verifier + assert binding.channel is routes.get(route.worker_id) + async with open_worker_routes((replace(route, enrollment_verifier=None),)) as routes: + assert routes.enrollment_route(route.worker_id, "org", "docs", _PROFILE, 17) is None diff --git a/tests/unit/test_mcp_worker_selection.py b/tests/unit/test_mcp_worker_selection.py new file mode 100644 index 00000000000..2c8f2b65ba6 --- /dev/null +++ b/tests/unit/test_mcp_worker_selection.py @@ -0,0 +1,84 @@ +import asyncio +import unittest +from dataclasses import replace +from unittest.mock import create_autospec, patch +from uuid import UUID + +from server.knowledge.app.mcp_worker_read import WorkerReadChannel, WorkerReadRefused +from server.knowledge.app.mcp_worker_selection import SelectionAuthority, verify_worker_selection +from server.knowledge.domain.mcp_identity import ResourceIdentity, selection_sha256 +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection +from server.settings import settings + + +class TestSelectionVerification(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + connection = ReaderConnection("alice", UUID(int=1), UUID(int=2), 3, "b" * 64) + self.authority = SelectionAuthority( + "org", "team", UUID(int=4), UUID(int=5), 6, 7, connection + ) + self.standing: SelectionAuthority | None = self.authority + self.resources = tuple( + ResourceIdentity(id=f"urn:document:{number}", type="resource") for number in range(5) + ) + self.channel = create_autospec(WorkerReadChannel, instance=True) + self.started: list[str] = [] + self.inflight = 0 + self.peak = 0 + + async def _current(self): + return self.standing + + async def _check_only(self, scope, operation, require_current): + self.assertEqual(operation, "check_access") + self.assertEqual(scope, await require_current()) + self.assertEqual(scope.connection_id, self.authority.connection.connection_id) + self.started.append(scope.resource_id) + self.inflight += 1 + self.peak = max(self.peak, self.inflight) + try: + await asyncio.sleep(0) + self.assertEqual(scope, await require_current()) + finally: + self.inflight -= 1 + + async def _verify(self): + return await verify_worker_selection( + self.authority, + self.resources, + mode="snapshot", + channel=self.channel, + current=self._current, + deadline=asyncio.get_running_loop().time() + 1, + ) + + async def test_all_resources_are_checked_under_sealed_destination_and_bounded_concurrency(self): + self.channel.run.side_effect = self._check_only + receipt = await self._verify() + self.assertEqual(self.started, [item.id for item in self.resources]) + self.assertEqual(self.peak, 2) + self.assertEqual(self.inflight, 0) + self.assertEqual(receipt.resources_sha256, selection_sha256(self.resources)) + self.assertEqual(receipt.destination_id, self.authority.destination_id) + self.assertEqual(receipt.source_id, self.authority.source_id) + self.assertEqual(receipt.selection_generation, self.authority.selection_generation) + + async def test_configured_serial_checks_still_verify_the_whole_selection(self): + self.channel.run.side_effect = self._check_only + with patch.object(settings, "knowledge_source_worker_selection_parallelism", 1): + receipt = await self._verify() + self.assertEqual(self.started, [item.id for item in self.resources]) + self.assertEqual(self.peak, 1) + self.assertEqual(receipt.resources_sha256, selection_sha256(self.resources)) + + async def test_revocation_cancels_batch_without_a_grant_or_remaining_requests(self): + async def read(scope, operation, require_current): + if scope.resource_id == self.resources[0].id: + self.standing = replace(self.authority, approval_generation=8) + await self._check_only(scope, operation, require_current) + + self.channel.run.side_effect = read + with self.assertRaisesRegex(WorkerReadRefused, "^denied$"): + await self._verify() + self.assertEqual(self.channel.run.await_count, 2) + self.assertEqual(self.inflight, 0) diff --git a/tests/unit/test_mcp_worker_send_fence.py b/tests/unit/test_mcp_worker_send_fence.py new file mode 100644 index 00000000000..e1055908415 --- /dev/null +++ b/tests/unit/test_mcp_worker_send_fence.py @@ -0,0 +1,207 @@ +import asyncio +from contextlib import asynccontextmanager +from dataclasses import replace +from unittest.mock import AsyncMock +from uuid import uuid4 + +import pytest + +from server.knowledge.app import mcp_worker_pg_directory as directory +from server.knowledge.app.mcp_worker_read import WorkerReadRefused, WorkerReadScope +from server.knowledge.domain.mcp_worker_permissions import ReaderConnection + +_WORKER, _SOURCE, _ALICE, _BOB = uuid4(), uuid4(), uuid4(), uuid4() +_PROFILE = "a" * 64 +_SCOPE = WorkerReadScope( + _WORKER, + "org", + "team", + _SOURCE, + 9, + "bob", + _BOB, + 4, + _PROFILE, + 2, + "urn:resource:selected", + 3, + ReaderConnection("alice", _WORKER, _ALICE, 5, _PROFILE), +) + + +async def recheck() -> None: + """The source is still the one the frame checked.""" + + +@pytest.fixture +def authority(monkeypatch): + conn = object() + open_transaction = False + + @asynccontextmanager + async def transaction(key, *, sources=False): + nonlocal open_transaction + assert key == directory.approvals.ApprovalKey("org", "team", _WORKER, _PROFILE) + # A live frame holds the source lock with the knowledge lock. + assert sources + open_transaction = True + try: + yield conn + finally: + open_transaction = False + + async def deliver(): + assert open_transaction + + approve = AsyncMock(return_value=directory.approvals.WorkerApproval(2, 1, True, True)) + link = AsyncMock(return_value=directory.readers.Link(9, _BOB, 4, 3, True)) + account = AsyncMock( + side_effect=[ + (_PROFILE, directory.accounts.AccountState(5, True, "realm")), + (_PROFILE, directory.accounts.AccountState(4, True, "realm")), + ] + ) + monkeypatch.setattr(directory.approvals, "scope_transaction", transaction) + monkeypatch.setattr(directory.approvals, "current_on", approve) + monkeypatch.setattr(directory.readers, "current_on", link) + monkeypatch.setattr(directory.accounts, "reader_account_on", account) + return conn, approve, link, account, AsyncMock(side_effect=deliver) + + +@pytest.mark.asyncio +async def test_protected_send_uses_current_locked_approval_link_and_exact_accounts(authority): + conn, approve, link, account, deliver = authority + await directory.fence_live_delivery( + _SCOPE, deliver, asyncio.get_running_loop().time() + 2, recheck + ) + approve.assert_awaited_once_with( + conn, directory.approvals.ApprovalKey("org", "team", _WORKER, _PROFILE), lock=True + ) + link.assert_awaited_once_with( + conn, directory.readers.LinkKey("org", "team", _SOURCE, "bob"), lock=True + ) + assert [c.args for c in account.await_args_list] == [ + (conn, "org", "alice", _WORKER, _ALICE), + (conn, "org", "bob", _WORKER, _BOB), + ] + assert all(c.kwargs == {"lock": True} for c in account.await_args_list) + deliver.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_a_source_change_seen_under_the_source_lock_withholds_the_frame(authority): + _, approve, _, _, deliver = authority + changed = AsyncMock(side_effect=WorkerReadRefused("denied")) + with pytest.raises(WorkerReadRefused, match="^denied$"): + await directory.fence_live_delivery( + _SCOPE, deliver, asyncio.get_running_loop().time() + 2, changed + ) + changed.assert_awaited_once() + approve.assert_not_awaited() + deliver.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("revoked", ["approval", "link", "account", "realm"]) +async def test_final_send_is_refused_after_prior_authority_changes(authority, revoked): + _, approve, link, account, deliver = authority + if revoked == "approval": + approve.return_value = replace(approve.return_value, generation=3) + elif revoked == "link": + link.return_value = replace(link.return_value, active=False) + else: + account.side_effect = [ + (_PROFILE, directory.accounts.AccountState(5, revoked != "account", "realm")), + (_PROFILE, directory.accounts.AccountState(4, True, "different realm")), + ] + with pytest.raises(WorkerReadRefused, match="^denied$"): + await directory.fence_live_delivery( + _SCOPE, deliver, asyncio.get_running_loop().time() + 2, recheck + ) + deliver.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("revoked", [False, True]) +async def test_large_live_body_fits_the_publication_budget_without_repeat_lookups( + monkeypatch, revoked +): + from types import SimpleNamespace + + from starlette.responses import Response + + from server.core import request_tail + from server.knowledge.app import mcp_worker_protected as protected + + body = b"x" * (16 * 1024 * 1024) + sent = 0 + elapsed_ms = 0 + checks = 0 + transactions = 0 + source_locked = False + + async def check(): + nonlocal elapsed_ms, checks + # Simulate the elapsed budget without waiting for a wall clock. + elapsed_ms += 20 + if elapsed_ms >= 2000: + raise TimeoutError + assert not source_locked + checks += 1 + if revoked and sent: + raise WorkerReadRefused("denied") + + async def fence(scope, deliver, deadline, recheck_source): + nonlocal elapsed_ms, transactions, source_locked + assert scope == _SCOPE + elapsed_ms += 10 + if elapsed_ms >= 2000: + raise TimeoutError + # The fence transaction holds the source lock shared while it sends. + source_locked = True + try: + transactions += 1 + await deliver() + finally: + source_locked = False + + async def live_read(*, resolve, worker, retain, deadline): + await check() # The read already verifies current authority before retention. + await retain(_SCOPE, check, deadline) + + async def app(scope, receive, send): + await protected.protected_live_read( + SimpleNamespace(org=_SCOPE.org), + SimpleNamespace( + fence_delivery=fence, + source=None, + connection=None, + enrollment=None, + worker=None, + worker_approval=None, + ), + deadline=asyncio.get_running_loop().time() + 5, + ) + await Response(body)(scope, receive, send) + + async def send(message): + nonlocal sent + assert source_locked + sent += len(message.get("body", b"")) + + auth = SimpleNamespace(org=_SCOPE.org) + monkeypatch.setattr(protected, "current_auth", lambda: auth) + monkeypatch.setattr(protected, "_require_context", lambda org, auth: None) + monkeypatch.setattr(protected, "read_selected_live", live_read) + monkeypatch.setattr(protected.request_work, "mark_mirrored", lambda: True) + monkeypatch.setattr(protected.session_admission, "require", AsyncMock()) + response = request_tail.RequestTailMiddleware(app)({"type": "http"}, None, send) + if revoked: + with pytest.raises(request_tail.RequiredTailError): + await response + assert 0 < sent < len(body) + assert checks == transactions + 2 + else: + await response + assert sent == len(body) + assert checks == transactions + 1 diff --git a/tests/unit/test_mcp_worker_setup.py b/tests/unit/test_mcp_worker_setup.py new file mode 100644 index 00000000000..fd18393ac09 --- /dev/null +++ b/tests/unit/test_mcp_worker_setup.py @@ -0,0 +1,416 @@ +from dataclasses import replace +from hashlib import sha256 +from uuid import UUID + +import pytest + +from server.knowledge.domain.mcp_identity import ResourceIdentity, selection_sha256 +from server.knowledge.domain.mcp_worker_permissions import ( + ReaderConnection, + StoredCopyRevision, + VerifiedWorkerReadEvidence, + can_read_stored_copy, +) +from server.knowledge.domain.mcp_worker_setup import ( + MAX_SELECTION_GRANT_AGE_SECONDS, + MAX_SETUP_RESOURCES, + ApprovedWorkerAccount, + SetupCaller, + SetupDestination, + SetupIntent, + SetupState, + VerifiedSelectionGrant, + WorkerSetupRejected, + confirm_worker_setup, + plan_worker_setup, +) +from server.knowledge.domain.mcp_worker_source import decode_worker_source, encode_worker_source + +NOW = 1_800_000_000 + + +def _resource(identifier: str) -> ResourceIdentity: + return ResourceIdentity(type="resource", id=identifier) + + +@pytest.fixture +def intent(): + return SetupIntent((_resource("doc:one"), _resource("doc:two")), "snapshot") + + +def _grant(account: ApprovedWorkerAccount, intent: SetupIntent) -> VerifiedSelectionGrant: + return VerifiedSelectionGrant( + account.org, + account.connection, + account.approval_generation, + selection_sha256(intent.selection), + NOW - 1, + NOW + 10, + "team", + UUID(int=5), + UUID(int=8), + 9, + ) + + +@pytest.fixture +def state(intent): + caller = SetupCaller("org", "alice", "assistant") + account = ApprovedWorkerAccount( + "org", + ReaderConnection("alice", UUID(int=1), UUID(int=2), 3, "a" * 64), + approval_generation=4, + active=True, + modes=frozenset(("live", "snapshot", "selected_refresh")), + verified_resource_space="realm", + exact_reader_checks=True, + ) + return SetupState( + caller=caller, + destination=SetupDestination( + "org", + "team", + UUID(int=5), + "team", + 6, + 7, + caller, + ordinary=True, + can_write=True, + team_approved=True, + ), + account=account, + selection_grant=_grant(account, intent), + source_id=UUID(int=8), + selection_generation=9, + policy_generation=10, + now=NOW, + store_qualified=True, + erasure_qualified=True, + ) + + +def _bob_state(state: SetupState, intent: SetupIntent) -> SetupState: + caller = replace(state.caller, subject="bob") + account = replace( + state.account, + connection=replace(state.account.connection, owner="bob", connection_id=UUID(int=11)), + ) + return replace( + state, + caller=caller, + destination=replace(state.destination, grantee=caller), + account=account, + selection_grant=_grant(account, intent), + ) + + +def test_confirmation_recomputes_registration_without_accepting_preview_fields(state, intent): + plan = plan_worker_setup(state, intent) + current = replace(state, now=NOW + 1) + assert plan.preview.expires_at == state.selection_grant.expires_at + confirmed = confirm_worker_setup(plan.fingerprint, state=current, intent=intent) + assert confirmed == plan + assert confirmed is not plan + row = encode_worker_source( + org=confirmed.caller.org, + namespace=confirmed.namespace, + source_id=confirmed.source_id, + owner=confirmed.caller.subject, + name="selection", + config=confirmed.config, + selection=confirmed.selection, + ) + assert decode_worker_source(row) == (confirmed.config, intent.selection) + + +def test_bob_needs_own_account_and_exact_selection_grant(state, intent): + plan = plan_worker_setup(state, intent) + bob = _bob_state(state, intent) + with pytest.raises(WorkerSetupRejected, match="^authority_unavailable$"): + plan_worker_setup(replace(bob, account=state.account), intent) + with pytest.raises(WorkerSetupRejected, match="^selection_unverified$"): + plan_worker_setup(replace(bob, selection_grant=state.selection_grant), intent) + assert ( + plan_worker_setup(bob, intent).config.owner_connection_id != plan.config.owner_connection_id + ) + with pytest.raises(WorkerSetupRejected, match="^stale_preview$"): + confirm_worker_setup(plan.fingerprint, state=bob, intent=intent) + + +def test_personal_namespace_stays_owner_only_even_when_team_requested(state, intent): + personal = replace( + state.destination, kind="automatic_personal", personal_owner="alice", namespace="personal" + ) + state = replace( + state, + destination=personal, + selection_grant=replace(state.selection_grant, namespace=personal.namespace), + ) + plan = plan_worker_setup(state, replace(intent, share_with_team=True)) + assert plan.config.reader_policy == plan.preview.reader_policy == "owner_only" + assert plan.preview.requires_collection_grant + bob = _bob_state(state, intent) + with pytest.raises(WorkerSetupRejected, match="^authority_unavailable$"): + plan_worker_setup(bob, intent) + + +def test_team_policy_requires_opt_in_and_does_not_grant_readers_access(state, intent): + assert plan_worker_setup(state, intent).preview.reader_policy == "owner_only" + plan = plan_worker_setup(state, replace(intent, share_with_team=True)) + assert plan.config.reader_policy == plan.preview.reader_policy == "current_team_access" + assert plan.preview.requires_collection_grant + assert plan.preview.requires_exact_reader_evidence + assert not plan.preview.syncs_upstream_acls + + +def test_team_preview_and_owner_grant_do_not_replace_bobs_exact_read_evidence(state, intent): + plan = plan_worker_setup(state, replace(intent, share_with_team=True)) + revision = StoredCopyRevision( + plan.caller.org, + plan.namespace, + plan.source_id, + plan.config.selection_generation, + sha256(plan.selection[0].id.encode()).hexdigest(), + UUID(int=12), + "b" * 64, + ) + alice_proof = VerifiedWorkerReadEvidence(revision, state.account.connection, NOW, NOW, NOW + 1) + bob = _bob_state(state, intent).account.connection + bob_proof = replace(alice_proof, connection=bob) + + def check(granted, proof): + return can_read_stored_copy( + collection_granted=granted, + requester=bob.owner, + current_revision=revision, + active_connection=bob, + evidence=proof, + now=NOW, + max_evidence_age_seconds=1, + ) + + assert not check(True, None) + assert not check(True, alice_proof) + other_revision = replace(revision, revision_id=UUID(int=13)) + assert not check(True, replace(bob_proof, confirmed_revision=other_revision)) + assert not check(False, bob_proof) + assert check(True, bob_proof) + + +@pytest.mark.parametrize( + ("record", "changes"), + [ + ("destination", {"kind": "private"}), + ("destination", {"team_approved": False}), + ("account", {"verified_resource_space": None}), + ("account", {"exact_reader_checks": False}), + ], +) +def test_team_requires_approval_realm_and_per_reader_capability(state, intent, record, changes): + state = replace(state, **{record: replace(getattr(state, record), **changes)}) + assert plan_worker_setup(state, intent).preview.reader_policy == "owner_only" + with pytest.raises(WorkerSetupRejected, match="^team_unavailable$"): + plan_worker_setup(state, replace(intent, share_with_team=True)) + + +@pytest.mark.parametrize( + ("record", "changes", "reason"), + [ + ("destination", {"can_write": False}, "authority_unavailable"), + ("destination", {"ordinary": False}, "authority_unavailable"), + ("destination", {"org": "other"}, "authority_unavailable"), + ("account", {"active": False}, "authority_unavailable"), + ("selection_grant", {"expires_at": NOW}, "selection_unverified"), + ("selection_grant", {"confirmed_at": NOW + 1}, "selection_unverified"), + ( + "selection_grant", + {"confirmed_at": NOW - MAX_SELECTION_GRANT_AGE_SECONDS}, + "selection_unverified", + ), + ("selection_grant", {"org": "other"}, "selection_unverified"), + ("selection_grant", {"approval_generation": 1}, "selection_unverified"), + ], +) +def test_prior_preview_does_not_override_current_grants(state, intent, record, changes, reason): + preview = plan_worker_setup(state, intent) + current = replace(state, **{record: replace(getattr(state, record), **changes)}) + with pytest.raises(WorkerSetupRejected, match=f"^{reason}$"): + confirm_worker_setup(preview.fingerprint, state=current, intent=intent) + + +def test_denied_or_revoked_selection_has_no_grant(state, intent): + preview = plan_worker_setup(state, intent) + with pytest.raises(WorkerSetupRejected, match="^selection_unverified$"): + confirm_worker_setup( + preview.fingerprint, state=replace(state, selection_grant=None), intent=intent + ) + + +@pytest.mark.parametrize( + ("record", "changes"), + [ + ("destination", {"grant_generation": 101}), + ("destination", {"generation": 101}), + ("destination", {"destination_id": UUID(int=101)}), + ("destination", {"namespace": "other"}), + ("destination", {"kind": "private"}), + ("account", {"approval_generation": 101}), + ("account", {"verified_resource_space": "other"}), + ("connection", {"connection_generation": 101}), + ("connection", {"profile_digest": "b" * 64}), + ("connection", {"worker_id": UUID(int=101)}), + ("state", {"policy_generation": 101}), + ("state", {"selection_generation": 101}), + ("state", {"source_id": UUID(int=101)}), + ("caller", {"agent": "other"}), + ], +) +def test_confirmation_rejects_changed_authority_even_when_still_eligible( + state, intent, record, changes +): + preview = plan_worker_setup(state, intent) + if record == "state": + current = replace(state, **changes) + elif record == "connection": + account = replace(state.account, connection=replace(state.account.connection, **changes)) + current = replace(state, account=account, selection_grant=_grant(account, intent)) + elif record == "account": + account = replace(state.account, **changes) + current = replace(state, account=account, selection_grant=_grant(account, intent)) + elif record == "caller": + caller = replace(state.caller, **changes) + current = replace( + state, caller=caller, destination=replace(state.destination, grantee=caller) + ) + else: + current = replace(state, destination=replace(state.destination, **changes)) + current = replace( + current, + selection_grant=replace( + current.selection_grant, + namespace=current.destination.namespace, + destination_id=current.destination.destination_id, + source_id=current.source_id, + selection_generation=current.selection_generation, + ), + ) + assert plan_worker_setup(current, intent).fingerprint != preview.fingerprint + with pytest.raises(WorkerSetupRejected, match="^stale_preview$"): + confirm_worker_setup(preview.fingerprint, state=current, intent=intent) + + +def test_selection_evidence_cannot_move_to_a_different_collection(state, intent): + destination = replace(state.destination, namespace="other", destination_id=UUID(int=101)) + with pytest.raises(WorkerSetupRejected, match="^selection_unverified$"): + plan_worker_setup(replace(state, destination=destination), intent) + + +def test_new_selection_evidence_requires_a_new_preview(state, intent): + plan = plan_worker_setup(state, intent) + renewed = replace( + state, + now=NOW + 1, + selection_grant=replace(state.selection_grant, confirmed_at=NOW + 1, expires_at=NOW + 11), + ) + with pytest.raises(WorkerSetupRejected, match="^stale_preview$"): + confirm_worker_setup(plan.fingerprint, state=renewed, intent=intent) + + +@pytest.mark.parametrize("fingerprint", [None, "a" * 63, "é" * 64, "a" * 64]) +def test_confirmation_rejects_invalid_fingerprint(state, intent, fingerprint): + with pytest.raises(WorkerSetupRejected, match="^stale_preview$"): + confirm_worker_setup(fingerprint, state=state, intent=intent) + + +@pytest.mark.parametrize("change", ["reorder", "replace"]) +def test_exact_selection_must_be_reviewed_again(state, intent, change): + initial = plan_worker_setup(state, intent) + selected = intent.selection[::-1] if change == "reorder" else (_resource("doc:three"),) + changed = replace(intent, selection=selected) + with pytest.raises(WorkerSetupRejected, match="^selection_unverified$"): + plan_worker_setup(state, changed) + current = replace(state, selection_grant=_grant(state.account, changed)) + with pytest.raises(WorkerSetupRejected, match="^stale_preview$"): + confirm_worker_setup(initial.fingerprint, state=current, intent=changed) + + +@pytest.mark.parametrize( + "selection", + [ + (), + (_resource("doc:duplicate"),) * 2, + tuple(_resource(f"doc:{index}") for index in range(MAX_SETUP_RESOURCES + 1)), + tuple(_resource(f"{index}:" + "é" * 1000) for index in range(70)), + ], + ids=["empty", "duplicate", "count", "bytes"], +) +def test_selection_size_limits(state, intent, selection): + with pytest.raises(WorkerSetupRejected, match="^invalid_selection$"): + plan_worker_setup(state, replace(intent, selection=selection)) + + +def test_refresh_rejects_resource_id_not_representable_in_job(state, intent): + intent = replace( + intent, selection=(_resource("é" * 513),), mode="selected_refresh", interval_seconds=300 + ) + with pytest.raises(WorkerSetupRejected, match="^invalid_selection$"): + plan_worker_setup(state, intent) + + +@pytest.mark.parametrize("qualification", ["store_qualified", "erasure_qualified"]) +def test_only_durable_modes_require_store_and_erasure_qualification(state, intent, qualification): + current = replace(state, **{qualification: False}) + for mode, interval in (("snapshot", None), ("selected_refresh", 300)): + with pytest.raises(WorkerSetupRejected, match="^storage_unqualified$"): + plan_worker_setup(current, replace(intent, mode=mode, interval_seconds=interval)) + preview = plan_worker_setup(current, replace(intent, mode="live")).preview + assert not preview.stores_copy + assert not preview.writes_memory + assert not preview.scheduled_refresh + assert not preview.checks_explicit_deletion + + +def test_profile_must_approve_exact_mode(state, intent): + account = replace(state.account, modes=frozenset(("snapshot",))) + current = replace(state, account=account) + assert plan_worker_setup(current, intent).preview.stores_copy + with pytest.raises(WorkerSetupRejected, match="^unsupported_mode$"): + plan_worker_setup(current, replace(intent, mode="live")) + + +@pytest.mark.parametrize( + ("mode", "interval"), + [ + ("live", 300), + ("snapshot", 300), + ("selected_refresh", None), + ("selected_refresh", 299), + ("selected_refresh", 86_401), + ("selected_refresh", 300.0), + ], +) +def test_cadence_is_only_for_selected_refresh_and_bounded(state, intent, mode, interval): + with pytest.raises(WorkerSetupRejected, match="^invalid_setup$"): + plan_worker_setup(state, replace(intent, mode=mode, interval_seconds=interval)) + + +def test_confirmation_requires_same_mode_and_cadence(state, intent): + refresh = replace(intent, mode="selected_refresh", interval_seconds=300) + plan = plan_worker_setup(state, refresh) + for changed in (intent, replace(refresh, interval_seconds=86_400)): + with pytest.raises(WorkerSetupRejected, match="^stale_preview$"): + confirm_worker_setup(plan.fingerprint, state=state, intent=changed) + + +def test_refresh_without_delete_evidence_does_not_claim_a_delete_path(state, intent): + refresh = replace(intent, mode="selected_refresh", interval_seconds=300) + plan = plan_worker_setup(state, refresh) + assert plan.preview.stores_copy and plan.preview.scheduled_refresh + assert not plan.preview.checks_explicit_deletion + assert not plan.preview.syncs_upstream_acls + current = replace(state, account=replace(state.account, explicit_deletion_checks=True)) + assert plan_worker_setup(current, refresh).preview.checks_explicit_deletion + assert not plan_worker_setup(current, intent).preview.checks_explicit_deletion + with pytest.raises(WorkerSetupRejected, match="^stale_preview$"): + confirm_worker_setup(plan.fingerprint, state=current, intent=refresh) diff --git a/tests/unit/test_mcp_worker_source.py b/tests/unit/test_mcp_worker_source.py new file mode 100644 index 00000000000..8f4eeff2c13 --- /dev/null +++ b/tests/unit/test_mcp_worker_source.py @@ -0,0 +1,115 @@ +import json +import unittest +from dataclasses import replace +from unittest.mock import AsyncMock +from uuid import UUID, uuid4 + +from server.knowledge.domain.mcp_worker_source import ( + WORKER_REGISTRATION, + WorkerSourceRefused, + decode_worker_source, + encode_worker_source, +) +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource +from server.knowledge.store.sources import get_source, insert_source + + +class TestWorkerSource(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + connection = str(uuid4()) + self.config = { + "version": 2, + "worker_id": str(uuid4()), + "profile_digest": "a" * 64, + "owner_connection_id": connection, + "owner_connection_generation": 3, + "approval_generation": 2, + "selection_generation": 4, + "mode": "selected_refresh", + "reader_policy": "current_team_access", + "interval_seconds": 300, + } + self.source = KnowledgeSource( + org="org", + namespace="team", + name="source", + kind="mcp", + source_id=str(uuid4()), + access=MIRRORED_ACCESS, + credential_mode="worker", + owner_subject="alice", + connection_id=connection, + config={WORKER_REGISTRATION: json.dumps(self.config)}, + items=[{"type": "resource", "id": "urn:resource:Résumé"}], + ) + + def test_preserves_exact_selection_and_opaque_worker_connection(self) -> None: + config, [document] = decode_worker_source(self.source) + self.assertEqual(document.id, "urn:resource:Résumé") + self.assertEqual(str(config.owner_connection_id), self.source.connection_id) + self.assertEqual(config.selection_generation, 4) + + def test_registration_roundtrip_preserves_identity_without_credential_fields(self) -> None: + config, selected = decode_worker_source(self.source) + row = encode_worker_source( + org=self.source.org, + namespace=self.source.namespace, + name=self.source.name, + source_id=UUID(self.source.source_id), + owner=self.source.owner_subject, + config=config, + selection=selected, + ) + self.assertEqual(decode_worker_source(row), (config, selected)) + self.assertEqual(row.source_id, self.source.source_id) + self.assertEqual(row.credential_enc, "") + self.assertEqual(row.secret_enc, "") + self.assertEqual(row.created_by, row.owner_subject) + + def test_never_interprets_older_or_inactive_authority(self) -> None: + cases = ( + {"config": {WORKER_REGISTRATION: json.dumps({**self.config, "version": 1})}}, + {"kind": "linear"}, + {"credential_mode": "connected"}, + {"credential_enc": "legacy"}, + {"access": "namespace"}, + {"connection_id": str(uuid4())}, + {"active": False}, + {"pending_delete": True}, + ) + for fields in cases: + with self.subTest(fields=tuple(fields)), self.assertRaises(WorkerSourceRefused): + decode_worker_source(replace(self.source, **fields)) + + def test_rejects_credential_data_ambiguous_modes_and_duplicate_selection(self) -> None: + cases = ({"credential": "value"}, {"mode": "live"}, {"owner_connection_generation": "3"}) + for fields in cases: + config = {**self.config, **fields} + with self.subTest(fields=tuple(fields)), self.assertRaises(WorkerSourceRefused): + decode_worker_source( + replace(self.source, config={WORKER_REGISTRATION: json.dumps(config)}) + ) + repeated = self.source.items * 2 + with self.assertRaises(WorkerSourceRefused): + decode_worker_source(replace(self.source, items=repeated)) + + async def test_existing_store_preserves_worker_rows_but_does_not_advertise_legacy_kind( + self, + ) -> None: + client = AsyncMock() + await insert_source(self.source, ch=client) + stored = client.insert.await_args.args[1][0] + assert stored["kind"] == "" + assert stored["source_kind"] == "mcp" + assert stored["credential_enc"] == stored["secret_enc"] == "" + client.query_one.return_value = stored + source = await get_source( + self.source.org, self.source.namespace, self.source.name, ch=client + ) + assert source is not None + assert decode_worker_source(source) == decode_worker_source(self.source) + assert client.query_one.await_args.kwargs["params"] == { + "org": self.source.org, + "ns": self.source.namespace, + "name": self.source.name, + } diff --git a/tests/unit/test_pg_mcp_worker_approvals.py b/tests/unit/test_pg_mcp_worker_approvals.py new file mode 100644 index 00000000000..7abd2eac195 --- /dev/null +++ b/tests/unit/test_pg_mcp_worker_approvals.py @@ -0,0 +1,79 @@ +import unittest +from unittest.mock import AsyncMock, Mock, patch +from uuid import UUID + +from server.knowledge.store import pg_mcp_worker_approvals as approvals +from server.knowledge.store.pg_mcp_worker_enrollment import WriteOrigin + + +class TestWorkerApprovals(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.enterContext(patch.object(approvals.pg, "enabled", return_value=True)) + self.key = approvals.ApprovalKey("org", "team", UUID(int=2), "a" * 64) + self.owner = approvals.ApprovalOwner( + "alice", WriteOrigin("agent", "-", "alice", "asserted") + ) + self.conn = Mock(is_in_transaction=Mock(return_value=True), fetchrow=AsyncMock()) + + async def test_approval_is_locked_and_scoped_to_one_exact_profile(self) -> None: + self.conn.fetchrow.return_value = { + "generation": 3, + "modes": approvals.LIVE, + "team_access": False, + "active": True, + } + entry = await approvals.current_on(self.conn, self.key, lock=True) + self.assertEqual(entry, approvals.WorkerApproval(3, approvals.LIVE, False, True)) + query, *args = self.conn.fetchrow.await_args.args + self.assertIn( + "org = $1 AND namespace = $2 AND worker_id = $3 AND profile_digest = $4", query + ) + self.assertTrue(query.endswith(" FOR SHARE")) + self.assertEqual(tuple(args), self.key.arguments()) + + async def test_stale_approval_cannot_write_or_reuse_generation(self) -> None: + self.conn.fetchrow.return_value = None + outcome = await approvals.replace_on( + self.conn, + self.key, + expected_generation=4, + modes=0, + team_access=False, + owner=self.owner, + ) + self.assertIsNone(outcome) + query, *args = self.conn.fetchrow.await_args.args + self.assertIn("AND generation = $12", query) + self.assertIn("nextval('loom.mcp_worker_approval_generations')", query) + self.assertEqual(args[-1], 4) + + async def test_a_new_approval_cannot_overwrite_an_existing_scope(self) -> None: + self.conn.fetchrow.return_value = None + self.assertIsNone( + await approvals.replace_on( + self.conn, + self.key, + expected_generation=0, + modes=approvals.LIVE, + team_access=True, + owner=self.owner, + ) + ) + query, *_ = self.conn.fetchrow.await_args.args + self.assertIn("ON CONFLICT (org, namespace, worker_id, profile_digest) DO NOTHING", query) + + async def test_invalid_or_untransactional_change_never_queries_the_store(self) -> None: + self.assertIsNone( + await approvals.replace_on( + self.conn, + self.key, + expected_generation=1, + modes=0, + team_access=True, + owner=self.owner, + ) + ) + self.conn.is_in_transaction.return_value = False + with self.assertRaises(RuntimeError): + await approvals.current_on(self.conn, self.key, lock=True) + self.conn.fetchrow.assert_not_awaited() diff --git a/tests/unit/test_pg_mcp_worker_enrollment.py b/tests/unit/test_pg_mcp_worker_enrollment.py new file mode 100644 index 00000000000..3bc2424c427 --- /dev/null +++ b/tests/unit/test_pg_mcp_worker_enrollment.py @@ -0,0 +1,161 @@ +"""Verify the store's transaction and SQL contracts without a Postgres process.""" + +from dataclasses import replace +from pathlib import Path +from unittest.mock import AsyncMock, Mock, call +from uuid import UUID + +import pytest + +from server.knowledge.store import pg_mcp_worker_enrollment as enrollment + +_ORG = "example-org" +_NAMESPACE = "account-owner-scope" +_REQUESTER = "requester" +_WORKER = UUID(int=1) +_PROFILE = "a" * 64 +_CONNECTION = UUID(int=2) +_NONCE = UUID(int=3) +_ORIGIN = enrollment.WriteOrigin("agent", "-", "actor", "direct") +_GENERATION = 3 +_ISSUED = 1_000 +_EXPIRY = _ISSUED + 120 +_RESOURCE_SPACE = "b" * 64 +_ACCOUNT_ARGS = (_ORG, _NAMESPACE, _REQUESTER, _WORKER, _PROFILE, _CONNECTION) +_ACCOUNT = enrollment.AccountKey(*_ACCOUNT_ARGS) +_CHALLENGE = enrollment.Challenge(_ACCOUNT, _GENERATION, _NONCE, _ISSUED, _EXPIRY) +_CHALLENGE_ARGS = (*_ACCOUNT_ARGS, _GENERATION, _NONCE, _ISSUED, _EXPIRY) +_ORIGIN_ARGS = ("agent", "-", "actor", "direct") + + +@pytest.fixture +def conn(monkeypatch: pytest.MonkeyPatch) -> Mock: + monkeypatch.setattr(enrollment.pg, "enabled", lambda: True) + return Mock( + is_in_transaction=Mock(return_value=True), + execute=AsyncMock(), + fetchval=AsyncMock(return_value=True), + fetchrow=AsyncMock(return_value=None), + ) + + +@pytest.mark.asyncio +async def test_issue_binds_fresh_nonce_and_origin(conn: Mock) -> None: + assert await enrollment.issue_challenge(conn, _CHALLENGE, _ORIGIN) + conn.execute.assert_awaited_once_with(enrollment._LOCK, _ORG, _CONNECTION) + conn.fetchval.assert_awaited_once_with(enrollment._ISSUE, *_CHALLENGE_ARGS, *_ORIGIN_ARGS) + sql = enrollment._ISSUE + assert "$9::bigint <= extract(epoch FROM statement_timestamp())" in sql + assert "$10::bigint > extract(epoch FROM statement_timestamp())" in sql + assert "org = $1 AND connection_id = $6 AND NOT consumed" in sql + assert "ON CONFLICT (org, nonce) DO NOTHING" in sql + conn.fetchval.return_value = None + assert not await enrollment.issue_challenge(conn, _CHALLENGE, _ORIGIN) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("lifetime", [-1, 0, 121]) +async def test_issue_rejects_out_of_range_lifetime(conn: Mock, lifetime: int) -> None: + challenge = replace(_CHALLENGE, expires_at=_ISSUED + lifetime) + assert not await enrollment.issue_challenge(conn, challenge, _ORIGIN) + conn.fetchval.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_writes_require_callers_transaction(conn: Mock) -> None: + conn.is_in_transaction.return_value = False + with pytest.raises(RuntimeError, match="requires an authority transaction"): + await enrollment.issue_challenge(conn, _CHALLENGE, _ORIGIN) + with pytest.raises(RuntimeError, match="requires an authority transaction"): + await enrollment.consume_challenge(conn, _CHALLENGE, resource_space=None) + with pytest.raises(RuntimeError, match="requires an authority transaction"): + await enrollment.revoke_account(conn, _ACCOUNT, generation=_GENERATION, origin=_ORIGIN) + conn.fetchval.assert_not_awaited() + conn.execute.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_consume_serializes_and_binds_the_entire_expected_challenge(conn: Mock) -> None: + assert await enrollment.consume_challenge(conn, _CHALLENGE, resource_space=_RESOURCE_SPACE) + assert conn.mock_calls == [ + call.is_in_transaction(), + call.execute(enrollment._LOCK, _ORG, _CONNECTION), + call.fetchval(enrollment._CONSUME, *_CHALLENGE_ARGS, _RESOURCE_SPACE), + ] + sql = enrollment._CONSUME + assert "pg_advisory_xact_lock" in enrollment._LOCK + assert "SET consumed = true" in sql + assert "generation = $7 AND nonce = $8" in sql + assert "issued_at = $9 AND expires_at = $10 AND NOT consumed" in sql + assert "expires_at > extract(epoch FROM statement_timestamp())" in sql + assert "FROM claimed\n ON CONFLICT (org, connection_id)" in sql + assert "org = $1 AND namespace = $2 AND user_id = $3 AND worker_id = $4 " in sql + assert "AND profile_digest = $5 AND connection_id = $6" in sql + + +def test_account_write_requires_same_binding_and_a_strictly_newer_generation() -> None: + sql = enrollment._CONSUME + assert "account.namespace = EXCLUDED.namespace AND account.user_id = EXCLUDED.user_id" in sql + assert "AND account.worker_id = EXCLUDED.worker_id" in sql + assert "AND account.profile_digest = EXCLUDED.profile_digest" in sql + assert "account.resource_space IS NOT DISTINCT FROM EXCLUDED.resource_space" in sql + assert "account.generation < EXCLUDED.generation" in sql + assert "generation = $7 AND active" in sql + assert "resource_space IS NOT DISTINCT FROM $11 AND EXISTS (SELECT FROM claimed)" in sql + + +@pytest.mark.asyncio +async def test_revocation_uses_same_lock_and_preserves_the_generation(conn: Mock) -> None: + conn.fetchval.return_value = None + assert not await enrollment.revoke_account( + conn, _ACCOUNT, generation=_GENERATION, origin=_ORIGIN + ) + assert conn.mock_calls == [ + call.is_in_transaction(), + call.execute(enrollment._LOCK, _ORG, _CONNECTION), + call.fetchval(enrollment._REVOKE, *_ACCOUNT_ARGS, _GENERATION, *_ORIGIN_ARGS), + ] + sql = enrollment._REVOKE + assert "SET active = false" in sql + assert "generation = $7 AND active" in sql + assert "DELETE" not in sql + + +@pytest.mark.asyncio +async def test_get_requires_exact_owner_binding_and_returns_inactive_fence(conn: Mock) -> None: + assert await enrollment.get_account(conn, _ACCOUNT) is None + conn.fetchrow.return_value = { + "generation": _GENERATION, + "active": False, + "resource_space": _RESOURCE_SPACE, + } + assert await enrollment.get_account(conn, _ACCOUNT) == enrollment.AccountState( + _GENERATION, False, _RESOURCE_SPACE + ) + assert conn.fetchrow.await_args_list == [call(enrollment._GET, *_ACCOUNT_ARGS)] * 2 + + +@pytest.mark.asyncio +async def test_prune_limits_work_to_expired_challenges_in_one_org(conn: Mock) -> None: + conn.fetchval.return_value = 2 + assert await enrollment.prune_expired_challenges(conn, _ORG) == 2 + conn.fetchval.assert_awaited_once_with(enrollment._PRUNE, _ORG) + assert "WHERE org = $1 AND expires_at <=" in enrollment._PRUNE + assert "LIMIT 1000 FOR UPDATE SKIP LOCKED" in enrollment._PRUNE + assert "WHERE challenge.org = $1" in enrollment._PRUNE + assert "loom.mcp_worker_accounts" not in enrollment._PRUNE + + +def test_migration_is_additive_and_stores_metadata_only() -> None: + migration = ( + Path(__file__).resolve().parents[2] / "schemas/pg_migrations/015_mcp_worker_enrollment.sql" + ) + ddl = migration.read_text(encoding="utf-8") + assert ddl.count("CREATE TABLE IF NOT EXISTS") == 2 + assert "PRIMARY KEY (org, nonce)" in ddl + assert "PRIMARY KEY (org, connection_id)" in ddl + assert "CHECK (expires_at - issued_at BETWEEN 1 AND 120)" in ddl + assert "resource_space ~ '^[0-9a-f]{64}$'" in ddl + assert not any( + field in ddl for field in ("credential", "token", "endpoint", "content", "jsonb", "bytea") + ) diff --git a/tests/unit/test_pg_mcp_worker_readers.py b/tests/unit/test_pg_mcp_worker_readers.py new file mode 100644 index 00000000000..d647fed38c8 --- /dev/null +++ b/tests/unit/test_pg_mcp_worker_readers.py @@ -0,0 +1,53 @@ +import unittest +from unittest.mock import AsyncMock, Mock, patch +from uuid import UUID + +from server.knowledge.app.mcp_worker_pg_directory import current_connection, current_enrollment +from server.knowledge.store import pg_mcp_worker_enrollment as accounts +from server.knowledge.store import pg_mcp_worker_readers as readers + + +class TestWorkerReaderDirectory(unittest.IsolatedAsyncioTestCase): + def setUp(self) -> None: + self.enterContext(patch.object(readers.pg, "enabled", return_value=True)) + self.worker, self.connection, self.source = UUID(int=2), UUID(int=3), UUID(int=4) + self.key = readers.LinkKey("org", "team", self.source, "bob") + self.origin = accounts.WriteOrigin("agent", "-", "bob", "asserted") + + async def test_directory_does_not_return_a_disconnected_link(self) -> None: + with patch.object(readers, "current", AsyncMock()) as get: + get.return_value = readers.Link(4, self.connection, 3, 2, False) + self.assertIsNone(await current_enrollment(*self.key.parameters())) + get.assert_awaited_once_with(self.key) + + async def test_directory_binds_connection_to_exact_org_and_owner(self) -> None: + args = ("org", "bob", self.worker, self.connection) + result = ("a" * 64, accounts.AccountState(2, True, "b" * 64)) + with patch.object( + accounts, "current_reader_account", AsyncMock(return_value=result) + ) as get: + current = await current_connection(*args) + get.assert_awaited_once_with(*args) + self.assertIsNotNone(current) + assert current is not None + self.assertEqual(current.binding.owner, "bob") + self.assertEqual(current.binding.connection_id, self.connection) + + async def test_stale_change_does_not_overwrite_a_link(self) -> None: + conn = Mock( + is_in_transaction=Mock(return_value=True), fetchval=AsyncMock(return_value=None) + ) + result = await readers.set_on( + conn, + self.key, + selection_generation=5, + connection_id=self.connection, + connection_generation=2, + expected_link_generation=7, + origin=self.origin, + ) + query, *bound = conn.fetchval.await_args.args + self.assertIsNone(result) + self.assertIn("link_generation = $12 AND selection_generation <= $5", query) + self.assertEqual(tuple(bound[:4]), self.key.parameters()) + self.assertEqual(bound[-1], 7) diff --git a/tests/unit/test_pg_source_lock.py b/tests/unit/test_pg_source_lock.py new file mode 100644 index 00000000000..692cb8c1843 --- /dev/null +++ b/tests/unit/test_pg_source_lock.py @@ -0,0 +1,142 @@ +"""The Postgres source lock: how a source write takes it, waits and refuses.""" + +from contextlib import asynccontextmanager +from types import SimpleNamespace +from typing import Any + +import asyncpg +import pytest + +from server.core import pg +from server.core.errors import OverloadedError +from server.knowledge.app import sources +from server.knowledge.store import pg_source_lock + + +class _Conn: + def __init__(self, busy: bool, lost: str = "") -> None: + self.busy, self.lost = busy, lost + self.statements: list[tuple[str, tuple[Any, ...]]] = [] + + async def execute(self, sql: str, *args: Any, **options: Any) -> str: + self.statements.append((sql, args)) + self.timeout = options.get("timeout") + if self.busy and "pg_advisory_lock(" in sql: + raise asyncpg.LockNotAvailableError("lock timeout") + if self.lost and self.lost in sql: + raise asyncpg.ConnectionDoesNotExistError("connection lost") + return "SELECT 1" + + +def _pool(monkeypatch: pytest.MonkeyPatch, conn: _Conn) -> None: + @asynccontextmanager + async def connection(): + yield conn + + monkeypatch.setattr(pg_source_lock.pg, "connection", connection) + + +@pytest.mark.asyncio +async def test_a_busy_source_lock_is_overloaded_not_a_statement_timeout(monkeypatch): + conn = _Conn(busy=True) + _pool(monkeypatch, conn) + with pytest.raises(OverloadedError, match="document sources of 'docs'"): + async with pg_source_lock.exclusive("org", "docs", wait_s=2.5): + pytest.fail("the lock was not held") + (timeouts, timeout_args), (lock, lock_args) = conn.statements + assert "lock_timeout" in timeouts and "statement_timeout" in timeouts + # Keepalives let Postgres drop the lock of a vanished host within about a minute. + for call in ( + "set_config('tcp_keepalives_idle', '30', false)", + "set_config('tcp_keepalives_interval', '10', false)", + "set_config('tcp_keepalives_count', '3', false)", + ): + assert call in timeouts + # The statement timeout outlasts the lock wait, so lock_timeout decides. + assert timeout_args == ("2500ms", "3500ms") + assert "pg_advisory_lock(" in lock and lock_args == ("org", "docs") + # The client timeout outlasts the lock wait too. + assert conn.timeout == 3.5 + + +@pytest.mark.asyncio +async def test_the_source_lock_is_held_for_the_block(monkeypatch): + conn = _Conn(busy=False) + _pool(monkeypatch, conn) + async with pg_source_lock.exclusive("org", "docs", wait_s=0): + assert len(conn.statements) == 2 + assert conn.statements[0][1] == ("1ms", "1001ms") + + +@pytest.mark.asyncio +# A failover can surface on the session's first statement or on the lock itself. +@pytest.mark.parametrize("statement", ["set_config(", "pg_advisory_lock("]) +async def test_a_lost_connection_while_locking_is_a_postgres_outage(monkeypatch, statement): + _pool(monkeypatch, _Conn(busy=False, lost=statement)) + with pytest.raises(pg.PostgresUnavailableError): + async with pg_source_lock.exclusive("org", "docs", wait_s=1): + pytest.fail("the lock was not held") + + +@pytest.mark.asyncio +async def test_a_source_write_holds_the_lock_within_its_lease_wait(monkeypatch): + now = [100.0] + held: list[float] = [] + inside = False + + @asynccontextmanager + async def lease(name, *, ttl_s, wait_s, ch): + now[0] += 0.2 # the lease wait spends part of wait_s + yield True + + @asynccontextmanager + async def exclusive(org, namespace, *, wait_s): + nonlocal inside + held.append(wait_s) + inside = True + try: + yield + finally: + inside = False + + monkeypatch.setattr(sources.pg, "enabled", lambda: True) + monkeypatch.setattr(sources.leases, "holding", lease) + monkeypatch.setattr(sources.pg_source_lock, "exclusive", exclusive) + # Only this module's clock: the event loop keeps the real one. + monkeypatch.setattr(sources, "time", SimpleNamespace(monotonic=lambda: now[0])) + async with sources.sources_lease("org", "docs", wait_s=5.0): + assert inside + # The lock gets only what the lease wait left of the 5 s. + assert held == [pytest.approx(4.8)] and not inside + + +class _LostConn: + async def fetch(self, *args: Any) -> list[Any]: + raise asyncpg.ConnectionDoesNotExistError("connection lost") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("read", ["approval", "account", "link"]) +async def test_plain_worker_authority_reads_answer_an_outage_with_503(monkeypatch, read): + from uuid import UUID + + from server.knowledge.store import pg_mcp_worker_approvals as approvals + from server.knowledge.store import pg_mcp_worker_enrollment as accounts + from server.knowledge.store import pg_mcp_worker_readers as readers + + @asynccontextmanager + async def connection(): + yield _LostConn() + + monkeypatch.setattr(pg, "enabled", lambda: True) + monkeypatch.setattr(pg, "connection", connection) + worker, digest = UUID(int=1), "a" * 64 + calls = { + "approval": lambda: approvals.current_generation( + "org", "docs", worker, digest, "live", False + ), + "account": lambda: accounts.current_reader_account("org", "alice", worker, UUID(int=2)), + "link": lambda: readers.current(readers.LinkKey("org", "docs", UUID(int=3), "alice")), + } + with pytest.raises(pg.PostgresUnavailableError): + await calls[read]() diff --git a/tests/unit/test_sdk_example_audience_scoped_retrieval.py b/tests/unit/test_sdk_example_audience_scoped_retrieval.py index 2fda7d31c15..53120d33cfc 100644 --- a/tests/unit/test_sdk_example_audience_scoped_retrieval.py +++ b/tests/unit/test_sdk_example_audience_scoped_retrieval.py @@ -47,6 +47,7 @@ def __init__( self.keeps_collections = keeps_collections self.keeps_notes = keeps_notes self.lists_revoked = lists_revoked # collection.list lags behind a revoke + self.finance_listings_to_skip = 0 self.revoked: set[tuple[str, str]] = set() # (collection, user) self.grants: dict[str, set[str]] = {} # collection → users who read it self.docs: dict[tuple[str, str], str] = {} # (collection, source_uri) → content @@ -93,6 +94,12 @@ def reads(namespace: str) -> bool: for c, users in sorted(self.grants.items()) if user in users or (self.lists_revoked and (c, user) in self.revoked) ] + finance = next( + (row for row in rows if row["namespace"].startswith("col-example-finance-")), None + ) + if self.finance_listings_to_skip and finance is not None: + self.finance_listings_to_skip -= 1 + rows.remove(finance) return httpx.Response(200, json={"collections": rows, "next_cursor": None}) if op == "collection.create": self.grants[ns] = {user} @@ -146,10 +153,14 @@ def reads(namespace: str) -> bool: return httpx.Response(200, json={}) +@pytest.mark.parametrize("finance_listings_to_skip", [0, 2]) async def test_every_check_passes_and_the_run_removes_what_it_made( - monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], + finance_listings_to_skip: int, ) -> None: server = Server() + server.finance_listings_to_skip = finance_listings_to_skip server.install(monkeypatch) example = load_example(monkeypatch) assert await example.main(sign=str) == 0 @@ -163,6 +174,21 @@ async def test_every_check_passes_and_the_run_removes_what_it_made( assert len(server.deleted) == 3 +async def test_missing_fixture_grant_times_out_without_running_a_search( + monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str] +) -> None: + example = load_example(monkeypatch) + monkeypatch.setattr(example, "GRANT_WAIT_S", 0) + server = Server() + server.finance_listings_to_skip = 2 + server.install(monkeypatch) + assert await example.main(sign=str) == 1 + out = capsys.readouterr().out + assert "the shared collections did not become visible to the recipient" in out + assert not server.searches() + assert not server.docs and not server.grants + + async def test_a_shared_request_names_only_the_destinations_collection( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/tests/unit/test_source_publication_tail.py b/tests/unit/test_source_publication_tail.py index b5742233232..6a96b07a5df 100644 --- a/tests/unit/test_source_publication_tail.py +++ b/tests/unit/test_source_publication_tail.py @@ -314,3 +314,81 @@ async def send(message): assert checks == [True, True] await middleware({**scope, "path": "/ordinary"}, None, send) assert sent[-1]["body"] == b"ordinary" + + +@pytest.mark.parametrize("mode", ["unfenced", "fenced", "streaming", "revoked"]) +async def test_large_body_uses_a_fresh_fence_for_each_bounded_send(mode): + from starlette.responses import Response, StreamingResponse + + limit = 512 * 1024 + body = b"a" * limit + b"b" * 123 + sent = [] + live = True + held = None + acquisitions = 0 + + async def check(): + if not live: + raise LostCorpus() + + async def fence(deliver): + nonlocal held, acquisitions + assert held is None + acquisitions += 1 + held = acquisitions + try: + await deliver() + finally: + held = None + + async def stream(): + yield body + yield b"last" + + async def app(scope, receive, send): + request_tail.retain_publication( + object(), check, lambda: live, fence=None if mode == "unfenced" else fence + ) + if mode == "streaming": + await StreamingResponse( + stream(), headers={"content-length": str(len(body) + len(b"last"))} + )(scope, receive, send) + else: + await Response(body)(scope, receive, send) + + async def send(message): + nonlocal live + chunk = message.get("body", b"") + if mode != "unfenced" and (chunk or message["type"] == "http.response.start"): + assert held is not None + if len(chunk) > limit: + raise TimeoutError("body exceeds the simulated per-send budget") + sent.append((held, message)) + if chunk and mode == "revoked": + live = False + + response = request_tail.RequestTailMiddleware(app)( + {"type": "http", "asgi": {"spec_version": "2.4"}}, None, send + ) + if mode == "revoked": + with pytest.raises(request_tail.RequiredTailError): + await response + else: + await response + + size = len(body) + (len(b"last") if mode == "streaming" else 0) + assert dict(sent[0][1]["headers"])[b"content-length"] == str(size).encode() + frames = [(guard, msg["body"], msg.get("more_body", False)) for guard, msg in sent[1:]] + if mode == "unfenced": + assert frames == [(None, body, False)] + elif mode == "streaming": + assert frames == [ + (2, body[:limit], True), + (3, body[limit:], True), + (4, b"last", True), + (None, b"", False), + ] + elif mode == "revoked": + assert frames == [(2, body[:limit], True)] + else: + assert frames == [(2, body[:limit], True), (3, body[limit:], False)]