From af2cbed14f2def315172b48a412c8b345d172f72 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 19:28:16 +0000 Subject: [PATCH 01/30] Add a bounded outbound MCP read client Configure one remote read engine for resources and explicitly approved tools. Keep protocol evidence separate from source authorization and publication, and qualify transport limits, revocation and cancellation with synthetic SDK servers. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 121 ++++ llms.txt | 1 + pyproject.toml | 4 + server/clients/mcp_source.py | 852 +++++++++++++++++++++++++ tests/unit/test_mcp_source_client.py | 721 +++++++++++++++++++++ tests/unit/test_mcp_source_network.py | 174 +++++ tests/unit/test_mcp_source_protocol.py | 637 ++++++++++++++++++ uv.lock | 242 +++++++ 8 files changed, 2752 insertions(+) create mode 100644 docs/architecture/mcp-source-client.md create mode 100644 server/clients/mcp_source.py create mode 100644 tests/unit/test_mcp_source_client.py create mode 100644 tests/unit/test_mcp_source_network.py create mode 100644 tests/unit/test_mcp_source_protocol.py diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md new file mode 100644 index 0000000000..f549e989bf --- /dev/null +++ b/docs/architecture/mcp-source-client.md @@ -0,0 +1,121 @@ +# Outbound MCP source client + +The outbound MCP source client reads resources through a configured remote HTTP endpoint. +It provides protocol discovery and normalized evidence without storing documents, authorizing +Loom readers or running an agent. Source lifecycle and publication remain responsibilities +of the [document source layer](document-sources.md). + +## Source entry points + +`server/clients/mcp_source.py` contains the client configuration, approved tool mappings, +capability discovery and evidence types. The official protocol SDK handles MCP messages; +the client constrains the HTTP transport and validates configured operations and results. + +This client is an internal prerequisite. It adds no source registration operation, dashboard +control, worker dispatch or operator cutover. Connecting existing document sources continues +to use their current implementation. The client does not qualify an external service. + +## Connection and endpoint boundary + +A configuration identifies one exact HTTPS endpoint. Its caller supplies a separately +acquired upstream credential bound to that endpoint. The client does not accept a Loom +request, forward incoming headers, discover alternate endpoints or follow redirects. +A mandatory access validator runs around operations and HTTP response work. The source +layer is responsible for storing credentials sealed, binding the connection +to the authenticated owner and organization, checking current grants and revocation, +and approving the endpoint through operator policy before constructing a client. + +The transport uses `server/core/webhooks.py` (`pinned_target`) to validate public DNS +addresses and preserve the configured Host header and TLS server name while connecting +to a validated address. Proxy environment variables do not select another route. +Requests outside the configured endpoint are refused. A server response cannot select +a different server, credential or connection. + +The supported profile is Streamable HTTP with an explicitly supplied upstream bearer +credential, or an explicitly anonymous endpoint. Interactive authorization, credential +refresh, legacy HTTP with SSE and local +stdio commands are outside this profile. The client launches no external command. An +expired or refused credential ends the operation; no native connector or broader +credential substitutes for it. Transport and token binding follow the +[MCP HTTP transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) +and [authorization contract](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization). + +## Read operations and capabilities + +Standard resource listing and reading use `resources/list` and `resources/read` when the +server advertises resources. Tool-based reads require an explicit mapping approved by +the caller's control plane. A mapping names the exact tool, its argument and result +schemas, fixed scope arguments and result selectors. Search text, a selected resource +identity or a pagination cursor fills only its configured argument. It cannot replace +a fixed scope argument or choose another tool. + +Discovery verifies the configured schemas before execution. Tool descriptions and +`readOnlyHint` are untrusted descriptive fields, never approval to call a tool. Unknown +capabilities remain unsupported; an action-only server supplies no usable document source. +Schema drift refuses the configured operation rather than guessing another result shape. +Returned resource links are evidence, never instructions to fetch an arbitrary URL. +Listing and search do not expand the explicitly approved resource identities. An empty +selection grants no read authority. + +The qualified content profile is text resources and mapped structured tool output. Binary +resource blobs and tools that return only unstructured text are unsupported. Approved +tool schemas use a bounded subset with closed objects, bounded arrays and strings, +and no references, regular expressions or combinatorial validators. + +Each read produces normalized evidence: resource identity, citation URI, title, media +type, content and any supplied revision. A read receipt binds the requested identity, +configured operation and returned body; listing metadata and search snippets have no +successful resource-read receipt. Identity is scoped by the source connection; +the same upstream identifier on another connection denotes separate evidence. A caller +that persists a document must retain the connection and resource identity with its +provenance. A citation address alone does not establish tenant or reader authority. + +## Bounds and cancellation + +Discovery, pagination, results, content and HTTP responses have finite limits. A session +has an overall deadline as well as request bounds. Cancellation ends owned protocol work; +it does not publish partial evidence as a successful read. Errors expose bounded error +codes rather than upstream content, endpoints or credentials. + +A successful final page closes that listing operation. It does not establish a deletion +history, complete reader permissions, revision support or a subscription contract. +Partial pages, errors, refused access and notifications are never deletion evidence. +The client has no retirement or erasure authority. + +## Storage and publication + +The client keeps evidence in memory for its caller and writes no knowledge document, +original, chunk, memory, account, cache or source checkpoint. There is no persistent +connection cache shared between users. The caller decides whether the evidence serves +live retrieval, an explicitly selected snapshot or a supported refresh contract. + +Live retrieval belongs in the existing protected live-search path. That path checks +current owner authority around reads and again before delivery, and applies private +result, accounting and publication rules. Calling this client does not grant permission +to bypass those checks or expose private content through diagnostics, exports or derived +memories. A team destination does not establish permission to private source evidence. +Without admitted upstream ACL evidence, a personal import remains owner-only. An +intentional collection-wide publication needs separate explicit authority. + +The absence of a client-side durable cache is not a no-retention guarantee. The remote +server, downstream host, application logging and trace configuration have their own +retention. The integrating source layer must disclose those boundaries and protect +content-bearing outputs under the existing publication contract. + +## Invariants + +- Endpoint, credential audience, approved tool, fixed scope and identity cannot be + widened by query arguments, resource content or server metadata. +- A protocol capability is not a permission grant or a synchronization guarantee. +- A read receipt proves the operation that produced evidence; it does not prove that + a different user may read the result. +- A connection or live lookup imports nothing and deletes nothing. +- Unsupported authentication, transport, schema and access contracts fail closed. + +## Upgrade boundary + +This internal client changes no stored row, wire field or source kind. Builds continue +using the same schema, account history, source checkpoints, documents and originals. +There is no account migration, credential reuse, source retirement or runtime switch. +Integrating the client into source registration requires its own explicit storage, +rolling-upgrade, access and operator reconfiguration contract. diff --git a/llms.txt b/llms.txt index 4b32f3b00c..3acffda1d2 100644 --- a/llms.txt +++ b/llms.txt @@ -165,6 +165,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 and Notion registrations. - [LLM and embedding architecture](docs/architecture/llm-architecture.md): Loom has two pluggable providers: an embedder (`server/embedding/`) that turns text into vectors, and an LLM client (`server/llm/`) that completes prompts. +- [Outbound MCP source client](docs/architecture/mcp-source-client.md): The outbound MCP source client reads resources through a configured remote HTTP endpoint. - [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/pyproject.toml b/pyproject.toml index 5b377ade10..cdf2dc91b0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -27,6 +27,9 @@ dependencies = [ "aiohttp>=3.10", # clickhouse-connect's async client requires it "anyio>=4", # a wait no cancellation cuts short: server.core.shielded "httpx[http2]>=0.27", + # Outbound MCP sources use the official protocol client; schemas constrain approved tool mappings. + "mcp>=1.30.0,<2", + "jsonschema>=4.20", "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts "tenacity>=9.0", @@ -103,6 +106,7 @@ dev = [ "mdx-truly-sane-lists==1.3", "pymdown-extensions==12.3", "markdown-it-py==4.0.0", + "types-jsonschema>=4.20", ] # Operator CLI extra — needed only by `dev/loom_ingest.py` to fetch an S3 # source. Not a server dep; the CLI lazy-imports it with an actionable error diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py new file mode 100644 index 0000000000..e0922d0067 --- /dev/null +++ b/server/clients/mcp_source.py @@ -0,0 +1,852 @@ +"""Bounded reads from an explicitly configured remote MCP source. + +The caller owns connection authorization and secret storage. No remote hint grants +permission to call a tool, import a document, or share its contents. +""" + +from __future__ import annotations + +import asyncio +import copy +import hashlib +import json +import math +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import AsyncExitStack +from dataclasses import asdict, dataclass, field, replace +from datetime import timedelta +from typing import Any, Literal, TypeVar +from urllib.parse import urlsplit + +import httpx +from jsonschema import Draft202012Validator, SchemaError +from mcp import ClientSession, types +from mcp.client.streamable_http import streamable_http_client +from mcp.shared.exceptions import McpError +from pydantic import AnyUrl + +from server.core.ch import set_query_tag +from server.core.diagnostics import private_work +from server.core.webhooks import pinned_target + +ErrorCode = Literal[ + "config", "unsupported", "denied", "protocol", "schema", "limit", "timeout", "closed" +] + + +class MCPSourceError(Exception): + """Only a fixed code may cross the client boundary.""" + + def __init__(self, code: ErrorCode) -> None: + if code not in { + "config", + "unsupported", + "denied", + "protocol", + "schema", + "limit", + "timeout", + "closed", + }: + code = "protocol" + self.code = code + super().__init__("MCP source " + code) + + +def _error_code(error: BaseException) -> ErrorCode: + if isinstance(error, MCPSourceError): + return error.code + if isinstance(error, (TimeoutError, httpx.TimeoutException)): + return "timeout" + if isinstance(error, McpError) and error.error.code == httpx.codes.REQUEST_TIMEOUT: + return "timeout" + if isinstance(error, BaseExceptionGroup): + codes = {_error_code(child) for child in error.exceptions} + priorities: tuple[ErrorCode, ...] = ( + "denied", + "limit", + "timeout", + "schema", + "unsupported", + "closed", + ) + for code in priorities: + if code in codes: + return code + return "protocol" + + +@dataclass(frozen=True) +class MCPLimits: + timeout_seconds: float = 30 + request_seconds: float = 10 + max_pages: int = 8 + max_results: int = 100 + max_content_bytes: int = 1_000_000 + max_wire_bytes: int = 4_000_000 + max_requests: int = 64 + + def __post_init__(self) -> None: + for value, ceiling in ((self.timeout_seconds, 120), (self.request_seconds, 30)): + if ( + type(value) not in (int, float) + or not math.isfinite(value) + or not 0 < value <= ceiling + ): + raise MCPSourceError("config") + for value, ceiling in ( + (self.max_pages, 32), + (self.max_results, 1000), + (self.max_content_bytes, 4_000_000), + (self.max_wire_bytes, 16_000_000), + (self.max_requests, 256), + ): + if type(value) is not int or not 0 < value <= ceiling: + raise MCPSourceError("config") + + +@dataclass(frozen=True, repr=False) +class MCPBearer: + token: str + audience: str + + +@dataclass(frozen=True, repr=False) +class MCPToolMapping: + name: str + input_schema: dict[str, Any] + output_schema: dict[str, Any] + argument_name: str + fixed_arguments: dict[str, Any] = field(default_factory=dict) + items_path: tuple[str, ...] = () + id_path: tuple[str, ...] = ("id",) + title_path: tuple[str, ...] | None = ("title",) + text_path: tuple[str, ...] | None = ("text",) + uri_path: tuple[str, ...] | None = ("uri",) + revision_path: tuple[str, ...] | None = None + cursor_argument: str | None = None + next_cursor_path: tuple[str, ...] | None = None + + +@dataclass(frozen=True, repr=False) +class MCPSourceConfig: + endpoint: str + bearer_audience: str | None = None + approved_tools: tuple[str, ...] = () + search: MCPToolMapping | None = None + read: MCPToolMapping | None = None + limits: MCPLimits = field(default_factory=MCPLimits) + approved_resource_ids: tuple[str, ...] = () + + +@dataclass(frozen=True, repr=False) +class MCPEvidence: + resource_id: str + uri: str + title: str + text: str = "" + mime_type: str = "text/plain" + revision: str | None = None + receipt: MCPReadReceipt | None = None + + +@dataclass(frozen=True, repr=False) +class MCPReadReceipt: + operation: Literal["resources/read", "tools/call"] + requested_id: str + content_sha256: str + config_sha256: str + + +@dataclass(frozen=True, repr=False) +class MCPPage: + items: tuple[MCPEvidence, ...] + next_cursor: str | None + complete: bool + + +@dataclass(frozen=True) +class MCPDiscovery: + resources: bool + tools: tuple[str, ...] + + +def _json(value: Any, maximum: int) -> bytes: + try: + encoded = json.dumps( + value, ensure_ascii=True, allow_nan=False, separators=(",", ":"), sort_keys=True + ).encode() + except (ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + if len(encoded) > maximum: + raise MCPSourceError("limit") + return encoded + + +def _string(value: Any, maximum: int = 2048, *, empty: bool = False) -> str: + if not isinstance(value, str) or (not value and not empty): + raise MCPSourceError("schema") + if len(value.encode()) > maximum or any(ord(c) < 32 or ord(c) == 127 for c in value): + raise MCPSourceError("limit") + return value + + +def _origin(url: str) -> tuple[str, str, int]: + _string(url, 2048) + try: + parts = urlsplit(url) + if ( + parts.scheme != "https" + or not parts.hostname + or parts.username is not None + or parts.password is not None + or parts.query + or parts.fragment + or "\\" in url + or "%" in url + or any(c.isspace() for c in url) + or parts.port == 0 + or any(p in (".", "..") for p in parts.path.split("/")) + ): + raise MCPSourceError("config") + return parts.scheme, parts.hostname.encode("idna").decode().lower(), parts.port or 443 + except (ValueError, UnicodeError): + raise MCPSourceError("config") from None + + +# This subset has no references, regular expressions or combinatorial validators. +_SCHEMA_KEYS = frozenset( + { + "type", + "properties", + "required", + "additionalProperties", + "items", + "maxItems", + "minItems", + "maxLength", + "minLength", + "minimum", + "maximum", + "enum", + "const", + "title", + "description", + } +) + + +def _schema(schema: dict[str, Any]) -> None: + _json(schema, 16_384) + remaining = 256 + + def visit(node: Any, depth: int) -> None: + nonlocal remaining + remaining -= 1 + if remaining < 0 or depth > 8 or not isinstance(node, dict) or set(node) - _SCHEMA_KEYS: + raise MCPSourceError("schema") + if not isinstance(node.get("type"), str) or node["type"] not in { + "object", + "array", + "string", + "integer", + "number", + "boolean", + "null", + }: + raise MCPSourceError("schema") + if node["type"] == "object": + if node.get("additionalProperties") is not False: + raise MCPSourceError("schema") + properties = node.get("properties", {}) + if not isinstance(properties, dict) or len(properties) > 32: + raise MCPSourceError("schema") + for name, child in properties.items(): + _string(name, 128) + visit(child, depth + 1) + if node["type"] == "array": + if type(node.get("maxItems")) is not int or not 0 <= node["maxItems"] <= 1000: + raise MCPSourceError("schema") + visit(node.get("items"), depth + 1) + if node["type"] == "string": + if type(node.get("maxLength")) is not int or not 0 <= node["maxLength"] <= 4_000_000: + raise MCPSourceError("schema") + if "enum" in node and (not isinstance(node["enum"], list) or len(node["enum"]) > 32): + raise MCPSourceError("schema") + + visit(schema, 0) + try: + Draft202012Validator.check_schema(schema) + except (SchemaError, ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + + +def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: + _json(value, maximum) + if not Draft202012Validator(schema).is_valid(value): + raise MCPSourceError("schema") + + +def _path(value: Any, path: tuple[str, ...] | None, default: Any = "") -> Any: + if path is None: + return default + for key in path: + if not isinstance(value, dict) or key not in value: + raise MCPSourceError("schema") + value = value[key] + return value + + +class _LimitedStream(httpx.AsyncByteStream): + def __init__(self, stream: httpx.AsyncByteStream, owner: _PinnedTransport) -> None: + self.stream, self.owner = stream, owner + + async def __aiter__(self) -> AsyncIterator[bytes]: + try: + async with asyncio.timeout_at(self.owner.deadline): + async for chunk in self.stream: + self.owner.received += len(chunk) + if self.owner.received > self.owner.limits.max_wire_bytes: + raise MCPSourceError("limit") + await self.owner.validate_access() + yield chunk + except Exception as error: # noqa: BLE001 — only fixed diagnostics cross the transport boundary + self.owner.failure = _error_code(error) + raise MCPSourceError(self.owner.failure) from None + + async def aclose(self) -> None: + await self.stream.aclose() + + +class _PinnedTransport(httpx.AsyncBaseTransport): + def __init__( + self, + config: MCPSourceConfig, + credential: MCPBearer | None, + deadline: float, + validate_access: Callable[[], Awaitable[None]], + *, + transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self.endpoint = httpx.URL(config.endpoint) + self.credential, self.deadline, self.limits = credential, deadline, config.limits + self.validate_access = validate_access + self.inner = ( + transport + if transport is not None + else httpx.AsyncHTTPTransport(retries=0, trust_env=False) + ) + self.received, self.requests = 0, 0 + self.target: tuple[str, str, str] | None = None + self.pin_lock = asyncio.Lock() + self.failure: ErrorCode | None = None + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + try: + return await self._handle(request) + except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials + self.failure = _error_code(error) + raise MCPSourceError(self.failure) from None + + async def _handle(self, request: httpx.Request) -> httpx.Response: + async with asyncio.timeout_at(self.deadline): + if self.failure is not None: + raise MCPSourceError(self.failure) + if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: + raise MCPSourceError("denied") + self.requests += 1 + if self.requests > self.limits.max_requests: + raise MCPSourceError("limit") + await self.validate_access() + if self.target is None: + async with self.pin_lock: + if self.target is None: + refusal, pinned, host, sni = await pinned_target( + str(self.endpoint), schemes=("https",) + ) + if refusal or not host or not sni: + raise MCPSourceError("denied") + self.target = pinned, host, sni + pinned, host, sni = self.target + # Construct an allowlist of protocol headers, never propagate inbound headers. + headers = { + key: value + for key, value in request.headers.items() + if key + in { + "accept", + "content-type", + "mcp-session-id", + "mcp-protocol-version", + "last-event-id", + "mcp-method", + "mcp-name", + } + } + if any(len(v) > 2048 for v in headers.values()): + raise MCPSourceError("limit") + headers.update({"host": host, "accept-encoding": "identity"}) + if self.credential is not None: + headers["authorization"] = "Bearer " + self.credential.token + body = await request.aread() + if len(body) > 32_768: + raise MCPSourceError("limit") + outgoing = httpx.Request( + request.method, + pinned, + headers=headers, + content=body, + extensions={"timeout": request.extensions.get("timeout", {}), "sni_hostname": sni}, + ) + await self.validate_access() + response = await self.inner.handle_async_request(outgoing) + try: + await self.validate_access() + except Exception as error: # noqa: BLE001 — a revoked response must close before returning its fixed refusal + await response.aclose() + raise MCPSourceError(_error_code(error)) from None + if response.is_redirect: + await response.aclose() + raise MCPSourceError("denied") + if response.status_code in {401, 403}: + await response.aclose() + raise MCPSourceError("denied") + # Reject compression so the wire budget also bounds decoded protocol bytes. + if response.headers.get("content-encoding", "identity") != "identity": + await response.aclose() + raise MCPSourceError("protocol") + if not isinstance(response.stream, httpx.AsyncByteStream): + await response.aclose() + raise MCPSourceError("protocol") + response.stream = _LimitedStream(response.stream, self) + return response + + async def aclose(self) -> None: + await self.inner.aclose() + + +_T = TypeVar("_T") + + +class MCPSourceClient: + """One owner-authorized, bounded session; resources and tools yield evidence.""" + + def __init__( + self, + config: MCPSourceConfig, + credential: MCPBearer | None, + *, + validate_access: Callable[[], Awaitable[None]], + _transport: httpx.AsyncBaseTransport | None = None, + ) -> None: + self._config = copy.deepcopy(config) + self._test_transport = _transport + self.credential = credential + self.validate_access = validate_access + origin = _origin(config.endpoint) + if credential is None: + if config.bearer_audience is not None: + raise MCPSourceError("config") + elif ( + config.bearer_audience is None + or origin != _origin(config.bearer_audience) + or credential.audience != config.bearer_audience + or not isinstance(credential.token, str) + or not 0 < len(credential.token) <= 8192 + or any(not 33 <= ord(c) <= 126 for c in credential.token) + ): + raise MCPSourceError("config") + if len(config.approved_tools) > 2 or len(set(config.approved_tools)) != len( + config.approved_tools + ): + raise MCPSourceError("config") + mappings = [m for m in (self._config.search, self._config.read) if m is not None] + if set(config.approved_tools) != {m.name for m in mappings}: + raise MCPSourceError("config") + for mapping in mappings: + _string(mapping.name, 128) + _string(mapping.argument_name, 128) + _schema(mapping.input_schema) + _schema(mapping.output_schema) + if ( + mapping.input_schema["type"] != "object" + or mapping.output_schema["type"] != "object" + ): + raise MCPSourceError("config") + if not isinstance(mapping.fixed_arguments, dict): + raise MCPSourceError("config") + if mapping.cursor_argument is not None: + _string(mapping.cursor_argument, 128) + _json(mapping.fixed_arguments, 16_384) + if mapping.argument_name in mapping.fixed_arguments or ( + mapping.cursor_argument is not None + and ( + mapping.cursor_argument == mapping.argument_name + or mapping.cursor_argument in mapping.fixed_arguments + ) + ): + raise MCPSourceError("config") + for path in ( + mapping.items_path, + mapping.id_path, + mapping.title_path, + mapping.text_path, + mapping.uri_path, + mapping.revision_path, + mapping.next_cursor_path, + ): + if path is not None: + if not isinstance(path, tuple) or len(path) > 8: + raise MCPSourceError("config") + for part in path: + _string(part, 128) + self._stack: AsyncExitStack | None = None + self._session: ClientSession | None = None + self._transport: _PinnedTransport | None = None + self._operation_failure: ErrorCode | None = None + self._deadline = 0.0 + self._discovery: MCPDiscovery | None = None + self._schema_changed = False + self._pages, self._results = 0, 0 + self._issued_cursors: dict[str, tuple[str, str]] = {} + self._used_cursors: set[str] = set() + if len(config.approved_resource_ids) > config.limits.max_results: + raise MCPSourceError("config") + self._selected_ids = frozenset( + _string(identity) for identity in config.approved_resource_ids + ) + self._resource_titles: dict[str, str] = {} + + def __repr__(self) -> str: + return "MCPSourceClient()" + + @property + def config(self) -> MCPSourceConfig: + return copy.deepcopy(self._config) + + @property + def config_sha256(self) -> str: + return hashlib.sha256(_json(asdict(self._config), 131_072)).hexdigest() + + def _with_receipt( + self, evidence: MCPEvidence, operation: Literal["resources/read", "tools/call"] + ) -> MCPEvidence: + receipt = MCPReadReceipt( + operation, + evidence.resource_id, + hashlib.sha256(evidence.text.encode()).hexdigest(), + self.config_sha256, + ) + return replace(evidence, receipt=receipt) + + async def __aenter__(self) -> MCPSourceClient: + if self._stack is not None or self._deadline: + raise MCPSourceError("closed") + self._stack = AsyncExitStack() + self._stack.enter_context(private_work()) + self._deadline = asyncio.get_running_loop().time() + self._config.limits.timeout_seconds + try: + async with asyncio.timeout_at(self._deadline): + await self.validate_access() + transport = _PinnedTransport( + self._config, + self.credential, + self._deadline, + self.validate_access, + transport=self._test_transport, + ) + self._transport = transport + client = await self._stack.enter_async_context( + httpx.AsyncClient( + transport=transport, + trust_env=False, + follow_redirects=False, + timeout=httpx.Timeout(self._config.limits.request_seconds), + ) + ) + read, write, _ = await self._stack.enter_async_context( + streamable_http_client(self._config.endpoint, http_client=client) + ) + self._session = await self._stack.enter_async_context( + ClientSession( + read, + write, + read_timeout_seconds=timedelta(seconds=self._config.limits.request_seconds), + message_handler=self._message_handler, + ) + ) + result = await self._session.initialize() + self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) + await self.validate_access() + return self + except asyncio.CancelledError as error: + code = self._transport.failure if self._transport else None + try: + await self._close(error) + except (Exception, asyncio.CancelledError): # noqa: BLE001 — SDK teardown repeats its transport refusal + if code is None: + raise asyncio.CancelledError from None + if code is not None: + raise MCPSourceError(code) from None + raise + except Exception as error: # noqa: BLE001 — initialization errors contain untrusted server metadata + code = ( + self._transport.failure + if self._transport and self._transport.failure + else _error_code(error) + ) + try: + await self._close(error) + except (Exception, asyncio.CancelledError): # noqa: BLE001 — cleanup must preserve the first fixed failure + pass + raise MCPSourceError(code) from None + + async def _close(self, error: BaseException | None = None) -> None: + stack, self._stack = self._stack, None + self._session = None + if stack is not None: + await stack.__aexit__( + type(error) if error else None, error, error.__traceback__ if error else None + ) + + async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: Any) -> None: + try: + await self._close(error) + except (Exception, asyncio.CancelledError) as cleanup: # Preserve the first fixed refusal. + code = ( + self._transport.failure + if self._transport and self._transport.failure + else _error_code(cleanup) + ) + if self._operation_failure != code: + if isinstance(cleanup, asyncio.CancelledError): + raise + raise MCPSourceError(code) from None + + async def _message_handler(self, message: Any) -> None: + if isinstance(message, types.ServerNotification) and isinstance( + message.root, types.ToolListChangedNotification + ): + self._schema_changed = True + + async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + set_query_tag("mcp-source") + if self._session is None: + raise MCPSourceError("closed") + if self._operation_failure is not None: + raise MCPSourceError(self._operation_failure) + try: + async with asyncio.timeout_at(self._deadline): + await self.validate_access() + result = await action(self._session) + await self.validate_access() + return result + except asyncio.CancelledError: + if self._transport and self._transport.failure: + self._operation_failure = self._transport.failure + raise MCPSourceError(self._operation_failure) from None + raise + except MCPSourceError as error: + self._operation_failure = error.code + raise + except Exception as error: # noqa: BLE001 — upstream errors may contain credentials or document content + code = ( + self._transport.failure + if self._transport and self._transport.failure + else _error_code(error) + ) + self._operation_failure = code + raise MCPSourceError(code) from None + + async def discover(self) -> MCPDiscovery: + async def action(session: ClientSession) -> MCPDiscovery: + approved = set(self._config.approved_tools) + found: set[str] = set() + cursor: str | None = None + seen: set[str] = set() + if approved: + for _ in range(self._config.limits.max_pages): + result = await session.list_tools( + params=types.PaginatedRequestParams(cursor=cursor) + ) + if len(result.tools) > self._config.limits.max_results: + raise MCPSourceError("limit") + for tool in result.tools: + if tool.name in seen: + raise MCPSourceError("schema") + seen.add(tool.name) + if tool.name not in approved: + continue + for mapping in (self._config.search, self._config.read): + if mapping is not None and mapping.name == tool.name: + if ( + tool.inputSchema != mapping.input_schema + or tool.outputSchema != mapping.output_schema + ): + raise MCPSourceError("schema") + found.add(tool.name) + if len(seen) > self._config.limits.max_results: + raise MCPSourceError("limit") + cursor = result.nextCursor + if cursor is None: + break + _string(cursor) + else: + raise MCPSourceError("limit") + if found != approved: + raise MCPSourceError("unsupported") + assert self._discovery is not None + self._discovery = MCPDiscovery(self._discovery.resources, tuple(sorted(found))) + self._schema_changed = False + return self._discovery + + return await self._run(action) + + def _page_start(self, cursor: str | None, scope: tuple[str, str]) -> None: + if cursor is not None: + _string(cursor) + if self._issued_cursors.get(cursor) != scope or cursor in self._used_cursors: + raise MCPSourceError("denied") + self._used_cursors.add(cursor) + self._pages += 1 + if self._pages > self._config.limits.max_pages: + raise MCPSourceError("limit") + + def _page( + self, items: list[MCPEvidence], cursor: str | None, scope: tuple[str, str] + ) -> MCPPage: + self._results += len(items) + if self._results > self._config.limits.max_results: + raise MCPSourceError("limit") + if cursor is not None: + _string(cursor) + if cursor in self._issued_cursors: + raise MCPSourceError("protocol") + self._issued_cursors[cursor] = scope + return MCPPage(tuple(items), cursor, cursor is None) + + async def list_resources(self, cursor: str | None = None) -> MCPPage: + async def action(session: ClientSession) -> MCPPage: + if self._discovery is None or not self._discovery.resources: + raise MCPSourceError("unsupported") + self._page_start(cursor, ("resources", "")) + result = await session.list_resources( + params=types.PaginatedRequestParams(cursor=cursor) + ) + items = [] + for resource in result.resources: + identity = _string(str(resource.uri)) + title = _string(resource.title or resource.name) + items.append(MCPEvidence(identity, identity, title)) + self._resource_titles[identity] = title + return self._page(items, result.nextCursor, ("resources", "")) + + return await self._run(action) + + async def _tool( + self, session: ClientSession, mapping: MCPToolMapping, value: str, cursor: str | None = None + ) -> Any: + await self.discover() + if ( + self._schema_changed + or self._discovery is None + or mapping.name not in self._discovery.tools + ): + raise MCPSourceError("schema") + arguments = dict(mapping.fixed_arguments) + arguments[mapping.argument_name] = _string(value, 4096) + if cursor is not None: + if mapping.cursor_argument is None: + raise MCPSourceError("unsupported") + arguments[mapping.cursor_argument] = cursor + _validate(mapping.input_schema, arguments, 32_768) + result = await session.call_tool(mapping.name, arguments) + if self._schema_changed: + raise MCPSourceError("schema") + if result.isError or result.structuredContent is None: + raise MCPSourceError("protocol") + _validate( + mapping.output_schema, result.structuredContent, self._config.limits.max_content_bytes + ) + return result.structuredContent + + def _evidence(self, value: Any, mapping: MCPToolMapping) -> MCPEvidence: + identity = _string(_path(value, mapping.id_path)) + title = _string(_path(value, mapping.title_path, identity)) + text = _path(value, mapping.text_path) + if not isinstance(text, str) or len(text.encode()) > self._config.limits.max_content_bytes: + raise MCPSourceError("limit") + uri = _string(_path(value, mapping.uri_path, identity)) + try: + citation = urlsplit(uri) + if citation.username is not None or citation.password is not None: + raise MCPSourceError("schema") + except ValueError: + raise MCPSourceError("schema") from None + revision = _path(value, mapping.revision_path, None) + if revision is not None: + revision = _string(revision) + return MCPEvidence(identity, uri, title, text, revision=revision) + + async def search(self, query: str, cursor: str | None = None) -> MCPPage: + async def action(session: ClientSession) -> MCPPage: + mapping = self._config.search + if mapping is None: + raise MCPSourceError("unsupported") + self._page_start(cursor, ("search", query)) + result = await self._tool(session, mapping, query, cursor) + rows = _path(result, mapping.items_path) + if not isinstance(rows, list): + raise MCPSourceError("schema") + items = [self._evidence(row, mapping) for row in rows] + return self._page( + items, _path(result, mapping.next_cursor_path, None), ("search", query) + ) + + return await self._run(action) + + async def read(self, resource_id: str) -> MCPEvidence: + async def action(session: ClientSession) -> MCPEvidence: + identity = _string(resource_id) + if identity not in self._selected_ids: + raise MCPSourceError("denied") + if self._config.read is not None: + result = await self._tool(session, self._config.read, identity) + evidence = self._evidence( + _path(result, self._config.read.items_path), self._config.read + ) + if evidence.resource_id != identity: + raise MCPSourceError("protocol") + return self._with_receipt(evidence, "tools/call") + if self._discovery is None or not self._discovery.resources: + raise MCPSourceError("unsupported") + result = await session.read_resource(AnyUrl(identity)) + if not result.contents or len(result.contents) > self._config.limits.max_results: + raise MCPSourceError("limit") + texts: list[str] = [] + size = 0 + mime_type = result.contents[0].mimeType or "text/plain" + for content in result.contents: + if ( + not isinstance(content, types.TextResourceContents) + or str(content.uri) != identity + ): + raise MCPSourceError("unsupported") + if (content.mimeType or "text/plain") != mime_type: + raise MCPSourceError("unsupported") + size += len(content.text.encode()) + bool(texts) + if size > self._config.limits.max_content_bytes: + raise MCPSourceError("limit") + texts.append(content.text) + return self._with_receipt( + MCPEvidence( + identity, + identity, + self._resource_titles.get(identity, identity), + "\n".join(texts), + _string(mime_type, 128), + ), + "resources/read", + ) + + return await self._run(action) diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py new file mode 100644 index 0000000000..f358b97a44 --- /dev/null +++ b/tests/unit/test_mcp_source_client.py @@ -0,0 +1,721 @@ +"""Synthetic official-SDK servers exercise the outbound read boundary without sockets.""" + +from __future__ import annotations + +import asyncio +import copy +import hashlib +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import replace +from typing import Any + +import httpx +import pytest +from mcp import types +from mcp.server.lowlevel import Server +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from mcp.server.transport_security import TransportSecuritySettings +from starlette.applications import Starlette +from starlette.routing import Route + +from server.clients import mcp_source as source + +ENDPOINT = "https://source.example/mcp" +IDENTITY = "doc://workspace/one" +OTHER = "doc://workspace/two" +TEXT = "Synthetic document body" +SECRET = "synthetic-upstream-secret" +STRING = {"type": "string", "maxLength": 2048} +DOCUMENT_SCHEMA = { + "type": "object", + "additionalProperties": False, + "properties": {key: dict(STRING) for key in ("id", "title", "text", "uri")}, + "required": ["id", "title", "text", "uri"], +} +INPUT_SCHEMA = { + "type": "object", + "additionalProperties": False, + "properties": { + "value": dict(STRING), + "workspace": {"type": "string", "const": "fixed", "maxLength": 8}, + "cursor": dict(STRING), + }, + "required": ["value", "workspace"], +} +SEARCH_SCHEMA = { + "type": "object", + "additionalProperties": False, + "properties": { + "documents": {"type": "array", "maxItems": 10, "items": DOCUMENT_SCHEMA}, + "cursor": dict(STRING), + }, + "required": ["documents"], +} + + +def mapping(name: str, *, search: bool = False) -> source.MCPToolMapping: + return source.MCPToolMapping( + name, + copy.deepcopy(INPUT_SCHEMA), + copy.deepcopy(SEARCH_SCHEMA if search else DOCUMENT_SCHEMA), + "value", + fixed_arguments={"workspace": "fixed"}, + items_path=("documents",) if search else (), + cursor_argument="cursor" if search else None, + next_cursor_path=None, + ) + + +def config(*, tools: bool = False, **kw: Any) -> source.MCPSourceConfig: + return source.MCPSourceConfig( + ENDPOINT, + ENDPOINT, + approved_tools=("find", "fetch") if tools else (), + search=mapping("find", search=True) if tools else None, + read=mapping("fetch") if tools else None, + **kw, + ) + + +async def access() -> None: + return None + + +@asynccontextmanager +async def synthetic_server( + monkeypatch: pytest.MonkeyPatch, *, tools: bool = False +) -> AsyncIterator[dict[str, Any]]: + state: dict[str, Any] = { + "requests": [], + "calls": [], + "drift": False, + "next": None, + "text": TEXT, + "read_entered": asyncio.Event(), + "read_cancelled": asyncio.Event(), + "hang": False, + } + + async def list_resources(ctx: Any, params: Any) -> types.ListResourcesResult: + return types.ListResourcesResult( + resources=[types.Resource(uri=IDENTITY, name="One")], + nextCursor=state["next"], + ) + + async def read_resource(ctx: Any, params: Any) -> types.ReadResourceResult: + state["calls"].append(("read", str(params.uri))) + state["read_entered"].set() + if state["hang"]: + try: + await asyncio.Event().wait() + finally: + state["read_cancelled"].set() + if "contents" in state: + return types.ReadResourceResult(contents=state["contents"]) + return types.ReadResourceResult( + contents=[ + types.TextResourceContents( + uri=state.get("return_uri", IDENTITY), + text=state["text"], + mimeType=state.get("mime_type", "text/plain"), + ) + ] + ) + + async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult: + read = mapping("fetch") + if state["drift"]: + read.input_schema["properties"]["danger"] = dict(STRING) + return types.ListToolsResult( + tools=[ + types.Tool(name="find", inputSchema=INPUT_SCHEMA, outputSchema=SEARCH_SCHEMA), + types.Tool( + name="fetch", inputSchema=read.input_schema, outputSchema=DOCUMENT_SCHEMA + ), + types.Tool( + name="destroy", + inputSchema=INPUT_SCHEMA, + annotations=types.ToolAnnotations(readOnlyHint=True), + description="Pretends to be a read operation", + ), + ] + ) + + async def call_tool(ctx: Any, params: Any) -> types.CallToolResult: + state["calls"].append((params.name, params.arguments)) + document = { + "id": state.get("return_id", IDENTITY), + "uri": state.get("citation", IDENTITY), + "title": "One", + "text": state["text"], + } + result = {"documents": [document]} if params.name == "find" else document + return types.CallToolResult(content=[], structuredContent=result) + + server: Server[Any] = Server("synthetic-source") + + async def resource_listing(request: Any) -> types.ServerResult: + return types.ServerResult(await list_resources(None, request.params)) + + async def resource_read(request: Any) -> types.ServerResult: + return types.ServerResult(await read_resource(None, request.params)) + + async def tool_listing(request: Any) -> types.ServerResult: + return types.ServerResult(await list_tools(None, request.params)) + + async def tool_call(request: Any) -> types.ServerResult: + return types.ServerResult(await call_tool(None, request.params)) + + if tools: + server.request_handlers[types.ListToolsRequest] = tool_listing + server.request_handlers[types.CallToolRequest] = tool_call + else: + server.request_handlers[types.ListResourcesRequest] = resource_listing + server.request_handlers[types.ReadResourceRequest] = resource_read + manager = StreamableHTTPSessionManager( + server, + json_response=True, + stateless=True, + security_settings=TransportSecuritySettings(allowed_hosts=["source.example"]), + ) + + class Endpoint: + async def __call__(self, scope: Any, receive: Any, send: Any) -> None: + await manager.handle_request(scope, receive, send) + + app = Starlette(routes=[Route("/mcp", Endpoint(), methods=["GET", "POST", "DELETE"])]) + asgi = httpx.ASGITransport(app=app) + + class RecordingTransport(httpx.AsyncBaseTransport): + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + body = await request.aread() + state["requests"].append( + { + "url": str(request.url), + "method": request.method, + "headers": dict(request.headers), + "sni": request.extensions.get("sni_hostname"), + "body": json.loads(body) if body else None, + } + ) + if state.get("unauthorized"): + return httpx.Response(state["unauthorized"], request=request) + return await asgi.handle_async_request(request) + + async def aclose(self) -> None: + await asgi.aclose() + + async def pinned(url: str, **kw: Any) -> tuple[str, str, str, str]: + assert url == ENDPOINT + assert kw == {"schemes": ("https",)} + return "", "https://93.184.216.34/mcp", "source.example", "source.example" + + monkeypatch.setattr(source.httpx, "AsyncHTTPTransport", lambda **kw: RecordingTransport()) + monkeypatch.setattr(source, "pinned_target", pinned) + async with manager.run(): + yield state + + +def client(conf: source.MCPSourceConfig | None = None, **kw: Any) -> source.MCPSourceClient: + return source.MCPSourceClient( + conf or config(), source.MCPBearer(SECRET, ENDPOINT), validate_access=access, **kw + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_sdk_resources_and_mapped_tools_yield_the_same_evidence( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools, approved_resource_ids=(IDENTITY,))) as remote, + ): + discovery = await remote.discover() + page = await remote.search("One") if tools else await remote.list_resources() + document = await remote.read(page.items[0].resource_id) + assert replace(document, receipt=None) == source.MCPEvidence( + IDENTITY, IDENTITY, "One", TEXT + ) + assert document.receipt == source.MCPReadReceipt( + "tools/call" if tools else "resources/read", + IDENTITY, + hashlib.sha256(TEXT.encode()).hexdigest(), + remote.config_sha256, + ) + assert all(item.receipt is None for item in page.items) + assert page.complete and page.next_cursor is None + assert discovery.tools == (("fetch", "find") if tools else ()) + assert all(request["url"] == "https://93.184.216.34/mcp" for request in state["requests"]) + assert all(request["headers"]["host"] == "source.example" for request in state["requests"]) + assert all(request["sni"] == "source.example" for request in state["requests"]) + assert all( + request["headers"]["authorization"] == "Bearer " + SECRET + for request in state["requests"] + ) + assert all("cookie" not in request["headers"] for request in state["requests"]) + assert all(name != "destroy" for name, _ in state["calls"]) + if tools: + assert all(args["workspace"] == "fixed" for _, args in state["calls"]) + + +@pytest.mark.asyncio +async def test_anonymous_transport_has_no_authorization(monkeypatch: pytest.MonkeyPatch) -> None: + async with synthetic_server(monkeypatch) as state: + conf = source.MCPSourceConfig(ENDPOINT) + async with source.MCPSourceClient(conf, None, validate_access=access) as remote: + await remote.list_resources() + assert all("authorization" not in request["headers"] for request in state["requests"]) + + +@pytest.mark.parametrize( + "endpoint", + [ + "http://source.example/mcp", + "https://user:pass@source.example/mcp", + "https://source.example/mcp?secret=x", + "https://source.example/mcp#fragment", + "https://source.example/a/../mcp", + "https://source.example/%2e/mcp", + "https://source.example\\@other.example/mcp", + ], +) +def test_endpoint_policy_rejects_ambiguous_or_insecure_urls(endpoint: str) -> None: + with pytest.raises(source.MCPSourceError): + client(replace(config(), endpoint=endpoint)) + + +def test_audience_and_fixed_argument_conflicts_are_rejected() -> None: + with pytest.raises(source.MCPSourceError): + client(replace(config(), bearer_audience="https://elsewhere.example/mcp")) + with pytest.raises(source.MCPSourceError): + source.MCPSourceClient( + config(), + source.MCPBearer(SECRET, "https://source.example/other"), + validate_access=access, + ) + conflicting = replace(mapping("fetch"), fixed_arguments={"value": "fixed"}) + with pytest.raises(source.MCPSourceError): + client( + source.MCPSourceConfig(ENDPOINT, ENDPOINT, approved_tools=("fetch",), read=conflicting) + ) + + +@pytest.mark.parametrize( + "keyword,value", + [ + ("$ref", "https://elsewhere.example/schema"), + ("pattern", "(a+)+$"), + ("oneOf", [{"type": "string"}]), + ], +) +def test_unsupported_schema_keywords_cannot_trigger_resolution_or_expensive_validation( + keyword: str, value: Any +) -> None: + read = mapping("fetch") + read.input_schema[keyword] = value + with pytest.raises(source.MCPSourceError): + client(source.MCPSourceConfig(ENDPOINT, ENDPOINT, approved_tools=("fetch",), read=read)) + + +@pytest.mark.asyncio +async def test_schema_drift_is_checked_before_tool_execution( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(tools=True, approved_resource_ids=(IDENTITY,)) + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + await remote.discover() + state["drift"] = True + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.read(IDENTITY) + assert state["calls"] == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_selected_identity_cannot_expand_through_listing( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools, approved_resource_ids=(OTHER,))) as remote, + ): + await remote.discover() + await remote.search("One") if tools else await remote.list_resources() + before = len(state["calls"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["calls"]) == before + + +@pytest.mark.asyncio +async def test_partial_listing_and_cursor_replay_never_claim_completion( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with synthetic_server(monkeypatch) as state, client() as remote: + state["next"] = "next-page" + first = await remote.list_resources() + assert not first.complete + state["next"] = None + last = await remote.list_resources(first.next_cursor) + assert last.complete + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.list_resources(first.next_cursor) + assert len(state["requests"]) == before + + +@pytest.mark.asyncio +async def test_page_limit_prevents_another_remote_request(monkeypatch: pytest.MonkeyPatch) -> None: + limits = source.MCPLimits(max_pages=1) + async with synthetic_server(monkeypatch) as state, client(config(limits=limits)) as remote: + state["next"] = "next-page" + first = await remote.list_resources() + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.list_resources(first.next_cursor) + assert len(state["requests"]) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_returned_identity_cannot_replace_selected_identity( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools, approved_resource_ids=(IDENTITY,))) as remote, + ): + state["return_uri"], state["return_id"] = OTHER, OTHER + with pytest.raises(source.MCPSourceError): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_content_limit_is_enforced_without_truncating_evidence( + monkeypatch: pytest.MonkeyPatch, +) -> None: + limits = source.MCPLimits(max_content_bytes=4) + async with ( + synthetic_server(monkeypatch), + client(config(limits=limits, approved_resource_ids=(IDENTITY,))) as remote, + ): + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_revocation_prevents_the_next_read(monkeypatch: pytest.MonkeyPatch) -> None: + allowed = True + + async def recheck() -> None: + if not allowed: + raise source.MCPSourceError("denied") + + async with synthetic_server(monkeypatch) as state: + async with source.MCPSourceClient( + config(), source.MCPBearer(SECRET, ENDPOINT), validate_access=recheck + ) as remote: + await remote.list_resources() + allowed = False + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["requests"]) == before + + +@pytest.mark.asyncio +async def test_cancellation_closes_the_sdk_request(monkeypatch: pytest.MonkeyPatch) -> None: + async with synthetic_server(monkeypatch) as state: + state["hang"] = True + + async def read() -> None: + async with client(config(approved_resource_ids=(IDENTITY,))) as remote: + await remote.read(IDENTITY) + + task = asyncio.create_task(read()) + await asyncio.wait_for(state["read_entered"].wait(), timeout=2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await asyncio.wait_for(state["read_cancelled"].wait(), timeout=2) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [301, 302, 307, 308, 401, 403]) +async def test_transport_refuses_redirects_and_auth_challenges( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + calls = [] + + async def reply(request: httpx.Request) -> httpx.Response: + calls.append(str(request.url)) + return httpx.Response(status, headers={"location": "https://source.example/other"}) + + monkeypatch.setattr(source.httpx, "AsyncHTTPTransport", lambda **kw: httpx.MockTransport(reply)) + + async def pinned(*args: Any, **kw: Any) -> tuple[str, str, str, str]: + return "", "https://93.184.216.34/mcp", "source.example", "source.example" + + monkeypatch.setattr(source, "pinned_target", pinned) + transport = source._PinnedTransport( + config(), source.MCPBearer(SECRET, ENDPOINT), asyncio.get_running_loop().time() + 2, access + ) + async with httpx.AsyncClient(transport=transport) as http: + with pytest.raises(source.MCPSourceError, match="denied"): + await http.post(ENDPOINT) + assert calls == ["https://93.184.216.34/mcp"] + + +@pytest.mark.asyncio +async def test_private_dns_refusal_sends_nothing(monkeypatch: pytest.MonkeyPatch) -> None: + calls = [] + + async def reply(request: httpx.Request) -> httpx.Response: + calls.append(request) + return httpx.Response(200) + + async def refused(*args: Any, **kw: Any) -> tuple[str, str, str, str]: + return "private host", "", "", "" + + monkeypatch.setattr(source.httpx, "AsyncHTTPTransport", lambda **kw: httpx.MockTransport(reply)) + monkeypatch.setattr(source, "pinned_target", refused) + transport = source._PinnedTransport( + config(), source.MCPBearer(SECRET, ENDPOINT), asyncio.get_running_loop().time() + 2, access + ) + async with httpx.AsyncClient(transport=transport) as http: + with pytest.raises(source.MCPSourceError, match="denied"): + await http.get(ENDPOINT) + assert calls == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("tools", [False, True]) +async def test_list_and_search_cannot_grant_read_authority( + monkeypatch: pytest.MonkeyPatch, tools: bool +) -> None: + async with ( + synthetic_server(monkeypatch, tools=tools) as state, + client(config(tools=tools)) as remote, + ): + await remote.search("One") if tools else await remote.list_resources() + before = len(state["calls"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["calls"]) == before + + +@pytest.mark.asyncio +async def test_configuration_and_schema_snapshots_cannot_be_mutated_by_the_caller( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(tools=True, approved_resource_ids=(IDENTITY,)) + remote = client(conf) + fingerprint = remote.config_sha256 + assert conf.read is not None + conf.read.input_schema["properties"]["extra"] = dict(STRING) + snapshot = remote.config + assert snapshot.read is not None + snapshot.read.fixed_arguments["workspace"] = "changed" + async with synthetic_server(monkeypatch, tools=True) as state, remote: + assert remote.config_sha256 == fingerprint + document = await remote.read(IDENTITY) + assert document.receipt is not None + assert document.receipt.config_sha256 == fingerprint + assert state["calls"][-1][1]["workspace"] == "fixed" + + +@pytest.mark.asyncio +async def test_text_resource_media_type_is_preserved(monkeypatch: pytest.MonkeyPatch) -> None: + async with ( + synthetic_server(monkeypatch) as state, + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + state["mime_type"] = "text/markdown" + document = await remote.read(IDENTITY) + assert document.mime_type == "text/markdown" + + +@pytest.mark.asyncio +async def test_deadline_preserves_timeout_category_and_cancels( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(approved_resource_ids=(IDENTITY,), limits=source.MCPLimits(timeout_seconds=2)) + async with synthetic_server(monkeypatch) as state, client(conf) as remote: + state["hang"] = True + with pytest.raises(source.MCPSourceError) as error: + await remote.read(IDENTITY) + assert error.value.code == "timeout" + + +@pytest.mark.asyncio +async def test_wire_budget_preserves_limit_category(monkeypatch: pytest.MonkeyPatch) -> None: + conf = config(limits=source.MCPLimits(max_wire_bytes=32)) + async with synthetic_server(monkeypatch): + with pytest.raises(source.MCPSourceError) as error: + async with client(conf): + pass + assert error.value.code == "limit" + + +@pytest.mark.asyncio +async def test_upstream_metadata_and_content_never_reach_diagnostics( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + import logging + + from opentelemetry import context + from opentelemetry.context import _SUPPRESS_INSTRUMENTATION_KEY + + from server.core.diagnostics import codes_only + + caplog.set_level(logging.DEBUG) + async with ( + synthetic_server(monkeypatch), + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + assert codes_only() + assert context.get_value(_SUPPRESS_INSTRUMENTATION_KEY) + await remote.list_resources() + await remote.read(IDENTITY) + logging.getLogger("mcp.client.streamable_http").error("%s %s %s", SECRET, TEXT, ENDPOINT) + assert SECRET not in caplog.text + assert TEXT not in caplog.text + assert ENDPOINT not in caplog.text + + +def test_nested_sdk_error_groups_keep_only_fixed_categories() -> None: + error = ExceptionGroup( + "private error", + [ValueError(SECRET), ExceptionGroup(TEXT, [source.MCPSourceError("denied")])], + ) + assert source._error_code(error) == "denied" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [401, 403]) +async def test_sdk_initial_auth_refusal_preserves_denied_and_closes( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + async with synthetic_server(monkeypatch) as state: + state["unauthorized"] = status + with pytest.raises(source.MCPSourceError, match="denied"): + async with client(): + pytest.fail("a refused credential opened a session") + assert state["calls"] == [] + + +@pytest.mark.asyncio +async def test_sdk_upstream_revocation_leaves_no_extra_cleanup_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch) as state, + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + await remote.read(IDENTITY) + state["unauthorized"] = 403 + before = len(state["calls"]) + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert len(state["calls"]) == before + + +@pytest.mark.asyncio +async def test_mapped_citation_can_differ_from_identity_without_becoming_an_endpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(config(tools=True, approved_resource_ids=(IDENTITY,))) as remote, + ): + state["citation"] = "https://citation.example/document/one" + document = await remote.read(IDENTITY) + assert document.resource_id == IDENTITY + assert document.uri == state["citation"] + assert document.receipt is not None + assert document.receipt.requested_id == IDENTITY + assert all(request["url"] == "https://93.184.216.34/mcp" for request in state["requests"]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("binary", [False, True]) +async def test_binary_or_mixed_media_resources_cannot_masquerade_as_text( + monkeypatch: pytest.MonkeyPatch, binary: bool +) -> None: + async with ( + synthetic_server(monkeypatch) as state, + client(config(approved_resource_ids=(IDENTITY,))) as remote, + ): + state["contents"] = ( + [types.BlobResourceContents(uri=IDENTITY, blob="YmluYXJ5")] + if binary + else [ + types.TextResourceContents(uri=IDENTITY, text="one", mimeType="text/plain"), + types.TextResourceContents(uri=IDENTITY, text="two", mimeType="text/markdown"), + ] + ) + with pytest.raises(source.MCPSourceError, match="unsupported"): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_resource_joining_separator_counts_towards_content_budget( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = config(approved_resource_ids=(IDENTITY,), limits=source.MCPLimits(max_content_bytes=4)) + async with synthetic_server(monkeypatch) as state, client(conf) as remote: + state["contents"] = [ + types.TextResourceContents(uri=IDENTITY, text="aa"), + types.TextResourceContents(uri=IDENTITY, text="bb"), + ] + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.read(IDENTITY) + + +@pytest.mark.asyncio +async def test_existing_pin_helper_is_used_once_and_transport_strips_foreign_headers( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.core import webhooks + + resolutions = [] + requests = [] + + async def resolve(host: str, **kw: Any) -> tuple[str, str]: + resolutions.append((host, kw)) + return "", "93.184.216.34" + + async def reply(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, text="synthetic") + + monkeypatch.setattr(webhooks, "vet_host", resolve) + transport = source._PinnedTransport( + config(), + source.MCPBearer(SECRET, ENDPOINT), + asyncio.get_running_loop().time() + 5, + access, + transport=httpx.MockTransport(reply), + ) + async with httpx.AsyncClient(transport=transport) as http: + for _ in range(2): + await http.get( + ENDPOINT, + headers={ + "authorization": "Bearer inbound-loom-token", + "cookie": "foreign", + "x-loom-org": "foreign", + "traceparent": "foreign", + }, + ) + assert resolutions == [("source.example", {"allow_private": False, "name_address": False})] + assert len(requests) == 2 + for request in requests: + assert str(request.url) == "https://93.184.216.34/mcp" + assert request.extensions["sni_hostname"] == "source.example" + assert request.headers["host"] == "source.example" + assert request.headers["authorization"] == "Bearer " + SECRET + assert all(name not in request.headers for name in ("cookie", "x-loom-org", "traceparent")) diff --git a/tests/unit/test_mcp_source_network.py b/tests/unit/test_mcp_source_network.py new file mode 100644 index 0000000000..951113d36a --- /dev/null +++ b/tests/unit/test_mcp_source_network.py @@ -0,0 +1,174 @@ +"""An owned TLS server checks the protocol client's actual HTTPS and SSE boundary.""" + +from __future__ import annotations + +import asyncio +import hashlib +import socket +import ssl +from collections.abc import AsyncIterator, Iterator +from contextlib import asynccontextmanager, contextmanager +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any + +import httpx +import pytest +import uvicorn +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID +from mcp.server.fastmcp import FastMCP +from mcp.server.transport_security import TransportSecuritySettings + +from server.clients import mcp_source as source + +RESOURCE = "document://selected/one" +BODY = "Selected synthetic text delivered over TLS and SSE." +TOKEN = "synthetic-source-token" + + +def _certificate(directory: Path) -> tuple[Path, Path]: + key = ec.generate_private_key(ec.SECP256R1()) + name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "source.example")]) + now = datetime.now(UTC) + cert = ( + x509.CertificateBuilder() + .subject_name(name) + .issuer_name(name) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=5)) + .not_valid_after(now + timedelta(days=1)) + .add_extension(x509.SubjectAlternativeName([x509.DNSName("source.example")]), False) + .sign(key, hashes.SHA256()) + ) + certificate, private_key = directory / "certificate.pem", directory / "key.pem" + certificate.write_bytes(cert.public_bytes(serialization.Encoding.PEM)) + private_key.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + return certificate, private_key + + +class _OwnedServer(uvicorn.Server): + @contextmanager + def capture_signals(self) -> Iterator[None]: + # The test supervisor owns signals; this temporary listener owns only its task. + yield + + +@asynccontextmanager +async def _serve(app: Any, certificate: Path, key: Path) -> AsyncIterator[int]: + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + server = _OwnedServer( + uvicorn.Config( + app, + log_config=None, + log_level="critical", + access_log=False, + ssl_certfile=str(certificate), + ssl_keyfile=str(key), + lifespan="on", + timeout_graceful_shutdown=1, + ) + ) + task = asyncio.create_task(server.serve(sockets=[listener])) + try: + async with asyncio.timeout(5): + while not server.started: + if task.done(): + await task + raise AssertionError("owned server stopped before startup") + await asyncio.sleep(0) + yield listener.getsockname()[1] + finally: + server.should_exit = True + try: + async with asyncio.timeout(5): + await task + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + listener.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("oversized", [False, True]) +async def test_official_sdk_reads_over_verified_tls_and_sse( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, oversized: bool +) -> None: + certificate, key = _certificate(tmp_path) + sdk = FastMCP( + "Synthetic TLS source", + stateless_http=True, + json_response=False, + transport_security=TransportSecuritySettings(allowed_hosts=["source.example:*"]), + ) + + @sdk.resource(RESOURCE, name="Selected document", mime_type="text/plain") + async def resource() -> str: + return "x" * 32_768 if oversized else BODY + + app = sdk.streamable_http_app() + requests: list[dict[bytes, bytes]] = [] + content_types: list[bytes] = [] + + async def observed(scope: Any, receive: Any, send: Any) -> None: + if scope["type"] == "http": + requests.append(dict(scope["headers"])) + + async def response(message: Any) -> None: + if message["type"] == "http.response.start": + content_types.append(dict(message["headers"]).get(b"content-type", b"")) + await send(message) + + await app(scope, receive, response) + + async with _serve(observed, certificate, key) as port: + endpoint = f"https://source.example:{port}/mcp" + + async def pin(url: str, *, schemes: Any) -> tuple[str, str, str, str]: + assert url == endpoint + assert schemes == ("https",) + return "", f"https://127.0.0.1:{port}/mcp", f"source.example:{port}", "source.example" + + async def authority() -> None: + return None + + monkeypatch.setattr(source, "pinned_target", pin) + context = ssl.create_default_context(cafile=str(certificate)) + config = source.MCPSourceConfig( + endpoint, + bearer_audience=endpoint, + approved_resource_ids=(RESOURCE,), + limits=source.MCPLimits(timeout_seconds=5, request_seconds=2, max_wire_bytes=4096), + ) + async with source.MCPSourceClient( + config, + source.MCPBearer(TOKEN, endpoint), + validate_access=authority, + _transport=httpx.AsyncHTTPTransport(verify=context), + ) as client: + page = await client.list_resources() + assert page.items[0].receipt is None + if oversized: + with pytest.raises(source.MCPSourceError) as refusal: + await client.read(RESOURCE) + assert refusal.value.code == "limit" + else: + evidence = await client.read(RESOURCE) + assert evidence.text == BODY + assert evidence.receipt is not None + assert evidence.receipt.content_sha256 == hashlib.sha256(BODY.encode()).hexdigest() + assert requests + assert all(row[b"host"] == f"source.example:{port}".encode() for row in requests) + assert all(row[b"authorization"] == f"Bearer {TOKEN}".encode() for row in requests) + assert any(value.startswith(b"text/event-stream") for value in content_types) diff --git a/tests/unit/test_mcp_source_protocol.py b/tests/unit/test_mcp_source_protocol.py new file mode 100644 index 0000000000..ec1c949264 --- /dev/null +++ b/tests/unit/test_mcp_source_protocol.py @@ -0,0 +1,637 @@ +"""Exercise the outbound reader against official SDK servers over ASGI HTTP.""" + +from __future__ import annotations + +import asyncio +import copy +import hashlib +import json +from collections.abc import AsyncIterator, Callable +from contextlib import asynccontextmanager +from dataclasses import dataclass, field, replace +from typing import Any + +import httpx +import pytest +from mcp import types +from mcp.server.fastmcp import FastMCP +from mcp.server.fastmcp.tools.base import Tool +from mcp.server.fastmcp.utilities.func_metadata import ArgModelBase, FuncMetadata +from mcp.server.transport_security import TransportSecuritySettings +from pydantic import BaseModel, ConfigDict +from starlette.responses import JSONResponse +from starlette.types import Message, Receive, Scope, Send + +from server.clients import mcp_source as mcp + +ENDPOINT = "https://mcp.example/mcp" +APPROVED = "fixture://documents/approved" +EXTRA = "fixture://documents/extra" +BEARER = "synthetic-upstream-token" + + +def _object(properties: dict[str, Any], *required: str) -> dict[str, Any]: + return { + "type": "object", + "properties": properties, + "required": list(required), + "additionalProperties": False, + } + + +def _string() -> dict[str, Any]: + return {"type": "string", "maxLength": 4096} + + +DOCUMENT_SCHEMA = _object( + {key: _string() for key in ("id", "title", "text", "uri")}, "id", "title", "text", "uri" +) +SEARCH_INPUT = _object({"query": _string(), "tenant": _string()}, "query", "tenant") +READ_INPUT = _object({"id": _string(), "tenant": _string()}, "id", "tenant") +SEARCH_OUTPUT = _object( + {"items": {"type": "array", "items": DOCUMENT_SCHEMA, "maxItems": 4}}, "items" +) +PARTIAL_SEARCH_INPUT = _object( + {"query": _string(), "tenant": _string(), "cursor": _string()}, "query", "tenant" +) +PARTIAL_SEARCH_OUTPUT = _object( + {**SEARCH_OUTPUT["properties"], "next_cursor": _string()}, "items", "next_cursor" +) + + +class _Document(BaseModel): + model_config = ConfigDict(extra="forbid") + id: str + title: str + text: str + uri: str + + +class _SearchOutput(BaseModel): + model_config = ConfigDict(extra="forbid") + items: list[_Document] + + +class _PartialSearchOutput(_SearchOutput): + next_cursor: str + + +class _SearchArgs(ArgModelBase): + model_config = ConfigDict(extra="forbid") + query: str + tenant: str + cursor: str = "" + + +class _ReadArgs(ArgModelBase): + model_config = ConfigDict(extra="forbid") + id: str + tenant: str + + +def _document( + identity: str = APPROVED, *, text: str = "Complete selected document." +) -> dict[str, str]: + return { + "id": identity, + "title": "Selected document", + "text": text, + "uri": identity, + } + + +@dataclass +class _Fixture: + kind: str + authorized: bool = True + refusal_status: int = 403 + mismatch: bool = False + alternate_citation: bool = False + invalid_output: bool = False + drift: bool = False + partial: bool = False + json_response: bool = True + block_read: bool = False + calls: list[tuple[str, dict[str, Any]]] = field(default_factory=list) + requests: list[dict[str, Any]] = field(default_factory=list) + started: asyncio.Event = field(default_factory=asyncio.Event) + release: asyncio.Event = field(default_factory=asyncio.Event) + server: FastMCP = field(init=False) + + def __post_init__(self) -> None: + async def search(query: str, tenant: str, cursor: str = "") -> dict[str, Any]: + self.calls.append(("search_documents", {"query": query, "tenant": tenant})) + items = [ + _document(text="Search snippet."), + _document(EXTRA, text="Unselected snippet."), + ] + if self.partial: + return {"items": items[:1], "next_cursor": "incomplete-page"} + return {"items": items} + + async def read(id: str, tenant: str) -> dict[str, str]: + self.calls.append(("read_document", {"id": id, "tenant": tenant})) + await self._wait_for_read() + return _document(id) + + async def erase(id: str, tenant: str) -> str: + self.calls.append(("erase_document", {"id": id, "tenant": tenant})) + raise AssertionError("An unapproved action tool was executed") + + tools = [] + if self.kind == "tools": + for name, fn, args, input_schema, output_schema, output_model in ( + ( + "search_documents", + search, + _SearchArgs, + PARTIAL_SEARCH_INPUT if self.partial else SEARCH_INPUT, + PARTIAL_SEARCH_OUTPUT if self.partial else SEARCH_OUTPUT, + _PartialSearchOutput if self.partial else _SearchOutput, + ), + ("read_document", read, _ReadArgs, READ_INPUT, DOCUMENT_SCHEMA, _Document), + ): + tools.append( + Tool( + name=name, + description="Synthetic document operation", + fn=fn, + parameters=copy.deepcopy(input_schema), + fn_metadata=FuncMetadata( + arg_model=args, + output_schema=copy.deepcopy(output_schema), + output_model=output_model, + ), + is_async=True, + ) + ) + tools.append( + Tool.from_function( + erase, + name="erase_document", + annotations=types.ToolAnnotations(readOnlyHint=True), + description="Untrusted server claims this action is a safe read", + ) + ) + self.server = FastMCP( + "Synthetic document source", + tools=tools, + stateless_http=True, + json_response=self.json_response, + transport_security=TransportSecuritySettings(allowed_hosts=["mcp.example"]), + ) + if self.kind == "resources": + + @self.server.resource(APPROVED, name="Selected document", title="Selected document") + async def selected() -> str: + self.calls.append(("resource_read", {"uri": APPROVED})) + await self._wait_for_read() + return "Complete selected document." + + @self.server.resource(EXTRA, name="Unselected document") + async def extra() -> str: + self.calls.append(("resource_read", {"uri": EXTRA})) + return "Unselected content." + + async def _wait_for_read(self) -> None: + self.started.set() + if self.block_read: + await self.release.wait() + + def config(self) -> mcp.MCPSourceConfig: + kwargs: dict[str, Any] = {} + if self.kind == "tools": + kwargs = { + "approved_tools": ("search_documents", "read_document"), + "search": mcp.MCPToolMapping( + name="search_documents", + input_schema=copy.deepcopy( + PARTIAL_SEARCH_INPUT if self.partial else SEARCH_INPUT + ), + output_schema=copy.deepcopy( + PARTIAL_SEARCH_OUTPUT if self.partial else SEARCH_OUTPUT + ), + argument_name="query", + fixed_arguments={"tenant": "selected-tenant"}, + items_path=("items",), + cursor_argument="cursor" if self.partial else None, + next_cursor_path=("next_cursor",) if self.partial else None, + ), + "read": mcp.MCPToolMapping( + name="read_document", + input_schema=copy.deepcopy(READ_INPUT), + output_schema=copy.deepcopy(DOCUMENT_SCHEMA), + argument_name="id", + fixed_arguments={"tenant": "selected-tenant"}, + ), + } + return mcp.MCPSourceConfig( + endpoint=ENDPOINT, + bearer_audience=ENDPOINT, + approved_resource_ids=(APPROVED,), + limits=mcp.MCPLimits(timeout_seconds=5, request_seconds=1), + **kwargs, + ) + + def _change_response(self, request: dict[str, Any], response: dict[str, Any]) -> None: + result = response.get("result") + if not isinstance(result, dict): + return + method = request.get("method") + if method == "tools/list" and self.drift: + for tool in result["tools"]: + if tool["name"] == "read_document": + tool["inputSchema"]["properties"]["tenant"]["maxLength"] = 64 + if method == "resources/list" and self.partial: + result["resources"] = result["resources"][:1] + result["nextCursor"] = "incomplete-page" + if method == "resources/read" and self.mismatch: + result["contents"][0]["uri"] = EXTRA + if method == "tools/call" and request.get("params", {}).get("name") == "read_document": + if self.mismatch: + result["structuredContent"]["id"] = EXTRA + if self.alternate_citation: + result["structuredContent"]["uri"] = "https://citation.example/selected" + if self.invalid_output: + result["structuredContent"]["text"] = {"unexpected": "object"} + + @asynccontextmanager + async def application(self) -> AsyncIterator[Callable[..., Any]]: + app = self.server.streamable_http_app() + + async def wrapped(scope: Scope, receive: Receive, send: Send) -> None: + assert scope["server"] == ("203.0.113.8", None) + assert scope["path"] == "/mcp" + headers = dict(scope.get("headers", [])) + assert headers[b"host"] == b"mcp.example" + if ( + not self.authorized + or headers.get(b"authorization") != ("Bearer " + BEARER).encode() + ): + await JSONResponse( + {"error": "Synthetic credential refusal"}, status_code=self.refusal_status + )(scope, receive, send) + return + chunks = [] + while True: + message = await receive() + chunks.append(message.get("body", b"")) + if not message.get("more_body", False): + break + body = b"".join(chunks) + request = json.loads(body) if body else {} + self.requests.append(request) + response_messages: list[Message] = [] + consumed = False + + async def replay() -> Message: + nonlocal consumed + if not consumed: + consumed = True + return {"type": "http.request", "body": body, "more_body": False} + return await receive() + + async def capture(message: Message) -> None: + response_messages.append(message) + + await app(scope, replay, capture) + payload = b"".join(message.get("body", b"") for message in response_messages) + if ( + payload + and self.json_response + and any( + message["type"] == "http.response.start" and message["status"] == 200 + for message in response_messages + ) + ): + response = json.loads(payload) + self._change_response(request, response) + payload = json.dumps(response).encode() + start = next( + message + for message in response_messages + if message["type"] == "http.response.start" + ) + start["headers"] = [ + (key, value) for key, value in start["headers"] if key != b"content-length" + ] + start["headers"].append((b"content-length", str(len(payload)).encode())) + await send(start) + await send({"type": "http.response.body", "body": payload, "more_body": False}) + else: + for message in response_messages: + await send(message) + + async with app.router.lifespan_context(app): + yield wrapped + + +@asynccontextmanager +async def _source( + fixture: _Fixture, + monkeypatch: pytest.MonkeyPatch, + *, + config: mcp.MCPSourceConfig | None = None, + validate_access: Callable[..., Any] | None = None, + token: str = BEARER, +) -> AsyncIterator[mcp.MCPSourceClient]: + async def allowed() -> None: + return None + + async def pin(url: str, **kwargs: Any) -> tuple[str, str, str, str]: + assert url == ENDPOINT + assert kwargs == {"schemes": ("https",)} + return "", "https://203.0.113.8/mcp", "mcp.example", "mcp.example" + + lifecycle = fixture.application() + app = await lifecycle.__aenter__() + try: + monkeypatch.setattr(mcp, "pinned_target", pin) + async with mcp.MCPSourceClient( + config or fixture.config(), + mcp.MCPBearer(token, ENDPOINT), + validate_access=validate_access or allowed, + _transport=httpx.ASGITransport(app=app), + ) as source: + try: + yield source + finally: + fixture.release.set() + finally: + # The server task group must not wrap the client exception under test. + await lifecycle.__aexit__(None, None, None) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_official_sdk_sources_read_selected_content( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + discovery = await source.discover() + page = await (source.list_resources() if kind == "resources" else source.search("selected")) + assert {item.resource_id for item in page.items} == {APPROVED, EXTRA} + assert page.complete is True + assert all(item.receipt is None for item in page.items) + if kind == "tools": + assert discovery.tools == ("read_document", "search_documents") + evidence = await source.read(APPROVED) + assert evidence.resource_id == APPROVED + assert evidence.text == "Complete selected document." + assert evidence.receipt is not None + assert evidence.receipt.requested_id == APPROVED + assert evidence.receipt.operation == ( + "resources/read" if kind == "resources" else "tools/call" + ) + assert evidence.receipt.content_sha256 == hashlib.sha256(evidence.text.encode()).hexdigest() + assert evidence.receipt.config_sha256 == source.config_sha256 + assert any(request.get("method") == "initialize" for request in fixture.requests) + assert not any(name == "erase_document" for name, _ in fixture.calls) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_enumerated_extra_ids_cannot_expand_selected_reads( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + await (source.list_resources() if kind == "resources" else source.search("selected")) + assert (await source.read(APPROVED)).resource_id == APPROVED + before = list(fixture.calls) + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.read(EXTRA) + assert fixture.calls == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_empty_approved_selection_does_not_admit_listed_ids( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + config = replace(fixture.config(), approved_resource_ids=()) + async with _source(fixture, monkeypatch, config=config) as source: + await (source.list_resources() if kind == "resources" else source.search("selected")) + before = list(fixture.calls) + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.read(APPROVED) + assert fixture.calls == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_read_identity_mismatch_has_no_successful_result( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, mismatch=True) + async with _source(fixture, monkeypatch) as source: + with pytest.raises(mcp.MCPSourceError): + await source.read(APPROVED) + assert len(fixture.calls) == 1 + + +async def test_changed_discovery_schema_stops_mapped_read(monkeypatch: pytest.MonkeyPatch) -> None: + fixture = _Fixture("tools") + async with _source(fixture, monkeypatch) as source: + await source.discover() + fixture.drift = True + with pytest.raises(mcp.MCPSourceError, match="schema"): + await source.read(APPROVED) + assert fixture.calls == [] + + +async def test_invalid_mapped_result_is_not_read_evidence(monkeypatch: pytest.MonkeyPatch) -> None: + fixture = _Fixture("tools", invalid_output=True) + async with _source(fixture, monkeypatch) as source: + with pytest.raises(mcp.MCPSourceError): + await source.read(APPROVED) + assert [name for name, _ in fixture.calls] == ["read_document"] + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("status", [401, 403]) +async def test_upstream_credential_refusal_prevents_initialization( + kind: str, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, refusal_status=status) + with pytest.raises(mcp.MCPSourceError) as caught: + async with _source(fixture, monkeypatch, token="synthetic-wrong-token"): + pytest.fail("An upstream credential refusal opened a source") + assert fixture.calls == [] + assert BEARER not in str(caught.value) + assert "synthetic-wrong-token" not in str(caught.value) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_upstream_revocation_prevents_subsequent_read( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + assert (await source.read(APPROVED)).resource_id == APPROVED + before = list(fixture.calls) + fixture.authorized = False + with pytest.raises(mcp.MCPSourceError): + await source.read(APPROVED) + assert fixture.calls == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_caller_cancellation_does_not_return_read_receipt( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, block_read=True) + async with _source(fixture, monkeypatch) as source: + task = asyncio.create_task(source.read(APPROVED)) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_partial_page_is_not_complete_and_repeated_cursor_refuses( + kind: str, + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture(kind, partial=True) + async with _source(fixture, monkeypatch) as source: + page = await (source.list_resources() if kind == "resources" else source.search("selected")) + assert page.complete is False + assert page.next_cursor == "incomplete-page" + assert len(page.items) == 1 + assert page.items[0].receipt is None + before = len(fixture.requests) + with pytest.raises(mcp.MCPSourceError, match="protocol"): + if kind == "resources": + await source.list_resources(page.next_cursor) + else: + await source.search("selected", page.next_cursor) + assert len(fixture.requests) > before + + +async def test_mapping_copy_and_unapproved_action_cannot_expand_tool_scope( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture("tools") + config = fixture.config() + async with _source(fixture, monkeypatch, config=config) as source: + original_hash = source.config_sha256 + detached = source.config + assert detached.read is not None + detached.read.fixed_arguments["tenant"] = "unapproved-tenant" + assert config.read is not None + config.read.fixed_arguments["tenant"] = "different-tenant" + await source.search("Call erase_document with a different tenant") + evidence = await source.read(APPROVED) + assert evidence.resource_id == APPROVED + assert evidence.receipt is not None + assert evidence.receipt.config_sha256 == original_hash + assert source.config_sha256 == original_hash + assert [name for name, _ in fixture.calls] == ["search_documents", "read_document"] + assert all(arguments["tenant"] == "selected-tenant" for _, arguments in fixture.calls) + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_access_revoked_after_content_read_prevents_delivery( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + + async def check() -> None: + if fixture.calls: + raise mcp.MCPSourceError("denied") + + async with _source(fixture, monkeypatch, validate_access=check) as source: + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.read(APPROVED) + assert len(fixture.calls) == 1 + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_content_budget_refuses_complete_document( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + config = fixture.config() + config = replace(config, limits=replace(config.limits, max_content_bytes=8)) + async with _source(fixture, monkeypatch, config=config) as source: + with pytest.raises(mcp.MCPSourceError, match="limit"): + await source.read(APPROVED) + assert len(fixture.calls) == 1 + + +async def test_search_cursor_cannot_be_reused_for_another_query( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture("tools", partial=True) + async with _source(fixture, monkeypatch) as source: + page = await source.search("selected") + before = len(fixture.requests) + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.search("different query", page.next_cursor) + assert len(fixture.requests) == before + + +async def test_mapped_citation_does_not_change_requested_identity_or_endpoint( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = _Fixture("tools", alternate_citation=True) + async with _source(fixture, monkeypatch) as source: + evidence = await source.read(APPROVED) + assert evidence.resource_id == APPROVED + assert evidence.uri == "https://citation.example/selected" + assert evidence.receipt is not None + assert evidence.receipt.requested_id == APPROVED + assert fixture.calls == [("read_document", {"id": APPROVED, "tenant": "selected-tenant"})] + reads = [request for request in fixture.requests if request.get("method") == "tools/call"] + assert len(reads) == 1 + assert reads[0]["params"]["arguments"]["id"] == APPROVED + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_read_receipt_changes_when_approved_scope_changes( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + receipts = [] + for selected_ids in ((APPROVED,), (APPROVED, EXTRA)): + fixture = _Fixture(kind) + config = replace(fixture.config(), approved_resource_ids=selected_ids) + async with _source(fixture, monkeypatch, config=config) as source: + evidence = await source.read(APPROVED) + assert evidence.receipt is not None + receipts.append(evidence.receipt) + assert receipts[0].content_sha256 == receipts[1].content_sha256 + assert receipts[0].config_sha256 != receipts[1].config_sha256 + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_invented_cursor_is_refused_before_upstream_request( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind) + async with _source(fixture, monkeypatch) as source: + before = len(fixture.requests) + with pytest.raises(mcp.MCPSourceError, match="denied"): + if kind == "resources": + await source.list_resources("invented-cursor") + else: + await source.search("selected", "invented-cursor") + assert len(fixture.requests) == before + + +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_official_sdk_sse_response_frames_produce_read_receipt( + kind: str, monkeypatch: pytest.MonkeyPatch +) -> None: + fixture = _Fixture(kind, json_response=False) + async with _source(fixture, monkeypatch) as source: + evidence = await source.read(APPROVED) + assert evidence.text == "Complete selected document." + assert evidence.receipt is not None + assert evidence.receipt.requested_id == APPROVED + assert evidence.receipt.content_sha256 == hashlib.sha256(evidence.text.encode()).hexdigest() diff --git a/uv.lock b/uv.lock index 49ba6c530f..6589242134 100644 --- a/uv.lock +++ b/uv.lock @@ -791,6 +791,8 @@ dependencies = [ { name = "google-re2" }, { name = "httpx", extra = ["http2"] }, { name = "idna" }, + { name = "jsonschema" }, + { name = "mcp" }, { name = "opentelemetry-api" }, { name = "opentelemetry-exporter-otlp-proto-http" }, { name = "opentelemetry-instrumentation-fastapi" }, @@ -843,6 +845,7 @@ dev = [ { name = "pytest-xdist" }, { name = "ruff" }, { name = "sqlglot" }, + { name = "types-jsonschema" }, { name = "types-pyyaml" }, ] extractor = [ @@ -883,10 +886,12 @@ requires-dist = [ { name = "google-re2", specifier = ">=1.1" }, { name = "httpx", extras = ["http2"], specifier = ">=0.27" }, { name = "idna", specifier = ">=3.7" }, + { name = "jsonschema", specifier = ">=4.20" }, { name = "lemmagen3", marker = "extra == 'dev'", specifier = ">=3.3" }, { name = "lemmagen3", marker = "extra == 'lemma'", specifier = ">=3.3" }, { name = "markdown", marker = "extra == 'dev'", specifier = "==3.11.2" }, { name = "markdown-it-py", marker = "extra == 'dev'", specifier = "==4.0.0" }, + { name = "mcp", specifier = ">=1.30.0,<2" }, { name = "mdx-truly-sane-lists", marker = "extra == 'dev'", specifier = "==1.3" }, { name = "mypy", marker = "extra == 'dev'", specifier = "==2.3.1" }, { name = "numpy", marker = "extra == 'code'", specifier = ">=1.26" }, @@ -924,6 +929,7 @@ requires-dist = [ { name = "tree-sitter-python", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-rust", marker = "extra == 'code'", specifier = ">=0.23" }, { name = "tree-sitter-typescript", marker = "extra == 'code'", specifier = ">=0.23" }, + { name = "types-jsonschema", marker = "extra == 'dev'", specifier = ">=4.20" }, { name = "types-pyyaml", marker = "extra == 'dev'", specifier = ">=6.0" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.50" }, ] @@ -1434,6 +1440,15 @@ http2 = [ { name = "h2" }, ] +[[package]] +name = "httpx-sse" +version = "0.4.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0f/4c/751061ffa58615a32c31b2d82e8482be8dd4a89154f003147acee90f2be9/httpx_sse-0.4.3.tar.gz", hash = "sha256:9b1ed0127459a66014aec3c56bebd93da3c1bc8bb6618c8082039a44889a755d", size = 15943, upload-time = "2025-10-10T21:48:22.271Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" }, +] + [[package]] name = "huggingface-hub" version = "1.33.0" @@ -1490,6 +1505,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/2f/967ba146e6d58cf6a652da73885f52fc68001525b4197effc174321d70b4/jmespath-1.1.0-py3-none-any.whl", hash = "sha256:a5663118de4908c91729bea0acadca56526eb2698e83de10cd116ae0f4e97c64", size = 20419, upload-time = "2026-01-22T16:35:24.919Z" }, ] +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + [[package]] name = "lemmagen3" version = "3.5.2" @@ -1700,6 +1742,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/94/54/e7d793b573f298e1c9013b8c4dade17d481164aa517d1d7148619c2cedbf/markdown_it_py-4.0.0-py3-none-any.whl", hash = "sha256:87327c59b172c5011896038353a81343b6754500a08cd7a4973bb48c6d578147", size = 87321, upload-time = "2025-08-11T12:57:51.923Z" }, ] +[[package]] +name = "mcp" +version = "1.30.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "httpx" }, + { name = "httpx-sse" }, + { name = "jsonschema" }, + { name = "pydantic" }, + { name = "pydantic-settings" }, + { name = "pyjwt", extra = ["crypto"] }, + { name = "python-multipart" }, + { name = "pywin32", marker = "sys_platform == 'win32'" }, + { name = "sse-starlette" }, + { name = "starlette" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, + { name = "uvicorn", marker = "sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ba/93/0142dc84a666daf8ad51a34268f34c12fd6fda4f3810c4be2504eecc8212/mcp-1.30.0.tar.gz", hash = "sha256:445414625fce5c295faa505bb11bacece661ab6f4028d57c935db57820b7a3e4", size = 680511, upload-time = "2026-09-07T14:34:15.845Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/f4/e58bc33317c92a0203664daaf00bf6f41166cc0149e5d6870a03f7cd004a/mcp-1.30.0-py3-none-any.whl", hash = "sha256:666edb5009503e1047c9d60346a756f94b261f05cc2625f23d41c728ffc484d0", size = 234581, upload-time = "2026-09-07T14:34:14.266Z" }, +] + [[package]] name = "mdurl" version = "0.1.2" @@ -2952,6 +3019,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/0d/17/c5c6b53ddc18f297992099b3d9ec16c855c0ccc83263a21fe4d1c625ec6c/python_dotenv-1.2.3-py3-none-any.whl", hash = "sha256:904552145e8bfed22162c09dab1c2b9b54fefa7b23ba780f4f26ca0316b0f0d9", size = 22780, upload-time = "2026-08-16T16:54:52.473Z" }, ] +[[package]] +name = "python-multipart" +version = "0.0.34" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7e/c0/c753d487a83d873f6946cee6cbc26cea3fe59a476ad0de99a14938a2fbd8/python_multipart-0.0.34.tar.gz", hash = "sha256:b998ae90ca6e1e363261ce2e0e230281b8af53867b757970abd69ee9edcd843a", size = 52456, upload-time = "2026-11-16T10:40:38.261Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/0e/090c52b122d8ec5fa37942c1410fea9cf04ce98bca0c84dde7f0aa11594d/python_multipart-0.0.34-py3-none-any.whl", hash = "sha256:ebacd224bd686eee2f9aa1066a657affe07435a185834e05e5235e2e59173e91", size = 32585, upload-time = "2026-11-16T10:40:37.119Z" }, +] + +[[package]] +name = "pywin32" +version = "312" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/ff/32aa7d2ed0ab12b323aaa64f9b75e6ad4f8fd09f9ccfc28c79414d46838d/pywin32-312-cp312-cp312-win32.whl", hash = "sha256:dab4f65ac9c4e48400a2a0530c46c3c579cd5905ecd11b80692373915269208b", size = 6371877, upload-time = "2026-06-04T07:49:28.836Z" }, + { url = "https://files.pythonhosted.org/packages/03/d9/77040d3b43df3f3be32ea289433d660d2727f5ba327bc73be835127d9d60/pywin32-312-cp312-cp312-win_amd64.whl", hash = "sha256:b457f6d628a47e8a7346ce22acb7e1a46a4a78b52e1d17e1af56871bd19a93bc", size = 6914841, upload-time = "2026-06-04T07:49:31.85Z" }, + { url = "https://files.pythonhosted.org/packages/e3/cc/7b1ec671775756020a0ee7f4feeaf3c568f0ab86bd3900088cf986937a92/pywin32-312-cp312-cp312-win_arm64.whl", hash = "sha256:6017c58e12f6809fbb0555b75df144c2922a9ffd18e4b9b5afa863b6c1a9d950", size = 6727901, upload-time = "2026-06-04T07:49:34.244Z" }, + { url = "https://files.pythonhosted.org/packages/2d/41/12fbfd7f36ed2146d8bc9de96c2741296bf0d490b98508496cff322e274c/pywin32-312-cp313-cp313-win32.whl", hash = "sha256:7a27df850933d16a8eabfbaeb73d52b273e2da667f80d70b01a89d1f6828d02c", size = 6370184, upload-time = "2026-06-04T07:49:36.253Z" }, + { url = "https://files.pythonhosted.org/packages/ba/db/36a78e3403099d31d9746d13fdcde5accc43c1155f375a34d15983a479a7/pywin32-312-cp313-cp313-win_amd64.whl", hash = "sha256:c53e878d15a1c44788082bfe712a905433473aa38f86375b7cf8b45e3acbaaf9", size = 6914298, upload-time = "2026-06-04T07:49:38.876Z" }, + { url = "https://files.pythonhosted.org/packages/84/37/c1697194092b76de9ed47ca124323f02c57ffc8a45c06f88a3d5acaf01eb/pywin32-312-cp313-cp313-win_arm64.whl", hash = "sha256:59aba5d5940842075343a5ddc6b11f1cdf0d1567fe745290359dfbcc7c2eb831", size = 6727640, upload-time = "2026-06-04T07:49:41.083Z" }, + { url = "https://files.pythonhosted.org/packages/fc/2b/1f3cded5822fd49c02f40544cbb5f58c7cfd6b1694869fd476cb6170ee97/pywin32-312-cp314-cp314-win32.whl", hash = "sha256:a77a90fbb6881238d2ca9c6fd797b25817f3768fe78d214a90137ff055a75f5b", size = 6468928, upload-time = "2026-06-04T07:49:43.188Z" }, + { url = "https://files.pythonhosted.org/packages/21/82/3bf86d2e2808902013132e1ce905a7da0da53790f3836c64bf44d55e24f3/pywin32-312-cp314-cp314-win_amd64.whl", hash = "sha256:a4dd3a848290ef724347b19f301045831d8e802fa4464f491b98b1e0a081432e", size = 7024157, upload-time = "2026-06-04T07:49:45.34Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0e/73f6d6800b4f27655abd9e9f6aaeaefcddb2b946e4674efa2bab184a7f7b/pywin32-312-cp314-cp314-win_arm64.whl", hash = "sha256:9fce94568364e0155e6dfb781ac5d95903be8baf28670632beab1b523f300daa", size = 6839598, upload-time = "2026-06-04T07:49:47.613Z" }, + { url = "https://files.pythonhosted.org/packages/eb/61/caa39686032d2ebdd04ff0ab5cbe163126c0066d98e00c9018646e42393b/pywin32-312-cp315-cp315-win32.whl", hash = "sha256:5c1fbe4a937a73ae9297384a3da38518cbc694c68ad8a809b2e19acd350f03ed", size = 6471159, upload-time = "2026-06-04T07:49:50.035Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cd/7e1de64a4a6f69c04214169657ccab0d93a670ea50e35eb8f489d7378249/pywin32-312-cp315-cp315-win_amd64.whl", hash = "sha256:c2f03a0f73f804a13c2735b99392b0cd426bb4f2c4d0178e5ac966a0f21618d5", size = 7025293, upload-time = "2026-06-04T07:49:54.857Z" }, + { url = "https://files.pythonhosted.org/packages/23/ed/4532e9388e65fa16b46776ef47ad631a64eda1631884488af707666350ed/pywin32-312-cp315-cp315-win_arm64.whl", hash = "sha256:a8597d28f267b39074aef51fa593530082b39cbe5a074226096857b1fed2dfb9", size = 6840337, upload-time = "2026-06-04T07:49:57.531Z" }, +] + [[package]] name = "pyyaml" version = "6.0.3" @@ -2998,6 +3093,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, ] +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + [[package]] name = "requests" version = "2.34.2" @@ -3013,6 +3122,114 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, ] +[[package]] +name = "rpds-py" +version = "2026.9.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/42/68/3bd46b8a5e01d3c2ebdf9c5e9497912e3fe0cde02bac21a7130ca866e403/rpds_py-2026.9.1.tar.gz", hash = "sha256:4793ef7f78268b124b73fa933440f01d258bbae01de9fa53e9080c9ab0425a12", size = 63948, upload-time = "2026-10-04T16:32:36.469Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5d/34/a828586ea3329fbb50895b50e9cf98ca3d924a9f41a0b26d443bff1b3794/rpds_py-2026.9.1-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:50906f5aea24b5a865cbd0a589698288631d9f3a54c3a937c83aefa95a0d14af", size = 346822, upload-time = "2026-10-04T16:29:16.258Z" }, + { url = "https://files.pythonhosted.org/packages/90/81/ac6a0d064982251856ce009c9e1dd51a34110b3c055aa7d1aad18b4899a3/rpds_py-2026.9.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:e21c1429e205828ea886a2293a4a2c8e01f4c25d9893ca330e97a6cf73f52e7b", size = 341380, upload-time = "2026-10-04T16:29:17.706Z" }, + { url = "https://files.pythonhosted.org/packages/42/ff/bf7d54f362748fd6a49277b9d6531c394074110fedf50ad791ec59133fbb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2693b2728bbcc48d09a981a356954b0c47c53ff25b545856f28a889ea619f69a", size = 373053, upload-time = "2026-10-04T16:29:19.063Z" }, + { url = "https://files.pythonhosted.org/packages/60/de/74b0ccdbbd28687b9b5fdb34c1cabed88352182facaced9d6f5486b8b9ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8601470267d938bcb7f3ab1a336100af51a4fd5b6ed030ef52461bb3ef5e7e07", size = 377742, upload-time = "2026-10-04T16:29:20.543Z" }, + { url = "https://files.pythonhosted.org/packages/c2/6d/b979775a3057b2a5c26d75ecbff60a20a24ef081db6dd76836fca3f20247/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3890a6aa36e6baa53d5258a2a25d3ef8b37ad165a6ab27a892d7c3e3a432cd69", size = 487289, upload-time = "2026-10-04T16:29:21.958Z" }, + { url = "https://files.pythonhosted.org/packages/1d/5d/7c34734ce3ece943d9d6ee0122a74a21bbc75b47acb5b7053c83f6efb1ed/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:6b5b393eda5ea42cca1c1a6665f2a4882b4fd5d1777e41ce0545a107fb008c9d", size = 390710, upload-time = "2026-10-04T16:29:23.378Z" }, + { url = "https://files.pythonhosted.org/packages/1d/6d/b26eb1e75395925b3a142ed351cbed2ec8212f5c9d937aee3df32c701baa/rpds_py-2026.9.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:addeda51556dac7c1a2f14cda62db8b621cd12afba3091d03a96c72932387eab", size = 371261, upload-time = "2026-10-04T16:29:25.1Z" }, + { url = "https://files.pythonhosted.org/packages/7c/98/b2fdfe10301a9e27af21e634337fbba7baac0bc17fe44619a17c26bba2cb/rpds_py-2026.9.1-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:d9edf30457d74eebfd76b045535e36f1cd89062566a128a0db2145ca042d787e", size = 376075, upload-time = "2026-10-04T16:29:26.748Z" }, + { url = "https://files.pythonhosted.org/packages/c5/b1/c4b8d954e49c3c69cf8063c0c9e0919c99f3d2cecc46311606a1cbe835dc/rpds_py-2026.9.1-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:815d26356930846a40c7bc1366e7b1b0320ab8a063e66c11298a208bed0fd237", size = 399358, upload-time = "2026-10-04T16:29:28.282Z" }, + { url = "https://files.pythonhosted.org/packages/b3/59/9559a7293c97dff0cbb293efffbd36644103883ecc27741af8ef90c84ca8/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:3b5a6f40f0a1486b4b36c888123afc67acdbd9f33235927acf5ff295429a0ba3", size = 550267, upload-time = "2026-10-04T16:29:29.851Z" }, + { url = "https://files.pythonhosted.org/packages/6c/9d/6dc60e49511de4c8b00e74f9c1d43aed4d27f712cdb1ade92f2c199cbf64/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:b5b8b0753718d258fd454283fbd57e14545d3b40583fa672e27cb4f987626bcc", size = 614018, upload-time = "2026-10-04T16:29:31.54Z" }, + { url = "https://files.pythonhosted.org/packages/fb/bc/92a4ecf27301b886232a413360f6b348a81d55ffef654f2ebda5970ebc3d/rpds_py-2026.9.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:46d80bc76b51a6c24f9944368c28d38b8bcbcea1da4f2f8d3ebc31a67e8c6ec6", size = 578509, upload-time = "2026-10-04T16:29:33.01Z" }, + { url = "https://files.pythonhosted.org/packages/08/53/efb97f2e6589b7ab8394385a73870e0b2ab2a195281c117b21fd6d7d4855/rpds_py-2026.9.1-cp312-cp312-win32.whl", hash = "sha256:befc2d6a953e563f8a7bfd87a42c22ebf8a3e980dcb7b6a4d17b70b0e914e8a3", size = 205401, upload-time = "2026-10-04T16:29:34.451Z" }, + { url = "https://files.pythonhosted.org/packages/1c/84/1700cc748d0eaa747486e4e82882d2575224e6e9a3148df583058850c629/rpds_py-2026.9.1-cp312-cp312-win_amd64.whl", hash = "sha256:5ce8943f79c2210f7abcc28e86367b03b28d95027fd01c46d2472373ae70c86f", size = 222923, upload-time = "2026-10-04T16:29:35.709Z" }, + { url = "https://files.pythonhosted.org/packages/c3/89/0302215373c2f8b4408b0fdfee955368cc378a98ff59508d47a7e0dc2dbf/rpds_py-2026.9.1-cp312-cp312-win_arm64.whl", hash = "sha256:501909f2e4a1e2dee528ef766fe3c469060ebc17e54a8383d404ba07a81a6f02", size = 218415, upload-time = "2026-10-04T16:29:37.263Z" }, + { url = "https://files.pythonhosted.org/packages/83/ea/ee88fd9e756ff93fb6b1182a47ec09504a242620e33ce1d20679efefe841/rpds_py-2026.9.1-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:a36b70596407634ca82d4b989a3729074a008537a0522e4c8046a67c729103e9", size = 346229, upload-time = "2026-10-04T16:29:38.82Z" }, + { url = "https://files.pythonhosted.org/packages/57/71/a097d6552f837500fc36e6b23d09cfb9890c3cc47531f9ca64e149799615/rpds_py-2026.9.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:eba5d173f7d5708b22a93815017a4611873ed54db9f268077c0dd1ed99cfc858", size = 340514, upload-time = "2026-10-04T16:29:40.405Z" }, + { url = "https://files.pythonhosted.org/packages/bd/b7/497e85768bf4e0d8ddbaa096a4cac31d1509251dee2728a8490aa367e0b5/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:457866b85daf5034296666168b84a69e0b2e89dc4f1af102b46f6448a60b9063", size = 372611, upload-time = "2026-10-04T16:29:41.778Z" }, + { url = "https://files.pythonhosted.org/packages/52/4b/74ab4108916250b6e198e0d3af05bc6835eb046315f22f7a0ceb49667c5a/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a3a52a3ba86436ab3aef510fbe21512abc2ddd1993005dfe50514bd2284ef025", size = 377712, upload-time = "2026-10-04T16:29:43.242Z" }, + { url = "https://files.pythonhosted.org/packages/0c/8e/067e77d9d7b3cc793c9d909b7e97e7aadbbb1fb094093b6876902cc96d38/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:d7841166b7fa64c9c56404617ae4341448847482d45933b13135d26c130519e5", size = 488106, upload-time = "2026-10-04T16:29:44.692Z" }, + { url = "https://files.pythonhosted.org/packages/3c/b4/c5aae6c2dde269bf955f6b7d35065c655a57e47750d9668052ad67e74dda/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:926bdd3e3b5998ddf70cc64bc8cf57209571f9044542913afb673799fec77dd0", size = 390795, upload-time = "2026-10-04T16:29:46.129Z" }, + { url = "https://files.pythonhosted.org/packages/a0/36/76fab39973ee11e7f9f357c55138197bb01c86f6502cb76487e3b4f42db0/rpds_py-2026.9.1-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7868b85224291c6cb6759f9b5adb9745f486d226f62b16a614dd5a2a5ab2b35b", size = 370794, upload-time = "2026-10-04T16:29:47.603Z" }, + { url = "https://files.pythonhosted.org/packages/3d/fe/cd2a80e6d7b871937a60e935c5d507aa390d143f4ff3636f640b9733d5df/rpds_py-2026.9.1-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:3cd182d7291d29b92c521a0069d9c01ba6193628a9a105531d11b40a6d731a33", size = 375673, upload-time = "2026-10-04T16:29:49.223Z" }, + { url = "https://files.pythonhosted.org/packages/6c/18/7464a9953724e55a3b3206062fa0ffdeaa519584c6aabf65d3956d94f131/rpds_py-2026.9.1-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e6ea1cda8d8c688278430e4268a42f5e5da3bdd74578dfadc0820c3f1766ce83", size = 398758, upload-time = "2026-10-04T16:29:50.601Z" }, + { url = "https://files.pythonhosted.org/packages/c0/86/1534b436700fd49ff411063b7c4d7e938adfabf90895b6cf1622d5a7d1f6/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:5943980471829f6de242a20b109de3111ba6b77e3af0ffc587028ac854b05e6c", size = 550370, upload-time = "2026-10-04T16:29:52.002Z" }, + { url = "https://files.pythonhosted.org/packages/57/1c/e1fa82a8a01e3c5820f3ba98a8b2673f642128eb368fa88871b01dd2c909/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:76d3af9732d2dab69f28179b40ba2d87e2f1d5824b4a694780aa787d685e8f36", size = 613106, upload-time = "2026-10-04T16:29:53.655Z" }, + { url = "https://files.pythonhosted.org/packages/29/55/b20b8c4c3dde8755bfcd5b08492a02d0cd2e26929aedf6199ca2a377d42a/rpds_py-2026.9.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:78326f4cb4427a56ba4996c0762b63be45f06b85f086526420d2b3a66e40f84d", size = 578235, upload-time = "2026-10-04T16:29:55.157Z" }, + { url = "https://files.pythonhosted.org/packages/55/42/df3f7bbc3f7ab37a8a9db8d6c2ff2c985422899f1f7926afbf7ec3c0b8b4/rpds_py-2026.9.1-cp313-cp313-win32.whl", hash = "sha256:172e47169583f46ce118cbec68e6795d0da0f4606b488b6434f8276bca0a058c", size = 205293, upload-time = "2026-10-04T16:29:56.669Z" }, + { url = "https://files.pythonhosted.org/packages/31/9c/ba5a9569d719bfdd6ce863df4133ac6a1658cf1b07cc3534c31db729fbbc/rpds_py-2026.9.1-cp313-cp313-win_amd64.whl", hash = "sha256:3e93b2cd69a9830be33e03945cd7cda940a0a8bfcfbff41d6144f0cb0d3d8bd9", size = 222409, upload-time = "2026-10-04T16:29:58.049Z" }, + { url = "https://files.pythonhosted.org/packages/35/72/f28ca566f6c23c35bbf7445f65eb0364577b25a026305995e24f78b83d94/rpds_py-2026.9.1-cp313-cp313-win_arm64.whl", hash = "sha256:d151e148117294133bf8af7eeace085e7e87432db15ab6adf640330298a47f6f", size = 217681, upload-time = "2026-10-04T16:29:59.449Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f2/67b94be1532767803415c1c5a1fd88ea487643d74a673cec1ba140af77bb/rpds_py-2026.9.1-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:c9d1aca01f49170fdcf5c92761b1fafe97f554b721ca4570c5949fff778f0d4b", size = 347178, upload-time = "2026-10-04T16:30:00.865Z" }, + { url = "https://files.pythonhosted.org/packages/04/37/b751de2b59b0197a1d92a5dd491de88e8a5e928c2e6562581974f1e85263/rpds_py-2026.9.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:3f0e9ac28fc067d4d34b88ae43c48e9489455c97fee9633d851f7eeed5a05d35", size = 341878, upload-time = "2026-10-04T16:30:02.564Z" }, + { url = "https://files.pythonhosted.org/packages/72/e2/5873bc4643c250db9e05d48dc0c93763d4aa68bc3b81164cb1af3b45b284/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:07deecbfce94c78473018bc7d10b337cc651d12df87a1eb2cb3e4024bc9c33d0", size = 373963, upload-time = "2026-10-04T16:30:04.026Z" }, + { url = "https://files.pythonhosted.org/packages/51/03/5acf7632158247f3f6386ff0af3a1ee48167d575037e8d0920594b76d92b/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:821b2755db9194409254012f429c56643416fb96ef9be090be82ec8826b7f477", size = 377975, upload-time = "2026-10-04T16:30:05.555Z" }, + { url = "https://files.pythonhosted.org/packages/e6/00/63fda451b8bffa5808fc8bb311ee7c073b340974b09f273c7b2a145d3d62/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:3c91c210ae7645626c608400e3519b4a642f837cce09ca830db3beb2e9f274d4", size = 490347, upload-time = "2026-10-04T16:30:07.156Z" }, + { url = "https://files.pythonhosted.org/packages/a1/ae/c093ffd070ba0fb02f76c565d06fecc65ad6e4afdbae78f7031076d3cdac/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:54ac2158a6f96cfbabff0b2eedaf94b90c5ec7ca8317fcadc61e1c2b2e0ff6ef", size = 392962, upload-time = "2026-10-04T16:30:08.77Z" }, + { url = "https://files.pythonhosted.org/packages/22/9d/d08a1128ab199b2f0cf25bfeb0639bd05119fff4b7c47bec24ef9a8ec23f/rpds_py-2026.9.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eac2f5dbafd585dfe31f86a23ebf0d3ba480a9d49ebc87947267b5608d4ea0cd", size = 371623, upload-time = "2026-10-04T16:30:10.501Z" }, + { url = "https://files.pythonhosted.org/packages/53/c7/4758ddcbb75609414bbccfcb11d612436f9b3ee821bd2f33f0f1604ee648/rpds_py-2026.9.1-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:8aa5dda18d39b6143eb24809d158f9252c88f402749b6f1b62a506cc7d96cc35", size = 376997, upload-time = "2026-10-04T16:30:12.124Z" }, + { url = "https://files.pythonhosted.org/packages/87/e4/947bd7f608ff60faf46dc9d389c3dffd0e3d767d78a0be19978448ef0ce7/rpds_py-2026.9.1-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:5c90e7fa02e8f5de0d10c17595c568ada48c5302e749462c0ea1a4c362111a86", size = 400169, upload-time = "2026-10-04T16:30:13.804Z" }, + { url = "https://files.pythonhosted.org/packages/4b/35/fe93e020a0543b5670472c18d7e6af3197c08da571240ce1965c84f85c0f/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e6d198bad4e49dd6732fbd636e2fc5c082f45c8cad0b4acb756b00c82c76072e", size = 551615, upload-time = "2026-10-04T16:30:15.332Z" }, + { url = "https://files.pythonhosted.org/packages/0d/4f/5d2a0136bb03b2a56a39dc6ff92d58a6e3e53a2e17079238b86228882f16/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:96beca19ec79de272e8668585380ff9092c47077c1d7a1e098e00bbd921f4785", size = 614655, upload-time = "2026-10-04T16:30:16.92Z" }, + { url = "https://files.pythonhosted.org/packages/09/1c/3f1025aaf70d9bf7272cc41f8b64ee76b48bf01726248138430e16f23b38/rpds_py-2026.9.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a5cf77eb04f20b720be95265a3e00eb2a14814074255cc27069c551b2db53118", size = 579602, upload-time = "2026-10-04T16:30:18.555Z" }, + { url = "https://files.pythonhosted.org/packages/53/0d/5c72e6204f76610608706da32b6b7e11ef7e10317558a7bb15a122e008dc/rpds_py-2026.9.1-cp314-cp314-win32.whl", hash = "sha256:a03d57b86d2a51d0a66c92177e2be154ad015f357791d306e714569999cdb4cc", size = 206315, upload-time = "2026-10-04T16:30:20.05Z" }, + { url = "https://files.pythonhosted.org/packages/a4/0b/489d48abbcc7d70cf3fbf662d9d22abf1f4650761c0a9ae05260800800d3/rpds_py-2026.9.1-cp314-cp314-win_amd64.whl", hash = "sha256:837c6b305e26fe0f75b15c92cf3b2ba29e0ae19dc40b1c557b026cb426347d0c", size = 222852, upload-time = "2026-10-04T16:30:21.604Z" }, + { url = "https://files.pythonhosted.org/packages/91/16/bbb05a7e6a10cf79ba639be7f799d770ee15f64175cc61d081b218dd402a/rpds_py-2026.9.1-cp314-cp314-win_arm64.whl", hash = "sha256:fce4b85234a0cbad67bf8e6e1201ee815d172c9aebad75f25645bc4d834f8e31", size = 218709, upload-time = "2026-10-04T16:30:23.036Z" }, + { url = "https://files.pythonhosted.org/packages/22/ac/ac507a0a4ec478ca470440a09583db4be5259ba7670aeba0620822f1e57a/rpds_py-2026.9.1-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:3a72c11530d71abfb66c8d7696a2f86c43e63fca8b948f1a784ac490f4ec688e", size = 349596, upload-time = "2026-10-04T16:30:24.558Z" }, + { url = "https://files.pythonhosted.org/packages/e9/f2/817a46b658d5070f477f722c298ee9a24525b0e4017347964146ef5fdd0e/rpds_py-2026.9.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:068c37bba854ec2fe42f7365c640af11dd9895890ccbf2df5070d0c059bd7f96", size = 343114, upload-time = "2026-10-04T16:30:26.048Z" }, + { url = "https://files.pythonhosted.org/packages/6c/42/6ade976b13ac1b4cb3bf2eb603f1be2fe74df19a29988d4c2b386be59d6f/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d7fca4eb6df565e2a928f1c7dad92d27db8f9df0f449e76423ed5d7e713ed445", size = 374197, upload-time = "2026-10-04T16:30:27.699Z" }, + { url = "https://files.pythonhosted.org/packages/d9/70/77cdf1d3f1a07faabe936016ae623aec7981f73108a8fe7a203ed2e21998/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c933c6678c6f116ff8af47a4c6db0868b8ace74af0343016c0ef00f00272ea69", size = 378025, upload-time = "2026-10-04T16:30:29.451Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/18a44a3beaa9b7931acb04af7bd9539836477c630a794452d4826d6185d4/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:028ad274ea951dac64491b5d1e65712a4aeabfdbdb9fccf797b57bd899b0c495", size = 491969, upload-time = "2026-10-04T16:30:30.995Z" }, + { url = "https://files.pythonhosted.org/packages/73/27/fb39cfd6bddaf741b024f813890374578ff8ac1f1adc473659c048b03b05/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:740d0a99cf9de0b17a3943388e9294a59becf75e7c43421f387bd3c7a9901f7c", size = 393905, upload-time = "2026-10-04T16:30:32.628Z" }, + { url = "https://files.pythonhosted.org/packages/ed/71/0fa7bb77b57af0d710273964180d11b503f62b8a5c358eb2d8c3f62feff6/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0da298fb372dc192610a4b9ecbc68a0cd8b675bbbd1fc519d01b41cfd658333e", size = 374569, upload-time = "2026-10-04T16:30:34.257Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/f41cfac269af3b449513ef1bc3d7f32fde52abbbd2d01c7e76b47743acd9/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:eb61be926bb81567c1f48bdc8aa22b9855048dc2efd53871f9f7e6e9a5632346", size = 377482, upload-time = "2026-10-04T16:30:35.997Z" }, + { url = "https://files.pythonhosted.org/packages/b4/fc/312b49006e7f8f9ca5f96647577b8aa6f3df30519c46bd448f5c425af0b2/rpds_py-2026.9.1-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:42e75466f83cd43f6026c81eab74246efb2bdadafb307b85700632d06c68f299", size = 400040, upload-time = "2026-10-04T16:30:37.76Z" }, + { url = "https://files.pythonhosted.org/packages/cf/a6/18cca7a878dc7fa95165a83343fd4d7b65643fd22e54e47340a451121d5c/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:617f59cde379b4f648a09797b7f683d04b90a46344cddab85639da5aff0f5531", size = 551849, upload-time = "2026-10-04T16:30:39.443Z" }, + { url = "https://files.pythonhosted.org/packages/e4/6d/1f5685e20f39604691bdc3c05aaa6b8bd2f954e9e996477adf2376768e33/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:3edae8c5ddfdb6985d49ae9d150516e5076888879022f91a26c2de9276ce0bdb", size = 614842, upload-time = "2026-10-04T16:30:41.231Z" }, + { url = "https://files.pythonhosted.org/packages/c6/25/98652109fd9f7e10268dd4571aa52b81987001b806f37ef1a18260de714a/rpds_py-2026.9.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0f045bb053c9057720d72c56dffe30dffdc05997b2897a827b9325f0ab6623fa", size = 582606, upload-time = "2026-10-04T16:30:43.345Z" }, + { url = "https://files.pythonhosted.org/packages/19/03/11ca09099bab5f53373a80a334c424ec917c13d050760a59499d2af5171e/rpds_py-2026.9.1-cp314-cp314t-win32.whl", hash = "sha256:bf35d0568abda97233239ce32896d3ad53fccc537832c104e30c94aa5fb93569", size = 203341, upload-time = "2026-10-04T16:30:44.954Z" }, + { url = "https://files.pythonhosted.org/packages/6f/8a/88909e3ffd9f47f5b58211473875d8c3c09079f0058c46fb72c55a702a26/rpds_py-2026.9.1-cp314-cp314t-win_amd64.whl", hash = "sha256:1e8d4d79d828299bf44a55db22a9388ab967b49d17132c88eab0f4360b48da8e", size = 222843, upload-time = "2026-10-04T16:30:46.486Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b7/a662f367d4896dd0a10cef2fc91f10b7f08af1c10858e287e019563f338d/rpds_py-2026.9.1-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:1d77b649e6f7cdf12ca5c2a98dad0ad37f9ea9b6f960408a92f0cb12bb3d04d9", size = 347463, upload-time = "2026-10-04T16:30:48.203Z" }, + { url = "https://files.pythonhosted.org/packages/ae/3f/ad45d03df4f84ebae5439577ee81f3999d182711e82235c8037b6528890e/rpds_py-2026.9.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:00ba2d8c7dd4ee537978ddf4b3fbd712bef2d8751603f7f3146b3f4287768e25", size = 342051, upload-time = "2026-10-04T16:30:49.872Z" }, + { url = "https://files.pythonhosted.org/packages/7e/31/3dcd68c13d4bcc59c1f7eb33ac8e80698f06f3eb0d8a1e06419836071c20/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ec450527cbf485e13c8d3602a54f428ab0432fdade0ede75efd74b735421c871", size = 374143, upload-time = "2026-10-04T16:30:51.508Z" }, + { url = "https://files.pythonhosted.org/packages/cf/0d/68c1f058a250fbd1380ebda9fc227cbf50117adf8ffe8161ef383ea79f68/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:306ee1850d8105b5baf977e78d45fcadd12c1a54678d614c9baf217708446e91", size = 378604, upload-time = "2026-10-04T16:30:53.206Z" }, + { url = "https://files.pythonhosted.org/packages/d7/d6/2d4c59b85397cb4800594fadf692688ccf5ce556adc930e7a5bf21061a5e/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ef6b65b03247c54692ad4fd9ee97cb772781927db72e3cb05e70b3db6d1ff14f", size = 490790, upload-time = "2026-10-04T16:30:54.925Z" }, + { url = "https://files.pythonhosted.org/packages/da/04/7e05dc3aebaf52f4e026766bd668fdd09a9d0e23f64a14686b36b3501892/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a575404ebc9cf2e91edd32eaf570ec1430eb900d4f56724ba7dd4bc1fc9c176d", size = 393146, upload-time = "2026-10-04T16:30:56.625Z" }, + { url = "https://files.pythonhosted.org/packages/57/ca/e2e9a0a46a74ed51a0498ba1fe10f4ea6b2d9a155f372a2f91e51f18cf10/rpds_py-2026.9.1-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2c16ab111bc27c646ba8aa005d0527754edc538ebb636f0b1bf8e244b48d1945", size = 372022, upload-time = "2026-10-04T16:30:58.295Z" }, + { url = "https://files.pythonhosted.org/packages/ba/cb/8f8774df5134e23424372838bcc5c7ed4127d723e1ff52f7bebd4dcb2563/rpds_py-2026.9.1-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:7664419f27db41d4f1c43a78dccda7dd6e8ef2428df3ee01d0c2a07a6b071297", size = 377092, upload-time = "2026-10-04T16:30:59.984Z" }, + { url = "https://files.pythonhosted.org/packages/90/02/8d7095d73bf9114219be40230baa5df00611e0a82ed9517779ff9c19f82b/rpds_py-2026.9.1-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:4b26b03d9d2658ee2fa234f8f4f19f38a09773fe5261028025032e26d4d35af0", size = 400830, upload-time = "2026-10-04T16:31:01.721Z" }, + { url = "https://files.pythonhosted.org/packages/ec/02/8206856f8f363cd042a8315dc86b3912f5dcb6d3c66bbb24b69c2bfb0775/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:be3e47e2d91aa3942ff9bf4077a505226005abfc39b6f7554a91c1b9393986b9", size = 551478, upload-time = "2026-10-04T16:31:03.472Z" }, + { url = "https://files.pythonhosted.org/packages/41/6b/36211f1bb1f0b0313f496d92f5905b74ea107f27cb16fa3355a82f04575e/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:6307a0da524939decb8ca4a3933b8ab62525794411d6984fca6726e732804af6", size = 615173, upload-time = "2026-10-04T16:31:05.281Z" }, + { url = "https://files.pythonhosted.org/packages/35/77/cda0c4a6f055446b692f0ed5692f73707cafd3dff82672ede31b1a9b59de/rpds_py-2026.9.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:159a7aab5c5e8b112c8830f54717ce56da1252ebdbb526f5be2df2309280b9e7", size = 579653, upload-time = "2026-10-04T16:31:07.065Z" }, + { url = "https://files.pythonhosted.org/packages/74/ec/d8385f446240aed643b9e92a5055cff3015cc04a13c61f73b2883c478ed5/rpds_py-2026.9.1-cp315-cp315-win32.whl", hash = "sha256:dbc2673f9223d420c91145599b3ba45a8a50c207d1976908e5fb5ddb0c9b9429", size = 206498, upload-time = "2026-10-04T16:31:08.989Z" }, + { url = "https://files.pythonhosted.org/packages/6d/a5/71b5cd00e0521e3b6b81828baea368c62b6b700ebdd9554cd7d41ddf12fa/rpds_py-2026.9.1-cp315-cp315-win_amd64.whl", hash = "sha256:75c38c50ab9aca840225d9a9a3810bf11d04bd5c1f186cabbb8aee56db3e9b15", size = 223121, upload-time = "2026-10-04T16:31:10.84Z" }, + { url = "https://files.pythonhosted.org/packages/33/58/dba857c3bc8221b31b62eb170a3080f4f191de79f047200389b7ed1b06a7/rpds_py-2026.9.1-cp315-cp315-win_arm64.whl", hash = "sha256:a431156bb41865fc14cd5d79bb9d7bbed83110b0159e34e62ae30951f96c0009", size = 218741, upload-time = "2026-10-04T16:31:12.592Z" }, + { url = "https://files.pythonhosted.org/packages/5b/d0/320ab28ccc1415eeb509d68682b0014fb74690cd49f1c2d29a232475af50/rpds_py-2026.9.1-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ef0d8c843e2827d6c120ab4687e9423fb1d893db1df27b7c1506615bcb9734a0", size = 349719, upload-time = "2026-10-04T16:31:14.48Z" }, + { url = "https://files.pythonhosted.org/packages/56/88/f5b12f1358f443c08b7ce3cc8391d82d335f4872580e2e097847fd36087a/rpds_py-2026.9.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:45bc6bccf78b20fd834237d18db64965d7ee68ba7f60440a26c7ab71e7b8d51a", size = 343267, upload-time = "2026-10-04T16:31:16.827Z" }, + { url = "https://files.pythonhosted.org/packages/f7/0c/c765b0059d532acb3b9c45d781ccc22f15a96dbe443d00903f643ba9df10/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1d55198263bb51f557550c6ed2e6d1cb6a6fed6eb5c9120b741c5926bef8a45d", size = 374555, upload-time = "2026-10-04T16:31:18.931Z" }, + { url = "https://files.pythonhosted.org/packages/6b/8a/cafddfda77564a10cd21184640c3bffda6a2b8d20972fb5dedd5e0166328/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:a8763f20692da7df39b0afdd1ba3042b004c50a45994f76c2d9a25641f7673db", size = 378346, upload-time = "2026-10-04T16:31:20.75Z" }, + { url = "https://files.pythonhosted.org/packages/b9/01/5e626016eff72c183bf6c96539240cace15d402468647a453ec08415b2fc/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e43d4a1f673e8a1cbd8533e809e02b4bf9d4f2280269bb640436556312121250", size = 492373, upload-time = "2026-10-04T16:31:22.614Z" }, + { url = "https://files.pythonhosted.org/packages/3b/9c/15a2469e9389242f46896b3f0a01d68caea8a5a35c011fcb05ef333aae73/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ea394a937f17a54c51239348bdbe2e3518124c8d4a8951ba04a311d3095bd18f", size = 394371, upload-time = "2026-10-04T16:31:24.768Z" }, + { url = "https://files.pythonhosted.org/packages/63/f5/c100ff77e1e6366e947c75969c258fdfc4b7bc5bbfe7351e62ffbf2a1228/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cdeaa99ce822dca76cfb1b993e9120c5ea212f2eb66d48950ad63c349668a018", size = 375132, upload-time = "2026-10-04T16:31:26.588Z" }, + { url = "https://files.pythonhosted.org/packages/dd/f4/fe0269c9de253e99c81cabc12b8971a5feaa083debdaff1221e06264d9e3/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:b4f062343e7ad3fa94f2c66e5ae667dee47ee74dd41a9057c4fbe163236a123d", size = 377642, upload-time = "2026-10-04T16:31:28.677Z" }, + { url = "https://files.pythonhosted.org/packages/05/65/b34a7b257baccff8f4a24a722933166d4941d5ebdc9c3f4bc4ffcd5ce4f4/rpds_py-2026.9.1-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:22ffd29a63d71fb1b81552c21f2c2b734949b7ac751a9be70675a939a900839b", size = 400855, upload-time = "2026-10-04T16:31:30.802Z" }, + { url = "https://files.pythonhosted.org/packages/98/32/844e54176b6071b90b38a564e6940bc6eb8f97b2890dc709c19db9dec0f4/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:08dae4a4095150a7c4545a1fb40b98e1ab1744fbc2770d92c977b9dadaa49ab6", size = 552573, upload-time = "2026-10-04T16:31:32.709Z" }, + { url = "https://files.pythonhosted.org/packages/17/73/6041d20729dffbfdf155c02d65be58bc225a1c1fb548fd87c23ef306138f/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:9a0460d43603d1fd9ef59c30278531e15d78581721ddb538fa560aa7817ea4ad", size = 615840, upload-time = "2026-10-04T16:31:34.565Z" }, + { url = "https://files.pythonhosted.org/packages/af/9e/418094adaee6b056ce199051b255448ed872829051e341b2294c80da0977/rpds_py-2026.9.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:1c2d1f6da5128eabf34e963d7163a818846075a52568250d006c4c953b40f903", size = 582764, upload-time = "2026-10-04T16:31:36.665Z" }, + { url = "https://files.pythonhosted.org/packages/3d/9b/1698ebf6b840ddfe8b472198abbed6ace35c6e398faeecd6c47dae742a4e/rpds_py-2026.9.1-cp315-cp315t-win32.whl", hash = "sha256:5c6ee90dee3e85e055ddfd502d611643d9b0fd94c818220bda84ec3dacd9b27b", size = 203795, upload-time = "2026-10-04T16:31:38.53Z" }, + { url = "https://files.pythonhosted.org/packages/8a/e2/91f70d804c61f8eac39a417e82aa1024f655ab9e8bdd7393b196242bc41b/rpds_py-2026.9.1-cp315-cp315t-win_amd64.whl", hash = "sha256:fe5ad0664ec772b02c45859041aa17655709cced7a31005817fbbbd988c25567", size = 223037, upload-time = "2026-10-04T16:31:40.468Z" }, + { url = "https://files.pythonhosted.org/packages/a3/90/a9ba81408369d34c1aca73319c15adc91ed45c1d21e9e8ee4832ffb7fe0b/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6cdc537c8633d7fd92a82e2e0d2ab74320a3f63d5e59fb9cf08711e08fe151c4", size = 381109, upload-time = "2026-10-04T16:32:08.994Z" }, + { url = "https://files.pythonhosted.org/packages/b3/44/5192a0bed94cec86bd2a5e1cc5a1bb8f7eec3aec907eacd2deb13e87e326/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:10e208f2425d973938afcd56e28a7c4be32e27b6a60b5d381f49fb9d8acf9759", size = 388222, upload-time = "2026-10-04T16:32:11.321Z" }, + { url = "https://files.pythonhosted.org/packages/92/cd/5356549711448f18b52f7a11ffbe90f1228774996fbf3c6cd1b18d22abaf/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:6c0dbbcc19735fe5f8b0a54c07659d154a9e69f47e15d0a6ab7299215daf62cb", size = 500384, upload-time = "2026-10-04T16:32:13.478Z" }, + { url = "https://files.pythonhosted.org/packages/7a/88/ddda9d28adfe33119c75b2e733d4ba7e326f41d7e1b1093951771768ca48/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:684fd492fff4fead00587544e059be2bbcb6f93454f21fa2a91b66fc7508be82", size = 401661, upload-time = "2026-10-04T16:32:15.653Z" }, + { url = "https://files.pythonhosted.org/packages/32/c3/bb59ba16a6b4a57995d15b8c04c00f28df3b938c4dcdde48fbe0f73edb0c/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d1028417bb44037eb3069c1009bd7b7277212876cda22fbe565b0bca9fab6d2c", size = 380748, upload-time = "2026-10-04T16:32:17.727Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b8/0580faa1c5a32ddc160130dd7ae54d2d007272a89a40a6b5db3e50f9f585/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_31_riscv64.whl", hash = "sha256:492e5e428cbe126221611f47e068f01660352feec4ad18bc0f5ea9b2ae88fb14", size = 385731, upload-time = "2026-10-04T16:32:19.855Z" }, + { url = "https://files.pythonhosted.org/packages/bf/70/f73564642bbe3322c7eeef2c2f258cf040b71c41a430b532e59d04a1b838/rpds_py-2026.9.1-pp312-pypy312_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:88b5268892fde430d5531f95bc560b6efbbd67c929662c586afd729a96e7461c", size = 412131, upload-time = "2026-10-04T16:32:22.285Z" }, + { url = "https://files.pythonhosted.org/packages/8c/5d/17fff2e1f8f68721a2afb5cb48f7e442c751bb6b4883157c5abaf618cd08/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_aarch64.whl", hash = "sha256:01445c8d194aa032a08e944f16567672da1c62dbdbefd8b6d0693032e290cf68", size = 558193, upload-time = "2026-10-04T16:32:24.4Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d0/869ab6fb08531f97aae4a780b4d61b4190d8aef48fe054ee28bcf7114466/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_i686.whl", hash = "sha256:eef6a03b0b6d08d0835ccfa8ec8d1bc70525e3801387567137b50c557695e6da", size = 622448, upload-time = "2026-10-04T16:32:26.844Z" }, + { url = "https://files.pythonhosted.org/packages/ba/a5/9672e532fe02cd3b92c78cfd8743abca939d96853006c63835009a1ecb6f/rpds_py-2026.9.1-pp312-pypy312_pp73-musllinux_1_2_x86_64.whl", hash = "sha256:6b9bf3135b4ad5981df9a73d71a35272d650a2985ae9c2746357b24d59de2448", size = 591126, upload-time = "2026-10-04T16:32:29.274Z" }, + { url = "https://files.pythonhosted.org/packages/80/ef/3a9f8e4279c7920af561deed4cb7ebebed2794a8f608cf404d5eef14a105/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_10_12_x86_64.whl", hash = "sha256:56c6952a9b15047466d0c2347c446a761d4527f89976156341e68f0ce5cc08b0", size = 357108, upload-time = "2026-10-04T16:32:31.641Z" }, + { url = "https://files.pythonhosted.org/packages/b7/55/4b2fa381a583760aea5c92841e4e928a358e1c6511b129219e9c2826a226/rpds_py-2026.9.1-pp312-pypy312_pp80-macosx_11_0_arm64.whl", hash = "sha256:b242c27c8f836305a4a72df9cdd564386ac57b807bd252a063223331c9316b37", size = 346877, upload-time = "2026-10-04T16:32:34.061Z" }, +] + [[package]] name = "ruff" version = "0.16.9" @@ -3077,6 +3294,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/8f/88/fb7ce53c23e171ad059fd3a5ff6889399da2804cf0cfda2a10c64f32fdf7/sqlglot-30.27.0-py3-none-any.whl", hash = "sha256:b630686fc167762e20960ad3d007ad03d81af0a804c9f7d117f1fe06433c839e", size = 801972, upload-time = "2026-10-30T18:18:57.65Z" }, ] +[[package]] +name = "sse-starlette" +version = "3.7.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio" }, + { name = "starlette" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/41/43/a232e3cd804293bd4f6d01e8895bc0f6f83ea148d712baf9d783c7d93d23/sse_starlette-3.7.0.tar.gz", hash = "sha256:326416da2ab52e9a41b3f409d3ff897eda45aa68c9f3b7b17d0913aab8d219c3", size = 43869, upload-time = "2026-11-07T11:15:49.389Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/11/25cabac0a24fa76f58637d8671b549c90d818d69d26beecf0c59a3b186e0/sse_starlette-3.7.0-py3-none-any.whl", hash = "sha256:f1d3136caa12d129284fca3d2ded79bc9af943320b6472712955fea52a6d3eea", size = 18432, upload-time = "2026-11-07T11:15:47.86Z" }, +] + [[package]] name = "starlette" version = "1.7.0" @@ -3295,6 +3525,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/9f/e4/81f9a935789233cf412a0ed5fe04c883841d2c8fb0b7e075958a35c65032/tree_sitter_typescript-0.23.2-cp39-abi3-win_arm64.whl", hash = "sha256:05db58f70b95ef0ea126db5560f3775692f609589ed6f8dd0af84b7f19f1cbb7", size = 274052, upload-time = "2024-11-11T02:36:09.514Z" }, ] +[[package]] +name = "types-jsonschema" +version = "4.26.0.20261006" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/29/d2/1f742605f5a6d39f993134885b8de41c98af606871d3ebddaf3e776bd1eb/types_jsonschema-4.26.0.20261006.tar.gz", hash = "sha256:3eb7db61b6819d40addfdaac7173e749071a7d4a9a4394f0c844598ec84b2500", size = 16843, upload-time = "2026-10-06T08:16:07.318Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/a0/4f2e3c0dc3d5cad958006f2e0307065cc8fe4fbf0393ff0b69d55ee9bbe5/types_jsonschema-4.26.0.20261006-py3-none-any.whl", hash = "sha256:29301f4e65e3928540cdf5e23ad716e38bb0c0b416a48dada213edd3d70206ec", size = 16113, upload-time = "2026-10-06T08:16:06.355Z" }, +] + [[package]] name = "types-pyyaml" version = "6.0.12.20260906" From 846942b6f7631fff08732cd5508276298feed79f Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 20:12:02 +0000 Subject: [PATCH 02/30] MCP cancellation drains its SDK session A cancelled response waiter leaves the SDK HTTP task alive. Give each open client a lifecycle owner, join its shutdown before returning cancellation, and retain the session deadline through idle time. Verify stream cleanup, repeated cancellation and isolation from other clients. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 7 +- pyproject.toml | 4 +- server/clients/mcp_source.py | 204 +++++++----- tests/unit/test_mcp_source_cancellation.py | 343 +++++++++++++++++++++ 4 files changed, 478 insertions(+), 80 deletions(-) create mode 100644 tests/unit/test_mcp_source_cancellation.py diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index f549e989bf..334e6dc02e 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -73,8 +73,11 @@ provenance. A citation address alone does not establish tenant or reader authori ## Bounds and cancellation Discovery, pagination, results, content and HTTP responses have finite limits. A session -has an overall deadline as well as request bounds. Cancellation ends owned protocol work; -it does not publish partial evidence as a successful read. Errors expose bounded error +has an overall deadline, including idle time, as well as request bounds. The SDK context +managers live in one task per open client. Cancelling an operation closes and joins that +task before returning cancellation; another client's SDK scope remains independent. +A cancelled client is terminal. Cancellation publishes no partial read evidence. +Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. A successful final page closes that listing operation. It does not establish a deletion diff --git a/pyproject.toml b/pyproject.toml index cdf2dc91b0..ab6322f200 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,8 +30,8 @@ dependencies = [ # Outbound MCP sources use the official protocol client; schemas constrain approved tool mappings. "mcp>=1.30.0,<2", "jsonschema>=4.20", - "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host - "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts + "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host + "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts "tenacity>=9.0", "pyjwt[crypto]>=2.10", # OpenTelemetry: ship spans + logs to HyperDX / ClickStack's OTLP diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index e0922d0067..5d4778457a 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -12,12 +12,13 @@ import json import math from collections.abc import AsyncIterator, Awaitable, Callable -from contextlib import AsyncExitStack +from contextlib import AsyncExitStack, ExitStack from dataclasses import asdict, dataclass, field, replace from datetime import timedelta from typing import Any, Literal, TypeVar from urllib.parse import urlsplit +import anyio import httpx from jsonschema import Draft202012Validator, SchemaError from mcp import ClientSession, types @@ -315,7 +316,9 @@ async def __aiter__(self) -> AsyncIterator[bytes]: raise MCPSourceError(self.owner.failure) from None async def aclose(self) -> None: - await self.stream.aclose() + # The SDK cancels its task group before joining HTTP stream finalizers. + with anyio.CancelScope(shield=True): + await self.stream.aclose() class _PinnedTransport(httpx.AsyncBaseTransport): @@ -500,7 +503,11 @@ def __init__( raise MCPSourceError("config") for part in path: _string(part, 128) - self._stack: AsyncExitStack | None = None + self._privacy: ExitStack | None = None + self._owner_task: asyncio.Task[None] | None = None + self._ready: asyncio.Future[None] | None = None + self._closing = False + self._owner_failure: ErrorCode | None = None self._session: ClientSession | None = None self._transport: _PinnedTransport | None = None self._operation_failure: ErrorCode | None = None @@ -540,88 +547,121 @@ def _with_receipt( return replace(evidence, receipt=receipt) async def __aenter__(self) -> MCPSourceClient: - if self._stack is not None or self._deadline: + if self._owner_task is not None or self._deadline: raise MCPSourceError("closed") - self._stack = AsyncExitStack() - self._stack.enter_context(private_work()) - self._deadline = asyncio.get_running_loop().time() + self._config.limits.timeout_seconds + self._privacy = ExitStack() + self._privacy.enter_context(private_work()) + loop = asyncio.get_running_loop() + self._deadline = loop.time() + self._config.limits.timeout_seconds + self._ready = loop.create_future() + self._owner_task = asyncio.create_task(self._serve_session()) try: - async with asyncio.timeout_at(self._deadline): - await self.validate_access() - transport = _PinnedTransport( - self._config, - self.credential, - self._deadline, - self.validate_access, - transport=self._test_transport, - ) - self._transport = transport - client = await self._stack.enter_async_context( - httpx.AsyncClient( - transport=transport, - trust_env=False, - follow_redirects=False, - timeout=httpx.Timeout(self._config.limits.request_seconds), - ) - ) - read, write, _ = await self._stack.enter_async_context( - streamable_http_client(self._config.endpoint, http_client=client) - ) - self._session = await self._stack.enter_async_context( - ClientSession( - read, - write, - read_timeout_seconds=timedelta(seconds=self._config.limits.request_seconds), - message_handler=self._message_handler, - ) - ) - result = await self._session.initialize() - self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) - await self.validate_access() + await self._ready return self - except asyncio.CancelledError as error: - code = self._transport.failure if self._transport else None + except asyncio.CancelledError: try: - await self._close(error) - except (Exception, asyncio.CancelledError): # noqa: BLE001 — SDK teardown repeats its transport refusal - if code is None: - raise asyncio.CancelledError from None - if code is not None: - raise MCPSourceError(code) from None + await self._close() + except asyncio.CancelledError: + pass + finally: + self._leave_private() raise - except Exception as error: # noqa: BLE001 — initialization errors contain untrusted server metadata - code = ( - self._transport.failure - if self._transport and self._transport.failure - else _error_code(error) - ) + except Exception as error: # noqa: BLE001 — only fixed initialization failures reach callers try: - await self._close(error) - except (Exception, asyncio.CancelledError): # noqa: BLE001 — cleanup must preserve the first fixed failure - pass - raise MCPSourceError(code) from None - - async def _close(self, error: BaseException | None = None) -> None: - stack, self._stack = self._stack, None - self._session = None - if stack is not None: - await stack.__aexit__( - type(error) if error else None, error, error.__traceback__ if error else None + await self._close() + finally: + self._leave_private() + raise MCPSourceError(self._owner_failure or _error_code(error)) from None + + async def _serve_session(self) -> None: + # SDK AnyIO scopes are entered and exited by this one lifecycle owner. + with private_work(): + try: + async with AsyncExitStack() as stack: + async with asyncio.timeout_at(self._deadline): + await self._initialize(stack) + assert self._ready is not None + if not self._ready.done(): + self._ready.set_result(None) + await asyncio.Future[None]() + except ( + Exception, # noqa: BLE001 — SDK lifecycle failures must remain fixed codes + asyncio.CancelledError, + ) as error: + failure = self._transport.failure if self._transport else None + expected_close = self._closing and isinstance(error, asyncio.CancelledError) + if failure is not None or not expected_close: + self._owner_failure = failure or _error_code(error) + if self._ready is not None and not self._ready.done(): + self._ready.set_exception(MCPSourceError(self._owner_failure or "closed")) + finally: + self._session = None + + async def _initialize(self, stack: AsyncExitStack) -> None: + await self.validate_access() + transport = _PinnedTransport( + self._config, + self.credential, + self._deadline, + self.validate_access, + transport=self._test_transport, + ) + self._transport = transport + client = await stack.enter_async_context( + httpx.AsyncClient( + transport=transport, + trust_env=False, + follow_redirects=False, + timeout=httpx.Timeout(self._config.limits.request_seconds), ) + ) + read, write, _ = await stack.enter_async_context( + streamable_http_client(self._config.endpoint, http_client=client) + ) + self._session = await stack.enter_async_context( + ClientSession( + read, + write, + read_timeout_seconds=timedelta(seconds=self._config.limits.request_seconds), + message_handler=self._message_handler, + ) + ) + result = await self._session.initialize() + self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) + await self.validate_access() + + async def _close(self) -> None: + set_query_tag("mcp-source.cleanup") + owner = self._owner_task + if owner is None: + return + if not self._closing: + self._closing = True + owner.cancel() + interrupted: asyncio.CancelledError | None = None + while not owner.done(): + try: + await asyncio.shield(owner) + except asyncio.CancelledError as error: + interrupted = error + if not owner.cancelled(): + owner.result() + if interrupted is not None: + raise interrupted + + def _leave_private(self) -> None: + privacy, self._privacy = self._privacy, None + if privacy is not None: + privacy.close() async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: Any) -> None: try: - await self._close(error) - except (Exception, asyncio.CancelledError) as cleanup: # Preserve the first fixed refusal. - code = ( - self._transport.failure - if self._transport and self._transport.failure - else _error_code(cleanup) - ) - if self._operation_failure != code: - if isinstance(cleanup, asyncio.CancelledError): - raise - raise MCPSourceError(code) from None + await self._close() + failure = self._owner_failure + if error is None and failure is not None and failure != self._operation_failure: + raise MCPSourceError(failure) + finally: + self._leave_private() async def _message_handler(self, message: Any) -> None: if isinstance(message, types.ServerNotification) and isinstance( @@ -630,9 +670,14 @@ async def _message_handler(self, message: Any) -> None: self._schema_changed = True async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: + with private_work(): + return await self._execute(action) + + async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: set_query_tag("mcp-source") if self._session is None: - raise MCPSourceError("closed") + self._operation_failure = self._owner_failure or "closed" + raise MCPSourceError(self._operation_failure) if self._operation_failure is not None: raise MCPSourceError(self._operation_failure) try: @@ -640,11 +685,18 @@ async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: await self.validate_access() result = await action(self._session) await self.validate_access() + if self._operation_failure is not None: + raise MCPSourceError(self._operation_failure) return result except asyncio.CancelledError: if self._transport and self._transport.failure: self._operation_failure = self._transport.failure raise MCPSourceError(self._operation_failure) from None + self._operation_failure = "closed" + try: + await self._close() + except asyncio.CancelledError: + pass raise except MCPSourceError as error: self._operation_failure = error.code diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py new file mode 100644 index 0000000000..21da39b73a --- /dev/null +++ b/tests/unit/test_mcp_source_cancellation.py @@ -0,0 +1,343 @@ +"""Cancellation must drain owned HTTP work before the client context closes.""" + +from __future__ import annotations + +import asyncio +import json +from collections.abc import AsyncIterator +from dataclasses import dataclass, field +from typing import Any + +import httpx +import pytest + +from server.clients import mcp_source as source +from tests.unit.clock_fake import ManualClock + +ENDPOINT = "https://source.example/mcp" +IDENTITY = "doc://workspace/one" +TEXT = "selected body" +STRING = {"type": "string", "maxLength": 2048} +INPUT = { + "type": "object", + "additionalProperties": False, + "properties": {"id": STRING}, + "required": ["id"], +} +OUTPUT = { + "type": "object", + "additionalProperties": False, + "properties": {name: STRING for name in ("id", "uri", "title", "text")}, + "required": ["id", "uri", "title", "text"], +} + + +async def access() -> None: + return None + + +async def pin(*args: Any, **kwargs: Any) -> tuple[str, str, str, str]: + return "", "https://93.184.216.34/mcp", "source.example", "source.example" + + +@dataclass +class HTTPFixture: + kind: str + block: bool = True + phase: str = "headers" + hold_cleanup: bool = False + block_initialize: bool = False + started: asyncio.Event = field(default_factory=asyncio.Event) + stopped: asyncio.Event = field(default_factory=asyncio.Event) + release: asyncio.Event = field(default_factory=asyncio.Event) + reads: int = 0 + closing: asyncio.Event = field(default_factory=asyncio.Event) + cleanup_release: asyncio.Event = field(default_factory=asyncio.Event) + pool_closed: asyncio.Event = field(default_factory=asyncio.Event) + pool_closes: int = 0 + + async def cleanup(self) -> None: + self.closing.set() + if self.hold_cleanup: + await self.cleanup_release.wait() + self.stopped.set() + + def config(self) -> source.MCPSourceConfig: + mapping = source.MCPToolMapping("read_document", INPUT, OUTPUT, "id") + return source.MCPSourceConfig( + ENDPOINT, + approved_resource_ids=(IDENTITY,), + approved_tools=("read_document",) if self.kind == "tools" else (), + read=mapping if self.kind == "tools" else None, + limits=source.MCPLimits(timeout_seconds=5, request_seconds=2), + ) + + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response(405) + payload = json.loads(await request.aread()) + method = payload["method"] + if method == "notifications/initialized": + return httpx.Response(202) + if method == "initialize": + if self.block_initialize: + self.started.set() + try: + await self.release.wait() + finally: + await self.cleanup() + result = { + "protocolVersion": "2025-11-25", + "capabilities": {self.kind: {}}, + "serverInfo": {"name": "synthetic", "version": "1"}, + } + elif method == "tools/list": + result = { + "tools": [{"name": "read_document", "inputSchema": INPUT, "outputSchema": OUTPUT}] + } + elif method in {"resources/read", "tools/call"}: + self.reads += 1 + if self.phase != "headers": + return httpx.Response( + 200, + stream=ReadStream(self, payload["id"]), + headers={ + "content-type": "text/event-stream" + if self.phase == "sse" + else "application/json" + }, + ) + self.started.set() + try: + if self.block: + await self.release.wait() + result = self.document() + finally: + await self.cleanup() + else: + raise AssertionError(method) + return httpx.Response(200, json={"jsonrpc": "2.0", "id": payload["id"], "result": result}) + + def document(self) -> dict[str, Any]: + if self.kind == "resources": + return {"contents": [{"uri": IDENTITY, "text": TEXT}]} + return { + "content": [], + "structuredContent": {"id": IDENTITY, "uri": IDENTITY, "title": "One", "text": TEXT}, + } + + def client(self) -> source.MCPSourceClient: + return source.MCPSourceClient( + self.config(), + None, + validate_access=access, + _transport=FixtureTransport(self), + ) + + +class ReadStream(httpx.AsyncByteStream): + def __init__(self, fixture: HTTPFixture, request_id: int) -> None: + self.fixture, self.request_id = fixture, request_id + + async def __aiter__(self) -> AsyncIterator[bytes]: + self.fixture.started.set() + if self.fixture.block: + await self.fixture.release.wait() + body = json.dumps( + {"jsonrpc": "2.0", "id": self.request_id, "result": self.fixture.document()} + ).encode() + yield b"event: message\ndata: " + body + b"\n\n" if self.fixture.phase == "sse" else body + + async def aclose(self) -> None: + await self.fixture.cleanup() + + +class FixtureTransport(httpx.MockTransport): + def __init__(self, fixture: HTTPFixture) -> None: + super().__init__(fixture.reply) + self.fixture = fixture + + async def aclose(self) -> None: + await super().aclose() + self.fixture.pool_closes += 1 + self.fixture.pool_closed.set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["headers", "json", "sse"]) +async def test_cancelled_read_drains_http_before_context_close( + monkeypatch: pytest.MonkeyPatch, + kind: str, + phase: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, phase=phase) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + # Capture the invariant before either releasing upstream or closing the client. + stopped_inside_open_context = fixture.stopped.is_set() + assert task.cancelled() + assert fixture.pool_closed.is_set() + before = fixture.reads + with pytest.raises(source.MCPSourceError, match="closed"): + await remote.read(IDENTITY) + assert fixture.reads == before + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert stopped_inside_open_context, "cancelled read left its owned HTTP request running" + assert fixture.pool_closes == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["headers", "json", "sse"]) +async def test_adjacent_normal_selected_read_returns_receipt( + monkeypatch: pytest.MonkeyPatch, + kind: str, + phase: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, block=False, phase=phase) + async with fixture.client() as remote: + evidence = await remote.read(IDENTITY) + assert evidence.text == TEXT + assert evidence.receipt is not None + assert evidence.receipt.requested_id == IDENTITY + assert fixture.stopped.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_repeated_cancellation_still_awaits_stream_cleanup( + monkeypatch: pytest.MonkeyPatch, + kind: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, phase="sse", hold_cleanup=True) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + await asyncio.wait_for(fixture.closing.wait(), timeout=1) + assert not task.done() + task.cancel() + await asyncio.sleep(0) + assert not task.done() + assert not fixture.stopped.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + finally: + fixture.release.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_terminal_cancellation_does_not_stop_another_client( + monkeypatch: pytest.MonkeyPatch, + kind: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + cancelled, neighbor = HTTPFixture(kind), HTTPFixture(kind) + async with cancelled.client() as first, neighbor.client() as second: + first_task = asyncio.create_task(first.read(IDENTITY)) + second_task = asyncio.create_task(second.read(IDENTITY)) + try: + await asyncio.wait_for(cancelled.started.wait(), timeout=1) + await asyncio.wait_for(neighbor.started.wait(), timeout=1) + first_task.cancel() + with pytest.raises(asyncio.CancelledError): + await first_task + assert cancelled.stopped.is_set() + assert not second_task.done() + assert not neighbor.stopped.is_set() + assert not neighbor.pool_closed.is_set() + neighbor.release.set() + evidence = await second_task + assert evidence.text == TEXT + assert evidence.receipt is not None + finally: + cancelled.release.set() + neighbor.release.set() + for task in (first_task, second_task): + if not task.done(): + task.cancel() + await asyncio.gather(first_task, second_task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_cancellation_during_initialize_drains_lifecycle_owner( + monkeypatch: pytest.MonkeyPatch, + kind: str, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, block_initialize=True) + + async def opening() -> None: + async with fixture.client(): + pytest.fail("a blocked initialize unexpectedly completed") + + task = asyncio.create_task(opening()) + try: + await asyncio.wait_for(fixture.started.wait(), timeout=1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + assert fixture.reads == 0 + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_idle_session_deadline_closes_pool_before_context_exit( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, block=False) + closed_inside = False + exit_failure = None + try: + async with fixture.client() as remote: + clock.advance(6) + # All fixture I/O is ready; let the expired timer and SDK cleanup run. + for _ in range(100): + await asyncio.sleep(0) + if fixture.pool_closed.is_set(): + break + closed_inside = fixture.pool_closed.is_set() + if closed_inside: + with pytest.raises(source.MCPSourceError) as refusal: + await remote.read(IDENTITY) + assert refusal.value.code == "timeout" + assert fixture.reads == 0 + except source.MCPSourceError as error: + exit_failure = error.code + assert closed_inside, "the session deadline left its idle HTTP pool open" + assert exit_failure is None, "cleanup repeated an already reported deadline refusal" + assert fixture.pool_closes == 1 From c36be9546bb02ddfeab165c07d41043e5b25a3a4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 20:35:05 +0000 Subject: [PATCH 03/30] Drain terminal MCP requests before returning Join the SDK lifecycle owner after every operation failure, including request deadlines and cancellation after a background refusal. Preserve the first caller cancellation while draining stream finalizers and the HTTP pool. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 7 +- server/clients/mcp_source.py | 46 ++-- tests/unit/test_mcp_source_cancellation.py | 252 ++++++++++++++++++++- 3 files changed, 277 insertions(+), 28 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 334e6dc02e..d5b6058187 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -74,9 +74,10 @@ provenance. A citation address alone does not establish tenant or reader authori Discovery, pagination, results, content and HTTP responses have finite limits. A session has an overall deadline, including idle time, as well as request bounds. The SDK context -managers live in one task per open client. Cancelling an operation closes and joins that -task before returning cancellation; another client's SDK scope remains independent. -A cancelled client is terminal. Cancellation publishes no partial read evidence. +managers live in one task per open client. A failed or cancelled operation makes its +client terminal and closes and joins that task before returning, including when an SDK +request deadline expires while HTTP response data is still arriving. Another client's +SDK scope remains independent. Cancellation publishes no partial read evidence. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 5d4778457a..1f9e67ddbf 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -643,7 +643,7 @@ async def _close(self) -> None: try: await asyncio.shield(owner) except asyncio.CancelledError as error: - interrupted = error + interrupted = interrupted or error if not owner.cancelled(): owner.result() if interrupted is not None: @@ -658,7 +658,7 @@ async def __aexit__(self, exc_type: Any, error: BaseException | None, traceback: try: await self._close() failure = self._owner_failure - if error is None and failure is not None and failure != self._operation_failure: + if error is None and failure is not None and self._operation_failure is None: raise MCPSourceError(failure) finally: self._leave_private() @@ -675,12 +675,11 @@ async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: set_query_tag("mcp-source") - if self._session is None: - self._operation_failure = self._owner_failure or "closed" - raise MCPSourceError(self._operation_failure) - if self._operation_failure is not None: - raise MCPSourceError(self._operation_failure) try: + if self._session is None: + raise MCPSourceError(self._owner_failure or "closed") + if self._operation_failure is not None: + raise MCPSourceError(self._operation_failure) async with asyncio.timeout_at(self._deadline): await self.validate_access() result = await action(self._session) @@ -688,26 +687,25 @@ async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T if self._operation_failure is not None: raise MCPSourceError(self._operation_failure) return result - except asyncio.CancelledError: - if self._transport and self._transport.failure: - self._operation_failure = self._transport.failure - raise MCPSourceError(self._operation_failure) from None - self._operation_failure = "closed" + except ( + Exception, # Terminal refusals must drain owned HTTP work before returning. + asyncio.CancelledError, + ) as error: + if isinstance(error, asyncio.CancelledError): + code: ErrorCode = "closed" + elif isinstance(error, MCPSourceError): + code = error.code + else: + code = (self._transport.failure if self._transport else None) or _error_code(error) + code = self._operation_failure or code + self._operation_failure = code try: await self._close() except asyncio.CancelledError: - pass - raise - except MCPSourceError as error: - self._operation_failure = error.code - raise - except Exception as error: # noqa: BLE001 — upstream errors may contain credentials or document content - code = ( - self._transport.failure - if self._transport and self._transport.failure - else _error_code(error) - ) - self._operation_failure = code + if not isinstance(error, asyncio.CancelledError): + raise + if isinstance(error, asyncio.CancelledError): + raise raise MCPSourceError(code) from None async def discover(self) -> MCPDiscovery: diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 21da39b73a..f79fe79541 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -5,7 +5,7 @@ import asyncio import json from collections.abc import AsyncIterator -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import Any import httpx @@ -341,3 +341,253 @@ async def test_idle_session_deadline_closes_pool_before_context_exit( assert closed_inside, "the session deadline left its idle HTTP pool open" assert exit_failure is None, "cleanup repeated an already reported deadline refusal" assert fixture.pool_closes == 1 + + +class HeartbeatStream(ReadStream): + async def __aiter__(self) -> AsyncIterator[bytes]: + fixture = self.fixture + assert isinstance(fixture, HeartbeatFixture) + fixture.started.set() + while not fixture.release.is_set(): + fixture.beats += 1 + yield b": keepalive\n\n" if fixture.phase == "sse" else b" " + await asyncio.sleep(0.01) + + +@dataclass +class HeartbeatFixture(HTTPFixture): + beats: int = 0 + + async def reply(self, request: httpx.Request) -> httpx.Response: + response = await super().reply(request) + if request.method == "POST": + payload = json.loads(await request.aread()) + if payload["method"] in {"resources/read", "tools/call"}: + response.stream = HeartbeatStream(self, payload["id"]) + return response + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["json", "sse"]) +async def test_active_request_deadline_joins_http_before_return( + monkeypatch: pytest.MonkeyPatch, kind: str, phase: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HeartbeatFixture(kind, phase=phase) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.15)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + try: + with pytest.raises(source.MCPSourceError) as refusal: + await remote.read(IDENTITY) + assert refusal.value.code == "timeout" + assert fixture.beats >= 2 + assert fixture.stopped.is_set(), "request deadline left its HTTP stream active" + assert fixture.pool_closed.is_set() + beats, reads = fixture.beats, fixture.reads + await asyncio.sleep(0.03) + assert fixture.beats == beats + with pytest.raises(source.MCPSourceError, match="timeout"): + await remote.read(IDENTITY) + assert fixture.reads == reads + finally: + fixture.release.set() + assert fixture.pool_closes == 1 + + +class RefusalStream(httpx.AsyncByteStream): + def __init__(self, closed: asyncio.Event) -> None: + self.closed = closed + + async def __aiter__(self) -> AsyncIterator[bytes]: + yield b"" + + async def aclose(self) -> None: + self.closed.set() + + +@dataclass +class StatefulFixture(HTTPFixture): + refusal_closed: asyncio.Event = field(default_factory=asyncio.Event) + + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "GET": + await self.started.wait() + return httpx.Response(403, stream=RefusalStream(self.refusal_closed)) + response = await super().reply(request) + if json.loads(await request.aread())["method"] == "initialize": + response.headers["mcp-session-id"] = "synthetic-session" + return response + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("repeat", [False, True]) +async def test_background_refusal_preserves_cancel_and_joins_cleanup( + monkeypatch: pytest.MonkeyPatch, kind: str, repeat: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StatefulFixture(kind, phase="sse", hold_cleanup=repeat) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), 1) + await asyncio.wait_for(fixture.refusal_closed.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "denied" + task.cancel("original caller cancellation") + if repeat: + await asyncio.wait_for(fixture.closing.wait(), 1) + task.cancel("second caller cancellation") + await asyncio.sleep(0) + assert not task.done() + assert not fixture.pool_closed.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original caller cancellation",) + assert task.cancelled() + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + finally: + fixture.release.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert fixture.pool_closes == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("code", ["denied", "protocol"]) +async def test_terminal_failure_drains_only_its_client( + monkeypatch: pytest.MonkeyPatch, kind: str, code: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + failed, neighbor = HTTPFixture(kind, phase="sse"), HTTPFixture(kind, phase="sse") + revoked = False + + async def authorization() -> None: + if revoked: + if code == "denied": + raise source.MCPSourceError("denied") + raise RuntimeError("private upstream diagnostics") + + async with ( + source.MCPSourceClient( + failed.config(), + None, + validate_access=authorization, + _transport=FixtureTransport(failed), + ) as first, + neighbor.client() as second, + ): + first_task = asyncio.create_task(first.read(IDENTITY)) + second_task = asyncio.create_task(second.read(IDENTITY)) + try: + await asyncio.wait_for(failed.started.wait(), 1) + await asyncio.wait_for(neighbor.started.wait(), 1) + revoked = True + with pytest.raises(source.MCPSourceError) as refusal: + await first.discover() + assert refusal.value.code == code + assert str(refusal.value) == "MCP source " + code + assert failed.stopped.is_set() + assert failed.pool_closed.is_set() + assert not neighbor.stopped.is_set() + assert not neighbor.pool_closed.is_set() + assert not second_task.done() + neighbor.release.set() + evidence = await second_task + assert evidence.text == TEXT + assert evidence.receipt is not None + outcome = (await asyncio.gather(first_task, return_exceptions=True))[0] + assert isinstance(outcome, source.MCPSourceError) + finally: + failed.release.set() + neighbor.release.set() + for task in (first_task, second_task): + if not task.done(): + task.cancel() + await asyncio.gather(first_task, second_task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("cancel_cleanup", [False, True]) +async def test_request_deadline_waits_for_finalizer_despite_repeated_cancel( + monkeypatch: pytest.MonkeyPatch, kind: str, cancel_cleanup: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HeartbeatFixture(kind, phase="sse", hold_cleanup=True) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.15)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.closing.wait(), 1) + assert fixture.beats >= 2 + assert not task.done() + assert not fixture.pool_closed.is_set() + if cancel_cleanup: + task.cancel("cleanup caller cancellation") + await asyncio.sleep(0) + task.cancel("repeated cleanup cancellation") + await asyncio.sleep(0) + assert not task.done() + fixture.cleanup_release.set() + if cancel_cleanup: + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("cleanup caller cancellation",) + assert task.cancelled() + else: + with pytest.raises(source.MCPSourceError, match="timeout"): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + finally: + fixture.release.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert fixture.pool_closes == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_total_deadline_drains_active_http_before_return( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture(kind, phase="sse") + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=10)) + async with source.MCPSourceClient( + config, None, validate_access=access, _transport=FixtureTransport(fixture) + ) as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.started.wait(), 1) + assert not task.done() + clock.advance(6) + with pytest.raises(source.MCPSourceError, match="timeout"): + await task + assert fixture.stopped.is_set() + assert fixture.pool_closed.is_set() + assert fixture.reads == 1 + finally: + fixture.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert fixture.pool_closes == 1 From 4dc7c27c687c9ac7cc36b9ebea808ff897ccba62 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 21:00:17 +0000 Subject: [PATCH 04/30] Disable external schema retrieval and close unclaimed responses Reject schema keywords outside their declared type and validate with an explicit registry that cannot retrieve external resources. Retain response cleanup through authority checks and join its finalizer outside the work deadline when handoff fails or is cancelled. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 4 + pyproject.toml | 1 + server/clients/mcp_source.py | 193 ++++++++++--------- tests/unit/test_mcp_source_cancellation.py | 207 +++++++++++++++++++++ tests/unit/test_mcp_source_client.py | 83 +++++++++ uv.lock | 2 + 6 files changed, 391 insertions(+), 99 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index d5b6058187..17205a4313 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -61,6 +61,8 @@ The qualified content profile is text resources and mapped structured tool outpu resource blobs and tools that return only unstructured text are unsupported. Approved tool schemas use a bounded subset with closed objects, bounded arrays and strings, and no references, regular expressions or combinatorial validators. +Keywords must belong to the schema's declared type. External schema retrieval is +disabled independently of configuration validation. Each read produces normalized evidence: resource identity, citation URI, title, media type, content and any supplied revision. A read receipt binds the requested identity, @@ -78,6 +80,8 @@ managers live in one task per open client. A failed or cancelled operation makes client terminal and closes and joins that task before returning, including when an SDK request deadline expires while HTTP response data is still arriving. Another client's SDK scope remains independent. Cancellation publishes no partial read evidence. +The transport retains cleanup ownership while checking authority after response headers +arrive and before handing the response to the protocol client. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. diff --git a/pyproject.toml b/pyproject.toml index ab6322f200..6cf0314b3b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,7 @@ dependencies = [ # Outbound MCP sources use the official protocol client; schemas constrain approved tool mappings. "mcp>=1.30.0,<2", "jsonschema>=4.20", + "referencing>=0.37.0", "idna>=3.7", # UTS 46 host names: server.settings.catalog.ascii_host "dnspython>=2.6", # a cancellable lookup for names a tenant chooses: server.core.hosts "tenacity>=9.0", diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 1f9e67ddbf..f220945469 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -25,6 +25,8 @@ from mcp.client.streamable_http import streamable_http_client from mcp.shared.exceptions import McpError from pydantic import AnyUrl +from referencing import Registry +from referencing.exceptions import Unresolvable from server.core.ch import set_query_tag from server.core.diagnostics import private_work @@ -216,25 +218,16 @@ def _origin(url: str) -> tuple[str, str, int]: # This subset has no references, regular expressions or combinatorial validators. -_SCHEMA_KEYS = frozenset( - { - "type", - "properties", - "required", - "additionalProperties", - "items", - "maxItems", - "minItems", - "maxLength", - "minLength", - "minimum", - "maximum", - "enum", - "const", - "title", - "description", - } -) +_SCHEMA_KEYS = frozenset({"type", "enum", "const", "title", "description"}) +_SCHEMA_TYPE_KEYS = { + "object": {"properties", "required", "additionalProperties"}, + "array": {"items", "maxItems", "minItems"}, + "string": {"maxLength", "minLength"}, + "integer": {"minimum", "maximum"}, + "number": {"minimum", "maximum"}, + "boolean": set(), + "null": set(), +} def _schema(schema: dict[str, Any]) -> None: @@ -244,17 +237,12 @@ def _schema(schema: dict[str, Any]) -> None: def visit(node: Any, depth: int) -> None: nonlocal remaining remaining -= 1 - if remaining < 0 or depth > 8 or not isinstance(node, dict) or set(node) - _SCHEMA_KEYS: + if remaining < 0 or depth > 8 or not isinstance(node, dict): raise MCPSourceError("schema") - if not isinstance(node.get("type"), str) or node["type"] not in { - "object", - "array", - "string", - "integer", - "number", - "boolean", - "null", - }: + kind = node.get("type") + if not isinstance(kind, str) or kind not in _SCHEMA_TYPE_KEYS: + raise MCPSourceError("schema") + if set(node) - (_SCHEMA_KEYS | _SCHEMA_TYPE_KEYS[kind]): raise MCPSourceError("schema") if node["type"] == "object": if node.get("additionalProperties") is not False: @@ -284,7 +272,12 @@ def visit(node: Any, depth: int) -> None: def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: _json(value, maximum) - if not Draft202012Validator(schema).is_valid(value): + try: + # An explicit empty registry never retrieves external schema resources. + valid = Draft202012Validator(schema, registry=Registry()).is_valid(value) + except Unresolvable: + raise MCPSourceError("schema") from None + if not valid: raise MCPSourceError("schema") @@ -352,77 +345,79 @@ async def handle_async_request(self, request: httpx.Request) -> httpx.Response: raise MCPSourceError(self.failure) from None async def _handle(self, request: httpx.Request) -> httpx.Response: - async with asyncio.timeout_at(self.deadline): - if self.failure is not None: - raise MCPSourceError(self.failure) - if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: - raise MCPSourceError("denied") - self.requests += 1 - if self.requests > self.limits.max_requests: - raise MCPSourceError("limit") - await self.validate_access() - if self.target is None: - async with self.pin_lock: - if self.target is None: - refusal, pinned, host, sni = await pinned_target( - str(self.endpoint), schemes=("https",) - ) - if refusal or not host or not sni: - raise MCPSourceError("denied") - self.target = pinned, host, sni - pinned, host, sni = self.target - # Construct an allowlist of protocol headers, never propagate inbound headers. - headers = { - key: value - for key, value in request.headers.items() - if key - in { - "accept", - "content-type", - "mcp-session-id", - "mcp-protocol-version", - "last-event-id", - "mcp-method", - "mcp-name", + response: httpx.Response | None = None + handed_off = False + try: + async with asyncio.timeout_at(self.deadline): + if self.failure is not None: + raise MCPSourceError(self.failure) + if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: + raise MCPSourceError("denied") + self.requests += 1 + if self.requests > self.limits.max_requests: + raise MCPSourceError("limit") + await self.validate_access() + if self.target is None: + async with self.pin_lock: + if self.target is None: + refusal, pinned, host, sni = await pinned_target( + str(self.endpoint), schemes=("https",) + ) + if refusal or not host or not sni: + raise MCPSourceError("denied") + self.target = pinned, host, sni + pinned, host, sni = self.target + # Construct an allowlist of protocol headers, never propagate inbound headers. + headers = { + key: value + for key, value in request.headers.items() + if key + in { + "accept", + "content-type", + "mcp-session-id", + "mcp-protocol-version", + "last-event-id", + "mcp-method", + "mcp-name", + } } - } - if any(len(v) > 2048 for v in headers.values()): - raise MCPSourceError("limit") - headers.update({"host": host, "accept-encoding": "identity"}) - if self.credential is not None: - headers["authorization"] = "Bearer " + self.credential.token - body = await request.aread() - if len(body) > 32_768: - raise MCPSourceError("limit") - outgoing = httpx.Request( - request.method, - pinned, - headers=headers, - content=body, - extensions={"timeout": request.extensions.get("timeout", {}), "sni_hostname": sni}, - ) - await self.validate_access() - response = await self.inner.handle_async_request(outgoing) - try: + if any(len(v) > 2048 for v in headers.values()): + raise MCPSourceError("limit") + headers.update({"host": host, "accept-encoding": "identity"}) + if self.credential is not None: + headers["authorization"] = "Bearer " + self.credential.token + body = await request.aread() + if len(body) > 32_768: + raise MCPSourceError("limit") + outgoing = httpx.Request( + request.method, + pinned, + headers=headers, + content=body, + extensions={ + "timeout": request.extensions.get("timeout", {}), + "sni_hostname": sni, + }, + ) await self.validate_access() - except Exception as error: # noqa: BLE001 — a revoked response must close before returning its fixed refusal - await response.aclose() - raise MCPSourceError(_error_code(error)) from None - if response.is_redirect: - await response.aclose() - raise MCPSourceError("denied") - if response.status_code in {401, 403}: - await response.aclose() - raise MCPSourceError("denied") - # Reject compression so the wire budget also bounds decoded protocol bytes. - if response.headers.get("content-encoding", "identity") != "identity": - await response.aclose() - raise MCPSourceError("protocol") - if not isinstance(response.stream, httpx.AsyncByteStream): - await response.aclose() - raise MCPSourceError("protocol") - response.stream = _LimitedStream(response.stream, self) - return response + response = await self.inner.handle_async_request(outgoing) + await self.validate_access() + if response.is_redirect or response.status_code in {401, 403}: + raise MCPSourceError("denied") + # Reject compression so the wire budget bounds decoded protocol bytes. + if response.headers.get("content-encoding", "identity") != "identity": + raise MCPSourceError("protocol") + if not isinstance(response.stream, httpx.AsyncByteStream): + raise MCPSourceError("protocol") + response.stream = _LimitedStream(response.stream, self) + handed_off = True + return response + finally: + if response is not None and not handed_off: + # Leave the deadline scope before joining an unclaimed response's finalizer. + with anyio.CancelScope(shield=True): + await response.aclose() async def aclose(self) -> None: await self.inner.aclose() diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index f79fe79541..e6b86996ff 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -591,3 +591,210 @@ async def test_total_deadline_drains_active_http_before_return( task.cancel() await asyncio.gather(task, return_exceptions=True) assert fixture.pool_closes == 1 + + +@dataclass +class HandoffFixture(HTTPFixture): + acquired: asyncio.Event = field(default_factory=asyncio.Event) + checking: asyncio.Event = field(default_factory=asyncio.Event) + authority_release: asyncio.Event = field(default_factory=asyncio.Event) + private_failure: bool = False + response_closes: int = 0 + + async def reply(self, request: httpx.Request) -> httpx.Response: + response = await super().reply(request) + if request.method == "POST": + method = json.loads(await request.aread())["method"] + if method in {"resources/read", "tools/call"}: + self.acquired.set() + return response + + async def authority(self) -> None: + if self.acquired.is_set(): + self.checking.set() + if self.private_failure: + raise RuntimeError("private callback details") + await self.authority_release.wait() + + async def cleanup(self) -> None: + self.response_closes += 1 + await super().cleanup() + + def client(self) -> source.MCPSourceClient: + return source.MCPSourceClient( + self.config(), None, validate_access=self.authority, _transport=FixtureTransport(self) + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("repeat", [False, True]) +async def test_response_handoff_cancel_awaits_acquired_finalizer( + monkeypatch: pytest.MonkeyPatch, kind: str, repeat: bool +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse", hold_cleanup=repeat) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + task.cancel("original handoff cancellation") + if repeat: + await asyncio.wait_for(fixture.closing.wait(), 1) + assert not task.done() + task.cancel("repeated handoff cancellation") + await asyncio.sleep(0) + assert not task.done() + assert not fixture.pool_closed.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original handoff cancellation",) + assert task.cancelled() + assert fixture.stopped.is_set(), "acquired response finalizer was abandoned" + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + assert not fixture.started.is_set(), "unapproved response reached body iteration" + finally: + fixture.cleanup_release.set() + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("deadline", ["request", "total"]) +async def test_response_handoff_deadline_awaits_acquired_finalizer( + monkeypatch: pytest.MonkeyPatch, kind: str, deadline: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse") + config = fixture.config() + config = replace( + config, limits=replace(config.limits, request_seconds=10 if deadline == "total" else 2) + ) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + clock.advance(6 if deadline == "total" else 3) + with pytest.raises(source.MCPSourceError, match="timeout"): + await task + assert fixture.stopped.is_set(), "deadline abandoned the acquired response" + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + assert not fixture.started.is_set() + finally: + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_response_handoff_private_failure_keeps_neighbor_independent( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture( + kind, block=False, phase="sse", private_failure=True, hold_cleanup=True + ) + neighbor = HTTPFixture(kind, phase="sse") + async with fixture.client() as first, neighbor.client() as second: + other = asyncio.create_task(second.read(IDENTITY)) + failed = asyncio.create_task(first.read(IDENTITY)) + try: + await asyncio.wait_for(neighbor.started.wait(), 1) + await asyncio.wait_for(fixture.closing.wait(), 1) + assert not failed.done() + assert not neighbor.pool_closed.is_set() + assert not other.done() + neighbor.release.set() + evidence = await other + assert evidence.text == TEXT + assert evidence.receipt is not None + fixture.cleanup_release.set() + with pytest.raises(source.MCPSourceError) as refusal: + await failed + assert str(refusal.value) == "MCP source protocol" + assert fixture.stopped.is_set() + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + finally: + fixture.cleanup_release.set() + neighbor.release.set() + for task in (other, failed): + if not task.done(): + task.cancel() + await asyncio.gather(other, failed, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_response_handoff_authorized_neighbor_returns_receipt( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse") + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + assert fixture.response_closes == 0 + fixture.authority_release.set() + evidence = await task + assert evidence.text == TEXT + assert evidence.receipt is not None + assert fixture.response_closes == 1 + finally: + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_response_handoff_cancel_finalizer_outlives_total_deadline( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HandoffFixture(kind, block=False, phase="sse", hold_cleanup=True) + async with fixture.client() as remote: + task = asyncio.create_task(remote.read(IDENTITY)) + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + task.cancel("original handoff cancellation") + await asyncio.wait_for(fixture.closing.wait(), 1) + clock.advance(6) + # Deliver all expired deadline callbacks while the finalizer is blocked. + for _ in range(100): + await asyncio.sleep(0) + if task.done(): + break + assert not task.done(), "the deadline interrupted acquired-response cleanup" + assert not fixture.pool_closed.is_set() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original handoff cancellation",) + assert fixture.stopped.is_set() + assert fixture.response_closes == 1 + assert fixture.pool_closed.is_set() + finally: + fixture.cleanup_release.set() + fixture.authority_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index f358b97a44..95b7660610 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -5,7 +5,9 @@ import asyncio import copy import hashlib +import io import json +import urllib.request from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import replace @@ -719,3 +721,84 @@ async def reply(request: httpx.Request) -> httpx.Response: assert request.headers["host"] == "source.example" assert request.headers["authorization"] == "Bearer " + SECRET assert all(name not in request.headers for name in ("cookie", "x-loom-org", "traceparent")) + + +@pytest.mark.parametrize( + "node", + [ + {"type": "string", "maxLength": 10, "items": {"$ref": "urn:synthetic:hidden"}}, + {"type": "object", "additionalProperties": False, "items": {"$ref": "urn:hidden"}}, + {"type": "number", "properties": {"text": {"$ref": "urn:hidden"}}}, + {"type": "boolean", "additionalProperties": {"$ref": "urn:hidden"}}, + { + "type": "null", + "items": { + "type": "array", + "maxItems": 1, + "items": {"$ref": "https://reference.example/hidden"}, + }, + }, + { + "type": "array", + "maxItems": 1, + "items": STRING, + "properties": {"hidden": {"$ref": "urn:hidden"}}, + }, + {"type": "string", "maxLength": 10, "minimum": 0}, + {"type": "integer", "required": ["hidden"]}, + ], +) +def test_schema_hardening_rejects_type_inapplicable_keywords(node: dict[str, Any]) -> None: + read = mapping("fetch") + read.output_schema["properties"]["text"] = node + with pytest.raises(source.MCPSourceError, match="schema"): + client(source.MCPSourceConfig(ENDPOINT, ENDPOINT, approved_tools=("fetch",), read=read)) + + +@pytest.mark.parametrize("keyword", ["$ref", "$dynamicRef"]) +@pytest.mark.parametrize( + "uri", + ["urn:synthetic:no-retrieval", "https://reference.example/schema", "file:///synthetic/schema"], +) +def test_schema_hardening_runtime_never_retrieves_external_resources( + monkeypatch: pytest.MonkeyPatch, keyword: str, uri: str +) -> None: + attempted: list[str] = [] + + def intercepted(request: Any) -> io.BytesIO: + attempted.append(request.full_url) + return io.BytesIO(b'{"type":"string"}') + + monkeypatch.setattr(urllib.request, "urlopen", intercepted) + # Deliberately bypass admission: a future admission defect must still be safe. + schema = {keyword: uri, "type": "string", "maxLength": 10} + with pytest.raises(source.MCPSourceError, match="schema"): + source._validate(schema, "body", 1024) + assert attempted == [], "validation escaped the pinned HTTP boundary" + + +def test_schema_hardening_retains_supported_subset_validation() -> None: + schema = { + "type": "object", + "additionalProperties": False, + "properties": { + "rows": { + "type": "array", + "maxItems": 2, + "minItems": 1, + "items": {"type": "string", "maxLength": 10, "minLength": 1}, + }, + "count": {"type": "integer", "minimum": 1, "maximum": 2}, + "weight": {"type": "number", "minimum": 0, "maximum": 1}, + "present": {"type": "boolean", "const": True}, + "absent": {"type": "null"}, + }, + "required": ["rows", "count"], + } + source._schema(schema) + source._validate( + schema, {"rows": ["one"], "count": 1, "weight": 0.5, "present": True, "absent": None}, 1024 + ) + for invalid in ({"rows": [], "count": 1}, {"rows": ["one"], "count": 3}): + with pytest.raises(source.MCPSourceError, match="schema"): + source._validate(schema, invalid, 1024) diff --git a/uv.lock b/uv.lock index 6589242134..7a9bc9e048 100644 --- a/uv.lock +++ b/uv.lock @@ -803,6 +803,7 @@ dependencies = [ { name = "pydantic-settings" }, { name = "pyjwt", extra = ["crypto"] }, { name = "pyyaml" }, + { name = "referencing" }, { name = "snowballstemmer" }, { name = "tenacity" }, { name = "uvicorn", extra = ["standard"] }, @@ -916,6 +917,7 @@ requires-dist = [ { name = "pytest-rerunfailures", marker = "extra == 'dev'", specifier = ">=15.0" }, { name = "pytest-xdist", marker = "extra == 'dev'", specifier = ">=3.6" }, { name = "pyyaml", specifier = ">=6.0" }, + { name = "referencing", specifier = ">=0.37.0" }, { name = "ruff", marker = "extra == 'dev'", specifier = "==0.16.9" }, { name = "snowballstemmer", specifier = ">=2.2" }, { name = "sqlglot", marker = "extra == 'extractor'", specifier = ">=30.27,<31" }, From 28d8533b607aa10c055c7fa5d193f143d7958cea Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 22:16:24 +0000 Subject: [PATCH 05/30] Refuse MCP results after terminal transport failures Check session state and total expiry around authority callbacks and publication so background HTTP failures cannot yield successful read evidence. Scope issued cursors by operation and query and accept an absent optional final-page cursor. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 7 +- server/clients/mcp_source.py | 105 +++++-- tests/unit/test_mcp_source_cancellation.py | 344 +++++++++++++++++++++ tests/unit/test_mcp_source_client.py | 111 ++++++- 4 files changed, 535 insertions(+), 32 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 17205a4313..1aade6a10e 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -79,12 +79,17 @@ has an overall deadline, including idle time, as well as request bounds. The SDK managers live in one task per open client. A failed or cancelled operation makes its client terminal and closes and joins that task before returning, including when an SDK request deadline expires while HTTP response data is still arriving. Another client's -SDK scope remains independent. Cancellation publishes no partial read evidence. +SDK scope remains independent. A known background transport failure or an expired +deadline refuses discovery and result publication, including cached discovery. +Cancellation publishes no partial read evidence. The transport retains cleanup ownership while checking authority after response headers arrive and before handing the response to the protocol client. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. +An omitted optional mapped cursor ends that listing. Issued cursors are bound to their +operation and query, so a cursor from one query cannot authorize another. Reusing a +cursor in the same listing is refused even when another listing uses the same text. A successful final page closes that listing operation. It does not establish a deletion history, complete reader permissions, revision support or a subscription contract. Partial pages, errors, refused access and notifications are never deletion evidence. diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index f220945469..ed333fe3bc 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -79,6 +79,15 @@ def _error_code(error: BaseException) -> ErrorCode: return "protocol" +def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = True) -> None: + if failure is not None: + raise MCPSourceError(failure) + if not active: + raise MCPSourceError("closed") + if asyncio.get_running_loop().time() >= deadline: + raise MCPSourceError("timeout") + + @dataclass(frozen=True) class MCPLimits: timeout_seconds: float = 30 @@ -281,11 +290,17 @@ def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: raise MCPSourceError("schema") -def _path(value: Any, path: tuple[str, ...] | None, default: Any = "") -> Any: +def _path( + value: Any, path: tuple[str, ...] | None, default: Any = "", *, optional: bool = False +) -> Any: if path is None: return default for key in path: - if not isinstance(value, dict) or key not in value: + if not isinstance(value, dict): + raise MCPSourceError("schema") + if key not in value: + if optional: + return default raise MCPSourceError("schema") value = value[key] return value @@ -298,14 +313,15 @@ def __init__(self, stream: httpx.AsyncByteStream, owner: _PinnedTransport) -> No async def __aiter__(self) -> AsyncIterator[bytes]: try: async with asyncio.timeout_at(self.owner.deadline): + self.owner._check_state() async for chunk in self.stream: self.owner.received += len(chunk) if self.owner.received > self.owner.limits.max_wire_bytes: raise MCPSourceError("limit") - await self.owner.validate_access() + await self.owner._authorize() yield chunk except Exception as error: # noqa: BLE001 — only fixed diagnostics cross the transport boundary - self.owner.failure = _error_code(error) + self.owner.failure = self.owner.failure or _error_code(error) raise MCPSourceError(self.owner.failure) from None async def aclose(self) -> None: @@ -337,11 +353,19 @@ def __init__( self.pin_lock = asyncio.Lock() self.failure: ErrorCode | None = None + def _check_state(self) -> None: + _guard_state(self.deadline, self.failure) + + async def _authorize(self) -> None: + self._check_state() + await self.validate_access() + self._check_state() + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: try: return await self._handle(request) except Exception as error: # noqa: BLE001 — HTTP exceptions may contain upstream credentials - self.failure = _error_code(error) + self.failure = self.failure or _error_code(error) raise MCPSourceError(self.failure) from None async def _handle(self, request: httpx.Request) -> httpx.Response: @@ -349,14 +373,13 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: handed_off = False try: async with asyncio.timeout_at(self.deadline): - if self.failure is not None: - raise MCPSourceError(self.failure) + self._check_state() if request.url != self.endpoint or request.method not in {"POST", "GET", "DELETE"}: raise MCPSourceError("denied") self.requests += 1 if self.requests > self.limits.max_requests: raise MCPSourceError("limit") - await self.validate_access() + await self._authorize() if self.target is None: async with self.pin_lock: if self.target is None: @@ -400,9 +423,9 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: "sni_hostname": sni, }, ) - await self.validate_access() + await self._authorize() response = await self.inner.handle_async_request(outgoing) - await self.validate_access() + await self._authorize() if response.is_redirect or response.status_code in {401, 403}: raise MCPSourceError("denied") # Reject compression so the wire budget bounds decoded protocol bytes. @@ -413,6 +436,9 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: response.stream = _LimitedStream(response.stream, self) handed_off = True return response + except Exception as error: # noqa: BLE001 — poison the session before awaiting private failure cleanup + self.failure = self.failure or _error_code(error) + raise MCPSourceError(self.failure) from None finally: if response is not None and not handed_off: # Leave the deadline scope before joining an unclaimed response's finalizer. @@ -510,8 +536,8 @@ def __init__( self._discovery: MCPDiscovery | None = None self._schema_changed = False self._pages, self._results = 0, 0 - self._issued_cursors: dict[str, tuple[str, str]] = {} - self._used_cursors: set[str] = set() + self._issued_cursors: set[tuple[tuple[str, str], str]] = set() + self._used_cursors: set[tuple[tuple[str, str], str]] = set() if len(config.approved_resource_ids) > config.limits.max_results: raise MCPSourceError("config") self._selected_ids = frozenset( @@ -541,6 +567,26 @@ def _with_receipt( ) return replace(evidence, receipt=receipt) + def _check_state(self, *, require_session: bool = False) -> None: + owner = self._owner_task + failure = self._operation_failure or self._owner_failure + if failure is None and self._transport is not None: + failure = self._transport.failure + # The lifecycle owner may perform SDK session termination during cleanup. + lifecycle = not require_session and asyncio.current_task() is owner + active = ( + owner is not None + and not owner.done() + and (not self._closing or lifecycle) + and (not require_session or self._session is not None) + ) + _guard_state(self._deadline, failure, active=active) + + async def _authorize(self) -> None: + self._check_state() + await self.validate_access() + self._check_state() + async def __aenter__(self) -> MCPSourceClient: if self._owner_task is not None or self._deadline: raise MCPSourceError("closed") @@ -552,6 +598,7 @@ async def __aenter__(self) -> MCPSourceClient: self._owner_task = asyncio.create_task(self._serve_session()) try: await self._ready + self._check_state(require_session=True) return self except asyncio.CancelledError: try: @@ -593,12 +640,12 @@ async def _serve_session(self) -> None: self._session = None async def _initialize(self, stack: AsyncExitStack) -> None: - await self.validate_access() + await self._authorize() transport = _PinnedTransport( self._config, self.credential, self._deadline, - self.validate_access, + self._authorize, transport=self._test_transport, ) self._transport = transport @@ -623,7 +670,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None: ) result = await self._session.initialize() self._discovery = MCPDiscovery(result.capabilities.resources is not None, ()) - await self.validate_access() + await self._authorize() async def _close(self) -> None: set_query_tag("mcp-source.cleanup") @@ -671,16 +718,14 @@ async def _run(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: async def _execute(self, action: Callable[[ClientSession], Awaitable[_T]]) -> _T: set_query_tag("mcp-source") try: - if self._session is None: - raise MCPSourceError(self._owner_failure or "closed") - if self._operation_failure is not None: - raise MCPSourceError(self._operation_failure) + self._check_state(require_session=True) async with asyncio.timeout_at(self._deadline): - await self.validate_access() + await self._authorize() + self._check_state(require_session=True) + assert self._session is not None result = await action(self._session) - await self.validate_access() - if self._operation_failure is not None: - raise MCPSourceError(self._operation_failure) + await self._authorize() + self._check_state(require_session=True) return result except ( Exception, # Terminal refusals must drain owned HTTP work before returning. @@ -750,9 +795,10 @@ async def action(session: ClientSession) -> MCPDiscovery: def _page_start(self, cursor: str | None, scope: tuple[str, str]) -> None: if cursor is not None: _string(cursor) - if self._issued_cursors.get(cursor) != scope or cursor in self._used_cursors: + key = scope, cursor + if key not in self._issued_cursors or key in self._used_cursors: raise MCPSourceError("denied") - self._used_cursors.add(cursor) + self._used_cursors.add(key) self._pages += 1 if self._pages > self._config.limits.max_pages: raise MCPSourceError("limit") @@ -765,9 +811,10 @@ def _page( raise MCPSourceError("limit") if cursor is not None: _string(cursor) - if cursor in self._issued_cursors: + key = scope, cursor + if key in self._issued_cursors: raise MCPSourceError("protocol") - self._issued_cursors[cursor] = scope + self._issued_cursors.add(key) return MCPPage(tuple(items), cursor, cursor is None) async def list_resources(self, cursor: str | None = None) -> MCPPage: @@ -845,7 +892,9 @@ async def action(session: ClientSession) -> MCPPage: raise MCPSourceError("schema") items = [self._evidence(row, mapping) for row in rows] return self._page( - items, _path(result, mapping.next_cursor_path, None), ("search", query) + items, + _path(result, mapping.next_cursor_path, None, optional=True), + ("search", query), ) return await self._run(action) diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index e6b86996ff..32406b642b 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -51,6 +51,7 @@ class HTTPFixture: stopped: asyncio.Event = field(default_factory=asyncio.Event) release: asyncio.Event = field(default_factory=asyncio.Event) reads: int = 0 + requests: int = 0 closing: asyncio.Event = field(default_factory=asyncio.Event) cleanup_release: asyncio.Event = field(default_factory=asyncio.Event) pool_closed: asyncio.Event = field(default_factory=asyncio.Event) @@ -73,6 +74,7 @@ def config(self) -> source.MCPSourceConfig: ) async def reply(self, request: httpx.Request) -> httpx.Response: + self.requests += 1 if request.method == "GET": return httpx.Response(405) payload = json.loads(await request.aread()) @@ -798,3 +800,345 @@ async def test_response_handoff_cancel_finalizer_outlives_total_deadline( if not task.done(): task.cancel() await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_background_denial_refuses_receipt_without_caller_cancel( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture, neighbor = StatefulFixture(kind, phase="sse"), HTTPFixture(kind, phase="sse") + async with fixture.client() as first, neighbor.client() as second: + failed, other = ( + asyncio.create_task(first.read(IDENTITY)), + asyncio.create_task(second.read(IDENTITY)), + ) + try: + await asyncio.wait_for(fixture.started.wait(), 1) + await asyncio.wait_for(neighbor.started.wait(), 1) + await asyncio.wait_for(fixture.refusal_closed.wait(), 1) + assert first._transport is not None and first._transport.failure == "denied" + assert not neighbor.pool_closed.is_set() and not other.done() + fixture.release.set() + neighbor.release.set() + evidence = await other + assert evidence.receipt is not None and evidence.text == TEXT + with pytest.raises(source.MCPSourceError, match="denied"): + await failed + assert fixture.stopped.is_set() and fixture.pool_closed.is_set() + reads = fixture.reads + with pytest.raises(source.MCPSourceError, match="denied"): + await first.read(IDENTITY) + assert fixture.reads == reads + finally: + fixture.release.set() + neighbor.release.set() + for task in (failed, other): + if not task.done(): + task.cancel() + await asyncio.gather(failed, other, return_exceptions=True) + + +class HeldRefusalStream(RefusalStream): + def __init__(self, closed: asyncio.Event, release: asyncio.Event) -> None: + super().__init__(closed) + self.release = release + + async def aclose(self) -> None: + self.closed.set() + await self.release.wait() + + +@dataclass +class StateRaceFixture(HTTPFixture): + pause_at: str = "handoff" + hold_refusal: bool = False + refusal_release: asyncio.Event = field(default_factory=asyncio.Event) + armed: bool = False + acquired: bool = False + sdk_checks: int = 0 + caller: asyncio.Task[Any] | None = None + checking: asyncio.Event = field(default_factory=asyncio.Event) + resume: asyncio.Event = field(default_factory=asyncio.Event) + denied: asyncio.Event = field(default_factory=asyncio.Event) + initialized: asyncio.Event = field(default_factory=asyncio.Event) + get_started: asyncio.Event = field(default_factory=asyncio.Event) + + async def reply(self, request: httpx.Request) -> httpx.Response: + if request.method == "GET": + self.get_started.set() + await self.checking.wait() + stream = ( + HeldRefusalStream(self.denied, self.refusal_release) + if self.hold_refusal + else RefusalStream(self.denied) + ) + return httpx.Response(403, stream=stream) + if request.method == "DELETE": + return httpx.Response(204) + response = await super().reply(request) + method = json.loads(await request.aread())["method"] + if method == "initialize": + response.headers["mcp-session-id"] = "synthetic-session" + elif method == "notifications/initialized": + self.initialized.set() + elif method in {"resources/read", "tools/call"}: + self.acquired = True + return response + + async def authority(self) -> None: + if not self.armed or self.checking.is_set(): + return + caller = asyncio.current_task() is self.caller + if not caller and not self.acquired: + self.sdk_checks += 1 + matches = { + "operation": caller and not self.acquired, + "dispatch": not caller and not self.acquired and self.sdk_checks == 2, + "handoff": self.acquired and not self.started.is_set(), + "chunk": self.started.is_set() and not self.stopped.is_set(), + "publication": caller and self.stopped.is_set(), + } + if matches[self.pause_at]: + self.checking.set() + await self.resume.wait() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("phase", ["operation", "dispatch", "handoff", "chunk", "publication"]) +async def test_state_guard_rechecks_denial_after_suspended_authority( + monkeypatch: pytest.MonkeyPatch, kind: str, phase: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse", pause_at=phase) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.3)) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + requests_before = fixture.requests + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "denied" + fixture.resume.set() + with pytest.raises(source.MCPSourceError, match="denied"): + await task + assert fixture.pool_closed.is_set() + if phase in {"operation", "dispatch"}: + assert fixture.reads == 0 + assert fixture.requests == requests_before + else: + assert fixture.stopped.is_set() + if phase == "handoff": + assert not fixture.started.is_set() + reads = fixture.reads + with pytest.raises(source.MCPSourceError, match="denied"): + await remote.read(IDENTITY) + assert fixture.reads == reads + finally: + fixture.resume.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("when", ["before", "authority", "publication"]) +async def test_state_guard_synchronous_discovery_refuses_elapsed_deadline( + monkeypatch: pytest.MonkeyPatch, when: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources") + armed = False + checks = 0 + + async def authority() -> None: + nonlocal checks + if armed: + checks += 1 + if when != "publication" or checks == 2: + clock.advance(6) + + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + before = fixture.requests + if when == "before": + clock.advance(6) + else: + armed = True + with pytest.raises(source.MCPSourceError, match="timeout"): + await remote.discover() + assert fixture.pool_closed.is_set() + assert fixture.requests == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize("code", ["denied", "limit", "protocol"]) +async def test_state_guard_cached_publication_rechecks_terminal_failure( + monkeypatch: pytest.MonkeyPatch, code: source.ErrorCode +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources") + checks = 0 + armed = False + + async def authority() -> None: + nonlocal checks + if armed: + checks += 1 + if checks == 2: + assert remote._transport is not None + remote._transport.failure = code + + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + armed = True + with pytest.raises(source.MCPSourceError, match=code): + await remote.discover() + assert fixture.pool_closed.is_set() + assert fixture.reads == 0 + + +@pytest.mark.asyncio +async def test_state_guard_closing_owner_cannot_publish_cached_discovery( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = HTTPFixture("resources") + checks = 0 + armed = False + + async def authority() -> None: + nonlocal checks + if armed: + checks += 1 + if checks == 2: + await remote._close() + + async with source.MCPSourceClient( + fixture.config(), None, validate_access=authority, _transport=FixtureTransport(fixture) + ) as remote: + armed = True + with pytest.raises(source.MCPSourceError, match="closed"): + await remote.discover() + assert fixture.pool_closed.is_set() + assert fixture.reads == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_caller_cancel_keeps_identity_after_background_denial( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse", hold_cleanup=True) + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.checking.wait(), 1) + await asyncio.wait_for(fixture.denied.wait(), 1) + task.cancel("original state-guard cancellation") + await asyncio.wait_for(fixture.closing.wait(), 1) + task.cancel("repeated state-guard cancellation") + await asyncio.sleep(0) + assert not task.done() + fixture.cleanup_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original state-guard cancellation",) + assert fixture.stopped.is_set() and fixture.pool_closed.is_set() + finally: + fixture.resume.set() + fixture.cleanup_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_ordinary_stateful_session_still_returns_receipt_and_closes( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse") + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + evidence = await remote.read(IDENTITY) + assert evidence.receipt is not None and evidence.text == TEXT + assert fixture.stopped.is_set() + assert not fixture.pool_closed.is_set() + assert fixture.pool_closed.is_set() and fixture.pool_closes == 1 + assert remote._transport is not None and remote._transport.failure is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_state_guard_refusal_poison_precedes_held_response_cleanup( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse", pause_at="chunk", hold_refusal=True) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.3)) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "denied" + fixture.resume.set() + await asyncio.wait_for(fixture.stopped.wait(), 1) + clock.advance(0.4) + for _ in range(100): + await asyncio.sleep(0) + if remote._closing: + break + assert remote._closing and not task.done() + assert not fixture.pool_closed.is_set() + fixture.refusal_release.set() + with pytest.raises(source.MCPSourceError, match="denied"): + await task + assert fixture.pool_closed.is_set() + finally: + fixture.resume.set() + fixture.refusal_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 95b7660610..9d1bd5b034 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -87,7 +87,7 @@ async def access() -> None: @asynccontextmanager async def synthetic_server( - monkeypatch: pytest.MonkeyPatch, *, tools: bool = False + monkeypatch: pytest.MonkeyPatch, *, tools: bool = False, both: bool = False ) -> AsyncIterator[dict[str, Any]]: state: dict[str, Any] = { "requests": [], @@ -154,6 +154,8 @@ async def call_tool(ctx: Any, params: Any) -> types.CallToolResult: "text": state["text"], } result = {"documents": [document]} if params.name == "find" else document + if params.name == "find" and state.get("paginate") and "cursor" not in params.arguments: + result["cursor"] = state.get("page_cursor", "page-2") return types.CallToolResult(content=[], structuredContent=result) server: Server[Any] = Server("synthetic-source") @@ -170,10 +172,10 @@ async def tool_listing(request: Any) -> types.ServerResult: async def tool_call(request: Any) -> types.ServerResult: return types.ServerResult(await call_tool(None, request.params)) - if tools: + if tools or both: server.request_handlers[types.ListToolsRequest] = tool_listing server.request_handlers[types.CallToolRequest] = tool_call - else: + if not tools or both: server.request_handlers[types.ListResourcesRequest] = resource_listing server.request_handlers[types.ReadResourceRequest] = resource_read manager = StreamableHTTPSessionManager( @@ -802,3 +804,106 @@ def test_schema_hardening_retains_supported_subset_validation() -> None: for invalid in ({"rows": [], "count": 1}, {"rows": ["one"], "count": 3}): with pytest.raises(source.MCPSourceError, match="schema"): source._validate(schema, invalid, 1024) + + +def paginated_config() -> source.MCPSourceConfig: + conf = config(tools=True) + assert conf.search is not None + return replace(conf, search=replace(conf.search, next_cursor_path=("cursor",))) + + +@pytest.mark.asyncio +async def test_state_guard_mapped_search_accepts_final_optional_cursor_omission( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"] = True + first = await remote.search("alpha") + assert first.next_cursor == "page-2" and not first.complete + final = await remote.search("alpha", first.next_cursor) + assert final.next_cursor is None and final.complete + assert len(final.items) == 1 + assert all(item.receipt is None for item in final.items) + + +@pytest.mark.asyncio +async def test_state_guard_same_cursor_text_is_independent_across_scopes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True, both=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"], state["next"] = True, "page-2" + alpha = await remote.search("alpha") + beta = await remote.search("beta") + resources = await remote.list_resources() + assert alpha.next_cursor == beta.next_cursor == resources.next_cursor == "page-2" + assert (await remote.search("alpha", alpha.next_cursor)).complete + assert (await remote.search("beta", beta.next_cursor)).complete + state["next"] = None + assert (await remote.list_resources(resources.next_cursor)).complete + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["replay", "cross-scope", "reissue"]) +async def test_state_guard_scoped_cursor_still_refuses_replay_or_unissued_scope( + monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"] = True + first = await remote.search("alpha") + if mode == "replay": + assert (await remote.search("alpha", first.next_cursor)).complete + query = "beta" if mode == "cross-scope" else "alpha" + cursor = None if mode == "reissue" else first.next_cursor + with pytest.raises( + source.MCPSourceError, match="protocol" if mode == "reissue" else "denied" + ): + await remote.search(query, cursor) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cursor", ["", None, 17]) +async def test_state_guard_present_invalid_cursor_is_never_completion( + monkeypatch: pytest.MonkeyPatch, cursor: Any +) -> None: + async with ( + synthetic_server(monkeypatch, tools=True) as state, + client(paginated_config()) as remote, + ): + state["paginate"], state["page_cursor"] = True, cursor + with pytest.raises(source.MCPSourceError): + await remote.search("alpha") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("code", ["denied", "limit", "protocol"]) +async def test_state_guard_search_cannot_publish_after_terminal_failure( + monkeypatch: pytest.MonkeyPatch, code: source.ErrorCode +) -> None: + task: asyncio.Task[source.MCPPage] | None = None + + async def authority() -> None: + if asyncio.current_task() is task and state["calls"]: + assert remote._transport is not None + remote._transport.failure = code + + async with synthetic_server(monkeypatch, tools=True) as state: + async with source.MCPSourceClient( + config(tools=True), source.MCPBearer(SECRET, ENDPOINT), validate_access=authority + ) as remote: + task = asyncio.create_task(remote.search("alpha")) + with pytest.raises(source.MCPSourceError, match=code): + await task + assert state["calls"][-1][0] == "find" + before = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match=code): + await remote.search("beta") + assert len(state["requests"]) == before From e864d7ca5c99f1870ea7eb76c22cdda41150f492 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Sun, 22 Nov 2026 23:01:59 +0000 Subject: [PATCH 06/30] Refuse unexpected MCP responses before protocol handoff Record HTTP status and media failures before the SDK can consume background errors. Preserve optional GET and DELETE responses with status 405. Distinguish omitted mapped cursors from present invalid values during page normalization. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 5 +- server/clients/mcp_source.py | 31 ++- tests/unit/test_mcp_source_cancellation.py | 251 ++++++++++++++++++++- tests/unit/test_mcp_source_client.py | 94 +++++++- 4 files changed, 373 insertions(+), 8 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 1aade6a10e..3f86da29c8 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -81,13 +81,16 @@ client terminal and closes and joins that task before returning, including when request deadline expires while HTTP response data is still arriving. Another client's SDK scope remains independent. A known background transport failure or an expired deadline refuses discovery and result publication, including cached discovery. +Unexpected HTTP status or response media types are terminal before protocol handoff. +Optional GET and DELETE responses with status 405 remain supported. Cancellation publishes no partial read evidence. The transport retains cleanup ownership while checking authority after response headers arrive and before handing the response to the protocol client. Closing a request does not prove that remote processing has stopped. Errors expose bounded error codes rather than upstream content, endpoints or credentials. -An omitted optional mapped cursor ends that listing. Issued cursors are bound to their +Only an omitted optional mapped cursor ends that listing. Every present mapped cursor +must be a nonempty bounded string; an explicit null is refused. Issued cursors are bound to their operation and query, so a cursor from one query cannot authorize another. Reusing a cursor in the same listing is refused even when another listing uses the same text. A successful final page closes that listing operation. It does not establish a deletion diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index ed333fe3bc..58f4df3e4c 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -88,6 +88,28 @@ def _guard_state(deadline: float, failure: ErrorCode | None, *, active: bool = T raise MCPSourceError("timeout") +def _check_response(method: str, response: httpx.Response) -> None: + status = response.status_code + if response.is_redirect or status in {401, 403}: + raise MCPSourceError("denied") + if status == 405 and method in {"GET", "DELETE"}: + return + if method == "DELETE": + if status not in {200, 204}: + raise MCPSourceError("protocol") + return + if method == "POST" and status == 202: + return + if status != 200: + raise MCPSourceError("protocol") + media = response.headers.get("content-type", "").partition(";")[0].strip().lower() + allowed = ( + {"text/event-stream"} if method == "GET" else {"application/json", "text/event-stream"} + ) + if media not in allowed: + raise MCPSourceError("protocol") + + @dataclass(frozen=True) class MCPLimits: timeout_seconds: float = 30 @@ -290,6 +312,9 @@ def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: raise MCPSourceError("schema") +_MISSING_CURSOR = object() + + def _path( value: Any, path: tuple[str, ...] | None, default: Any = "", *, optional: bool = False ) -> Any: @@ -426,8 +451,7 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: await self._authorize() response = await self.inner.handle_async_request(outgoing) await self._authorize() - if response.is_redirect or response.status_code in {401, 403}: - raise MCPSourceError("denied") + _check_response(request.method, response) # Reject compression so the wire budget bounds decoded protocol bytes. if response.headers.get("content-encoding", "identity") != "identity": raise MCPSourceError("protocol") @@ -891,9 +915,10 @@ async def action(session: ClientSession) -> MCPPage: if not isinstance(rows, list): raise MCPSourceError("schema") items = [self._evidence(row, mapping) for row in rows] + next_cursor = _path(result, mapping.next_cursor_path, _MISSING_CURSOR, optional=True) return self._page( items, - _path(result, mapping.next_cursor_path, None, optional=True), + None if next_cursor is _MISSING_CURSOR else _string(next_cursor), ("search", query), ) diff --git a/tests/unit/test_mcp_source_cancellation.py b/tests/unit/test_mcp_source_cancellation.py index 32406b642b..612cd44b77 100644 --- a/tests/unit/test_mcp_source_cancellation.py +++ b/tests/unit/test_mcp_source_cancellation.py @@ -853,6 +853,11 @@ async def aclose(self) -> None: @dataclass class StateRaceFixture(HTTPFixture): pause_at: str = "handoff" + background_status: int = 403 + background_content_type: str = "text/event-stream" + read_status: int = 200 + delete_status: int = 204 + deletes: int = 0 hold_refusal: bool = False refusal_release: asyncio.Event = field(default_factory=asyncio.Event) armed: bool = False @@ -874,9 +879,17 @@ async def reply(self, request: httpx.Request) -> httpx.Response: if self.hold_refusal else RefusalStream(self.denied) ) - return httpx.Response(403, stream=stream) + return httpx.Response( + self.background_status, + stream=stream, + headers={ + "content-type": self.background_content_type, + "x-private-upstream": "synthetic-private-header", + }, + ) if request.method == "DELETE": - return httpx.Response(204) + self.deletes += 1 + return httpx.Response(self.delete_status) response = await super().reply(request) method = json.loads(await request.aread())["method"] if method == "initialize": @@ -885,6 +898,7 @@ async def reply(self, request: httpx.Request) -> httpx.Response: self.initialized.set() elif method in {"resources/read", "tools/call"}: self.acquired = True + response.status_code = self.read_status return response async def authority(self) -> None: @@ -1142,3 +1156,236 @@ async def test_state_guard_refusal_poison_precedes_held_response_cleanup( if not task.done(): task.cancel() await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +@pytest.mark.parametrize("operation", ["discover", "read"]) +@pytest.mark.parametrize( + "status,media", + [ + (404, "text/event-stream"), + (500, "text/event-stream"), + (429, "text/event-stream"), + (200, "application/json"), + (204, "text/event-stream"), + ], +) +async def test_status_cursor_background_failure_poison_precedes_drain( + monkeypatch: pytest.MonkeyPatch, kind: str, operation: str, status: int, media: str +) -> None: + loop = asyncio.get_running_loop() + clock = ManualClock(t=loop.time()) + monkeypatch.setattr(loop, "time", clock.monotonic) + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + kind, + block=False, + phase="sse", + pause_at="operation" if operation == "discover" else "chunk", + hold_refusal=True, + background_status=status, + background_content_type=media, + ) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.3)) + neighbor = HTTPFixture(kind, block=False, phase="sse") + async with ( + source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote, + neighbor.client() as independent, + ): + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task( + remote.discover() if operation == "discover" else remote.read(IDENTITY) + ) + fixture.caller = task + try: + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "protocol" + fixture.resume.set() + clock.advance(0.4) + for _ in range(100): + await asyncio.sleep(0) + if remote._closing: + break + assert remote._closing and not task.done() + assert not fixture.pool_closed.is_set() + evidence = await independent.read(IDENTITY) + assert evidence.receipt is not None and evidence.text == TEXT + fixture.refusal_release.set() + with pytest.raises(source.MCPSourceError) as refusal: + await task + assert str(refusal.value) == "MCP source protocol" + assert fixture.pool_closed.is_set() + if operation == "read": + assert fixture.stopped.is_set() + requests = fixture.requests + with pytest.raises(source.MCPSourceError, match="protocol"): + await remote.discover() + assert fixture.requests == requests + assert remote._transport.requests <= config.limits.max_requests + assert remote._transport.failure == "protocol" + finally: + fixture.resume.set() + fixture.refusal_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_status_cursor_optional_get_and_delete_405_are_allowed( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + kind, block=False, phase="sse", background_status=405, delete_status=405 + ) + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + fixture.checking.set() + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure is None + discovery = await remote.discover() + assert discovery.resources is (kind == "resources") + evidence = await remote.read(IDENTITY) + assert evidence.receipt is not None and evidence.text == TEXT + assert fixture.deletes == 1 + assert fixture.pool_closed.is_set() and fixture.pool_closes == 1 + assert remote._transport.failure is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [405, 201, 204, 206]) +async def test_status_cursor_post_unexpected_status_is_terminal_protocol( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + "resources", block=False, phase="sse", background_status=405, read_status=status + ) + config = fixture.config() + config = replace(config, limits=replace(config.limits, request_seconds=0.1)) + async with source.MCPSourceClient( + config, None, validate_access=fixture.authority, _transport=FixtureTransport(fixture) + ) as remote: + fixture.checking.set() + await asyncio.wait_for(fixture.denied.wait(), 1) + with pytest.raises(source.MCPSourceError, match="protocol"): + await remote.read(IDENTITY) + assert remote._transport is not None and remote._transport.failure == "protocol" + assert fixture.stopped.is_set() and fixture.pool_closed.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [202, 404, 500]) +async def test_status_cursor_delete_unexpected_status_is_not_silently_ignored( + monkeypatch: pytest.MonkeyPatch, status: int +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + "resources", block=False, phase="sse", background_status=405, delete_status=status + ) + with pytest.raises(source.MCPSourceError, match="protocol"): + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + fixture.checking.set() + await asyncio.wait_for(fixture.denied.wait(), 1) + evidence = await remote.read(IDENTITY) + assert evidence.receipt is not None + assert fixture.deletes == 1 and fixture.pool_closed.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_status_cursor_cancellation_identity_survives_held_http_500( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture( + kind, block=False, phase="sse", pause_at="chunk", background_status=500, hold_refusal=True + ) + async with source.MCPSourceClient( + fixture.config(), + None, + validate_access=fixture.authority, + _transport=FixtureTransport(fixture), + ) as remote: + await asyncio.wait_for(fixture.initialized.wait(), 1) + await asyncio.wait_for(fixture.get_started.wait(), 1) + fixture.armed = True + task = asyncio.create_task(remote.read(IDENTITY)) + fixture.caller = task + try: + await asyncio.wait_for(fixture.denied.wait(), 1) + assert remote._transport is not None and remote._transport.failure == "protocol" + task.cancel("original HTTP status cancellation") + await asyncio.wait_for(fixture.stopped.wait(), 1) + task.cancel("repeated HTTP status cancellation") + await asyncio.sleep(0) + assert not task.done() + assert not fixture.pool_closed.is_set() + fixture.refusal_release.set() + with pytest.raises(asyncio.CancelledError) as cancelled: + await task + assert cancelled.value.args == ("original HTTP status cancellation",) + assert fixture.pool_closed.is_set() + assert remote._transport.failure == "protocol" + finally: + fixture.resume.set() + fixture.refusal_release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["resources", "tools"]) +async def test_status_cursor_valid_background_sse_keeps_normal_receipt( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + monkeypatch.setattr(source, "pinned_target", pin) + fixture = StateRaceFixture(kind, block=False, phase="sse") + streaming, closed = asyncio.Event(), asyncio.Event() + + class Background(httpx.AsyncByteStream): + async def __aiter__(self) -> AsyncIterator[bytes]: + streaming.set() + yield b": keepalive\n\n" + await asyncio.Future[None]() + + async def aclose(self) -> None: + closed.set() + + async def reply(request: httpx.Request) -> httpx.Response: + if request.method == "GET": + return httpx.Response( + 200, + stream=Background(), + headers={"content-type": "text/event-stream; charset=utf-8"}, + ) + return await fixture.reply(request) + + transport = FixtureTransport(fixture) + transport.handler = reply + async with source.MCPSourceClient( + fixture.config(), None, validate_access=fixture.authority, _transport=transport + ) as remote: + await asyncio.wait_for(streaming.wait(), 1) + evidence = await remote.read(IDENTITY) + assert evidence.text == TEXT and evidence.receipt is not None + assert remote._transport is not None and remote._transport.failure is None + assert closed.is_set() and fixture.pool_closed.is_set() diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 9d1bd5b034..650f269402 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -132,7 +132,11 @@ async def list_tools(ctx: Any, params: Any) -> types.ListToolsResult: read.input_schema["properties"]["danger"] = dict(STRING) return types.ListToolsResult( tools=[ - types.Tool(name="find", inputSchema=INPUT_SCHEMA, outputSchema=SEARCH_SCHEMA), + types.Tool( + name="find", + inputSchema=INPUT_SCHEMA, + outputSchema=state.get("search_output_schema", SEARCH_SCHEMA), + ), types.Tool( name="fetch", inputSchema=read.input_schema, outputSchema=DOCUMENT_SCHEMA ), @@ -154,6 +158,8 @@ async def call_tool(ctx: Any, params: Any) -> types.CallToolResult: "text": state["text"], } result = {"documents": [document]} if params.name == "find" else document + if params.name == "find": + result.update(state.get("search_extra", {})) if params.name == "find" and state.get("paginate") and "cursor" not in params.arguments: result["cursor"] = state.get("page_cursor", "page-2") return types.CallToolResult(content=[], structuredContent=result) @@ -694,7 +700,7 @@ async def resolve(host: str, **kw: Any) -> tuple[str, str]: async def reply(request: httpx.Request) -> httpx.Response: requests.append(request) - return httpx.Response(200, text="synthetic") + return httpx.Response(200, text="synthetic", headers={"content-type": "text/event-stream"}) monkeypatch.setattr(webhooks, "vet_host", resolve) transport = source._PinnedTransport( @@ -907,3 +913,87 @@ async def authority() -> None: with pytest.raises(source.MCPSourceError, match=code): await remote.search("beta") assert len(state["requests"]) == before + + +@pytest.mark.asyncio +@pytest.mark.parametrize("present", [False, True]) +async def test_status_cursor_null_schema_distinguishes_presence_from_omission( + monkeypatch: pytest.MonkeyPatch, present: bool +) -> None: + conf = paginated_config() + assert conf.search is not None + conf.search.output_schema["properties"]["cursor"] = {"type": "null"} + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = conf.search.output_schema + state["paginate"], state["page_cursor"] = present, None + if present: + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("alpha") + assert state["calls"][-1][0] == "find" + assert remote._owner_task is not None and remote._owner_task.done() + requests = len(state["requests"]) + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("beta") + assert len(state["requests"]) == requests + else: + final = await remote.search("alpha") + assert final.complete and final.next_cursor is None + assert all(item.receipt is None for item in final.items) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "cursor,schema", + [ + (False, {"type": "boolean"}), + (17, {"type": "integer"}), + ([], {"type": "array", "maxItems": 1, "items": STRING}), + ({}, {"type": "object", "additionalProperties": False}), + ("", STRING), + ], +) +async def test_status_cursor_schema_admitted_invalid_values_refuse( + monkeypatch: pytest.MonkeyPatch, cursor: Any, schema: dict[str, Any] +) -> None: + conf = paginated_config() + assert conf.search is not None + conf.search.output_schema["properties"]["cursor"] = schema + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = conf.search.output_schema + state["paginate"], state["page_cursor"] = True, cursor + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("alpha") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("parent,schema", [(None, {"type": "null"}), (17, {"type": "integer"})]) +async def test_status_cursor_malformed_nested_parent_never_counts_as_missing( + monkeypatch: pytest.MonkeyPatch, parent: Any, schema: dict[str, Any] +) -> None: + conf = paginated_config() + assert conf.search is not None + output = copy.deepcopy(conf.search.output_schema) + output["properties"]["page"] = schema + conf = replace( + conf, search=replace(conf.search, output_schema=output, next_cursor_path=("page", "cursor")) + ) + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = output + state["search_extra"] = {"page": parent} + with pytest.raises(source.MCPSourceError, match="schema"): + await remote.search("alpha") + + +@pytest.mark.asyncio +async def test_status_cursor_schema_admitted_string_still_has_normalized_bound( + monkeypatch: pytest.MonkeyPatch, +) -> None: + conf = paginated_config() + assert conf.search is not None + conf.search.output_schema["properties"]["cursor"] = {"type": "string", "maxLength": 4096} + async with synthetic_server(monkeypatch, tools=True) as state, client(conf) as remote: + state["search_output_schema"] = conf.search.output_schema + state["paginate"], state["page_cursor"] = True, "x" * 2049 + with pytest.raises(source.MCPSourceError, match="limit"): + await remote.search("alpha") + assert state["calls"][-1][0] == "find" From b13c0aa16f0a7ee99f009fd30f43ce947fda1305 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 00:02:39 +0000 Subject: [PATCH 07/30] Bind MCP credential origins to the dispatched hostname Use the HTTP client normalization for audience and endpoint checks and refuse pin helpers that change the authorized Host or TLS name. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 4 +- server/clients/mcp_source.py | 22 ++- tests/unit/test_mcp_source_client.py | 225 +++++++++++++++++++++++++ 3 files changed, 244 insertions(+), 7 deletions(-) diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index 3f86da29c8..ff25e330fc 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -27,7 +27,9 @@ and approving the endpoint through operator policy before constructing a client. The transport uses `server/core/webhooks.py` (`pinned_target`) to validate public DNS addresses and preserve the configured Host header and TLS server name while connecting -to a validated address. Proxy environment variables do not select another route. +to a validated address. Endpoint and credential-origin checks use the same HTTPX ASCII +hostname as dispatch. The pinned Host header and TLS server name must match it exactly; +trailing-dot aliases remain distinct. Proxy environment variables do not select another route. Requests outside the configured endpoint are refused. A server response cannot select a different server, credential or connection. diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 58f4df3e4c..0135aee475 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -225,9 +225,9 @@ def _string(value: Any, maximum: int = 2048, *, empty: bool = False) -> str: return value -def _origin(url: str) -> tuple[str, str, int]: - _string(url, 2048) +def _endpoint_url(url: str) -> httpx.URL: try: + _string(url, 2048) parts = urlsplit(url) if ( parts.scheme != "https" @@ -243,11 +243,17 @@ def _origin(url: str) -> tuple[str, str, int]: or any(p in (".", "..") for p in parts.path.split("/")) ): raise MCPSourceError("config") - return parts.scheme, parts.hostname.encode("idna").decode().lower(), parts.port or 443 - except (ValueError, UnicodeError): + # HTTPX must authorize the same ASCII hostname that it sends on the wire. + return httpx.URL(url) + except (httpx.InvalidURL, ValueError, UnicodeError): raise MCPSourceError("config") from None +def _origin(url: str) -> tuple[str, str, int]: + endpoint = _endpoint_url(url) + return endpoint.scheme, endpoint.raw_host.decode("ascii"), endpoint.port or 443 + + # This subset has no references, regular expressions or combinatorial validators. _SCHEMA_KEYS = frozenset({"type", "enum", "const", "title", "description"}) _SCHEMA_TYPE_KEYS = { @@ -365,7 +371,7 @@ def __init__( *, transport: httpx.AsyncBaseTransport | None = None, ) -> None: - self.endpoint = httpx.URL(config.endpoint) + self.endpoint = _endpoint_url(config.endpoint) self.credential, self.deadline, self.limits = credential, deadline, config.limits self.validate_access = validate_access self.inner = ( @@ -411,7 +417,11 @@ async def _handle(self, request: httpx.Request) -> httpx.Response: refusal, pinned, host, sni = await pinned_target( str(self.endpoint), schemes=("https",) ) - if refusal or not host or not sni: + if ( + refusal + or host != self.endpoint.netloc.decode("ascii") + or sni != self.endpoint.raw_host.decode("ascii") + ): raise MCPSourceError("denied") self.target = pinned, host, sni pinned, host, sni = self.target diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 650f269402..4b1858b55e 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -997,3 +997,228 @@ async def test_status_cursor_schema_admitted_string_still_has_normalized_bound( with pytest.raises(source.MCPSourceError, match="limit"): await remote.search("alpha") assert state["calls"][-1][0] == "find" + + +@pytest.mark.parametrize( + "endpoint,audience", + [ + ("https://faß.example/mcp", "https://fass.example/mcp"), + ("https://fass.example/mcp", "https://faß.example/mcp"), + ("https://ς.example/mcp", "https://σ.example/mcp"), + ("https://σ.example/mcp", "https://ς.example/mcp"), + ("https://xn--fa-hia.example/mcp", "https://fass.example/mcp"), + ("https://source.example/mcp", "https://other.example/mcp"), + ("https://source.example./mcp", "https://source.example/mcp"), + ("https://source.example/mcp", "https://source.example./mcp"), + ("https://source.example:444/mcp", "https://source.example:443/mcp"), + ("https://[2001:db8::1]/mcp", "https://[2001:db8::2]/mcp"), + ("https://[2001:0db8:0:0::1]/mcp", "https://[2001:db8::1]/mcp"), + ], +) +@pytest.mark.asyncio +async def test_origin_wire_distinct_hosts_refuse_before_pin_or_dispatch( + monkeypatch: pytest.MonkeyPatch, endpoint: str, audience: str +) -> None: + calls = [] + + async def pin(*args: Any, **kw: Any) -> tuple[str, str, str, str]: + calls.append("pin") + raise AssertionError("invalid binding reached DNS pin") + + async def reply(request: httpx.Request) -> httpx.Response: + calls.append("http") + raise AssertionError("invalid binding reached HTTP") + + monkeypatch.setattr(source, "pinned_target", pin) + async with httpx.MockTransport(reply) as transport: + with pytest.raises(source.MCPSourceError, match="^MCP source config$") as refused: + source.MCPSourceClient( + source.MCPSourceConfig(endpoint, audience), + source.MCPBearer(SECRET, audience), + validate_access=access, + _transport=transport, + ) + assert SECRET not in str(refused.value) + assert calls == [] + + +@pytest.mark.parametrize( + "endpoint,audience,ascii_host,host_header", + [ + (ENDPOINT, ENDPOINT, "source.example", "source.example"), + ("https://SOURCE.EXAMPLE:443/mcp", ENDPOINT, "source.example", "source.example"), + ( + "https://faß.example/mcp", + "https://xn--fa-hia.example/mcp", + "xn--fa-hia.example", + "xn--fa-hia.example", + ), + ( + "https://XN--FA-HIA.EXAMPLE/mcp", + "https://faß.example/mcp", + "xn--fa-hia.example", + "xn--fa-hia.example", + ), + ( + "https://ς.example/mcp", + "https://xn--3xa.example/mcp", + "xn--3xa.example", + "xn--3xa.example", + ), + ( + "https://σ.example/mcp", + "https://XN--4XA.EXAMPLE/mcp", + "xn--4xa.example", + "xn--4xa.example", + ), + ( + "https://BÜCHER.example/mcp", + "https://xn--bcher-kva.example/mcp", + "xn--bcher-kva.example", + "xn--bcher-kva.example", + ), + ( + "https://source.example:8443/mcp", + "https://SOURCE.EXAMPLE:8443/profile", + "source.example", + "source.example:8443", + ), + ( + "https://[2001:db8::1]:443/mcp", + "https://[2001:db8::1]/mcp", + "2001:db8::1", + "[2001:db8::1]", + ), + ], +) +@pytest.mark.asyncio +async def test_origin_canonical_binding_matches_pin_and_actual_dispatch( + monkeypatch: pytest.MonkeyPatch, + endpoint: str, + audience: str, + ascii_host: str, + host_header: str, +) -> None: + from server.core import webhooks + + pins = [] + resolutions = [] + requests = [] + existing_pin = source.pinned_target + + async def resolve(host: str, **kw: Any) -> tuple[str, str]: + resolutions.append((host, kw)) + return "", "93.184.216.34" + + async def pin(url: str, **kw: Any) -> tuple[str, str, str, str]: + pins.append(url) + assert httpx.URL(url).raw_host == ascii_host.encode("ascii") + assert url.isascii() + return await existing_pin(url, **kw) + + async def reply(request: httpx.Request) -> httpx.Response: + requests.append(request) + assert pins and resolutions + assert request.headers["host"] == host_header + assert request.extensions["sni_hostname"] == ascii_host + assert request.headers["authorization"] == "Bearer " + SECRET + assert request.url.raw_host == b"93.184.216.34" + return httpx.Response( + 200, headers={"content-type": "text/event-stream"}, content=b": ok\n\n" + ) + + monkeypatch.setattr(webhooks, "vet_host", resolve) + monkeypatch.setattr(source, "pinned_target", pin) + conf = source.MCPSourceConfig(endpoint, audience) + credential = source.MCPBearer(SECRET, audience) + admitted = source.MCPSourceClient(conf, credential, validate_access=access) + assert source._origin(endpoint) == ("https", ascii_host, httpx.URL(endpoint).port or 443) + transport = source._PinnedTransport( + admitted.config, + admitted.credential, + asyncio.get_running_loop().time() + 5, + access, + transport=httpx.MockTransport(reply), + ) + async with httpx.AsyncClient(transport=transport, trust_env=False) as http: + response = await http.get(endpoint) + assert response.content == b": ok\n\n" + assert pins == [str(httpx.URL(endpoint))] + assert resolutions == [(ascii_host, {"allow_private": False, "name_address": False})] + assert len(requests) == 1 + assert admitted.config.endpoint == endpoint + assert admitted.config.bearer_audience == audience + + +@pytest.mark.parametrize( + "endpoint", + [ + "https://\ud800.example/mcp", + "https://☃.example/mcp", + "https://[broken]/mcp", + "https://source.example:bad/mcp", + "https://source.example:65536/mcp", + "https://source.example:0/mcp", + "https://@source.example/mcp", + "https://source.example/mcp?private", + "https://source.example/mcp#private", + "https://source.example/./mcp", + "https://source.example/%2e/mcp", + "https://source.example/white space", + "https://source.example/\tprivate", + "https://source.example/\x7fprivate", + ], +) +def test_origin_bad_urls_have_only_fixed_private_failures(endpoint: str) -> None: + with pytest.raises(source.MCPSourceError) as refused: + source.MCPSourceClient( + source.MCPSourceConfig(endpoint, endpoint), + source.MCPBearer(SECRET, endpoint), + validate_access=access, + ) + assert str(refused.value) in {"MCP source " + code for code in ("config", "schema", "limit")} + assert SECRET not in str(refused.value) + + +@pytest.mark.parametrize( + "endpoint,pinned_host,pinned_sni", + [ + (ENDPOINT, "other.example", "source.example"), + (ENDPOINT, "source.example", "other.example"), + (ENDPOINT, "source.example:444", "source.example"), + ("https://source.example./mcp", "source.example", "source.example"), + ], +) +@pytest.mark.asyncio +async def test_origin_pin_alias_refuses_before_credential_dispatch( + monkeypatch: pytest.MonkeyPatch, endpoint: str, pinned_host: str, pinned_sni: str +) -> None: + requests = [] + pins = [] + + async def pin(url: str, **kw: Any) -> tuple[str, str, str, str]: + pins.append(url) + return "", "https://93.184.216.34/mcp", pinned_host, pinned_sni + + async def reply(request: httpx.Request) -> httpx.Response: + requests.append(request) + return httpx.Response(200, headers={"content-type": "text/event-stream"}) + + monkeypatch.setattr(source, "pinned_target", pin) + conf = source.MCPSourceConfig(endpoint, endpoint) + credential = source.MCPBearer(SECRET, endpoint) + admitted = source.MCPSourceClient(conf, credential, validate_access=access) + assert source._origin(endpoint)[1] == httpx.URL(endpoint).raw_host.decode("ascii") + transport = source._PinnedTransport( + admitted.config, + admitted.credential, + asyncio.get_running_loop().time() + 5, + access, + transport=httpx.MockTransport(reply), + ) + async with httpx.AsyncClient(transport=transport, trust_env=False) as http: + with pytest.raises(source.MCPSourceError, match="^MCP source denied$"): + await http.get(endpoint) + assert pins == [str(httpx.URL(endpoint))] + assert requests == [] + assert transport.failure == "denied" From 1702f99585d1a9b64856b28e06469d51f32b5723 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 00:23:30 +0000 Subject: [PATCH 08/30] Preserve MCP source identity through owner cleanup and restore Keep versioned payloads opaque, include source-only history in scoped erasure and qualify restore and key rotation on isolated hosted stores. Signed-off-by: zlareb1 --- .github/workflows/ci.yml | 1 + .github/workflows/mcp-source-lifecycle.yml | 157 +++ docs/architecture/mcp-source-lifecycle.md | 123 +++ .../migrations/116_mcp_source_lifecycle.sql | 3 + scripts/gates/mcp_source_lifecycle.py | 691 +++++++++++++ server/erasure/store/census.py | 18 +- server/knowledge/app/connected_accounts.py | 127 ++- server/knowledge/app/connected_restore.py | 120 ++- server/knowledge/app/source_access.py | 18 +- server/knowledge/app/sources.py | 12 + server/knowledge/domain/connected_accounts.py | 20 + server/knowledge/domain/mcp_sources.py | 216 ++++ server/knowledge/domain/sources.py | 30 +- server/knowledge/store/source_access.py | 3 +- server/knowledge/store/sources.py | 101 +- .../test_mcp_source_lifecycle_ch.py | 940 ++++++++++++++++++ tests/unit/test_mcp_connection_lifecycle.py | 619 ++++++++++++ tests/unit/test_mcp_source_contract.py | 284 ++++++ tests/unit/test_mcp_source_lifecycle.py | 208 ++++ .../test_mcp_source_lifecycle_diagnostics.py | 52 + tests/unit/test_mcp_source_read_gate.py | 174 ++++ tests/unit/test_schema_baseline.py | 1 + 22 files changed, 3838 insertions(+), 80 deletions(-) create mode 100644 .github/workflows/mcp-source-lifecycle.yml create mode 100644 docs/architecture/mcp-source-lifecycle.md create mode 100644 schemas/migrations/116_mcp_source_lifecycle.sql create mode 100644 scripts/gates/mcp_source_lifecycle.py create mode 100644 server/knowledge/domain/mcp_sources.py create mode 100644 tests/integration/test_mcp_source_lifecycle_ch.py create mode 100644 tests/unit/test_mcp_connection_lifecycle.py create mode 100644 tests/unit/test_mcp_source_contract.py create mode 100644 tests/unit/test_mcp_source_lifecycle.py create mode 100644 tests/unit/test_mcp_source_lifecycle_diagnostics.py create mode 100644 tests/unit/test_mcp_source_read_gate.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index bad7d30157..be00082dd5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1033,6 +1033,7 @@ jobs: tests/integration/test_knowledge_ingest_queue.py tests/integration/test_knowledge_sharing.py tests/integration/test_knowledge_restore.py + tests/integration/test_mcp_source_lifecycle_ch.py tests/integration/test_restored_memory_ids.py tests/integration/test_memory_import.py tests/integration/test_cross_principal_leakage.py diff --git a/.github/workflows/mcp-source-lifecycle.yml b/.github/workflows/mcp-source-lifecycle.yml new file mode 100644 index 0000000000..e053e2e84e --- /dev/null +++ b/.github/workflows/mcp-source-lifecycle.yml @@ -0,0 +1,157 @@ +name: MCP source lifecycle + +on: + pull_request: + paths: + - .github/workflows/mcp-source-lifecycle.yml + - scripts/gates/mcp_source_lifecycle.py + - server/knowledge/** + - server/erasure/app/connected_accounts.py + - server/erasure/store/census.py + - server/auth/claims.py + - server/core/** + - server/cli/_ch.py + - schemas/** + - dev/ci_start_clickhouse.sh + - dev/ci_start_postgres.sh + - dev/clickhouse_release.sh + - tests/integration/test_mcp_source_lifecycle_ch.py + - pyproject.toml + - uv.lock + workflow_dispatch: + +permissions: + contents: read + +env: + PYTHON_VERSION: "3.12" + UV_VERSION: "0.12.19" + +jobs: + clickhouse: + name: Resolve the ClickHouse release + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + image: ${{ steps.resolve.outputs.image }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: /dev/clickhouse_release.sh + sparse-checkout-cone-mode: false + - id: resolve + run: | + image=$(bash dev/clickhouse_release.sh) + echo "image=$image" >> "$GITHUB_OUTPUT" + + restore: + name: Offline source restore (${{ matrix.authority }}) + needs: clickhouse + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + include: + - authority: clickhouse + pg_dsn: "" + - authority: postgres + pg_dsn: postgres://loom:loomdev@127.0.0.1:5432/loom + env: + LOOM_CLICKHOUSE_IMAGE: ${{ needs.clickhouse.outputs.image }} + LOOM_CH_CONTAINER: loom-mcp-lifecycle-ch + LOOM_CH_HOST: 127.0.0.1 + LOOM_CH_PORT: "8123" + LOOM_CH_USER: loom + LOOM_CH_READER_USER: loom_reader + LOOM_CH_PASSWORD: loomdev + LOOM_CH_DATABASE: loom + LOOM_CH_SECURE: "false" + LOOM_PG_CONTAINER: loom-mcp-lifecycle-pg + LOOM_PG_IMAGE: postgres:16 + LOOM_PG_STANDBY: "1" + LOOM_PG_DSN: ${{ matrix.pg_dsn }} + LOOM_STORAGE_AUTHORITY: ${{ matrix.authority }} + LOOM_AUTH_REQUIRED: "false" + LOOM_JWT_SECRET: ci-only-mcp-lifecycle-fixture + LOOM_LLM_PROVIDER: fake + LOOM_EMBEDDING_MODEL: fake-ngram-1024 + LOOM_BACKGROUND_WORKERS: "off" + LOOM_BOOT_MIGRATE: "true" + LOOM_ENV_FILE: "" + LOOM_MCP_SOURCE_LIFECYCLE_FIXTURE: offline-isolated + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: | + server + scripts + schemas + dev + deploy + sdk + extractor + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + id: python + with: + python-version: ${{ env.PYTHON_VERSION }} + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: ${{ env.UV_VERSION }} + enable-cache: true + cache-dependency-glob: uv.lock + - name: Install the locked development dependencies + run: | + uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code + echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + - name: Refuse preexisting fixture containers + run: | + for container in "$LOOM_CH_CONTAINER" "$LOOM_PG_CONTAINER" "$LOOM_PG_CONTAINER-standby"; do + if docker container inspect "$container" >/dev/null 2>&1; then + echo "fixture container already exists" + exit 1 + fi + done + - name: Start the owned ClickHouse with Keeper + id: clickhouse + run: bash dev/ci_start_clickhouse.sh + - name: Start the owned synchronous Postgres fixture + id: postgres + if: matrix.authority == 'postgres' + run: bash dev/ci_start_postgres.sh + - name: Apply the normal ClickHouse migration journal + run: python -m server.core.schema.migrate + # The script initializes/verifies the selected authority; it starts no service or worker. + - name: Qualify full offline source restoration + run: >- + python -m scripts.gates.mcp_source_lifecycle --isolated-fixture + --result "$RUNNER_TEMP/mcp-source-lifecycle-${{ matrix.authority }}.json" + - name: Upload the bounded redacted qualification result + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mcp-source-lifecycle-${{ matrix.authority }} + path: ${{ runner.temp }}/mcp-source-lifecycle-${{ matrix.authority }}.json + if-no-files-found: error + retention-days: 7 + - name: Stop only this job's fixture containers + if: always() + run: | + cleanup_status=0 + stop_owned() { + if docker container inspect "$1" >/dev/null 2>&1; then + docker stop --time 10 "$1" || cleanup_status=1 + elif [ "$2" = 'success' ]; then + cleanup_status=1 + fi + } + if [ '${{ steps.clickhouse.outcome }}' != 'skipped' ] && [ '${{ steps.clickhouse.outcome }}' != '' ]; then + stop_owned "$LOOM_CH_CONTAINER" '${{ steps.clickhouse.outcome }}' + fi + if [ '${{ steps.postgres.outcome }}' != 'skipped' ] && [ '${{ steps.postgres.outcome }}' != '' ]; then + stop_owned "$LOOM_PG_CONTAINER-standby" '${{ steps.postgres.outcome }}' + stop_owned "$LOOM_PG_CONTAINER" '${{ steps.postgres.outcome }}' + fi + exit "$cleanup_status" diff --git a/docs/architecture/mcp-source-lifecycle.md b/docs/architecture/mcp-source-lifecycle.md new file mode 100644 index 0000000000..f2253acdf1 --- /dev/null +++ b/docs/architecture/mcp-source-lifecycle.md @@ -0,0 +1,123 @@ +# MCP source lifecycle format + +MCP source metadata uses the existing connected-account and document-source stores. +The format preserves connection identity and opaque source payloads during lifecycle +work. It grants no source execution, document access or publication authority. +The [outbound client](https://github.com/ClickHouse/loom/pull/1194) handles protocol reads separately. +All exposed operations belong to Loom's existing operations registry and inbound +MCP endpoint; an external source is an outbound connection. + +## Identity and storage authority + +A connection belongs to one organization and canonical authenticated owner. Its +account kind is an opaque slot, `mcp:` followed by 32 lowercase hexadecimal digits. +The existing account key is `(org, subject, kind)`; a single account kind named `mcp` +would collapse independent connections. The account's existing connection generation +and durable fence distinguish a current binding from stopped historical bindings. +A slot is not a remote user, tenant, workspace or verified email identity. + +The versioned connection envelope binds organization, owner, slot, generation, +approved profile identity and digest, endpoint and credential audience. Bearer +material is excluded from ordinary serialization and repr. Explicit envelope encoding +produces only the plaintext intended for the existing connected-account sealing +purpose. The codec admits anonymous or preissued-bearer shapes; it performs no +network access, endpoint approval, authorization enrollment or token refresh. +The existing stores remain the authority for encrypted account rows and fencing. +There is no second credential vault or connection registry. + +A source retains its ordinary organization, namespace, name and source ID. The +additive `connection_slot` and `source_contract_version` columns permit lifecycle +inventory without opening credentials or parsing source content. Native rows use +an empty slot and version zero. An MCP source uses kind `mcp`, credential mode `mcp` +and a known version, with an explicit connection generation and approved profile +binding. Those markers describe storage; they do not admit execution. + +The source contract splits metadata into `config_json` and its ordered, unique +resource selection into `items_json`. The selected identities have one stored +representation. IDs are opaque and scoped by the connection binding. They cannot +select a different owner, endpoint or tool. The codec bounds the envelope, selection +and individual UTF-8 IDs, refuses unknown fields and versions, and returns a fixed +error that excludes the supplied payload. Its reader-policy field is a declaration +requiring separate authorization, never a grant. + +## Unknown formats and lifecycle writes + +A nonzero contract version, MCP kind or MCP credential mode makes a row opaque to +native source codecs. Loading it retains the exact config and item strings, including +unknown versions or invalid JSON. Complete row writes preserve both strings and the +slot, version, source identity, owner, generation and encrypted columns. Lifecycle +work must not normalize an unknown payload into an empty native configuration. +The raw fields are excluded from repr and public source detail projections. + +Native serving, mirror synchronization, source management and checked source access +refuse opaque rows. The access path repeats the discriminator check after loading a +connected source; current standing also refuses an unknown format before secret use +and after rereading the registration. No native connector is an MCP fallback. +This format alone supplies no generic read authority. + +Account lifecycle matching compares organization, owner and exact account kind or +MCP slot. Stopping one slot cannot select every source with kind `mcp`. Existing +account-before-namespace lease order, connection fences and retirement records remain +in use. Historical selectors and residue counts inspect raw versions, including +bindings hidden by the latest row. Owner cleanup and restore inventory can discover +source-only history without a decryptable account row or a current approved profile. +Malformed slot keys refuse; cleanup never guesses a slot from opaque JSON. + +Owner erasure inventories account and raw source-history identities, including an +owner with no surviving account row. It resolves verified aliases per organization, +preflights selected historical generations, then rereads standing under each account +lease before fencing and retirement. Explicit organization scope remains in force. +A permanent cutoff permits source-only cleanup; a dated cutoff cannot establish an +unknown connection's age and refuses. A lifted cutoff or newer current account is +preserved. This scoped deletion path shares per-owner lifecycle primitives with +restore; it never invokes deployment-wide offline restore. Remote revocation follows +all local cleanup. + +Disconnect and explicit erasure retain their existing meanings. Local bearer removal +does not prove remote token revocation. Restore is destructive offline lifecycle +work with fencing and a final census; it is not a reconfiguration or upgrade tool. +No migration deletes documents, originals, uploads, credentials, checkpoints or history. + +## Admission and upgrades + +The additive schema and lifecycle-aware build are preparation. They add no public +connection creation, MCP source registration, source worker dispatch or runtime +activation. No wire field is removed, so there is no `ignored_args` change. +Native operations continue under their existing contracts. + +The preceding build does not understand generic slot cleanup or preserve the new +fields in a complete replacement write. Therefore applying the schema is insufficient +permission to persist generic authority. A later admission path must require the +lifecycle-aware build across every live deployment before creating or rebinding a +connection or source. It must also establish a maintenance and rollback floor for +standalone erasure, reseal and restore tools, which deployment heartbeats cannot fence. +Mixed-version tests must distinguish execution refusal from lifecycle compatibility. + +The final replacement must retain native registrations as nonexecuting reconfiguration +metadata, preserve stored content and require an owner-authorized MCP binding. It must +not infer endpoints, reuse native credentials at a different audience or invoke source +removal, disconnect or restore as upgrade cleanup. Operator cutover is separate from +schema installation. Rollback after generic writes must retain lifecycle-aware tools. + +## Access, retrieval and provenance boundary + +Live retrieval uses the existing protected live-search path and writes no imported +knowledge or memory. Selected snapshot and refresh use the existing knowledge, +original, extraction, chunk, indexing, accounting and erasure paths with current +connection and selection checks. A persisted source identity must retain connection +and resource binding separately from its display citation. A citation is never +permission to fetch another endpoint. + +Missing upstream ACL evidence defaults personal imports to owner-only access at every +read, cache, export, derived-result and delivery boundary. A team destination grants +no private-source authority. Intentional collection-copy publication requires explicit +source-sharing authority, current destination grants and disclosure that upstream +permissions are not mirrored. Preview explains current effective access and capability +limits; mutation and delivery revalidate them. Ordinary collection inheritance and the +automatic personal-namespace restriction remain in force. + +Standard resource and tool capabilities do not prove complete enumeration, deletion, +revision history or reader permissions. Partial pages, errors and notifications cannot +retire content. Continuous synchronization needs its own qualified evidence contract; +a selected refresh must name that narrower behavior. These access and execution paths +require separate implementation and hosted qualification before generic admission. diff --git a/schemas/migrations/116_mcp_source_lifecycle.sql b/schemas/migrations/116_mcp_source_lifecycle.sql new file mode 100644 index 0000000000..d6a6fae5e5 --- /dev/null +++ b/schemas/migrations/116_mcp_source_lifecycle.sql @@ -0,0 +1,3 @@ +-- Lifecycle cleanup identifies a connection without decoding its private payload. +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS connection_slot String DEFAULT ''; +ALTER TABLE loom.knowledge_sources ADD COLUMN IF NOT EXISTS source_contract_version UInt16 DEFAULT 0; diff --git a/scripts/gates/mcp_source_lifecycle.py b/scripts/gates/mcp_source_lifecycle.py new file mode 100644 index 0000000000..ceb003dc26 --- /dev/null +++ b/scripts/gates/mcp_source_lifecycle.py @@ -0,0 +1,691 @@ +"""Qualify offline source restoration only in a dedicated disposable CI deployment.""" + +from __future__ import annotations + +import argparse +import asyncio +import json +import logging +import os +import re +import sys +from dataclasses import dataclass, field, replace +from hashlib import sha256 +from pathlib import Path +from typing import Any +from unittest.mock import patch +from uuid import uuid4 + +_LIMIT = 512 +_FIXTURE_KEY = "ci-only-mcp-lifecycle-fixture" +_ROTATED_KEY = "ci-only-mcp-lifecycle-rotated-fixture" +_PROFILE_ID = "offline-lifecycle-profile" +_PROFILE_DIGEST = sha256(b"offline-lifecycle-profile-v1").hexdigest() +_ENDPOINT = "https://source.example.test/mcp" +_TABLES = { + "connected_accounts": "org, subject, kind, version", + "knowledge_sources": "org, namespace, name, version", + "knowledge_mirrors": "org, namespace, mirror, version", + "code_index_state": "org, namespace, state_key, version", + "oauth_signin_state": "claim_key", +} + + +def require(condition: bool) -> None: + if not condition: + raise AssertionError("MCP_LIFECYCLE_QUALIFICATION_FAILED") + + +def fixture_guard(opt_in: bool, result: Path) -> str: + expected = { + "GITHUB_ACTIONS": "true", + "GITHUB_WORKFLOW": "MCP source lifecycle", + "LOOM_MCP_SOURCE_LIFECYCLE_FIXTURE": "offline-isolated", + "LOOM_CH_HOST": "127.0.0.1", + "LOOM_CH_PORT": "8123", + "LOOM_CH_USER": "loom", + "LOOM_CH_PASSWORD": "loomdev", + "LOOM_CH_DATABASE": "loom", + "LOOM_CH_SECURE": "false", + "LOOM_JWT_SECRET": _FIXTURE_KEY, + "LOOM_AUTH_REQUIRED": "false", + "LOOM_LLM_PROVIDER": "fake", + "LOOM_EMBEDDING_MODEL": "fake-ngram-1024", + "LOOM_BACKGROUND_WORKERS": "off", + "LOOM_BOOT_MIGRATE": "true", + } + require(opt_in and all(os.environ.get(k) == v for k, v in expected.items())) + authority = os.environ.get("LOOM_STORAGE_AUTHORITY", "") + require(authority in {"clickhouse", "postgres"}) + require( + os.environ.get("LOOM_PG_DSN", "") + == ("postgres://loom:loomdev@127.0.0.1:5432/loom" if authority == "postgres" else "") + ) + require(not os.environ.get("LOOM_BASE_URL") and not os.environ.get("LOOM_CELL")) + root = Path(os.environ["RUNNER_TEMP"]).resolve() + require(result.resolve().parent == root and not result.exists()) + return authority + + +async def count(ch: Any, table: str) -> int: + require(re.fullmatch(r"[a-z_][a-z0-9_]*", table) is not None) + row = await ch.query_one(f"SELECT count() AS n FROM loom.{table}") + require(row is not None and "n" in row) + return int(row["n"]) + + +async def owned_stores(ch: Any, orgs: tuple[str, ...], *, pg_ready: bool = True) -> None: + """Count foreign rows before global maintenance; never read their content.""" + from server.core import pg + from server.knowledge.app.connected_restore import offline_refusal + + require(not await offline_refusal(ch)) + require(await count(ch, "instances") == 0 and await count(ch, "worker_status") == 0) + tables = await ch.query_all( + "SELECT DISTINCT c.table AS table_name FROM system.columns AS c " + "INNER JOIN system.tables AS t ON c.database = t.database AND c.table = t.name " + "WHERE c.database = 'loom' AND c.name = 'org' " + "AND t.engine NOT IN ('View', 'MaterializedView', 'Dictionary') " + "ORDER BY table_name LIMIT 513" + ) + require(0 < len(tables) <= _LIMIT) + for table in tables: + name = table["table_name"] + require(re.fullmatch(r"[a-z_][a-z0-9_]*", name) is not None) + row = await ch.query_one( + f"SELECT count() AS n FROM loom.{name} " + "WHERE org NOT IN {orgs:Array(String)} OR isNull(org)", + params={"orgs": list(orgs)}, + ) + require(row is not None and row["n"] == 0) + if pg.enabled() and pg_ready: + # The disposable fixture's migration role must see every row despite RLS. + require( + bool( + await pg.fetchval( + "SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user" + ) + ) + ) + tables = await pg.fetch( + "SELECT DISTINCT c.table_name AS table_name FROM information_schema.columns c " + "JOIN information_schema.tables t USING (table_catalog, table_schema, table_name) " + "WHERE c.table_schema = 'loom' AND c.column_name = 'org' " + "AND t.table_type = 'BASE TABLE' ORDER BY table_name LIMIT 513" + ) + require(0 < len(tables) <= _LIMIT) + for table in tables: + name = table["table_name"] + require(re.fullmatch(r"[a-z_][a-z0-9_]*", name) is not None) + require( + await pg.fetchval( + f"SELECT count(*) FROM loom.{name} WHERE org <> ALL($1::text[]) OR org IS NULL", + list(orgs), + ) + == 0 + ) + + +async def snapshot(ch: Any) -> dict[str, list[dict[str, Any]]]: + out = {} + for table, order in _TABLES.items(): + rows = await ch.query_all(f"SELECT * FROM loom.{table} ORDER BY {order} LIMIT 129") + require(len(rows) < 129) + out[table] = rows + return out + + +@dataclass +class Fixture: + orgs: tuple[str, str] + accounts: list[Any] = field(default_factory=list) + sources: list[dict[str, Any]] = field(default_factory=list) + connections: dict[str, tuple[str, str, str]] = field(default_factory=dict) + mirrors: dict[tuple[str, str], str] = field(default_factory=dict) + envelope_plaintext: str = field(default="", repr=False) + + def connection(self, owner: tuple[str, str, str], *, inactive: bool = False) -> str: + from server.knowledge.app import connected_accounts as accounts + + value = accounts._next_connection(inactive=inactive) + self.connections[value] = owner + return value + + def source( + self, + owner: tuple[str, str, str], + connection: str, + name: str, + namespace: str = "selected", + *, + active: bool = True, + ) -> None: + org, subject, slot = owner + native = slot == "gdrive" + self.sources.append( + { + "org": org, + "namespace": namespace, + "name": name, + "source_id": str(uuid4()), + "kind": "", + "source_kind": "gdrive" if native else "mcp", + "config_json": "{}" if native else '{ "unknown-contract": ', + "items_json": "[]" if native else '[ {"opaque-resource": ', + "credential_mode": "connected" if native else "mcp", + "access": "mirrored", + "owner_subject": subject, + "connection_slot": "" if native else slot, + "connection_id": connection, + "source_contract_version": 0 if native else 65535, + "credential_enc": "unreadable-fixture-source-envelope", + "secret_enc": "", + "created_by": subject, + "active": active, + "pending_delete": False, + "version": 1, + } + ) + self.mirrors.setdefault((org, namespace), "acl-" + uuid4().hex[:24]) + + @property + def target(self) -> tuple[str, str, str]: + return self.orgs[0], "owner-a", "mcp:" + "a" * 32 + + def prepare(self) -> None: + from pydantic import SecretStr + + from server.core.secrets_at_rest import seal + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.domain.connected_accounts import ConnectedAccount + from server.knowledge.domain.mcp_sources import ConnectionEnvelope, encode_envelope + + a, b = self.orgs + owners = [ + self.target, + (a, "owner-a", "mcp:" + "b" * 32), + (a, "owner-b", "mcp:" + "a" * 32), + (a, "owner-z", "gdrive"), + (b, "owner-a", "mcp:" + "a" * 32), + ] + for index, owner in enumerate(owners): + generation = self.connection(owner) + credential = "unreadable-fixture-account-envelope" + if owner == self.target: + self.envelope_plaintext = encode_envelope( + ConnectionEnvelope( + version=1, + org=owner[0], + owner=owner[1], + slot=owner[2], + generation=generation, + profile_id=_PROFILE_ID, + profile_sha256=_PROFILE_DIGEST, + endpoint=_ENDPOINT, + audience=_ENDPOINT, + auth="bearer", + bearer=SecretStr(uuid4().hex), + ) + ) + credential = seal(accounts.CREDENTIAL_PURPOSE, self.envelope_plaintext) + self.accounts.append( + ConnectedAccount( + *owner, + generation, + credential_enc=credential, + active=True, + ) + ) + self.source(owner, generation, f"current-{index}", active=owner[2] != "gdrive") + previous = self.connection(self.target, inactive=True) + self.source(self.target, previous, "previous", "historical", active=False) + orphan = (a, "owner-a", "mcp:" + "c" * 32) + for index in range(2): + generation = self.connection(orphan, inactive=index == 0) + self.source(orphan, generation, f"source-only-{index}", active=index == 1) + + async def seed(self, ch: Any) -> None: + from server.auth import claims + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.app.sources import sources_lease + from server.knowledge.store import connected_accounts as account_store + from server.knowledge.store import mirrors, sources + + for generation, owner in self.connections.items(): + async with accounts.account_lease(*owner): + key = accounts._fence_key(generation) + require(await claims.get(ch, key) is None) + await accounts._move_fence(None, generation, ch=ch) + for account in self.accounts: + async with accounts.account_lease(account.org, account.subject, account.kind): + await account_store.put(account) + for (org, namespace), mirror in self.mirrors.items(): + async with sources_lease(org, namespace): + await mirrors.add_mirror(org, namespace, mirror) + for row in self.sources: + slot = row["connection_slot"] or row["source_kind"] + async with accounts.account_lease(row["org"], row["owner_subject"], slot): + async with sources_lease(row["org"], row["namespace"]): + await ch.insert("loom.knowledge_sources", [row]) + orphan = self.orgs[0], "owner-a", "mcp:" + "c" * 32 + require(await account_store.restore_keys(owner=orphan) == []) + history = await sources.connected_history(owner=orphan) + require( + {s.connection_id for s in history} + == {g for g, owner in self.connections.items() if owner == orphan} + ) + + async def claims_owned(self, ch: Any, *, stopped: bool = False) -> dict[str, str]: + from server.auth import claims + from server.knowledge.app import connected_accounts as accounts + + expected = {accounts._fence_key(g) for g in self.connections} + rows = await ch.query_all("SELECT claim_key FROM loom.oauth_signin_state LIMIT 129") + require({r["claim_key"] for r in rows} == expected) + out = {} + for generation in self.connections: + key = accounts._fence_key(generation) + observed = await claims.get(ch, key) + require(observed is not None and accounts._fence_key(observed) == key) + if stopped: + require(observed.partition("/")[2].startswith("0")) + out[key] = observed + return out + + def retirement(self, row: dict[str, Any]) -> Any: + from server.knowledge.store.source_retirements import Retirement + + return Retirement( + row["org"], + row["namespace"], + row["name"], + row["source_id"], + row["source_kind"], + self.mirrors[row["org"], row["namespace"]], + ) + + async def retirement_pending(self, ch: Any, source: dict[str, Any]) -> None: + from server.knowledge.store import source_retirements + + item = self.retirement(source) + require(await source_retirements.pending(item)) + row = await ch.query_one( + "SELECT state_value, detail FROM loom.code_index_state FINAL " + "WHERE org = {org:String} AND namespace = {mirror:String} " + "AND state_key = {key:String} LIMIT 1", + params={"org": item.org, "mirror": item.mirror, "key": item.key}, + ) + require(row is not None and row["state_value"] == "pending") + require( + json.loads(row["detail"]) + == { + "namespace": source["namespace"], + "name": source["name"], + "source_id": source["source_id"], + "kind": source["source_kind"], + } + ) + + async def boundary(self, ch: Any, ended: Any) -> None: + from server.auth import claims + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.store import connected_accounts as account_store + from server.knowledge.store import sources + + require((ended.org, ended.subject, ended.kind) == self.target) + marker = await account_store.get(*self.target) + require(marker is not None and not marker.active and not marker.credential_enc) + require((marker.org, marker.subject, marker.kind) == self.target) + require(marker.connection_id == ended.connection_id and marker.connected_at is None) + require(marker.disconnected_at is not None) + require(not marker.account_id and not marker.workspace_id and not marker.account_email_enc) + require(not marker.scopes and not marker.refresh_id) + for generation, owner in self.connections.items(): + observed = await claims.get(ch, accounts._fence_key(generation)) + require(observed is not None) + if owner == self.target: + require(observed.partition("/")[2].startswith("0")) + else: + require(observed == generation) + for row in self.sources: + slot = row["connection_slot"] or row["source_kind"] + if (row["org"], row["owner_subject"], slot) != self.target: + continue + current = await sources.latest_source(row["org"], row["namespace"], row["name"]) + require(current is not None and not current.active and current.pending_delete) + require( + current.source_id == row["source_id"] + and not current.credential_enc + and not current.secret_enc + ) + require( + ( + current.org, + current.namespace, + current.owner_subject, + current.connection_slot, + current.connection_id, + ) + == ( + row["org"], + row["namespace"], + row["owner_subject"], + row["connection_slot"], + row["connection_id"], + ) + ) + require(current.generic_config_json == row["config_json"]) + require(current.generic_items_json == row["items_json"]) + require(current.source_contract_version == row["source_contract_version"]) + await self.retirement_pending(ch, row) + + +async def current_accounts(ch: Any, fixture: Fixture) -> dict[tuple[str, str, str], Any]: + from server.knowledge.store import connected_accounts as account_store + + rows = {} + for account in fixture.accounts: + key = account.org, account.subject, account.kind + current = await account_store.get(*key, ch=ch) + require(current is not None) + rows[key] = current + return rows + + +async def reseal_rotation( + ch: Any, + fixture: Fixture, + current_key: str, + previous_key: str, + client_attempts: list[None], +) -> None: + from server.core.secrets_at_rest import unseal + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.domain.mcp_sources import bind_envelope, decode_envelope + from server.settings import settings + + before = await current_accounts(ch, fixture) + raw_before = await snapshot(ch) + fences = await fixture.claims_owned(ch) + missing = sorted("/".join(key) for key in before if key != fixture.target) + require(len(missing) == 4) + with ( + patch.object(settings, "jwt_secret", current_key), + patch.object(settings, "jwt_secret_previous", previous_key), + ): + candidates, unreadable = await accounts.reseal_registry( + "credential_enc", accounts.CREDENTIAL_PURPOSE, dry_run=True, ch=ch + ) + require(not client_attempts and candidates == 1 and sorted(unreadable) == missing) + require(await current_accounts(ch, fixture) == before) + require(await fixture.claims_owned(ch) == fences) + raw_dry_run = await snapshot(ch) + require(all(raw_dry_run[t] == raw_before[t] for t in _TABLES if t != "connected_accounts")) + + candidates, unreadable = await accounts.reseal_registry( + "credential_enc", accounts.CREDENTIAL_PURPOSE, dry_run=False, ch=ch + ) + require(not client_attempts and candidates == 1 and sorted(unreadable) == missing) + after = await current_accounts(ch, fixture) + old, new = before[fixture.target], after[fixture.target] + require(new.credential_enc != old.credential_enc and new.version > old.version) + require(replace(new, credential_enc=old.credential_enc, version=old.version) == old) + require(all(after[key] == value for key, value in before.items() if key != fixture.target)) + require(await fixture.claims_owned(ch) == fences) + raw_after = await snapshot(ch) + require(all(raw_after[t] == raw_before[t] for t in _TABLES if t != "connected_accounts")) + # Removing the fallback key proves that the new current key opens the envelope. + with patch.object(settings, "jwt_secret_previous", ""): + plaintext = unseal(accounts.CREDENTIAL_PURPOSE, new.credential_enc, warn=False) + require(bool(plaintext) and plaintext == fixture.envelope_plaintext) + envelope = decode_envelope(plaintext) + require(envelope.auth == "bearer" and envelope.bearer is not None) + bind_envelope( + envelope, + org=new.org, + owner=new.subject, + slot=new.kind, + generation=new.connection_id, + profile_id=_PROFILE_ID, + profile_sha256=_PROFILE_DIGEST, + endpoint=_ENDPOINT, + audience=_ENDPOINT, + ) + + +class FixtureInterrupted(RuntimeError): + """The single injected failure occurs before physical erasure, after real retirement.""" + + +async def interrupt_restore(ch: Any, fixture: Fixture, before: dict[str, Any]) -> dict[str, str]: + from server.erasure.store.census import connected_restore_residue + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.app import connected_restore as restore + + real_erase = accounts._erase_locked + interrupted = False + stopped_at_boundary: dict[str, str] = {} + + async def interrupt(ended: Any, *, keep_marker: bool) -> None: + nonlocal interrupted, stopped_at_boundary + if (ended.org, ended.subject, ended.kind) == fixture.target and not interrupted: + require(not keep_marker) + await fixture.boundary(ch, ended) + boundary = await snapshot(ch) + target_ids = { + row["source_id"] + for row in fixture.sources + if (row["org"], row["owner_subject"], row["connection_slot"]) == fixture.target + } + require( + [ + row + for row in boundary["knowledge_sources"] + if str(row["source_id"]) not in target_ids + ] + == [ + row + for row in before["knowledge_sources"] + if str(row["source_id"]) not in target_ids + ] + ) + require( + [ + row + for row in boundary["connected_accounts"] + if (row["org"], row["subject"], row["kind"]) != fixture.target + ] + == [ + row + for row in before["connected_accounts"] + if (row["org"], row["subject"], row["kind"]) != fixture.target + ] + ) + stopped_at_boundary = await fixture.claims_owned(ch) + interrupted = True + raise FixtureInterrupted() + await real_erase(ended, keep_marker=keep_marker) + + with patch.object(accounts, "_erase_locked", new=interrupt): + try: + await restore.restore_all(apply=True, ch=ch) + except FixtureInterrupted: + pass + else: + require(False) + require(interrupted and await count(ch, "knowledge_sources") > 0) + require(await connected_restore_residue(ch=ch) > 0) + return stopped_at_boundary + + +async def complete_restore(ch: Any, fixture: Fixture, stopped_at_boundary: dict[str, str]) -> None: + from server.erasure.app.connected_accounts import require_restore_erased + from server.erasure.store.census import connected_restore_residue + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.app import connected_restore as restore + from server.knowledge.store import connected_accounts as account_store + from server.knowledge.store import sources + + await owned_stores(ch, fixture.orgs) + await restore.restore_all(apply=True, ch=ch) + require(await count(ch, "connected_accounts") == 0) + require(await count(ch, "knowledge_sources") == 0) + require(await account_store.restore_keys() == [] and await sources.connected_history() == []) + require(await connected_restore_residue(ch=ch) == 0) + await require_restore_erased(ch=ch) + stopped = await fixture.claims_owned(ch, stopped=True) + for generation, owner in fixture.connections.items(): + key = accounts._fence_key(generation) + if owner == fixture.target: + require(stopped[key] == stopped_at_boundary[key]) + if generation.partition("/")[2].startswith("0"): + require(stopped[key] == generation) + for row in fixture.sources: + await fixture.retirement_pending(ch, row) + require(await count(ch, "code_index_state") == len(fixture.sources)) + + +async def qualify(result: dict[str, Any]) -> None: + from server import boot + from server.cli._ch import connect_verified, disconnect + from server.core.ch import get_client, set_query_tag + from server.core.errors import OverloadedError + from server.erasure.app.connected_accounts import require_restore_erased + from server.erasure.store.census import connected_restore_residue + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.app import connected_restore as restore + from server.settings import settings + + require(settings.llm_provider == "fake" and settings.embedding_model == "fake-ngram-1024") + require(settings.storage_authority == result["config"]["authority"]) + require(not settings.auth_actually_required()) + require(str(settings.jwt_secret) == _FIXTURE_KEY and not settings.jwt_secret_previous) + ch = get_client() + await ch.connect() + try: + set_query_tag("gate.mcp_source_lifecycle") + result["stage"] = "fresh_store_guard" + await owned_stores(ch, (), pg_ready=False) + require(await count(ch, "oauth_signin_state") == 0) + await boot.require_storage_authority(ch) + await connect_verified(ch) + await owned_stores(ch, ()) + require(await count(ch, "oauth_signin_state") == 0) + nonce = uuid4().hex + fixture = Fixture((f"mcp-lifecycle-{nonce}-a", f"mcp-lifecycle-{nonce}-b")) + fixture.prepare() + result["stage"] = "seed" + await fixture.seed(ch) + await owned_stores(ch, fixture.orgs) + await fixture.claims_owned(ch) + require(await count(ch, "connected_accounts") == len(fixture.accounts)) + require(await count(ch, "knowledge_sources") == len(fixture.sources)) + require(await connected_restore_residue(ch=ch) > 0) + try: + await require_restore_erased(ch=ch) + except OverloadedError: + pass + else: + require(False) + before = await snapshot(ch) + result["counts"] = { + "accounts": len(fixture.accounts), + "sources": len(fixture.sources), + "generations": len(fixture.connections), + "mirrors": len(fixture.mirrors), + } + client_attempts: list[None] = [] + + def refuse_native_client(*args: Any, **kwargs: Any) -> Any: + # Fail-only sentinel: no client or provider result can be supplied by this seam. + client_attempts.append(None) + raise AssertionError("MCP_LIFECYCLE_NATIVE_CLIENT_FORBIDDEN") + + with patch.object(accounts, "client", new=refuse_native_client): + result["stage"] = "dry_run" + await restore.restore_all(apply=False, ch=ch) + require(await snapshot(ch) == before) + require(not client_attempts) + result["checks"].append("dry_run_unchanged") + + result["stage"] = "reseal_forward" + await reseal_rotation(ch, fixture, _ROTATED_KEY, _FIXTURE_KEY, client_attempts) + result["checks"].append("reseal_forward_one_candidate_four_unreadable") + result["stage"] = "reseal_back" + await reseal_rotation(ch, fixture, _FIXTURE_KEY, _ROTATED_KEY, client_attempts) + require(str(settings.jwt_secret) == _FIXTURE_KEY and not settings.jwt_secret_previous) + result["checks"].append("reseal_back_one_candidate_four_unreadable") + + result["stage"] = "interruption" + stopped_at_boundary = await interrupt_restore(ch, fixture, before) + require(not client_attempts) + result["checks"].append("real_retirement_before_injected_erase_failure") + + result["stage"] = "retry" + await complete_restore(ch, fixture, stopped_at_boundary) + require(not client_attempts) + result["checks"].append("retry_erases_all_raw_bindings_and_keeps_retirements") + result["counts"]["final_global_residue"] = 0 + result["counts"]["pending_retirements"] = len(fixture.sources) + + result["stage"] = "idempotent_rerun" + after = await snapshot(ch) + await restore.restore_all(apply=True, ch=ch) + require(await snapshot(ch) == after) + await require_restore_erased(ch=ch) + await owned_stores(ch, fixture.orgs) + require(not client_attempts) + result["checks"].append("completed_restore_rerun_unchanged") + result["counts"]["native_client_attempts"] = len(client_attempts) + result["stage"] = "complete" + result["status"] = "passed" + finally: + await disconnect(ch) + + +def failure_detail(error: Exception) -> dict[str, Any]: + root = Path(__file__).parents[2] + frames = [] + cursor = error.__traceback__ + for _ in range(64): + if cursor is None: + break + try: + path = Path(cursor.tb_frame.f_code.co_filename).relative_to(root).as_posix() + except ValueError: + pass + else: + if re.fullmatch(r"[A-Za-z0-9_./-]{1,160}", path): + frames.append({"path": path, "line": cursor.tb_lineno}) + cursor = cursor.tb_next + return {"type": re.sub(r"[^A-Za-z0-9_]", "_", type(error).__name__)[:64], "frames": frames[-8:]} + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--isolated-fixture", action="store_true", required=True) + parser.add_argument("--result", type=Path, required=True) + args = parser.parse_args() + logging.disable(logging.CRITICAL) + result: dict[str, Any] = {"status": "failed", "stage": "guard", "checks": []} + try: + authority = fixture_guard(args.isolated_fixture, args.result) + except Exception: # noqa: BLE001 — an unverified target must not open any store + print("MCP lifecycle fixture guard refused", file=sys.stderr) + return 2 + result["config"] = {"authority": authority, "models": "fake", "workers": "off"} + try: + asyncio.run(asyncio.wait_for(qualify(result), timeout=300)) + except Exception as error: # noqa: BLE001 — emit no payload, SQL exception or credential in CI + result["status"] = "failed" + result["failure"] = failure_detail(error) + payload = json.dumps(result, sort_keys=True, indent=2) + "\n" + require(len(payload.encode()) <= 16384) + with args.result.open("x") as output: + output.write(payload) + print("MCP lifecycle qualification " + result["status"]) + return 0 if result["status"] == "passed" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/server/erasure/store/census.py b/server/erasure/store/census.py index 236d052526..0ace2e9f9d 100644 --- a/server/erasure/store/census.py +++ b/server/erasure/store/census.py @@ -45,7 +45,9 @@ from server.erasure.store.provider_copies import copy_residue from server.erasure.store.steps_memory import SESSION_OUTCOME_TABLES, TERM_AGGREGATE_TABLES from server.erasure.store.steps_pg import PG_CENSUS, pg_residue +from server.knowledge.domain.connected_accounts import known_account_kind from server.knowledge.domain.live_chunks import LIVE_CHUNK_SQL +from server.knowledge.domain.mcp_sources import is_mcp_slot from server.settings import settings log = logging.getLogger(__name__) @@ -842,11 +844,18 @@ async def connected_source_residue( ch: _CHClient | None = None, ) -> int: """Canonical-owner deletion includes historical bindings, without matching user_id.""" + if not known_account_kind(kind): + raise RuntimeError("connected_source_census_kind_unavailable") + predicate = ( + "(credential_mode = 'mcp' OR source_kind = 'mcp') AND connection_slot = {kind:String}" + if is_mcp_slot(kind) + else "credential_mode = 'connected' AND source_kind = {kind:String}" + ) row = await (ch or _default_client()).query_one( "SELECT count() AS n FROM loom.knowledge_sources " "WHERE org = {org:String} AND namespace = {ns:String} " - "AND owner_subject = {owner:String} AND credential_mode = 'connected' " - "AND source_kind = {kind:String}", + "AND owner_subject = {owner:String} " + f"AND {predicate}", params={"org": org, "ns": namespace, "owner": subject, "kind": kind}, ) if row is None or "n" not in row: @@ -1065,7 +1074,10 @@ async def connected_restore_residue(*, ch: _CHClient | None = None) -> int: total = 0 for table, predicate in ( ("loom.connected_accounts", "1"), - ("loom.knowledge_sources", "credential_mode = 'connected'"), + ( + "loom.knowledge_sources", + "credential_mode IN ('connected', 'mcp') OR source_kind = 'mcp'", + ), ): row = await client.query_one(f"SELECT count() AS n FROM {table} WHERE {predicate}") if row is None or "n" not in row: diff --git a/server/knowledge/app/connected_accounts.py b/server/knowledge/app/connected_accounts.py index 4901d7ff95..646d3748d6 100644 --- a/server/knowledge/app/connected_accounts.py +++ b/server/knowledge/app/connected_accounts.py @@ -37,10 +37,11 @@ accepts_callback, refreshing, rotated, + source_account_key, source_matches, stopped, ) -from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource, opaque_payload from server.knowledge.store import connected_accounts as store from server.knowledge.store import sources as source_store from server.observability import audit @@ -368,21 +369,37 @@ async def _stop_locked(account: ConnectedAccount, *, strict: bool = False) -> Co ended = dataclasses.replace(ended, connection_id=previous) elif strict and previous != account.connection_id: raise unavailable() - landed = await claims.swap(get_client(), key, previous, ended.connection_id, _FENCE_EXPIRY) + # A validated stopped fence already records this stop under the account lease. + landed = previous + if previous != ended.connection_id: + landed = await claims.swap(get_client(), key, previous, ended.connection_id, _FENCE_EXPIRY) if landed != ended.connection_id: raise unavailable() await store.put(ended) + account_key = account.org, account.subject, account.kind for source in await source_store.connected_sources(account.org, account.subject): - if source.kind != account.kind: + binding = source_account_key( + org=source.org, + owner=source.owner_subject, + kind=source.kind, + mode=source.credential_mode, + slot=source.connection_slot, + ) + if binding != account_key: continue async with source_ops.sources_lease(source.org, source.namespace): current = await source_store.latest_source(source.org, source.namespace, source.name) if ( current is None or current.source_id != source.source_id - or current.credential_mode != "connected" - or current.owner_subject != account.subject - or current.kind != account.kind + or source_account_key( + org=current.org, + owner=current.owner_subject, + kind=current.kind, + mode=current.credential_mode, + slot=current.connection_slot, + ) + != account_key ): continue pending = await source_ops._queue_retirement(current) @@ -438,7 +455,7 @@ async def _erase_locked(account: ConnectedAccount, *, keep_marker: bool) -> None async def _revoke( account: ConnectedAccount, *, credential: str, deadline: float | None = None ) -> None: - if not credential: + if not credential or account.kind not in KINDS: return try: provider = client(account.kind) @@ -480,6 +497,22 @@ async def disconnect(org: str, subject: str, kind: str) -> None: ) +async def _owner_cutoff_allows( + owner: tuple[str, str, str], current: ConnectedAccount | None +) -> bool: + spellings = await aliases.verified_spellings(owner[0], owner[1]) + cutoffs = await revocation.cutoffs(spellings, permanent=current is None) + if current is not None: + since = int(current.connected_at.timestamp()) if current.connected_at else 0 + return any(revocation.kills(row, since) for row in cutoffs.values()) + if not cutoffs: + return False + if any(row is None for row in cutoffs.values()): + return True + # A source-only generation has no trusted birth time to compare with a dated cutoff. + raise unavailable() + + async def stop_subjects( subjects: list[str], *, @@ -492,37 +525,46 @@ async def stop_subjects( set_query_tag("knowledge.connected_accounts.stop_subjects") ended = [] async with asyncio.timeout(settings.knowledge_connected_stop_timeout_s): - found = await store.owned(subjects, org=org) - if respect_cutoff: - wanted = set(subjects) - known = {(account.org, account.subject) for account in found} - for owner_org, owner in await store.owner_identities(org=org): - if (owner_org, owner) in known: - continue - spellings = await aliases.verified_spellings(owner_org, owner) - if wanted.intersection(spellings): - # Verified ties are org-specific. Never canonicalize in one org - # and then use that identity to stop rows in another org. - found.extend(await store.owned([owner], org=owner_org)) - for account in found: - async with account_lease(account.org, account.subject, account.kind): - current = await store.get(account.org, account.subject, account.kind) - if current is not None: - if respect_cutoff: - spellings = await aliases.verified_spellings(current.org, current.subject) - cutoffs = await revocation.cutoffs(spellings) - since = int(current.connected_at.timestamp()) if current.connected_at else 0 - if not any(revocation.kills(row, since) for row in cutoffs.values()): - continue - credential = ( - unseal(CREDENTIAL_PURPOSE, current.credential_enc, warn=False) or "" - if revoke - else "" - ) - stopped_account = await _stop_locked(current) - if erase_owner: - await _erase_locked(stopped_account, keep_marker=False) - ended.append((current, credential)) + if erase_owner: + from server.knowledge.app.connected_restore import erase_subjects + + ended = await erase_subjects( + subjects, org=org, respect_cutoff=respect_cutoff, revoke=revoke, ch=get_client() + ) + else: + found = await store.owned(subjects, org=org) + if respect_cutoff: + wanted = set(subjects) + known = {(account.org, account.subject) for account in found} + for owner_org, owner in await store.owner_identities(org=org): + if (owner_org, owner) in known: + continue + spellings = await aliases.verified_spellings(owner_org, owner) + if wanted.intersection(spellings): + # Verified ties are org-specific. Never canonicalize in one org + # and then use that identity to stop rows in another org. + found.extend(await store.owned([owner], org=owner_org)) + for account in found: + async with account_lease(account.org, account.subject, account.kind): + current = await store.get(account.org, account.subject, account.kind) + if current is not None: + if respect_cutoff: + spellings = await aliases.verified_spellings( + current.org, current.subject + ) + cutoffs = await revocation.cutoffs(spellings) + since = ( + int(current.connected_at.timestamp()) if current.connected_at else 0 + ) + if not any(revocation.kills(row, since) for row in cutoffs.values()): + continue + credential = ( + unseal(CREDENTIAL_PURPOSE, current.credential_enc, warn=False) or "" + if revoke + else "" + ) + await _stop_locked(current) + ended.append((current, credential)) if not revoke: return # All local owners and sources are fenced before the first slow provider call. @@ -534,6 +576,10 @@ async def stop_subjects( async def _source_standing(source: KnowledgeSource, account: ConnectedAccount) -> None: from server.knowledge.app import sources as source_ops + if opaque_payload( + kind=source.kind, mode=source.credential_mode, version=source.source_contract_version + ): + raise unavailable() if ( account.org != source.org or account.subject != source.owner_subject @@ -581,6 +627,11 @@ async def _source_standing(source: KnowledgeSource, account: ConnectedAccount) - or current.access != MIRRORED_ACCESS or current.items != source.items or current.config != source.config + or opaque_payload( + kind=current.kind, + mode=current.credential_mode, + version=current.source_contract_version, + ) ): raise unavailable() await source_ops._require_source_namespace(source.org, source.namespace) diff --git a/server/knowledge/app/connected_restore.py b/server/knowledge/app/connected_restore.py index 0d06f07980..1c84939551 100644 --- a/server/knowledge/app/connected_restore.py +++ b/server/knowledge/app/connected_restore.py @@ -1,4 +1,4 @@ -"""Offline retirement of restored connection authority, before serving any copy.""" +"""Retirement of connection history under account-before-source leases.""" from __future__ import annotations @@ -9,7 +9,7 @@ from datetime import UTC, datetime from typing import Any -from server.auth import claims +from server.auth import aliases, claims from server.core import ch as ch_module from server.core.ch import set_query_tag from server.core.secrets_at_rest import unseal @@ -17,7 +17,12 @@ from server.knowledge.app import connected_accounts as accounts from server.knowledge.app import source_push from server.knowledge.app import sources as source_ops -from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE, KINDS, ConnectedAccount +from server.knowledge.domain.connected_accounts import ( + CREDENTIAL_PURPOSE, + ConnectedAccount, + known_account_kind, + source_account_key, +) from server.knowledge.domain.sources import KnowledgeSource from server.knowledge.store import connected_accounts as account_store from server.knowledge.store import sources as source_store @@ -44,13 +49,10 @@ def _include( groups: dict[Owner, set[str]], prefixes: dict[str, Owner], rows: list[Registration] ) -> None: for org, subject, kind, connection in rows: - if ( - any( - not isinstance(value, str) or not value or value != value.strip() - for value in (org, subject, kind, connection) - ) - or kind not in KINDS - ): + if any( + not isinstance(value, str) or not value or value != value.strip() + for value in (org, subject, kind, connection) + ) or not known_account_kind(kind): raise accounts.unavailable() key = accounts._fence_key(connection) if connection.partition("/")[2][0] not in "01": @@ -62,6 +64,16 @@ def _include( groups[owner].add(connection) +def _source_binding(source: KnowledgeSource) -> Owner | None: + return source_account_key( + org=source.org, + owner=source.owner_subject, + kind=source.kind, + mode=source.credential_mode, + slot=source.connection_slot, + ) + + async def _metadata( ch: Any, owner: Owner | None = None ) -> tuple[list[Registration], list[KnowledgeSource]]: @@ -73,7 +85,10 @@ async def _metadata( for value in (source.namespace, source.name, source.source_id) ): raise accounts.unavailable() - keys.append((source.org, source.owner_subject, source.kind, source.connection_id)) + binding = _source_binding(source) + if binding is None: + raise accounts.unavailable() + keys.append((*binding, source.connection_id)) if owner is not None and any(row[:3] != owner for row in keys): raise accounts.unavailable() return keys, sources @@ -92,6 +107,8 @@ async def _stop_key(connection: str, ch: Any) -> str: if observed is not None and observed.partition("/")[2].startswith("0") else accounts._next_connection(connection, inactive=True) ) + if ended == observed: + return ended landed = await claims.swap(ch, key, observed, ended, accounts._FENCE_EXPIRY) if landed != ended: raise accounts.unavailable() @@ -101,6 +118,9 @@ async def _stop_key(connection: str, ch: Any) -> str: async def _retire_history(sources: list[KnowledgeSource], ch: Any) -> None: seen = set() for source in sources: + binding = _source_binding(source) + if binding is None: + raise accounts.unavailable() identity = source.org, source.namespace, source.source_id if identity in seen: continue @@ -114,9 +134,7 @@ async def _retire_history(sources: list[KnowledgeSource], ch: Any) -> None: if ( current is not None and current.source_id == source.source_id - and current.credential_mode == "connected" - and current.owner_subject == source.owner_subject - and current.kind == source.kind + and _source_binding(current) == binding ): await source_store.insert_source( dataclasses.replace( @@ -131,23 +149,35 @@ async def _retire_history(sources: list[KnowledgeSource], ch: Any) -> None: async def _restore_owner( - owner: Owner, groups: dict[Owner, set[str]], prefixes: dict[str, Owner], ch: Any + owner: Owner, + groups: dict[Owner, set[str]], + prefixes: dict[str, Owner], + ch: Any, + *, + respect_cutoff: bool = False, + revoke: bool = True, ) -> tuple[ConnectedAccount, str] | None: async with accounts.account_lease(*owner, ch=ch): - keys, sources = await _metadata(ch, owner) current = await account_store.get(*owner, ch=ch) + if current is not None and (current.org, current.subject, current.kind) != owner: + raise accounts.unavailable() + if respect_cutoff and not await accounts._owner_cutoff_allows(owner, current): + return None + keys, sources = await _metadata(ch, owner) if current is not None: keys.append((current.org, current.subject, current.kind, current.connection_id)) - if (current.org, current.subject, current.kind) != owner: - raise accounts.unavailable() _include(groups, prefixes, keys) + if len(prefixes) > settings.knowledge_connected_registry_scan_limit: + raise accounts.unavailable() + if not groups[owner]: + return None stopped: dict[str, str] = {} for connection in sorted(groups[owner]): key = accounts._fence_key(connection) if key not in stopped: stopped[key] = await _stop_key(connection, ch) credential = "" - if current is not None and current.credential_enc: + if revoke and current is not None and current.credential_enc: try: credential = unseal(CREDENTIAL_PURPOSE, current.credential_enc, warn=False) or "" except Exception: # noqa: BLE001 — local deletion never depends on recovering a remote secret @@ -163,6 +193,58 @@ async def _restore_owner( return (current, credential) if current is not None else None +async def _erasure_owners( + subjects: list[str], *, org: str | None, respect_cutoff: bool, ch: Any +) -> set[Owner]: + found = await account_store.owned(subjects, org=org, ch=ch) + sources = await source_store.connected_owners( + None if respect_cutoff else subjects, org=org, ch=ch + ) + owners = {(row.org, row.subject, row.kind) for row in found} + owners.update(owner for owner in sources if owner[1] in subjects) + if respect_cutoff: + identities = set(await account_store.owner_identities(org=org, ch=ch)) + identities.update(owner[:2] for owner in sources) + if len(identities) > settings.knowledge_connected_registry_scan_limit: + raise accounts.unavailable() + for owner_org, subject in sorted(identities): + if subject in subjects: + continue + spellings = await aliases.verified_spellings(owner_org, subject) + if set(subjects).intersection(spellings): + owners.update(owner for owner in sources if owner[:2] == (owner_org, subject)) + found = await account_store.owned([subject], org=owner_org, ch=ch) + owners.update((row.org, row.subject, row.kind) for row in found) + if len(owners) > settings.knowledge_connected_registry_scan_limit: + raise accounts.unavailable() + if org is not None and any(owner[0] != org for owner in owners): + raise accounts.unavailable() + return owners + + +async def erase_subjects( + subjects: list[str], *, org: str | None, respect_cutoff: bool, revoke: bool, ch: Any +) -> list[tuple[ConnectedAccount, str]]: + """Owner-deletion callers authorize only their selected identities, never global restore.""" + if not subjects: + return [] + owners = await _erasure_owners(subjects, org=org, respect_cutoff=respect_cutoff, ch=ch) + groups: dict[Owner, set[str]] = defaultdict(set) + prefixes: dict[str, Owner] = {} + for owner in sorted(owners): + keys, _sources = await _metadata(ch, owner) + _include(groups, prefixes, keys) + if len(prefixes) > settings.knowledge_connected_registry_scan_limit: + raise accounts.unavailable() + ended = [] + for owner in sorted(owners): + if account := await _restore_owner( + owner, groups, prefixes, ch, respect_cutoff=respect_cutoff, revoke=revoke + ): + ended.append(account) + return ended + + async def restore_all(*, apply: bool, ch: Any) -> None: """Maintenance for the configured deployment; no account survives a restore. diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index 254345e946..a853d63800 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -21,7 +21,7 @@ from server.knowledge.domain.access_list import UNREAD, AccessList, allows, from_json from server.knowledge.domain.document_access import fresh, source_id from server.knowledge.domain.serving import Serving -from server.knowledge.domain.sources import KnowledgeSource +from server.knowledge.domain.sources import KnowledgeSource, opaque_payload from server.knowledge.store import mirrors as mirrors_repo from server.knowledge.store import source_access as store from server.operations.base import Role @@ -311,6 +311,12 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) for row in sources: key = row["namespace"], row["source_id"] mode = row.get("credential_mode", "shared") + if opaque_payload( + kind=str(row.get("source_kind") or ""), + mode=mode, + version=int(row.get("source_contract_version") or 0), + ): + continue if mode == "shared": if key not in plan._connected_pins: eligible.append(row) @@ -319,7 +325,15 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) continue try: source = await source_store.latest_source(plan.org, row["namespace"], row["name"]) - if source is None or source.source_id != row["source_id"]: + if ( + source is None + or source.source_id != row["source_id"] + or opaque_payload( + kind=source.kind, + mode=source.credential_mode, + version=source.source_contract_version, + ) + ): continue pinned = plan._connected_pins.get(key) if pinned is not None and ( diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index fcbc9f0d73..ee0599b09c 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -359,6 +359,10 @@ async def _source_or_404(org: str, namespace: str, name: str) -> KnowledgeSource raise NotFoundError( f"no document source {domain.shown(name)} in {namespace!r}", code="SOURCE_NOT_FOUND" ) + if domain.opaque_payload( + kind=src.kind, mode=src.credential_mode, version=src.source_contract_version + ): + _require_served(src) return src @@ -402,6 +406,10 @@ def _sync(src: KnowledgeSource, state: dict[str, str] | None) -> KnowledgeSource async def _details_allowed(src: KnowledgeSource) -> bool: + if domain.opaque_payload( + kind=src.kind, mode=src.credential_mode, version=src.source_contract_version + ): + return False if src.credential_mode == "shared": return True if src.credential_mode != "connected" or not request_work.mark_mirrored(): @@ -1021,6 +1029,10 @@ async def handle_knowledge_source_remove( f"no document source {domain.shown(name)} in {input.namespace!r}", code="SOURCE_NOT_FOUND", ) + if domain.opaque_payload( + kind=src.kind, mode=src.credential_mode, version=src.source_contract_version + ): + _require_served(src) if src.credential_mode == "connected": from server.knowledge.app.connected_sources import require_operator diff --git a/server/knowledge/domain/connected_accounts.py b/server/knowledge/domain/connected_accounts.py index 2cf45b28c6..7a0c4a380b 100644 --- a/server/knowledge/domain/connected_accounts.py +++ b/server/knowledge/domain/connected_accounts.py @@ -5,12 +5,32 @@ from dataclasses import dataclass, field, replace from datetime import datetime +from server.knowledge.domain.mcp_sources import is_mcp_slot + KINDS = frozenset({"gdrive", "notion", "linear"}) CREDENTIAL_PURPOSE = "connected_accounts.credential" EMAIL_PURPOSE = "connected_accounts.email" PKCE_PURPOSE = "connected_accounts.pkce" +def known_account_kind(value: object) -> bool: + """Recognize cleanup keys without admitting remote reads.""" + return isinstance(value, str) and (value in KINDS or is_mcp_slot(value)) + + +def source_account_key( + *, org: str, owner: str, kind: str, mode: str, slot: str +) -> tuple[str, str, str] | None: + """Use lifecycle metadata; unreadable credentials must not block owner erasure.""" + if mode == "connected" and kind in KINDS: + account_kind = kind + elif (mode == "mcp" or kind == "mcp") and is_mcp_slot(slot): + account_kind = slot + else: + return None + return org, owner, account_kind + + @dataclass(frozen=True, repr=False) class ConnectedAccount: org: str diff --git a/server/knowledge/domain/mcp_sources.py b/server/knowledge/domain/mcp_sources.py new file mode 100644 index 0000000000..572f701fc2 --- /dev/null +++ b/server/knowledge/domain/mcp_sources.py @@ -0,0 +1,216 @@ +"""Pure MCP connection and selection codecs; lifecycle and authorization stay with callers.""" + +from __future__ import annotations + +import json +import unicodedata +from typing import Annotated, Any, Literal, Self + +from pydantic import ( + AfterValidator, + BaseModel, + ConfigDict, + Field, + SecretStr, + TypeAdapter, + field_validator, + model_validator, +) + +MAX_ENVELOPE_BYTES = 32 * 1024 +MAX_RESOURCES = 1000 +MAX_RESOURCE_BYTES = 2048 +_MAX_ITEMS_BYTES = MAX_RESOURCES * (2 * MAX_RESOURCE_BYTES + 64) + 2 + + +class MCPSourceContractError(ValueError): + """A public codec failure contains no supplied payload or credential.""" + + def __init__(self) -> None: + super().__init__("MCP_SOURCE_CONTRACT_INVALID") + + +def _identifier(value: str) -> str: + if ( + not value.strip() + or len(value.encode("utf-8")) > MAX_RESOURCE_BYTES + or any(unicodedata.category(char) == "Cc" for char in value) + ): + raise ValueError("invalid identifier") + return value + + +_Identifier = Annotated[str, Field(min_length=1, max_length=2048), AfterValidator(_identifier)] +_Slot = Annotated[_Identifier, Field(pattern=r"^mcp:[0-9a-f]{32}$")] +_Generation = Annotated[_Identifier, Field(pattern=r"^[0-9a-f]{32}/[01][0-9a-f]{31}$")] +_Digest = Annotated[_Identifier, Field(pattern=r"^[0-9a-f]{64}$")] +_Version = Annotated[int, Field(strict=True, ge=1, le=1)] +_SLOT_ADAPTER: TypeAdapter[str] = TypeAdapter(_Slot) + + +def is_mcp_slot(value: object) -> bool: + """Recognize a lifecycle key without opening an envelope or granting read access.""" + try: + _SLOT_ADAPTER.validate_python(value, strict=True) + except (ValueError, TypeError, RecursionError): + return False + return True + + +class _ContractModel(BaseModel): + model_config = ConfigDict( + strict=True, + frozen=True, + extra="forbid", + hide_input_in_errors=True, + revalidate_instances="always", + ) + + +class ConnectionEnvelope(_ContractModel): + """One slot's sealing plaintext; endpoint approval is a caller responsibility.""" + + version: _Version + org: _Identifier + owner: _Identifier + slot: _Slot + generation: _Generation + profile_id: _Identifier + profile_sha256: _Digest + endpoint: _Identifier + audience: _Identifier | None + auth: Literal["none", "bearer"] + bearer: SecretStr | None = Field(default=None, exclude=True, repr=False) + label: Annotated[_Identifier, Field(max_length=256)] | None = None + + @field_validator("bearer") + @classmethod + def _bearer_shape(cls, value: SecretStr | None) -> SecretStr | None: + if value is not None: + token = value.get_secret_value() + if not 0 < len(token) <= 8192 or any(not 33 <= ord(char) <= 126 for char in token): + raise ValueError("invalid bearer") + return value + + @model_validator(mode="after") + def _auth_shape(self) -> Self: + if self.auth == "none": + if self.bearer is not None or self.audience is not None: + raise ValueError("invalid anonymous auth") + elif self.bearer is None or self.audience is None: + raise ValueError("invalid bearer auth") + return self + + +class ResourceIdentity(_ContractModel): + type: Literal["resource"] + id: _Identifier + + +class SourceContract(_ContractModel): + """Reader policy is declarative; grants, consent and publication are checked elsewhere. + + The outer row version and binding remain the caller's responsibility. Unknown raw + contracts need lifecycle preservation, not execution through this codec. + """ + + version: _Version + slot: _Slot + generation: _Generation + profile_id: _Identifier + profile_sha256: _Digest + mode: Literal["live", "snapshot", "selected_refresh"] + reader_policy: Literal["owner_only", "collection_copy"] + resources: Annotated[ + tuple[ResourceIdentity, ...], Field(min_length=1, max_length=MAX_RESOURCES) + ] + + @field_validator("resources") + @classmethod + def _unique_resources(cls, value: tuple[ResourceIdentity, ...]) -> tuple[ResourceIdentity, ...]: + if len({resource.id for resource in value}) != len(value): + raise ValueError("duplicate resource") + return value + + +def _bounded_text(value: str, maximum: int) -> str: + if not isinstance(value, str) or len(value.encode("utf-8")) > maximum: + raise ValueError("invalid payload size") + return value + + +def _encode(value: Any, maximum: int) -> str: + return _bounded_text( + json.dumps( + value, ensure_ascii=False, allow_nan=False, sort_keys=True, separators=(",", ":") + ), + maximum, + ) + + +def encode_envelope(envelope: ConnectionEnvelope) -> str: + """Reveal the bearer only into plaintext intended for the existing sealing helper.""" + try: + envelope = ConnectionEnvelope.model_validate(envelope) + payload = envelope.model_dump(mode="json") + if envelope.bearer is not None: + payload["bearer"] = envelope.bearer.get_secret_value() + return _encode(payload, MAX_ENVELOPE_BYTES) + except (ValueError, TypeError, RecursionError): + raise MCPSourceContractError() from None + + +def decode_envelope(plaintext: str) -> ConnectionEnvelope: + try: + return ConnectionEnvelope.model_validate_json(_bounded_text(plaintext, MAX_ENVELOPE_BYTES)) + except (ValueError, TypeError, RecursionError): + raise MCPSourceContractError() from None + + +def bind_envelope( + envelope: ConnectionEnvelope, + *, + org: str, + owner: str, + slot: str, + generation: str, + profile_id: str, + profile_sha256: str, + endpoint: str, + audience: str | None, +) -> None: + """Compare the fetched row and current approved profile exactly, without guessing identity.""" + if ( + envelope.org, + envelope.owner, + envelope.slot, + envelope.generation, + envelope.profile_id, + envelope.profile_sha256, + envelope.endpoint, + envelope.audience, + ) != (org, owner, slot, generation, profile_id, profile_sha256, endpoint, audience): + raise MCPSourceContractError() + + +def encode_source(contract: SourceContract) -> tuple[str, str]: + """Return config_json and items_json; selection has exactly one stored representation.""" + try: + contract = SourceContract.model_validate(contract) + config = contract.model_dump(mode="json", exclude={"resources"}) + items = [resource.model_dump(mode="json") for resource in contract.resources] + return _encode(config, MAX_ENVELOPE_BYTES), _encode(items, _MAX_ITEMS_BYTES) + except (ValueError, TypeError, RecursionError): + raise MCPSourceContractError() from None + + +def decode_source(config_json: str, items_json: str) -> SourceContract: + """Join the two stored columns; this codec admits only the known contract version.""" + try: + config = json.loads(_bounded_text(config_json, MAX_ENVELOPE_BYTES)) + items = json.loads(_bounded_text(items_json, _MAX_ITEMS_BYTES)) + if not isinstance(config, dict) or not isinstance(items, list) or "resources" in config: + raise ValueError("invalid source columns") + return SourceContract.model_validate({**config, "resources": tuple(items)}) + except (ValueError, TypeError, RecursionError): + raise MCPSourceContractError() from None diff --git a/server/knowledge/domain/sources.py b/server/knowledge/domain/sources.py index 7686cb3b06..2305ca8c86 100644 --- a/server/knowledge/domain/sources.py +++ b/server/knowledge/domain/sources.py @@ -139,6 +139,16 @@ class KnowledgeSource: # The namespace's mirror, which the sync sets before a mirrored source's turn; never # stored. mirror: str = "" + source_contract_version: int = 0 + connection_slot: str = "" + # Lifecycle writes preserve unknown payloads without interpreting or exposing them. + generic_config_json: str = field(default="", repr=False) + generic_items_json: str = field(default="", repr=False) + + +def opaque_payload(*, kind: str, mode: str, version: int) -> bool: + """Preserve new formats without interpreting them through a native source codec.""" + return version != 0 or kind == "mcp" or mode == "mcp" def shown(value: Any) -> str: @@ -565,15 +575,27 @@ def options_in(kind: str, config: dict[str, Any]) -> dict[str, Any]: def served(src: KnowledgeSource) -> bool: """Whether this build serves `src`: one shown to every reader of its namespace. A mirrored one, or any `access` a later build writes, is that build's.""" - return src.credential_mode == "shared" and src.access == NAMESPACE_ACCESS + return ( + not opaque_payload( + kind=src.kind, mode=src.credential_mode, version=src.source_contract_version + ) + and src.credential_mode == "shared" + and src.access == NAMESPACE_ACCESS + ) def mirror_synced(src: KnowledgeSource) -> bool: """Whether the sync worker writes `src` into its namespace's mirror: a mirrored folder-store source or a person's connected page/project source.""" - return src.access == MIRRORED_ACCESS and ( - src.kind == "gdrive" - or (src.credential_mode == "connected" and src.kind in {"notion", "linear"}) + return ( + not opaque_payload( + kind=src.kind, mode=src.credential_mode, version=src.source_contract_version + ) + and src.access == MIRRORED_ACCESS + and ( + src.kind == "gdrive" + or (src.credential_mode == "connected" and src.kind in {"notion", "linear"}) + ) ) diff --git a/server/knowledge/store/source_access.py b/server/knowledge/store/source_access.py index 00adc82a30..2579072e54 100644 --- a/server/knowledge/store/source_access.py +++ b/server/knowledge/store/source_access.py @@ -47,7 +47,8 @@ async def active_sources( if not namespaces: return [] return await (ch or _default_client()).query_all( - "SELECT namespace, name, credential_mode, toString(source_id) AS source_id " + "SELECT namespace, name, credential_mode, source_kind, source_contract_version, " + "toString(source_id) AS source_id " "FROM loom.knowledge_sources FINAL " "WHERE org = {org:String} AND namespace IN {names:Array(String)} " "AND active AND access = 'mirrored' ORDER BY namespace, name", diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 3a39f327ca..405d4e89ad 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -28,7 +28,9 @@ from server.core.datetimes import naive_utc_now_seconds from server.core.repo_base import _CHClient, _default_client +from server.knowledge.domain.connected_accounts import known_account_kind from server.knowledge.domain.live_chunks import has_live_chunks_sql +from server.knowledge.domain.mcp_sources import is_mcp_slot from server.knowledge.domain.sources import ( NAMESPACE_ACCESS, SYNC_WORKER_ACTOR, @@ -36,6 +38,7 @@ id_list_config, items_from_config, json_object, + opaque_payload, options_in, state_key, stored_config, @@ -53,11 +56,22 @@ _COLUMNS = ( "org, namespace, name, source_id, kind, source_kind, config_json, items_json, " "credential_enc, secret_enc, access, credential_mode, owner_subject, connection_id, " + "source_contract_version, connection_slot, " "created_by, active, pending_delete, created_at, " "updated_at" ) +def _account_predicate(kind: str) -> str: + if not known_account_kind(kind): + raise RuntimeError("connected_source_kind_unavailable") + if is_mcp_slot(kind): + return ( + "(credential_mode = 'mcp' OR source_kind = 'mcp') AND connection_slot = {kind:String}" + ) + return "credential_mode = 'connected' AND source_kind = {kind:String}" + + def _items(raw: str) -> list[dict[str, Any]]: """The stored items, or [] (the source's config names them).""" try: @@ -71,7 +85,12 @@ def _source(row: dict[str, Any]) -> KnowledgeSource: created = row.get("created_at") updated = row.get("updated_at") kind = str(row.get("source_kind") or row.get("kind") or "") - config = json_object(str(row.get("config_json") or "")) + mode = str(row.get("credential_mode") or "shared") + version = int(row.get("source_contract_version") or 0) + generic = opaque_payload(kind=kind, mode=mode, version=version) + config_raw = str(row.get("config_json") or "") + items_raw = str(row.get("items_json") or "") + config = {} if generic else json_object(config_raw) return KnowledgeSource( org=str(row.get("org") or ""), namespace=str(row.get("namespace") or ""), @@ -80,11 +99,11 @@ def _source(row: dict[str, Any]) -> KnowledgeSource: source_id=str(row.get("source_id") or ""), config=options_in(kind, config), # A row an older build wrote holds its items in `config` alone. - items=_items(str(row.get("items_json") or "")) or items_from_config(kind, config), + items=[] if generic else (_items(items_raw) or items_from_config(kind, config)), credential_enc=str(row.get("credential_enc") or ""), secret_enc=str(row.get("secret_enc") or ""), access=str(row.get("access") or NAMESPACE_ACCESS), - credential_mode=str(row.get("credential_mode") or "shared"), + credential_mode=mode, owner_subject=str(row.get("owner_subject") or ""), connection_id=str(row.get("connection_id") or ""), created_by=str(row.get("created_by") or ""), @@ -92,6 +111,10 @@ def _source(row: dict[str, Any]) -> KnowledgeSource: pending_delete=bool(row.get("pending_delete")), created_at=created if isinstance(created, datetime) else None, updated_at=updated if isinstance(updated, datetime) else None, + source_contract_version=version, + connection_slot=str(row.get("connection_slot") or ""), + generic_config_json=config_raw if generic else "", + generic_items_json=items_raw if generic else "", ) @@ -129,7 +152,8 @@ async def connected_sources( """Every owned source, including inactive rows whose cleanup may still be owed.""" rows = await (ch or _default_client()).query_all( f"SELECT {_COLUMNS} FROM {TABLE} FINAL WHERE org = {{org:String}} " - "AND credential_mode = 'connected' AND owner_subject = {subject:String} " + "AND (credential_mode IN ('connected', 'mcp') OR source_kind = 'mcp') " + "AND owner_subject = {subject:String} " "ORDER BY namespace, name LIMIT {limit:UInt64}", params={ "org": org, @@ -247,7 +271,7 @@ async def connected_owner_namespaces( rows = await (ch or _default_client()).query_all( f"SELECT DISTINCT namespace FROM {TABLE} " "WHERE org = {org:String} AND owner_subject = {owner:String} " - "AND credential_mode = 'connected' AND source_kind = {kind:String} " + f"AND {_account_predicate(kind)} " "ORDER BY namespace LIMIT {limit:UInt64}", params={"org": org, "owner": subject, "kind": kind, "limit": maximum + 1}, ) @@ -262,8 +286,8 @@ async def erase_connected_owner( """The caller holds the stopped account and this namespace's source lease.""" await (ch or _default_client()).execute( f"DELETE FROM {TABLE} WHERE org = {{org:String}} AND namespace = {{ns:String}} " - "AND owner_subject = {owner:String} AND credential_mode = 'connected' " - "AND source_kind = {kind:String}", + "AND owner_subject = {owner:String} " + f"AND {_account_predicate(kind)}", params={"org": org, "ns": namespace, "owner": subject, "kind": kind}, settings={"lightweight_deletes_sync": 2}, ) @@ -275,6 +299,9 @@ async def insert_source(src: KnowledgeSource, *, ch: _CHClient | None = None) -> writing replica's: the lease-serialized writes stay ordered while those clocks differ by less than the lease's handoff between writes.""" now = naive_utc_now_seconds() + generic = opaque_payload( + kind=src.kind, mode=src.credential_mode, version=src.source_contract_version + ) row = { "org": src.org, "namespace": src.namespace, @@ -282,14 +309,18 @@ async def insert_source(src: KnowledgeSource, *, ch: _CHClient | None = None) -> "source_id": src.source_id, "kind": src.kind if id_list_config(src) is not None else "", "source_kind": src.kind, - "config_json": json.dumps(stored_config(src), sort_keys=True), - "items_json": json.dumps(src.items, sort_keys=True), + "config_json": src.generic_config_json + if generic + else json.dumps(stored_config(src), sort_keys=True), + "items_json": src.generic_items_json if generic else json.dumps(src.items, sort_keys=True), "credential_enc": src.credential_enc, "secret_enc": src.secret_enc, "access": src.access, "credential_mode": src.credential_mode, "owner_subject": src.owner_subject, "connection_id": src.connection_id, + "source_contract_version": src.source_contract_version, + "connection_slot": src.connection_slot, "created_by": src.created_by, "active": src.active, "pending_delete": src.pending_delete, @@ -520,17 +551,59 @@ async def count_documents( ] +async def connected_owners( + subjects: list[str] | None = None, + *, + org: str | None = None, + ch: _CHClient | None = None, +) -> list[tuple[str, str, str]]: + """Discover raw-history identities without selecting source payloads or credentials.""" + if subjects == []: + return [] + where = "(credential_mode IN ('connected', 'mcp') OR source_kind = 'mcp')" + params: dict[str, Any] = {} + if org is not None: + where += " AND org = {org:String}" + params["org"] = org + if subjects is not None: + where += " AND owner_subject IN {subjects:Array(String)}" + params["subjects"] = subjects + maximum = settings.knowledge_connected_registry_scan_limit + rows = await (ch or _default_client()).query_all( + "SELECT DISTINCT org, owner_subject, " + "if(credential_mode = 'mcp' OR source_kind = 'mcp', connection_slot, source_kind) AS slot " + f"FROM {TABLE} WHERE {where} " + "ORDER BY org, owner_subject, slot LIMIT {limit:UInt64}", + params={**params, "limit": maximum + 1}, + ) + if len(rows) > maximum: + raise RuntimeError("connected_source_owner_bound") + return [(row["org"], row["owner_subject"], row["slot"]) for row in rows] + + async def connected_history( *, owner: tuple[str, str, str] | None = None, ch: _CHClient | None = None ) -> list[KnowledgeSource]: """Metadata of every historical connected source id, including replaced names.""" - where = "credential_mode = 'connected'" + where = "(credential_mode IN ('connected', 'mcp') OR source_kind = 'mcp')" if owner: - where += " AND (org, owner_subject, source_kind) = {owner:Tuple(String, String, String)}" + if not known_account_kind(owner[2]): + raise RuntimeError("connected_source_kind_unavailable") + if is_mcp_slot(owner[2]): + where = ( + "(credential_mode = 'mcp' OR source_kind = 'mcp') " + "AND (org, owner_subject, connection_slot) = {owner:Tuple(String, String, String)}" + ) + else: + where = ( + "credential_mode = 'connected' AND " + "(org, owner_subject, source_kind) = {owner:Tuple(String, String, String)}" + ) maximum = settings.knowledge_connected_registry_scan_limit rows = await (ch or _default_client()).query_all( "SELECT DISTINCT org, namespace, name, source_id, source_kind, owner_subject, " - f"connection_id FROM {TABLE} WHERE {where} " + f"connection_id, credential_mode, connection_slot, source_contract_version " + f"FROM {TABLE} WHERE {where} " "ORDER BY org, owner_subject, source_kind, namespace, name, source_id, connection_id " "LIMIT {limit:UInt64}", params={"owner": owner or ("", "", ""), "limit": maximum + 1}, @@ -546,7 +619,9 @@ async def connected_history( source_id=row["source_id"], owner_subject=row["owner_subject"], connection_id=row["connection_id"], - credential_mode="connected", + credential_mode=str(row.get("credential_mode") or "connected"), + connection_slot=str(row.get("connection_slot") or ""), + source_contract_version=int(row.get("source_contract_version") or 0), access="mirrored", ) for row in rows diff --git a/tests/integration/test_mcp_source_lifecycle_ch.py b/tests/integration/test_mcp_source_lifecycle_ch.py new file mode 100644 index 0000000000..48b9d969cb --- /dev/null +++ b/tests/integration/test_mcp_source_lifecycle_ch.py @@ -0,0 +1,940 @@ +"""Hosted real-store lifecycle checks; no generic source execution is admitted.""" + +from __future__ import annotations + +import json +from collections import defaultdict +from collections.abc import AsyncIterator +from contextlib import AsyncExitStack, asynccontextmanager +from dataclasses import dataclass, field, replace +from datetime import UTC, datetime +from typing import Any +from uuid import UUID, uuid4 + +import pytest + +from server.auth import account_lifecycle, claims, revocation, scim +from server.core import ch as ch_module +from server.core.ch import CHClient, set_query_tag +from server.core.errors import OverloadedError, ValidationError +from server.erasure.app.connected_accounts import require_erased, require_sources_erased +from server.erasure.store.census import connected_account_residue, connected_source_residue +from server.knowledge.app import connected_accounts, connected_restore +from server.knowledge.app.sources import sources_lease +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.knowledge.domain.sources import mirror_synced, served +from server.knowledge.store import connected_accounts as account_store +from server.knowledge.store import mirrors as mirror_store +from server.knowledge.store import source_retirements +from server.knowledge.store import sources as source_store +from tests.integration._resources import unique_org + +pytestmark = pytest.mark.usefixtures("ch_target_required") + +OWNER = "first@example.test" +OTHER_OWNER = "second@example.test" +SLOT = "mcp:" + "a" * 32 +OTHER_SLOT = "mcp:" + "b" * 32 +# Fixed generations belong only to the four inactive metadata cases; never create their claims. +GENERATION = "1" * 32 + "/0" + "a" * 31 +LATER_GENERATION = "1" * 32 + "/1" + "b" * 31 +OTHER_GENERATION = "2" * 32 + "/1" + "c" * 31 +SECOND_OWNER_GENERATION = "3" * 32 + "/0" + "d" * 31 +NATIVE_GENERATION = "4" * 32 + "/0" + "e" * 31 +CONFIG = '{ "profile": "fixture", "future": {"marker": "opaque-config"} }' +ITEMS = '[ {"resource_id": "fixture://selected", "future": "opaque-selection"} ]' + + +@dataclass +class _World: + ch: CHClient + org: str + rows: list[dict[str, Any]] = field(default_factory=list) + accounts: list[ConnectedAccount] = field(default_factory=list) + mirrors: dict[tuple[str, str], str] = field(default_factory=dict) + + @asynccontextmanager + async def locked(self, row: dict[str, Any]) -> AsyncIterator[None]: + kind = row["connection_slot"] or row["source_kind"] + async with connected_accounts.account_lease( + row["org"], row["owner_subject"], kind, ch=self.ch + ): + async with sources_lease(row["org"], row["namespace"], ch=self.ch): + yield + + def source_row( + self, + name: str, + source_id: str, + *, + namespace: str = "selected", + owner: str = OWNER, + slot: str = SLOT, + generation: str = GENERATION, + config: str = CONFIG, + items: str = ITEMS, + native: bool = False, + org: str | None = None, + active: bool = False, + contract_version: int = 1, + version: int = 1, + ) -> dict[str, Any]: + return { + "org": org or self.org, + "namespace": namespace, + "name": name, + "source_id": str(UUID(source_id)), + "kind": "gdrive" if native else "", + "source_kind": "gdrive" if native else "mcp", + "credential_mode": "connected" if native else "mcp", + "owner_subject": owner, + "connection_slot": "" if native else slot, + "connection_id": generation, + "source_contract_version": 0 if native else contract_version, + "access": "mirrored", + "config_json": config, + "items_json": items, + "credential_enc": "fixture-unreadable-envelope", + "secret_enc": "fixture-unreadable-secret", + "created_by": owner, + "active": active, + "pending_delete": False, + "version": version, + } + + async def seed(self, name: str, source_id: str, **kwargs: Any) -> dict[str, Any]: + row = self.source_row(name, source_id, **kwargs) + await self.insert_rows([row]) + return row + + async def insert_rows(self, rows: list[dict[str, Any]]) -> None: + self.rows.extend(rows) # Record exact identities before an insert can partially land. + accounts = sorted( + {(r["org"], r["owner_subject"], r["connection_slot"] or r["source_kind"]) for r in rows} + ) + namespaces = sorted({(r["org"], r["namespace"]) for r in rows}) + set_query_tag("test.mcp-source-lifecycle.seed") + async with AsyncExitStack() as stack: + for org, owner, kind in accounts: + await stack.enter_async_context( + connected_accounts.account_lease(org, owner, kind, ch=self.ch) + ) + for org, namespace in namespaces: + await stack.enter_async_context(sources_lease(org, namespace, ch=self.ch)) + await self.ch.insert("loom.knowledge_sources", rows) + + async def raw(self, row: dict[str, Any]) -> dict[str, Any] | None: + return await self.ch.query_one( + "SELECT org, namespace, name, source_id, kind, source_kind, credential_mode, " + "owner_subject, connection_slot, connection_id, source_contract_version, access, " + "config_json, items_json, credential_enc, secret_enc, created_by, active, " + "pending_delete, created_at FROM loom.knowledge_sources FINAL " + "WHERE org = {org:String} AND namespace = {namespace:String} " + "AND name = {name:String} AND source_id = {source_id:UUID} LIMIT 1", + params={key: row[key] for key in ("org", "namespace", "name", "source_id")}, + ) + + async def source_versions( + self, row: dict[str, Any], *, final: bool = False + ) -> list[dict[str, Any]]: + suffix = " FINAL" if final else "" + return await self.ch.query_all( + f"SELECT * FROM loom.knowledge_sources{suffix} " + "WHERE org = {org:String} AND namespace = {namespace:String} " + "AND name = {name:String} ORDER BY version LIMIT 10", + params={key: row[key] for key in ("org", "namespace", "name")}, + ) + + async def seed_account( + self, kind: str = SLOT, *, org: str | None = None, owner: str = OWNER + ) -> ConnectedAccount: + account = ConnectedAccount( + org or self.org, + owner, + kind, + uuid4().hex + "/1" + uuid4().hex[1:], + credential_enc="fixture-unreadable-account-envelope", + active=True, + connected_at=datetime.now(UTC), + ) + async with connected_accounts.account_lease( + account.org, account.subject, account.kind, ch=self.ch + ): + key = connected_accounts._fence_key(account.connection_id) + assert await claims.get(self.ch, key) is None + self.accounts.append(account) + await connected_accounts._move_fence(None, account.connection_id, ch=self.ch) + await account_store.put(account, ch=self.ch) + return account + + async def account_versions(self, account: ConnectedAccount) -> list[dict[str, Any]]: + return await self.ch.query_all( + "SELECT * FROM loom.connected_accounts WHERE org = {org:String} " + "AND subject = {owner:String} AND kind = {kind:String} ORDER BY version LIMIT 10", + params={"org": account.org, "owner": account.subject, "kind": account.kind}, + ) + + async def add_mirror(self, org: str, namespace: str) -> None: + mirror = "acl-" + uuid4().hex[:24] + self.mirrors[org, namespace] = mirror + async with sources_lease(org, namespace, ch=self.ch): + await mirror_store.add_mirror(org, namespace, mirror, ch=self.ch) + + def retirement(self, row: dict[str, Any]) -> source_retirements.Retirement: + return source_retirements.Retirement( + row["org"], + row["namespace"], + row["name"], + row["source_id"], + row["source_kind"], + self.mirrors[row["org"], row["namespace"]], + ) + + async def retirement_row(self, row: dict[str, Any]) -> dict[str, Any] | None: + item = self.retirement(row) + return await self.ch.query_one( + "SELECT * FROM loom.code_index_state FINAL WHERE org = {org:String} " + "AND namespace = {mirror:String} AND state_key = {key:String} LIMIT 1", + params={"org": item.org, "mirror": item.mirror, "key": item.key}, + ) + + async def cleanup_account(self, account: ConnectedAccount) -> None: + async with connected_accounts.account_lease( + account.org, account.subject, account.kind, ch=self.ch + ): + key = connected_accounts._fence_key(account.connection_id) + observed = await claims.get(self.ch, key) + if observed is not None: + assert connected_accounts._fence_key(observed) == key + if not observed.partition("/")[2].startswith("0"): + stopped = connected_accounts._next_connection(observed, inactive=True) + await connected_accounts._move_fence(observed, stopped, ch=self.ch) + observed = stopped + await account_store.erase(account.org, [account.subject], kind=account.kind, ch=self.ch) + await require_erased(account.org, account.subject, account.kind, ch=self.ch) + if observed is not None: + await claims._drop(self.ch, key, observed) + assert await claims.get(self.ch, key) is None + + async def cleanup_source(self, row: dict[str, Any]) -> None: + async with self.locked(row): + await self.ch.execute( + "DELETE FROM loom.knowledge_sources WHERE org = {org:String} " + "AND namespace = {namespace:String} AND name = {name:String} " + "AND source_id = {source_id:UUID}", + params={key: row[key] for key in ("org", "namespace", "name", "source_id")}, + settings={"lightweight_deletes_sync": 2}, + ) + if (row["org"], row["namespace"]) in self.mirrors: + item = self.retirement(row) + await self.ch.execute( + "DELETE FROM loom.code_index_state WHERE org = {org:String} " + "AND namespace = {mirror:String} AND state_key = {key:String}", + params={"org": item.org, "mirror": item.mirror, "key": item.key}, + settings={"lightweight_deletes_sync": 2}, + ) + + async def cleanup_mirror(self, org: str, namespace: str, mirror: str) -> None: + async with sources_lease(org, namespace, ch=self.ch): + await self.ch.execute( + "DELETE FROM loom.knowledge_mirrors WHERE org = {org:String} " + "AND namespace = {namespace:String} AND mirror = {mirror:String}", + params={"org": org, "namespace": namespace, "mirror": mirror}, + settings={"lightweight_deletes_sync": 2}, + ) + + async def cleanup(self) -> None: + failures = [] + work = [(self.cleanup_account, (a,)) for a in self.accounts] + work += [(self.cleanup_source, (r,)) for r in self.rows] + work += [(self.cleanup_mirror, (o, n, m)) for (o, n), m in self.mirrors.items()] + for operation, arguments in work: + set_query_tag("test.mcp-source-lifecycle.cleanup") + try: + await operation(*arguments) + except Exception as error: # noqa: BLE001 — attempt cleanup of every owned identity + failures.append(error) + if failures: + raise ExceptionGroup("MCP lifecycle fixture cleanup failed", failures) + + +@pytest.fixture +async def world(monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[_World]: + ch = CHClient() + await ch.connect() + state = _World(ch, unique_org("mcp-source-lifecycle")) + # Store/lease defaults resolve the first factory; account lifecycle captures the second. + # Both bindings use this same real client, without replacing any SQL or authority result. + monkeypatch.setattr(ch_module, "get_client", lambda: ch) + monkeypatch.setattr(connected_accounts, "get_client", lambda: ch) + try: + yield state + finally: + try: + await state.cleanup() + finally: + await ch.disconnect() + + +@pytest.mark.parametrize( + ("config", "items"), + [(CONFIG, ITEMS), ('{"marker":"opaque-config",', '[{"marker":"opaque-selection"},')], + ids=["unknown-fields", "corrupt-json"], +) +async def test_raw_metadata_roundtrips_without_native_admission( + world: _World, config: str, items: str +) -> None: + row = await world.seed("opaque", "a" * 32, config=config, items=items) + native = await world.seed( + "native", + "d" * 32, + native=True, + generation=NATIVE_GENERATION, + config='{"folder_ids":["fixture-folder"]}', + items='[{"type":"folder","id":"fixture-folder"}]', + ) + before, native_before = await world.raw(row), await world.raw(native) + assert before is not None and native_before is not None + async with world.locked(row): + source = await source_store.latest_source( + world.org, row["namespace"], row["name"], ch=world.ch + ) + assert source is not None + assert (source.kind, source.credential_mode, source.access) == ("mcp", "mcp", "mirrored") + assert source.connection_slot == SLOT + assert source.connection_id == GENERATION + assert source.source_contract_version == 1 + assert source.source_id == row["source_id"] + assert not served(source) and not mirror_synced(source) + assert "opaque-config" not in repr(source) + assert "opaque-selection" not in repr(source) + await source_store.insert_source( + replace(source, created_by="roundtrip-writer"), ch=world.ch + ) + assert await world.raw(row) == before | {"created_by": "roundtrip-writer"} + assert await world.raw(native) == native_before + neighbor = await source_store.latest_source( + world.org, native["namespace"], native["name"], ch=world.ch + ) + assert neighbor is not None and mirror_synced(neighbor) + + +async def test_slot_selectors_and_erasure_preserve_other_bindings(world: _World) -> None: + first = await world.seed("first", "a" * 32) + historical = await world.seed( + "historical", "e" * 32, namespace="historical", generation=LATER_GENERATION + ) + second = await world.seed("second", "b" * 32, slot=OTHER_SLOT, generation=OTHER_GENERATION) + other_owner = await world.seed( + "other-owner", "c" * 32, owner=OTHER_OWNER, generation=SECOND_OWNER_GENERATION + ) + native = await world.seed( + "native", + "d" * 32, + native=True, + generation=NATIVE_GENERATION, + config='{"folder_ids":["fixture-folder"]}', + items='[{"type":"folder","id":"fixture-folder"}]', + ) + retained = [second, other_owner, native] + snapshots = [await world.raw(row) for row in retained] + owned = await source_store.connected_sources(world.org, OWNER, ch=world.ch) + assert {source.source_id for source in owned} == { + row["source_id"] for row in (first, historical, second, native) + } + assert await source_store.connected_owner_namespaces(world.org, OWNER, SLOT, ch=world.ch) == [ + "historical", + "selected", + ] + assert await source_store.connected_owner_namespaces( + world.org, OWNER, OTHER_SLOT, ch=world.ch + ) == ["selected"] + history = await source_store.connected_history(owner=(world.org, OWNER, SLOT), ch=world.ch) + assert {source.source_id for source in history} == {first["source_id"], historical["source_id"]} + async with connected_accounts.account_lease(world.org, OWNER, SLOT, ch=world.ch): + # Absence is checked while holding the account lease; no active account can race this erase. + assert await account_store.get(world.org, OWNER, SLOT, ch=world.ch) is None + for row in (first, historical): + set_query_tag("test.mcp-source-lifecycle.erase") + async with sources_lease(world.org, row["namespace"], ch=world.ch): + assert ( + await connected_source_residue( + world.org, row["namespace"], OWNER, SLOT, ch=world.ch + ) + == 1 + ) + with pytest.raises(OverloadedError): + await require_sources_erased( + world.org, row["namespace"], OWNER, SLOT, ch=world.ch + ) + await source_store.erase_connected_owner( + world.org, row["namespace"], OWNER, SLOT, ch=world.ch + ) + await require_sources_erased(world.org, row["namespace"], OWNER, SLOT, ch=world.ch) + assert await world.raw(row) is None + assert [await world.raw(kept) for kept in retained] == snapshots + assert await source_store.connected_history(owner=(world.org, OWNER, SLOT), ch=world.ch) == [] + assert await source_store.connected_owner_namespaces(world.org, OWNER, SLOT, ch=world.ch) == [] + for row in retained: + set_query_tag("test.mcp-source-lifecycle.neighbor") + slot = row["connection_slot"] or row["source_kind"] + assert ( + await connected_source_residue( + world.org, row["namespace"], row["owner_subject"], slot, ch=world.ch + ) + == 1 + ) + + +async def test_source_only_restore_inventory_validates_slot_and_generation( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + first = await world.seed("first", "a" * 32) + past = await world.seed("historical", "e" * 32, generation=LATER_GENERATION) + second = await world.seed("second", "b" * 32, slot=OTHER_SLOT, generation=OTHER_GENERATION) + await world.seed("other-owner", "c" * 32, owner=OTHER_OWNER, generation=SECOND_OWNER_GENERATION) + + def refuse_decryption(*args: Any, **kwargs: Any) -> None: + pytest.fail("Restore inventory tried to decrypt an envelope") + + monkeypatch.setattr(connected_restore, "unseal", refuse_decryption) + owner = (world.org, OWNER, SLOT) + assert await account_store.restore_keys(owner=owner, ch=world.ch) == [] + keys, sources = await connected_restore._metadata(world.ch, owner) + assert set(keys) == {(*owner, GENERATION), (*owner, LATER_GENERATION)} + assert {source.source_id for source in sources} == {first["source_id"], past["source_id"]} + other_keys, other_sources = await connected_restore._metadata( + world.ch, (world.org, OWNER, OTHER_SLOT) + ) + assert other_keys == [(world.org, OWNER, OTHER_SLOT, OTHER_GENERATION)] + assert [source.source_id for source in other_sources] == [second["source_id"]] + groups: dict[tuple[str, str, str], set[str]] = defaultdict(set) + prefixes: dict[str, tuple[str, str, str]] = {} + connected_restore._include(groups, prefixes, keys + other_keys) + assert dict(groups) == { + owner: {GENERATION, LATER_GENERATION}, + (world.org, OWNER, OTHER_SLOT): {OTHER_GENERATION}, + } + for collision in [ + (world.org, OTHER_OWNER, SLOT, GENERATION), + (world.org, OWNER, OTHER_SLOT, GENERATION), + (world.org + "-other", OWNER, SLOT, GENERATION), + ]: + with pytest.raises(ValidationError): + connected_restore._include(defaultdict(set), dict(prefixes), [collision]) + invalid_slots = ( + "mcp", + "mcp:", + "mcp:" + "A" * 32, + "mcp:" + "a" * 31, + "mcp:" + "g" * 32, + SLOT + " ", + ) + for invalid in invalid_slots: + with pytest.raises(ValidationError): + connected_restore._include( + defaultdict(set), {}, [(world.org, OWNER, invalid, GENERATION)] + ) + for invalid_generation in ( + "1" * 32 + "/2" + "a" * 31, + GENERATION[:-1], + "F" * 32 + "/0" + "a" * 31, + ): + with pytest.raises(ValidationError): + connected_restore._include(defaultdict(set), {}, [(*owner, invalid_generation)]) + + +async def test_superseded_same_key_binding_is_erased_without_touching_final_owner( + world: _World, +) -> None: + other_org = unique_org("mcp-source-history-neighbor") + old = world.source_row( + "replaced", str(uuid4()), generation=uuid4().hex + "/1" + uuid4().hex[1:] + ) + newer = world.source_row( + old["name"], + str(uuid4()), + owner=OTHER_OWNER, + slot=OTHER_SLOT, + generation=uuid4().hex + "/1" + uuid4().hex[1:], + version=2, + ) + other_namespace = await world.seed("replaced", str(uuid4()), namespace="untouched") + other_tenant = await world.seed("replaced", str(uuid4()), org=other_org) + # One real batch keeps both versions at the actual (org, namespace, name) key. + await world.insert_rows([old, newer]) + raw = await world.source_versions(old) + assert {str(r["source_id"]) for r in raw} == {old["source_id"], newer["source_id"]}, ( + "both superseded raw versions must exist before history/erasure qualification" + ) + [latest] = await world.source_versions(old, final=True) + assert str(latest["source_id"]) == newer["source_id"] + assert (latest["owner_subject"], latest["connection_slot"]) == (OTHER_OWNER, OTHER_SLOT) + neighbors = [newer, other_namespace, other_tenant] + before = [await world.source_versions(row, final=True) for row in neighbors] + history = await source_store.connected_history(owner=(world.org, OWNER, SLOT), ch=world.ch) + assert {s.source_id for s in history} == {old["source_id"], other_namespace["source_id"]} + assert await source_store.connected_owner_namespaces(world.org, OWNER, SLOT, ch=world.ch) == [ + "selected", + "untouched", + ] + async with world.locked(old): + assert await account_store.get(world.org, OWNER, SLOT, ch=world.ch) is None + assert ( + await connected_source_residue(world.org, old["namespace"], OWNER, SLOT, ch=world.ch) + == 1 + ) + with pytest.raises(OverloadedError): + await require_sources_erased(world.org, old["namespace"], OWNER, SLOT, ch=world.ch) + await source_store.erase_connected_owner( + world.org, old["namespace"], OWNER, SLOT, ch=world.ch + ) + await require_sources_erased(world.org, old["namespace"], OWNER, SLOT, ch=world.ch) + remaining = await world.source_versions(old) + assert len(remaining) == 1 and str(remaining[0]["source_id"]) == newer["source_id"] + assert [await world.source_versions(row, final=True) for row in neighbors] == before + remaining_history = await source_store.connected_history( + owner=(world.org, OWNER, SLOT), ch=world.ch + ) + assert [s.source_id for s in remaining_history] == [other_namespace["source_id"]] + assert await connected_source_residue(world.org, "untouched", OWNER, SLOT, ch=world.ch) == 1 + assert await connected_source_residue(other_org, "selected", OWNER, SLOT, ch=world.ch) == 1 + + +async def _seed_lifecycle( + world: _World, +) -> tuple[ConnectedAccount, list[dict[str, Any]], list[ConnectedAccount], list[dict[str, Any]]]: + target = await world.seed_account() + neighbors = [ + await world.seed_account(OTHER_SLOT), + await world.seed_account("gdrive"), + await world.seed_account(owner=OTHER_OWNER), + await world.seed_account(org=unique_org("mcp-source-stop-neighbor")), + ] + for org, namespace in {(a.org, "selected") for a in [target, *neighbors]} | { + (target.org, "historical") + }: + await world.add_mirror(org, namespace) + selected = [] + for name, namespace in [("unknown-contract", "selected"), ("corrupt-contract", "historical")]: + selected.append( + await world.seed( + name, + str(uuid4()), + namespace=namespace, + generation=target.connection_id, + config='{"future":', + items='[{"future":', + contract_version=65535, + active=True, + ) + ) + other_rows = [] + for index, account in enumerate(neighbors): + other_rows.append( + await world.seed( + f"neighbor-{index}", + str(uuid4()), + org=account.org, + owner=account.subject, + slot=account.kind, + generation=account.connection_id, + native=account.kind == "gdrive", + ) + ) + return target, selected, neighbors, other_rows + + +async def _neighbor_snapshot( + world: _World, accounts: list[ConnectedAccount], rows: list[dict[str, Any]] +) -> tuple[Any, ...]: + return ( + [await world.account_versions(account) for account in accounts], + [ + await claims.get(world.ch, connected_accounts._fence_key(a.connection_id)) + for a in accounts + ], + [await world.source_versions(row, final=True) for row in rows], + [await world.retirement_row(row) for row in rows], + ) + + +def _forbid_decryption(*args: Any, **kwargs: Any) -> None: + pytest.fail("local stop/erasure tried to decrypt a generic credential") + + +async def _assert_stopped( + world: _World, + original: ConnectedAccount, + ended: ConnectedAccount, + rows: list[dict[str, Any]], + before: list[dict[str, Any]], +) -> None: + key = connected_accounts._fence_key(original.connection_id) + assert ended.connection_id != original.connection_id + assert connected_accounts._fence_key(ended.connection_id) == key + assert ended.connection_id.partition("/")[2].startswith("0") + assert await claims.get(world.ch, key) == ended.connection_id + marker = await account_store.get(original.org, original.subject, original.kind, ch=world.ch) + assert marker is not None and marker.connection_id == ended.connection_id + [raw] = await world.account_versions(original) + assert not raw["active"] and raw["connected_at"] is None + assert raw["disconnected_at"] is not None + for column in ( + "credential_enc", + "account_email_enc", + "account_id", + "workspace_id", + "refresh_id", + ): + assert raw[column] == "" + assert not raw["scopes"] + assert ( + await connected_account_residue( + original.org, + original.subject, + original.kind, + keep_connection=ended.connection_id, + ch=world.ch, + ) + == 0 + ) + assert ( + await connected_account_residue( + original.org, + original.subject, + original.kind, + ch=world.ch, + ) + == 1 + ) + await require_erased( + original.org, + original.subject, + original.kind, + keep_connection=ended.connection_id, + ch=world.ch, + ) + for row, initial in zip(rows, before, strict=True): + [current] = await world.source_versions(row, final=True) + assert current == initial | { + "active": False, + "credential_enc": "", + "secret_enc": "", + "pending_delete": True, + "updated_at": current["updated_at"], + "version": current["version"], + } + item = world.retirement(row) + assert await source_retirements.pending(item, ch=world.ch) + retirement = await world.retirement_row(row) + assert retirement is not None and retirement["state_value"] == "pending" + assert json.loads(retirement["detail"]) == { + "namespace": row["namespace"], + "name": row["name"], + "source_id": row["source_id"], + "kind": "mcp", + } + assert ( + await connected_source_residue( + original.org, + row["namespace"], + original.subject, + original.kind, + ch=world.ch, + ) + > 0 + ) + + +async def _erase_stopped( + world: _World, ended: ConnectedAccount, rows: list[dict[str, Any]] +) -> None: + async with connected_accounts.account_lease(ended.org, ended.subject, ended.kind, ch=world.ch): + await connected_accounts._erase_locked(ended, keep_marker=False) + assert await world.account_versions(ended) == [] + assert await account_store.get(ended.org, ended.subject, ended.kind, ch=world.ch) is None + await require_erased(ended.org, ended.subject, ended.kind, ch=world.ch) + for row in rows: + assert await world.source_versions(row) == [] + await require_sources_erased( + ended.org, row["namespace"], ended.subject, ended.kind, ch=world.ch + ) + # Removing account history must not discard the durable copy-retirement request. + assert await source_retirements.pending(world.retirement(row), ch=world.ch) + assert ( + await claims.get(world.ch, connected_accounts._fence_key(ended.connection_id)) + == ended.connection_id + ) + + +async def test_stop_and_owner_erase_use_real_fence_retirement_and_census( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + account, selected, neighbors, other_rows = await _seed_lifecycle(world) + before = [(await world.source_versions(row, final=True))[0] for row in selected] + neighbors_before = await _neighbor_snapshot(world, neighbors, other_rows) + monkeypatch.setattr(connected_accounts, "unseal", _forbid_decryption) + async with connected_accounts.account_lease( + account.org, account.subject, account.kind, ch=world.ch + ): + ended = await connected_accounts._stop_locked(account) + await _assert_stopped(world, account, ended, selected, before) + assert await _neighbor_snapshot(world, neighbors, other_rows) == neighbors_before + await _erase_stopped(world, ended, selected) + assert await _neighbor_snapshot(world, neighbors, other_rows) == neighbors_before + + +class _AfterFenceFailure(RuntimeError): + pass + + +async def test_stop_recovers_after_fence_lands_before_account_marker( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + account, selected, neighbors, other_rows = await _seed_lifecycle(world) + before = [(await world.source_versions(row, final=True))[0] for row in selected] + neighbors_before = await _neighbor_snapshot(world, neighbors, other_rows) + real_put = account_store.put + failed = False + + async def fail_marker_once(value: ConnectedAccount, **kwargs: Any) -> None: + nonlocal failed + if ( + not failed + and (value.org, value.subject, value.kind) + == (account.org, account.subject, account.kind) + and not value.active + ): + failed = True + raise _AfterFenceFailure("injected failure after durable stop fence") + await real_put(value, **kwargs) + + monkeypatch.setattr(connected_accounts, "unseal", _forbid_decryption) + async with connected_accounts.account_lease( + account.org, account.subject, account.kind, ch=world.ch + ): + with monkeypatch.context() as injection: + injection.setattr(account_store, "put", fail_marker_once) + with pytest.raises(_AfterFenceFailure, match="after durable stop fence"): + await connected_accounts._stop_locked(account) + assert failed + stopped_fence = await claims.get( + world.ch, connected_accounts._fence_key(account.connection_id) + ) + assert stopped_fence is not None and stopped_fence != account.connection_id + assert stopped_fence.partition("/")[2].startswith("0") + still_live = await account_store.get( + account.org, account.subject, account.kind, ch=world.ch + ) + assert still_live is not None and still_live.active + assert still_live.connection_id == account.connection_id + assert still_live.credential_enc == account.credential_enc + assert [(await world.source_versions(row, final=True))[0] for row in selected] == before + assert [await world.retirement_row(row) for row in selected] == [None, None] + ended = await connected_accounts._stop_locked(still_live) + assert ended.connection_id == stopped_fence + await _assert_stopped(world, account, ended, selected, before) + assert await _neighbor_snapshot(world, neighbors, other_rows) == neighbors_before + await _erase_stopped(world, ended, selected) + assert await _neighbor_snapshot(world, neighbors, other_rows) == neighbors_before + + +@asynccontextmanager +async def _scim_erasure_ready( + world: _World, monkeypatch: pytest.MonkeyPatch, owner: str +) -> AsyncIterator[None]: + """The real post-deactivation caller reads an actual, uniquely owned SCIM cutoff.""" + key = revocation.SCIM_PREFIX + owner + params = {"key": key} + + async def stored() -> dict[str, Any] | None: + return await world.ch.query_one( + "SELECT jti FROM loom.revoked_tokens FINAL WHERE jti = {key:String} LIMIT 1", + params=params, + ) + + def no_provider(*args: Any, **kwargs: Any) -> None: + pytest.fail("canonical generic owner erasure consulted a native provider") + + with monkeypatch.context() as wiring: + # Direct auth calls use the same real composition as HTTP/CLI roots. No SQL is faked. + wiring.setattr(account_lifecycle, "_stopper", connected_accounts.stop_subjects) + wiring.setattr(connected_accounts, "client", no_provider) + async with scim.subject_leases([owner]): + assert await stored() is None + try: + async with scim.subject_leases([owner]): + await world.ch.insert( + "loom.revoked_tokens", + [ + { + "jti": key, + "revoked_at": datetime.now(UTC), + "expires_at": revocation.revocation_expiry(None), + "reason": "synthetic owner erasure", + "revoked_by": "scim", + "issued_before": None, + "version": 1, + } + ], + ) + # Read the same real cutoff authority used by stop_subjects, not a cache stub. + assert await revocation.cutoffs([owner], permanent=True) == {owner: None} + yield + finally: + async with scim.subject_leases([owner]): + await world.ch.execute( + "DELETE FROM loom.revoked_tokens WHERE jti = {key:String}", + params=params, + settings={"lightweight_deletes_sync": 2}, + ) + assert await stored() is None + + +async def _seed_canonical_owner_erasure( + world: _World, *, with_accounts: bool +) -> tuple[ + str, + list[ConnectedAccount], + list[dict[str, Any]], + list[ConnectedAccount], + list[dict[str, Any]], +]: + # The SCIM handoff intentionally spans orgs: fixed shared subjects would be unsafe. + owner = f"mcp-erased-{uuid4().hex}@example.test" + neighbor_owner = f"mcp-retained-{uuid4().hex}@example.test" + orgs = [world.org, unique_org("mcp-source-owner-neighbor")] + accounts: list[ConnectedAccount] = [] + selected: list[dict[str, Any]] = [] + neighbors: list[ConnectedAccount] = [] + other_rows: list[dict[str, Any]] = [] + for org, account_slot in zip(orgs, (SLOT, OTHER_SLOT), strict=True): + set_query_tag("test.mcp-source-lifecycle.owner-seed") + await world.add_mirror(org, "owner-erasure") + for slot in (SLOT, OTHER_SLOT): + account = None + if with_accounts and slot == account_slot: + account = await world.seed_account(slot, org=org, owner=owner) + accounts.append(account) + generation = account.connection_id if account else uuid4().hex + "/1" + uuid4().hex[1:] + if account is None: + # Cleanup owns this historical prefix even if a later implementation fences it. + # This is bookkeeping only: no account row or claim is invented for the history. + async with connected_accounts.account_lease(org, owner, slot, ch=world.ch): + assert ( + await claims.get(world.ch, connected_accounts._fence_key(generation)) + is None + ) + world.accounts.append( + ConnectedAccount(org, owner, slot, generation, active=False) + ) + assert await account_store.get(org, owner, slot, ch=world.ch) is None + selected.append( + await world.seed( + ("registered" if account else "source-only") + + ("-first" if slot == SLOT else "-second"), + str(uuid4()), + org=org, + namespace="owner-erasure", + owner=owner, + slot=slot, + generation=generation, + active=account is not None, + contract_version=65535, + config='{"unknown-owner-contract":', + items='[{"unknown-selection":', + ) + ) + neighbor = await world.seed_account(SLOT, org=org, owner=neighbor_owner) + neighbors.append(neighbor) + other_rows.append( + await world.seed( + "other-owner", + str(uuid4()), + org=org, + namespace="owner-erasure", + owner=neighbor_owner, + slot=neighbor.kind, + generation=neighbor.connection_id, + active=True, + ) + ) + native = await world.seed_account("gdrive", owner=neighbor_owner) + neighbors.append(native) + other_rows.append( + await world.seed( + "native-owner-neighbor", + str(uuid4()), + namespace="owner-erasure", + owner=neighbor_owner, + generation=native.connection_id, + native=True, + active=True, + config='{"folder_ids":["fixture-folder"]}', + items='[{"type":"folder","id":"fixture-folder"}]', + ) + ) + return owner, accounts, selected, neighbors, other_rows + + +@pytest.mark.parametrize( + "with_accounts", [True, False], ids=["mixed-account-history", "source-only-owner"] +) +async def test_scim_owner_erasure_handoff_erases_source_only_history_across_orgs( + world: _World, monkeypatch: pytest.MonkeyPatch, with_accounts: bool +) -> None: + owner, accounts, selected, neighbors, other_rows = await _seed_canonical_owner_erasure( + world, with_accounts=with_accounts + ) + before = await _neighbor_snapshot(world, neighbors, other_rows) + assert len(await account_store.owned([owner], ch=world.ch)) == len(accounts) + for row in selected: + set_query_tag("test.mcp-source-lifecycle.owner-before") + assert await world.source_versions(row) + assert ( + await connected_source_residue( + row["org"], row["namespace"], owner, row["connection_slot"], ch=world.ch + ) + == 1 + ) + assert await world.retirement_row(row) is None + async with _scim_erasure_ready(world, monkeypatch, owner): + # This is SCIM delete's real post-deactivation caller, including its current/previous + # subject union, respect_cutoff, erase_owner and service-account cleanup. Not _erase_locked. + subjects = [owner] if with_accounts else [] + previous_subjects = [] if with_accounts else [owner] + await scim._revoke_tokens( + {"subjects": subjects, "deleted": True}, previous_subjects=previous_subjects + ) + assert await _neighbor_snapshot(world, neighbors, other_rows) == before + assert await account_store.owned([owner], ch=world.ch) == [] + for account in accounts: + set_query_tag("test.mcp-source-lifecycle.owner-account-erased") + await require_erased(account.org, owner, account.kind, ch=world.ch) + for row in selected: + set_query_tag("test.mcp-source-lifecycle.owner-after") + key = connected_accounts._fence_key(row["connection_id"]) + stopped = await claims.get(world.ch, key) + assert stopped is not None, "canonical owner erasure left source-only history unfenced" + assert stopped != row["connection_id"] + assert connected_accounts._fence_key(stopped) == key + assert stopped.partition("/")[2].startswith("0") + assert await world.source_versions(row) == [], ( + "canonical owner erasure returned with generic source-only history still stored" + ) + await require_sources_erased( + row["org"], row["namespace"], owner, row["connection_slot"], ch=world.ch + ) + assert ( + await source_store.connected_history( + owner=(row["org"], owner, row["connection_slot"]), ch=world.ch + ) + == [] + ) + assert await source_retirements.pending(world.retirement(row), ch=world.ch) + # A repeated offboarding tail must neither revive work nor touch another owner's rows. + await scim._revoke_tokens( + {"subjects": subjects, "deleted": True}, previous_subjects=previous_subjects + ) + assert await _neighbor_snapshot(world, neighbors, other_rows) == before diff --git a/tests/unit/test_mcp_connection_lifecycle.py b/tests/unit/test_mcp_connection_lifecycle.py new file mode 100644 index 0000000000..5d276941f4 --- /dev/null +++ b/tests/unit/test_mcp_connection_lifecycle.py @@ -0,0 +1,619 @@ +"""Restore finds generic connection history without opening credentials or payloads.""" + +from collections import defaultdict +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import replace +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock, Mock + +import pytest + +from server.core.errors import ValidationError +from server.knowledge.app import connected_restore as restore +from server.knowledge.domain.sources import KnowledgeSource + +SLOT = "mcp:" + "a" * 32 +OTHER_SLOT = "mcp:" + "b" * 32 +CONNECTION = "c" * 32 + "/1" + "d" * 31 +OWNER = ("org-one", "owner-one", SLOT) + + +def test_restore_keeps_owner_and_slot_identity_separate() -> None: + groups: dict[Any, set[str]] = defaultdict(set) + prefixes: dict[str, Any] = {} + rows = [ + (*OWNER, CONNECTION), + ("org-one", "owner-one", OTHER_SLOT, "e" * 32 + "/1" + "f" * 31), + ("org-one", "owner-two", SLOT, "0" * 32 + "/1" + "1" * 31), + ] + restore._include(groups, prefixes, rows) + assert set(groups) == {row[:3] for row in rows} + assert all(groups[row[:3]] == {row[3]} for row in rows) + assert len(prefixes) == 3 + + +@pytest.mark.parametrize("slot", ["mcp:", "mcp:abc", "mcp:" + "A" * 32, SLOT + "/other"]) +def test_restore_refuses_malformed_generic_slot(slot: str) -> None: + with pytest.raises(ValidationError, match="the connected account is unavailable"): + restore._include(defaultdict(set), {}, [("org-one", "owner-one", slot, CONNECTION)]) + + +def test_restore_still_refuses_a_fence_prefix_shared_by_two_owners() -> None: + groups: dict[Any, set[str]] = defaultdict(set) + prefixes: dict[str, Any] = {} + with pytest.raises(ValidationError, match="the connected account is unavailable"): + restore._include( + groups, + prefixes, + [(*OWNER, CONNECTION), ("org-one", "owner-two", SLOT, CONNECTION)], + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("owner", [None, OWNER]) +async def test_source_only_restore_history_uses_slot_without_decoding_payload( + monkeypatch: pytest.MonkeyPatch, owner: tuple[str, str, str] | None +) -> None: + source = SimpleNamespace( + org=OWNER[0], + namespace="collection-one", + name="selected-documents", + source_id="source-one", + owner_subject=OWNER[1], + kind="mcp", + credential_mode="mcp", + connection_slot=SLOT, + connection_id=CONNECTION, + source_contract_version=65535, + generic_config_json="unparseable payload", + generic_items_json="unparseable selection", + ) + + async def no_accounts(**kwargs: Any) -> list[Any]: + assert kwargs["owner"] == owner + return [] + + async def history(**kwargs: Any) -> list[Any]: + assert kwargs["owner"] == owner + return [source] + + monkeypatch.setattr(restore.account_store, "restore_keys", no_accounts) + monkeypatch.setattr(restore.source_store, "connected_history", history) + keys, sources = await restore._metadata(object(), owner=owner) + assert keys == [(*OWNER, CONNECTION)] + assert sources == [source] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("generic", [True, False]) +@pytest.mark.parametrize("changed", ["same", "slot", "owner", "source"]) +async def test_restore_inactivates_only_current_exact_account_binding( + monkeypatch: pytest.MonkeyPatch, generic: bool, changed: str +) -> None: + source = KnowledgeSource( + "org-one", + "collection-one", + "selected-documents", + "mcp" if generic else "gdrive", + source_id="source-one", + credential_mode="mcp" if generic else "connected", + owner_subject="owner-one", + connection_slot=SLOT if generic else "", + connection_id=CONNECTION, + source_contract_version=65535 if generic else 0, + generic_config_json="opaque corrupt config", + generic_items_json="opaque corrupt items", + credential_enc="sealed-envelope", + secret_enc="sealed-secret", + active=True, + ) + changes: dict[str, Any] = {} + if changed == "slot": + changes = {"connection_slot": OTHER_SLOT} if generic else {"kind": "notion"} + elif changed == "owner": + changes = {"owner_subject": "owner-two"} + elif changed == "source": + changes = {"source_id": "source-two"} + current = replace(source, **changes) + written: list[KnowledgeSource] = [] + client = object() + + @asynccontextmanager + async def lease(org: str, namespace: str) -> AsyncIterator[None]: + assert (org, namespace) == (source.org, source.namespace) + yield + + async def latest(org: str, namespace: str, name: str, *, ch: Any) -> KnowledgeSource: + assert (org, namespace, name, ch) == (source.org, source.namespace, source.name, client) + return current + + async def put(value: KnowledgeSource, *, ch: Any) -> None: + assert ch is client + written.append(value) + + queue = AsyncMock(return_value=True) + retire = AsyncMock() + monkeypatch.setattr(restore.source_ops, "sources_lease", lease) + monkeypatch.setattr(restore.source_ops, "_queue_retirement", queue) + monkeypatch.setattr(restore.source_push, "retire", retire) + monkeypatch.setattr(restore.source_store, "latest_source", latest) + monkeypatch.setattr(restore.source_store, "insert_source", put) + await restore._retire_history([source], client) + queue.assert_awaited_once_with(source) + retire.assert_awaited_once_with(source) + if changed == "same": + assert written == [ + replace(current, active=False, credential_enc="", secret_enc="", pending_delete=True) + ] + assert written[0].generic_config_json == source.generic_config_json + assert written[0].generic_items_json == source.generic_items_json + assert written[0].connection_slot == source.connection_slot + assert written[0].source_contract_version == source.source_contract_version + else: + assert written == [] + assert source.active and source.credential_enc == "sealed-envelope" + + +class _MarkerWritten(Exception): + pass + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", [SLOT, "gdrive"]) +async def test_retry_reuses_valid_stopped_fence_without_same_value_cas( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + accounts = restore.accounts + account = restore.ConnectedAccount( + "org-one", "owner-one", kind, CONNECTION, credential_enc="unreadable-envelope", active=True + ) + landed = CONNECTION.partition("/")[0] + "/0" + "e" * 31 + client = object() + get = AsyncMock(return_value=landed) + swap = AsyncMock(side_effect=AssertionError("same-value CAS is unsupported")) + written: list[Any] = [] + + async def put(value: Any) -> None: + written.append(value) + raise _MarkerWritten + + monkeypatch.setattr(accounts, "get_client", lambda: client) + monkeypatch.setattr(accounts.claims, "get", get) + monkeypatch.setattr(accounts.claims, "swap", swap) + monkeypatch.setattr(accounts.store, "put", put) + with pytest.raises(_MarkerWritten): + await accounts._stop_locked(account) + get.assert_awaited_once_with(client, accounts._fence_key(CONNECTION)) + swap.assert_not_awaited() + assert len(written) == 1 + assert written[0].connection_id == landed + assert not written[0].active + assert written[0].credential_enc == written[0].account_email_enc == "" + assert account.active and account.credential_enc == "unreadable-envelope" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "strict,previous", + [ + (False, "other-prefix"), + (False, "different-live"), + (True, "other-prefix"), + (True, "different-live"), + (True, "stopped"), + ], +) +async def test_stop_refuses_foreign_or_live_fences_and_strict_recovery( + monkeypatch: pytest.MonkeyPatch, strict: bool, previous: str +) -> None: + accounts = restore.accounts + account = restore.ConnectedAccount("org-one", "owner-one", SLOT, CONNECTION, active=True) + prefix = "f" * 32 if previous == "other-prefix" else CONNECTION.partition("/")[0] + tail = "1" if previous == "different-live" else "0" + observed = prefix + "/" + tail + "e" * 31 + client = object() + get = AsyncMock(return_value=observed) + swap = AsyncMock() + put = AsyncMock() + monkeypatch.setattr(accounts, "get_client", lambda: client) + monkeypatch.setattr(accounts.claims, "get", get) + monkeypatch.setattr(accounts.claims, "swap", swap) + monkeypatch.setattr(accounts.store, "put", put) + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await accounts._stop_locked(account, strict=strict) + swap.assert_not_awaited() + put.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("already_stopped", [False, True]) +async def test_restore_reuses_durable_inactive_fence_without_same_value_cas( + monkeypatch: pytest.MonkeyPatch, already_stopped: bool +) -> None: + landed = CONNECTION.partition("/")[0] + "/0" + "e" * 31 + connection = landed if already_stopped else CONNECTION + client = object() + get = AsyncMock(return_value=landed) + swap = AsyncMock(side_effect=AssertionError("same-value CAS is unsupported")) + monkeypatch.setattr(restore.claims, "get", get) + monkeypatch.setattr(restore.claims, "swap", swap) + assert await restore._stop_key(connection, client) == landed + get.assert_awaited_once_with(client, restore.accounts._fence_key(connection)) + swap.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", [SLOT, "mcp", "unknown-source"]) +async def test_generic_credential_never_enters_native_revocation_factory( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: + factory = Mock( + side_effect=AssertionError("native revocation factory must not receive this kind") + ) + monkeypatch.setattr(restore.accounts, "client", factory) + account = restore.ConnectedAccount("org-one", "owner-one", kind, CONNECTION) + await restore.accounts._revoke(account, credential="nonempty-generic-envelope") + factory.assert_not_called() + + +@pytest.mark.asyncio +async def test_native_revocation_control_still_uses_its_existing_client( + monkeypatch: pytest.MonkeyPatch, +) -> None: + revoke = AsyncMock() + factory = Mock(return_value=SimpleNamespace(revoke=revoke)) + monkeypatch.setattr(restore.accounts, "client", factory) + account = restore.ConnectedAccount("org-one", "owner-one", "gdrive", CONNECTION) + await restore.accounts._revoke(account, credential="fixture-native-credential") + factory.assert_called_once_with("gdrive") + revoke.assert_awaited_once() + assert revoke.await_args.args == ("fixture-native-credential",) + assert revoke.await_args.kwargs["refresh"] is True + + +@pytest.fixture +def owner_history(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + """I/O seams retain identities and lease order; the lifecycle handlers stay real.""" + accounts = restore.accounts + state = SimpleNamespace( + history={}, rows={}, fences={}, events=[], held=[], cutoffs={"owner-one": None} + ) + + @asynccontextmanager + async def account_lease(*owner: str, **kwargs: Any) -> AsyncIterator[None]: + assert not state.held + state.held.append(owner) + try: + yield + finally: + state.held.pop() + + async def owned(subjects: list[str], *, org: str | None = None, **kwargs: Any) -> list[Any]: + return [v for k, v in state.rows.items() if k[1] in subjects and org in (None, k[0])] + + async def source_owners( + subjects: list[str] | None = None, *, org: str | None = None, **kwargs: Any + ) -> list[Any]: + return [ + k + for k in state.history + if org in (None, k[0]) and (subjects is None or k[1] in subjects) + ] + + async def identities(*, org: str | None = None, **kwargs: Any) -> list[Any]: + return sorted({k[:2] for k in state.rows if org in (None, k[0])}) + + async def get(*owner: str, **kwargs: Any) -> Any: + return state.rows.get(owner) + + async def history(*, owner: Any = None, **kwargs: Any) -> list[Any]: + assert owner is not None + return state.history.get(owner, []) + + async def keys(*, owner: Any = None, **kwargs: Any) -> list[Any]: + row = state.rows.get(owner) + return [(*owner, row.connection_id)] if row else [] + + monkeypatch.setattr(accounts, "get_client", lambda: state) + monkeypatch.setattr(accounts, "account_lease", account_lease) + monkeypatch.setattr(accounts.store, "owned", owned) + monkeypatch.setattr(accounts.store, "owner_identities", identities) + monkeypatch.setattr(accounts.store, "get", get) + monkeypatch.setattr(accounts.store, "restore_keys", keys) + monkeypatch.setattr(restore.source_store, "connected_owners", source_owners, raising=False) + monkeypatch.setattr(restore.source_store, "connected_history", history) + monkeypatch.setattr( + accounts.aliases, "verified_spellings", AsyncMock(side_effect=lambda o, s: [s]) + ) + monkeypatch.setattr( + accounts.revocation, "cutoffs", AsyncMock(side_effect=lambda *a, **k: state.cutoffs) + ) + monkeypatch.setattr(accounts, "unseal", Mock(side_effect=AssertionError("unseal not required"))) + monkeypatch.setattr(restore, "unseal", Mock(side_effect=AssertionError("unseal not required"))) + monkeypatch.setattr(accounts, "_revoke", AsyncMock()) + _wire_owner_history_writes(monkeypatch, state) + return state + + +def _wire_owner_history_writes(monkeypatch: pytest.MonkeyPatch, state: SimpleNamespace) -> None: + async def fence_get(ch: Any, key: str) -> str | None: + assert ch is state + return state.fences.get(key) + + async def swap(ch: Any, key: str, old: Any, new: str, expiry: int) -> str: + assert state.held and state.fences.get(key) == old and old != new + state.fences[key] = new + state.events.append(("fence", state.held[0])) + return new + + async def put(account: Any, **kwargs: Any) -> None: + owner = account.org, account.subject, account.kind + assert state.held == [owner] and not account.active and not account.credential_enc + state.rows[owner] = account + state.events.append(("marker", owner)) + + async def retire(sources: list[Any], ch: Any) -> None: + assert ch is state + for source in sources: + owner = source.org, source.owner_subject, source.connection_slot or source.kind + assert state.held == [owner] + assert ( + state.fences[restore.accounts._fence_key(source.connection_id)].split("/")[1][0] + == "0" + ) + state.events.append(("retire", owner)) + + async def erase(account: Any, *, keep_marker: bool) -> None: + owner = account.org, account.subject, account.kind + assert not keep_marker and state.held == [owner] + assert ("retire", owner) in state.events + state.history.pop(owner, None) + state.rows.pop(owner, None) + state.events.append(("erase", owner)) + + monkeypatch.setattr(restore.claims, "get", fence_get) + monkeypatch.setattr(restore.claims, "swap", swap) + monkeypatch.setattr(restore.account_store, "put", put) + monkeypatch.setattr(restore, "_retire_history", retire) + monkeypatch.setattr(restore.accounts, "_erase_locked", erase) + + +def _owner_source(owner: tuple[str, str, str], prefix: str) -> KnowledgeSource: + return KnowledgeSource( + owner[0], + "collection-one", + "selected", + "mcp", + source_id="source-" + prefix, + credential_mode="mcp", + owner_subject=owner[1], + connection_slot=owner[2], + connection_id=prefix * 32 + "/1" + "d" * 31, + source_contract_version=65535, + generic_config_json="unknown {", + generic_items_json="corrupt [", + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("org", [None, "org-one"]) +@pytest.mark.parametrize("respect_cutoff", [False, True]) +async def test_owner_erasure_discovers_source_only_history_without_accounts( + owner_history: SimpleNamespace, org: str | None, respect_cutoff: bool +) -> None: + state = owner_history + owners = [OWNER, ("org-two", OWNER[1], OTHER_SLOT), (OWNER[0], "neighbor", SLOT)] + state.history = { + owner: [_owner_source(owner, prefix)] for owner, prefix in zip(owners, "abc", strict=True) + } + retained = { + k: v for k, v in state.history.items() if k[1] != OWNER[1] or org not in (None, k[0]) + } + await restore.accounts.stop_subjects( + [OWNER[1]], org=org, erase_owner=True, respect_cutoff=respect_cutoff, revoke=False + ) + assert state.history == retained + selected = set(owners) - set(retained) + assert {owner for event, owner in state.events if event == "erase"} == selected + assert not state.rows and len(state.fences) == len(selected) + restore.unseal.assert_not_called() + restore.accounts.unseal.assert_not_called() + + +@pytest.mark.asyncio +async def test_owner_erasure_refuses_dated_source_only_standing( + owner_history: SimpleNamespace, +) -> None: + state = owner_history + state.history = {OWNER: [_owner_source(OWNER, "a")]} + state.cutoffs = {OWNER[1]: 200} + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await restore.accounts.stop_subjects( + [OWNER[1]], erase_owner=True, respect_cutoff=True, revoke=False + ) + assert OWNER in state.history and not state.events + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cutoffs", [{}, {OWNER[1]: 100}, {OWNER[1]: 200}]) +async def test_owner_erasure_keeps_lifted_or_newer_account_standing( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, cutoffs: dict[str, int | None] +) -> None: + from datetime import UTC, datetime + + state = owner_history + state.history = {OWNER: [_owner_source(OWNER, "a")]} + state.rows[OWNER] = restore.ConnectedAccount( + *OWNER, CONNECTION, active=True, connected_at=datetime.fromtimestamp(200, UTC) + ) + state.cutoffs = cutoffs + # The inventory saw an older account; the account lease must protect the re-read authority. + stale = replace(state.rows[OWNER], connected_at=datetime.fromtimestamp(50, UTC)) + monkeypatch.setattr(restore.account_store, "owned", AsyncMock(return_value=[stale])) + await restore.accounts.stop_subjects( + [OWNER[1]], erase_owner=True, respect_cutoff=True, revoke=False + ) + assert OWNER in state.history and OWNER in state.rows and not state.events + + +@pytest.mark.asyncio +async def test_owner_erasure_keeps_source_only_history_when_cutoff_is_lifted( + owner_history: SimpleNamespace, +) -> None: + state = owner_history + state.history = {OWNER: [_owner_source(OWNER, "a")]} + state.cutoffs = {} + await restore.accounts.stop_subjects([OWNER[1]], erase_owner=True, respect_cutoff=True) + assert OWNER in state.history and not state.events + + +@pytest.mark.asyncio +async def test_owner_erasure_alias_is_verified_separately_in_each_org( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + other = ("org-two", OWNER[1], OTHER_SLOT) + state.history = {OWNER: [_owner_source(OWNER, "a")], other: [_owner_source(other, "b")]} + + async def spellings(org: str, subject: str) -> list[str]: + assert subject == OWNER[1] + return [subject, "verified-alias"] if org == OWNER[0] else [subject] + + monkeypatch.setattr(restore.accounts.aliases, "verified_spellings", spellings) + await restore.accounts.stop_subjects( + ["verified-alias"], erase_owner=True, respect_cutoff=True, revoke=False + ) + assert set(state.history) == {other} + assert {owner for event, owner in state.events if event == "erase"} == {OWNER} + + +@pytest.mark.asyncio +async def test_owner_erasure_retries_marker_after_retirement_before_erase_failure( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + state.history = {OWNER: [_owner_source(OWNER, "a")]} + erase = restore.accounts._erase_locked + attempted = False + + async def interrupted(account: Any, *, keep_marker: bool) -> None: + nonlocal attempted + if not attempted: + attempted = True + assert not keep_marker and ("retire", OWNER) in state.events + raise _MarkerWritten + await erase(account, keep_marker=keep_marker) + + monkeypatch.setattr(restore.accounts, "_erase_locked", interrupted) + with pytest.raises(_MarkerWritten): + await restore.accounts.stop_subjects( + [OWNER[1]], erase_owner=True, respect_cutoff=True, revoke=False + ) + stopped = dict(state.fences) + assert OWNER in state.history and OWNER in state.rows + await restore.accounts.stop_subjects( + [OWNER[1]], erase_owner=True, respect_cutoff=True, revoke=False + ) + assert not state.history and not state.rows and state.fences == stopped + assert state.events.count(("fence", OWNER)) == 1 + + +@pytest.mark.asyncio +async def test_owner_erasure_revokes_only_after_all_local_history_is_retired( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + native = (OWNER[0], OWNER[1], "gdrive") + state.rows[OWNER] = restore.ConnectedAccount(*OWNER, CONNECTION, active=True) + state.rows[native] = restore.ConnectedAccount(*native, "b" * 32 + "/1" + "e" * 31, active=True) + state.history = { + OWNER: [_owner_source(OWNER, "a")], + native: [ + replace( + _owner_source(native, "b"), + kind="gdrive", + credential_mode="connected", + connection_slot="", + ) + ], + } + revoked = [] + + async def revoke(account: Any, **kwargs: Any) -> None: + assert not state.history and not state.rows and not state.held + revoked.append((account.org, account.subject, account.kind)) + + monkeypatch.setattr(restore.accounts, "_revoke", revoke) + await restore.accounts.stop_subjects([OWNER[1]], erase_owner=True, respect_cutoff=True) + assert set(revoked) == {OWNER, native} + assert all( + event != "erase" or ("retire", owner) in state.events for event, owner in state.events + ) + + +@pytest.mark.asyncio +async def test_owner_erasure_refuses_aggregate_inventory_overflow_before_fencing( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + source = _owner_source(OWNER, "a") + state.history = {OWNER: [source, replace(source, connection_id="b" * 32 + "/1" + "e" * 31)]} + monkeypatch.setattr(restore.settings, "knowledge_connected_registry_scan_limit", 1) + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await restore.accounts.stop_subjects([OWNER[1]], erase_owner=True, revoke=False) + assert not state.events and OWNER in state.history + + +@pytest.mark.asyncio +@pytest.mark.parametrize("overflow", [False, True]) +async def test_owner_history_identity_query_is_bounded_scoped_and_payload_free( + monkeypatch: pytest.MonkeyPatch, overflow: bool +) -> None: + statements = [] + + async def query(sql: str, *, params: dict[str, Any]) -> list[dict[str, str]]: + statements.append(sql) + assert "org = {org:String}" in sql and "owner_subject IN {subjects:Array(String)}" in sql + assert " FINAL" not in sql + assert all(name not in sql for name in ("config_json", "items_json", "credential_enc")) + assert params == {"org": OWNER[0], "subjects": [OWNER[1]], "limit": 2} + return [{"org": OWNER[0], "owner_subject": OWNER[1], "slot": SLOT}] * (2 if overflow else 1) + + monkeypatch.setattr(restore.settings, "knowledge_connected_registry_scan_limit", 1) + ch = SimpleNamespace(query_all=query) + if overflow: + with pytest.raises(RuntimeError, match="connected_source_owner_bound"): + await restore.source_store.connected_owners([OWNER[1]], org=OWNER[0], ch=ch) + else: + assert await restore.source_store.connected_owners([OWNER[1]], org=OWNER[0], ch=ch) == [ + OWNER + ] + assert len(statements) == 1 + + +@pytest.mark.asyncio +async def test_owner_erasure_refuses_history_growth_past_bound_under_lease( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + source = _owner_source(OWNER, "a") + calls = 0 + + async def history(*, owner: Any = None, **kwargs: Any) -> list[Any]: + nonlocal calls + assert owner == OWNER + calls += 1 + if calls == 1: + assert not state.held + return [source] + assert state.held == [OWNER] + return [source, replace(source, connection_id="b" * 32 + "/1" + "e" * 31)] + + state.history = {OWNER: [source]} + monkeypatch.setattr(restore.source_store, "connected_history", history) + monkeypatch.setattr(restore.settings, "knowledge_connected_registry_scan_limit", 1) + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await restore.accounts.stop_subjects([OWNER[1]], erase_owner=True, revoke=False) + assert calls == 2 and not state.events diff --git a/tests/unit/test_mcp_source_contract.py b/tests/unit/test_mcp_source_contract.py new file mode 100644 index 0000000000..e69efbeb9b --- /dev/null +++ b/tests/unit/test_mcp_source_contract.py @@ -0,0 +1,284 @@ +"""The pure codecs do not qualify storage, secret rotation or source authorization.""" + +from __future__ import annotations + +import json +import traceback +from typing import Any + +import pytest +from pydantic import SecretStr, ValidationError + +from server.knowledge.domain.mcp_sources import ( + MAX_ENVELOPE_BYTES, + ConnectionEnvelope, + MCPSourceContractError, + ResourceIdentity, + SourceContract, + bind_envelope, + decode_envelope, + decode_source, + encode_envelope, + encode_source, +) + +_TOKEN = "fixture-secret-bearer" +_SLOT = "mcp:" + "a" * 32 +_GENERATION = "b" * 32 + "/1" + "c" * 31 + + +def _envelope(**changes: Any) -> dict[str, Any]: + return { + "version": 1, + "org": "test-org", + "owner": "person-one", + "slot": _SLOT, + "generation": _GENERATION, + "profile_id": "documents", + "profile_sha256": "d" * 64, + "endpoint": "https://source.example/mcp", + "audience": "https://source.example/mcp", + "auth": "bearer", + "bearer": _TOKEN, + "label": "My documents", + **changes, + } + + +def _decode(**changes: Any) -> ConnectionEnvelope: + return decode_envelope(json.dumps(_envelope(**changes))) + + +def _source(**changes: Any) -> SourceContract: + return SourceContract.model_validate( + { + "version": 1, + "slot": _SLOT, + "generation": _GENERATION, + "profile_id": "documents", + "profile_sha256": "d" * 64, + "mode": "snapshot", + "reader_policy": "owner_only", + "resources": ( + {"type": "resource", "id": "document:second"}, + {"type": "resource", "id": "document:first"}, + ), + **changes, + } + ) + + +def _binding(envelope: ConnectionEnvelope) -> dict[str, Any]: + return envelope.model_dump(exclude={"version", "auth", "label"}) + + +def _assert_public_error(call: Any) -> None: + with pytest.raises(MCPSourceContractError) as caught: + call() + assert str(caught.value) == "MCP_SOURCE_CONTRACT_INVALID" + assert _TOKEN not in repr(caught.value) + assert _TOKEN not in "".join(traceback.format_exception(caught.value)) + assert caught.value.__suppress_context__ or caught.value.__context__ is None + + +def test_envelope_roundtrip_keeps_secret_only_in_sealing_plaintext() -> None: + envelope = _decode() + assert envelope.bearer == SecretStr(_TOKEN) + assert decode_envelope(encode_envelope(envelope)) == envelope + assert json.loads(encode_envelope(envelope))["bearer"] == _TOKEN + assert _TOKEN not in repr(envelope) + assert _TOKEN not in str(dict(envelope)) + assert "bearer" not in envelope.model_dump() + assert "bearer" not in envelope.model_dump(include={"bearer"}) + assert _TOKEN not in envelope.model_dump_json() + # A general dump is not sealing plaintext; it must not restore a redacted token. + _assert_public_error(lambda: decode_envelope(envelope.model_dump_json())) + + +def test_anonymous_auth_roundtrip_and_frozen_models() -> None: + envelope = _decode(auth="none", bearer=None, audience=None) + assert decode_envelope(encode_envelope(envelope)) == envelope + with pytest.raises(ValidationError): + envelope.owner = "another-person" # type: ignore[misc] + source = _source() + with pytest.raises(ValidationError): + source.resources[0].id = "another-document" # type: ignore[misc] + assert isinstance(source.resources, tuple) + + +@pytest.mark.parametrize( + "changes", + [ + {"version": True}, + {"version": "1"}, + {"version": 1.0}, + {"version": 2}, + {"slot": "mcp:" + "A" * 32}, + {"slot": "mcp:" + "a" * 31}, + {"generation": "b" * 32 + "/2" + "c" * 31}, + {"generation": "b" * 32 + "/1" + "c" * 30}, + {"profile_sha256": "D" * 64}, + {"owner": 17}, + {"org": ""}, + {"profile_id": " "}, + {"owner": "person\nother"}, + {"owner": "person\x85other"}, + {"endpoint": "x" * 2049}, + {"endpoint": "é" * 1025}, + {"audience": False}, + {"label": "x" * 257}, + {"bearer": ""}, + {"bearer": "x" * 8193}, + {"bearer": _TOKEN + "\n"}, + {"bearer": "é"}, + {"bearer": 9}, + {"auth": "oauth"}, + {"auth": "none"}, + {"auth": "none", "audience": None}, + {"auth": "none", "bearer": None}, + {"bearer": None}, + {"audience": None}, + {"verified_email": "unproven@example.test"}, + {"refresh_token": _TOKEN}, + ], +) +def test_envelope_rejects_unknown_coercive_and_invalid_input(changes: dict[str, Any]) -> None: + _assert_public_error(lambda: _decode(**changes)) + + +@pytest.mark.parametrize("raw", ["", "{", "[]", "null", "42", '{"version":1}', _TOKEN]) +def test_envelope_rejects_missing_or_truncated_input(raw: str) -> None: + _assert_public_error(lambda: decode_envelope(raw)) + + +def test_envelope_plaintext_bytes_are_bounded_before_decoding_and_encoding() -> None: + raw = encode_envelope(_decode()) + boundary = raw + " " * (MAX_ENVELOPE_BYTES - len(raw.encode())) + assert decode_envelope(boundary).owner == "person-one" + _assert_public_error(lambda: decode_envelope(boundary + " ")) + # Valid local field bounds can still exceed the wire bound after JSON escaping. + envelope = ConnectionEnvelope.model_validate( + _envelope( + **dict.fromkeys(("org", "owner", "profile_id", "endpoint", "audience"), '"' * 2048), + bearer="\\" * 8192, + ) + ) + _assert_public_error(lambda: encode_envelope(envelope)) + + +def test_invalid_unicode_and_nontext_plaintext_have_public_errors() -> None: + _assert_public_error(lambda: decode_envelope("\ud800")) + _assert_public_error(lambda: decode_envelope(b"{}")) # type: ignore[arg-type] + _assert_public_error(lambda: _decode(owner="\ud800")) + + +@pytest.mark.parametrize( + ("field", "other"), + [ + ("org", "other-org"), + ("owner", "person-two"), + ("slot", "mcp:" + "e" * 32), + ("generation", "b" * 32 + "/0" + "c" * 31), + ("profile_id", "other-profile"), + ("profile_sha256", "e" * 64), + ("endpoint", "https://source.example/other"), + ("audience", "https://source.example/other"), + ("audience", None), + ], +) +def test_binding_requires_exact_row_and_current_profile(field: str, other: Any) -> None: + envelope = _decode() + bind_envelope(envelope, **_binding(envelope)) + _assert_public_error(lambda: bind_envelope(envelope, **{**_binding(envelope), field: other})) + + +def test_multiple_slots_do_not_change_each_others_binding() -> None: + first = _decode() + second = _decode(slot="mcp:" + "e" * 32, generation="f" * 32 + "/1" + "a" * 31) + bind_envelope(first, **_binding(first)) + bind_envelope(second, **_binding(second)) + _assert_public_error(lambda: bind_envelope(first, **_binding(second))) + assert decode_envelope(encode_envelope(first)) == first + + +def test_source_splits_columns_without_duplicating_selection_and_preserves_order() -> None: + source = _source() + config, items = encode_source(source) + assert "resources" not in json.loads(config) + assert "document:" not in config + assert json.loads(items) == [ + {"type": "resource", "id": "document:second"}, + {"type": "resource", "id": "document:first"}, + ] + assert decode_source(config, items) == source + assert source.resources[0].id == "document:second" + + +@pytest.mark.parametrize("mode", ["live", "snapshot", "selected_refresh"]) +@pytest.mark.parametrize("policy", ["owner_only", "collection_copy"]) +def test_policy_and_mode_are_declarations_not_authority(mode: str, policy: str) -> None: + source = _source(mode=mode, reader_policy=policy) + assert decode_source(*encode_source(source)) == source + assert source.reader_policy == policy + assert not hasattr(source, "authorized") + + +@pytest.mark.parametrize( + "changes", + [ + {"version": True}, + {"version": "1"}, + {"version": 2}, + {"mode": "sync_everything"}, + {"reader_policy": "upstream_acl"}, + {"recursive": True}, + {"slot": "gdrive"}, + {"generation": "not-a-generation"}, + {"profile_sha256": "not-a-digest"}, + {"profile_id": "\n"}, + ], +) +def test_source_rejects_unknown_or_coercive_metadata(changes: dict[str, Any]) -> None: + config, items = encode_source(_source()) + metadata = {**json.loads(config), **changes} + _assert_public_error(lambda: decode_source(json.dumps(metadata), items)) + + +@pytest.mark.parametrize( + "items", + [ + [], + {}, + [{"type": "resource", "id": ""}], + [{"type": "resource", "id": 4}], + [{"type": "resource", "id": "resource\x7f"}], + [{"type": "resource", "id": "x" * 2049}], + [{"type": "resource", "id": "é" * 1025}], + [{"type": "folder", "id": "folder-id"}], + [{"type": "resource", "id": "one", "recursive": True}], + [{"type": "resource", "id": "one"}] * 2, + [{"type": "resource", "id": str(i)} for i in range(1001)], + ], +) +def test_source_rejects_invalid_selection(items: Any) -> None: + config, _ = encode_source(_source()) + _assert_public_error(lambda: decode_source(config, json.dumps(items))) + + +def test_source_allows_1000_distinct_opaque_ids_without_native_parsing() -> None: + resources = tuple(ResourceIdentity(type="resource", id=f"opaque:{i}") for i in range(1000)) + source = _source(resources=resources) + assert decode_source(*encode_source(source)) == source + + +@pytest.mark.parametrize( + ("config", "items"), [("{", "[]"), ("[]", "[]"), ("{}", "["), ("{}", "null")] +) +def test_source_refuses_malformed_columns(config: str, items: str) -> None: + _assert_public_error(lambda: decode_source(config, items)) + + +def test_source_refuses_a_second_editable_selection_in_config() -> None: + config, items = encode_source(_source()) + metadata = {**json.loads(config), "resources": []} + _assert_public_error(lambda: decode_source(json.dumps(metadata), items)) diff --git a/tests/unit/test_mcp_source_lifecycle.py b/tests/unit/test_mcp_source_lifecycle.py new file mode 100644 index 0000000000..bac5785d2b --- /dev/null +++ b/tests/unit/test_mcp_source_lifecycle.py @@ -0,0 +1,208 @@ +"""Generic source metadata survives lifecycle writes without execution authority.""" + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import replace +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.core.errors import ValidationError +from server.knowledge.app import sources as source_ops +from server.knowledge.domain.sources import KnowledgeSource, mirror_synced, served +from server.knowledge.store import sources + + +class Registry: + def __init__(self, row: dict[str, Any]) -> None: + self.row = row + self.queries: list[str] = [] + self.written: list[dict[str, Any]] = [] + + async def query_one(self, query: str, **kwargs: Any) -> dict[str, Any]: + self.queries.append(query) + return dict(self.row) + + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + assert table == "loom.knowledge_sources" + self.written.extend(dict(row) for row in rows) + + +def generic_row(version: int, config: str, items: str) -> dict[str, Any]: + return { + "org": "org-one", + "namespace": "collection-one", + "name": "selected-documents", + "source_id": "source-one", + "kind": "", + "source_kind": "mcp", + "credential_mode": "mcp", + "access": "mirrored", + "owner_subject": "owner-one", + "connection_id": "a" * 32 + "/1" + "b" * 31, + "connection_slot": "mcp:" + "c" * 32, + "source_contract_version": version, + "config_json": config, + "items_json": items, + "active": True, + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("kind", "mode", "version"), + [ + ("mcp", "mcp", 1), + ("mcp", "mcp", 65535), + ("mcp", "shared", 0), + ("gdrive", "mcp", 0), + ("gdrive", "shared", 2), + ], +) +@pytest.mark.parametrize( + ("config", "items"), + [ + ( + ' { "version" : 77, "future": "opaque-sensitive-metadata" }\n', + '[ { "type":"future-resource", "id":"opaque-selected-id" } ]\n', + ), + ("unparseable opaque-sensitive-metadata", "unparseable opaque-selected-id"), + ], +) +async def test_lifecycle_roundtrip_preserves_unknown_payload_without_serving( + kind: str, mode: str, version: int, config: str, items: str +) -> None: + row = generic_row(version, config, items) + row.update(source_kind=kind, credential_mode=mode) + registry = Registry(row) + source = await sources.latest_source( + "org-one", "collection-one", "selected-documents", ch=registry + ) + assert source is not None + assert source.source_contract_version == version + assert source.connection_slot == "mcp:" + "c" * 32 + assert source.generic_config_json == config + assert source.generic_items_json == items + assert not served(replace(source, access="namespace")) + assert not mirror_synced(replace(source, access="mirrored")) + assert "opaque-sensitive-metadata" not in repr(source) + assert "opaque-selected-id" not in repr(source) + assert "source_contract_version" in registry.queries[0] + assert "connection_slot" in registry.queries[0] + + await sources.insert_source(replace(source, active=False, pending_delete=True), ch=registry) + [written] = registry.written + assert written["config_json"] == config + assert written["items_json"] == items + assert written["source_contract_version"] == version + assert written["connection_slot"] == source.connection_slot + assert written["source_id"] == source.source_id + assert written["connection_id"] == source.connection_id + assert written["owner_subject"] == source.owner_subject + assert written["source_kind"] == kind + assert written["kind"] == "" + assert written["credential_mode"] == mode + assert written["credential_enc"] == written["secret_enc"] == "" + assert not written["active"] + assert written["pending_delete"] + + +@pytest.mark.asyncio +async def test_native_source_still_uses_its_existing_codec() -> None: + row = generic_row(0, "{}", '[{"type":"page","id":"native-page"}]') + row.update(source_kind="notion", credential_mode="connected", connection_slot="") + registry = Registry(row) + source = await sources.latest_source( + "org-one", "collection-one", "selected-documents", ch=registry + ) + assert source is not None + assert source.items == [{"type": "page", "id": "native-page"}] + assert mirror_synced(source) + await sources.insert_source(replace(source, active=False), ch=registry) + [written] = registry.written + assert written["config_json"] == "{}" + assert written["items_json"] == '[{"id": "native-page", "type": "page"}]' + assert written["source_kind"] == "notion" + assert written["credential_mode"] == "connected" + + +def unsupported_source(kind: str, mode: str, version: int) -> KnowledgeSource: + return KnowledgeSource( + org="org-one", + namespace="collection-one", + name="selected-documents", + source_id="source-one", + kind=kind, + credential_mode=mode, + source_contract_version=version, + access="mirrored", + owner_subject="owner-one", + connection_slot="mcp:" + "c" * 32, + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("kind", "version", "allowed"), [("mcp", 0, False), ("gdrive", 2, False), ("gdrive", 0, True)] +) +async def test_opaque_details_stay_hidden(kind: str, version: int, allowed: bool) -> None: + assert await source_ops._details_allowed(unsupported_source(kind, "shared", version)) is allowed + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("kind", "mode", "version"), + [("mcp", "mcp", 1), ("mcp", "shared", 0), ("gdrive", "shared", 2)], +) +async def test_native_management_lookup_refuses_opaque_format( + monkeypatch: pytest.MonkeyPatch, kind: str, mode: str, version: int +) -> None: + source = unsupported_source(kind, mode, version) + + async def found(*args: Any) -> KnowledgeSource: + return source + + monkeypatch.setattr(source_ops.store, "get_source", found) + with pytest.raises(ValidationError) as caught: + await source_ops._source_or_404(source.org, source.namespace, source.name) + assert caught.value.extra["code"] == "SOURCE_NOT_SERVED" + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("kind", "mode", "version"), + [("mcp", "mcp", 1), ("mcp", "shared", 0), ("gdrive", "shared", 2)], +) +async def test_native_management_remove_refuses_before_retirement( + monkeypatch: pytest.MonkeyPatch, kind: str, mode: str, version: int +) -> None: + source = unsupported_source(kind, mode, version) + + async def found(*args: Any) -> KnowledgeSource: + return source + + @asynccontextmanager + async def lease(*args: Any) -> AsyncIterator[None]: + yield + + async def administrator(*args: Any) -> bool: + return True + + async def forbid_retirement(*args: Any) -> None: + pytest.fail("native management reached retirement for an opaque source") + + monkeypatch.setattr(source_ops.store, "get_source", found) + monkeypatch.setattr(source_ops, "sources_lease", lease) + monkeypatch.setattr(source_ops.authz, "row_in_scope", administrator) + monkeypatch.setattr(source_ops, "_queue_retirement", forbid_retirement) + request = SimpleNamespace( + org=source.org, + namespace=source.namespace, + name=source.name, + confirm=source.name, + delete_documents=False, + ) + with pytest.raises(ValidationError) as caught: + await source_ops.handle_knowledge_source_remove(request) + assert caught.value.extra["code"] == "SOURCE_NOT_SERVED" diff --git a/tests/unit/test_mcp_source_lifecycle_diagnostics.py b/tests/unit/test_mcp_source_lifecycle_diagnostics.py new file mode 100644 index 0000000000..7b7cc67871 --- /dev/null +++ b/tests/unit/test_mcp_source_lifecycle_diagnostics.py @@ -0,0 +1,52 @@ +"""Fixture failures report bounded locations without loading source or error payloads.""" + +import json +import linecache + +import pytest + +from scripts.gates.mcp_source_lifecycle import failure_detail + + +def _error(depth: int) -> RuntimeError: + if depth: + return _error(depth - 1) + try: + raise RuntimeError("fixture-private-credential-and-query") + except RuntimeError as error: + return error + + +def test_lifecycle_diagnostics_exclude_payload_and_source_reads( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def no_source(*args: object, **kwargs: object) -> str: + raise AssertionError("diagnostics must not load source lines") + + error = _error(0) + with monkeypatch.context() as patch: + patch.setattr(linecache, "getline", no_source) + detail = failure_detail(error) + assert detail["type"] == "RuntimeError" + assert "fixture-private" not in json.dumps(detail) + assert 0 < len(detail["frames"]) <= 8 + assert all(not frame["path"].startswith("/") for frame in detail["frames"]) + assert all(set(frame) == {"path", "line"} for frame in detail["frames"]) + + +def test_lifecycle_diagnostics_bound_deep_failure_frames() -> None: + def recurse(depth: int) -> None: + if depth: + recurse(depth - 1) + else: + raise RuntimeError("fixture-private-deep-payload") + + try: + recurse(100) + except RuntimeError as error: + detail = failure_detail(error) + else: + pytest.fail("fixture must raise") + assert detail["type"] == "RuntimeError" + assert len(detail["frames"]) == 8 + assert "fixture-private" not in json.dumps(detail) diff --git a/tests/unit/test_mcp_source_read_gate.py b/tests/unit/test_mcp_source_read_gate.py new file mode 100644 index 0000000000..3415e49313 --- /dev/null +++ b/tests/unit/test_mcp_source_read_gate.py @@ -0,0 +1,174 @@ +"""An older reader cannot admit a source format it only preserves for cleanup.""" + +from types import SimpleNamespace +from typing import Any + +import pytest + +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import source_access +from server.knowledge.domain.sources import KnowledgeSource + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("kind", "mode", "version", "names"), + [ + ("mcp", "mcp", 1, []), + ("mcp", "shared", 0, []), + ("gdrive", "shared", 2, []), + ("gdrive", "connected", 2, []), + ("gdrive", "shared", 0, ["collection-one"]), + ], +) +async def test_unsupported_format_never_enters_a_native_read_plan( + monkeypatch: pytest.MonkeyPatch, kind: str, mode: str, version: int, names: list[str] +) -> None: + async def mirrors(org: str, selected: list[str], **kwargs: Any) -> dict[str, str]: + assert org == "org-one" + assert selected == names + return {} + + async def listings(*args: Any) -> list[Any]: + return [] + + async def forbid_native_read(*args: Any) -> None: + pytest.fail("an unsupported format entered native source authorization") + + from server.knowledge.store import sources + + monkeypatch.setattr(sources, "latest_source", forbid_native_read) + monkeypatch.setattr(source_access.mirrors_repo, "mirrors_of", mirrors) + monkeypatch.setattr(source_access.store, "listings", listings) + plan = SimpleNamespace(org="org-one", _connected_pins={}, _scope_frozen=False, _auth=object()) + await source_access._prepare( + plan, + [ + { + "namespace": "collection-one", + "name": "selected-documents", + "source_id": "source-one", + "source_kind": kind, + "credential_mode": mode, + "source_contract_version": version, + } + ], + "", + ) + assert plan.sources == {} + assert plan.listing_starts == {} + + +@pytest.mark.asyncio +async def test_a_format_change_after_listing_cannot_enter_native_authorization( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.knowledge.store import sources + + async def changed(*args: Any) -> KnowledgeSource: + return KnowledgeSource( + org="org-one", + namespace="collection-one", + name="selected-documents", + source_id="source-one", + kind="gdrive", + credential_mode="connected", + source_contract_version=2, + ) + + async def forbid_native_read(*args: Any) -> None: + pytest.fail("a changed format entered native source authorization") + + async def mirrors(org: str, names: list[str], **kwargs: Any) -> dict[str, str]: + assert names == [] + return {} + + async def listings(*args: Any) -> list[Any]: + return [] + + monkeypatch.setattr(sources, "latest_source", changed) + monkeypatch.setattr(accounts, "validate_indexed", forbid_native_read) + monkeypatch.setattr(source_access.mirrors_repo, "mirrors_of", mirrors) + monkeypatch.setattr(source_access.store, "listings", listings) + plan = SimpleNamespace(org="org-one", _connected_pins={}, _scope_frozen=False, _auth=object()) + await source_access._prepare( + plan, + [ + { + "namespace": "collection-one", + "name": "selected-documents", + "source_id": "source-one", + "source_kind": "gdrive", + "credential_mode": "connected", + "source_contract_version": 0, + } + ], + "", + ) + assert plan.sources == {} + + +def native_connection_source(version: int) -> KnowledgeSource: + return KnowledgeSource( + org="org-one", + namespace="collection-one", + name="selected-documents", + source_id="source-one", + kind="gdrive", + credential_mode="connected", + source_contract_version=version, + access="mirrored", + owner_subject="owner-one", + connection_id="c" * 32 + "/1" + "d" * 31, + ) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("changed_after_check", [False, True]) +async def test_native_connection_standing_refuses_unknown_format_before_checkout( + monkeypatch: pytest.MonkeyPatch, changed_after_check: bool +) -> None: + from server.core.errors import ValidationError + from server.knowledge.app import sources as source_ops + + original = native_connection_source(0 if changed_after_check else 2) + account = SimpleNamespace( + org=original.org, + subject=original.owner_subject, + kind=original.kind, + connection_id=original.connection_id, + active=True, + credential_enc="sealed-test-credential", + connected_at=None, + ) + + async def fail_if_reached(*args: Any) -> None: + pytest.fail("an unknown source format passed native connection standing") + + async def allow(*args: Any) -> None: + return None + + async def writer(*args: Any) -> Any: + return accounts.Role.WRITER + + async def changed(*args: Any) -> KnowledgeSource: + return native_connection_source(2) + + monkeypatch.setattr( + accounts, + "settings", + SimpleNamespace( + auth_actually_required=lambda: True, knowledge_mirrored_sources_enabled=True + ), + ) + monkeypatch.setattr( + accounts, "_require_source_fence", allow if changed_after_check else fail_if_reached + ) + monkeypatch.setattr(accounts, "_standing", allow) + monkeypatch.setattr(accounts.aliases, "verified_spellings", allow) + monkeypatch.setattr(accounts.aliases, "invalidate", lambda *args: None) + monkeypatch.setattr(accounts.authz, "grant_role_for", writer) + monkeypatch.setattr(accounts.source_store, "latest_source", changed) + monkeypatch.setattr(source_ops, "_require_source_namespace", fail_if_reached) + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await accounts._source_standing(original, account) diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index f0aff2c8dd..3e8adcf911 100644 --- a/tests/unit/test_schema_baseline.py +++ b/tests/unit/test_schema_baseline.py @@ -171,6 +171,7 @@ def test_the_journal_files() -> None: "113_oauth_verified_email.sql", "114_memory_proposal_review.sql", "115_memory_refusals.sql", + "116_mcp_source_lifecycle.sql", ] From 6fc9ba97e02845ab5611e2a707b511100446043e Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 00:45:27 +0000 Subject: [PATCH 09/30] Bound historical generations and normalize source identities Count every retained connection generation before cleanup, preserve strict UUID identity checks with the normal row conversion and record the hosted schema output. Signed-off-by: zlareb1 --- schemas/schema.sql | 4 +- server/knowledge/app/connected_restore.py | 7 +- server/knowledge/store/sources.py | 2 +- tests/unit/test_mcp_connection_lifecycle.py | 105 ++++++++++++++++++++ 4 files changed, 112 insertions(+), 6 deletions(-) diff --git a/schemas/schema.sql b/schemas/schema.sql index 2b8590f2d8..0237607ecd 100644 --- a/schemas/schema.sql +++ b/schemas/schema.sql @@ -2319,7 +2319,9 @@ CREATE TABLE IF NOT EXISTS loom.knowledge_sources `access` LowCardinality(String) DEFAULT 'namespace', `credential_mode` LowCardinality(String) DEFAULT 'shared', `owner_subject` String DEFAULT '', - `connection_id` String DEFAULT '' + `connection_id` String DEFAULT '', + `connection_slot` String DEFAULT '', + `source_contract_version` UInt16 DEFAULT 0 ) ENGINE = ReplacingMergeTree(version) ORDER BY (org, namespace, name) diff --git a/server/knowledge/app/connected_restore.py b/server/knowledge/app/connected_restore.py index 1c84939551..d7baab97c2 100644 --- a/server/knowledge/app/connected_restore.py +++ b/server/knowledge/app/connected_restore.py @@ -62,6 +62,9 @@ def _include( raise accounts.unavailable() prefixes[key] = owner groups[owner].add(connection) + # Many historical generations can share one fence prefix. + if sum(map(len, groups.values())) > settings.knowledge_connected_registry_scan_limit: + raise accounts.unavailable() def _source_binding(source: KnowledgeSource) -> Owner | None: @@ -167,8 +170,6 @@ async def _restore_owner( if current is not None: keys.append((current.org, current.subject, current.kind, current.connection_id)) _include(groups, prefixes, keys) - if len(prefixes) > settings.knowledge_connected_registry_scan_limit: - raise accounts.unavailable() if not groups[owner]: return None stopped: dict[str, str] = {} @@ -234,8 +235,6 @@ async def erase_subjects( for owner in sorted(owners): keys, _sources = await _metadata(ch, owner) _include(groups, prefixes, keys) - if len(prefixes) > settings.knowledge_connected_registry_scan_limit: - raise accounts.unavailable() ended = [] for owner in sorted(owners): if account := await _restore_owner( diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 405d4e89ad..ae0eb5ae07 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -616,7 +616,7 @@ async def connected_history( namespace=row["namespace"], name=row["name"], kind=row["source_kind"], - source_id=row["source_id"], + source_id=str(row.get("source_id") or ""), owner_subject=row["owner_subject"], connection_id=row["connection_id"], credential_mode=str(row.get("credential_mode") or "connected"), diff --git a/tests/unit/test_mcp_connection_lifecycle.py b/tests/unit/test_mcp_connection_lifecycle.py index 5d276941f4..e8507754c6 100644 --- a/tests/unit/test_mcp_connection_lifecycle.py +++ b/tests/unit/test_mcp_connection_lifecycle.py @@ -7,6 +7,7 @@ from types import SimpleNamespace from typing import Any from unittest.mock import AsyncMock, Mock +from uuid import UUID import pytest @@ -617,3 +618,107 @@ async def history(*, owner: Any = None, **kwargs: Any) -> list[Any]: with pytest.raises(ValidationError, match="the connected account is unavailable"): await restore.accounts.stop_subjects([OWNER[1]], erase_owner=True, revoke=False) assert calls == 2 and not state.events + + +@pytest.mark.asyncio +async def test_owner_erasure_bounds_generations_sharing_each_owners_prefix( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + owners = [OWNER, (OWNER[0], "owner-two", SLOT)] + for owner, prefix in zip(owners, "ab", strict=True): + source = _owner_source(owner, prefix) + state.history[owner] = [ + source, + replace(source, connection_id=prefix * 32 + "/1" + "e" * 31), + ] + monkeypatch.setattr(restore.settings, "knowledge_connected_registry_scan_limit", 2) + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await restore.accounts.stop_subjects( + [owner[1] for owner in owners], erase_owner=True, revoke=False + ) + assert not state.events and not state.fences and not state.rows + assert set(state.history) == set(owners) + + +@pytest.mark.asyncio +async def test_owner_erasure_bounds_new_generation_on_final_owners_existing_prefix( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + owners = [OWNER, (OWNER[0], "owner-two", SLOT)] + state.history = { + owner: [_owner_source(owner, prefix)] for owner, prefix in zip(owners, "ab", strict=True) + } + calls: dict[Any, int] = defaultdict(int) + + async def history(*, owner: Any = None, **kwargs: Any) -> list[Any]: + calls[owner] += 1 + sources = list(state.history[owner]) + if owner == owners[1] and calls[owner] == 2: + assert state.held == [owner] and ("erase", owners[0]) in state.events + sources.append(replace(sources[0], connection_id="b" * 32 + "/1" + "e" * 31)) + assert len(sources) <= 2 + return sources + + monkeypatch.setattr(restore.source_store, "connected_history", history) + monkeypatch.setattr(restore.settings, "knowledge_connected_registry_scan_limit", 2) + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await restore.accounts.stop_subjects( + [owner[1] for owner in owners], erase_owner=True, revoke=False + ) + assert ("erase", owners[0]) in state.events + assert not any(owner == owners[1] for _event, owner in state.events) + assert set(state.history) == {owners[1]} + + +@pytest.mark.asyncio +async def test_offline_restore_dry_run_bounds_generations_not_only_prefixes( + monkeypatch: pytest.MonkeyPatch, +) -> None: + owners = [OWNER, (OWNER[0], "owner-two", SLOT)] + keys = [ + (*owner, prefix * 32 + "/1" + tail * 31) + for owner, prefix in zip(owners, "ab", strict=True) + for tail in "de" + ] + client = object() + monkeypatch.setattr(restore.ch_module, "get_client", lambda: client) + monkeypatch.setattr(restore, "offline_refusal", AsyncMock(return_value="")) + monkeypatch.setattr(restore, "_metadata", AsyncMock(return_value=(keys, []))) + monkeypatch.setattr(restore.settings, "knowledge_connected_registry_scan_limit", 2) + mutate = AsyncMock(side_effect=AssertionError("dry run must not mutate")) + monkeypatch.setattr(restore, "_restore_owner", mutate) + with pytest.raises(ValidationError, match="the connected account is unavailable"): + await restore.restore_all(apply=False, ch=client) + mutate.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("generic", [False, True]) +async def test_restore_inventory_normalizes_driver_uuid_without_weakening_binding( + monkeypatch: pytest.MonkeyPatch, generic: bool +) -> None: + source_id = UUID("abcd1234-1234-4234-8234-123456789abc") + + async def query(sql: str, *, params: dict[str, Any]) -> list[dict[str, Any]]: + return [ + { + "org": OWNER[0], + "namespace": "collection-one", + "name": "selected-documents", + "source_id": source_id, + "source_kind": "mcp" if generic else "gdrive", + "owner_subject": OWNER[1], + "connection_id": CONNECTION, + "credential_mode": "mcp" if generic else "connected", + "connection_slot": SLOT if generic else "", + "source_contract_version": 65535 if generic else 0, + } + ] + + monkeypatch.setattr(restore.account_store, "restore_keys", AsyncMock(return_value=[])) + keys, sources = await restore._metadata(SimpleNamespace(query_all=query)) + assert keys == [(OWNER[0], OWNER[1], SLOT if generic else "gdrive", CONNECTION)] + assert len(sources) == 1 and sources[0].source_id == str(source_id) + assert isinstance(sources[0].source_id, str) From c84526e4bbb70af07dc72858750c43c2d1fb42a2 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 00:23:39 +0000 Subject: [PATCH 10/30] Add MCP profile and destination setup primitives Preserve the unregistered catalog operation and destination component for later integration and hosted qualification. Signed-off-by: zlareb1 --- .../src/flows/SourceDestinationStep.test.tsx | 466 ++++++++++++++ frontend/src/flows/SourceDestinationStep.tsx | 293 +++++++++ server/knowledge/api/models_mcp_profiles.py | 48 ++ server/knowledge/api/ops_mcp_profiles.py | 18 + server/knowledge/app/mcp_profile_api.py | 60 ++ server/knowledge/app/mcp_profiles.py | 406 +++++++++++++ server/knowledge/domain/mcp_identity.py | 39 ++ server/settings/catalog.py | 16 + tests/unit/test_mcp_profile_api.py | 382 ++++++++++++ tests/unit/test_mcp_source_identity.py | 56 ++ tests/unit/test_mcp_source_profiles.py | 574 ++++++++++++++++++ 11 files changed, 2358 insertions(+) create mode 100644 frontend/src/flows/SourceDestinationStep.test.tsx create mode 100644 frontend/src/flows/SourceDestinationStep.tsx create mode 100644 server/knowledge/api/models_mcp_profiles.py create mode 100644 server/knowledge/api/ops_mcp_profiles.py create mode 100644 server/knowledge/app/mcp_profile_api.py create mode 100644 server/knowledge/app/mcp_profiles.py create mode 100644 server/knowledge/domain/mcp_identity.py create mode 100644 tests/unit/test_mcp_profile_api.py create mode 100644 tests/unit/test_mcp_source_identity.py create mode 100644 tests/unit/test_mcp_source_profiles.py diff --git a/frontend/src/flows/SourceDestinationStep.test.tsx b/frontend/src/flows/SourceDestinationStep.test.tsx new file mode 100644 index 0000000000..9be3ae5ccf --- /dev/null +++ b/frontend/src/flows/SourceDestinationStep.test.tsx @@ -0,0 +1,466 @@ +import userEvent from "@testing-library/user-event"; +import { type FormEvent, useState } from "react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; + +vi.mock("../api", async (importOriginal) => ({ + ...(await importOriginal()), + listCollections: vi.fn(), + createCollection: vi.fn(), + deleteCollection: vi.fn(), +})); +vi.mock("../components/Toast", async (importOriginal) => ({ + ...(await importOriginal()), + toast: vi.fn(), +})); + +import { type CollectionEntry, type CollectionListPage, createCollection, deleteCollection, listCollections } from "../api"; +import { invalidateSharedCollections } from "../lib/collectionPlaces"; +import { COLLECTIONS_PAGE, COLLECTIONS_PAGES } from "../lib/collections"; +import { axeViolations } from "../test/axe"; +import { + type SourceDestinationCopy, + type SourceDestinationProps, + SourceDestinationStep, +} from "./SourceDestinationStep"; + +const list = vi.mocked(listCollections); +const create = vi.mocked(createCollection); + +const copy: SourceDestinationCopy = { + title: "Destination", + description: "Choose a collection. Its grants do not grant access to your connection.", + searchLabel: "Search this page", + searchHint: "Search names and addresses on this page. Use Load more for the next page.", + pageScope: "this page", + destinationsLabel: "Writable collections", + loading: "Loading collections…", + loadError: "Collections could not be loaded.", + things: "collections", + empty: "No writable ordinary collections on this page.", + previous: "Previous page", + next: "Load more", + refresh: "Refresh collections", + create: "New collection", + createHint: "Create at the top level or inside a writable collection on this page.", + topLevelHint: "Top-level collection. Review its grants before publishing.", + selectionHint: "Review effective access in the next step. The server checks your permissions again.", + pagingError: "The next page repeated a cursor. Refresh the collection list.", + pagingLimit: "More collections exist. This view has reached its page limit.", + inheritanceHint: (parent) => `Inherits grants from ${parent}. Review effective access before publishing.`, + created: (namespace) => `Collection confirmed: ${namespace}. Select it after reviewing the list.`, + selected: (namespace) => `Selected destination: ${namespace}`, + page: (number) => `Page ${number}`, +}; + +function row(namespace: string, changes: Partial = {}): CollectionEntry { + return { namespace, title: namespace, personal: false, parent: "", role: "writer", ...changes }; +} +const alpha = row("col-alpha", { title: "Alpha" }); +const beta = row("col-beta", { title: "Beta", role: "admin", parent: "col-team" }); +const pageOf = (collections: CollectionEntry[], next_cursor: string | null = null): CollectionListPage => ({ + collections, + next_cursor, +}); + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +} + +function Harness(props: SourceDestinationProps) { + const [value, setValue] = useState(props.value); + return ( + { + setValue(next); + props.onChange(next); + }} + /> + ); +} + +function mount(overrides: Partial = {}) { + let props: SourceDestinationProps = { + org: "acme", + callerKey: "owner-a:auth-1", + contextKey: "connection-a:selection-1:snapshot", + value: null, + copy, + onChange: vi.fn(), + onInvalidated: vi.fn(), + onCollectionCreated: vi.fn(), + ...overrides, + }; + const view = render(); + return { + ...view, + props, + update: (next: Partial) => { + props = { ...props, ...next }; + view.rerender(); + }, + }; +} + +async function chooseAlpha() { + const choice = await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + fireEvent.click(choice); + await waitFor(() => expect(choice).toBeChecked()); +} + +describe("SourceDestinationStep", () => { + beforeEach(() => { + vi.resetAllMocks(); + list.mockResolvedValue(pageOf([alpha, beta])); + }); + afterEach(cleanup); + + it("reads one cancellable page and excludes personal, readonly and non-collection namespaces", async () => { + list.mockResolvedValue( + pageOf([ + alpha, + row("col-own", { personal: true, role: "admin" }), + row("col-me-owner", { role: "admin" }), + row("personal-owner", { role: "admin" }), + row("u-owner-hash", { role: "admin" }), + row("col-view", { role: "viewer" }), + ]), + ); + const { props } = mount(); + expect(await screen.findByRole("radio", { name: "Alpha (col-alpha)" })).toBeInTheDocument(); + expect(screen.getAllByRole("radio")).toHaveLength(1); + expect(list).toHaveBeenCalledExactlyOnceWith("acme", { + cursor: null, + limit: COLLECTIONS_PAGE, + signal: expect.any(AbortSignal), + }); + expect(props.onChange).not.toHaveBeenCalled(); + expect(create).not.toHaveBeenCalled(); + expect(deleteCollection).not.toHaveBeenCalled(); + }); + + it("pages only on request, with one page of choices at a time", async () => { + list.mockResolvedValueOnce(pageOf([alpha], "page-two")).mockResolvedValueOnce(pageOf([beta])); + mount(); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + expect(list).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole("button", { name: copy.next })); + await screen.findByRole("radio", { name: "Beta (col-beta)" }); + expect(screen.getByRole("heading", { name: copy.title })).toHaveFocus(); + expect(screen.queryByRole("radio", { name: "Alpha (col-alpha)" })).not.toBeInTheDocument(); + expect(list.mock.calls[1][1]).toMatchObject({ cursor: "page-two", limit: COLLECTIONS_PAGE }); + expect(screen.getByRole("button", { name: copy.next })).toBeDisabled(); + expect(screen.getByText("Page 2")).toBeInTheDocument(); + list.mockResolvedValueOnce(pageOf([alpha], "page-two")); + fireEvent.click(screen.getByRole("button", { name: "Previous page" })); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + expect(list.mock.calls[2][1]?.cursor).toBeNull(); + }); + + it("searches the current page by title or address without fetching or changing selection", async () => { + const { props } = mount(); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + fireEvent.change(screen.getByLabelText("Search this page"), { target: { value: "COL-BETA" } }); + expect(screen.getAllByRole("radio")).toHaveLength(1); + expect(screen.getByRole("radio", { name: "Beta (col-beta)" })).toBeInTheDocument(); + fireEvent.change(screen.getByLabelText("Search this page"), { target: { value: "missing" } }); + expect(screen.getByText(/missing/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Clear filters" })).toBeInTheDocument(); + expect(list).toHaveBeenCalledTimes(1); + expect(props.onChange).not.toHaveBeenCalled(); + }); + + it("uses the existing collection title folding for non-ASCII search", async () => { + list.mockResolvedValueOnce(pageOf([row("col-equipe", { title: "Équipe" }), alpha])); + mount(); + await screen.findByRole("radio", { name: "Équipe (col-equipe)" }); + fireEvent.change(screen.getByLabelText(copy.searchLabel), { target: { value: "éQUIPE" } }); + expect(screen.getAllByRole("radio")).toHaveLength(1); + expect(screen.getByRole("radio", { name: "Équipe (col-equipe)" })).toBeInTheDocument(); + }); + + it("shows loading, an error and explicit retry without retrying a mutation", async () => { + const pending = deferred(); + list.mockReturnValueOnce(pending.promise); + mount(); + expect(await screen.findByText(copy.loading)).toBeInTheDocument(); + await waitFor(() => expect(list).toHaveBeenCalledTimes(1)); + await act(async () => pending.reject(new Error("denied"))); + expect(await screen.findByRole("alert")).toHaveTextContent(copy.loadError); + expect(list).toHaveBeenCalledTimes(1); + fireEvent.click(screen.getByRole("button", { name: "Retry" })); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + expect(list).toHaveBeenCalledTimes(2); + expect(create).not.toHaveBeenCalled(); + }); + + it("distinguishes an empty writable page from a failed read and allows later pages", async () => { + list.mockResolvedValueOnce(pageOf([row("col-view", { role: "viewer" })], "more")); + mount(); + expect(await screen.findByText(copy.empty)).toBeInTheDocument(); + expect(screen.queryByRole("alert")).not.toBeInTheDocument(); + expect(screen.getByRole("button", { name: copy.next })).toBeEnabled(); + }); + + it("stops a repeated cursor without looping or hiding the current page", async () => { + list.mockResolvedValueOnce(pageOf([alpha], "repeat")).mockResolvedValueOnce(pageOf([beta], "repeat")); + mount(); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + fireEvent.click(screen.getByRole("button", { name: copy.next })); + await screen.findByRole("radio", { name: "Beta (col-beta)" }); + expect(screen.getByRole("alert")).toHaveTextContent(copy.pagingError); + expect(screen.getByRole("button", { name: copy.next })).toBeDisabled(); + expect(list).toHaveBeenCalledTimes(2); + }); + + it("bounds cursor history using the existing collection page limit", async () => { + list.mockImplementation(async (_org, options) => { + const index = Number(options?.cursor ?? 0); + return pageOf([alpha], String(index + 1)); + }); + mount(); + for (let index = 1; index <= COLLECTIONS_PAGES; index++) { + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + expect(screen.getByText(`Page ${index}`)).toBeInTheDocument(); + if (index < COLLECTIONS_PAGES) fireEvent.click(screen.getByRole("button", { name: copy.next })); + } + expect(screen.getByText(copy.pagingLimit)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: copy.next })).toBeDisabled(); + expect(list).toHaveBeenCalledTimes(COLLECTIONS_PAGES); + }); + + it("ignores a late page response after an explicit refresh", async () => { + const stale = deferred(); + const gamma = row("col-gamma", { title: "Gamma" }); + list + .mockResolvedValueOnce(pageOf([alpha], "two")) + .mockReturnValueOnce(stale.promise) + .mockResolvedValueOnce(pageOf([gamma])); + const { props } = mount(); + await chooseAlpha(); + fireEvent.click(screen.getByRole("button", { name: copy.next })); + await waitFor(() => expect(list).toHaveBeenCalledTimes(2)); + const signal = list.mock.calls[1][1]?.signal; + fireEvent.click(screen.getByRole("button", { name: "Refresh collections" })); + await screen.findByRole("radio", { name: "Gamma (col-gamma)" }); + await act(async () => stale.resolve(pageOf([beta]))); + expect(signal?.aborted).toBe(true); + expect(screen.queryByRole("radio", { name: "Beta (col-beta)" })).not.toBeInTheDocument(); + expect(props.onChange).toHaveBeenLastCalledWith(null); + }); + + it.each([ + { org: "other-org" }, + { callerKey: "owner-b:auth-2" }, + { contextKey: "connection-b:selection-2:snapshot" }, + { collectionVersion: 2 }, + ])("aborts an old context read and ignores its late result after %o", async (change) => { + const stale = deferred(); + list.mockReturnValueOnce(stale.promise).mockResolvedValueOnce(pageOf([beta])); + const { update, props } = mount(); + await waitFor(() => expect(list).toHaveBeenCalledTimes(1)); + const signal = list.mock.calls[0][1]?.signal; + update(change); + await screen.findByRole("radio", { name: "Beta (col-beta)" }); + expect(signal?.aborted).toBe(true); + await act(async () => stale.resolve(pageOf([alpha]))); + expect(screen.queryByRole("radio", { name: "Alpha (col-alpha)" })).not.toBeInTheDocument(); + expect(props.onInvalidated).toHaveBeenCalledWith("context_changed"); + expect(props.onChange).toHaveBeenCalledWith(null); + expect(props.onChange).not.toHaveBeenCalledWith(alpha); + }); + + it("clears a chosen destination and its preview on a caller change", async () => { + const { props, update } = mount(); + await chooseAlpha(); + expect(props.onChange).toHaveBeenLastCalledWith(alpha); + update({ callerKey: "owner-b:auth-2" }); + await waitFor(() => expect(props.onChange).toHaveBeenLastCalledWith(null)); + expect(await screen.findByRole("radio", { name: "Alpha (col-alpha)" })).not.toBeChecked(); + }); + + it.each([{ parent: "col-other" }, { role: "viewer" as const }, { personal: true }])( + "invalidates a restored destination when fresh metadata changes: %o", + async (change) => { + list.mockResolvedValueOnce(pageOf([row(alpha.namespace, { ...alpha, ...change })])); + const { props } = mount({ value: alpha }); + await waitFor(() => expect(props.onChange).toHaveBeenCalledWith(null)); + expect(props.onInvalidated).toHaveBeenCalledWith("collections_changed"); + }, + ); + + it("refreshes and invalidates on collection changes and window focus", async () => { + const { props } = mount(); + await chooseAlpha(); + act(() => invalidateSharedCollections({ org: "other-org", name: "col-away" })); + expect(list).toHaveBeenCalledTimes(1); + act(() => invalidateSharedCollections({ org: "acme", name: "col-alpha" })); + await waitFor(() => expect(list).toHaveBeenCalledTimes(2)); + expect(props.onChange).toHaveBeenLastCalledWith(null); + fireEvent.focus(window); + await waitFor(() => expect(list).toHaveBeenCalledTimes(3)); + }); + + it("keeps refresh content visible and busy while clearing the previous selection", async () => { + const pending = deferred(); + const { props } = mount(); + await chooseAlpha(); + list.mockReturnValueOnce(pending.promise); + fireEvent.click(screen.getByRole("button", { name: "Refresh collections" })); + const oldChoice = screen.getByRole("radio", { name: "Alpha (col-alpha)" }); + expect(oldChoice.closest("[aria-busy]")).toHaveAttribute("aria-busy", "true"); + expect(oldChoice).toBeDisabled(); + expect(props.onChange).toHaveBeenLastCalledWith(null); + await waitFor(() => expect(list).toHaveBeenCalledTimes(2)); + await act(async () => pending.resolve(pageOf([beta]))); + expect(await screen.findByRole("radio", { name: "Beta (col-beta)" })).not.toBeChecked(); + expect(screen.queryByRole("radio", { name: "Alpha (col-alpha)" })).not.toBeInTheDocument(); + }); + + it("states parent inheritance without claiming a private destination or a complete ACL", async () => { + mount(); + const choice = await screen.findByRole("radio", { name: "Beta (col-beta)" }); + expect(choice).toHaveAccessibleDescription(copy.inheritanceHint("col-team")); + expect(screen.getByText(copy.topLevelHint)).toBeInTheDocument(); + expect(screen.getByText(copy.description)).toBeInTheDocument(); + expect(screen.getByText(copy.selectionHint)).toBeInTheDocument(); + expect(screen.queryByText(/private collection/i)).not.toBeInTheDocument(); + }); + + it("reuses real collection creation and reports its exact identity even if catalog refresh fails", async () => { + create.mockResolvedValue({ namespace: "col-notes-actual", parent: "", created: true, title: "Notes" }); + const { props } = mount(); + await chooseAlpha(); + fireEvent.click(screen.getByRole("button", { name: "New collection" })); + fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Notes" } }); + list.mockRejectedValueOnce(new Error("catalog unavailable")); + fireEvent.click(screen.getByRole("button", { name: "Create", exact: true })); + await waitFor(() => + expect(props.onCollectionCreated).toHaveBeenCalledExactlyOnceWith({ + org: "acme", + callerKey: "owner-a:auth-1", + namespace: "col-notes-actual", + }), + ); + expect(create).toHaveBeenCalledExactlyOnceWith("acme", "col-notes", { + parent: "", + description: "", + title: "Notes", + deriveName: true, + }); + expect(await screen.findByText(copy.created("col-notes-actual"))).toBeInTheDocument(); + expect(await screen.findByRole("alert")).toHaveTextContent(copy.loadError); + expect(props.onChange).toHaveBeenLastCalledWith(null); + expect(props.onChange).not.toHaveBeenCalledWith(expect.objectContaining({ namespace: "col-notes-actual" })); + expect(deleteCollection).not.toHaveBeenCalled(); + }); + + it("keeps a refused creation draft for explicit recovery without automatic retry or deletion", async () => { + create.mockRejectedValue(new Error("outcome unknown")); + const { props } = mount(); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + fireEvent.click(screen.getByRole("button", { name: "New collection" })); + fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Keep this draft" } }); + fireEvent.click(screen.getByRole("button", { name: "Create", exact: true })); + await screen.findByRole("alert"); + expect(screen.getByLabelText("Title")).toHaveValue("Keep this draft"); + expect(create).toHaveBeenCalledTimes(1); + expect(props.onCollectionCreated).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true })); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + expect(deleteCollection).not.toHaveBeenCalled(); + }); + + it("passes the selected ordinary parent through the existing creation dialog", async () => { + create.mockResolvedValue({ namespace: "col-child", parent: beta.namespace, created: true }); + mount(); + const user = userEvent.setup(); + await screen.findByRole("radio", { name: "Beta (col-beta)" }); + await user.click(screen.getByRole("button", { name: "New collection" })); + await user.type(screen.getByLabelText("Title"), "Child"); + await user.click(screen.getByRole("combobox", { name: "Inside" })); + await user.click(screen.getByRole("option", { name: "Beta", exact: true })); + expect(screen.getByText(/A collection inside another inherits its grants/)).toBeInTheDocument(); + await user.click(screen.getByRole("button", { name: "Create", exact: true })); + await waitFor(() => + expect(create).toHaveBeenCalledWith("acme", "col-child", expect.objectContaining({ parent: beta.namespace })), + ); + }); + + it("never applies a late creation to a different caller or selects it automatically", async () => { + const pending = deferred>>(); + create.mockReturnValueOnce(pending.promise); + const { props, update } = mount(); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + fireEvent.click(screen.getByRole("button", { name: "New collection" })); + fireEvent.change(screen.getByLabelText("Title"), { target: { value: "Old draft" } }); + fireEvent.click(screen.getByRole("button", { name: "Create", exact: true })); + update({ callerKey: "owner-b:auth-2" }); + expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); + await act(async () => pending.resolve({ namespace: "col-old-draft", parent: "", created: true })); + expect(props.onCollectionCreated).not.toHaveBeenCalled(); + expect(screen.queryByText(copy.created("col-old-draft"))).not.toBeInTheDocument(); + expect(props.onChange).not.toHaveBeenCalledWith(expect.objectContaining({ namespace: "col-old-draft" })); + expect(deleteCollection).not.toHaveBeenCalled(); + }); + + it("cancels creation without a mutation and drains an outstanding list on unmount", async () => { + const pending = deferred(); + const { unmount } = mount(); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + fireEvent.click(screen.getByRole("button", { name: "New collection" })); + fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true })); + list.mockReturnValueOnce(pending.promise); + fireEvent.click(screen.getByRole("button", { name: "Refresh collections" })); + await waitFor(() => expect(list).toHaveBeenCalledTimes(2)); + const signal = list.mock.calls[1][1]?.signal; + unmount(); + expect(signal?.aborted).toBe(true); + await act(async () => pending.resolve(pageOf([alpha]))); + expect(create).not.toHaveBeenCalled(); + }); + + it("supports labelled keyboard choice and passes axe", async () => { + const { container, props } = mount(); + const user = userEvent.setup(); + await user.click(await screen.findByRole("radio", { name: "Alpha (col-alpha)" })); + await user.keyboard("{ArrowDown>}"); + await waitFor(() => expect(screen.getByRole("radio", { name: "Beta (col-beta)" })).toBeChecked()); + await user.keyboard("{/ArrowDown}"); + expect(props.onChange).toHaveBeenLastCalledWith(beta); + expect(screen.getByRole("radiogroup", { name: copy.destinationsLabel })).toBeInTheDocument(); + expect(screen.getByLabelText(copy.searchLabel)).toHaveAccessibleDescription(copy.searchHint); + expect(await axeViolations(container)).toEqual([]); + }); + + it("does not submit the surrounding setup form when searching with Enter", async () => { + const submit = vi.fn((event: FormEvent) => event.preventDefault()); + render( +
+ + , + ); + await screen.findByRole("radio", { name: "Alpha (col-alpha)" }); + const user = userEvent.setup(); + await user.type(screen.getByLabelText(copy.searchLabel), "alpha{Enter}"); + expect(submit).not.toHaveBeenCalled(); + expect(create).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/flows/SourceDestinationStep.tsx b/frontend/src/flows/SourceDestinationStep.tsx new file mode 100644 index 0000000000..dcf127b283 --- /dev/null +++ b/frontend/src/flows/SourceDestinationStep.tsx @@ -0,0 +1,293 @@ +import { Button } from "@clickhouse/click-ui/Button"; +import { SearchField } from "@clickhouse/click-ui/SearchField"; +import { useEffect, useId, useRef, useState } from "react"; +import { type CollectionEntry, listCollections } from "../api"; +import { Alert } from "../components/ui/Alert"; +import { ChoiceGroup } from "../components/ui/ChoiceGroup"; +import { ListState } from "../components/ui/ListState"; +import { Loading } from "../components/ui/Loading"; +import { SectionHeading } from "../components/ui/SectionHeading"; +import { onCollectionsChanged } from "../lib/collectionPlaces"; +import { canHold, COLLECTIONS_PAGE, COLLECTIONS_PAGES, collectionOrder, collectionTitle, titleKey } from "../lib/collections"; +import { useAbortableEffect } from "../lib/hooks"; +import { isCollectionName, isPersonalCollection } from "../lib/namespace"; +import { CreateCollectionDialog } from "./CreateCollectionDialog"; + +/** Supplied by the setup flow so this isolated step introduces no translation catalog. */ +export interface SourceDestinationCopy { + title: string; + description: string; + searchLabel: string; + searchHint: string; + pageScope: string; + destinationsLabel: string; + loading: string; + loadError: string; + things: string; + empty: string; + previous: string; + next: string; + refresh: string; + create: string; + createHint: string; + topLevelHint: string; + selectionHint: string; + pagingError: string; + pagingLimit: string; + inheritanceHint: (parent: string) => string; + created: (namespace: string) => string; + selected: (namespace: string) => string; + page: (number: number) => string; +} + +export type SourceDestinationInvalidation = "context_changed" | "collections_changed" | "selection_changed" | "refresh"; + +export interface SourceDestinationProps { + org: string; + /** Authenticated caller/auth revision, not an email or a source account address. */ + callerKey: string; + /** Parent changes this when connection, selected content or mode changes. */ + contextKey: string; + /** Parent changes this for grant/parent changes not covered by collection events. */ + collectionVersion?: string | number; + value: CollectionEntry | null; + onChange: (destination: CollectionEntry | null) => void; + /** Clears the parent's effective-access preview; this step never grants authority. */ + onInvalidated: (reason: SourceDestinationInvalidation) => void; + /** Exact confirmed identity, including when the next catalog read fails. Not auto-selected. */ + onCollectionCreated: (created: { org: string; callerKey: string; namespace: string }) => void; + copy: SourceDestinationCopy; + disabled?: boolean; +} + +function writableOrdinary(c: CollectionEntry): boolean { + return ( + canHold(c) && + (c.role === "writer" || c.role === "admin") && + isCollectionName(c.namespace) && + !isPersonalCollection(c.namespace) + ); +} + +/** Destination choice only. Collection grants do not delegate the source connection. */ +export function SourceDestinationStep(props: SourceDestinationProps) { + const scope = JSON.stringify([props.org, props.callerKey, props.contextKey, props.collectionVersion ?? 0]); + const previous = useRef(scope); + const callbacks = useRef(props); + callbacks.current = props; + const changed = previous.current !== scope; + useEffect(() => { + const wasChanged = previous.current !== scope; + previous.current = scope; + callbacks.current.onInvalidated(wasChanged ? "context_changed" : "refresh"); + if (wasChanged) callbacks.current.onChange(null); + }, [scope]); + return ; +} + +function DestinationChoices(props: SourceDestinationProps) { + const { org, callerKey, copy, disabled = false } = props; + const titleId = useId(); + const hintId = useId(); + const searchId = useId(); + const [query, setQuery] = useState(""); + const [cursors, setCursors] = useState<(string | null)[]>([null]); + const [page, setPage] = useState(0); + const [revision, setRevision] = useState(0); + const [answer, setAnswer] = useState<{ rows: CollectionEntry[]; next: string | null } | null>(null); + const [failed, setFailed] = useState(false); + const [busy, setBusy] = useState(true); + const [createOpen, setCreateOpen] = useState(false); + const [createdNamespace, setCreatedNamespace] = useState(null); + const current = useRef(props); + current.current = props; + const createVersion = useRef(0); + const cursor = cursors[page]; + + const reload = () => { + current.current.onInvalidated("refresh"); + if (current.current.value) current.current.onChange(null); + setBusy(true); + setCursors([null]); + setPage(0); + setRevision((r) => r + 1); + }; + const reloadRef = useRef(reload); + reloadRef.current = reload; + useEffect(() => { + const unsubscribe = onCollectionsChanged((made) => { + if (!made || made.org === org) reloadRef.current(); + }); + const focus = () => reloadRef.current(); + window.addEventListener("focus", focus); + return () => { + unsubscribe(); + window.removeEventListener("focus", focus); + }; + }, [org]); + + useAbortableEffect( + async (signal, live) => { + if (signal.aborted) return; + setBusy(true); + setFailed(false); + try { + const result = await listCollections(org, { cursor, limit: COLLECTIONS_PAGE, signal }); + if (!live()) return; + // Repeated rows from replicas are displayed once, using the last metadata read. + const rows = [...new Map(result.collections.map((c) => [c.namespace, c])).values()]; + setAnswer({ rows, next: result.next_cursor }); + setBusy(false); + } catch { + if (live()) { + setFailed(true); + setBusy(false); + } + } + }, + [org, cursor, revision], + ); + + useEffect(() => { + const selected = props.value; + if (!selected) return; + const found = answer?.rows.find((c) => c.namespace === selected.namespace); + if ( + !writableOrdinary(selected) || + (found && (!writableOrdinary(found) || found.parent !== selected.parent || found.role !== selected.role)) + ) { + current.current.onInvalidated("collections_changed"); + current.current.onChange(null); + } + }, [answer, props.value]); + + const lastPage = useRef(page); + useEffect(() => { + if (answer && !busy && lastPage.current !== page) { + document.getElementById(titleId)?.focus(); + lastPage.current = page; + } + }, [answer, busy, page, titleId]); + + const rows = (answer?.rows ?? []).filter(writableOrdinary).sort(collectionOrder); + const text = titleKey(query.trim()); + const visible = rows.filter((c) => titleKey(`${collectionTitle(c)} ${c.namespace}`).includes(text)); + const repeatedCursor = !!answer?.next && cursors.slice(0, page + 1).includes(answer.next); + const pageLimit = !!answer?.next && page + 1 >= COLLECTIONS_PAGES; + const choose = (namespace: string) => { + const row = visible.find((c) => c.namespace === namespace); + if (!row || disabled || busy) return; + props.onInvalidated("selection_changed"); + props.onChange(row); + }; + const goTo = (index: number) => { + setAnswer(null); + setBusy(true); + setFailed(false); + setPage(index); + }; + + return ( +
+ +

{copy.description}

+ { + if (event.key === "Enter") event.preventDefault(); + }} + disabled={disabled} + aria-describedby={hintId} + /> +

+ {copy.searchHint} +

+
+ + +
+

{copy.createHint}

+ {createdNamespace && } + {props.value &&

{copy.selected(props.value.namespace)}

} + {failed ? ( + + ) : !answer ? ( + + ) : ( +
+ {visible.length ? ( + ({ + value: c.namespace, + label: `${collectionTitle(c)} (${c.namespace})`, + hint: c.parent ? copy.inheritanceHint(c.parent) : copy.topLevelHint, + }))} + /> + ) : text ? ( + { + setQuery(""); + document.getElementById(searchId)?.focus(); + }} + /> + ) : ( + + )} + {repeatedCursor && } + {pageLimit && !repeatedCursor && } +
+ )} +
+ + {copy.page(page + 1)} + +
+

{copy.selectionHint}

+ {createOpen && !disabled && ( + { + props.onInvalidated("collections_changed"); + return ++createVersion.current; + }} + onCreated={(namespace, version) => { + if (version !== createVersion.current) return; + setCreatedNamespace(namespace); + props.onCollectionCreated({ org, callerKey, namespace }); + }} + /> + )} +
+ ); +} diff --git a/server/knowledge/api/models_mcp_profiles.py b/server/knowledge/api/models_mcp_profiles.py new file mode 100644 index 0000000000..5d080728e8 --- /dev/null +++ b/server/knowledge/api/models_mcp_profiles.py @@ -0,0 +1,48 @@ +"""Operator approval metadata; no endpoint, credential or publication authority.""" + +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field + + +class MCPProfilesInput(BaseModel): + """List approved profile declarations for the signed-in caller's organization.""" + + model_config = ConfigDict(extra="forbid") + + org: str = Field(description="The caller's authenticated organization.") + query: str = Field( + default="", + max_length=256, + description="Case-insensitive ID or label filter, at most 256 UTF-8 bytes; default empty.", + ) + cursor: str | None = Field( + default=None, + max_length=2048, + description="Continuation from this listing with the same arguments; default none.", + ) + limit: int = Field( + default=100, + ge=1, + le=100, + strict=True, + description="Maximum profile declarations per page, from 1 to 100; default 100.", + ) + + +class MCPProfileEntry(BaseModel): + """An operator declaration, without remote identity or compatibility verification.""" + + id: str + label: str + auth: Literal["none", "bearer"] + profile_sha256: str + approved_tools: list[str] + allow_collection_copy: bool = Field( + description="Operator read-policy approval only; copying still requires publication grants." + ) + + +class MCPProfilesOutput(BaseModel): + profiles: list[MCPProfileEntry] + next_cursor: str | None = None diff --git a/server/knowledge/api/ops_mcp_profiles.py b/server/knowledge/api/ops_mcp_profiles.py new file mode 100644 index 0000000000..469eea0871 --- /dev/null +++ b/server/knowledge/api/ops_mcp_profiles.py @@ -0,0 +1,18 @@ +"""Read-only operator profile discovery on the common operation transport.""" + +from server.knowledge.api.models_mcp_profiles import MCPProfilesInput, MCPProfilesOutput +from server.knowledge.app.mcp_profile_api import handle_mcp_profiles +from server.operations.base import Operation, Role + +OPERATIONS: list[Operation] = [ + Operation( + name="knowledge.source.mcp_profiles", + input_model=MCPProfilesInput, + output_model=MCPProfilesOutput, + handler=handle_mcp_profiles, + idempotent=True, + required_role=Role.VIEWER, + skip_namespace_authz=True, + maturity="experimental", + ), +] diff --git a/server/knowledge/app/mcp_profile_api.py b/server/knowledge/app/mcp_profile_api.py new file mode 100644 index 0000000000..07a3809ff8 --- /dev/null +++ b/server/knowledge/app/mcp_profile_api.py @@ -0,0 +1,60 @@ +"""Read approved profile declarations after the personal-connection identity check.""" + +from datetime import UTC, datetime + +from server.auth.context import current_auth +from server.core.cursors import decode_bound_cursor, encode_bound_cursor +from server.core.errors import ValidationError +from server.knowledge.api.models_mcp_profiles import ( + MCPProfileEntry, + MCPProfilesInput, + MCPProfilesOutput, +) +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app.mcp_profiles import MCPProfileError, load_mcp_profile_catalog + +# Catalog IDs have no timestamp; the shared cursor carries this fixed keyset anchor. +_CURSOR_TIME = datetime(1970, 1, 1, tzinfo=UTC) + + +async def handle_mcp_profiles(input: MCPProfilesInput) -> MCPProfilesOutput: + org, subject = await accounts.own_subject(current_auth()) + if org != input.org: + raise accounts.unavailable() + try: + catalog = load_mcp_profile_catalog() + scope = ( + "knowledge.source.mcp_profiles", + org, + subject, + input.query, + catalog.sha256, + str(input.limit), + ) + after = None + if input.cursor is not None: + anchor, after = decode_bound_cursor(input.cursor, scope) + if anchor != _CURSOR_TIME: + raise ValidationError("cursor is not one this op issued for this request") + page = catalog.page(org, input.query, after, input.limit) + next_cursor = ( + encode_bound_cursor(scope, _CURSOR_TIME, page.next_after) + if page.next_after is not None + else None + ) + return MCPProfilesOutput( + profiles=[ + MCPProfileEntry( + id=item.id, + label=item.label, + auth=item.auth, + profile_sha256=item.profile_sha256, + approved_tools=list(item.approved_tools), + allow_collection_copy=item.allow_collection_copy, + ) + for item in page.items + ], + next_cursor=next_cursor, + ) + except MCPProfileError: + raise ValidationError("MCP_PROFILE_INVALID") from None diff --git a/server/knowledge/app/mcp_profiles.py b/server/knowledge/app/mcp_profiles.py new file mode 100644 index 0000000000..4dd1e33162 --- /dev/null +++ b/server/knowledge/app/mcp_profiles.py @@ -0,0 +1,406 @@ +"""Operator read approvals and unopened clients; caller grants remain separate.""" + +from __future__ import annotations + +import hashlib +import json +import math +import unicodedata +from collections.abc import Awaitable, Callable +from dataclasses import asdict, dataclass, field, fields, replace +from functools import lru_cache +from typing import Any, Literal + +from server.clients.mcp_source import ( + MCPBearer, + MCPLimits, + MCPSourceClient, + MCPSourceConfig, + MCPSourceError, + MCPToolMapping, +) +from server.knowledge.domain.mcp_sources import ( + ConnectionEnvelope, + MCPSourceContractError, + SourceContract, + bind_envelope, +) +from server.settings import settings + +MAX_CATALOG_BYTES = 8 * 1024 * 1024 +MAX_PROFILES = 10_000 +MAX_PROFILE_BYTES = 65_536 +MAX_SCHEMA_BYTES = 16_384 +MAX_PROFILE_NODES = 4096 +MAX_PROFILE_DEPTH = 16 + + +class MCPProfileError(ValueError): + """Configuration and binding failures reveal no supplied values.""" + + def __init__(self) -> None: + super().__init__("MCP_PROFILE_INVALID") + + +def _text(value: Any, maximum: int, *, empty: bool = False) -> str: + if ( + not isinstance(value, str) + or (not empty and not value.strip()) + or len(value.encode("utf-8")) > maximum + or any(unicodedata.category(char) == "Cc" for char in value) + ): + raise MCPProfileError() + return value + + +def _object(value: Any, allowed: set[str], required: set[str]) -> dict[str, Any]: + if not isinstance(value, dict) or set(value) - allowed or required - set(value): + raise MCPProfileError() + return value + + +def _canonical(value: Any, maximum: int) -> str: + encoded = json.dumps( + value, sort_keys=True, ensure_ascii=False, allow_nan=False, separators=(",", ":") + ) + if len(encoded.encode("utf-8")) > maximum: + raise MCPProfileError() + return encoded + + +def _pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise MCPProfileError() + result[key] = value + return result + + +def _nonfinite(value: str) -> None: + raise MCPProfileError() + + +def _bounded_tree(value: Any) -> None: + remaining = MAX_PROFILE_NODES + + def visit(node: Any, depth: int) -> None: + nonlocal remaining + remaining -= 1 + if remaining < 0 or depth > MAX_PROFILE_DEPTH: + raise MCPProfileError() + if isinstance(node, dict): + for key, child in node.items(): + _text(key, MAX_SCHEMA_BYTES, empty=True) + visit(child, depth + 1) + elif isinstance(node, list): + for child in node: + visit(child, depth + 1) + elif isinstance(node, str): + _text(node, MAX_SCHEMA_BYTES, empty=True) + elif isinstance(node, float) and not math.isfinite(node): + raise MCPProfileError() + + visit(value, 0) + + +def _strings(value: Any, count: int, size: int) -> tuple[str, ...]: + if not isinstance(value, list) or len(value) > count: + raise MCPProfileError() + result = tuple(_text(item, size) for item in value) + if len(set(result)) != len(result): + raise MCPProfileError() + return result + + +def _mapping(value: Any) -> MCPToolMapping | None: + if value is None: + return None + data = dict( + _object( + value, + {item.name for item in fields(MCPToolMapping)}, + {"name", "input_schema", "output_schema", "argument_name"}, + ) + ) + for name in ("name", "argument_name", "cursor_argument"): + if name in data and not (name == "cursor_argument" and data[name] is None): + _text(data[name], 128) + for name in ("input_schema", "output_schema", "fixed_arguments"): + if name in data: + if not isinstance(data[name], dict): + raise MCPProfileError() + _canonical(data[name], MAX_SCHEMA_BYTES) + for name in ( + "items_path", + "id_path", + "title_path", + "text_path", + "uri_path", + "revision_path", + "next_cursor_path", + ): + if name in data: + if data[name] is None and name not in {"items_path", "id_path"}: + continue + path = data[name] + if not isinstance(path, list) or len(path) > 8: + raise MCPProfileError() + data[name] = tuple(_text(part, 128) for part in path) + return MCPToolMapping(**data) + + +def _config(value: Any) -> MCPSourceConfig: + data = _object( + value, + {"endpoint", "bearer_audience", "approved_tools", "search", "read", "limits"}, + {"endpoint"}, + ) + audience = data.get("bearer_audience") + if audience is not None: + audience = _text(audience, 2048) + limits = _object(data.get("limits", {}), {item.name for item in fields(MCPLimits)}, set()) + return MCPSourceConfig( + endpoint=_text(data["endpoint"], 2048), + bearer_audience=audience, + approved_tools=_strings(data.get("approved_tools", []), 2, 128), + search=_mapping(data.get("search")), + read=_mapping(data.get("read")), + limits=MCPLimits(**limits), + ) + + +def _snapshot(config: MCPSourceConfig) -> str: + data = asdict(config) + # Selection has one authority: the source contract, never the operator prototype. + del data["approved_resource_ids"] + return _canonical(data, MAX_PROFILE_BYTES) + + +@dataclass(frozen=True) +class MCPProfileMetadata: + id: str + label: str + auth: Literal["none", "bearer"] + profile_sha256: str + allow_collection_copy: bool + approved_tools: tuple[str, ...] + + +@dataclass(frozen=True, repr=False) +class FrozenProfileDefinition: + """Canonical operator profile JSON; its digest covers policy and config together.""" + + metadata: MCPProfileMetadata + allowed_orgs: frozenset[str] + config_snapshot: str = field(repr=False) + + def allows(self, org: str) -> bool: + return org in self.allowed_orgs or "*" in self.allowed_orgs + + +def _profile(value: Any) -> FrozenProfileDefinition: + _bounded_tree(value) + _canonical(value, MAX_PROFILE_BYTES) + data = _object( + value, + {"id", "label", "auth", "allowed_orgs", "allow_collection_copy", "config"}, + {"id", "label", "auth", "allowed_orgs", "config"}, + ) + identity = _text(data["id"], 128) + label = _text(data["label"], 256) + auth = data["auth"] + if auth not in ("none", "bearer"): + raise MCPProfileError() + orgs = _strings(data["allowed_orgs"], 256, 256) + copy_allowed = data.get("allow_collection_copy", False) + if type(copy_allowed) is not bool: + raise MCPProfileError() + config = _config(data["config"]) + if (auth == "bearer") != (config.bearer_audience is not None): + raise MCPProfileError() + snapshot = _snapshot(config) + approval = { + "id": identity, + "label": label, + "auth": auth, + "allowed_orgs": sorted(orgs), + "allow_collection_copy": copy_allowed, + "config": json.loads(snapshot), + } + snapshot = _canonical(approval, MAX_PROFILE_BYTES) + digest = hashlib.sha256(snapshot.encode()).hexdigest() + metadata = MCPProfileMetadata( + identity, label, auth, digest, copy_allowed, config.approved_tools + ) + return FrozenProfileDefinition(metadata, frozenset(orgs), snapshot) + + +@dataclass(frozen=True) +class MCPProfilePage: + items: tuple[MCPProfileMetadata, ...] + next_after: str | None = None + + +@dataclass(frozen=True, repr=False) +class MCPProfileCatalog: + """Parse only trusted operator configuration; request arguments select an ID later.""" + + _profiles: tuple[FrozenProfileDefinition, ...] = () + sha256: str = hashlib.sha256(b"[]").hexdigest() + + @classmethod + def parse(cls, payload: str | bytes | None = None) -> MCPProfileCatalog: + try: + if payload is None: + return cls() + if isinstance(payload, bytes): + if len(payload) > MAX_CATALOG_BYTES: + raise MCPProfileError() + payload = payload.decode("utf-8") + if not isinstance(payload, str) or len(payload.encode()) > MAX_CATALOG_BYTES: + raise MCPProfileError() + data = _object( + json.loads(payload, object_pairs_hook=_pairs, parse_constant=_nonfinite), + {"version", "profiles"}, + {"version", "profiles"}, + ) + if type(data["version"]) is not int or data["version"] != 1: + raise MCPProfileError() + rows = data["profiles"] + if not isinstance(rows, list) or len(rows) > MAX_PROFILES: + raise MCPProfileError() + profiles = tuple(sorted((_profile(row) for row in rows), key=lambda p: p.metadata.id)) + if sum(len(p.config_snapshot.encode()) for p in profiles) > MAX_CATALOG_BYTES: + raise MCPProfileError() + if len({p.metadata.id for p in profiles}) != len(profiles): + raise MCPProfileError() + digest = hashlib.sha256( + _canonical( + [p.metadata.profile_sha256 for p in profiles], MAX_CATALOG_BYTES + ).encode() + ).hexdigest() + return cls(profiles, digest) + except (ValueError, TypeError, RecursionError, OverflowError, MCPSourceError): + raise MCPProfileError() from None + + def get(self, org: str, profile_id: str) -> FrozenProfileDefinition: + try: + _text(org, 256) + _text(profile_id, 128) + for profile in self._profiles: + if profile.metadata.id == profile_id and profile.allows(org): + return profile + except (ValueError, TypeError): + pass + raise MCPProfileError() from None + + def page( + self, org: str, query: str = "", after: str | None = None, limit: int = 100 + ) -> MCPProfilePage: + try: + _text(org, 256) + needle = _text(query, 256, empty=True).casefold() + if after is not None: + _text(after, 128) + if type(limit) is not int or not 1 <= limit <= 100: + raise MCPProfileError() + items: list[MCPProfileMetadata] = [] + for profile in self._profiles: + if not profile.allows(org): + continue + metadata = profile.metadata + if needle not in metadata.id.casefold() and needle not in metadata.label.casefold(): + continue + if after is not None and metadata.id <= after: + continue + items.append(metadata) + if len(items) > limit: + return MCPProfilePage(tuple(items[:limit]), items[limit - 1].id) + return MCPProfilePage(tuple(items)) + except (ValueError, TypeError): + raise MCPProfileError() from None + + +def build_mcp_source_client( + profile: FrozenProfileDefinition, + envelope: ConnectionEnvelope, + *, + org: str, + owner: str, + slot: str, + generation: str, + validate_access: Callable[[], Awaitable[None]], + contract: SourceContract | None = None, +) -> MCPSourceClient: + """Bind sealed credentials to current approval; fresh access checks run on use. + + The caller supplies verified context and rejects local credentials. Its callback + rechecks grants, fleet readiness, source, profile and owner standing. Collection + copy approval is a read policy constraint; publication still needs its own grant. + """ + try: + if not isinstance(profile, FrozenProfileDefinition) or not callable(validate_access): + raise MCPProfileError() + if not isinstance(envelope, ConnectionEnvelope): + raise MCPProfileError() + envelope = ConnectionEnvelope.model_validate(envelope) + if not profile.allows(org) or profile.metadata.auth != envelope.auth: + raise MCPProfileError() + config = _config(json.loads(profile.config_snapshot)["config"]) + bind_envelope( + envelope, + org=org, + owner=owner, + slot=slot, + generation=generation, + profile_id=profile.metadata.id, + profile_sha256=profile.metadata.profile_sha256, + endpoint=config.endpoint, + audience=config.bearer_audience, + ) + selected: tuple[str, ...] = () + if contract is not None: + if not isinstance(contract, SourceContract): + raise MCPProfileError() + contract = SourceContract.model_validate(contract) + if ( + contract.slot, + contract.generation, + contract.profile_id, + contract.profile_sha256, + ) != ( + slot, + generation, + profile.metadata.id, + profile.metadata.profile_sha256, + ): + raise MCPProfileError() + if ( + contract.reader_policy == "collection_copy" + and not profile.metadata.allow_collection_copy + ): + raise MCPProfileError() + selected = tuple(resource.id for resource in contract.resources) + credential = None + if envelope.bearer is not None and envelope.audience is not None: + credential = MCPBearer(envelope.bearer.get_secret_value(), envelope.audience) + return MCPSourceClient( + replace(config, approved_resource_ids=selected), + credential, + validate_access=validate_access, + ) + except (ValueError, TypeError, RecursionError, MCPSourceError, MCPSourceContractError): + raise MCPProfileError() from None + + +@lru_cache(maxsize=1) +def _catalog_from_setting(payload: str) -> MCPProfileCatalog: + if not isinstance(payload, str): + raise MCPProfileError() + return MCPProfileCatalog.parse(None if payload == "" else payload) + + +def load_mcp_profile_catalog() -> MCPProfileCatalog: + """Read trusted operator configuration; retain at most one immutable snapshot.""" + return _catalog_from_setting(settings.knowledge_source_mcp_profiles_json) diff --git a/server/knowledge/domain/mcp_identity.py b/server/knowledge/domain/mcp_identity.py new file mode 100644 index 0000000000..2724001ae2 --- /dev/null +++ b/server/knowledge/domain/mcp_identity.py @@ -0,0 +1,39 @@ +"""Stable document addresses for opaque selected identities; no fetching or authority.""" + +from __future__ import annotations + +import hashlib +from uuid import UUID + +from server.knowledge.domain.mcp_sources import ResourceIdentity +from server.knowledge.domain.sources import mirror_uri + + +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/settings/catalog.py b/server/settings/catalog.py index 3839db6b86..6181f8d93e 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -2460,6 +2460,22 @@ class KnowledgeSettings(BaseModel): # Bytes read from a connected-account token or identity response; larger metadata # replies are refused before parsing. knowledge_connected_oauth_response_max_bytes: int = Field(default=64 * 1024, ge=1024) + # Operator-approved MCP read profiles as version-1 JSON, at most 8 MiB UTF-8; + # empty approves none, and profile metadata grants no connection or publication access. + knowledge_source_mcp_profiles_json: str = Field( + default="", max_length=8 * 1024 * 1024, repr=False + ) + + @field_validator("knowledge_source_mcp_profiles_json") + @classmethod + def _mcp_profiles_size(cls, value: str) -> str: + try: + if len(value.encode("utf-8")) > 8 * 1024 * 1024: + raise ValueError("MCP_PROFILE_INVALID") + except UnicodeError: + raise ValueError("MCP_PROFILE_INVALID") from None + return value + # Active document sources (knowledge.source.add) one namespace may register; an # add past it is refused with SOURCE_QUOTA. knowledge_sources_max_per_namespace: Annotated[int, LIVE] = Field(default=8, ge=1) diff --git a/tests/unit/test_mcp_profile_api.py b/tests/unit/test_mcp_profile_api.py new file mode 100644 index 0000000000..e524168b7f --- /dev/null +++ b/tests/unit/test_mcp_profile_api.py @@ -0,0 +1,382 @@ +"""Authenticated operator metadata pages use the common signed cursor.""" + +from __future__ import annotations + +import json +import socket +from collections.abc import Iterator +from dataclasses import replace +from datetime import UTC, datetime +from types import SimpleNamespace +from typing import Any + +import httpx +import pytest +from pydantic import ValidationError as ModelValidationError + +import server.settings as settings_module +from server.auth import reader_identity +from server.auth.context import current_auth_var +from server.auth.jwt import AuthInfo +from server.core.cursors import decode_bound_cursor, encode_bound_cursor +from server.core.errors import LoomServerError, ValidationError +from server.knowledge.api.models_mcp_profiles import MCPProfilesInput, MCPProfilesOutput +from server.knowledge.api.ops_mcp_profiles import OPERATIONS +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import mcp_profile_api, mcp_profiles +from server.knowledge.app.mcp_profile_api import handle_mcp_profiles +from server.knowledge.app.mcp_profiles import MCPProfileError, load_mcp_profile_catalog +from server.operations.base import Role +from server.settings._live import LIVE +from server.settings.catalog import KnowledgeSettings + + +def profile(identity: str, orgs: list[str], **changes: Any) -> dict[str, Any]: + value = { + "id": identity, + "label": "Opaque document label", + "auth": "bearer", + "allowed_orgs": orgs, + "config": { + "endpoint": "https://offline.invalid/mcp", + "bearer_audience": "https://offline.invalid/audience", + }, + } + value.update(changes) + return value + + +def configure(world: SimpleNamespace, *rows: dict[str, Any]) -> None: + world.settings.knowledge_source_mcp_profiles_json = json.dumps({"version": 1, "profiles": rows}) + + +def auth(subject: str = "person-a", org: str = "org-a", **changes: Any) -> AuthInfo: + caller = AuthInfo( + subject=subject, + org=org, + namespaces=("personal",), + roles=(Role.VIEWER,), + is_service_account=False, + issued_at=1000, + session_id="session-" + subject, + ) + return replace(caller, **changes) + + +@pytest.fixture +def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]: + fake = SimpleNamespace( + knowledge_source_mcp_profiles_json="", + jwt_secret="unit-profile-cursor-key", + auth_actually_required=lambda: True, + ) + state = SimpleNamespace(settings=fake, active=True, managed_denial=False, revoked={}, seen=[]) + + def refuse(*args: Any, **kwargs: Any) -> Any: + pytest.fail("metadata listing must not open HTTP, sockets, DNS, sessions or account rows") + + async def canonical(org: str, subject: str) -> str: + state.seen.append((org, subject)) + return subject + + async def identity(org: str, subject: str) -> SimpleNamespace: + return SimpleNamespace(subject=subject, emails=()) + + async def spellings(org: str, subject: str) -> list[str]: + return [subject] + + async def active(org: str, subjects: list[str]) -> bool: + return state.active + + async def managed(subject: str, *, org: str, also: tuple[str, ...]) -> bool: + return state.managed_denial + + async def cutoffs(keys: list[str]) -> dict[str, int]: + return state.revoked + + monkeypatch.setattr(httpx, "AsyncClient", refuse) + monkeypatch.setattr(socket, "socket", refuse) + monkeypatch.setattr(socket, "getaddrinfo", refuse) + monkeypatch.setattr(mcp_profiles, "MCPSourceClient", refuse) + monkeypatch.setattr(accounts.store, "owned", refuse) + monkeypatch.setattr(mcp_profiles, "settings", fake) + monkeypatch.setattr(settings_module, "settings", fake) + monkeypatch.setattr(accounts, "settings", fake) + monkeypatch.setattr(reader_identity, "settings", fake) + monkeypatch.setattr(accounts.aliases, "canonical_subject", canonical) + monkeypatch.setattr(accounts.aliases, "verified_spellings", spellings) + monkeypatch.setattr(accounts, "resolve_reader", identity) + monkeypatch.setattr(accounts.store, "account_active", active) + monkeypatch.setattr(accounts.scim, "refuses_subject", managed) + monkeypatch.setattr(accounts.revocation, "cutoffs", cutoffs) + token = current_auth_var.set(auth()) + try: + yield state + finally: + current_auth_var.reset(token) + + +def test_setting_is_empty_bounded_and_not_live() -> None: + field = KnowledgeSettings.model_fields["knowledge_source_mcp_profiles_json"] + assert field.default == "" + assert field.repr is False + assert KnowledgeSettings().knowledge_source_mcp_profiles_json == "" + assert LIVE not in field.metadata + with pytest.raises(ModelValidationError): + KnowledgeSettings(knowledge_source_mcp_profiles_json="é" * (4 * 1024 * 1024 + 1)) + + +@pytest.mark.asyncio +async def test_empty_setting_returns_no_profiles(world: SimpleNamespace) -> None: + result = await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + assert result.model_dump() == {"profiles": [], "next_cursor": None} + assert world.seen == [("org-a", "person-a")] + + +def test_loader_uses_actual_content_and_detaches_metadata(world: SimpleNamespace) -> None: + configure(world, profile("first", ["org-a"])) + first = load_mcp_profile_catalog() + assert load_mcp_profile_catalog() is first + configure(world, profile("second", ["org-b"])) + second = load_mcp_profile_catalog() + assert second.sha256 != first.sha256 + assert [item.id for item in first.page("org-a").items] == ["first"] + assert second.page("org-a").items == () + world.settings.knowledge_source_mcp_profiles_json = "{secret-invalid-config" + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + load_mcp_profile_catalog() + world.settings.knowledge_source_mcp_profiles_json = "" + assert load_mcp_profile_catalog().page("org-a").items == () + + +@pytest.mark.asyncio +async def test_two_org_users_only_see_eligible_safe_metadata(world: SimpleNamespace) -> None: + configure( + world, + profile("a", ["org-a"], allow_collection_copy=True), + profile("b", ["org-b"]), + profile("c", []), + ) + first = await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + current_auth_var.set(auth("person-b", "org-b")) + second = await handle_mcp_profiles(MCPProfilesInput(org="org-b")) + assert [item.id for item in first.profiles] == ["a"] + assert [item.id for item in second.profiles] == ["b"] + assert first.profiles[0].allow_collection_copy is True + assert set(first.profiles[0].model_dump()) == { + "id", + "label", + "auth", + "profile_sha256", + "approved_tools", + "allow_collection_copy", + } + serialized = first.model_dump_json() + for forbidden in ("allowed_orgs", "endpoint", "offline.invalid", "audience", "config", "total"): + assert forbidden not in serialized + first.profiles[0].approved_tools.append("unapproved") + current_auth_var.set(auth()) + fresh = await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + assert fresh.profiles[0].approved_tools == [] + assert world.seen == [("org-a", "person-a"), ("org-b", "person-b"), ("org-a", "person-a")] + + +@pytest.mark.asyncio +async def test_wrong_org_refuses_before_loading_invalid_operator_setting( + world: SimpleNamespace, +) -> None: + world.settings.knowledge_source_mcp_profiles_json = "{private-malformed-setting" + with pytest.raises(ValidationError) as caught: + await handle_mcp_profiles(MCPProfilesInput(org="org-b", query="private")) + assert caught.value.to_detail() == { + "code": "CONNECTION_UNAVAILABLE", + "message": "the connected account is unavailable", + } + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "changes", + [ + {"is_service_account": True}, + {"reads_as_creator": True, "creator": "person-a"}, + {"issued_at": None}, + {"session_id": ""}, + {"org": "*"}, + {"impersonated_by": "other"}, + ], +) +async def test_connection_list_personal_identity_contract_is_retained( + world: SimpleNamespace, + changes: dict[str, Any], +) -> None: + world.settings.knowledge_source_mcp_profiles_json = "{private-malformed-setting" + current_auth_var.set(auth(**changes)) + with pytest.raises(LoomServerError) as caught: + await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + assert "MCP_PROFILE_INVALID" not in str(caught.value) + assert world.seen == [] + + +@pytest.mark.asyncio +async def test_missing_auth_refuses_before_catalog(world: SimpleNamespace) -> None: + current_auth_var.set(None) + with pytest.raises(LoomServerError): + await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + assert world.seen == [] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("denial", ["active", "managed", "revoked"]) +async def test_current_identity_standing_is_rechecked(world: SimpleNamespace, denial: str) -> None: + configure(world, profile("approved", ["org-a"])) + assert (await handle_mcp_profiles(MCPProfilesInput(org="org-a"))).profiles + if denial == "active": + world.active = False + elif denial == "managed": + world.managed_denial = True + else: + world.revoked = {"person-a": 1001} + with pytest.raises(LoomServerError): + await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + + +@pytest.mark.asyncio +async def test_signed_paging_filters_org_before_continuation(world: SimpleNamespace) -> None: + configure(world, profile("c", ["org-a"]), profile("b", ["org-b"]), profile("a", ["org-a"])) + first = await handle_mcp_profiles(MCPProfilesInput(org="org-a", limit=1)) + assert [item.id for item in first.profiles] == ["a"] + assert first.next_cursor is not None and first.next_cursor != "a" + catalog = load_mcp_profile_catalog() + scope = ("knowledge.source.mcp_profiles", "org-a", "person-a", "", catalog.sha256, "1") + anchor, after = decode_bound_cursor(first.next_cursor, scope) + assert anchor == datetime(1970, 1, 1, tzinfo=UTC) and after == "a" + last = await handle_mcp_profiles( + MCPProfilesInput(org="org-a", limit=1, cursor=first.next_cursor) + ) + assert [item.id for item in last.profiles] == ["c"] + assert last.next_cursor is None + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change", ["query", "org", "user", "catalog", "limit", "key"]) +async def test_common_cursor_refuses_scope_or_catalog_drift( + world: SimpleNamespace, change: str +) -> None: + configure(world, profile("a", ["org-a", "org-b"]), profile("b", ["org-a", "org-b"])) + first = await handle_mcp_profiles(MCPProfilesInput(org="org-a", limit=1)) + args: dict[str, Any] = {"org": "org-a", "limit": 1, "cursor": first.next_cursor} + if change == "query": + args["query"] = "Opaque" + elif change == "org": + current_auth_var.set(auth("person-b", "org-b")) + args["org"] = "org-b" + elif change == "user": + current_auth_var.set(auth("person-b")) + elif change == "catalog": + configure(world, profile("a", ["org-a"]), profile("c", ["org-a"])) + elif change == "limit": + args["limit"] = 2 + else: + world.settings.jwt_secret = "rotated-unit-cursor-key" + with pytest.raises(ValidationError, match="cursor is not one this op issued"): + await handle_mcp_profiles(MCPProfilesInput(**args)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("cursor", ["a", "!", "é", "", "not-an-issued-cursor"]) +async def test_raw_or_invalid_continuation_is_refused(world: SimpleNamespace, cursor: str) -> None: + configure(world, profile("a", ["org-a"])) + with pytest.raises(ValidationError, match="cursor is not one this op issued"): + await handle_mcp_profiles(MCPProfilesInput(org="org-a", cursor=cursor)) + + +@pytest.mark.asyncio +async def test_wrong_common_cursor_anchor_refuses(world: SimpleNamespace) -> None: + configure(world, profile("a", ["org-a"])) + scope = ( + "knowledge.source.mcp_profiles", + "org-a", + "person-a", + "", + load_mcp_profile_catalog().sha256, + "100", + ) + cursor = encode_bound_cursor(scope, datetime(2000, 1, 1, tzinfo=UTC), "a") + with pytest.raises(ValidationError, match="cursor is not one this op issued"): + await handle_mcp_profiles(MCPProfilesInput(org="org-a", cursor=cursor)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("payload", [" ", "{secret", '{"version":1,"profiles":[],"secret":1}']) +async def test_invalid_operator_setting_has_fixed_public_error( + world: SimpleNamespace, payload: str +) -> None: + world.settings.knowledge_source_mcp_profiles_json = payload + with pytest.raises(ValidationError) as caught: + await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + assert caught.value.to_detail() == { + "code": "VALIDATION_FAILED", + "message": "MCP_PROFILE_INVALID", + } + assert "secret" not in repr(caught.value) + assert caught.value.__suppress_context__ + + +@pytest.mark.parametrize( + "changes", + [ + {"limit": 0}, + {"limit": 101}, + {"limit": True}, + {"query": "a" * 257}, + {"cursor": "a" * 2049}, + {"endpoint": "https://injected.invalid"}, + {"token": "secret"}, + {"profile_json": "{}"}, + ], +) +def test_wire_request_accepts_only_bounded_listing_arguments(changes: dict[str, Any]) -> None: + with pytest.raises(ModelValidationError): + MCPProfilesInput(org="org-a", **changes) + + +def test_operation_is_read_only_and_uses_connection_list_role_contract() -> None: + assert len(OPERATIONS) == 1 + operation = OPERATIONS[0] + assert operation.name == "knowledge.source.mcp_profiles" + assert operation.handler is handle_mcp_profiles + assert operation.input_model is MCPProfilesInput + assert operation.output_model is MCPProfilesOutput + assert operation.read_only and operation.required_role == Role.VIEWER + assert operation.skip_namespace_authz + assert not operation.deployment_scoped and not operation.writes and not operation.audit + assert operation.maturity == "experimental" + assert mcp_profile_api.handle_mcp_profiles is operation.handler + + +@pytest.mark.asyncio +async def test_query_matches_only_eligible_id_or_label(world: SimpleNamespace) -> None: + configure( + world, + profile("alpha", ["org-a"], label="Read manuals"), + profile("beta", ["org-a"], label="Other documents"), + profile("hidden", ["org-b"], label="Read private material"), + ) + result = await handle_mcp_profiles(MCPProfilesInput(org="org-a", query="READ")) + assert [item.id for item in result.profiles] == ["alpha"] + assert result.next_cursor is None + missing = await handle_mcp_profiles(MCPProfilesInput(org="org-a", query="hidden")) + assert missing.model_dump() == {"profiles": [], "next_cursor": None} + + +@pytest.mark.asyncio +async def test_signed_cursor_does_not_preserve_a_revoked_identity(world: SimpleNamespace) -> None: + configure(world, profile("a", ["org-a"]), profile("b", ["org-a"])) + first = await handle_mcp_profiles(MCPProfilesInput(org="org-a", limit=1)) + assert first.next_cursor is not None + world.active = False + world.settings.knowledge_source_mcp_profiles_json = "{private-invalid-config" + with pytest.raises(LoomServerError) as caught: + await handle_mcp_profiles(MCPProfilesInput(org="org-a", limit=1, cursor=first.next_cursor)) + assert "MCP_PROFILE_INVALID" not in str(caught.value) diff --git a/tests/unit/test_mcp_source_identity.py b/tests/unit/test_mcp_source_identity.py new file mode 100644 index 0000000000..353537d243 --- /dev/null +++ b/tests/unit/test_mcp_source_identity.py @@ -0,0 +1,56 @@ +"""Opaque identities cannot change provenance syntax or collide across sources.""" + +import hashlib + +import pytest + +from server.knowledge.domain.mcp_identity import MCPIdentityError, resource_digest, resource_uri +from server.knowledge.domain.sources import mirror_uri_suffix + +SOURCE = "abcd1234-1234-4234-8234-123456789abc" +OTHER_SOURCE = "abcd1234-1234-4234-8234-123456789abd" + + +@pytest.mark.parametrize( + "identity", + [ + "opaque-id", + "https://example.test/resource?next=other#fragment", + "../different/path", + "id#" + OTHER_SOURCE, + "file:///unused", + "a" * 2048, + "é" * 1024, + ], +) +def test_address_preserves_exact_identity_and_existing_copy_suffix(identity: str) -> None: + expected = hashlib.sha256(identity.encode()).hexdigest() + assert resource_digest(identity) == expected + assert resource_uri(SOURCE, identity) == "mcp-resource:" + expected + "#" + SOURCE + assert resource_uri(SOURCE, identity).endswith(mirror_uri_suffix(SOURCE)) + assert resource_uri(OTHER_SOURCE, identity) != resource_uri(SOURCE, identity) + + +@pytest.mark.parametrize( + "left,right", + [("é", "e\u0301"), ("id", "ID"), ("a/b", "a%2Fb"), ("a#b", "a%23b")], +) +def test_opaque_identity_spellings_are_not_equated(left: str, right: str) -> None: + assert resource_uri(SOURCE, left) != resource_uri(SOURCE, right) + + +@pytest.mark.parametrize("identity", ["", " ", "a\nb", "a\x00b", "a" * 2049, "é" * 1025]) +def test_invalid_resource_identity_is_redacted(identity: str) -> None: + with pytest.raises(MCPIdentityError) as failure: + resource_uri(SOURCE, identity) + assert str(failure.value) == "MCP_RESOURCE_IDENTITY_INVALID" + + +@pytest.mark.parametrize( + "source", + ["", SOURCE.upper(), SOURCE.replace("-", ""), "{" + SOURCE + "}", SOURCE + "#other"], +) +def test_only_canonical_stored_source_identity_is_accepted(source: str) -> None: + with pytest.raises(MCPIdentityError) as failure: + resource_uri(source, "private-resource") + assert str(failure.value) == "MCP_RESOURCE_IDENTITY_INVALID" diff --git a/tests/unit/test_mcp_source_profiles.py b/tests/unit/test_mcp_source_profiles.py new file mode 100644 index 0000000000..639c3eb253 --- /dev/null +++ b/tests/unit/test_mcp_source_profiles.py @@ -0,0 +1,574 @@ +"""Operator approvals bind credentials and selection without granting publication.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import socket +from dataclasses import FrozenInstanceError +from typing import Any + +import httpx +import pytest + +from server.clients.mcp_source import MCPLimits, MCPSourceClient, MCPToolMapping +from server.knowledge.app import mcp_profiles +from server.knowledge.app.mcp_profiles import ( + MAX_CATALOG_BYTES, + MCPProfileCatalog, + MCPProfileError, + build_mcp_source_client, +) +from server.knowledge.domain.mcp_sources import ConnectionEnvelope, SourceContract + +SLOT = "mcp:" + "a" * 32 +GENERATION = "b" * 32 + "/0" + "c" * 31 +ENDPOINT = "https://documents.example/mcp" +AUDIENCE = "https://documents.example/readers" + + +@pytest.fixture(autouse=True) +def no_network(monkeypatch: pytest.MonkeyPatch) -> None: + def refuse(*args: Any, **kwargs: Any) -> Any: + pytest.fail("profile operations must not construct HTTP clients or open sockets") + + monkeypatch.setattr(httpx, "AsyncClient", refuse) + monkeypatch.setattr(socket, "socket", refuse) + monkeypatch.setattr(socket, "getaddrinfo", refuse) + + +async def access_check() -> None: + raise AssertionError("access checks belong to actual client use") + + +def row(identity: str = "approved", **changes: Any) -> dict[str, Any]: + result = { + "id": identity, + "label": "Document server", + "auth": "none", + "allowed_orgs": ["org-a"], + "config": {"endpoint": ENDPOINT}, + } + result.update(changes) + return result + + +def catalog(*rows: dict[str, Any]) -> MCPProfileCatalog: + return MCPProfileCatalog.parse(json.dumps({"version": 1, "profiles": rows})) + + +def envelope(profile: Any, **changes: Any) -> ConnectionEnvelope: + payload = { + "version": 1, + "org": "org-a", + "owner": "owner-a", + "slot": SLOT, + "generation": GENERATION, + "profile_id": profile.metadata.id, + "profile_sha256": profile.metadata.profile_sha256, + "endpoint": ENDPOINT, + "audience": None, + "auth": "none", + } + payload.update(changes) + return ConnectionEnvelope.model_validate(payload) + + +def selection(profile: Any, **changes: Any) -> SourceContract: + payload = { + "version": 1, + "slot": SLOT, + "generation": GENERATION, + "profile_id": profile.metadata.id, + "profile_sha256": profile.metadata.profile_sha256, + "mode": "live", + "reader_policy": "owner_only", + "resources": ({"type": "resource", "id": "doc://selected"},), + } + payload.update(changes) + return SourceContract.model_validate(payload) + + +def client( + profile: Any, sealed: ConnectionEnvelope | None = None, **changes: Any +) -> MCPSourceClient: + context = { + "org": "org-a", + "owner": "owner-a", + "slot": SLOT, + "generation": GENERATION, + "validate_access": access_check, + } + context.update(changes) + return build_mcp_source_client(profile, sealed or envelope(profile), **context) + + +def tool_mapping() -> dict[str, Any]: + return { + "name": "read_document", + "argument_name": "document_id", + "input_schema": { + "type": "object", + "properties": { + "document_id": {"type": "string", "maxLength": 128}, + "scope": {"type": "string", "maxLength": 128}, + }, + "required": ["document_id", "scope"], + "additionalProperties": False, + }, + "output_schema": { + "type": "object", + "properties": { + "id": {"type": "string", "maxLength": 128}, + "text": {"type": "string", "maxLength": 1024}, + }, + "required": ["id", "text"], + "additionalProperties": False, + }, + "fixed_arguments": {"scope": "operator-scope"}, + } + + +def test_empty_catalog_has_no_eligible_profiles() -> None: + empty = MCPProfileCatalog.parse() + assert empty.page("org-a").items == () + assert empty.page("org-a").next_after is None + assert catalog().sha256 == empty.sha256 + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + empty.get("org-a", "missing") + + +def test_org_filter_precedes_paging_and_search() -> None: + profiles = catalog( + row("d", label="Other"), + row("b", allowed_orgs=["org-b"]), + row("c", label="DOCUMENT second"), + row("a"), + row("e", allowed_orgs=[]), + ) + first = profiles.page("org-a", "document", limit=1) + assert [p.id for p in first.items] == ["a"] + assert first.next_after == "a" + second = profiles.page("org-a", "document", after=first.next_after, limit=1) + assert [p.id for p in second.items] == ["c"] + assert second.next_after is None + assert profiles.page("org-c").items == () + for identity in ("b", "e", "absent"): + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + profiles.get("org-a", identity) + + +def test_org_wildcard_requires_explicit_operator_approval() -> None: + profiles = catalog(row("all", allowed_orgs=["*"]), row("none", allowed_orgs=[])) + assert [p.id for p in profiles.page("another-org").items] == ["all"] + + +@pytest.mark.parametrize( + "changes", + [ + {"limit": 0}, + {"limit": 101}, + {"limit": True}, + {"query": "x" * 257}, + {"after": "x" * 129}, + {"query": "secret\n"}, + {"org": ""}, + ], +) +def test_page_arguments_are_bounded(changes: dict[str, Any]) -> None: + args = {"org": "org-a", **changes} + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + catalog(row()).page(**args) + + +@pytest.mark.parametrize( + "payload", + [ + "", + "[]", + '{"version":1,"profiles":[],"secret":true}', + '{"version":1,"version":1,"profiles":[]}', + '{"version":true,"profiles":[]}', + '{"version":2,"profiles":[]}', + '{"version":1,"profiles":null}', + '{"version":1,"profiles":[],"x":NaN}', + '{"version":1,"profiles":[{"id":"secret","id":"other"}]}', + b"\xff", + b" " * (MAX_CATALOG_BYTES + 1), + ], +) +def test_invalid_catalog_errors_never_echo_payload(payload: str | bytes) -> None: + with pytest.raises(MCPProfileError) as caught: + MCPProfileCatalog.parse(payload) + assert str(caught.value) == "MCP_PROFILE_INVALID" + assert "secret" not in repr(caught.value) + assert caught.value.__suppress_context__ + + +@pytest.mark.parametrize( + "change", + [ + {"unknown": "secret"}, + {"id": ""}, + {"id": "x" * 129}, + {"label": "x" * 257}, + {"label": "secret\u0085"}, + {"allowed_orgs": "org-a"}, + {"allowed_orgs": ["org-a"] * 2}, + {"auth": "oauth"}, + {"allow_collection_copy": 1}, + {"approved_resource_ids": []}, + {"config": {"endpoint": ENDPOINT, "approved_resource_ids": ["doc://injected"]}}, + {"config": {"endpoint": ENDPOINT, "selection": []}}, + {"config": {"endpoint": ENDPOINT, "limits": {"max_results": True}}}, + {"config": {"endpoint": ENDPOINT, "limits": {"unknown": 1}}}, + {"config": {"endpoint": ENDPOINT, "limits": {"timeout_seconds": float("inf")}}}, + {"config": {"endpoint": ENDPOINT, "approved_tools": "read"}}, + {"config": {"endpoint": ENDPOINT, "read": {"name": "read"}}}, + {"config": {"endpoint": ENDPOINT, "bearer_audience": AUDIENCE}}, + {"auth": "bearer"}, + ], +) +def test_profile_shape_errors_are_redacted(change: dict[str, Any]) -> None: + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + catalog(row(**change)) + + +def test_duplicate_ids_and_nested_duplicate_fields_refuse() -> None: + with pytest.raises(MCPProfileError): + catalog(row(), row()) + payload = json.dumps({"version": 1, "profiles": [row()]}).replace( + '"endpoint":', '"endpoint":"secret","endpoint":' + ) + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + MCPProfileCatalog.parse(payload) + + +def test_profile_depth_nodes_and_schema_bytes_are_bounded() -> None: + deep: Any = "secret" + for _ in range(18): + deep = [deep] + for schema in ({"deep": deep}, {"nodes": [0] * 4100}, {"description": "x" * 16_384}): + mapping = tool_mapping() + mapping["input_schema"] = schema + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + catalog(row(config={"endpoint": ENDPOINT, "read": mapping})) + + +def test_resource_profile_uses_real_defaults_and_opens_nothing() -> None: + profile = catalog(row()).get("org-a", "approved") + opened = client(profile) + assert isinstance(opened, MCPSourceClient) + assert opened.config.limits == MCPLimits() + assert opened.config.approved_resource_ids == () + assert opened.config.read is None + assert opened.credential is None + assert opened.validate_access is access_check + + +def test_mapped_tool_profile_keeps_public_defaults_and_fixed_scope() -> None: + mapping = tool_mapping() + profile = catalog( + row( + config={ + "endpoint": ENDPOINT, + "approved_tools": ["read_document"], + "read": mapping, + } + ) + ).get("org-a", "approved") + opened = client(profile, contract=selection(profile)) + actual = opened.config.read + assert actual is not None + defaults = MCPToolMapping("read_document", {}, {}, "document_id") + assert (actual.items_path, actual.id_path, actual.title_path, actual.revision_path) == ( + defaults.items_path, + defaults.id_path, + defaults.title_path, + defaults.revision_path, + ) + assert actual.fixed_arguments == {"scope": "operator-scope"} + assert opened.config.approved_resource_ids == ("doc://selected",) + + +def test_bearer_comes_only_from_decoded_envelope() -> None: + profile = catalog( + row( + auth="bearer", + config={ + "endpoint": ENDPOINT, + "bearer_audience": AUDIENCE, + }, + ) + ).get("org-a", "approved") + sealed = envelope(profile, auth="bearer", audience=AUDIENCE, bearer="sealed-upstream-secret") + opened = client(profile, sealed) + assert opened.credential is not None + assert opened.credential.token == "sealed-upstream-secret" + assert opened.credential.audience == AUDIENCE + assert "secret" not in repr(opened) + + +@pytest.mark.parametrize( + "changes", + [ + {"org": "org-b"}, + {"owner": "owner-b"}, + {"slot": "mcp:" + "d" * 32}, + {"generation": "e" * 32 + "/0" + "f" * 31}, + {"profile_id": "other"}, + {"profile_sha256": "0" * 64}, + {"endpoint": ENDPOINT + "/other"}, + ], +) +def test_wrong_envelope_binding_refuses_before_client_construction( + changes: dict[str, Any], + monkeypatch: pytest.MonkeyPatch, +) -> None: + profile = catalog(row()).get("org-a", "approved") + sealed = envelope(profile, **changes) + + def refuse(*args: Any, **kwargs: Any) -> Any: + pytest.fail("bad binding reached the client constructor") + + monkeypatch.setattr(mcp_profiles, "MCPSourceClient", refuse) + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + client(profile, sealed) + + +def test_full_audience_and_auth_mode_match_exactly() -> None: + bearer = catalog( + row( + auth="bearer", + config={ + "endpoint": ENDPOINT, + "bearer_audience": AUDIENCE, + }, + ) + ).get("org-a", "approved") + for sealed in ( + envelope(bearer), + envelope(bearer, auth="bearer", audience=AUDIENCE + "/other", bearer="sealed-secret"), + ): + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + client(bearer, sealed) + anonymous = catalog(row()).get("org-a", "approved") + with pytest.raises(MCPProfileError): + client(anonymous, envelope(anonymous, auth="bearer", audience=AUDIENCE, bearer="secret")) + + +@pytest.mark.parametrize( + "changes", + [ + {"slot": "mcp:" + "d" * 32}, + {"generation": "e" * 32 + "/0" + "f" * 31}, + {"profile_id": "other"}, + {"profile_sha256": "0" * 64}, + ], +) +def test_contract_must_match_current_binding(changes: dict[str, Any]) -> None: + profile = catalog(row()).get("org-a", "approved") + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + client(profile, contract=selection(profile, **changes)) + + +def test_decoded_models_and_callback_are_required() -> None: + profile = catalog(row()).get("org-a", "approved") + for args in ( + {"contract": selection(profile).model_dump()}, + {"validate_access": None}, + ): + with pytest.raises(MCPProfileError): + client(profile, **args) + with pytest.raises(MCPProfileError): + client(profile, envelope(profile).model_dump()) # type: ignore[arg-type] + with pytest.raises(MCPProfileError): + client(row(), envelope(profile)) + + +def test_tampered_models_are_revalidated() -> None: + profile = catalog(row()).get("org-a", "approved") + bad_envelope = envelope(profile).model_copy(update={"bearer": "secret"}) + bad_selection = selection(profile).model_copy(update={"resources": ({"id": "injected"},)}) + for sealed, contract in ((bad_envelope, None), (envelope(profile), bad_selection)): + with pytest.raises(MCPProfileError): + client(profile, sealed, contract=contract) + + +def test_real_constructor_checks_schema_semantics_only_when_building() -> None: + mapping = tool_mapping() + mapping["input_schema"]["$ref"] = "https://unapproved.example/schema" + profiles = catalog( + row( + config={ + "endpoint": ENDPOINT, + "approved_tools": ["read_document"], + "read": mapping, + } + ) + ) + assert profiles.page("org-a").items[0].id == "approved" + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + client(profiles.get("org-a", "approved")) + + +def test_offline_catalog_does_not_instantiate_clients(monkeypatch: pytest.MonkeyPatch) -> None: + def refuse(*args: Any, **kwargs: Any) -> Any: + pytest.fail("catalog parsing or paging constructed a client") + + monkeypatch.setattr(mcp_profiles, "MCPSourceClient", refuse) + profiles = catalog(row(config={"endpoint": "https://offline.invalid/mcp"})) + assert profiles.page("org-a").items[0].id == "approved" + + +def test_snapshots_and_selected_scope_are_detached_between_users() -> None: + raw = row( + allowed_orgs=["org-a", "org-b"], + config={ + "endpoint": ENDPOINT, + "approved_tools": ["read_document"], + "read": tool_mapping(), + }, + ) + profile = catalog(raw).get("org-a", "approved") + digest = profile.metadata.profile_sha256 + first = client(profile, contract=selection(profile)) + second_contract = selection(profile, resources=({"type": "resource", "id": "doc://other"},)) + second = client( + profile, + envelope(profile, org="org-b", owner="owner-b"), + org="org-b", + owner="owner-b", + contract=second_contract, + ) + raw["config"]["read"]["fixed_arguments"]["scope"] = "injected" + detached = first.config + assert detached.read is not None + detached.read.fixed_arguments["scope"] = "injected" + assert first.config.approved_resource_ids == ("doc://selected",) + assert second.config.approved_resource_ids == ("doc://other",) + for opened in (first, second, client(profile)): + actual = opened.config.read + assert actual is not None and actual.fixed_arguments == {"scope": "operator-scope"} + assert profile.metadata.profile_sha256 == digest + with pytest.raises(FrozenInstanceError): + profile.metadata.label = "changed" # type: ignore[misc] + + +def test_digest_is_canonical_and_changes_with_approval() -> None: + original = row() + reordered = dict(reversed(list(original.items()))) + assert catalog(original).sha256 == catalog(reordered).sha256 + changed = copy.deepcopy(original) + changed["allow_collection_copy"] = True + assert catalog(original).sha256 != catalog(changed).sha256 + assert catalog(original, row("second")).sha256 == catalog(row("second"), original).sha256 + + +def test_collection_copy_policy_is_separate_from_publication_grants() -> None: + denied = catalog(row()).get("org-a", "approved") + with pytest.raises(MCPProfileError): + client(denied, contract=selection(denied, reader_policy="collection_copy")) + approved = catalog(row(allow_collection_copy=True)).get("org-a", "approved") + opened = client(approved, contract=selection(approved, reader_policy="collection_copy")) + assert opened.validate_access is access_check + assert opened.config.approved_resource_ids == ("doc://selected",) + with pytest.raises(MCPProfileError): + client(approved, org="denied-org") + + +@pytest.mark.parametrize( + "changes", + [ + {"org": "org-b"}, + {"owner": "owner-b"}, + {"slot": "mcp:" + "d" * 32}, + {"generation": "e" * 32 + "/0" + "f" * 31}, + ], +) +def test_authenticated_expected_tuple_is_not_inferred_from_envelope( + changes: dict[str, Any], +) -> None: + profile = catalog(row(allowed_orgs=["org-a", "org-b"])).get("org-a", "approved") + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + client(profile, **changes) + + +@pytest.mark.parametrize( + "change", + [ + {"unknown": "secret"}, + {"input_schema": []}, + {"output_schema": None}, + {"fixed_arguments": []}, + {"items_path": None}, + {"id_path": "id"}, + {"text_path": ["x"] * 9}, + {"cursor_argument": 1}, + {"name": "secret\n"}, + ], +) +def test_mapping_shapes_reject_without_copying_schema_semantics(change: dict[str, Any]) -> None: + mapping = {**tool_mapping(), **change} + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + catalog(row(config={"endpoint": ENDPOINT, "read": mapping})) + + +def test_profile_digest_covers_the_detached_canonical_snapshot() -> None: + profile = catalog(row()).get("org-a", "approved") + snapshot = json.loads(profile.config_snapshot) + assert ( + profile.metadata.profile_sha256 + == hashlib.sha256(profile.config_snapshot.encode()).hexdigest() + ) + assert snapshot["allow_collection_copy"] is False + assert "approved_resource_ids" not in snapshot["config"] + assert snapshot["config"]["limits"]["max_pages"] == MCPLimits().max_pages + snapshot["config"]["endpoint"] = "https://injected.example/mcp" + assert client(profile).config.endpoint == ENDPOINT + + +def test_both_approved_tool_mappings_use_the_common_client() -> None: + read = tool_mapping() + search = {**tool_mapping(), "name": "find_documents", "argument_name": "query"} + search["input_schema"] = { + "type": "object", + "properties": { + "query": {"type": "string", "maxLength": 128}, + "scope": {"type": "string", "maxLength": 128}, + }, + "required": ["query", "scope"], + "additionalProperties": False, + } + profile = catalog( + row( + config={ + "endpoint": ENDPOINT, + "approved_tools": ["read_document", "find_documents"], + "read": read, + "search": search, + "limits": {"max_results": 2}, + } + ) + ).get("org-a", "approved") + opened = client(profile) + assert opened.config.search is not None and opened.config.read is not None + assert opened.config.search.name == "find_documents" + assert opened.config.read.name == "read_document" + assert opened.config.limits.max_results == 2 + + +def test_oversized_selection_refuses_through_real_client_limits() -> None: + profile = catalog(row(config={"endpoint": ENDPOINT, "limits": {"max_results": 1}})).get( + "org-a", "approved" + ) + two = selection( + profile, + resources=( + {"type": "resource", "id": "doc://first"}, + {"type": "resource", "id": "doc://second"}, + ), + ) + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + client(profile, contract=two) From 9aae4db745663a9709d0073fe89daeddfa30583d Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 01:57:03 +0000 Subject: [PATCH 11/30] Keep restore recovery within the admitted registration limit Signed-off-by: zlareb1 --- .github/workflows/mcp-source-lifecycle.yml | 1 + docs/architecture/mcp-source-lifecycle.md | 15 ++ scripts/gates/mcp_source_lifecycle.py | 149 +++++++++++++------- server/knowledge/app/connected_restore.py | 13 +- tests/unit/test_mcp_connection_lifecycle.py | 100 +++++++++++++ 5 files changed, 223 insertions(+), 55 deletions(-) diff --git a/.github/workflows/mcp-source-lifecycle.yml b/.github/workflows/mcp-source-lifecycle.yml index e053e2e84e..c0b27a16d7 100644 --- a/.github/workflows/mcp-source-lifecycle.yml +++ b/.github/workflows/mcp-source-lifecycle.yml @@ -81,6 +81,7 @@ jobs: LOOM_BOOT_MIGRATE: "true" LOOM_ENV_FILE: "" LOOM_MCP_SOURCE_LIFECYCLE_FIXTURE: offline-isolated + LOOM_KNOWLEDGE_CONNECTED_REGISTRY_SCAN_LIMIT: "8" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: diff --git a/docs/architecture/mcp-source-lifecycle.md b/docs/architecture/mcp-source-lifecycle.md index f2253acdf1..98268ec948 100644 --- a/docs/architecture/mcp-source-lifecycle.md +++ b/docs/architecture/mcp-source-lifecycle.md @@ -73,6 +73,21 @@ preserved. This scoped deletion path shares per-owner lifecycle primitives with restore; it never invokes deployment-wide offline restore. Remote revocation follows all local cleanup. + +The credential-free recovery marker retains an already inventoried registration +generation: the current account's registration, or an exact-owner historical +registration when no account survives. It stays inactive and contains no credential, +remote identity, scope or refresh state. Every family fence is stopped. Retaining +that registration keeps interruption recovery within the same bounded raw-history +workset, even when it already fills the configured generation limit. + +The erasure call receives a separate in-memory object carrying the actual stopped +fence value from the marker registration's own prefix. The strict erasure guard +still requires equality with that durable claim. The stored registration identifies +recovery work; it grants no checkout authority. Retirement and all raw-history +censuses must finish before the recovery row disappears. Retrying neither adds a +registration nor skips a historical generation or its prefix validation. + Disconnect and explicit erasure retain their existing meanings. Local bearer removal does not prove remote token revocation. Restore is destructive offline lifecycle work with fencing and a final census; it is not a reconfiguration or upgrade tool. diff --git a/scripts/gates/mcp_source_lifecycle.py b/scripts/gates/mcp_source_lifecycle.py index ceb003dc26..96c9040083 100644 --- a/scripts/gates/mcp_source_lifecycle.py +++ b/scripts/gates/mcp_source_lifecycle.py @@ -17,6 +17,7 @@ from uuid import uuid4 _LIMIT = 512 +_GENERATION_LIMIT = 8 _FIXTURE_KEY = "ci-only-mcp-lifecycle-fixture" _ROTATED_KEY = "ci-only-mcp-lifecycle-rotated-fixture" _PROFILE_ID = "offline-lifecycle-profile" @@ -53,6 +54,7 @@ def fixture_guard(opt_in: bool, result: Path) -> str: "LOOM_EMBEDDING_MODEL": "fake-ngram-1024", "LOOM_BACKGROUND_WORKERS": "off", "LOOM_BOOT_MIGRATE": "true", + "LOOM_KNOWLEDGE_CONNECTED_REGISTRY_SCAN_LIMIT": str(_GENERATION_LIMIT), } require(opt_in and all(os.environ.get(k) == v for k, v in expected.items())) authority = os.environ.get("LOOM_STORAGE_AUTHORITY", "") @@ -326,20 +328,33 @@ async def retirement_pending(self, ch: Any, source: dict[str, Any]) -> None: } ) - async def boundary(self, ch: Any, ended: Any) -> None: + async def boundary_marker(self, ch: Any, ended: Any) -> None: from server.auth import claims from server.knowledge.app import connected_accounts as accounts from server.knowledge.store import connected_accounts as account_store - from server.knowledge.store import sources require((ended.org, ended.subject, ended.kind) == self.target) marker = await account_store.get(*self.target) + original = next(a for a in self.accounts if (a.org, a.subject, a.kind) == self.target) require(marker is not None and not marker.active and not marker.credential_enc) require((marker.org, marker.subject, marker.kind) == self.target) - require(marker.connection_id == ended.connection_id and marker.connected_at is None) + require(marker.connection_id == original.connection_id and marker.connected_at is None) require(marker.disconnected_at is not None) require(not marker.account_id and not marker.workspace_id and not marker.account_email_enc) require(not marker.scopes and not marker.refresh_id) + key = accounts._fence_key(marker.connection_id) + require(key == accounts._fence_key(ended.connection_id)) + require(await claims.get(ch, key) == ended.connection_id) + require(ended.connection_id.partition("/")[2].startswith("0")) + require(not ended.active and not ended.credential_enc and not ended.account_email_enc) + require(not await accounts._fence_current(marker, ch=ch)) + + async def boundary(self, ch: Any, ended: Any) -> None: + from server.auth import claims + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.store import sources + + await self.boundary_marker(ch, ended) for generation, owner in self.connections.items(): observed = await claims.get(ch, accounts._fence_key(generation)) require(observed is not None) @@ -380,6 +395,16 @@ async def boundary(self, ch: Any, ended: Any) -> None: await self.retirement_pending(ch, row) +async def registration_workset(ch: Any) -> set[tuple[str, str, str, str]]: + from collections import defaultdict + + from server.knowledge.app import connected_restore as restore + + rows, _sources = await restore._metadata(ch) + restore._include(defaultdict(set), {}, rows) + return set(rows) + + async def current_accounts(ch: Any, fixture: Fixture) -> dict[tuple[str, str, str], Any]: from server.knowledge.store import connected_accounts as account_store @@ -545,6 +570,66 @@ async def complete_restore(ch: Any, fixture: Fixture, stopped_at_boundary: dict[ require(await count(ch, "code_index_state") == len(fixture.sources)) +async def run_restore_phases( + ch: Any, + fixture: Fixture, + before: dict[str, Any], + initial_workset: set[tuple[str, str, str, str]], + result: dict[str, Any], +) -> None: + from server.erasure.app.connected_accounts import require_restore_erased + from server.knowledge.app import connected_accounts as accounts + from server.knowledge.app import connected_restore as restore + from server.settings import settings + + client_attempts: list[None] = [] + + def refuse_native_client(*args: Any, **kwargs: Any) -> Any: + # Fail-only sentinel: no client or provider result can be supplied by this seam. + client_attempts.append(None) + raise AssertionError("MCP_LIFECYCLE_NATIVE_CLIENT_FORBIDDEN") + + with patch.object(accounts, "client", new=refuse_native_client): + result["stage"] = "dry_run" + await restore.restore_all(apply=False, ch=ch) + require(await snapshot(ch) == before) + require(not client_attempts) + result["checks"].append("dry_run_unchanged") + + result["stage"] = "reseal_forward" + await reseal_rotation(ch, fixture, _ROTATED_KEY, _FIXTURE_KEY, client_attempts) + result["checks"].append("reseal_forward_one_candidate_four_unreadable") + result["stage"] = "reseal_back" + await reseal_rotation(ch, fixture, _FIXTURE_KEY, _ROTATED_KEY, client_attempts) + require(str(settings.jwt_secret) == _FIXTURE_KEY and not settings.jwt_secret_previous) + result["checks"].append("reseal_back_one_candidate_four_unreadable") + + result["stage"] = "interruption" + stopped_at_boundary = await interrupt_restore(ch, fixture, before) + interrupted_workset = await registration_workset(ch) + require(interrupted_workset == initial_workset) + result["counts"]["interrupted_registration_workset"] = len(interrupted_workset) + require(not client_attempts) + result["checks"].append("real_retirement_before_injected_erase_failure") + + result["stage"] = "retry" + await complete_restore(ch, fixture, stopped_at_boundary) + require(not client_attempts) + result["checks"].append("retry_erases_all_raw_bindings_and_keeps_retirements") + result["counts"]["final_global_residue"] = 0 + result["counts"]["pending_retirements"] = len(fixture.sources) + + result["stage"] = "idempotent_rerun" + after = await snapshot(ch) + await restore.restore_all(apply=True, ch=ch) + require(await snapshot(ch) == after) + await require_restore_erased(ch=ch) + await owned_stores(ch, fixture.orgs) + require(not client_attempts) + result["checks"].append("completed_restore_rerun_unchanged") + result["counts"]["native_client_attempts"] = len(client_attempts) + + async def qualify(result: dict[str, Any]) -> None: from server import boot from server.cli._ch import connect_verified, disconnect @@ -552,13 +637,12 @@ async def qualify(result: dict[str, Any]) -> None: from server.core.errors import OverloadedError from server.erasure.app.connected_accounts import require_restore_erased from server.erasure.store.census import connected_restore_residue - from server.knowledge.app import connected_accounts as accounts - from server.knowledge.app import connected_restore as restore from server.settings import settings require(settings.llm_provider == "fake" and settings.embedding_model == "fake-ngram-1024") require(settings.storage_authority == result["config"]["authority"]) require(not settings.auth_actually_required()) + require(settings.knowledge_connected_registry_scan_limit == _GENERATION_LIMIT) require(str(settings.jwt_secret) == _FIXTURE_KEY and not settings.jwt_secret_previous) ch = get_client() await ch.connect() @@ -588,55 +672,17 @@ async def qualify(result: dict[str, Any]) -> None: else: require(False) before = await snapshot(ch) + initial_workset = await registration_workset(ch) + require(initial_workset == {(*owner, g) for g, owner in fixture.connections.items()}) + require(len(initial_workset) == _GENERATION_LIMIT) result["counts"] = { "accounts": len(fixture.accounts), "sources": len(fixture.sources), "generations": len(fixture.connections), "mirrors": len(fixture.mirrors), + "initial_registration_workset": len(initial_workset), } - client_attempts: list[None] = [] - - def refuse_native_client(*args: Any, **kwargs: Any) -> Any: - # Fail-only sentinel: no client or provider result can be supplied by this seam. - client_attempts.append(None) - raise AssertionError("MCP_LIFECYCLE_NATIVE_CLIENT_FORBIDDEN") - - with patch.object(accounts, "client", new=refuse_native_client): - result["stage"] = "dry_run" - await restore.restore_all(apply=False, ch=ch) - require(await snapshot(ch) == before) - require(not client_attempts) - result["checks"].append("dry_run_unchanged") - - result["stage"] = "reseal_forward" - await reseal_rotation(ch, fixture, _ROTATED_KEY, _FIXTURE_KEY, client_attempts) - result["checks"].append("reseal_forward_one_candidate_four_unreadable") - result["stage"] = "reseal_back" - await reseal_rotation(ch, fixture, _FIXTURE_KEY, _ROTATED_KEY, client_attempts) - require(str(settings.jwt_secret) == _FIXTURE_KEY and not settings.jwt_secret_previous) - result["checks"].append("reseal_back_one_candidate_four_unreadable") - - result["stage"] = "interruption" - stopped_at_boundary = await interrupt_restore(ch, fixture, before) - require(not client_attempts) - result["checks"].append("real_retirement_before_injected_erase_failure") - - result["stage"] = "retry" - await complete_restore(ch, fixture, stopped_at_boundary) - require(not client_attempts) - result["checks"].append("retry_erases_all_raw_bindings_and_keeps_retirements") - result["counts"]["final_global_residue"] = 0 - result["counts"]["pending_retirements"] = len(fixture.sources) - - result["stage"] = "idempotent_rerun" - after = await snapshot(ch) - await restore.restore_all(apply=True, ch=ch) - require(await snapshot(ch) == after) - await require_restore_erased(ch=ch) - await owned_stores(ch, fixture.orgs) - require(not client_attempts) - result["checks"].append("completed_restore_rerun_unchanged") - result["counts"]["native_client_attempts"] = len(client_attempts) + await run_restore_phases(ch, fixture, before, initial_workset, result) result["stage"] = "complete" result["status"] = "passed" finally: @@ -673,7 +719,12 @@ def main() -> int: except Exception: # noqa: BLE001 — an unverified target must not open any store print("MCP lifecycle fixture guard refused", file=sys.stderr) return 2 - result["config"] = {"authority": authority, "models": "fake", "workers": "off"} + result["config"] = { + "authority": authority, + "models": "fake", + "workers": "off", + "generation_limit": _GENERATION_LIMIT, + } try: asyncio.run(asyncio.wait_for(qualify(result), timeout=300)) except Exception as error: # noqa: BLE001 — emit no payload, SQL exception or credential in CI diff --git a/server/knowledge/app/connected_restore.py b/server/knowledge/app/connected_restore.py index d7baab97c2..7ce78dd72d 100644 --- a/server/knowledge/app/connected_restore.py +++ b/server/knowledge/app/connected_restore.py @@ -170,7 +170,7 @@ async def _restore_owner( if current is not None: keys.append((current.org, current.subject, current.kind, current.connection_id)) _include(groups, prefixes, keys) - if not groups[owner]: + if not keys: return None stopped: dict[str, str] = {} for connection in sorted(groups[owner]): @@ -183,12 +183,13 @@ async def _restore_owner( credential = unseal(CREDENTIAL_PURPOSE, current.credential_enc, warn=False) or "" except Exception: # noqa: BLE001 — local deletion never depends on recovering a remote secret pass - ended = ConnectedAccount( - *owner, next(iter(stopped.values())), disconnected_at=datetime.now(UTC) + registration = current.connection_id if current is not None else min(row[3] for row in keys) + marker = ConnectedAccount(*owner, registration, disconnected_at=datetime.now(UTC)) + # Retain an inventoried registration so recovery cannot expand its admitted workset. + await account_store.put(marker, ch=ch) + ended = dataclasses.replace( + marker, connection_id=stopped[accounts._fence_key(registration)] ) - # Preserve a credential-free recovery marker until every historical source - # id has durable retirement work and both raw-history censuses are empty. - await account_store.put(ended, ch=ch) await _retire_history(sources, ch) await accounts._erase_locked(ended, keep_marker=False) return (current, credential) if current is not None else None diff --git a/tests/unit/test_mcp_connection_lifecycle.py b/tests/unit/test_mcp_connection_lifecycle.py index e8507754c6..9fcf4b0450 100644 --- a/tests/unit/test_mcp_connection_lifecycle.py +++ b/tests/unit/test_mcp_connection_lifecycle.py @@ -722,3 +722,103 @@ async def query(sql: str, *, params: dict[str, Any]) -> list[dict[str, Any]]: assert keys == [(OWNER[0], OWNER[1], SLOT if generic else "gdrive", CONNECTION)] assert len(sources) == 1 and sources[0].source_id == str(source_id) assert isinstance(sources[0].source_id, str) + + +def _retry_budget_store( + monkeypatch: pytest.MonkeyPatch, state: SimpleNamespace, owner: tuple[str, str, str] +) -> None: + async def keys(*, owner: Any = None, **kwargs: Any) -> list[Any]: + assert owner == state.owner + if len(state.registrations) > restore.settings.knowledge_connected_registry_scan_limit: + raise RuntimeError("connected_restore_inventory_bound") + return [(*owner, generation) for generation in sorted(state.registrations)] + + async def put(account: Any, **kwargs: Any) -> None: + assert state.held == [owner] and not account.active and not account.credential_enc + state.rows[owner] = account + state.registrations.add(account.connection_id) + state.markers.append(account) + state.events.append(("marker", owner)) + + real_erase = restore.accounts._erase_locked + + async def erase(account: Any, *, keep_marker: bool) -> None: + key = restore.accounts._fence_key(account.connection_id) + assert state.fences[key] == account.connection_id + assert account.connection_id.partition("/")[2].startswith("0") + assert not account.active and not account.credential_enc and not account.account_email_enc + assert ("retire", owner) in state.events + state.proofs.append(account) + if len(state.proofs) == 1: + raise _MarkerWritten + await real_erase(account, keep_marker=keep_marker) + state.registrations.clear() + + monkeypatch.setattr(restore.account_store, "restore_keys", keys) + monkeypatch.setattr(restore.account_store, "put", put) + monkeypatch.setattr(restore.accounts, "_erase_locked", erase) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("limit,separate_prefixes", [(1, False), (2, False), (2, True)]) +@pytest.mark.parametrize("account_backed", [False, True]) +@pytest.mark.parametrize("generic", [False, True]) +async def test_retry_budget_retains_admitted_registration_workset( + owner_history: SimpleNamespace, + monkeypatch: pytest.MonkeyPatch, + limit: int, + separate_prefixes: bool, + account_backed: bool, + generic: bool, +) -> None: + state = owner_history + owner = OWNER if generic else (*OWNER[:2], "gdrive") + sources = [_owner_source(owner, "a")] + if limit == 2: + generation = ("b" if separate_prefixes else "a") * 32 + "/1" + "e" * 31 + sources.append(replace(sources[0], connection_id=generation)) + if not generic: + sources = [ + replace(s, kind="gdrive", credential_mode="connected", connection_slot="") + for s in sources + ] + state.history = {owner: sources} + registration = sources[-1 if account_backed else 0].connection_id + if account_backed: + state.rows[owner] = restore.ConnectedAccount(*owner, registration, active=True) + state.owner, state.markers, state.proofs = owner, [], [] + state.registrations = {registration} if account_backed else set() + original = {s.connection_id for s in sources} | state.registrations + assert len(original) == limit + monkeypatch.setattr(restore.settings, "knowledge_connected_registry_scan_limit", limit) + _retry_budget_store(monkeypatch, state, owner) + with pytest.raises(_MarkerWritten): + await restore.accounts.stop_subjects([owner[1]], erase_owner=True, revoke=False) + stopped = dict(state.fences) + keys, _sources = await restore._metadata(state, owner) + restore._include(defaultdict(set), {}, keys) + assert {row[3] for row in keys} == original + await restore.accounts.stop_subjects([owner[1]], erase_owner=True, revoke=False) + assert not state.history and not state.rows and not state.registrations + assert state.fences == stopped and len(state.proofs) == 2 + for marker, proof in zip(state.markers, state.proofs, strict=True): + assert (marker.org, marker.subject, marker.kind) == owner + assert marker.connection_id == registration and marker.connected_at is None + assert marker.disconnected_at is not None and not marker.active + assert not any( + ( + marker.credential_enc, + marker.account_email_enc, + marker.account_id, + marker.workspace_id, + marker.scopes, + marker.refresh_id, + ) + ) + assert restore.accounts._fence_key(marker.connection_id) == restore.accounts._fence_key( + proof.connection_id + ) + assert ( + state.fences[restore.accounts._fence_key(marker.connection_id)] == proof.connection_id + ) + assert not await restore.accounts.available(marker) From 0b6e5115dfe7269066b2f40260d6497f5f11186b Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 01:57:12 +0000 Subject: [PATCH 12/30] Admit bounded standard MCP schemas and explicit result formats Signed-off-by: zlareb1 --- docs/architecture/mcp-source-client.md | 63 +++- server/clients/mcp_source.py | 351 ++++++++++++----- server/knowledge/app/mcp_profiles.py | 26 +- tests/unit/test_mcp_source_interop.py | 500 +++++++++++++++++++++++++ 4 files changed, 838 insertions(+), 102 deletions(-) create mode 100644 tests/unit/test_mcp_source_interop.py diff --git a/docs/architecture/mcp-source-client.md b/docs/architecture/mcp-source-client.md index ff25e330fc..a28ac56e41 100644 --- a/docs/architecture/mcp-source-client.md +++ b/docs/architecture/mcp-source-client.md @@ -59,17 +59,66 @@ Returned resource links are evidence, never instructions to fetch an arbitrary U Listing and search do not expand the explicitly approved resource identities. An empty selection grants no read authority. -The qualified content profile is text resources and mapped structured tool output. Binary -resource blobs and tools that return only unstructured text are unsupported. Approved -tool schemas use a bounded subset with closed objects, bounded arrays and strings, -and no references, regular expressions or combinatorial validators. -Keywords must belong to the schema's declared type. External schema retrieval is -disabled independently of configuration validation. +Text resources and explicitly mapped tool results use the same evidence engine. Binary +resource blobs and binary tool content remain unsupported. A mapping declares +`result_format`; content, descriptions and tool hints never select a format: + +| Format | Result contract | +| --- | --- | +| `structured` (default) | Validate `structuredContent` against the configured object schema. Text alone is refused. | +| `json_text` | Require exactly one text block and no structured content. Parse strict JSON, then validate the configured object schema and apply its exact selectors. Duplicate keys, nonfinite numbers, prose and malformed JSON are refused. | +| `text` | Read only: require exactly one text block and no structured content, validated against a string schema. Bind the body to the selected request identity; custom structured selectors and cursors are refused. | + +Search always needs a validated structured row projection, including when its carrier is +JSON text. No model parses a result and no format falls back to another format. Numeric +resource identities are unsupported; identities and cursor values remain bounded strings. + +`require_output_schema` defaults to true: discovery admits and compares the advertised +output schema exactly with the configured result contract. With false, the server must +omit `outputSchema`; the operator's configured schema validates every result. Appearance +or disappearance of that advertised schema is drift. Input schema admission and exact +comparison apply in both cases. Defaults in schemas never fill fixed arguments or grant +scope. The public SDK session request API performs the tool RPC; independent result bounds +run before the client's schema validator, without invoking duplicate SDK output validation. + +### Schema subset and work bounds + +Schemas may describe typed objects, homogeneous arrays, primitive values and nullable +optionals. Object `additionalProperties` may be omitted, boolean or a supported schema. +String and array length keywords are optional. `enum`, `const`, numeric bounds and bounded +`title`, `description`, `default` and `examples` data are supported. Descriptions may contain +newlines; endpoint, identity, tool, selector and fixed policy strings may not. + +Root `$defs` and acyclic `#/$defs/name` references are supported. Definition names cannot +contain pointer escapes, slashes, fragments or percent escapes. A nullable `anyOf` contains +exactly one null schema and one supported alternative; a two-element `type` array may +likewise pair one type with null. Empty schemas permit bounded data. Mapping roots still +declare an object type, or a string type for plain text. + +Admission rejects external or dynamic references, cycles, nested definitions, schema +resource identifiers, regex keywords, format validators and other combinators. Keywords +must apply to their declared type, so an inapplicable keyword cannot hide a reference. +Schemas are limited to 16,384 serialized bytes, 64 definitions, 64 properties per typed +object, depth 16 and 256 expanded schema visits. Every definition is checked even if unused; +shared-reference fanout consumes the expanded budget. Runtime validation uses the public +JSON Schema validator and an empty public reference registry: no URI can trigger remote +schema retrieval even if admission is bypassed. + +Instances have independent limits before validation: 4,096 data nodes (including object +keys), depth 16, 256 object members, 1,000 array items, 1,000,000 UTF-8 bytes per string and +4,096 bits per integer, plus the configured serialized payload byte limit. Protocol results +and extracted values are both bounded. Together with the finite expanded schema traversal +and nullable-only branching, these limits bound validation work without requiring servers +to advertise restrictive length keywords. This subset does not claim general JSON Schema +compatibility. Each read produces normalized evidence: resource identity, citation URI, title, media type, content and any supplied revision. A read receipt binds the requested identity, configured operation and returned body; listing metadata and search snippets have no -successful resource-read receipt. Identity is scoped by the source connection; +successful resource-read receipt. `identity_verified` is false for plain-text tool reads: +that receipt binds the approved request and body but verifies no separately echoed identity. +Other reads verify the returned identity and set it true. Neither value establishes reader +permissions. Identity is scoped by the source connection; the same upstream identifier on another connection denotes separate evidence. A caller that persists a document must retain the connection and resource identity with its provenance. A citation address alone does not establish tenant or reader authority. diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 0135aee475..69a0ffb620 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -160,6 +160,8 @@ class MCPToolMapping: revision_path: tuple[str, ...] | None = None cursor_argument: str | None = None next_cursor_path: tuple[str, ...] | None = None + result_format: Literal["structured", "json_text", "text"] = "structured" + require_output_schema: bool = True @dataclass(frozen=True, repr=False) @@ -190,6 +192,7 @@ class MCPReadReceipt: requested_id: str content_sha256: str config_sha256: str + identity_verified: bool = True @dataclass(frozen=True, repr=False) @@ -254,53 +257,138 @@ def _origin(url: str) -> tuple[str, str, int]: return endpoint.scheme, endpoint.raw_host.decode("ascii"), endpoint.port or 443 -# This subset has no references, regular expressions or combinatorial validators. -_SCHEMA_KEYS = frozenset({"type", "enum", "const", "title", "description"}) +# Instance limits do not depend on a server supplying restrictive schema keywords. +_MAX_DATA_NODES = 4096 +_MAX_DATA_DEPTH = 16 +_MAX_DATA_ITEMS = 1000 +_MAX_DATA_STRING_BYTES = 1_000_000 +_SCHEMA_ANNOTATIONS = frozenset({"title", "description", "default", "examples"}) +_SCHEMA_KEYS = _SCHEMA_ANNOTATIONS | {"enum", "const"} _SCHEMA_TYPE_KEYS = { - "object": {"properties", "required", "additionalProperties"}, + "object": {"properties", "required", "additionalProperties", "minProperties", "maxProperties"}, "array": {"items", "maxItems", "minItems"}, "string": {"maxLength", "minLength"}, - "integer": {"minimum", "maximum"}, - "number": {"minimum", "maximum"}, + "integer": {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"}, + "number": {"minimum", "maximum", "exclusiveMinimum", "exclusiveMaximum"}, "boolean": set(), "null": set(), } +def _bounded_data(value: Any, maximum: int, *, policy: bool = False) -> None: + remaining = _MAX_DATA_NODES + pending = [(value, 0)] + while pending: + node, depth = pending.pop() + remaining -= 1 + if remaining < 0 or depth > _MAX_DATA_DEPTH: + raise MCPSourceError("limit") + if isinstance(node, dict): + if len(node) > 256 or any(not isinstance(key, str) for key in node): + raise MCPSourceError("limit") + pending.extend((item, depth + 1) for pair in node.items() for item in pair) + elif isinstance(node, list): + if len(node) > _MAX_DATA_ITEMS: + raise MCPSourceError("limit") + pending.extend((item, depth + 1) for item in node) + elif isinstance(node, str): + try: + if policy: + _string(node, min(maximum, _MAX_DATA_STRING_BYTES), empty=True) + if len(node.encode()) > min(maximum, _MAX_DATA_STRING_BYTES): + raise MCPSourceError("limit") + except UnicodeError: + raise MCPSourceError("schema") from None + elif type(node) is int: + if node.bit_length() > 4096: + raise MCPSourceError("limit") + elif node is not None and type(node) not in (bool, float): + raise MCPSourceError("schema") + _json(value, maximum) + + +def _schema_kind(node: dict[str, Any]) -> str | None: + kind = node.get("type") + if isinstance(kind, list): + if len(kind) != 2 or "null" not in kind: + raise MCPSourceError("schema") + non_null = [item for item in kind if item != "null"] + if len(non_null) != 1: + raise MCPSourceError("schema") + kind = non_null[0] + if kind is not None and (not isinstance(kind, str) or kind not in _SCHEMA_TYPE_KEYS): + raise MCPSourceError("schema") + return kind + + +def _schema_children(node: dict[str, Any], *, root: bool = False) -> list[Any]: + keys = set(node) - ({"$defs"} if root else set()) + if "enum" in node and (not isinstance(node["enum"], list) or len(node["enum"]) > 32): + raise MCPSourceError("schema") + if "$ref" in node: + if keys - (_SCHEMA_ANNOTATIONS | {"$ref"}): + raise MCPSourceError("schema") + return [] + if "anyOf" in node: + choices = node["anyOf"] + if ( + keys - (_SCHEMA_KEYS | {"anyOf"}) + or not isinstance(choices, list) + or len(choices) != 2 + or sum(choice == {"type": "null"} for choice in choices) != 1 + ): + raise MCPSourceError("schema") + return choices + kind = _schema_kind(node) + allowed = _SCHEMA_KEYS | ({"type"} | _SCHEMA_TYPE_KEYS[kind] if kind else set()) + if keys - allowed: + raise MCPSourceError("schema") + if kind == "object": + properties = node.get("properties", {}) + additional = node.get("additionalProperties", True) + if not isinstance(properties, dict) or len(properties) > 64: + raise MCPSourceError("schema") + for name in properties: + _string(name, 128) + if type(additional) is not bool and not isinstance(additional, dict): + raise MCPSourceError("schema") + return [*properties.values(), *([additional] if isinstance(additional, dict) else [])] + return [node["items"]] if kind == "array" and "items" in node else [] + + def _schema(schema: dict[str, Any]) -> None: - _json(schema, 16_384) + if not isinstance(schema, dict): + raise MCPSourceError("schema") + _bounded_data(schema, 16_384) + definitions = schema.get("$defs", {}) + if not isinstance(definitions, dict) or len(definitions) > 64: + raise MCPSourceError("schema") + for name in definitions: + _string(name, 128) + if any(char in name for char in "/~#%"): + raise MCPSourceError("schema") remaining = 256 - def visit(node: Any, depth: int) -> None: + def visit(node: Any, depth: int, active: tuple[str, ...] = (), *, root: bool = False) -> None: nonlocal remaining remaining -= 1 - if remaining < 0 or depth > 8 or not isinstance(node, dict): - raise MCPSourceError("schema") - kind = node.get("type") - if not isinstance(kind, str) or kind not in _SCHEMA_TYPE_KEYS: + if remaining < 0 or depth > 16 or not isinstance(node, dict): raise MCPSourceError("schema") - if set(node) - (_SCHEMA_KEYS | _SCHEMA_TYPE_KEYS[kind]): - raise MCPSourceError("schema") - if node["type"] == "object": - if node.get("additionalProperties") is not False: - raise MCPSourceError("schema") - properties = node.get("properties", {}) - if not isinstance(properties, dict) or len(properties) > 32: - raise MCPSourceError("schema") - for name, child in properties.items(): - _string(name, 128) - visit(child, depth + 1) - if node["type"] == "array": - if type(node.get("maxItems")) is not int or not 0 <= node["maxItems"] <= 1000: + children = _schema_children(node, root=root) + if "$ref" in node: + ref = node["$ref"] + if not isinstance(ref, str) or not ref.startswith("#/$defs/"): raise MCPSourceError("schema") - visit(node.get("items"), depth + 1) - if node["type"] == "string": - if type(node.get("maxLength")) is not int or not 0 <= node["maxLength"] <= 4_000_000: + name = ref[len("#/$defs/") :] + if name not in definitions or name in active: raise MCPSourceError("schema") - if "enum" in node and (not isinstance(node["enum"], list) or len(node["enum"]) > 32): - raise MCPSourceError("schema") + visit(definitions[name], depth + 1, (*active, name)) + for child in children: + visit(child, depth + 1, active) - visit(schema, 0) + for name, definition in definitions.items(): + visit(definition, 1, (name,)) + visit(schema, 0, root=True) try: Draft202012Validator.check_schema(schema) except (SchemaError, ValueError, TypeError, RecursionError): @@ -308,16 +396,128 @@ def visit(node: Any, depth: int) -> None: def _validate(schema: dict[str, Any], value: Any, maximum: int) -> None: - _json(value, maximum) + _bounded_data(value, maximum) try: # An explicit empty registry never retrieves external schema resources. valid = Draft202012Validator(schema, registry=Registry()).is_valid(value) - except Unresolvable: + except (Unresolvable, ValueError, TypeError, RecursionError): raise MCPSourceError("schema") from None if not valid: raise MCPSourceError("schema") +def validate_mcp_tool_mapping(mapping: MCPToolMapping, *, search: bool = False) -> None: + """Validate an operator contract without opening a session or granting authority.""" + _string(mapping.name, 128) + _string(mapping.argument_name, 128) + _schema(mapping.input_schema) + _schema(mapping.output_schema) + if ( + mapping.result_format not in ("structured", "json_text", "text") + or type(mapping.require_output_schema) is not bool + or mapping.input_schema.get("type") != "object" + or mapping.output_schema.get("type") + != ("string" if mapping.result_format == "text" else "object") + or (search and mapping.result_format == "text") + or (mapping.result_format == "text" and mapping.items_path) + ): + raise MCPSourceError("config") + if mapping.result_format == "text" and ( + (mapping.id_path, mapping.title_path, mapping.text_path, mapping.uri_path) + != (("id",), ("title",), ("text",), ("uri",)) + or mapping.revision_path is not None + or mapping.next_cursor_path is not None + or mapping.cursor_argument is not None + ): + raise MCPSourceError("config") + if not isinstance(mapping.fixed_arguments, dict): + raise MCPSourceError("config") + if mapping.cursor_argument is not None: + _string(mapping.cursor_argument, 128) + _bounded_data(mapping.fixed_arguments, 16_384, policy=True) + if mapping.argument_name in mapping.fixed_arguments or ( + mapping.cursor_argument is not None + and ( + mapping.cursor_argument == mapping.argument_name + or mapping.cursor_argument in mapping.fixed_arguments + ) + ): + raise MCPSourceError("config") + for path in ( + mapping.items_path, + mapping.id_path, + mapping.title_path, + mapping.text_path, + mapping.uri_path, + mapping.revision_path, + mapping.next_cursor_path, + ): + if path is not None: + if not isinstance(path, tuple) or len(path) > 8: + raise MCPSourceError("config") + for part in path: + _string(part, 128) + + +def _json_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + if len(pairs) > 256: + raise MCPSourceError("limit") + result = {} + for key, value in pairs: + if key in result: + raise MCPSourceError("schema") + result[key] = value + return result + + +def _nonfinite(value: str) -> None: + raise MCPSourceError("schema") + + +def _text_json(text: str, maximum: int) -> Any: + _bounded_data(text, maximum) + try: + return json.loads(text, object_pairs_hook=_json_pairs, parse_constant=_nonfinite) + except (ValueError, TypeError, RecursionError): + raise MCPSourceError("schema") from None + + +def _tool_value(result: types.CallToolResult, mapping: MCPToolMapping, limits: MCPLimits) -> Any: + if result.isError: + raise MCPSourceError("protocol") + _bounded_data(result.model_dump(mode="json"), limits.max_wire_bytes) + if any(not isinstance(block, types.TextContent) for block in result.content): + raise MCPSourceError("unsupported") + if mapping.result_format == "structured": + value: Any = result.structuredContent + if value is None: + raise MCPSourceError("protocol") + else: + if result.structuredContent is not None or len(result.content) != 1: + raise MCPSourceError("protocol") + block = result.content[0] + if not isinstance(block, types.TextContent): + raise MCPSourceError("unsupported") + value = ( + _text_json(block.text, limits.max_content_bytes) + if mapping.result_format == "json_text" + else block.text + ) + _validate(mapping.output_schema, value, limits.max_content_bytes) + return value + + +def _check_tool_schema(tool: types.Tool, mapping: MCPToolMapping) -> None: + _schema(tool.inputSchema) + if tool.inputSchema != mapping.input_schema: + raise MCPSourceError("schema") + if tool.outputSchema is not None: + _schema(tool.outputSchema) + expected = mapping.output_schema if mapping.require_output_schema else None + if tool.outputSchema != expected: + raise MCPSourceError("schema") + + _MISSING_CURSOR = object() @@ -522,42 +722,7 @@ def __init__( if set(config.approved_tools) != {m.name for m in mappings}: raise MCPSourceError("config") for mapping in mappings: - _string(mapping.name, 128) - _string(mapping.argument_name, 128) - _schema(mapping.input_schema) - _schema(mapping.output_schema) - if ( - mapping.input_schema["type"] != "object" - or mapping.output_schema["type"] != "object" - ): - raise MCPSourceError("config") - if not isinstance(mapping.fixed_arguments, dict): - raise MCPSourceError("config") - if mapping.cursor_argument is not None: - _string(mapping.cursor_argument, 128) - _json(mapping.fixed_arguments, 16_384) - if mapping.argument_name in mapping.fixed_arguments or ( - mapping.cursor_argument is not None - and ( - mapping.cursor_argument == mapping.argument_name - or mapping.cursor_argument in mapping.fixed_arguments - ) - ): - raise MCPSourceError("config") - for path in ( - mapping.items_path, - mapping.id_path, - mapping.title_path, - mapping.text_path, - mapping.uri_path, - mapping.revision_path, - mapping.next_cursor_path, - ): - if path is not None: - if not isinstance(path, tuple) or len(path) > 8: - raise MCPSourceError("config") - for part in path: - _string(part, 128) + validate_mcp_tool_mapping(mapping, search=mapping is self._config.search) self._privacy: ExitStack | None = None self._owner_task: asyncio.Task[None] | None = None self._ready: asyncio.Future[None] | None = None @@ -591,13 +756,18 @@ def config_sha256(self) -> str: return hashlib.sha256(_json(asdict(self._config), 131_072)).hexdigest() def _with_receipt( - self, evidence: MCPEvidence, operation: Literal["resources/read", "tools/call"] + self, + evidence: MCPEvidence, + operation: Literal["resources/read", "tools/call"], + *, + identity_verified: bool = True, ) -> MCPEvidence: receipt = MCPReadReceipt( operation, evidence.resource_id, hashlib.sha256(evidence.text.encode()).hexdigest(), self.config_sha256, + identity_verified, ) return replace(evidence, receipt=receipt) @@ -803,11 +973,7 @@ async def action(session: ClientSession) -> MCPDiscovery: continue for mapping in (self._config.search, self._config.read): if mapping is not None and mapping.name == tool.name: - if ( - tool.inputSchema != mapping.input_schema - or tool.outputSchema != mapping.output_schema - ): - raise MCPSourceError("schema") + _check_tool_schema(tool, mapping) found.add(tool.name) if len(seen) > self._config.limits.max_results: raise MCPSourceError("limit") @@ -886,15 +1052,18 @@ async def _tool( raise MCPSourceError("unsupported") arguments[mapping.cursor_argument] = cursor _validate(mapping.input_schema, arguments, 32_768) - result = await session.call_tool(mapping.name, arguments) + # Public SDK RPC path lets independent data bounds precede schema validation. + result = await session.send_request( + types.ClientRequest( + types.CallToolRequest( + params=types.CallToolRequestParams(name=mapping.name, arguments=arguments) + ) + ), + types.CallToolResult, + ) if self._schema_changed: raise MCPSourceError("schema") - if result.isError or result.structuredContent is None: - raise MCPSourceError("protocol") - _validate( - mapping.output_schema, result.structuredContent, self._config.limits.max_content_bytes - ) - return result.structuredContent + return _tool_value(result, mapping, self._config.limits) def _evidence(self, value: Any, mapping: MCPToolMapping) -> MCPEvidence: identity = _string(_path(value, mapping.id_path)) @@ -934,19 +1103,25 @@ async def action(session: ClientSession) -> MCPPage: return await self._run(action) + async def _read_tool(self, session: ClientSession, identity: str) -> MCPEvidence: + mapping = self._config.read + assert mapping is not None + result = await self._tool(session, mapping, identity) + if mapping.result_format == "text": + evidence = MCPEvidence(identity, identity, identity, result) + return self._with_receipt(evidence, "tools/call", identity_verified=False) + evidence = self._evidence(_path(result, mapping.items_path), mapping) + if evidence.resource_id != identity: + raise MCPSourceError("protocol") + return self._with_receipt(evidence, "tools/call") + async def read(self, resource_id: str) -> MCPEvidence: async def action(session: ClientSession) -> MCPEvidence: identity = _string(resource_id) if identity not in self._selected_ids: raise MCPSourceError("denied") if self._config.read is not None: - result = await self._tool(session, self._config.read, identity) - evidence = self._evidence( - _path(result, self._config.read.items_path), self._config.read - ) - if evidence.resource_id != identity: - raise MCPSourceError("protocol") - return self._with_receipt(evidence, "tools/call") + return await self._read_tool(session, identity) if self._discovery is None or not self._discovery.resources: raise MCPSourceError("unsupported") result = await session.read_resource(AnyUrl(identity)) diff --git a/server/knowledge/app/mcp_profiles.py b/server/knowledge/app/mcp_profiles.py index 4dd1e33162..ec0a50bea4 100644 --- a/server/knowledge/app/mcp_profiles.py +++ b/server/knowledge/app/mcp_profiles.py @@ -18,6 +18,7 @@ MCPSourceConfig, MCPSourceError, MCPToolMapping, + validate_mcp_tool_mapping, ) from server.knowledge.domain.mcp_sources import ( ConnectionEnvelope, @@ -84,7 +85,7 @@ def _nonfinite(value: str) -> None: def _bounded_tree(value: Any) -> None: remaining = MAX_PROFILE_NODES - def visit(node: Any, depth: int) -> None: + def visit(node: Any, depth: int, *, schema_data: bool = False) -> None: nonlocal remaining remaining -= 1 if remaining < 0 or depth > MAX_PROFILE_DEPTH: @@ -92,12 +93,21 @@ def visit(node: Any, depth: int) -> None: if isinstance(node, dict): for key, child in node.items(): _text(key, MAX_SCHEMA_BYTES, empty=True) - visit(child, depth + 1) + visit( + child, + depth + 1, + schema_data=schema_data + or (depth == 2 and key in {"input_schema", "output_schema"}), + ) elif isinstance(node, list): for child in node: - visit(child, depth + 1) + visit(child, depth + 1, schema_data=schema_data) elif isinstance(node, str): - _text(node, MAX_SCHEMA_BYTES, empty=True) + if schema_data: + if len(node.encode()) > MAX_SCHEMA_BYTES: + raise MCPProfileError() + else: + _text(node, MAX_SCHEMA_BYTES, empty=True) elif isinstance(node, float) and not math.isfinite(node): raise MCPProfileError() @@ -113,7 +123,7 @@ def _strings(value: Any, count: int, size: int) -> tuple[str, ...]: return result -def _mapping(value: Any) -> MCPToolMapping | None: +def _mapping(value: Any, *, search: bool = False) -> MCPToolMapping | None: if value is None: return None data = dict( @@ -147,7 +157,9 @@ def _mapping(value: Any) -> MCPToolMapping | None: if not isinstance(path, list) or len(path) > 8: raise MCPProfileError() data[name] = tuple(_text(part, 128) for part in path) - return MCPToolMapping(**data) + mapping = MCPToolMapping(**data) + validate_mcp_tool_mapping(mapping, search=search) + return mapping def _config(value: Any) -> MCPSourceConfig: @@ -164,7 +176,7 @@ def _config(value: Any) -> MCPSourceConfig: endpoint=_text(data["endpoint"], 2048), bearer_audience=audience, approved_tools=_strings(data.get("approved_tools", []), 2, 128), - search=_mapping(data.get("search")), + search=_mapping(data.get("search"), search=True), read=_mapping(data.get("read")), limits=MCPLimits(**limits), ) diff --git a/tests/unit/test_mcp_source_interop.py b/tests/unit/test_mcp_source_interop.py new file mode 100644 index 0000000000..10d3990bd8 --- /dev/null +++ b/tests/unit/test_mcp_source_interop.py @@ -0,0 +1,500 @@ +"""Ordinary SDK schemas and explicitly configured result formats over owned ASGI HTTP.""" + +from __future__ import annotations + +import copy +import hashlib +import json +from dataclasses import dataclass, field, replace +from typing import Any + +import pytest +from mcp.server.fastmcp import FastMCP +from mcp.server.fastmcp.tools.base import Tool +from mcp.server.transport_security import TransportSecuritySettings +from pydantic import BaseModel, Field + +from server.clients import mcp_source as mcp +from server.knowledge.app import mcp_profiles as profiles +from tests.unit.test_mcp_source_protocol import APPROVED, BEARER, ENDPOINT, EXTRA, _Fixture, _source + +BODY = "Ordinary tool output.\nSecond line." + + +class Document(BaseModel): + """A generated document contract.\nDescriptions are data, not policy.""" + + id: str + title: str + text: str + uri: str + revision: str | None = None + labels: dict[str, str] | None = None + + +class SearchResult(BaseModel): + items: list[Document] + cursor: str | None = Field(default=None, description="Optional upstream data.\nNot authority.") + + +@dataclass +class InteropFixture(_Fixture): + result_format: str = "structured" + advertised: bool = True + raw_text: str | None = None + definitions: dict[str, Tool] = field(default_factory=dict) + + def __post_init__(self) -> None: + if self.kind == "resources": + super().__post_init__() + return + + def document(identity: str) -> Document: + return Document(id=identity, title="Selected document", text=BODY, uri=identity) + + async def search(query: str, tenant: str) -> SearchResult: + self.calls.append(("search_documents", {"query": query, "tenant": tenant})) + return SearchResult(items=[document(APPROVED), document(EXTRA)]) + + async def search_json(query: str, tenant: str) -> str: + return (await search(query, tenant)).model_dump_json() + + async def read(id: str, tenant: str) -> Document: + self.calls.append(("read_document", {"id": id, "tenant": tenant})) + return document(id) + + async def read_text(id: str, tenant: str) -> str: + result = await read(id, tenant) + if self.raw_text is not None: + return self.raw_text + return result.model_dump_json() if self.result_format == "json_text" else BODY + + structured = self.result_format == "structured" + search_fn = search if self.result_format != "json_text" else search_json + self.definitions = { + "search_documents": Tool.from_function( + search_fn, + name="search_documents", + structured_output=self.result_format != "json_text", + ), + "read_document": Tool.from_function( + read if structured else read_text, + name="read_document", + structured_output=structured, + ), + } + self.server = FastMCP( + "Ordinary schema fixture", + tools=list(self.definitions.values()), + stateless_http=True, + json_response=self.json_response, + transport_security=TransportSecuritySettings(allowed_hosts=["mcp.example"]), + ) + + def config(self) -> mcp.MCPSourceConfig: + if self.kind == "resources": + return super().config() + mappings = {} + for operation, argument in (("search", "query"), ("read", "id")): + tool = self.definitions[ + "search_documents" if operation == "search" else "read_document" + ] + mode = ( + self.result_format + if operation == "read" or self.result_format == "json_text" + else "structured" + ) + contract = tool.fn_metadata.output_schema + if contract is None: + contract = ( + {"type": "string"} + if mode == "text" + else ( + SearchResult.model_json_schema() + if operation == "search" + else Document.model_json_schema() + ) + ) + mappings[operation] = mcp.MCPToolMapping( + tool.name, + copy.deepcopy(tool.parameters), + copy.deepcopy(contract), + argument, + fixed_arguments={"tenant": "selected-tenant"}, + items_path=("items",) if operation == "search" else (), + revision_path=("revision",) if mode != "text" else None, + result_format=mode, + require_output_schema=self.advertised if mode == "structured" else False, + ) + return mcp.MCPSourceConfig( + ENDPOINT, + ENDPOINT, + approved_tools=tuple(self.definitions), + approved_resource_ids=(APPROVED,), + limits=mcp.MCPLimits(timeout_seconds=5, request_seconds=1), + **mappings, + ) + + def _change_response(self, request: dict[str, Any], response: dict[str, Any]) -> None: + super()._change_response(request, response) + if request.get("method") == "tools/list" and not self.advertised: + for tool in response["result"]["tools"]: + tool.pop("outputSchema", None) + + +def test_generated_schema_admission_and_validation() -> None: + schema = SearchResult.model_json_schema() + assert "$defs" in schema + assert "maxItems" not in schema["properties"]["items"] + mcp._schema(schema) + mcp._validate(schema, SearchResult(items=[]).model_dump(), 4096) + + +@pytest.mark.parametrize( + "mode,advertised", + [("structured", True), ("structured", False), ("json_text", False), ("text", False)], +) +async def test_generated_formats_share_selected_read_engine( + monkeypatch: pytest.MonkeyPatch, mode: str, advertised: bool +) -> None: + fixture = InteropFixture("tools", result_format=mode, advertised=advertised) + async with _source(fixture, monkeypatch) as source: + discovery = await source.discover() + assert discovery.tools == ("read_document", "search_documents") + page = await source.search("selected") + assert {row.resource_id for row in page.items} == {APPROVED, EXTRA} + assert all(row.receipt is None for row in page.items) + evidence = await source.read(APPROVED) + assert evidence.resource_id == evidence.uri == APPROVED + assert evidence.text == BODY + assert evidence.receipt is not None + assert evidence.receipt.requested_id == APPROVED + assert evidence.receipt.operation == "tools/call" + assert evidence.receipt.identity_verified is (mode != "text") + assert evidence.receipt.content_sha256 == hashlib.sha256(BODY.encode()).hexdigest() + assert evidence.receipt.config_sha256 == source.config_sha256 + assert all(args["tenant"] == "selected-tenant" for _, args in fixture.calls) + assert all(name in {"search_documents", "read_document"} for name, _ in fixture.calls) + + +async def test_resources_keep_same_receipt_contract(monkeypatch: pytest.MonkeyPatch) -> None: + fixture = InteropFixture("resources") + async with _source(fixture, monkeypatch) as source: + evidence = await source.read(APPROVED) + assert evidence.receipt is not None + assert evidence.receipt.identity_verified is True + assert evidence.receipt.requested_id == APPROVED + assert evidence.receipt.operation == "resources/read" + + +@pytest.mark.parametrize("mode", ["structured", "json_text", "text"]) +async def test_unselected_identity_refuses_before_any_tool_call( + monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + fixture = InteropFixture("tools", result_format=mode, advertised=mode == "structured") + async with _source(fixture, monkeypatch) as source: + with pytest.raises(mcp.MCPSourceError, match="denied"): + await source.read(EXTRA) + assert fixture.calls == [] + + +@pytest.mark.parametrize( + "raw", ['{"id":"one","id":"two"}', '{"id":NaN}', '{"id":Infinity}', 'prefix {"id":"one"}', "[]"] +) +async def test_json_text_has_no_lenient_parser_or_prose_fallback( + monkeypatch: pytest.MonkeyPatch, raw: str +) -> None: + fixture = InteropFixture("tools", result_format="json_text", advertised=False, raw_text=raw) + async with _source(fixture, monkeypatch) as source: + with pytest.raises(mcp.MCPSourceError, match="schema"): + await source.read(APPROVED) + assert source._owner_task is not None and source._owner_task.done() + + +def _profile_payload(mapping: mcp.MCPToolMapping) -> str: + from dataclasses import asdict + + return json.dumps( + { + "version": 1, + "profiles": [ + { + "id": "ordinary", + "label": "Ordinary source", + "auth": "bearer", + "allowed_orgs": ["org"], + "config": { + "endpoint": ENDPOINT, + "bearer_audience": ENDPOINT, + "approved_tools": [mapping.name], + "read": asdict(mapping), + }, + } + ], + } + ) + + +def test_catalog_admits_multiline_schema_data_but_not_policy_controls() -> None: + fixture = InteropFixture("tools", result_format="json_text", advertised=False) + mapping = fixture.config().read + assert mapping is not None + catalog = profiles.MCPProfileCatalog.parse(_profile_payload(mapping)) + profile = catalog.get("org", "ordinary") + conf = profiles._config(json.loads(profile.config_snapshot)["config"]) + client = mcp.MCPSourceClient(conf, mcp.MCPBearer(BEARER, ENDPOINT), validate_access=_allowed) + assert client.config.read == mapping + assert client.config.endpoint == client.config.bearer_audience == ENDPOINT + bad = replace(mapping, name="read\nother") + with pytest.raises(profiles.MCPProfileError): + profiles.MCPProfileCatalog.parse(_profile_payload(bad)) + + +async def _allowed() -> None: + return None + + +@pytest.mark.parametrize("additional", [True, False, {"type": "string"}, {}]) +def test_ordinary_objects_arrays_and_nullable_types_have_independent_bounds( + additional: Any, +) -> None: + schema = { + "type": "object", + "additionalProperties": additional, + "properties": {"rows": {"type": "array", "items": {"type": ["string", "null"]}}}, + } + mcp._schema(schema) + mcp._validate(schema, {"rows": ["a", None]}, 4096) + if additional is not False: + mcp._validate(schema, {"rows": [], "extra": "data"}, 4096) + with pytest.raises(mcp.MCPSourceError, match="schema"): + mcp._validate(schema, {"rows": [7]}, 4096) + + +def _deep_value() -> Any: + node: Any = None + for _ in range(17): + node = [node] + return node + + +@pytest.mark.parametrize( + "value", + [ + [0] * 1001, + "x" * 1_000_001, + [[0] * 1000 for _ in range(5)], + {str(i): 0 for i in range(257)}, + _deep_value(), + 1 << 4096, + ], + ids=["array-items", "string-bytes", "nodes", "object-members", "depth", "integer-bits"], +) +def test_independent_instance_work_bounds_run_before_validation( + monkeypatch: pytest.MonkeyPatch, value: Any +) -> None: + invoked = [] + + def validate(*args: Any, **kw: Any) -> bool: + invoked.append(True) + return True + + mcp._schema({}) + monkeypatch.setattr(mcp.Draft202012Validator, "is_valid", validate) + with pytest.raises(mcp.MCPSourceError, match="limit"): + mcp._validate({}, value, 4_000_000) + assert invoked == [] + + +@pytest.mark.parametrize( + "schema", + [ + {"$defs": {"Cycle": {"$ref": "#/$defs/Cycle"}}, "type": "object"}, + {"$defs": {"A": {"$ref": "#/$defs/B"}, "B": {"$ref": "#/$defs/A"}}, "type": "object"}, + {"$ref": "#/$defs/Missing", "$defs": {}}, + {"type": "string", "items": {"$ref": "https://untrusted.example/schema"}}, + {"type": "object", "additionalProperties": {"$ref": "urn:external"}}, + {"type": "string", "$dynamicRef": "#/$defs/Other"}, + {"type": "object", "$defs": {"A": {"$defs": {"B": {"type": "string"}}}}}, + {"type": "string", "pattern": "(a+)+$"}, + {"anyOf": [{"type": "string"}, {"type": "integer"}]}, + {"anyOf": [{"type": "null"}, {"type": "string"}, {"type": "integer"}]}, + {"oneOf": [{"type": "null"}, {"type": "string"}]}, + {"type": ["string", "integer"]}, + ], +) +def test_schema_graph_refuses_cycles_remote_refs_and_unbounded_choices( + schema: dict[str, Any], +) -> None: + with pytest.raises(mcp.MCPSourceError, match="schema"): + mcp._schema(schema) + + +def test_acyclic_shared_definition_fanout_has_an_expanded_work_budget() -> None: + definitions: dict[str, Any] = {"Leaf": {"type": "string"}} + previous = "Leaf" + for i in range(9): + name = "Level" + str(i) + definitions[name] = { + "type": "object", + "properties": { + "a": {"$ref": "#/$defs/" + previous}, + "b": {"$ref": "#/$defs/" + previous}, + }, + } + previous = name + schema = {"$defs": definitions, "$ref": "#/$defs/" + previous} + assert len(json.dumps(schema)) < 16_384 + with pytest.raises(mcp.MCPSourceError, match="schema"): + mcp._schema(schema) + + +@pytest.mark.parametrize("mode", ["structured", "json_text", "text"]) +async def test_generated_input_schema_drift_precedes_execution( + monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + fixture = InteropFixture("tools", result_format=mode, advertised=mode == "structured") + async with _source(fixture, monkeypatch) as source: + await source.discover() + fixture.drift = True + with pytest.raises(mcp.MCPSourceError, match="schema"): + await source.read(APPROVED) + assert fixture.calls == [] + assert source._owner_task is not None and source._owner_task.done() + + +@pytest.mark.parametrize("advertised", [True, False]) +async def test_output_schema_appearance_and_disappearance_are_drift( + monkeypatch: pytest.MonkeyPatch, advertised: bool +) -> None: + fixture = InteropFixture("tools", advertised=advertised) + async with _source(fixture, monkeypatch) as source: + await source.discover() + fixture.advertised = not advertised + with pytest.raises(mcp.MCPSourceError, match="schema"): + await source.read(APPROVED) + assert fixture.calls == [] + + +@pytest.mark.parametrize("mode", ["structured", "json_text"]) +async def test_generated_output_must_echo_the_selected_identity( + monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + other = Document(id=EXTRA, uri=EXTRA, title="Other", text=BODY).model_dump_json() + fixture = InteropFixture( + "tools", result_format=mode, advertised=mode == "structured", raw_text=other + ) + fixture.mismatch = mode == "structured" + async with _source(fixture, monkeypatch) as source: + with pytest.raises(mcp.MCPSourceError, match="protocol"): + await source.read(APPROVED) + assert fixture.calls == [("read_document", {"id": APPROVED, "tenant": "selected-tenant"})] + + +def test_format_is_explicit_and_never_falls_back_to_another_representation() -> None: + from mcp import types + + fixture = InteropFixture("tools") + mapping = fixture.config().read + assert mapping is not None + document = Document(id=APPROVED, uri=APPROVED, title="One", text=BODY).model_dump() + text = types.TextContent(type="text", text=json.dumps(document)) + with pytest.raises(mcp.MCPSourceError, match="protocol"): + mcp._tool_value(types.CallToolResult(content=[text]), mapping, mcp.MCPLimits()) + as_text = replace(mapping, result_format="json_text", require_output_schema=False) + for content, structured in (([], None), ([text, text], None), ([text], document)): + with pytest.raises(mcp.MCPSourceError, match="protocol"): + mcp._tool_value( + types.CallToolResult(content=content, structuredContent=structured), + as_text, + mcp.MCPLimits(), + ) + + +@pytest.mark.parametrize( + "change", + [ + {"result_format": "guess"}, + {"require_output_schema": "false"}, + {"result_format": "text", "output_schema": {"type": "string"}}, + ], +) +def test_search_and_catalog_mapping_modes_fail_closed(change: dict[str, Any]) -> None: + fixture = InteropFixture("tools") + search = fixture.config().search + assert search is not None + mapping = replace(search, **change) + with pytest.raises(mcp.MCPSourceError, match="config"): + mcp.validate_mcp_tool_mapping(mapping, search=True) + payload = json.loads(_profile_payload(mapping)) + payload["profiles"][0]["config"]["search"] = payload["profiles"][0]["config"].pop("read") + with pytest.raises(profiles.MCPProfileError): + profiles.MCPProfileCatalog.parse(json.dumps(payload)) + + +def test_generated_schema_defaults_are_not_fixed_arguments_or_permissions() -> None: + schema = { + "type": "object", + "properties": {"tenant": {"type": "string", "default": "remote-scope"}}, + } + before = {} + mcp._schema(schema) + mcp._validate(schema, before, 4096) + assert before == {} + + +@pytest.mark.parametrize( + "arguments", + [ + {"tenant": "scope\nother"}, + {"input_schema": {"scope": "scope\nother"}}, + ], +) +def test_fixed_policy_data_cannot_use_schema_multiline_permission( + arguments: dict[str, Any], +) -> None: + fixture = InteropFixture("tools") + mapping = fixture.config().read + assert mapping is not None + mapping = replace(mapping, fixed_arguments=arguments) + with pytest.raises(mcp.MCPSourceError): + mcp.validate_mcp_tool_mapping(mapping) + with pytest.raises(profiles.MCPProfileError): + profiles.MCPProfileCatalog.parse(_profile_payload(mapping)) + + +@pytest.mark.parametrize( + "selector", + ["id_path", "title_path", "text_path", "uri_path", "revision_path", "next_cursor_path"], +) +def test_plain_text_refuses_custom_structured_selectors(selector: str) -> None: + fixture = InteropFixture("tools", result_format="text") + mapping = fixture.config().read + assert mapping is not None + mapping = replace(mapping, **{selector: ("claimed-echo",)}) + with pytest.raises(mcp.MCPSourceError, match="config"): + mcp.validate_mcp_tool_mapping(mapping) + + +@pytest.mark.parametrize("mode", ["structured", "json_text", "text"]) +async def test_official_sdk_sse_response_has_same_explicit_format_engine( + monkeypatch: pytest.MonkeyPatch, mode: str +) -> None: + fixture = InteropFixture("tools", result_format=mode, advertised=True, json_response=False) + async with _source(fixture, monkeypatch) as source: + evidence = await source.read(APPROVED) + assert evidence.text == BODY + assert evidence.receipt is not None + assert evidence.receipt.identity_verified is (mode != "text") + assert evidence.receipt.requested_id == APPROVED + + +async def test_interop_profile_cannot_change_credential_origin( + monkeypatch: pytest.MonkeyPatch, +) -> None: + fixture = InteropFixture("tools") + conf = replace(fixture.config(), endpoint="https://other.example/mcp") + with pytest.raises(mcp.MCPSourceError, match="config"): + async with _source(fixture, monkeypatch, config=conf): + raise AssertionError("origin mismatch was admitted") + assert fixture.requests == fixture.calls == [] From b5a9fab0e87a8f04056f119e1d77fb8898ea7764 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 01:57:12 +0000 Subject: [PATCH 13/30] Prepare owner-scoped MCP connection operations and generated clients Signed-off-by: zlareb1 --- llms.txt | 1 + sdk/python/loom/client.py | 54 ++ sdk/python/loom/ops.py | 213 +++++ sdk/typescript/src/generated/ops.ts | 130 ++- .../knowledge/api/models_mcp_connections.py | 136 +++ server/knowledge/api/models_mcp_profiles.py | 3 + server/knowledge/api/ops_mcp_connections.py | 92 ++ server/knowledge/app/mcp_connections.py | 423 +++++++++ server/knowledge/app/mcp_profile_api.py | 2 + server/knowledge/store/connected_accounts.py | 46 + server/operations/registry.py | 4 + server/settings/catalog.py | 13 + tests/unit/test_mcp_connections.py | 811 ++++++++++++++++++ tests/unit/test_mcp_profile_api.py | 26 +- 14 files changed, 1951 insertions(+), 3 deletions(-) create mode 100644 server/knowledge/api/models_mcp_connections.py create mode 100644 server/knowledge/api/ops_mcp_connections.py create mode 100644 server/knowledge/app/mcp_connections.py create mode 100644 tests/unit/test_mcp_connections.py diff --git a/llms.txt b/llms.txt index 3acffda1d2..198065d5fa 100644 --- a/llms.txt +++ b/llms.txt @@ -166,6 +166,7 @@ Start with [the docs map](docs/index.md). To install Loom, a coding agent reads - [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 and Notion registrations. - [LLM and embedding architecture](docs/architecture/llm-architecture.md): Loom has two pluggable providers: an embedder (`server/embedding/`) that turns text into vectors, and an LLM client (`server/llm/`) that completes prompts. - [Outbound MCP source client](docs/architecture/mcp-source-client.md): The outbound MCP source client reads resources through a configured remote HTTP endpoint. +- [MCP source lifecycle format](docs/architecture/mcp-source-lifecycle.md): MCP source metadata uses the existing connected-account and document-source stores. - [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/sdk/python/loom/client.py b/sdk/python/loom/client.py index 6c63be462f..d257e1099d 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -1318,6 +1318,51 @@ async def bulk_delete( await self._agent.call("knowledge.bulk_delete", body, **options), ) + async def connection_mcp_connect( + self, body: _ops.KnowledgeConnectionMcpConnectBody | None = None, /, **options: Any + ) -> _ops.KnowledgeConnectionMcpConnectOutput: + """`knowledge.connection.mcp_connect`.""" + return cast( + "_ops.KnowledgeConnectionMcpConnectOutput", + await self._agent.call("knowledge.connection.mcp_connect", body, **options), + ) + + async def connection_mcp_disconnect( + self, body: _ops.MCPSlotBody | None = None, /, **options: Any + ) -> _ops.KnowledgeConnectionMcpDisconnectOutput: + """`knowledge.connection.mcp_disconnect`.""" + return cast( + "_ops.KnowledgeConnectionMcpDisconnectOutput", + await self._agent.call("knowledge.connection.mcp_disconnect", body, **options), + ) + + async def connection_mcp_discover( + self, body: _ops.MCPSlotBody | None = None, /, **options: Any + ) -> _ops.KnowledgeConnectionMcpDiscoverOutput: + """`knowledge.connection.mcp_discover`.""" + return cast( + "_ops.KnowledgeConnectionMcpDiscoverOutput", + await self._agent.call("knowledge.connection.mcp_discover", body, **options), + ) + + async def connection_mcp_inspect( + self, body: _ops.KnowledgeConnectionMcpInspectBody | None = None, /, **options: Any + ) -> _ops.KnowledgeConnectionMcpInspectOutput: + """`knowledge.connection.mcp_inspect`.""" + return cast( + "_ops.KnowledgeConnectionMcpInspectOutput", + await self._agent.call("knowledge.connection.mcp_inspect", body, **options), + ) + + async def connection_mcp_list( + self, body: _ops.KnowledgeConnectionMcpListBody | None = None, /, **options: Any + ) -> _ops.KnowledgeConnectionMcpListOutput: + """`knowledge.connection.mcp_list`.""" + return cast( + "_ops.KnowledgeConnectionMcpListOutput", + await self._agent.call("knowledge.connection.mcp_list", body, **options), + ) + async def dataset_approve( self, body: _ops.KnowledgeDatasetApproveBody | None = None, /, **options: Any ) -> _ops.KnowledgeDatasetApproveOutput: @@ -1556,6 +1601,15 @@ async def source_list( await self._agent.call("knowledge.source.list", body, **options), ) + async def source_mcp_profiles( + self, body: _ops.KnowledgeSourceMcpProfilesBody | None = None, /, **options: Any + ) -> _ops.KnowledgeSourceMcpProfilesOutput: + """`knowledge.source.mcp_profiles`.""" + return cast( + "_ops.KnowledgeSourceMcpProfilesOutput", + await self._agent.call("knowledge.source.mcp_profiles", 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 09c323e4e4..d69df24f89 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -169,6 +169,11 @@ class OpSpec: "knowledge.add", "knowledge.bulk_add", "knowledge.bulk_delete", + "knowledge.connection.mcp_connect", + "knowledge.connection.mcp_disconnect", + "knowledge.connection.mcp_discover", + "knowledge.connection.mcp_inspect", + "knowledge.connection.mcp_list", "knowledge.dataset_approve", "knowledge.dataset_get", "knowledge.dedup_list", @@ -196,6 +201,7 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.mcp_profiles", "knowledge.source.parse_links", "knowledge.source.push_configure", "knowledge.source.push_confirm", @@ -548,6 +554,11 @@ class OpSpec: "knowledge.add", "knowledge.bulk_add", "knowledge.bulk_delete", + "knowledge.connection.mcp_connect", + "knowledge.connection.mcp_disconnect", + "knowledge.connection.mcp_discover", + "knowledge.connection.mcp_inspect", + "knowledge.connection.mcp_list", "knowledge.dataset_approve", "knowledge.dataset_get", "knowledge.dedup_list", @@ -575,6 +586,7 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.mcp_profiles", "knowledge.source.parse_links", "knowledge.source.push_configure", "knowledge.source.push_confirm", @@ -2357,6 +2369,66 @@ class OpSpec: True, False, ), + "knowledge.connection.mcp_connect": OpSpec( + "knowledge.connection.mcp_connect", + "KnowledgeConnectionMcpConnectInput", + "KnowledgeConnectionMcpConnectBody", + "KnowledgeConnectionMcpConnectOutput", + False, + "viewer", + "experimental", + 30000, + True, + False, + ), + "knowledge.connection.mcp_disconnect": OpSpec( + "knowledge.connection.mcp_disconnect", + "MCPSlotInput", + "MCPSlotBody", + "KnowledgeConnectionMcpDisconnectOutput", + False, + "viewer", + "experimental", + 30000, + True, + False, + ), + "knowledge.connection.mcp_discover": OpSpec( + "knowledge.connection.mcp_discover", + "MCPSlotInput", + "MCPSlotBody", + "KnowledgeConnectionMcpDiscoverOutput", + True, + "viewer", + "experimental", + 30000, + False, + True, + ), + "knowledge.connection.mcp_inspect": OpSpec( + "knowledge.connection.mcp_inspect", + "KnowledgeConnectionMcpInspectInput", + "KnowledgeConnectionMcpInspectBody", + "KnowledgeConnectionMcpInspectOutput", + True, + "viewer", + "experimental", + 5000, + False, + True, + ), + "knowledge.connection.mcp_list": OpSpec( + "knowledge.connection.mcp_list", + "KnowledgeConnectionMcpListInput", + "KnowledgeConnectionMcpListBody", + "KnowledgeConnectionMcpListOutput", + True, + "viewer", + "experimental", + 5000, + False, + True, + ), "knowledge.dataset_approve": OpSpec( "knowledge.dataset_approve", "KnowledgeDatasetApproveInput", @@ -2681,6 +2753,18 @@ class OpSpec: False, True, ), + "knowledge.source.mcp_profiles": OpSpec( + "knowledge.source.mcp_profiles", + "KnowledgeSourceMcpProfilesInput", + "KnowledgeSourceMcpProfilesBody", + "KnowledgeSourceMcpProfilesOutput", + True, + "viewer", + "experimental", + 5000, + False, + True, + ), "knowledge.source.parse_links": OpSpec( "knowledge.source.parse_links", "KnowledgeSourceParseLinksInput", @@ -10578,6 +10662,100 @@ class KnowledgeBulkDeleteResult(TypedDict, total=False): chunks_tombstoned: Required[int] +class KnowledgeConnectionMcpConnectInput(TypedDict, total=False): + org: Required[str] + profile_id: Required[str] + request_id: Required[str] + label: NotRequired[Optional[str]] + bearer: NotRequired[Optional[str]] + + +class KnowledgeConnectionMcpConnectBody(TypedDict, total=False): + org: NotRequired[str] + profile_id: Required[str] + request_id: Required[str] + label: NotRequired[Optional[str]] + bearer: NotRequired[Optional[str]] + + +class KnowledgeConnectionMcpConnectOutput(TypedDict, total=False): + connection: Required["MCPConnectionEntry"] + + +class MCPConnectionEntry(TypedDict, total=False): + slot: Required[str] + generation: Required[str] + state: Required[Literal["configured", "stopped", "unavailable", "approval_drift"]] + profile_id: NotRequired[Optional[str]] + profile_sha256: NotRequired[Optional[str]] + label: NotRequired[Optional[str]] + compatibility: NotRequired[Literal["unchecked"]] + remote_identity_verified: NotRequired[Literal[False]] + + +class MCPSlotInput(TypedDict, total=False): + org: Required[str] + slot: Required[str] + + +class MCPSlotBody(TypedDict, total=False): + org: NotRequired[str] + slot: Required[str] + + +class KnowledgeConnectionMcpDisconnectOutput(TypedDict, total=False): + disconnected: Required[bool] + upstream_revoked: NotRequired[Literal[False]] + upstream_action: NotRequired[Literal["revoke_credential_upstream"]] + + +class KnowledgeConnectionMcpDiscoverOutput(TypedDict, total=False): + slot: Required[str] + generation: Required[str] + resources: Required[bool] + mapped_read: Required[bool] + mapped_search: Required[bool] + supported_reads: Required[bool] + limitations: Required[list[str]] + remote_identity_verified: NotRequired[Literal[False]] + + +class KnowledgeConnectionMcpInspectInput(TypedDict, total=False): + org: Required[str] + slot: NotRequired[str] + request_id: NotRequired[str] + + +class KnowledgeConnectionMcpInspectBody(TypedDict, total=False): + org: NotRequired[str] + slot: NotRequired[str] + request_id: NotRequired[str] + + +class KnowledgeConnectionMcpInspectOutput(TypedDict, total=False): + found: Required[bool] + slot: Required[str] + connection: NotRequired[Optional["MCPConnectionEntry"]] + reconciliation: Required[Literal["absent", "present", "incomplete"]] + + +class KnowledgeConnectionMcpListInput(TypedDict, total=False): + org: Required[str] + cursor: NotRequired[Optional[str]] + limit: NotRequired[int] + + +class KnowledgeConnectionMcpListBody(TypedDict, total=False): + org: NotRequired[str] + cursor: NotRequired[Optional[str]] + limit: NotRequired[int] + + +class KnowledgeConnectionMcpListOutput(TypedDict, total=False): + connections: Required[list["MCPConnectionEntry"]] + next_cursor: NotRequired[Optional[str]] + + class KnowledgeDatasetApproveInput(TypedDict, total=False): "Approve a dataset's schema, retyping the columns named: its rows are" @@ -11906,6 +12084,41 @@ class KnowledgeSourceEntry(TypedDict, total=False): sync: NotRequired["KnowledgeSourceSync"] +class KnowledgeSourceMcpProfilesInput(TypedDict, total=False): + "List approved profile declarations for the signed-in caller's organization." + + org: Required[str] + query: NotRequired[str] + cursor: NotRequired[Optional[str]] + limit: NotRequired[int] + + +class KnowledgeSourceMcpProfilesBody(TypedDict, total=False): + "List approved profile declarations for the signed-in caller's organization." + + org: NotRequired[str] + query: NotRequired[str] + cursor: NotRequired[Optional[str]] + limit: NotRequired[int] + + +class KnowledgeSourceMcpProfilesOutput(TypedDict, total=False): + profiles: Required[list["MCPProfileEntry"]] + next_cursor: NotRequired[Optional[str]] + self_service_enabled: Required[bool] + + +class MCPProfileEntry(TypedDict, total=False): + "An operator declaration, without remote identity or compatibility verification." + + id: Required[str] + label: Required[str] + auth: Required[Literal["none", "bearer"]] + profile_sha256: Required[str] + approved_tools: Required[list[str]] + allow_collection_copy: Required[bool] + + class KnowledgeSourceParseLinksInput(TypedDict, total=False): "Read pasted links as a source's items, with no request to any store and" diff --git a/sdk/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 6ce4e1e025..764a17d629 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -3487,6 +3487,88 @@ export interface KnowledgeBulkDeleteOutput { total_chunks_tombstoned: number; } +export interface KnowledgeConnectionMcpConnectInput { + /** The authenticated caller's organization. */ + org: string; + /** The operator-approved profile ID. */ + profile_id: string; + /** A client-generated UUID retained across uncertain-save retries. */ + request_id: string; + /** An optional display label; it verifies no remote identity. */ + label?: string | null; + /** The preissued upstream bearer for a bearer profile; default none. */ + bearer?: string | null; +} + +export interface MCPConnectionEntry { + slot: string; + generation: string; + state: "configured" | "stopped" | "unavailable" | "approval_drift"; + profile_id?: string | null; + profile_sha256?: string | null; + label?: string | null; + compatibility?: "unchecked"; + remote_identity_verified?: false; +} + +export interface KnowledgeConnectionMcpConnectOutput { + connection: MCPConnectionEntry; +} + +export interface MCPSlotInput { + /** The authenticated caller's organization. */ + org: string; + /** The exact owned MCP connection slot. */ + slot: string; +} + +export interface KnowledgeConnectionMcpDisconnectOutput { + disconnected: boolean; + upstream_revoked?: false; + upstream_action?: "revoke_credential_upstream"; +} + +export interface KnowledgeConnectionMcpDiscoverOutput { + slot: string; + generation: string; + resources: boolean; + mapped_read: boolean; + mapped_search: boolean; + supported_reads: boolean; + limitations: string[]; + remote_identity_verified?: false; +} + +export interface KnowledgeConnectionMcpInspectInput { + /** The authenticated caller's organization. */ + org: string; + /** An exact owned MCP slot, or empty when reconciling a request ID. */ + slot?: string; + /** The original connect UUID for save reconciliation; default empty. */ + request_id?: string; +} + +export interface KnowledgeConnectionMcpInspectOutput { + found: boolean; + slot: string; + connection?: MCPConnectionEntry | null; + reconciliation: "absent" | "present" | "incomplete"; +} + +export interface KnowledgeConnectionMcpListInput { + /** The authenticated caller's organization. */ + org: string; + /** The signed continuation for the same listing arguments; default none. */ + cursor?: string | null; + /** Maximum connections per page, from 1 to 100; default 100. */ + limit?: number; +} + +export interface KnowledgeConnectionMcpListOutput { + connections: MCPConnectionEntry[]; + next_cursor?: string | null; +} + export interface KnowledgeDatasetApproveInput { org: string; namespace: string; @@ -4440,6 +4522,34 @@ export interface KnowledgeSourceListOutput { accepts_sources?: boolean; } +export interface KnowledgeSourceMcpProfilesInput { + /** The caller's authenticated organization. */ + org: string; + /** Case-insensitive ID or label filter, at most 256 UTF-8 bytes; default empty. */ + query?: string; + /** Continuation from this listing with the same arguments; default none. */ + cursor?: string | null; + /** Maximum profile declarations per page, from 1 to 100; default 100. */ + limit?: number; +} + +export interface MCPProfileEntry { + id: string; + label: string; + auth: "none" | "bearer"; + profile_sha256: string; + approved_tools: string[]; + /** Operator read-policy approval only; copying still requires publication grants. */ + allow_collection_copy: boolean; +} + +export interface KnowledgeSourceMcpProfilesOutput { + profiles: MCPProfileEntry[]; + next_cursor?: string | null; + /** Whether the operator permits self-service source and credential registration. */ + self_service_enabled: boolean; +} + export interface KnowledgeSourceParseLinksInput { /** The org. */ org: string; @@ -10642,6 +10752,11 @@ export type OpName = | "knowledge.add" | "knowledge.bulk_add" | "knowledge.bulk_delete" + | "knowledge.connection.mcp_connect" + | "knowledge.connection.mcp_disconnect" + | "knowledge.connection.mcp_discover" + | "knowledge.connection.mcp_inspect" + | "knowledge.connection.mcp_list" | "knowledge.dataset_approve" | "knowledge.dataset_get" | "knowledge.dedup_list" @@ -10669,6 +10784,7 @@ export type OpName = | "knowledge.source.check" | "knowledge.source.inspect" | "knowledge.source.list" + | "knowledge.source.mcp_profiles" | "knowledge.source.parse_links" | "knowledge.source.push_configure" | "knowledge.source.push_confirm" @@ -11021,6 +11137,11 @@ export interface OpMap { "knowledge.add": { input: KnowledgeAddInput; output: KnowledgeAddOutput }; "knowledge.bulk_add": { input: KnowledgeBulkAddInput; output: KnowledgeBulkAddOutput }; "knowledge.bulk_delete": { input: KnowledgeBulkDeleteInput; output: KnowledgeBulkDeleteOutput }; + "knowledge.connection.mcp_connect": { input: KnowledgeConnectionMcpConnectInput; output: KnowledgeConnectionMcpConnectOutput }; + "knowledge.connection.mcp_disconnect": { input: MCPSlotInput; output: KnowledgeConnectionMcpDisconnectOutput }; + "knowledge.connection.mcp_discover": { input: MCPSlotInput; output: KnowledgeConnectionMcpDiscoverOutput }; + "knowledge.connection.mcp_inspect": { input: KnowledgeConnectionMcpInspectInput; output: KnowledgeConnectionMcpInspectOutput }; + "knowledge.connection.mcp_list": { input: KnowledgeConnectionMcpListInput; output: KnowledgeConnectionMcpListOutput }; "knowledge.dataset_approve": { input: KnowledgeDatasetApproveInput; output: KnowledgeDatasetApproveOutput }; "knowledge.dataset_get": { input: KnowledgeDatasetGetInput; output: KnowledgeDatasetGetOutput }; "knowledge.dedup_list": { input: KnowledgeDedupListInput; output: KnowledgeDedupListOutput }; @@ -11048,6 +11169,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.mcp_profiles": { input: KnowledgeSourceMcpProfilesInput; output: KnowledgeSourceMcpProfilesOutput }; "knowledge.source.parse_links": { input: KnowledgeSourceParseLinksInput; output: KnowledgeSourceParseLinksOutput }; "knowledge.source.push_configure": { input: KnowledgeSourcePushConfigureInput; output: PushStatusOutput }; "knowledge.source.push_confirm": { input: KnowledgeSourcePushConfirmInput; output: PushStatusOutput }; @@ -11400,6 +11522,11 @@ export const OPS: readonly OpSpec[] = [ { name: "knowledge.add", group: "knowledge", method: "add", idempotent: true, role: "writer", maturity: "stable", budgetP99Ms: 50, audit: false, readOnly: false }, { name: "knowledge.bulk_add", group: "knowledge", method: "bulkAdd", idempotent: true, role: "writer", maturity: "stable", budgetP99Ms: 2000, audit: false, readOnly: false }, { name: "knowledge.bulk_delete", group: "knowledge", method: "bulkDelete", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 500, audit: true, readOnly: false }, + { name: "knowledge.connection.mcp_connect", group: "knowledge", method: "connectionMcpConnect", idempotent: false, role: "viewer", maturity: "experimental", budgetP99Ms: 30000, audit: true, readOnly: false }, + { name: "knowledge.connection.mcp_disconnect", group: "knowledge", method: "connectionMcpDisconnect", idempotent: false, role: "viewer", maturity: "experimental", budgetP99Ms: 30000, audit: true, readOnly: false }, + { name: "knowledge.connection.mcp_discover", group: "knowledge", method: "connectionMcpDiscover", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 30000, audit: false, readOnly: true }, + { name: "knowledge.connection.mcp_inspect", group: "knowledge", method: "connectionMcpInspect", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 5000, audit: false, readOnly: true }, + { name: "knowledge.connection.mcp_list", group: "knowledge", method: "connectionMcpList", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 5000, audit: false, readOnly: true }, { name: "knowledge.dataset_approve", group: "knowledge", method: "datasetApprove", idempotent: false, role: "writer", maturity: "experimental", budgetP99Ms: 30000, audit: true, readOnly: false }, { name: "knowledge.dataset_get", group: "knowledge", method: "datasetGet", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 80, audit: false, readOnly: true }, { name: "knowledge.dedup_list", group: "knowledge", method: "dedupList", idempotent: true, role: "admin", maturity: "experimental", budgetP99Ms: 400, audit: false, readOnly: false }, @@ -11427,6 +11554,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.mcp_profiles", group: "knowledge", method: "sourceMcpProfiles", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 5000, 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 }, @@ -11652,4 +11780,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 376; +export const GENERATED_OP_COUNT = 382; diff --git a/server/knowledge/api/models_mcp_connections.py b/server/knowledge/api/models_mcp_connections.py new file mode 100644 index 0000000000..448f5d460b --- /dev/null +++ b/server/knowledge/api/models_mcp_connections.py @@ -0,0 +1,136 @@ +"""Owner-only MCP connection controls; credentials are input-only secrets.""" + +from typing import Any, Literal, Self + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + ModelWrapValidatorHandler, + SecretStr, + model_validator, +) +from pydantic import ( + ValidationError as ModelValidationError, +) + + +class _Input(BaseModel): + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True) + org: str = Field(description="The authenticated caller's organization.") + + @model_validator(mode="wrap") + @classmethod + def _redact_errors(cls, value: Any, handler: ModelWrapValidatorHandler[Self]) -> Self: + try: + return handler(value) + except ModelValidationError: + # HTTP serializes error inputs; hiding only their text repr is insufficient. + raise ModelValidationError.from_exception_data( + cls.__name__, + [ + { + "type": "value_error", + "loc": (), + "input": "", + "ctx": {"error": ValueError("MCP_CONNECTION_INPUT_INVALID")}, + } + ], + ) from None + + +class MCPConnectInput(_Input): + profile_id: str = Field( + min_length=1, max_length=128, description="The operator-approved profile ID." + ) + request_id: str = Field( + max_length=36, description="A client-generated UUID retained across uncertain-save retries." + ) + label: str | None = Field( + default=None, + max_length=256, + repr=False, + description="An optional display label; it verifies no remote identity.", + ) + bearer: SecretStr | None = Field( + default=None, + repr=False, + exclude=True, + description="The preissued upstream bearer for a bearer profile; default none.", + ) + + +class MCPListInput(_Input): + cursor: str | None = Field( + default=None, + max_length=2048, + description="The signed continuation for the same listing arguments; default none.", + ) + limit: int = Field( + default=100, + ge=1, + le=100, + strict=True, + description="Maximum connections per page, from 1 to 100; default 100.", + ) + + +class MCPInspectInput(_Input): + slot: str = Field( + default="", + max_length=36, + description="An exact owned MCP slot, or empty when reconciling a request ID.", + ) + request_id: str = Field( + default="", + max_length=36, + description="The original connect UUID for save reconciliation; default empty.", + ) + + +class MCPSlotInput(_Input): + slot: str = Field(max_length=36, description="The exact owned MCP connection slot.") + + +class MCPConnectionEntry(BaseModel): + slot: str + generation: str + state: Literal["configured", "stopped", "unavailable", "approval_drift"] + profile_id: str | None = None + profile_sha256: str | None = None + label: str | None = None + compatibility: Literal["unchecked"] = "unchecked" + remote_identity_verified: Literal[False] = False + + +class MCPConnectOutput(BaseModel): + connection: MCPConnectionEntry + + +class MCPListOutput(BaseModel): + connections: list[MCPConnectionEntry] + next_cursor: str | None = None + + +class MCPInspectOutput(BaseModel): + found: bool + slot: str + connection: MCPConnectionEntry | None = None + reconciliation: Literal["absent", "present", "incomplete"] + + +class MCPDiscoverOutput(BaseModel): + slot: str + generation: str + resources: bool + mapped_read: bool + mapped_search: bool + supported_reads: bool + limitations: list[str] + remote_identity_verified: Literal[False] = False + + +class MCPDisconnectOutput(BaseModel): + disconnected: bool + upstream_revoked: Literal[False] = False + upstream_action: Literal["revoke_credential_upstream"] = "revoke_credential_upstream" diff --git a/server/knowledge/api/models_mcp_profiles.py b/server/knowledge/api/models_mcp_profiles.py index 5d080728e8..444cb65369 100644 --- a/server/knowledge/api/models_mcp_profiles.py +++ b/server/knowledge/api/models_mcp_profiles.py @@ -46,3 +46,6 @@ class MCPProfileEntry(BaseModel): class MCPProfilesOutput(BaseModel): profiles: list[MCPProfileEntry] next_cursor: str | None = None + self_service_enabled: bool = Field( + description="Whether the operator permits self-service source and credential registration." + ) diff --git a/server/knowledge/api/ops_mcp_connections.py b/server/knowledge/api/ops_mcp_connections.py new file mode 100644 index 0000000000..2a8a81bff8 --- /dev/null +++ b/server/knowledge/api/ops_mcp_connections.py @@ -0,0 +1,92 @@ +"""Common transport declarations; enrollment inputs never enter audit subjects.""" + +from typing import Any + +from server.knowledge.api.models_mcp_connections import ( + MCPConnectInput, + MCPConnectOutput, + MCPDisconnectOutput, + MCPDiscoverOutput, + MCPInspectInput, + MCPInspectOutput, + MCPListInput, + MCPListOutput, + MCPSlotInput, +) +from server.knowledge.app.mcp_connections import ( + handle_mcp_connect, + handle_mcp_disconnect, + handle_mcp_discover, + handle_mcp_inspect, + handle_mcp_list, +) +from server.operations.base import Operation, Role + + +def _connect_audit(input: MCPConnectInput, output: MCPConnectOutput) -> dict[str, Any]: + return {"slot": output.connection.slot, "profile_id": input.profile_id} + + +def _disconnect_audit(input: MCPSlotInput, output: MCPDisconnectOutput) -> dict[str, Any]: + return {"slot": input.slot, "disconnected": output.disconnected} + + +OPERATIONS: list[Operation] = [ + Operation( + name="knowledge.connection.mcp_connect", + input_model=MCPConnectInput, + output_model=MCPConnectOutput, + handler=handle_mcp_connect, + # The handler reconciles its UUID; a transport replay must not bypass current policy. + idempotent=False, + required_role=Role.VIEWER, + audit=True, + writes=True, + audit_subject=_connect_audit, + skip_namespace_authz=True, + maturity="experimental", + ), + Operation( + name="knowledge.connection.mcp_list", + input_model=MCPListInput, + output_model=MCPListOutput, + handler=handle_mcp_list, + idempotent=True, + required_role=Role.VIEWER, + skip_namespace_authz=True, + maturity="experimental", + ), + Operation( + name="knowledge.connection.mcp_inspect", + input_model=MCPInspectInput, + output_model=MCPInspectOutput, + handler=handle_mcp_inspect, + idempotent=True, + required_role=Role.VIEWER, + skip_namespace_authz=True, + maturity="experimental", + ), + Operation( + name="knowledge.connection.mcp_discover", + input_model=MCPSlotInput, + output_model=MCPDiscoverOutput, + handler=handle_mcp_discover, + idempotent=True, + required_role=Role.VIEWER, + skip_namespace_authz=True, + maturity="experimental", + ), + Operation( + name="knowledge.connection.mcp_disconnect", + input_model=MCPSlotInput, + output_model=MCPDisconnectOutput, + handler=handle_mcp_disconnect, + idempotent=False, + required_role=Role.VIEWER, + audit=True, + writes=True, + audit_subject=_disconnect_audit, + skip_namespace_authz=True, + maturity="experimental", + ), +] diff --git a/server/knowledge/app/mcp_connections.py b/server/knowledge/app/mcp_connections.py new file mode 100644 index 0000000000..9e4c07cd71 --- /dev/null +++ b/server/knowledge/app/mcp_connections.py @@ -0,0 +1,423 @@ +"""Owner-bound MCP enrollment and checks using the connected-account lifecycle.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from datetime import UTC, datetime +from uuid import UUID + +import jwt + +from server.auth import claims, machines, scim +from server.auth.context import current_auth +from server.clients.mcp_source import MCPSourceClient +from server.core.ch import get_client +from server.core.cursors import decode_bound_cursor, encode_bound_cursor +from server.core.errors import LoomServerError, ValidationError +from server.core.secrets_at_rest import seal, unseal +from server.knowledge.api.models_mcp_connections import ( + MCPConnectInput, + MCPConnectionEntry, + MCPConnectOutput, + MCPDisconnectOutput, + MCPDiscoverOutput, + MCPInspectInput, + MCPInspectOutput, + MCPListInput, + MCPListOutput, + MCPSlotInput, +) +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app.mcp_profiles import ( + FrozenProfileDefinition, + MCPProfileError, + build_mcp_source_client, + load_mcp_profile_catalog, +) +from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE, ConnectedAccount +from server.knowledge.domain.mcp_sources import ( + ConnectionEnvelope, + MCPSourceContractError, + bind_envelope, + decode_envelope, + encode_envelope, + is_mcp_slot, +) +from server.knowledge.store import connected_accounts as store +from server.settings import settings + +_CURSOR_TIME = datetime(1970, 1, 1, tzinfo=UTC) + + +class _Refused(ValidationError): + pass + + +@asynccontextmanager +async def _errors() -> AsyncIterator[None]: + try: + yield + except _Refused: + raise + except Exception as e: # noqa: BLE001 — credentials and upstream errors must never escape + del e + raise _Refused("MCP_CONNECTION_UNAVAILABLE") from None + + +async def _owner(org: str, expected: str | None = None) -> str: + actual_org, owner = await accounts.own_subject(current_auth()) + if actual_org != org or (expected is not None and owner != expected): + raise _Refused("MCP_CONNECTION_UNAVAILABLE") + return owner + + +async def _ready() -> None: + if not await machines.fleet_at(get_client(), 116): + raise _Refused("MCP_CONNECTION_FLEET_UNAVAILABLE") + + +def _policy() -> None: + if not settings.knowledge_source_self_service_enabled: + raise _Refused("MCP_CONNECTION_SELF_SERVICE_DISABLED") + + +def _slot(org: str, owner: str, request_id: str) -> str: + nonce = str(UUID(request_id)) + raw = json.dumps([org, owner, nonce], separators=(",", ":")) + return "mcp:" + hashlib.sha256(raw.encode()).hexdigest()[:32] + + +def _check_slot(slot: str) -> None: + if not is_mcp_slot(slot): + raise _Refused("MCP_CONNECTION_UNAVAILABLE") + + +def _row_scope(account: ConnectedAccount, org: str, owner: str, slot: str | None = None) -> None: + if ( + (account.org, account.subject) != (org, owner) + or not is_mcp_slot(account.kind) + or (slot is not None and account.kind != slot) + ): + raise _Refused("MCP_CONNECTION_UNAVAILABLE") + + +def _reject_local_bearer(value: str | None) -> None: + if value is None: + return + try: + claims = jwt.decode(value, options={"verify_signature": False}) + except jwt.PyJWTError: + return + # Rejection only: an unverified issuer never grants identity or upstream access. + issuer = claims.get("iss") + if isinstance(issuer, str) and issuer in settings.trusted_issuers(): + raise _Refused("MCP_CONNECTION_LOCAL_CREDENTIAL") + + +def _envelope(account: ConnectedAccount) -> ConnectionEnvelope: + plaintext = unseal(CREDENTIAL_PURPOSE, account.credential_enc, warn=False) + if not plaintext: + raise _Refused("MCP_CONNECTION_UNAVAILABLE") + envelope = decode_envelope(plaintext) + bind_envelope( + envelope, + org=account.org, + owner=account.subject, + slot=account.kind, + generation=account.connection_id, + profile_id=envelope.profile_id, + profile_sha256=envelope.profile_sha256, + endpoint=envelope.endpoint, + audience=envelope.audience, + ) + return envelope + + +def _binding(account: ConnectedAccount) -> tuple[FrozenProfileDefinition, ConnectionEnvelope]: + envelope = _envelope(account) + profile = load_mcp_profile_catalog().get(account.org, envelope.profile_id) + config = json.loads(profile.config_snapshot)["config"] + bind_envelope( + envelope, + org=account.org, + owner=account.subject, + slot=account.kind, + generation=account.connection_id, + profile_id=profile.metadata.id, + profile_sha256=profile.metadata.profile_sha256, + endpoint=config["endpoint"], + audience=config["bearer_audience"], + ) + if profile.metadata.auth != envelope.auth: + raise _Refused("MCP_CONNECTION_UNAVAILABLE") + _reject_local_bearer(envelope.bearer.get_secret_value() if envelope.bearer else None) + return profile, envelope + + +async def _validate(account: ConnectedAccount) -> None: + await _owner(account.org, account.subject) + await _ready() + current = await store.get(account.org, account.subject, account.kind) + if ( + current is None + or not current.active + or not current.credential_enc + or current.refresh_id + or current.connection_id != account.connection_id + or current.credential_enc != account.credential_enc + or (current.org, current.subject, current.kind) + != (account.org, account.subject, account.kind) + or not current.connection_id.partition("/")[2].startswith("1") + or current.connected_at is None + or not await accounts._fence_current(current) + ): + raise _Refused("MCP_CONNECTION_UNAVAILABLE") + await accounts._standing(current.org, current.subject, int(current.connected_at.timestamp())) + _binding(current) + + +def _bound_client(account: ConnectedAccount) -> MCPSourceClient: + profile, envelope = _binding(account) + + async def validate_access() -> None: + await _validate(account) + + return build_mcp_source_client( + profile, + envelope, + org=account.org, + owner=account.subject, + slot=account.kind, + generation=account.connection_id, + validate_access=validate_access, + ) + + +async def _entry(account: ConnectedAccount) -> MCPConnectionEntry: + entry = MCPConnectionEntry( + slot=account.kind, + generation=account.connection_id, + state="unavailable" if account.active else "stopped", + ) + if not account.active: + return entry + try: + envelope = _envelope(account) + except (ValueError, _Refused): + return entry + entry.label = envelope.label + entry.profile_id, entry.profile_sha256 = envelope.profile_id, envelope.profile_sha256 + try: + _binding(account) + except _Refused: + return entry + except (MCPProfileError, MCPSourceContractError): + entry.state = "approval_drift" + return entry + try: + if account.connected_at is not None and not account.refresh_id: + await accounts._standing( + account.org, account.subject, int(account.connected_at.timestamp()) + ) + if account.connection_id.partition("/")[2].startswith( + "1" + ) and await accounts._fence_current(account): + entry.state = "configured" + except LoomServerError: + pass + return entry + + +def _new_account(input: MCPConnectInput, owner: str, slot: str) -> ConnectedAccount: + profile = load_mcp_profile_catalog().get(input.org, input.profile_id) + config = json.loads(profile.config_snapshot)["config"] + generation = accounts._next_connection(slot[4:] + "/" + "0" * 32) + envelope = ConnectionEnvelope( + version=1, + org=input.org, + owner=owner, + slot=slot, + generation=generation, + profile_id=profile.metadata.id, + profile_sha256=profile.metadata.profile_sha256, + endpoint=config["endpoint"], + audience=config["bearer_audience"], + auth=profile.metadata.auth, + bearer=input.bearer, + label=input.label, + ) + _reject_local_bearer(input.bearer.get_secret_value() if input.bearer else None) + account = ConnectedAccount( + input.org, + owner, + slot, + generation, + active=True, + connected_at=datetime.now(UTC), + credential_enc=seal(CREDENTIAL_PURPOSE, encode_envelope(envelope)), + ) + _bound_client(account) + return account + + +async def _retry(input: MCPConnectInput, account: ConnectedAccount) -> MCPConnectOutput: + await _validate(account) + profile, envelope = _binding(account) + if ( + input.profile_id != profile.metadata.id + or input.label != envelope.label + or input.bearer != envelope.bearer + ): + raise _Refused("MCP_CONNECTION_REQUEST_CONFLICT") + _bound_client(account) + return MCPConnectOutput(connection=await _entry(account)) + + +async def handle_mcp_connect(input: MCPConnectInput) -> MCPConnectOutput: + async with _errors(): + owner = await _owner(input.org) + _policy() + await _ready() + slot = _slot(input.org, owner, input.request_id) + async with scim.subject_leases([owner]): + async with accounts.account_lease(input.org, owner, slot): + await _owner(input.org, owner) + _policy() + await _ready() + current = await store.get(input.org, owner, slot) + if current is not None: + _row_scope(current, input.org, owner, slot) + return await _retry(input, current) + account = _new_account(input, owner, slot) + if ( + await claims.get(get_client(), accounts._fence_key(account.connection_id)) + is not None + ): + raise _Refused("MCP_CONNECTION_INCOMPLETE") + if ( + await store.mcp_owner_active_count( + input.org, + owner, + maximum=settings.knowledge_mcp_connections_max_per_person, + ) + >= settings.knowledge_mcp_connections_max_per_person + ): + raise _Refused("MCP_CONNECTION_QUOTA") + await _owner(input.org, owner) + _policy() + await _ready() + _binding(account) + # Reserve this nonce before a write can have an uncertain outcome. + await accounts._move_fence(None, account.connection_id) + await _owner(input.org, owner) + _policy() + await _ready() + _binding(account) + await store.put(account) + await _validate(account) + return MCPConnectOutput(connection=await _entry(account)) + + +async def handle_mcp_list(input: MCPListInput) -> MCPListOutput: + async with _errors(): + owner = await _owner(input.org) + scope = ("knowledge.connection.mcp_list", input.org, owner, str(input.limit)) + after = "" + if input.cursor is not None: + anchor, after = decode_bound_cursor(input.cursor, scope) + if anchor != _CURSOR_TIME: + raise _Refused("MCP_CONNECTION_CURSOR_INVALID") + _check_slot(after) + rows = await store.mcp_owner_page(input.org, owner, after=after, limit=input.limit + 1) + for row in rows: + _row_scope(row, input.org, owner) + entries = [await _entry(row) for row in rows[: input.limit]] + cursor = ( + encode_bound_cursor(scope, _CURSOR_TIME, rows[input.limit - 1].kind) + if len(rows) > input.limit + else None + ) + await _owner(input.org, owner) + return MCPListOutput(connections=entries, next_cursor=cursor) + + +async def handle_mcp_inspect(input: MCPInspectInput) -> MCPInspectOutput: + async with _errors(): + owner = await _owner(input.org) + if bool(input.slot) == bool(input.request_id): + raise _Refused("MCP_CONNECTION_SELECTION_INVALID") + slot = _slot(input.org, owner, input.request_id) if input.request_id else input.slot + _check_slot(slot) + account = await store.get(input.org, owner, slot) + if account is None: + incomplete = False + if input.request_id: + key = accounts._fence_key(slot[4:] + "/" + "0" * 32) + incomplete = await claims.get(get_client(), key) is not None + return MCPInspectOutput( + found=False, slot=slot, reconciliation="incomplete" if incomplete else "absent" + ) + _row_scope(account, input.org, owner, slot) + entry = await _entry(account) + await _owner(input.org, owner) + return MCPInspectOutput( + found=True, + slot=slot, + connection=entry, + reconciliation="incomplete" if entry.state == "unavailable" else "present", + ) + + +async def handle_mcp_discover(input: MCPSlotInput) -> MCPDiscoverOutput: + async with _errors(): + owner = await _owner(input.org) + _check_slot(input.slot) + account = await store.get(input.org, owner, input.slot) + if account is None: + raise _Refused("MCP_CONNECTION_UNAVAILABLE") + _row_scope(account, input.org, owner, input.slot) + await _validate(account) + client = _bound_client(account) + async with client: + discovered = await client.discover() + await _validate(account) + config = client.config + mapped_read = config.read is not None and config.read.name in discovered.tools + mapped_search = config.search is not None and config.search.name in discovered.tools + result = MCPDiscoverOutput( + slot=account.kind, + generation=account.connection_id, + resources=discovered.resources, + mapped_read=mapped_read, + mapped_search=mapped_search, + supported_reads=discovered.resources or mapped_read, + limitations=[ + "no_verified_remote_identity", + "no_acl_or_permission_sync_proof", + "no_deletion_or_complete_enumeration_proof", + "no_import_or_publication_grant", + "no_upstream_credential_revocation", + ], + ) + await _validate(account) + return result + + +async def handle_mcp_disconnect(input: MCPSlotInput) -> MCPDisconnectOutput: + async with _errors(): + owner = await _owner(input.org) + _check_slot(input.slot) + async with scim.subject_leases([owner]): + async with accounts.account_lease(input.org, owner, input.slot): + await _owner(input.org, owner) + account = await store.get(input.org, owner, input.slot) + if account is None: + return MCPDisconnectOutput(disconnected=False) + _row_scope(account, input.org, owner, input.slot) + async with asyncio.timeout(settings.knowledge_connected_stop_timeout_s): + await accounts._stop_locked(account) + return MCPDisconnectOutput(disconnected=True) diff --git a/server/knowledge/app/mcp_profile_api.py b/server/knowledge/app/mcp_profile_api.py index 07a3809ff8..26395323b6 100644 --- a/server/knowledge/app/mcp_profile_api.py +++ b/server/knowledge/app/mcp_profile_api.py @@ -12,6 +12,7 @@ ) from server.knowledge.app import connected_accounts as accounts from server.knowledge.app.mcp_profiles import MCPProfileError, load_mcp_profile_catalog +from server.settings import settings # Catalog IDs have no timestamp; the shared cursor carries this fixed keyset anchor. _CURSOR_TIME = datetime(1970, 1, 1, tzinfo=UTC) @@ -43,6 +44,7 @@ async def handle_mcp_profiles(input: MCPProfilesInput) -> MCPProfilesOutput: else None ) return MCPProfilesOutput( + self_service_enabled=settings.knowledge_source_self_service_enabled, profiles=[ MCPProfileEntry( id=item.id, diff --git a/server/knowledge/store/connected_accounts.py b/server/knowledge/store/connected_accounts.py index 60efaaab6f..7b28f3c565 100644 --- a/server/knowledge/store/connected_accounts.py +++ b/server/knowledge/store/connected_accounts.py @@ -189,3 +189,49 @@ async def restore_workers_recent(*, ch: _CHClient | None = None) -> int: if row is None or "n" not in row: raise RuntimeError("connected_restore_offline_unavailable") return int(row["n"]) + + +async def mcp_owner_page( + org: str, subject: str, *, after: str = "", limit: int = 101, ch: _CHClient | None = None +) -> list[ConnectedAccount]: + """Current valid MCP slots for one canonical owner, including stopped markers.""" + if type(limit) is not int or not 1 <= limit <= 101: + raise ValueError("mcp_account_page_bound") + with own_write_reads(): + rows = await (ch or _default_client()).query_all( + f"SELECT {_COLUMNS} FROM {TABLE} FINAL " + "WHERE org = {org:String} AND subject = {subject:String} " + "AND match(kind, {slot_pattern:String}) AND kind > {after:String} " + "ORDER BY kind LIMIT {limit:UInt32}", + params={ + "org": org, + "subject": subject, + "slot_pattern": r"^mcp:[0-9a-f]{32}$", + "after": after, + "limit": limit, + }, + ) + return [_account(dict(row)) for row in rows] + + +async def mcp_owner_active_count( + org: str, subject: str, *, maximum: int, ch: _CHClient | None = None +) -> int: + """Count only to the quota ceiling plus one; the caller holds its owner barrier.""" + if type(maximum) is not int or not 1 <= maximum <= 4096: + raise ValueError("mcp_account_count_bound") + with own_write_reads(): + row = await (ch or _default_client()).query_one( + f"SELECT count() AS n FROM (SELECT 1 FROM {TABLE} FINAL " + "WHERE org = {org:String} AND subject = {subject:String} AND active = 1 " + "AND match(kind, {slot_pattern:String}) LIMIT {limit:UInt32})", + params={ + "org": org, + "subject": subject, + "slot_pattern": r"^mcp:[0-9a-f]{32}$", + "limit": maximum + 1, + }, + ) + if row is None: + raise RuntimeError("mcp_account_count_unavailable") + return int(row["n"]) diff --git a/server/operations/registry.py b/server/operations/registry.py index 4d06fc2e18..5303336d2f 100644 --- a/server/operations/registry.py +++ b/server/operations/registry.py @@ -32,6 +32,8 @@ from server.knowledge.api import ops_conversations as conversations from server.knowledge.api import ops_gaps as knowledge_gaps from server.knowledge.api import ops_knowledge as knowledge +from server.knowledge.api import ops_mcp_connections as knowledge_mcp_connections +from server.knowledge.api import ops_mcp_profiles as knowledge_mcp_profiles 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 @@ -67,6 +69,8 @@ memory_records, knowledge, knowledge_sources, + knowledge_mcp_profiles, + knowledge_mcp_connections, connections, knowledge_source_push, knowledge_gaps, diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 6181f8d93e..9b4af13792 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -2476,6 +2476,11 @@ def _mcp_profiles_size(cls, value: str) -> str: raise ValueError("MCP_PROFILE_INVALID") from None return value + # Allow self-service source registration and credential storage or replacement. + # False refuses those mutations before a probe; existing reads and removal remain available. + knowledge_source_self_service_enabled: bool = True + # Active MCP connection slots one canonical person may hold per organization. + knowledge_mcp_connections_max_per_person: int = Field(default=32, ge=1, le=4096) # Active document sources (knowledge.source.add) one namespace may register; an # add past it is refused with SOURCE_QUOTA. knowledge_sources_max_per_namespace: Annotated[int, LIVE] = Field(default=8, ge=1) @@ -6428,6 +6433,14 @@ class TrackerSettings(BaseModel): "knowledge.source.check": 30000, "knowledge.source.inspect": 400, "knowledge.source.list": 300, + # Verified owner lookup and a cold bounded operator catalog parse; no source request. + "knowledge.source.mcp_profiles": 5000, + # Local owner enrollment/retirement is bounded; discovery also waits for the MCP server. + "knowledge.connection.mcp_connect": 30000, + "knowledge.connection.mcp_disconnect": 30000, + "knowledge.connection.mcp_discover": 30000, + "knowledge.connection.mcp_inspect": 5000, + "knowledge.connection.mcp_list": 5000, "knowledge.source.parse_links": 50, "knowledge.source.remove": 400, "knowledge.source.rotate": 30000, diff --git a/tests/unit/test_mcp_connections.py b/tests/unit/test_mcp_connections.py new file mode 100644 index 0000000000..a9fdc46be5 --- /dev/null +++ b/tests/unit/test_mcp_connections.py @@ -0,0 +1,811 @@ +"""Owner isolation, guarded commits and complete local disconnect without source I/O.""" + +from __future__ import annotations + +import asyncio +import json +import socket +from collections import defaultdict +from collections.abc import AsyncIterator, Iterator +from contextlib import asynccontextmanager +from dataclasses import replace +from types import SimpleNamespace +from typing import Any +from uuid import uuid4 + +import httpx +import jwt +import pytest +from pydantic import SecretStr +from pydantic import ValidationError as ModelError + +from server.auth import reader_identity +from server.auth.context import current_auth_var +from server.auth.jwt import AuthInfo +from server.clients.mcp_source import MCPDiscovery, MCPSourceClient +from server.core import secrets_at_rest +from server.core.errors import LoomServerError +from server.knowledge.api.models_mcp_connections import ( + MCPConnectInput, + MCPInspectInput, + MCPListInput, + MCPSlotInput, +) +from server.knowledge.api.ops_mcp_connections import OPERATIONS +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import mcp_connections as app +from server.knowledge.app import mcp_profiles +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.knowledge.domain.mcp_sources import decode_envelope, encode_envelope +from server.knowledge.store import connected_accounts as store +from server.operations.base import Role +from server.settings import settings + +TOKEN = "synthetic-upstream-secret" + + +def caller(subject: str = "person-a", org: str = "org-a") -> AuthInfo: + return AuthInfo( + subject, org, ("personal",), (Role.VIEWER,), False, issued_at=1000, session_id="session" + ) + + +def request(**changes: Any) -> MCPConnectInput: + return MCPConnectInput( + org="org-a", profile_id="docs", request_id=str(uuid4()), bearer=SecretStr(TOKEN), **changes + ) + + +class World: + def __init__(self) -> None: + self.rows: dict[tuple[str, str, str], ConnectedAccount] = {} + self.history: list[ConnectedAccount] = [] + self.fences: dict[str, str] = {} + self.owners: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock) + self.slots: dict[tuple[str, str, str], asyncio.Lock] = defaultdict(asyncio.Lock) + self.held_owners: set[str] = set() + self.held_slots: set[tuple[str, str, str]] = set() + self.events: list[str] = [] + self.ch = object() + self.fleet = True + self.standing = True + self.fail_write = "" + self.remote_hook: Any = None + self.remote_cancel = False + self.remote_entered = asyncio.Event() + self.closed = 0 + self.resources = True + self.census = 0 + self.settings = SimpleNamespace( + knowledge_source_self_service_enabled=True, + knowledge_mcp_connections_max_per_person=32, + knowledge_connected_stop_timeout_s=3, + trusted_issuers=lambda: {"unit-loom"}, + auth_actually_required=lambda: True, + ) + self.configure() + + def configure(self, *, auth: str = "bearer", **changes: Any) -> None: + config = { + "endpoint": "https://docs.example/mcp", + "bearer_audience": "https://docs.example/audience" if auth == "bearer" else None, + } + row = { + "id": "docs", + "label": "Operator label", + "auth": auth, + "allowed_orgs": ["org-a", "org-b"], + "config": config, + } + row.update(changes) + self.settings.knowledge_source_mcp_profiles_json = json.dumps( + {"version": 1, "profiles": [row]} + ) + + async def get(self, org: str, owner: str, slot: str, **kwargs: Any) -> ConnectedAccount | None: + await asyncio.sleep(0) + return self.rows.get((org, owner, slot)) + + async def put(self, row: ConnectedAccount, **kwargs: Any) -> None: + key = row.org, row.subject, row.kind + assert key in self.held_slots and row.subject in self.held_owners + if self.fail_write == "before": + raise RuntimeError(TOKEN) + self.rows[key] = row + self.history.append(row) + self.events.append("put") + if self.fail_write == "after": + raise RuntimeError(TOKEN) + if self.fail_write == "cancel": + raise asyncio.CancelledError + + async def erase(self, org: str, subjects: list[str], *, kind: str, **kwargs: Any) -> None: + assert len(subjects) == 1 and (org, subjects[0], kind) in self.held_slots + self.history = [ + r for r in self.history if (r.org, r.subject, r.kind) != (org, subjects[0], kind) + ] + self.rows.pop((org, subjects[0], kind), None) + self.events.append("erase") + + async def count(self, org: str, owner: str, *, maximum: int, **kwargs: Any) -> int: + assert owner in self.held_owners + await asyncio.sleep(0) + return min( + sum(r.active for r in self.rows.values() if (r.org, r.subject) == (org, owner)), + maximum + 1, + ) + + async def page( + self, org: str, owner: str, *, after: str, limit: int, **kwargs: Any + ) -> list[ConnectedAccount]: + assert 1 <= limit <= 101 + return sorted( + [ + r + for r in self.rows.values() + if (r.org, r.subject) == (org, owner) and r.kind > after + ], + key=lambda r: r.kind, + )[:limit] + + @asynccontextmanager + async def owner_lease(self, owners: list[str]) -> AsyncIterator[None]: + assert len(owners) == 1 + owner = owners[0] + async with self.owners[owner]: + self.held_owners.add(owner) + try: + yield + finally: + self.held_owners.remove(owner) + + @asynccontextmanager + async def slot_lease( + self, org: str, owner: str, slot: str, **kwargs: Any + ) -> AsyncIterator[None]: + assert owner in self.held_owners + key = org, owner, slot + async with self.slots[key]: + self.held_slots.add(key) + try: + yield + finally: + self.held_slots.remove(key) + + async def claim_get(self, ch: Any, key: str) -> str | None: + assert ch is self.ch + return self.fences.get(key) + + async def claim_swap( + self, ch: Any, key: str, previous: str | None, current: str, expiry: Any + ) -> str | None: + assert ch is self.ch + if self.fences.get(key) == previous: + self.fences[key] = current + return self.fences.get(key) + + async def ready(self, ch: Any, migration: int) -> bool: + assert ch is self.ch and migration == 116 + return self.fleet + + async def canonical(self, org: str, owner: str) -> str: + return owner + + async def identity(self, org: str, owner: str) -> SimpleNamespace | None: + return SimpleNamespace(subject=owner, emails=()) if self.standing else None + + async def spellings(self, org: str, owner: str) -> list[str]: + return [owner] + + async def active(self, org: str, owners: list[str]) -> bool: + return self.standing + + async def managed(self, *args: Any, **kwargs: Any) -> bool: + return False + + async def cutoffs(self, keys: list[str]) -> dict[str, Any]: + return {} + + async def sources(self, org: str, owner: str) -> list[Any]: + return [] + + async def erased(self, org: str, owner: str, kind: str, *, keep_connection: str | None) -> None: + assert all( + not r.credential_enc + for r in self.history + if (r.org, r.subject, r.kind) == (org, owner, kind) + ) + assert self.rows[(org, owner, kind)].active is False + assert self.rows[(org, owner, kind)].connection_id == keep_connection + self.census += 1 + + +def no_io(*args: Any, **kwargs: Any) -> Any: + pytest.fail("unexpected network, database or native provider path") + + +def patch_auth(monkeypatch: pytest.MonkeyPatch, world: World) -> None: + monkeypatch.setattr(accounts, "settings", world.settings) + monkeypatch.setattr(reader_identity, "settings", world.settings) + monkeypatch.setattr(accounts.aliases, "canonical_subject", world.canonical) + monkeypatch.setattr(accounts.aliases, "verified_spellings", world.spellings) + monkeypatch.setattr(accounts, "resolve_reader", world.identity) + monkeypatch.setattr(accounts.store, "account_active", world.active) + monkeypatch.setattr(accounts.scim, "refuses_subject", world.managed) + monkeypatch.setattr(accounts.revocation, "cutoffs", world.cutoffs) + + +@pytest.fixture +def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[World]: + from server.erasure.app import connected_accounts as erasure + + state = World() + patch_auth(monkeypatch, state) + monkeypatch.setattr(app, "settings", state.settings) + monkeypatch.setattr(mcp_profiles, "settings", state.settings) + monkeypatch.setattr(settings, "jwt_secret", "unit-connection-sealing-key") + monkeypatch.setattr(settings, "jwt_secret_previous", "") + monkeypatch.setattr(httpx, "AsyncClient", no_io) + monkeypatch.setattr(socket, "socket", no_io) + monkeypatch.setattr(socket, "getaddrinfo", no_io) + monkeypatch.setattr(accounts, "client", no_io) + monkeypatch.setattr(app, "get_client", lambda: state.ch) + monkeypatch.setattr(accounts, "get_client", lambda: state.ch) + monkeypatch.setattr(store, "get", state.get) + monkeypatch.setattr(store, "put", state.put) + monkeypatch.setattr(store, "erase", state.erase) + monkeypatch.setattr(store, "mcp_owner_page", state.page) + monkeypatch.setattr(store, "mcp_owner_active_count", state.count) + monkeypatch.setattr(accounts, "account_lease", state.slot_lease) + monkeypatch.setattr(app.scim, "subject_leases", state.owner_lease) + monkeypatch.setattr(accounts.claims, "get", state.claim_get) + monkeypatch.setattr(accounts.claims, "swap", state.claim_swap) + monkeypatch.setattr(app.machines, "fleet_at", state.ready) + monkeypatch.setattr(accounts.source_store, "connected_sources", state.sources) + monkeypatch.setattr(erasure, "require_erased", state.erased) + token = current_auth_var.set(caller()) + try: + yield state + finally: + current_auth_var.reset(token) + + +async def connect(world: World, input: MCPConnectInput | None = None): + return await app.handle_mcp_connect(input or request()) + + +@pytest.mark.asyncio +async def test_connect_seals_exact_binding_without_opening_a_client(world: World) -> None: + result = await connect(world) + row = next(iter(world.rows.values())) + envelope = decode_envelope( + secrets_at_rest.unseal(accounts.CREDENTIAL_PURPOSE, row.credential_enc) + ) + assert (envelope.org, envelope.owner, envelope.slot, envelope.generation) == ( + "org-a", + "person-a", + row.kind, + row.connection_id, + ) + assert envelope.bearer is not None and envelope.bearer.get_secret_value() == TOKEN + assert ( + envelope.endpoint == "https://docs.example/mcp" + and envelope.audience == "https://docs.example/audience" + ) + assert row.account_id == row.workspace_id == "" and not row.scopes + assert result.connection.state == "configured" + assert ( + result.connection.compatibility == "unchecked" + and not result.connection.remote_identity_verified + ) + assert TOKEN not in result.model_dump_json() and TOKEN not in repr(row) + assert not world.held_owners and not world.held_slots + + +@pytest.mark.asyncio +async def test_anonymous_profile_accepts_no_bearer(world: World) -> None: + world.configure(auth="none") + with pytest.raises(LoomServerError): + await connect(world) + assert not world.rows + input = request().model_copy(update={"bearer": None}) + assert (await connect(world, input)).connection.state == "configured" + + +@pytest.mark.asyncio +async def test_same_nonce_is_scoped_by_owner_and_org(world: World) -> None: + first_input = request() + first = await connect(world, first_input) + current_auth_var.set(caller("person-b")) + second = await connect(world, first_input) + current_auth_var.set(caller("person-a", "org-b")) + third = await connect(world, first_input.model_copy(update={"org": "org-b"})) + assert len({first.connection.slot, second.connection.slot, third.connection.slot}) == 3 + assert len(world.rows) == 3 + + +@pytest.mark.asyncio +async def test_successful_retry_does_not_replace_generation_or_credential(world: World) -> None: + input = request() + first = await connect(world, input) + row = next(iter(world.rows.values())) + second = await connect(world, input) + assert first == second and len(world.history) == 1 + assert next(iter(world.rows.values())).credential_enc == row.credential_enc + for change in ({"bearer": SecretStr("changed")}, {"label": "Changed"}, {"profile_id": "other"}): + with pytest.raises(LoomServerError): + await connect(world, input.model_copy(update=change)) + assert len(world.history) == 1 + + +@pytest.mark.asyncio +async def test_fresh_slots_share_owner_quota_barrier(world: World) -> None: + world.settings.knowledge_mcp_connections_max_per_person = 1 + results = await asyncio.gather(connect(world), connect(world), return_exceptions=True) + assert sum(not isinstance(result, BaseException) for result in results) == 1 + assert len(world.rows) == 1 + assert any("QUOTA" in str(result) for result in results if isinstance(result, BaseException)) + assert not world.held_owners and not world.held_slots + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["policy", "fleet", "standing", "org"]) +async def test_enrollment_refuses_before_effects(world: World, mode: str) -> None: + if mode == "policy": + world.settings.knowledge_source_self_service_enabled = False + elif mode == "fleet": + world.fleet = False + elif mode == "standing": + world.standing = False + else: + current_auth_var.set(caller(org="org-b")) + with pytest.raises(LoomServerError): + await connect(world) + assert not world.history and not world.fences + + +@pytest.mark.asyncio +@pytest.mark.parametrize("when", ["before", "after", "cancel"]) +async def test_uncertain_save_is_inspectable_and_never_silently_replaced( + world: World, when: str +) -> None: + input = request() + world.fail_write = when + with pytest.raises((LoomServerError, asyncio.CancelledError)) as caught: + await connect(world, input) + assert TOKEN not in str(caught.value) + world.fail_write = "" + result = await app.handle_mcp_inspect(MCPInspectInput(org="org-a", request_id=input.request_id)) + if when == "before": + assert not result.found and result.reconciliation == "incomplete" + with pytest.raises(LoomServerError, match="INCOMPLETE"): + await connect(world, input) + assert not world.rows + else: + assert result.found and result.reconciliation == "present" + saved = next(iter(world.rows.values())) + assert (await connect(world, input)).connection.generation == saved.connection_id + assert len(world.history) == 1 + assert not world.held_owners and not world.held_slots + + +@pytest.mark.asyncio +async def test_fence_only_partial_save_refuses_an_alternate_generation(world: World) -> None: + input = request() + slot = app._slot("org-a", "person-a", input.request_id) + world.fences[accounts._fence_key(slot[4:] + "/" + "0" * 32)] = slot[4:] + "/1" + "d" * 31 + with pytest.raises(LoomServerError, match="INCOMPLETE"): + await connect(world, input) + result = await app.handle_mcp_inspect(MCPInspectInput(org="org-a", request_id=input.request_id)) + assert not result.found and result.reconciliation == "incomplete" and not world.rows + + +@pytest.mark.asyncio +async def test_local_jwts_including_expired_are_never_forwarded(world: World) -> None: + for claims in ({"iss": "unit-loom"}, {"iss": "unit-loom", "exp": 1}): + token = jwt.encode(claims, "unit-token-signing-key-that-is-long-enough", algorithm="HS256") + with pytest.raises(LoomServerError, match="LOCAL_CREDENTIAL"): + await connect(world, request().model_copy(update={"bearer": SecretStr(token)})) + assert not world.rows + + +@pytest.mark.asyncio +async def test_list_inspect_and_disconnect_are_owner_scoped_and_policy_independent( + world: World, +) -> None: + own = (await connect(world)).connection.slot + current_auth_var.set(caller("person-b")) + foreign = (await connect(world)).connection.slot + current_auth_var.set(caller()) + world.settings.knowledge_source_self_service_enabled = False + listed = await app.handle_mcp_list(MCPListInput(org="org-a")) + assert [entry.slot for entry in listed.connections] == [own] + hidden = await app.handle_mcp_inspect(MCPInspectInput(org="org-a", slot=foreign)) + assert not hidden.found and hidden.reconciliation == "absent" + assert not ( + await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=foreign)) + ).disconnected + ended = await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=own)) + assert ended.disconnected and not ended.upstream_revoked + assert world.census == 1 and world.events[-2:] == ["erase", "put"] + assert not world.rows[("org-a", "person-a", own)].credential_enc + assert world.rows[("org-a", "person-b", foreign)].active + world.settings.knowledge_source_self_service_enabled = True + assert ( + await app.handle_mcp_inspect(MCPInspectInput(org="org-a", slot=own)) + ).connection.state == "stopped" + + +@pytest.mark.asyncio +async def test_disconnect_runs_complete_stop_again_after_census_failure( + world: World, monkeypatch: pytest.MonkeyPatch +) -> None: + from server.erasure.app import connected_accounts as erasure + + slot = (await connect(world)).connection.slot + + async def fail(*args: Any, **kwargs: Any) -> None: + raise RuntimeError(TOKEN) + + monkeypatch.setattr(erasure, "require_erased", fail) + with pytest.raises(LoomServerError): + await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=slot)) + assert not world.rows[("org-a", "person-a", slot)].active + monkeypatch.setattr(erasure, "require_erased", world.erased) + assert (await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=slot))).disconnected + assert world.census == 1 + + +@pytest.mark.asyncio +async def test_stopped_nonce_never_revives(world: World) -> None: + input = request() + slot = (await connect(world, input)).connection.slot + await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=slot)) + with pytest.raises(LoomServerError): + await connect(world, input) + assert not world.rows[("org-a", "person-a", slot)].active + + +def mock_protocol(monkeypatch: pytest.MonkeyPatch, world: World) -> None: + async def enter(client: MCPSourceClient) -> MCPSourceClient: + assert not world.held_owners and not world.held_slots + await client.validate_access() + return client + + async def exit(client: MCPSourceClient, *args: Any) -> None: + world.closed += 1 + + async def discover(client: MCPSourceClient) -> MCPDiscovery: + await client.validate_access() + world.remote_entered.set() + if world.remote_cancel: + await asyncio.Future() + if world.remote_hook is not None: + world.remote_hook() + await client.validate_access() + return MCPDiscovery(world.resources, ()) + + monkeypatch.setattr(MCPSourceClient, "__aenter__", enter) + monkeypatch.setattr(MCPSourceClient, "__aexit__", exit) + monkeypatch.setattr(MCPSourceClient, "discover", discover) + + +@pytest.mark.asyncio +async def test_discover_uses_real_factory_binding_and_returns_only_normalized_capabilities( + world: World, monkeypatch: pytest.MonkeyPatch +) -> None: + slot = (await connect(world)).connection.slot + mock_protocol(monkeypatch, world) + result = await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot)) + assert ( + result.resources + and result.supported_reads + and not result.mapped_read + and not result.mapped_search + ) + assert not result.remote_identity_verified and world.closed == 1 + assert TOKEN not in result.model_dump_json() and "endpoint" not in result.model_dump_json() + world.resources = False + result = await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot)) + assert not result.supported_reads + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "drift", ["owner", "org", "generation", "endpoint", "audience", "profile", "digest"] +) +async def test_drift_refuses_before_entering_remote_context( + world: World, monkeypatch: pytest.MonkeyPatch, drift: str +) -> None: + slot = (await connect(world)).connection.slot + key = "org-a", "person-a", slot + row = world.rows[key] + envelope = decode_envelope( + secrets_at_rest.unseal(accounts.CREDENTIAL_PURPOSE, row.credential_enc) + ) + changes = { + "owner": {"owner": "person-b"}, + "org": {"org": "org-b"}, + "generation": {"generation": "a" * 32 + "/1" + "b" * 31}, + "endpoint": {"endpoint": "https://other.example/mcp"}, + "audience": {"audience": "https://docs.example/other"}, + "profile": {"profile_id": "other"}, + "digest": {"profile_sha256": "0" * 64}, + } + envelope = envelope.model_copy(update=changes[drift]) + world.rows[key] = replace( + row, + credential_enc=secrets_at_rest.seal(accounts.CREDENTIAL_PURPOSE, encode_envelope(envelope)), + ) + monkeypatch.setattr(MCPSourceClient, "__aenter__", no_io) + with pytest.raises(LoomServerError): + await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot)) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change", ["standing", "fleet", "profile", "stopped", "generation"]) +async def test_mandatory_validator_rechecks_changes_around_remote_work( + world: World, monkeypatch: pytest.MonkeyPatch, change: str +) -> None: + slot = (await connect(world)).connection.slot + key = "org-a", "person-a", slot + + def mutate() -> None: + if change == "standing": + world.standing = False + elif change == "fleet": + world.fleet = False + elif change == "profile": + world.configure(allowed_orgs=[]) + elif change == "stopped": + world.rows[key] = replace(world.rows[key], active=False) + else: + world.rows[key] = replace( + world.rows[key], + connection_id=accounts._next_connection(world.rows[key].connection_id), + ) + + mock_protocol(monkeypatch, world) + world.remote_hook = mutate + with pytest.raises(LoomServerError): + await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot)) + assert world.closed == 1 + + +@pytest.mark.asyncio +async def test_cancelled_discovery_closes_context_and_releases_no_writer_lease( + world: World, monkeypatch: pytest.MonkeyPatch +) -> None: + slot = (await connect(world)).connection.slot + mock_protocol(monkeypatch, world) + world.remote_cancel = True + task = asyncio.create_task(app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot))) + await world.remote_entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert task.done() and world.closed == 1 and not world.held_owners and not world.held_slots + + +@pytest.mark.asyncio +async def test_common_cursors_bind_owner_org_and_limit(world: World) -> None: + await connect(world) + await connect(world) + first = await app.handle_mcp_list(MCPListInput(org="org-a", limit=1)) + assert first.next_cursor + second = await app.handle_mcp_list(MCPListInput(org="org-a", limit=1, cursor=first.next_cursor)) + assert second.connections[0].slot != first.connections[0].slot and second.next_cursor is None + for org, owner, limit in ( + ("org-a", "person-b", 1), + ("org-b", "person-a", 1), + ("org-a", "person-a", 2), + ): + current_auth_var.set(caller(owner, org)) + with pytest.raises(LoomServerError): + await app.handle_mcp_list(MCPListInput(org=org, limit=limit, cursor=first.next_cursor)) + + +def test_credentials_and_labels_are_omitted_from_audits_and_repr() -> None: + input = request().model_copy(update={"label": "owner-private-label"}) + assert TOKEN not in repr(input) and "owner-private-label" not in repr(input) + assert "bearer" not in input.model_dump() + schema = MCPConnectInput.model_json_schema() + secret = next(x for x in schema["properties"]["bearer"]["anyOf"] if x.get("type") == "string") + assert secret["format"] == "password" and secret["writeOnly"] + connect_op = next(op for op in OPERATIONS if op.name.endswith("mcp_connect")) + assert connect_op.audit and connect_op.writes and not connect_op.idempotent + output = SimpleNamespace(connection=SimpleNamespace(slot="mcp:" + "a" * 32)) + assert connect_op.audit_subject is not None + audit = connect_op.audit_subject(input, output) + assert audit == {"slot": output.connection.slot, "profile_id": "docs"} + assert TOKEN not in json.dumps(audit) and "owner-private-label" not in json.dumps(audit) + for field in ("owner", "endpoint", "audience", "tools", "headers"): + with pytest.raises(ModelError): + MCPConnectInput(**{**input.model_dump(), field: "injected"}) + + +@pytest.mark.asyncio +async def test_store_queries_are_bounded_owner_scoped_and_parameterized() -> None: + class CH: + async def query_all(self, sql: str, *, params: dict[str, Any]): + assert ( + " FINAL " in sql + and "org = {org:String}" in sql + and "subject = {subject:String}" in sql + ) + assert "match(kind, {slot_pattern:String})" in sql and "LIMIT {limit:UInt32}" in sql + assert "credential_enc" in sql and "ORDER BY kind" in sql + assert params == { + "org": "owner'org", + "subject": "person", + "slot_pattern": r"^mcp:[0-9a-f]{32}$", + "after": "", + "limit": 2, + } + return [] + + async def query_one(self, sql: str, *, params: dict[str, Any]): + assert "count()" in sql and "active = 1" in sql and "LIMIT {limit:UInt32}" in sql + assert "credential_enc" not in sql and params["limit"] == 33 + assert params["org"] == "owner'org" and params["subject"] == "person" + return {"n": 32} + + assert await store.mcp_owner_page("owner'org", "person", limit=2, ch=CH()) == [] + assert await store.mcp_owner_active_count("owner'org", "person", maximum=32, ch=CH()) == 32 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change", ["policy", "standing", "fleet", "profile"]) +async def test_commit_rechecks_inside_the_owner_barrier( + world: World, monkeypatch: pytest.MonkeyPatch, change: str +) -> None: + @asynccontextmanager + async def barrier(owners: list[str]) -> AsyncIterator[None]: + async with world.owner_lease(owners): + if change == "policy": + world.settings.knowledge_source_self_service_enabled = False + elif change == "standing": + world.standing = False + elif change == "fleet": + world.fleet = False + else: + world.configure(allowed_orgs=[]) + yield + + monkeypatch.setattr(app.scim, "subject_leases", barrier) + with pytest.raises(LoomServerError): + await connect(world) + assert not world.history and not world.fences + + +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["list", "inspect", "discover", "disconnect"]) +async def test_unexpected_store_scope_never_reveals_foreign_metadata_or_stops_it( + world: World, monkeypatch: pytest.MonkeyPatch, operation: str +) -> None: + own_slot = (await connect(world)).connection.slot + current_auth_var.set(caller("person-b")) + foreign_slot = (await connect(world)).connection.slot + foreign = world.rows[("org-a", "person-b", foreign_slot)] + current_auth_var.set(caller()) + + async def wrong_get(*args: Any, **kwargs: Any): + return foreign + + async def wrong_page(*args: Any, **kwargs: Any): + return [foreign] + + monkeypatch.setattr(store, "get", wrong_get) + monkeypatch.setattr(store, "mcp_owner_page", wrong_page) + with pytest.raises(LoomServerError, match="^MCP_CONNECTION_UNAVAILABLE$"): + if operation == "list": + await app.handle_mcp_list(MCPListInput(org="org-a")) + elif operation == "inspect": + await app.handle_mcp_inspect(MCPInspectInput(org="org-a", slot=own_slot)) + elif operation == "discover": + await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=own_slot)) + else: + await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=own_slot)) + assert world.rows[("org-a", "person-b", foreign_slot)].active + assert world.census == 0 + + +@pytest.mark.asyncio +async def test_approval_drift_is_visible_local_metadata_and_does_not_disable_removal( + world: World, +) -> None: + slot = (await connect(world)).connection.slot + world.configure(allowed_orgs=[]) + inspected = await app.handle_mcp_inspect(MCPInspectInput(org="org-a", slot=slot)) + assert inspected.connection is not None and inspected.connection.state == "approval_drift" + assert ( + inspected.connection.profile_id == "docs" + and inspected.connection.compatibility == "unchecked" + ) + with pytest.raises(LoomServerError): + await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot)) + assert (await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=slot))).disconnected + + +@pytest.mark.asyncio +async def test_unreadable_envelope_is_unavailable_but_complete_stop_still_works( + world: World, +) -> None: + slot = (await connect(world)).connection.slot + key = "org-a", "person-a", slot + world.rows[key] = replace(world.rows[key], credential_enc="unreadable") + inspected = await app.handle_mcp_inspect(MCPInspectInput(org="org-a", slot=slot)) + assert inspected.connection is not None and inspected.connection.state == "unavailable" + assert inspected.connection.profile_id is None and inspected.connection.label is None + with pytest.raises(LoomServerError): + await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot)) + assert (await app.handle_mcp_disconnect(MCPSlotInput(org="org-a", slot=slot))).disconnected + assert world.census == 1 + + +@pytest.mark.asyncio +async def test_fence_missing_after_save_is_not_reported_usable(world: World) -> None: + slot = (await connect(world)).connection.slot + world.fences.clear() + result = await app.handle_mcp_inspect(MCPInspectInput(org="org-a", slot=slot)) + assert result.reconciliation == "incomplete" and result.connection.state == "unavailable" + with pytest.raises(LoomServerError): + await app.handle_mcp_discover(MCPSlotInput(org="org-a", slot=slot)) + + +@pytest.mark.asyncio +async def test_missing_or_service_identity_never_enrolls(world: World) -> None: + for auth in (None, replace(caller(), is_service_account=True)): + current_auth_var.set(auth) + with pytest.raises(LoomServerError): + await connect(world) + assert not world.rows and not world.fences + + +@pytest.mark.asyncio +async def test_malformed_request_id_returns_fixed_redacted_error(world: World) -> None: + with pytest.raises(LoomServerError) as caught: + await connect(world, request().model_copy(update={"request_id": TOKEN})) + assert str(caught.value) == "MCP_CONNECTION_UNAVAILABLE" + assert caught.value.__suppress_context__ and TOKEN not in repr(caught.value) + assert not world.rows + + +@pytest.mark.asyncio +async def test_uncertain_write_reserves_nonce_before_any_row_becomes_visible(world: World) -> None: + input = request() + world.fail_write = "before" + with pytest.raises(LoomServerError): + await connect(world, input) + assert not world.rows + inspected = await app.handle_mcp_inspect( + MCPInspectInput(org="org-a", request_id=input.request_id) + ) + assert inspected.reconciliation == "incomplete" + world.fail_write = "" + with pytest.raises(LoomServerError, match="INCOMPLETE"): + await connect(world, input) + assert not world.rows + + +def test_serialized_validation_errors_never_echo_malformed_secret_input() -> None: + with pytest.raises(ModelError) as caught: + MCPConnectInput.model_validate( + { + "org": "org-a", + "profile_id": "docs", + "request_id": "request", + "bearer": {"mistyped-secret": TOKEN}, + "label": "owner-private-label", + } + ) + serialized = caught.value.json(include_url=False) + assert TOKEN not in serialized + assert "owner-private-label" not in serialized + assert "MCP_CONNECTION_INPUT_INVALID" in serialized + + +def test_unexpected_secret_on_a_read_input_is_also_redacted() -> None: + with pytest.raises(ModelError) as caught: + MCPSlotInput.model_validate({"org": "org-a", "slot": "mcp:" + "a" * 32, "bearer": TOKEN}) + assert TOKEN not in caught.value.json(include_url=False) diff --git a/tests/unit/test_mcp_profile_api.py b/tests/unit/test_mcp_profile_api.py index e524168b7f..7cf35cbf01 100644 --- a/tests/unit/test_mcp_profile_api.py +++ b/tests/unit/test_mcp_profile_api.py @@ -67,6 +67,7 @@ def auth(subject: str = "person-a", org: str = "org-a", **changes: Any) -> AuthI def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]: fake = SimpleNamespace( knowledge_source_mcp_profiles_json="", + knowledge_source_self_service_enabled=True, jwt_secret="unit-profile-cursor-key", auth_actually_required=lambda: True, ) @@ -100,6 +101,7 @@ async def cutoffs(keys: list[str]) -> dict[str, int]: monkeypatch.setattr(mcp_profiles, "MCPSourceClient", refuse) monkeypatch.setattr(accounts.store, "owned", refuse) monkeypatch.setattr(mcp_profiles, "settings", fake) + monkeypatch.setattr(mcp_profile_api, "settings", fake, raising=False) monkeypatch.setattr(settings_module, "settings", fake) monkeypatch.setattr(accounts, "settings", fake) monkeypatch.setattr(reader_identity, "settings", fake) @@ -129,7 +131,11 @@ def test_setting_is_empty_bounded_and_not_live() -> None: @pytest.mark.asyncio async def test_empty_setting_returns_no_profiles(world: SimpleNamespace) -> None: result = await handle_mcp_profiles(MCPProfilesInput(org="org-a")) - assert result.model_dump() == {"profiles": [], "next_cursor": None} + assert result.model_dump() == { + "profiles": [], + "next_cursor": None, + "self_service_enabled": True, + } assert world.seen == [("org-a", "person-a")] @@ -367,7 +373,11 @@ async def test_query_matches_only_eligible_id_or_label(world: SimpleNamespace) - assert [item.id for item in result.profiles] == ["alpha"] assert result.next_cursor is None missing = await handle_mcp_profiles(MCPProfilesInput(org="org-a", query="hidden")) - assert missing.model_dump() == {"profiles": [], "next_cursor": None} + assert missing.model_dump() == { + "profiles": [], + "next_cursor": None, + "self_service_enabled": True, + } @pytest.mark.asyncio @@ -380,3 +390,15 @@ async def test_signed_cursor_does_not_preserve_a_revoked_identity(world: SimpleN with pytest.raises(LoomServerError) as caught: await handle_mcp_profiles(MCPProfilesInput(org="org-a", limit=1, cursor=first.next_cursor)) assert "MCP_PROFILE_INVALID" not in str(caught.value) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("enabled", [True, False]) +async def test_operator_registration_policy_is_visible_without_hiding_approved_metadata( + world: SimpleNamespace, enabled: bool +) -> None: + configure(world, profile("approved", ["org-a"])) + world.settings.knowledge_source_self_service_enabled = enabled + result = await handle_mcp_profiles(MCPProfilesInput(org="org-a")) + assert result.self_service_enabled is enabled + assert [item.id for item in result.profiles] == ["approved"] From ca796ee338c0f5be1ed26715c75111c7069ebf1c Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 02:15:18 +0000 Subject: [PATCH 14/30] Bind SCIM lifecycle tests to their strict source inventory store Signed-off-by: zlareb1 --- docs/architecture/mcp-source-lifecycle.md | 1 - tests/unit/test_scim.py | 17 ++++++++++++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/docs/architecture/mcp-source-lifecycle.md b/docs/architecture/mcp-source-lifecycle.md index 98268ec948..d327872ff5 100644 --- a/docs/architecture/mcp-source-lifecycle.md +++ b/docs/architecture/mcp-source-lifecycle.md @@ -73,7 +73,6 @@ preserved. This scoped deletion path shares per-owner lifecycle primitives with restore; it never invokes deployment-wide offline restore. Remote revocation follows all local cleanup. - The credential-free recovery marker retains an already inventoried registration generation: the current account's registration, or an exact-owner historical registration when no account survives. It stays inactive and contains no credential, diff --git a/tests/unit/test_scim.py b/tests/unit/test_scim.py index 97f1a7e0c0..bbd9b84975 100644 --- a/tests/unit/test_scim.py +++ b/tests/unit/test_scim.py @@ -260,6 +260,15 @@ async def query_one(self, sql: str, params: dict[str, Any] | None = None) -> Any return row async def query_all(self, sql: str, params: dict[str, Any]) -> list[dict[str, Any]]: + if sql == ( + "SELECT DISTINCT org, owner_subject, " + "if(credential_mode = 'mcp' OR source_kind = 'mcp', connection_slot, source_kind) AS slot " + "FROM loom.knowledge_sources WHERE " + "(credential_mode IN ('connected', 'mcp') OR source_kind = 'mcp') " + "ORDER BY org, owner_subject, slot LIMIT {limit:UInt64}" + ): + assert params == {"limit": settings.knowledge_connected_registry_scan_limit + 1} + return [] if sql == ( "SELECT org, subject, kind, connection_id, account_id, workspace_id, " "account_email_enc, credential_enc, scopes, active, refresh_id, connected_at, " @@ -323,13 +332,16 @@ async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: class _World: """The tables, the real revocation writes and reads over them, and the audit log.""" - def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + def _tables(self) -> None: self.accounts: dict[str, list[str]] = {} # email -> subjects it reaches self.elsewhere: dict[str, list[str]] = {} # subject -> other orgs it is in self.reached_in: dict[str, list[str]] = {} # subject -> orgs its email reaches it in self.table = _Table(self.accounts, self.elsewhere, self.reached_in) self.audits: list[tuple[str, dict[str, Any]]] = [] self.revoked_at_audit: list[dict[str, Any]] = [] # SCIM's revocations as each audit lands + + def __init__(self, monkeypatch: pytest.MonkeyPatch) -> None: + self._tables() self.claim_limit: int | None = None # names held at once before a claim runs out self.claims: dict[tuple[str, str], asyncio.Lock] = {} # one holder a name, as a lease self.leases: list[str] = [] @@ -380,6 +392,9 @@ async def no_refresh() -> None: monkeypatch.setattr(settings, "scim_token", _TOKEN) monkeypatch.setattr(scim, "get_client", lambda: self.table) monkeypatch.setattr(ch, "get_client", lambda: self.table) + from server.knowledge.app import connected_accounts + + monkeypatch.setattr(connected_accounts, "get_client", lambda: self.table) monkeypatch.setattr(scim, "_held", held) monkeypatch.setattr(grant_claims, "service_account_change", name_claim) monkeypatch.setattr(revocation, "asyncio", SimpleNamespace(sleep=no_wait)) From e9d2e2ee8fbd77bbdbdef9fe52aa7fa9dd9162bd Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 02:22:20 +0000 Subject: [PATCH 15/30] Apply configured MCP contract admission limits Signed-off-by: zlareb1 --- docs/architecture/mcp-source-lifecycle.md | 8 +++ scripts/gates/mcp_source_lifecycle.py | 3 +- server/knowledge/app/mcp_contracts.py | 52 +++++++++++++++ server/knowledge/domain/mcp_sources.py | 21 ++---- server/settings/catalog.py | 6 ++ tests/unit/test_mcp_contract_limits.py | 79 +++++++++++++++++++++++ tests/unit/test_mcp_source_contract.py | 3 +- 7 files changed, 155 insertions(+), 17 deletions(-) create mode 100644 server/knowledge/app/mcp_contracts.py create mode 100644 tests/unit/test_mcp_contract_limits.py diff --git a/docs/architecture/mcp-source-lifecycle.md b/docs/architecture/mcp-source-lifecycle.md index d327872ff5..5ae8288cb4 100644 --- a/docs/architecture/mcp-source-lifecycle.md +++ b/docs/architecture/mcp-source-lifecycle.md @@ -87,6 +87,14 @@ recovery work; it grants no checkout authority. Retirement and all raw-history censuses must finish before the recovery row disappears. Retrying neither adds a registration nor skips a historical generation or its prefix validation. +Deployment admission limits live in the settings catalog: sealed plaintext bytes, +selected identities per source and UTF-8 bytes per selected identity. The app codecs +apply these bounds when writing and reading contracts. The pure version-one wire +models retain their fixed ceilings, so configuration can narrow admission without +accepting a format another lifecycle-aware build cannot parse. Lowering a limit +refuses an oversized stored contract; lifecycle preservation and erasure still use +its unchanged raw columns. The configured codecs create the hosted sealed fixture. + Disconnect and explicit erasure retain their existing meanings. Local bearer removal does not prove remote token revocation. Restore is destructive offline lifecycle work with fencing and a final census; it is not a reconfiguration or upgrade tool. diff --git a/scripts/gates/mcp_source_lifecycle.py b/scripts/gates/mcp_source_lifecycle.py index 96c9040083..56efcbdc78 100644 --- a/scripts/gates/mcp_source_lifecycle.py +++ b/scripts/gates/mcp_source_lifecycle.py @@ -200,7 +200,8 @@ def prepare(self) -> None: from server.core.secrets_at_rest import seal from server.knowledge.app import connected_accounts as accounts from server.knowledge.domain.connected_accounts import ConnectedAccount - from server.knowledge.domain.mcp_sources import ConnectionEnvelope, encode_envelope + from server.knowledge.app.mcp_contracts import encode_envelope + from server.knowledge.domain.mcp_sources import ConnectionEnvelope a, b = self.orgs owners = [ diff --git a/server/knowledge/app/mcp_contracts.py b/server/knowledge/app/mcp_contracts.py new file mode 100644 index 0000000000..be2d699e16 --- /dev/null +++ b/server/knowledge/app/mcp_contracts.py @@ -0,0 +1,52 @@ +"""Apply deployment admission limits around the pure versioned wire codecs.""" + +from server.knowledge.domain import mcp_sources as wire +from server.knowledge.domain.mcp_sources import ( + ConnectionEnvelope, + MCPSourceContractError, + SourceContract, +) +from server.settings import settings + + +def _envelope_size(value: str) -> None: + try: + exceeds = len(value.encode("utf-8")) > settings.knowledge_mcp_envelope_max_bytes + except (ValueError, TypeError, AttributeError): + raise MCPSourceContractError() from None + if exceeds: + raise MCPSourceContractError() + + +def encode_envelope(envelope: ConnectionEnvelope) -> str: + encoded = wire.encode_envelope(envelope) + _envelope_size(encoded) + return encoded + + +def decode_envelope(plaintext: str) -> ConnectionEnvelope: + _envelope_size(plaintext) + return wire.decode_envelope(plaintext) + + +def validate_source_contract(contract: SourceContract) -> None: + try: + contract = SourceContract.model_validate(contract) + except (ValueError, TypeError, RecursionError): + raise MCPSourceContractError() from None + if len(contract.resources) > settings.knowledge_mcp_selected_resources_max or any( + len(resource.id.encode("utf-8")) > settings.knowledge_mcp_resource_id_max_bytes + for resource in contract.resources + ): + raise MCPSourceContractError() + + +def encode_source(contract: SourceContract) -> tuple[str, str]: + validate_source_contract(contract) + return wire.encode_source(contract) + + +def decode_source(config_json: str, items_json: str) -> SourceContract: + contract = wire.decode_source(config_json, items_json) + validate_source_contract(contract) + return contract diff --git a/server/knowledge/domain/mcp_sources.py b/server/knowledge/domain/mcp_sources.py index 572f701fc2..8cc317ff2c 100644 --- a/server/knowledge/domain/mcp_sources.py +++ b/server/knowledge/domain/mcp_sources.py @@ -17,11 +17,6 @@ model_validator, ) -MAX_ENVELOPE_BYTES = 32 * 1024 -MAX_RESOURCES = 1000 -MAX_RESOURCE_BYTES = 2048 -_MAX_ITEMS_BYTES = MAX_RESOURCES * (2 * MAX_RESOURCE_BYTES + 64) + 2 - class MCPSourceContractError(ValueError): """A public codec failure contains no supplied payload or credential.""" @@ -33,7 +28,7 @@ def __init__(self) -> None: def _identifier(value: str) -> str: if ( not value.strip() - or len(value.encode("utf-8")) > MAX_RESOURCE_BYTES + or len(value.encode("utf-8")) > 2048 or any(unicodedata.category(char) == "Cc" for char in value) ): raise ValueError("invalid identifier") @@ -121,9 +116,7 @@ class SourceContract(_ContractModel): profile_sha256: _Digest mode: Literal["live", "snapshot", "selected_refresh"] reader_policy: Literal["owner_only", "collection_copy"] - resources: Annotated[ - tuple[ResourceIdentity, ...], Field(min_length=1, max_length=MAX_RESOURCES) - ] + resources: Annotated[tuple[ResourceIdentity, ...], Field(min_length=1, max_length=1000)] @field_validator("resources") @classmethod @@ -155,14 +148,14 @@ def encode_envelope(envelope: ConnectionEnvelope) -> str: payload = envelope.model_dump(mode="json") if envelope.bearer is not None: payload["bearer"] = envelope.bearer.get_secret_value() - return _encode(payload, MAX_ENVELOPE_BYTES) + return _encode(payload, 32768) except (ValueError, TypeError, RecursionError): raise MCPSourceContractError() from None def decode_envelope(plaintext: str) -> ConnectionEnvelope: try: - return ConnectionEnvelope.model_validate_json(_bounded_text(plaintext, MAX_ENVELOPE_BYTES)) + return ConnectionEnvelope.model_validate_json(_bounded_text(plaintext, 32768)) except (ValueError, TypeError, RecursionError): raise MCPSourceContractError() from None @@ -199,7 +192,7 @@ def encode_source(contract: SourceContract) -> tuple[str, str]: contract = SourceContract.model_validate(contract) config = contract.model_dump(mode="json", exclude={"resources"}) items = [resource.model_dump(mode="json") for resource in contract.resources] - return _encode(config, MAX_ENVELOPE_BYTES), _encode(items, _MAX_ITEMS_BYTES) + return _encode(config, 32768), _encode(items, 1000 * (2 * 2048 + 64) + 2) except (ValueError, TypeError, RecursionError): raise MCPSourceContractError() from None @@ -207,8 +200,8 @@ def encode_source(contract: SourceContract) -> tuple[str, str]: def decode_source(config_json: str, items_json: str) -> SourceContract: """Join the two stored columns; this codec admits only the known contract version.""" try: - config = json.loads(_bounded_text(config_json, MAX_ENVELOPE_BYTES)) - items = json.loads(_bounded_text(items_json, _MAX_ITEMS_BYTES)) + config = json.loads(_bounded_text(config_json, 32768)) + items = json.loads(_bounded_text(items_json, 1000 * (2 * 2048 + 64) + 2)) if not isinstance(config, dict) or not isinstance(items, list) or "resources" in config: raise ValueError("invalid source columns") return SourceContract.model_validate({**config, "resources": tuple(items)}) diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 9b4af13792..22b7d5d16a 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -2450,6 +2450,12 @@ class KnowledgeSettings(BaseModel): knowledge_connected_lease_ttl_s: float = Field(default=60.0, gt=0) # Seconds a connection change waits for another holder's account-generation lease. knowledge_connected_lease_wait_s: float = Field(default=5.0, ge=0) + # Maximum sealed MCP plaintext bytes admitted by this deployment, up to the v1 wire ceiling. + knowledge_mcp_envelope_max_bytes: int = Field(default=32768, ge=1024, le=32768) + # Maximum explicitly selected MCP identities per source, without implicit recursion. + knowledge_mcp_selected_resources_max: int = Field(default=1000, ge=1, le=1000) + # Maximum UTF-8 bytes in one selected MCP identity, up to the v1 wire ceiling. + knowledge_mcp_resource_id_max_bytes: int = Field(default=2048, ge=1, le=2048) # Maximum complete owner scan; exceeding it refuses instead of stopping a subset. knowledge_connected_registry_scan_limit: int = Field(default=4096, ge=1) # Registrations per page during root-secret resealing. diff --git a/tests/unit/test_mcp_contract_limits.py b/tests/unit/test_mcp_contract_limits.py new file mode 100644 index 0000000000..c3beb19d72 --- /dev/null +++ b/tests/unit/test_mcp_contract_limits.py @@ -0,0 +1,79 @@ +"""Configured admission bounds apply to stored envelopes and selected identities.""" + +from types import SimpleNamespace + +import pytest +from pydantic import SecretStr + +from server.knowledge.app import mcp_contracts +from server.knowledge.domain.mcp_sources import ( + ConnectionEnvelope, + MCPSourceContractError, + ResourceIdentity, + SourceContract, +) +from server.knowledge.domain.mcp_sources import encode_envelope as wire_envelope + + +@pytest.fixture +def limits(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + values = SimpleNamespace( + knowledge_mcp_envelope_max_bytes=1024, + knowledge_mcp_selected_resources_max=1, + knowledge_mcp_resource_id_max_bytes=8, + ) + monkeypatch.setattr(mcp_contracts, "settings", values) + return values + + +def contract(*identities: str) -> SourceContract: + return SourceContract( + version=1, + slot="mcp:" + "a" * 32, + generation="b" * 32 + "/1" + "c" * 31, + profile_id="approved", + profile_sha256="d" * 64, + mode="snapshot", + reader_policy="owner_only", + resources=tuple(ResourceIdentity(type="resource", id=i) for i in identities), + ) + + +def test_selection_count_is_an_operator_bound(limits: SimpleNamespace) -> None: + with pytest.raises(MCPSourceContractError, match="^MCP_SOURCE_CONTRACT_INVALID$"): + mcp_contracts.encode_source(contract("first", "second")) + + +def test_resource_identity_bound_counts_utf8_bytes(limits: SimpleNamespace) -> None: + mcp_contracts.encode_source(contract("é" * 4)) + with pytest.raises(MCPSourceContractError): + mcp_contracts.encode_source(contract("é" * 5)) + + +def test_reading_a_stored_selection_revalidates_current_limits(limits: SimpleNamespace) -> None: + config, items = mcp_contracts.encode_source(contract("selected")) + limits.knowledge_mcp_resource_id_max_bytes = 4 + with pytest.raises(MCPSourceContractError): + mcp_contracts.decode_source(config, items) + + +def test_envelope_bytes_are_an_operator_bound_on_both_directions(limits: SimpleNamespace) -> None: + envelope = ConnectionEnvelope( + version=1, + org="org", + owner="owner", + slot="mcp:" + "a" * 32, + generation="b" * 32 + "/1" + "c" * 31, + profile_id="approved", + profile_sha256="d" * 64, + endpoint="https://offline.invalid/mcp", + audience="https://offline.invalid/audience", + auth="bearer", + bearer=SecretStr("t" * 1024), + ) + raw = wire_envelope(envelope) + assert 1024 < len(raw.encode()) < 32768 + with pytest.raises(MCPSourceContractError): + mcp_contracts.encode_envelope(envelope) + with pytest.raises(MCPSourceContractError): + mcp_contracts.decode_envelope(raw) diff --git a/tests/unit/test_mcp_source_contract.py b/tests/unit/test_mcp_source_contract.py index e69efbeb9b..d0469bd086 100644 --- a/tests/unit/test_mcp_source_contract.py +++ b/tests/unit/test_mcp_source_contract.py @@ -10,7 +10,6 @@ from pydantic import SecretStr, ValidationError from server.knowledge.domain.mcp_sources import ( - MAX_ENVELOPE_BYTES, ConnectionEnvelope, MCPSourceContractError, ResourceIdentity, @@ -153,7 +152,7 @@ def test_envelope_rejects_missing_or_truncated_input(raw: str) -> None: def test_envelope_plaintext_bytes_are_bounded_before_decoding_and_encoding() -> None: raw = encode_envelope(_decode()) - boundary = raw + " " * (MAX_ENVELOPE_BYTES - len(raw.encode())) + boundary = raw + " " * (32768 - len(raw.encode())) assert decode_envelope(boundary).owner == "person-one" _assert_public_error(lambda: decode_envelope(boundary + " ")) # Valid local field bounds can still exceed the wire bound after JSON escaping. From f22f5f122c75145f072be050c5704e5b627ed56a Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 02:22:20 +0000 Subject: [PATCH 16/30] Read selected MCP resources through guarded knowledge writes Signed-off-by: zlareb1 --- docs/architecture/mcp-source-execution.md | 93 +++ server/knowledge/app/mcp_source_authority.py | 224 ++++++ server/knowledge/app/source_sync.py | 13 +- server/knowledge/app/source_sync_mcp.py | 207 +++++ tests/unit/test_mcp_source_sync.py | 771 +++++++++++++++++++ 5 files changed, 1303 insertions(+), 5 deletions(-) create mode 100644 docs/architecture/mcp-source-execution.md create mode 100644 server/knowledge/app/mcp_source_authority.py create mode 100644 server/knowledge/app/source_sync_mcp.py create mode 100644 tests/unit/test_mcp_source_sync.py diff --git a/docs/architecture/mcp-source-execution.md b/docs/architecture/mcp-source-execution.md new file mode 100644 index 0000000000..eba1cf5272 --- /dev/null +++ b/docs/architecture/mcp-source-execution.md @@ -0,0 +1,93 @@ +# Selected MCP source execution + +Selected MCP source execution copies explicitly registered text resources into a +protected mirror. This page describes its authority checks, publication boundary, +progress, and limits. + +## Source entry points + +`server/knowledge/app/mcp_source_authority.py` provides: + +- `validate_connection(org, owner, contract)`: checks the stored active account, + generation fence, owner standing and cutoffs, sealed envelope, and current + operator profile. Registration callers must hold their subject, account, and + destination locks. This check grants no source or destination authority. +- `validate_registration(source)`: checks a proposed row's supported contract, + connection binding, owner writer grant, and destination. The caller authorizes + the human and holds the subject, account, and namespace locks through insertion. + This helper refuses collection copying and grants no stored-source execution. +- `validate_source(source)`: requires the exact current active source row, + supported contract version, selected resources, owner, connection generation, + current writer grant, and allowed destination. It returns `SourceAuthority`. +- `SourceAuthority.client()`: builds an official MCP client restricted to the + stored selection. Each outbound operation rechecks source authority and the + account snapshot. +- `source_guard(source)`: holds the account lease before the namespace sources + lease, rechecks current source authority, and yields it while the locks remain + held. Protected live lookup can use this boundary for its final result release. + The caller must separately authorize the requesting reader and selected resource. +- `publication_guard(source)`: uses that boundary for durable publication and + refuses live mode or a missing current mirror. + +The connection manager's sealing and profile-binding helpers remain the only +envelope authority. Worker validation does not impersonate a human caller or +relax foreground connection validation. + +`server/knowledge/app/source_sync_mcp.py` (`turn`) follows the existing `Pass`, +`TurnResult`, pass deadline, stop checks, worker identity, and private accounting +contracts. Its caller owns the normal source-turn lease and worker actor scope. +The turn uses `ensure_mirror` under the account lease, `mirror_costs`, and an +explicit owner access list. + +## Publication + +The official client's configured read mapping selects `tools/call` when present; +otherwise the client uses `resources/read`. Tool descriptions never choose an +operation. Discovery validates approved tool schemas without enumerating resources +or changing the stored selection. + +Each accepted read has an identity-verified receipt matching the selected identity, +operation, client configuration digest, and text hash. Only text MIME types are +copied. Binary resources and plain tool text without verified result identity +refuse publication. There is no conversion or extraction step in this turn. + +The address comes from `mcp_identity.resource_uri`, using the registered source ID +and exact selected resource identity. Remote result URLs cannot change it. The +same address identifies the document, its chunks, and citations. Metadata records +the profile, generation, selection digest, read operation, and local text hash. +The source revision is empty because no upstream revision guarantee is assumed. + +Publication calls the existing `source_sync.write_document` and knowledge upsert +path, including original UTF-8 bytes, chunks, document metadata, indexing, imported +provenance, and source tags. The MCP commit guard is reacquired around original +storage and around chunk/document commit after embedding. Both locks remain held +through each storage boundary. A changed source, account, profile, owner standing, +writer grant, or destination refuses the commit. + +## Progress and invariants + +`live` mode creates no mirror and writes no knowledge. `snapshot` copies the +selection once per binding or explicit refresh request. `selected_refresh` rereads +the same fixed selection on subsequent turns. Progress uses a local index plus a +digest of the source identity, owner, connection binding, contract, and selection; +it never stores or reuses an MCP session cursor. + +Progress is stored through `TurnResult.kind_state` in the existing protected +mirror state. A failed or missing read leaves its index pending. A changed binding +or selection resets the index. A document bound holds new copies back while +allowing already stored selected copies to refresh. + +After every selected read and publication succeeds, with no pending publication, +the turn records the existing protected listing timestamp under the commit guard. +This timestamp covers only the registered selected set and its owner permission +lists. `TurnResult.full` stays false. Selected-set completion proves no complete +upstream enumeration, remote ACL synchronization, deletion, or revision ordering. +Absence, errors, partial results, and selection changes never delete documents. + +Without upstream ACL evidence, publication is owner-only. `collection_copy` is +refused even when the current operator profile permits it: the stored contract +does not prove durable writer consent for that publication. Admission must resolve +that missing authority before exposing this policy. + +Source admission, worker dispatch, requesting-reader authorization, live result +assembly, and source lifecycle routing are separate callers of these interfaces. diff --git a/server/knowledge/app/mcp_source_authority.py b/server/knowledge/app/mcp_source_authority.py new file mode 100644 index 0000000000..93f971fbcc --- /dev/null +++ b/server/knowledge/app/mcp_source_authority.py @@ -0,0 +1,224 @@ +"""Current stored MCP authority, shared by execution and commit-time fencing.""" + +from __future__ import annotations + +import hashlib +import json +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import asynccontextmanager +from dataclasses import dataclass, replace + +from server.auth import aliases, authz +from server.clients.mcp_source import MCPSourceClient +from server.core.ch import own_write_reads +from server.core.errors import ValidationError +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import mcp_connections, mirrors +from server.knowledge.app.mcp_contracts import decode_source +from server.knowledge.app.mcp_profiles import FrozenProfileDefinition, build_mcp_source_client +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.domain.mcp_sources import ConnectionEnvelope, SourceContract +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource +from server.knowledge.store import connected_accounts as account_store +from server.knowledge.store import sources as source_store +from server.operations.base import Role +from server.settings import settings +from server.workers import pass_context + + +class MCPAuthorityError(ValidationError): + def __init__(self) -> None: + super().__init__("MCP_SOURCE_UNAVAILABLE") + + +@asynccontextmanager +async def _refusals() -> AsyncIterator[None]: + try: + yield + except MCPAuthorityError: + raise + except Exception as e: # noqa: BLE001 — authority failures reveal no source or credential data + del e + raise MCPAuthorityError() from None + + +@dataclass(frozen=True, repr=False) +class ConnectionAuthority: + account: ConnectedAccount + profile: FrozenProfileDefinition + envelope: ConnectionEnvelope + contract: SourceContract + + def client(self, validate_access: Callable[[], Awaitable[None]]) -> MCPSourceClient: + return build_mcp_source_client( + self.profile, + self.envelope, + org=self.account.org, + owner=self.account.subject, + slot=self.account.kind, + generation=self.account.connection_id, + contract=self.contract, + validate_access=validate_access, + ) + + +async def validate_connection( + org: str, owner: str, contract: SourceContract +) -> ConnectionAuthority: + """Check stored owner authority without requiring a foreground human token. + + Registration must hold the subject/account/namespace locks its write needs. + This check grants neither a destination nor permission to publish a source. + """ + async with _refusals(): + contract = SourceContract.model_validate(contract) + await mcp_connections._ready() + with own_write_reads(): + account = await account_store.get(org, owner, contract.slot) + if ( + account is None + or (account.org, account.subject, account.kind) != (org, owner, contract.slot) + or not account.active + or not account.credential_enc + or account.refresh_id + or account.connection_id != contract.generation + or account.connected_at is None + or not contract.generation.partition("/")[2].startswith("1") + or not await accounts._fence_current(account) + ): + raise MCPAuthorityError() + await accounts._standing(org, owner, int(account.connected_at.timestamp())) + profile, envelope = mcp_connections._binding(account) + bound = ConnectionAuthority(account, profile, envelope, contract) + + async def checked() -> None: + await validate_connection(org, owner, contract) + + # The builder checks selection limits and every contract/profile binding. + bound.client(checked) + return bound + + +def source_contract(src: KnowledgeSource) -> SourceContract: + """Parse only the supported stored contract; no payload can widen its row.""" + if ( + src.kind != "mcp" + or src.credential_mode != "connected" + or type(src.source_contract_version) is not int + or src.source_contract_version != 1 + or src.active is not True + or src.pending_delete + or not src.owner_subject + or src.credential_enc + or src.secret_enc + or src.config + or src.items + ): + raise MCPAuthorityError() + contract = decode_source(src.generic_config_json, src.generic_items_json) + if (contract.generation, contract.slot) != (src.connection_id, src.connection_slot): + raise MCPAuthorityError() + resource_uri(src.source_id, contract.resources[0].id) + # No stored writer-consent proof exists for a deliberate collection copy. + if contract.reader_policy != "owner_only" or src.access != MIRRORED_ACCESS: + raise MCPAuthorityError() + return contract + + +@dataclass(frozen=True, repr=False) +class SourceAuthority: + source: KnowledgeSource + connection: ConnectionAuthority + + @property + def contract(self) -> SourceContract: + return self.connection.contract + + @property + def selection_sha256(self) -> str: + payload = [ + self.source.org, + self.source.namespace, + self.source.name, + self.source.source_id, + self.source.owner_subject, + self.source.connection_id, + self.contract.model_dump(mode="json"), + ] + return hashlib.sha256( + json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + async def validate(self) -> None: + fresh = await validate_source(self.source) + if fresh.connection.account != self.connection.account: + raise MCPAuthorityError() + + def client(self) -> MCPSourceClient: + return self.connection.client(self.validate) + + +async def validate_source(src: KnowledgeSource) -> SourceAuthority: + """Recheck an exact active stored row and its current destination authority. + + This is a worker/source check, not a requesting reader's authorization. A live + reader must separately prove its identity and access to this exact selection. + """ + async with _refusals(): + with own_write_reads(): + current = await source_store.get_source(src.org, src.namespace, src.name) + if current is None or replace(current, mirror="") != replace(src, mirror=""): + raise MCPAuthorityError() + connection = await validate_registration(src) + if src.mirror and await mirrors.live_mirror(src.org, src.namespace) != src.mirror: + raise MCPAuthorityError() + return SourceAuthority(src, connection) + + +async def validate_registration(src: KnowledgeSource) -> ConnectionAuthority: + """Check a proposed row's binding and destination, without granting execution. + + Registration owns human caller authorization and subject/account/namespace + locks, then repeats this check immediately before its source insert. Execution + still requires validate_source's exact current stored-row check. + """ + from server.knowledge.app import sources as source_ops + + async with _refusals(): + contract = source_contract(src) + if not settings.auth_actually_required() or not settings.knowledge_mirrored_sources_enabled: + raise MCPAuthorityError() + with own_write_reads(): + connection = await validate_connection(src.org, src.owner_subject, contract) + await aliases.verified_spellings(src.org, src.owner_subject) + aliases.invalidate(src.org, [src.owner_subject]) + role = await authz.grant_role_for(src.org, src.namespace, src.owner_subject) + if role is None or role < Role.WRITER: + raise MCPAuthorityError() + await source_ops._require_source_namespace(src.org, src.namespace) + await source_ops._require_no_erasure(src.org, src.namespace) + return connection + + +@asynccontextmanager +async def source_guard(src: KnowledgeSource) -> AsyncIterator[SourceAuthority]: + """Fence a stored source check or live result release; does not grant reader access.""" + from server.knowledge.app import sources as source_ops + + async with _refusals(): + contract = source_contract(src) + async with accounts.account_lease(src.org, src.owner_subject, contract.slot): + async with source_ops.sources_lease(src.org, src.namespace): + pass_context.check_stop() + bound = await validate_source(src) + yield bound + + +@asynccontextmanager +async def publication_guard(src: KnowledgeSource) -> AsyncIterator[None]: + """Hold account then namespace leases through the actual knowledge commit.""" + async with source_guard(src) as bound: + if bound.contract.mode == "live" or not src.mirror: + raise MCPAuthorityError() + yield diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index c506f80126..a9a15fb7f3 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -1350,15 +1350,18 @@ async def write_document( blob_content_type=str(f.get("mimeType") or "") if original else "", source_class="imported", ) + guard = ( + functools.partial(publication_guard, src) if src.credential_mode == "connected" else None + ) + if src.kind == "mcp": + from server.knowledge.app.mcp_source_authority import publication_guard as mcp_guard + + guard = functools.partial(mcp_guard, src) with contextlib.suppress(PublicationPending): # committed; the worker publishes it await writes.handle_knowledge_upsert( request, permissions=permissions, - commit_guard=( - functools.partial(publication_guard, src) - if src.credential_mode == "connected" - else None - ), + commit_guard=guard, ) return True diff --git a/server/knowledge/app/source_sync_mcp.py b/server/knowledge/app/source_sync_mcp.py new file mode 100644 index 0000000000..aaa7dea8de --- /dev/null +++ b/server/knowledge/app/source_sync_mcp.py @@ -0,0 +1,207 @@ +"""Bounded refresh of an explicit selected MCP resource set, without retirement.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import time +from dataclasses import replace +from datetime import UTC, datetime +from typing import Any + +from server.clients.mcp_source import MCPEvidence, MCPSourceClient, MCPSourceError +from server.core.ch import set_query_tag +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app import mirrors, private_sync +from server.knowledge.app import source_sync as sync +from server.knowledge.domain.access_list import AccessList +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.domain.sources import KnowledgeSource, mirror_uri_suffix +from server.knowledge.store import documents +from server.knowledge.store import mirrors as mirror_store +from server.workers import pass_context +from server.workers.status import set_worker_identity + + +def _detail(state: dict[str, str]) -> dict[str, Any]: + try: + value = json.loads(state.get("detail", "") or "{}") + return value if isinstance(value, dict) else {} + except (ValueError, TypeError): + return {} + + +def _progress( + bound: authority.SourceAuthority, saved: dict[str, Any], asked: dict[str, Any] +) -> dict[str, Any]: + count = len(bound.contract.resources) + index = saved.get("mcp_next_index", 0) + request = asked.get("requested_at", saved.get("mcp_requested_at", "")) + if ( + saved.get("mcp_selection_sha256") != bound.selection_sha256 + or saved.get("mcp_requested_at", "") != request + or type(index) is not int + or not 0 <= index <= count + ): + index = 0 + if index == count and bound.contract.mode == "selected_refresh": + index = 0 + return { + "mcp_mode": bound.contract.mode, + "mcp_selection_sha256": bound.selection_sha256, + "mcp_next_index": index, + "mcp_selected_count": count, + "mcp_requested_at": request, + "mcp_selected_complete": False, + } + + +def _receipt(client: MCPSourceClient, selected: str, evidence: MCPEvidence) -> str: + receipt = evidence.receipt + digest = hashlib.sha256(evidence.text.encode()).hexdigest() + operation = "tools/call" if client.config.read is not None else "resources/read" + if ( + receipt is None + or not evidence.text.strip() + or not receipt.identity_verified + or evidence.resource_id != selected + or receipt.requested_id != selected + or receipt.operation != operation + or receipt.content_sha256 != digest + or receipt.config_sha256 != client.config_sha256 + or not evidence.mime_type.partition(";")[0].strip().lower().startswith("text/") + ): + raise MCPSourceError("unsupported") + return digest + + +async def _publish( + bound: authority.SourceAuthority, + client: MCPSourceClient, + selected: str, + evidence: MCPEvidence, +) -> bool: + digest = _receipt(client, selected, evidence) + src = bound.source + return await sync.write_document( + src, + {"id": selected, "name": evidence.title, "mimeType": evidence.mime_type}, + resource_uri(src.source_id, selected), + evidence.text, + ingested_format="mcp_text", + original=evidence.text.encode(), + permissions=AccessList(owner=src.owner_subject), + extra_metadata={ + "mcp_content_sha256": digest, + "mcp_selection_sha256": bound.selection_sha256, + "mcp_profile_sha256": bound.contract.profile_sha256, + "mcp_connection_generation": bound.contract.generation, + "mcp_source_id": src.source_id, + "mcp_read_operation": "tools/call" if client.config.read else "resources/read", + "mcp_reader_policy": "owner_only", + }, + ) + + +async def _read_selected( + bound: authority.SourceAuthority, result: sync.TurnResult, run: sync.Pass +) -> None: + stored = await sync.stored_copies_with_room(bound.source, result) + progress = result.kind_state + client = bound.client() + async with client: + await client.discover() + for index in range(progress["mcp_next_index"], len(bound.contract.resources)): + set_query_tag("worker." + sync.WORKER) + if run.spent(): + result.mark(sync.TurnMark.PASS_BOUND) + return + selected = bound.contract.resources[index].id + if selected not in stored and result.room <= 0: + result.held += 1 + result.fail("failed", "MCP_DOCUMENT_LIMIT") + return + run.left -= 1 + evidence = await client.read(selected) + result.documents_seen += 1 + if run.budget.exhausted(): + result.mark(sync.TurnMark.PASS_BOUND) + return + await bound.validate() + pass_context.check_stop() + if not await _publish(bound, client, selected, evidence): + result.fail("failed", "MCP_DOCUMENT_HELD") + return + result.changed += 1 + if selected not in stored: + result.room -= 1 + progress["mcp_next_index"] = index + 1 + + +async def _finish( + bound: authority.SourceAuthority, result: sync.TurnResult, run: sync.Pass, started: datetime +) -> None: + src = bound.source + if result.status != "ok" or result.marks: + return + if run.budget.exhausted(): + result.mark(sync.TurnMark.PASS_BOUND) + return + if await documents.publications_owed(src.org, src.mirror, mirror_uri_suffix(src.source_id)): + result.fail("failed", "MCP_PUBLICATION_PENDING") + return + async with authority.publication_guard(src): + await mirror_store.record_listing(src.org, src.mirror, src.source_id, src.name, started) + result.kind_state["mcp_selected_complete"] = True + result.complete = True + + +async def _turn( + src: KnowledgeSource, state: dict[str, str], run: sync.Pass, result: sync.TurnResult +) -> None: + bound = await authority.validate_source(src) + if bound.contract.mode == "live": + result.kind_state = {"mcp_mode": "live", "mcp_selected_complete": False} + result.complete = True + return + async with accounts.account_lease(src.org, src.owner_subject, bound.contract.slot): + mirror = await mirrors.ensure_mirror(src.org, src.namespace, still_current=bound.validate) + src = replace(src, mirror=mirror) + bound = await authority.validate_source(src) + result.mirror = mirror + saved = _detail(await sync.mirror_state(src, mirror)) + result.kind_state = _progress(bound, saved, _detail(state)) + if ( + bound.contract.mode == "snapshot" + and result.kind_state["mcp_next_index"] == len(bound.contract.resources) + and saved.get("mcp_selected_complete") is True + ): + result.kind_state["mcp_selected_complete"] = True + result.complete = True + return + started = datetime.now(UTC) + async with private_sync.mirror_costs(src.org, mirror, sync.WORKER): + set_worker_identity(sync.WORKER, org=src.org, namespace=mirror) + await _read_selected(bound, result, run) + await _finish(bound, result, run, started) + + +async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: + """Refresh only stored selections; completion never asserts upstream enumeration.""" + result = sync.TurnResult(complete=False) + with private_sync.scope(): + try: + if run.spent(): + result.mark(sync.TurnMark.PASS_BOUND) + return result + async with asyncio.timeout(max(0.0, run.budget.stop_after - time.monotonic())): + await _turn(src, state, run, result) + except TimeoutError: + result.mark(sync.TurnMark.PASS_BOUND) + except authority.MCPAuthorityError: + result.fail("unavailable", "MCP_SOURCE_UNAVAILABLE") + except MCPSourceError as error: + result.fail("failed", "MCP_READ_" + error.code.upper()) + return result diff --git a/tests/unit/test_mcp_source_sync.py b/tests/unit/test_mcp_source_sync.py new file mode 100644 index 0000000000..7c6dc6b307 --- /dev/null +++ b/tests/unit/test_mcp_source_sync.py @@ -0,0 +1,771 @@ +"""Selected MCP execution with real SDK reads and in-memory storage seams.""" + +from __future__ import annotations + +import asyncio +import json +import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass, field, replace +from datetime import UTC, datetime +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock + +import httpx +import pytest +import pytest_asyncio +from mcp import types +from mcp.server.fastmcp import FastMCP +from mcp.server.transport_security import TransportSecuritySettings + +from server.clients import mcp_source as client_module +from server.clients.mcp_source import MCPSourceClient, MCPSourceError +from server.code.app.index.pass_budget import PassBudget +from server.knowledge.app import mcp_connections, mcp_profiles, sources, writes +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app import source_sync as sync +from server.knowledge.app import source_sync_mcp as engine +from server.knowledge.domain import access_list +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.domain.mcp_sources import ( + ConnectionEnvelope, + ResourceIdentity, + SourceContract, + encode_envelope, + encode_source, +) +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource +from server.knowledge.store import blobs, chunks, documents +from server.memory.domain.provenance import pipeline_actor +from server.operations.base import Role + +MIRROR = "acl-" + "a" * 24 +RESOURCE = "selected://document/one" +SECOND = "selected://document/two" +BINARY = "selected://document/binary" +TOOL_INPUT = { + "type": "object", + "properties": {"resource_id": {"type": "string"}}, + "required": ["resource_id"], + "additionalProperties": False, +} +TOOL_OUTPUT = { + "type": "object", + "properties": {key: {"type": "string"} for key in ("id", "title", "text", "uri")}, + "required": ["id", "title", "text", "uri"], + "additionalProperties": False, +} + + +@dataclass +class Harness: + source: KnowledgeSource + account: ConnectedAccount + contract: SourceContract + saved: dict[str, Any] = field(default_factory=dict) + events: list[str] = field(default_factory=list) + doc_rows: list[Any] = field(default_factory=list) + chunk_rows: list[Any] = field(default_factory=list) + originals: list[bytes] = field(default_factory=list) + reads: list[str] = field(default_factory=list) + locks: list[str] = field(default_factory=list) + listing: AsyncMock = field(default_factory=AsyncMock) + failing_resource: str = "" + text: str = "Selected resource text." + + def select( + self, + *, + mode: str = "snapshot", + policy: str = "owner_only", + two: bool = False, + resources: tuple[str, ...] | None = None, + ) -> None: + payload = self.contract.model_dump(mode="json") + payload.update(mode=mode, reader_policy=policy) + if two: + payload["resources"].append({"type": "resource", "id": SECOND}) + if resources is not None: + payload["resources"] = [{"type": "resource", "id": item} for item in resources] + self.contract = SourceContract.model_validate_json(json.dumps(payload)) + config, items = encode_source(self.contract) + self.source = replace(self.source, generic_config_json=config, generic_items_json=items) + + +def _catalog(tool: bool) -> mcp_profiles.MCPProfileCatalog: + config: dict[str, Any] = {"endpoint": "https://selected.example/mcp"} + if tool: + config.update( + approved_tools=["read_selected"], + read={ + "name": "read_selected", + "argument_name": "resource_id", + "input_schema": TOOL_INPUT, + "output_schema": TOOL_OUTPUT, + }, + ) + return mcp_profiles.MCPProfileCatalog.parse( + json.dumps( + { + "version": 1, + "profiles": [ + { + "id": "approved", + "label": "Selected", + "auth": "none", + "allowed_orgs": ["org"], + "allow_collection_copy": True, + "config": config, + } + ], + } + ) + ) + + +def test_authority_reads_the_actual_opaque_store_representation(harness: Harness) -> None: + config, items = encode_source(harness.contract) + stored = authority.source_store._source( + { + "org": harness.source.org, + "namespace": harness.source.namespace, + "name": harness.source.name, + "source_id": harness.source.source_id, + "source_kind": "mcp", + "credential_mode": "connected", + "owner_subject": harness.source.owner_subject, + "connection_id": harness.contract.generation, + "connection_slot": harness.contract.slot, + "source_contract_version": 1, + "config_json": config, + "items_json": items, + "active": True, + "access": MIRRORED_ACCESS, + } + ) + assert stored.config == {} and stored.items == [] + assert authority.source_contract(stored) == harness.contract + + +@pytest.fixture +def harness(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> Harness: + catalog = _catalog(getattr(request, "param", "") == "tool") + profile = catalog.get("org", "approved") + slot, generation = "mcp:" + "a" * 32, "a" * 32 + "/1" + "b" * 31 + contract = SourceContract( + version=1, + slot=slot, + generation=generation, + profile_id="approved", + profile_sha256=profile.metadata.profile_sha256, + mode="snapshot", + reader_policy="owner_only", + resources=(ResourceIdentity(type="resource", id=RESOURCE),), + ) + config, items = encode_source(contract) + source = KnowledgeSource( + "org", + "collection", + "selected", + "mcp", + "00000000-0000-4000-8000-000000000001", + generic_config_json=config, + generic_items_json=items, + access=MIRRORED_ACCESS, + credential_mode="connected", + owner_subject="owner", + connection_id=generation, + source_contract_version=1, + connection_slot=slot, + ) + account = ConnectedAccount( + "org", + "owner", + slot, + generation, + active=True, + connected_at=datetime.now(UTC), + credential_enc="sealed-fixture", + ) + h = Harness(source, account, contract) + envelope = ConnectionEnvelope( + version=1, + org="org", + owner="owner", + slot=slot, + generation=generation, + profile_id="approved", + profile_sha256=profile.metadata.profile_sha256, + endpoint="https://selected.example/mcp", + audience=None, + auth="none", + ) + monkeypatch.setattr(mcp_connections, "unseal", lambda *a, **k: encode_envelope(envelope)) + monkeypatch.setattr(mcp_connections, "load_mcp_profile_catalog", lambda: catalog) + monkeypatch.setattr(mcp_connections, "_ready", AsyncMock()) + monkeypatch.setattr(authority.account_store, "get", AsyncMock(side_effect=lambda *a: h.account)) + monkeypatch.setattr( + authority.source_store, "get_source", AsyncMock(side_effect=lambda *a: h.source) + ) + _owner_seams(monkeypatch) + _lock_seams(monkeypatch, h) + _mirror_seams(monkeypatch, h) + return h + + +def _owner_seams(monkeypatch: pytest.MonkeyPatch) -> None: + enabled = SimpleNamespace( + auth_actually_required=lambda: True, knowledge_mirrored_sources_enabled=True + ) + monkeypatch.setattr(authority, "settings", enabled) + monkeypatch.setattr(authority.accounts, "settings", enabled) + monkeypatch.setattr( + authority.accounts, + "resolve_reader", + AsyncMock(return_value=SimpleNamespace(subject="owner", emails=frozenset())), + ) + monkeypatch.setattr(authority.aliases, "verified_spellings", AsyncMock(return_value=["owner"])) + monkeypatch.setattr(authority.aliases, "invalidate", lambda *a: None) + monkeypatch.setattr(authority.account_store, "account_active", AsyncMock(return_value=True)) + monkeypatch.setattr(authority.accounts.scim, "refuses_subject", AsyncMock(return_value=False)) + monkeypatch.setattr(authority.accounts.revocation, "cutoffs", AsyncMock(return_value={})) + monkeypatch.setattr(authority.accounts, "_fence_current", AsyncMock(return_value=True)) + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=Role.WRITER)) + monkeypatch.setattr(sources, "_require_source_namespace", AsyncMock()) + monkeypatch.setattr(sources, "_require_no_erasure", AsyncMock()) + + +def _lock_seams(monkeypatch: pytest.MonkeyPatch, h: Harness) -> None: + account_lock, namespace_lock = asyncio.Lock(), asyncio.Lock() + + @asynccontextmanager + async def account(*args: Any) -> AsyncIterator[None]: + assert args == (h.source.org, h.source.owner_subject, h.contract.slot) + async with account_lock: + h.locks.append("account") + h.events.append("account") + try: + yield + finally: + h.locks.pop() + + @asynccontextmanager + async def namespace(*args: Any) -> AsyncIterator[None]: + assert h.locks == ["account"] + async with namespace_lock: + h.locks.append("namespace") + h.events.append("namespace") + try: + yield + finally: + h.locks.pop() + + monkeypatch.setattr(authority.accounts, "account_lease", account) + monkeypatch.setattr(sources, "sources_lease", namespace) + + +def _mirror_seams(monkeypatch: pytest.MonkeyPatch, h: Harness) -> None: + monkeypatch.setattr(engine.mirrors, "live_mirror", AsyncMock(return_value=MIRROR)) + monkeypatch.setattr( + sync, "mirror_state", AsyncMock(side_effect=lambda *a: {"detail": json.dumps(h.saved)}) + ) + monkeypatch.setattr(sync.store, "source_revisions", AsyncMock(return_value=[])) + monkeypatch.setattr(documents, "publications_owed", AsyncMock(return_value=False)) + monkeypatch.setattr(engine.mirror_store, "record_listing", h.listing) + monkeypatch.setattr(engine.private_sync, "write_private_cost_event_for", AsyncMock()) + + +@pytest_asyncio.fixture +async def upstream(harness: Harness, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[FastMCP]: + server = FastMCP( + "selected", + stateless_http=True, + json_response=True, + transport_security=TransportSecuritySettings( + allowed_hosts=["selected.example", "198.51.100.1"], + allowed_origins=["https://selected.example", "https://198.51.100.1"], + ), + ) + + @server.resource(RESOURCE) + async def first() -> str: + harness.reads.append(RESOURCE) + return harness.text + + @server.resource(SECOND) + async def second() -> str: + harness.reads.append(SECOND) + if harness.failing_resource == SECOND: + raise ValueError("synthetic unavailable resource") + return "Second selected text." + + @server.resource(BINARY, mime_type="application/octet-stream") + async def binary() -> bytes: + harness.reads.append(BINARY) + return b"\x00\x01" + + _tools(server, harness) + app = server.streamable_http_app() + original_builder = authority.build_mcp_source_client + + def build(*args: Any, **kwargs: Any) -> MCPSourceClient: + prototype = original_builder(*args, **kwargs) + return MCPSourceClient( + prototype.config, + prototype.credential, + validate_access=prototype.validate_access, + _transport=httpx.ASGITransport(app=app), + ) + + monkeypatch.setattr(authority, "build_mcp_source_client", build) + monkeypatch.setattr( + client_module, + "pinned_target", + AsyncMock( + return_value=("", "https://198.51.100.1/mcp", "selected.example", "selected.example") + ), + ) + ready = asyncio.get_running_loop().create_future() + stop = asyncio.Event() + + async def lifetime() -> None: + async with server.session_manager.run(): + ready.set_result(None) + await stop.wait() + + owner = asyncio.create_task(lifetime()) + await ready + try: + yield server + finally: + stop.set() + await owner + + +def _tools(server: FastMCP, h: Harness) -> None: + @server._mcp_server.list_tools() + async def listed() -> list[types.Tool]: + return [types.Tool(name="read_selected", inputSchema=TOOL_INPUT, outputSchema=TOOL_OUTPUT)] + + @server._mcp_server.call_tool() + async def called(name: str, arguments: dict[str, Any]) -> types.CallToolResult: + assert name == "read_selected" and arguments == {"resource_id": RESOURCE} + h.reads.append("tool:" + arguments["resource_id"]) + value = { + "id": RESOURCE, + "title": "Selected", + "text": "Mapped selected text.", + "uri": "https://untrusted.example/other", + } + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(value))], + structuredContent=value, + ) + + +@pytest.fixture +def storage(harness: Harness, monkeypatch: pytest.MonkeyPatch) -> Harness: + h = harness + monkeypatch.setattr( + writes, "get_embedder", lambda: SimpleNamespace(dim=2, model_name="fixture") + ) + monkeypatch.setattr(writes.codes_state, "refuse_width", AsyncMock()) + monkeypatch.setattr( + writes, + "_embed_inline_batch", + AsyncMock(side_effect=lambda embedder, texts: [[0.0, 1.0] for _ in texts]), + ) + monkeypatch.setattr(chunks, "find_doc_by_content_sha256", AsyncMock(return_value=None)) + monkeypatch.setattr(chunks, "count_active_for_doc", AsyncMock(return_value=0)) + monkeypatch.setattr(chunks, "count_matching_chunk_hashes", AsyncMock(return_value=0)) + monkeypatch.setattr(documents, "get_one", AsyncMock(return_value=None)) + monkeypatch.setattr(writes, "_drop_own_chunks", AsyncMock()) + + async def blob(org: str, namespace: str, raw: bytes, **kwargs: Any) -> str: + assert h.locks == ["account", "namespace"] + h.originals.append(raw) + return "original/selected" + + async def insert_chunks(rows: list[Any]) -> None: + assert h.locks == ["account", "namespace"] + h.chunk_rows.extend(rows) + + async def insert_document(row: Any, **kwargs: Any) -> None: + assert h.locks == ["account", "namespace"] + h.doc_rows.append(row) + + monkeypatch.setattr(blobs, "put", blob) + monkeypatch.setattr(chunks, "insert_chunks", insert_chunks) + monkeypatch.setattr(documents, "insert_one", insert_document) + return h + + +async def execute( + h: Harness, *, limit: int = 10, state: dict[str, str] | None = None +) -> sync.TurnResult: + started = time.monotonic() + with pipeline_actor(sync.SYNC_WORKER_ACTOR): + return await engine.turn( + h.source, state or {}, sync.Pass(PassBudget(started, started + 15), limit) + ) + + +@pytest.mark.asyncio +async def test_selected_sdk_read_uses_real_upsert_rows_and_owner_access( + storage: Harness, + upstream: FastMCP, +) -> None: + h = storage + result = await execute(h) + assert (result.status, result.complete, result.full, result.removed) == ("ok", True, False, 0) + assert h.reads == [RESOURCE] + assert h.originals == [b"Selected resource text."] + assert len(h.doc_rows) == len(h.chunk_rows) == 1 + document, chunk = h.doc_rows[0], h.chunk_rows[0] + uri = resource_uri(h.source.source_id, RESOURCE) + assert (document["org"], document["namespace"], document["source_uri"]) == ("org", MIRROR, uri) + assert document["content"] == chunk["content"] == "Selected resource text." + assert document["source_class"] == chunk["source_class"] == "imported" + assert document["actor"] == sync.SYNC_WORKER_ACTOR + assert (document["user_id"], document["session_id"], document["agent"]) == ("-", "-", "-") + assert access_list.from_json(document["access_json"]) == access_list.AccessList(owner="owner") + assert document["blob_path"] == "original/selected" + assert document["blob_size"] == len(h.originals[0]) + assert document["revision"] == 1 + assert document["version"] == chunk["doc_version"] + metadata = json.loads(document["metadata"]) + assert metadata["source_revision"] == "" + assert metadata["ingested_from"] == RESOURCE + assert metadata["mcp_read_operation"] == "resources/read" + assert metadata["mcp_connection_generation"] == h.contract.generation + assert document["source_uri"] == chunk["source_uri"] == uri + assert "source-id:" + h.source.source_id in document["tags"] + h.listing.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_snapshot_completion_and_bounded_resume(storage: Harness, upstream: FastMCP) -> None: + h = storage + h.select(two=True) + first = await execute(h, limit=1) + assert first.cut and not first.complete and first.kind_state["mcp_next_index"] == 1 + h.listing.assert_not_awaited() + h.saved = first.kind_state + second = await execute(h) + assert second.complete and h.reads == [RESOURCE, SECOND] + h.saved = second.kind_state + await execute(h) + assert h.reads == [RESOURCE, SECOND] + h.listing.assert_awaited_once() + + +@pytest.mark.asyncio +async def test_selected_refresh_and_explicit_snapshot_request( + storage: Harness, upstream: FastMCP +) -> None: + h = storage + first = await execute(h, state={"detail": '{"requested_at":"request-one"}'}) + h.saved = first.kind_state + await execute(h) + assert h.reads == [RESOURCE] + await execute(h, state={"detail": '{"requested_at":"request-two"}'}) + assert h.reads == [RESOURCE, RESOURCE] + h.select(mode="selected_refresh") + first = await execute(h) + h.saved = first.kind_state + second = await execute(h) + assert second.complete and not second.full and h.reads == [RESOURCE] * 4 + + +@pytest.mark.asyncio +async def test_live_and_exhausted_turns_publish_nothing(storage: Harness) -> None: + h = storage + h.select(mode="live") + result = await execute(h) + assert result.complete and result.mirror == "" and not result.full + h.select(mode="snapshot") + result = await execute(h, limit=0) + assert result.cut and not result.complete + assert not h.doc_rows and not h.originals + h.listing.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "change", + [ + {"org": "other"}, + {"namespace": "other"}, + {"source_id": "00000000-0000-4000-8000-000000000002"}, + {"owner_subject": "other"}, + {"connection_id": "a" * 32 + "/1" + "c" * 31}, + {"active": False}, + {"source_contract_version": 2}, + {"generic_items_json": "[]"}, + {"generic_config_json": "{}"}, + {"items": [{"type": "resource", "id": SECOND}]}, + {"config": {"mode": "live"}}, + {"connection_slot": "mcp:" + "c" * 32}, + {"access": "namespace"}, + {"credential_mode": "shared"}, + ], +) +async def test_exact_stored_source_is_required(harness: Harness, change: dict[str, Any]) -> None: + expected = harness.source + harness.source = replace(expected, **change) + with pytest.raises(authority.MCPAuthorityError, match="^MCP_SOURCE_UNAVAILABLE$"): + await authority.validate_source(expected) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "change", + [ + {"active": False}, + {"credential_enc": ""}, + {"refresh_id": "pending"}, + {"connection_id": "a" * 32 + "/1" + "c" * 31}, + {"connected_at": None}, + {"subject": "other"}, + {"org": "other"}, + {"kind": "mcp:" + "c" * 32}, + ], +) +async def test_account_binding_must_still_be_active( + harness: Harness, change: dict[str, Any] +) -> None: + harness.account = replace(harness.account, **change) + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_source(harness.source) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "seam", ["fence", "owner", "cutoff", "grant", "profile", "destination", "erasure"] +) +async def test_current_authority_refusals( + harness: Harness, + monkeypatch: pytest.MonkeyPatch, + seam: str, +) -> None: + if seam == "fence": + monkeypatch.setattr(authority.accounts, "_fence_current", AsyncMock(return_value=False)) + elif seam == "owner": + monkeypatch.setattr( + authority.account_store, "account_active", AsyncMock(return_value=False) + ) + elif seam == "cutoff": + assert harness.account.connected_at is not None + monkeypatch.setattr( + authority.accounts.revocation, + "cutoffs", + AsyncMock( + return_value={ + "owner": int(harness.account.connected_at.timestamp()) + 1, + } + ), + ) + elif seam == "grant": + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=None)) + elif seam == "profile": + monkeypatch.setattr( + mcp_connections, "load_mcp_profile_catalog", lambda: mcp_profiles.MCPProfileCatalog() + ) + else: + target = "_require_source_namespace" if seam == "destination" else "_require_no_erasure" + monkeypatch.setattr(sources, target, AsyncMock(side_effect=ValueError("private detail"))) + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_source(harness.source) + + +@pytest.mark.asyncio +async def test_collection_copy_is_refused_even_with_operator_allow(harness: Harness) -> None: + harness.select(policy="collection_copy") + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_source(harness.source) + + +@pytest.mark.asyncio +async def test_registration_checks_do_not_grant_unstored_source_execution( + harness: Harness, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(authority.source_store, "get_source", AsyncMock(return_value=None)) + bound = await authority.validate_registration(harness.source) + assert bound.contract == harness.contract + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_source(harness.source) + harness.select(policy="collection_copy") + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_registration(harness.source) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("lost", ["source", "account", "grant", "profile", "owner"]) +async def test_source_replacement_between_original_and_commit_refuses( + storage: Harness, + upstream: FastMCP, + monkeypatch: pytest.MonkeyPatch, + lost: str, +) -> None: + h = storage + original = writes._embed_inline_batch + + async def replace_source(*args: Any, **kwargs: Any) -> Any: + assert not h.locks + if lost == "source": + h.source = replace(h.source, active=False) + elif lost == "account": + h.account = replace(h.account, active=False) + elif lost == "grant": + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=None)) + elif lost == "profile": + monkeypatch.setattr( + mcp_connections, + "load_mcp_profile_catalog", + lambda: mcp_profiles.MCPProfileCatalog(), + ) + else: + monkeypatch.setattr( + authority.account_store, "account_active", AsyncMock(return_value=False) + ) + return await original(*args, **kwargs) + + monkeypatch.setattr(writes, "_embed_inline_batch", replace_source) + result = await execute(h) + assert not result.complete and result.status == "unavailable" + assert h.originals == [b"Selected resource text."] + assert not h.doc_rows and not h.chunk_rows + h.listing.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_commit_guard_keeps_locks_and_preserves_body_exceptions(harness: Harness) -> None: + src = replace(harness.source, mirror=MIRROR) + with pytest.raises(RuntimeError, match="commit result"): + async with authority.publication_guard(src): + assert harness.locks == ["account", "namespace"] + raise RuntimeError("commit result") + assert not harness.locks + + +@pytest.mark.asyncio +async def test_actual_receipt_rejects_tampering_and_unselected_reads( + harness: Harness, + upstream: FastMCP, +) -> None: + bound = await authority.validate_source(harness.source) + client = bound.client() + async with client: + evidence = await client.read(RESOURCE) + assert engine._receipt(client, RESOURCE, evidence) == evidence.receipt.content_sha256 + with pytest.raises(MCPSourceError): + engine._receipt(client, RESOURCE, replace(evidence, text="injected")) + with pytest.raises(MCPSourceError): + engine._receipt(client, SECOND, evidence) + with pytest.raises(MCPSourceError): + engine._receipt(client, RESOURCE, replace(evidence, receipt=None)) + assert evidence.receipt is not None + for receipt in ( + replace(evidence.receipt, identity_verified=False), + replace(evidence.receipt, operation="tools/call"), + replace(evidence.receipt, config_sha256="0" * 64), + ): + with pytest.raises(MCPSourceError): + engine._receipt(client, RESOURCE, replace(evidence, receipt=receipt)) + with pytest.raises(MCPSourceError): + await client.read(SECOND) + assert harness.reads == [RESOURCE] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("harness", ["tool"], indirect=True) +async def test_explicit_tool_mapping_cannot_change_citation( + storage: Harness, upstream: FastMCP +) -> None: + result = await execute(storage) + assert result.complete and result.status == "ok" + assert storage.reads == ["tool:" + RESOURCE] + assert storage.doc_rows[0]["source_uri"] == resource_uri(storage.source.source_id, RESOURCE) + assert storage.originals == [b"Mapped selected text."] + assert json.loads(storage.doc_rows[0]["metadata"])["mcp_read_operation"] == "tools/call" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("selected", [BINARY, "selected://document/absent"]) +async def test_unreadable_selected_resources_do_not_publish_or_delete( + storage: Harness, + upstream: FastMCP, + monkeypatch: pytest.MonkeyPatch, + selected: str, +) -> None: + retire = AsyncMock(side_effect=AssertionError("no deletion authority")) + monkeypatch.setattr(sync, "retire", retire) + storage.select(resources=(selected,)) + result = await execute(storage) + assert not result.complete and result.removed == 0 and result.status == "failed" + assert result.kind_state["mcp_next_index"] == 0 + assert not storage.originals and not storage.chunk_rows and not storage.doc_rows + storage.listing.assert_not_awaited() + retire.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_partial_set_keeps_success_and_retries_only_failure( + storage: Harness, upstream: FastMCP +) -> None: + h = storage + h.select(two=True) + h.failing_resource = SECOND + result = await execute(h) + assert not result.complete and result.kind_state["mcp_next_index"] == 1 and result.removed == 0 + assert len(h.doc_rows) == 1 + h.listing.assert_not_awaited() + h.saved, h.failing_resource = result.kind_state, "" + result = await execute(h) + assert result.complete and len(h.doc_rows) == 2 + assert h.reads == [RESOURCE, SECOND, SECOND] + + +@pytest.mark.asyncio +async def test_changed_selection_does_not_resume_another_set( + storage: Harness, upstream: FastMCP +) -> None: + h = storage + h.select(two=True) + h.saved = (await execute(h, limit=1)).kind_state + h.select(resources=(SECOND, RESOURCE)) + result = await execute(h, limit=1) + assert not result.complete and result.kind_state["mcp_next_index"] == 1 + assert h.reads == [RESOURCE, SECOND] + h.listing.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_live_contract_refuses_direct_knowledge_publication(storage: Harness) -> None: + storage.select(mode="live") + with pytest.raises(authority.MCPAuthorityError): + await sync.write_document( + replace(storage.source, mirror=MIRROR), + {"id": RESOURCE, "name": "selected"}, + resource_uri(storage.source.source_id, RESOURCE), + "text", + ingested_format="mcp_text", + original=b"text", + ) + assert not storage.originals and not storage.chunk_rows and not storage.doc_rows + + +@pytest.mark.asyncio +async def test_empty_selected_text_does_not_delete_or_publish( + storage: Harness, upstream: FastMCP +) -> None: + storage.text = "" + result = await execute(storage) + assert result.status == "failed" and not result.complete and result.removed == 0 + assert result.kind_state["mcp_next_index"] == 0 + assert not storage.originals and not storage.doc_rows and not storage.chunk_rows + storage.listing.assert_not_awaited() From 8a7865d0f808789d5713ff6d614a352c8aec9dca Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 02:22:20 +0000 Subject: [PATCH 17/30] Explain selected MCP source access before publication Signed-off-by: zlareb1 --- docs/reference/configuration.md | 3 + loom.example.yaml | 14 ++ schemas/loom-settings.schema.json | 18 ++ sdk/python/loom/client.py | 9 + sdk/python/loom/ops.py | 60 +++++++ sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 52 +++++- sdk/typescript/src/generated/ops.ts | 48 +++++- server/knowledge/api/models_mcp_sources.py | 53 ++++++ server/knowledge/api/ops_mcp_sources.py | 17 ++ server/knowledge/app/mcp_connections.py | 3 +- server/knowledge/app/mcp_profiles.py | 2 + server/knowledge/app/mcp_source_preview.py | 132 +++++++++++++++ server/operations/registry.py | 2 + server/settings/catalog.py | 1 + tests/unit/test_mcp_source_preview.py | 160 ++++++++++++++++++ tests/unit/test_mcp_source_profiles.py | 22 ++- 16 files changed, 580 insertions(+), 16 deletions(-) create mode 100644 server/knowledge/api/models_mcp_sources.py create mode 100644 server/knowledge/api/ops_mcp_sources.py create mode 100644 server/knowledge/app/mcp_source_preview.py create mode 100644 tests/unit/test_mcp_source_preview.py diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index cd8cae5741..8c59bad39c 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1014,6 +1014,9 @@ Knowledge documents and conversations: chunking, search floor, thread titles. | `LOOM_KNOWLEDGE_CONNECTED_REGISTRY_PAGE_SIZE` | `int` | `256` | | Registrations per page during root-secret resealing. | | `LOOM_KNOWLEDGE_CONNECTED_OAUTH_TIMEOUT_S` | `float` | `30.0` | | Seconds one connected-account OAuth request may take, including its response. The caller's remaining deadline can shorten this bound. | | `LOOM_KNOWLEDGE_CONNECTED_OAUTH_RESPONSE_MAX_BYTES` | `int` | `65536` | | Bytes read from a connected-account token or identity response; larger metadata replies are refused before parsing. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_PROFILES_JSON` | `str` | `''` | | Operator-approved MCP read profiles as version-1 JSON, at most 8 MiB UTF-8; empty approves none, and profile metadata grants no connection or publication access. | +| `LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED` | `bool` | `True` | | Allow self-service source registration and credential storage or replacement. False refuses those mutations before a probe; existing reads and removal remain available. | +| `LOOM_KNOWLEDGE_MCP_CONNECTIONS_MAX_PER_PERSON` | `int` | `32` | | Active MCP connection slots one canonical person may hold per organization. | | `LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE` | `int` | `8` | live | Active document sources (knowledge.source.add) one namespace may register; an add past it is refused with SOURCE_QUOTA. | | `LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_NAMESPACE` | `int` | `64` | live | Active connected sources per namespace, separate from the shared/crawl quota. | | `LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_PERSON` | `int` | `8` | live | Active connected sources one canonical person may register in one namespace. | diff --git a/loom.example.yaml b/loom.example.yaml index 6dc24f2ed7..b76de84e4d 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -2976,6 +2976,20 @@ settings: # replies are refused before parsing. [restart] # knowledge_connected_oauth_response_max_bytes: 65536 + # Operator-approved MCP read profiles as version-1 JSON, at most 8 MiB UTF-8; empty + # approves none, and profile metadata grants no connection or publication access. + # [restart] + # knowledge_source_mcp_profiles_json: "" + + # Allow self-service source registration and credential storage or replacement. False + # refuses those mutations before a probe; existing reads and removal remain available. + # [restart] + # knowledge_source_self_service_enabled: true + + # Active MCP connection slots one canonical person may hold per organization. + # [restart] + # knowledge_mcp_connections_max_per_person: 32 + # Active document sources (knowledge.source.add) one namespace may register; an add # past it is refused with SOURCE_QUOTA. [live] # knowledge_sources_max_per_namespace: 8 diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index cee1e2e3d7..d13b001524 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -3335,6 +3335,13 @@ "type": "number", "description": "Seconds for the whole optional live-search leg, including final membership checks. At most five; provider credential deadlines may shorten it further." }, + "knowledge_mcp_connections_max_per_person": { + "default": 32, + "maximum": 4096, + "minimum": 1, + "type": "integer", + "description": "Active MCP connection slots one canonical person may hold per organization." + }, "knowledge_mirrored_sources_enabled": { "default": false, "type": "boolean", @@ -3484,6 +3491,12 @@ "type": "integer", "description": "Documents one source holds: its stored ones plus the new ones a turn writes. At it a turn tries no new file, notes how many as `too_many_documents`, and still updates and retires. At most 200,000: each read of the stored copies grows with its square." }, + "knowledge_source_mcp_profiles_json": { + "default": "", + "maxLength": 8388608, + "type": "string", + "description": "Operator-approved MCP read profiles as version-1 JSON, at most 8 MiB UTF-8; empty approves none, and profile metadata grants no connection or publication access." + }, "knowledge_source_mirror_documents_per_pass": { "default": 40, "minimum": 1, @@ -3538,6 +3551,11 @@ "type": "integer", "description": "Documents of stopped mirrored sources retired per cleanup pass, independently of the content-sync budget. Cleanup continues while syncing is switched off." }, + "knowledge_source_self_service_enabled": { + "default": true, + "type": "boolean", + "description": "Allow self-service source registration and credential storage or replacement. False refuses those mutations before a probe; existing reads and removal remain available." + }, "knowledge_source_sync_cap_share": { "default": 0.25, "exclusiveMinimum": 0.0, diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index d257e1099d..25005698f9 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -1601,6 +1601,15 @@ async def source_list( await self._agent.call("knowledge.source.list", body, **options), ) + async def source_mcp_preview( + self, body: _ops.KnowledgeSourceMcpPreviewBody | None = None, /, **options: Any + ) -> _ops.KnowledgeSourceMcpPreviewOutput: + """`knowledge.source.mcp_preview`.""" + return cast( + "_ops.KnowledgeSourceMcpPreviewOutput", + await self._agent.call("knowledge.source.mcp_preview", body, **options), + ) + async def source_mcp_profiles( self, body: _ops.KnowledgeSourceMcpProfilesBody | None = None, /, **options: Any ) -> _ops.KnowledgeSourceMcpProfilesOutput: diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index d69df24f89..bfefd2f2b9 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -201,6 +201,7 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.mcp_preview", "knowledge.source.mcp_profiles", "knowledge.source.parse_links", "knowledge.source.push_configure", @@ -586,6 +587,7 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.mcp_preview", "knowledge.source.mcp_profiles", "knowledge.source.parse_links", "knowledge.source.push_configure", @@ -2753,6 +2755,18 @@ class OpSpec: False, True, ), + "knowledge.source.mcp_preview": OpSpec( + "knowledge.source.mcp_preview", + "KnowledgeSourceMcpPreviewInput", + "KnowledgeSourceMcpPreviewBody", + "KnowledgeSourceMcpPreviewOutput", + True, + "writer", + "experimental", + 5000, + False, + False, + ), "knowledge.source.mcp_profiles": OpSpec( "knowledge.source.mcp_profiles", "KnowledgeSourceMcpProfilesInput", @@ -12084,6 +12098,52 @@ class KnowledgeSourceEntry(TypedDict, total=False): sync: NotRequired["KnowledgeSourceSync"] +class KnowledgeSourceMcpPreviewInput(TypedDict, total=False): + org: Required[str] + namespace: Required[str] + slot: Required[str] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + reader_policy: NotRequired[Literal["owner_only", "collection_copy"]] + resource_ids: Required[list[str]] + + +class KnowledgeSourceMcpPreviewBody(TypedDict, total=False): + org: NotRequired[str] + namespace: NotRequired[str] + slot: Required[str] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + reader_policy: NotRequired[Literal["owner_only", "collection_copy"]] + resource_ids: Required[list[str]] + + +class KnowledgeSourceMcpPreviewOutput(TypedDict, total=False): + namespace: Required[str] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + rule: Required["MCPAccessRule"] + connection_state: Required[Literal["configured", "stopped", "unavailable", "approval_drift"]] + compatibility: NotRequired[Literal["unchecked"]] + permission_evidence: NotRequired[Literal["unsupported"]] + refresh_state: Required[Literal["not_applicable", "enabled", "disabled"]] + selected_count: Required[int] + checked_at: Required[str] + preview_grants_authority: NotRequired[Literal[False]] + limitations: Required[list[str]] + + +class MCPAccessRule(TypedDict, total=False): + access: Required[Literal["owner_only", "collection_wide", "unavailable"]] + reason: NotRequired[str] + stores_copy: Required[bool] + future_items_included: NotRequired[Literal[False]] + upstream_permissions: NotRequired[Literal["unsupported"]] + reader_list_complete: NotRequired[Literal[False]] + collection_readers_receive_copy: NotRequired[bool] + inherited_grants_apply: NotRequired[Literal[True]] + membership_changes_affect_copy: NotRequired[bool] + publication_confirmation_required: NotRequired[bool] + explanation: Required[str] + + class KnowledgeSourceMcpProfilesInput(TypedDict, total=False): "List approved profile declarations for the signed-in caller's organization." diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index f2a3ac84c2..a1f6ec5794 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 = 376 + OP_COUNT = 383 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -142,6 +142,11 @@ module Generated "knowledge.add" => OpSpec.new("knowledge.add", "knowledge", "add", true, false, "writer", "stable", %w[org namespace source_uri content title description tags metadata original_bytes_b64 original_filename blob_content_type agent session_id source_class].freeze, %w[org namespace source_uri content].freeze), "knowledge.bulk_add" => OpSpec.new("knowledge.bulk_add", "knowledge", "bulk_add", true, false, "writer", "stable", %w[org namespace entries agent session_id source_class].freeze, %w[org namespace entries].freeze), "knowledge.bulk_delete" => OpSpec.new("knowledge.bulk_delete", "knowledge", "bulk_delete", true, false, "writer", "experimental", %w[org namespace source_uris].freeze, %w[org namespace source_uris].freeze), + "knowledge.connection.mcp_connect" => OpSpec.new("knowledge.connection.mcp_connect", "knowledge", "connection_mcp_connect", false, false, "viewer", "experimental", %w[org profile_id request_id label bearer].freeze, %w[org profile_id request_id].freeze), + "knowledge.connection.mcp_disconnect" => OpSpec.new("knowledge.connection.mcp_disconnect", "knowledge", "connection_mcp_disconnect", false, false, "viewer", "experimental", %w[org slot].freeze, %w[org slot].freeze), + "knowledge.connection.mcp_discover" => OpSpec.new("knowledge.connection.mcp_discover", "knowledge", "connection_mcp_discover", true, true, "viewer", "experimental", %w[org slot].freeze, %w[org slot].freeze), + "knowledge.connection.mcp_inspect" => OpSpec.new("knowledge.connection.mcp_inspect", "knowledge", "connection_mcp_inspect", true, true, "viewer", "experimental", %w[org slot request_id].freeze, %w[org].freeze), + "knowledge.connection.mcp_list" => OpSpec.new("knowledge.connection.mcp_list", "knowledge", "connection_mcp_list", true, true, "viewer", "experimental", %w[org cursor limit].freeze, %w[org].freeze), "knowledge.dataset_approve" => OpSpec.new("knowledge.dataset_approve", "knowledge", "dataset_approve", false, false, "writer", "experimental", %w[org namespace source_uri dataset_id snapshot_id columns].freeze, %w[org namespace source_uri dataset_id snapshot_id].freeze), "knowledge.dataset_get" => OpSpec.new("knowledge.dataset_get", "knowledge", "dataset_get", true, true, "viewer", "experimental", %w[org namespace source_uri dataset_id sample_rows].freeze, %w[org namespace source_uri].freeze), "knowledge.dedup_list" => OpSpec.new("knowledge.dedup_list", "knowledge", "dedup_list", true, false, "admin", "experimental", %w[org namespace limit include_chunk_clusters].freeze, %w[org namespace].freeze), @@ -169,6 +174,8 @@ 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.mcp_preview" => OpSpec.new("knowledge.source.mcp_preview", "knowledge", "source_mcp_preview", true, false, "writer", "experimental", %w[org namespace slot mode reader_policy resource_ids].freeze, %w[org namespace slot mode resource_ids].freeze), + "knowledge.source.mcp_profiles" => OpSpec.new("knowledge.source.mcp_profiles", "knowledge", "source_mcp_profiles", true, true, "viewer", "experimental", %w[org query cursor limit].freeze, %w[org].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), @@ -1276,6 +1283,36 @@ def bulk_delete(body = nil, request_options: nil, **fields) call_op("knowledge.bulk_delete", body, fields, request_options) end + # `knowledge.connection.mcp_connect` (viewer, writes, experimental). + # Required: org, profile_id, request_id. + def connection_mcp_connect(body = nil, request_options: nil, **fields) + call_op("knowledge.connection.mcp_connect", body, fields, request_options) + end + + # `knowledge.connection.mcp_disconnect` (viewer, writes, experimental). + # Required: org, slot. + def connection_mcp_disconnect(body = nil, request_options: nil, **fields) + call_op("knowledge.connection.mcp_disconnect", body, fields, request_options) + end + + # `knowledge.connection.mcp_discover` (viewer, read-only, experimental). + # Required: org, slot. + def connection_mcp_discover(body = nil, request_options: nil, **fields) + call_op("knowledge.connection.mcp_discover", body, fields, request_options) + end + + # `knowledge.connection.mcp_inspect` (viewer, read-only, experimental). + # Required: org. + def connection_mcp_inspect(body = nil, request_options: nil, **fields) + call_op("knowledge.connection.mcp_inspect", body, fields, request_options) + end + + # `knowledge.connection.mcp_list` (viewer, read-only, experimental). + # Required: org. + def connection_mcp_list(body = nil, request_options: nil, **fields) + call_op("knowledge.connection.mcp_list", body, fields, request_options) + end + # `knowledge.dataset_approve` (writer, writes, experimental). # Approve a dataset's schema, retyping the columns named: its rows are # Required: org, namespace, source_uri, dataset_id, snapshot_id. @@ -1463,6 +1500,19 @@ def source_list(body = nil, request_options: nil, **fields) call_op("knowledge.source.list", body, fields, request_options) end + # `knowledge.source.mcp_preview` (writer, writes, Idempotency-Key, experimental). + # Required: org, namespace, slot, mode, resource_ids. + def source_mcp_preview(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_preview", body, fields, request_options) + end + + # `knowledge.source.mcp_profiles` (viewer, read-only, experimental). + # List approved profile declarations for the signed-in caller's organization. + # Required: org. + def source_mcp_profiles(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_profiles", 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/typescript/src/generated/ops.ts b/sdk/typescript/src/generated/ops.ts index 764a17d629..e65b0ed833 100644 --- a/sdk/typescript/src/generated/ops.ts +++ b/sdk/typescript/src/generated/ops.ts @@ -4522,6 +4522,49 @@ export interface KnowledgeSourceListOutput { accepts_sources?: boolean; } +export interface KnowledgeSourceMcpPreviewInput { + /** The authenticated organization. */ + org: string; + /** The ordinary destination collection or namespace. */ + namespace: string; + /** The signed-in owner's MCP connection slot. */ + slot: string; + /** Live lookup, a selected snapshot, or periodic refresh of the fixed selection. */ + mode: "live" | "snapshot" | "selected_refresh"; + /** Requested copy audience; default owner-only. */ + reader_policy?: "owner_only" | "collection_copy"; + /** Between 1 and 1000 explicit resource identities, without recursion. */ + resource_ids: string[]; +} + +export interface MCPAccessRule { + access: "owner_only" | "collection_wide" | "unavailable"; + reason?: string; + stores_copy: boolean; + future_items_included?: false; + upstream_permissions?: "unsupported"; + reader_list_complete?: false; + collection_readers_receive_copy?: boolean; + inherited_grants_apply?: true; + membership_changes_affect_copy?: boolean; + publication_confirmation_required?: boolean; + explanation: string; +} + +export interface KnowledgeSourceMcpPreviewOutput { + namespace: string; + mode: "live" | "snapshot" | "selected_refresh"; + rule: MCPAccessRule; + connection_state: "configured" | "stopped" | "unavailable" | "approval_drift"; + compatibility?: "unchecked"; + permission_evidence?: "unsupported"; + refresh_state: "not_applicable" | "enabled" | "disabled"; + selected_count: number; + checked_at: string; + preview_grants_authority?: false; + limitations: string[]; +} + export interface KnowledgeSourceMcpProfilesInput { /** The caller's authenticated organization. */ org: string; @@ -10784,6 +10827,7 @@ export type OpName = | "knowledge.source.check" | "knowledge.source.inspect" | "knowledge.source.list" + | "knowledge.source.mcp_preview" | "knowledge.source.mcp_profiles" | "knowledge.source.parse_links" | "knowledge.source.push_configure" @@ -11169,6 +11213,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.mcp_preview": { input: KnowledgeSourceMcpPreviewInput; output: KnowledgeSourceMcpPreviewOutput }; "knowledge.source.mcp_profiles": { input: KnowledgeSourceMcpProfilesInput; output: KnowledgeSourceMcpProfilesOutput }; "knowledge.source.parse_links": { input: KnowledgeSourceParseLinksInput; output: KnowledgeSourceParseLinksOutput }; "knowledge.source.push_configure": { input: KnowledgeSourcePushConfigureInput; output: PushStatusOutput }; @@ -11554,6 +11599,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.mcp_preview", group: "knowledge", method: "sourceMcpPreview", idempotent: true, role: "writer", maturity: "experimental", budgetP99Ms: 5000, audit: false, readOnly: false }, { name: "knowledge.source.mcp_profiles", group: "knowledge", method: "sourceMcpProfiles", idempotent: true, role: "viewer", maturity: "experimental", budgetP99Ms: 5000, 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 }, @@ -11780,4 +11826,4 @@ export const OP_BY_NAME: Readonly> = Object.fromEntries( OPS.map((o) => [o.name, o]), ) as Readonly>; -export const GENERATED_OP_COUNT = 382; +export const GENERATED_OP_COUNT = 383; diff --git a/server/knowledge/api/models_mcp_sources.py b/server/knowledge/api/models_mcp_sources.py new file mode 100644 index 0000000000..f4faf9e0c0 --- /dev/null +++ b/server/knowledge/api/models_mcp_sources.py @@ -0,0 +1,53 @@ +"""Selected MCP source scope and explanatory access, without credentials.""" + +from typing import Literal + +from pydantic import BaseModel, Field + +from server.knowledge.api.models_mcp_connections import _Input + + +class MCPSourcePreviewInput(_Input): + org: str = Field(description="The authenticated organization.") + namespace: str = Field(description="The ordinary destination collection or namespace.") + slot: str = Field(max_length=36, description="The signed-in owner's MCP connection slot.") + mode: Literal["live", "snapshot", "selected_refresh"] = Field( + description="Live lookup, a selected snapshot, or periodic refresh of the fixed selection." + ) + reader_policy: Literal["owner_only", "collection_copy"] = Field( + default="owner_only", description="Requested copy audience; default owner-only." + ) + resource_ids: list[str] = Field( + min_length=1, + max_length=1000, + repr=False, + description="Between 1 and 1000 explicit resource identities, without recursion.", + ) + + +class MCPAccessRule(BaseModel): + access: Literal["owner_only", "collection_wide", "unavailable"] + reason: str = "" + stores_copy: bool + future_items_included: Literal[False] = False + upstream_permissions: Literal["unsupported"] = "unsupported" + reader_list_complete: Literal[False] = False + collection_readers_receive_copy: bool = False + inherited_grants_apply: Literal[True] = True + membership_changes_affect_copy: bool = False + publication_confirmation_required: bool = False + explanation: str + + +class MCPSourcePreviewOutput(BaseModel): + namespace: str + mode: Literal["live", "snapshot", "selected_refresh"] + rule: MCPAccessRule + connection_state: Literal["configured", "stopped", "unavailable", "approval_drift"] + compatibility: Literal["unchecked"] = "unchecked" + permission_evidence: Literal["unsupported"] = "unsupported" + refresh_state: Literal["not_applicable", "enabled", "disabled"] + selected_count: int + checked_at: str + preview_grants_authority: Literal[False] = False + limitations: list[str] diff --git a/server/knowledge/api/ops_mcp_sources.py b/server/knowledge/api/ops_mcp_sources.py new file mode 100644 index 0000000000..a272d115ec --- /dev/null +++ b/server/knowledge/api/ops_mcp_sources.py @@ -0,0 +1,17 @@ +"""Selected source setup uses the common transport and destination grants.""" + +from server.knowledge.api.models_mcp_sources import MCPSourcePreviewInput, MCPSourcePreviewOutput +from server.knowledge.app.mcp_source_preview import handle_mcp_source_preview +from server.operations.base import Operation, Role + +OPERATIONS: list[Operation] = [ + Operation( + name="knowledge.source.mcp_preview", + input_model=MCPSourcePreviewInput, + output_model=MCPSourcePreviewOutput, + handler=handle_mcp_source_preview, + idempotent=True, + required_role=Role.WRITER, + maturity="experimental", + ), +] diff --git a/server/knowledge/app/mcp_connections.py b/server/knowledge/app/mcp_connections.py index 9e4c07cd71..c7ebee07ae 100644 --- a/server/knowledge/app/mcp_connections.py +++ b/server/knowledge/app/mcp_connections.py @@ -32,6 +32,7 @@ MCPSlotInput, ) from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app.mcp_contracts import decode_envelope, encode_envelope from server.knowledge.app.mcp_profiles import ( FrozenProfileDefinition, MCPProfileError, @@ -43,8 +44,6 @@ ConnectionEnvelope, MCPSourceContractError, bind_envelope, - decode_envelope, - encode_envelope, is_mcp_slot, ) from server.knowledge.store import connected_accounts as store diff --git a/server/knowledge/app/mcp_profiles.py b/server/knowledge/app/mcp_profiles.py index ec0a50bea4..541c070ef7 100644 --- a/server/knowledge/app/mcp_profiles.py +++ b/server/knowledge/app/mcp_profiles.py @@ -20,6 +20,7 @@ MCPToolMapping, validate_mcp_tool_mapping, ) +from server.knowledge.app.mcp_contracts import validate_source_contract from server.knowledge.domain.mcp_sources import ( ConnectionEnvelope, MCPSourceContractError, @@ -376,6 +377,7 @@ def build_mcp_source_client( if not isinstance(contract, SourceContract): raise MCPProfileError() contract = SourceContract.model_validate(contract) + validate_source_contract(contract) if ( contract.slot, contract.generation, diff --git a/server/knowledge/app/mcp_source_preview.py b/server/knowledge/app/mcp_source_preview.py new file mode 100644 index 0000000000..5b0bcf0e28 --- /dev/null +++ b/server/knowledge/app/mcp_source_preview.py @@ -0,0 +1,132 @@ +"""Explain one owner's selected scope without granting access or importing it.""" + +from datetime import UTC, datetime +from typing import Literal + +from server.auth import authz +from server.core.errors import AuthInsufficientError +from server.knowledge.api.models_mcp_sources import ( + MCPAccessRule, + MCPSourcePreviewInput, + MCPSourcePreviewOutput, +) +from server.knowledge.app import mcp_connections as connections +from server.knowledge.app import sources +from server.knowledge.app.mcp_contracts import validate_source_contract +from server.knowledge.domain.mcp_sources import ResourceIdentity, SourceContract +from server.knowledge.store import connected_accounts as account_store +from server.operations.base import Role +from server.settings import settings + + +def access_rule( + mode: str, policy: str, *, copy_approved: bool, administrator: bool +) -> MCPAccessRule: + """Collection membership cannot establish an upstream reader permission.""" + stores_copy = mode != "live" + if mode not in {"live", "snapshot", "selected_refresh"} or policy not in { + "owner_only", + "collection_copy", + }: + return MCPAccessRule( + stores_copy=stores_copy, + access="unavailable", + reason="unsupported_policy", + explanation="This source mode or access policy is unsupported.", + ) + if policy == "owner_only": + return MCPAccessRule( + stores_copy=stores_copy, + access="owner_only", + explanation=( + "Only the source owner with current destination access may read this material. " + "Adding collection members or changing its parent does not grant them access. " + "Upstream document permissions are unavailable." + ), + ) + reason = "shared_live_unsupported" if mode == "live" else "publication_not_authorized" + if mode == "live" or not copy_approved or not administrator: + return MCPAccessRule( + stores_copy=stores_copy, + access="unavailable", + reason=reason, + explanation="The current source and destination policy do not authorize this audience.", + ) + return MCPAccessRule( + stores_copy=stores_copy, + access="collection_wide", + collection_readers_receive_copy=True, + membership_changes_affect_copy=True, + publication_confirmation_required=True, + explanation=( + "Permitted destination readers may read the stored copy, including readers admitted " + "through inherited or future grants. Changing membership or its parent may broaden " + "access. This publishes a copy and does not preserve upstream document permissions. " + "Publication requires explicit authority over the selected material." + ), + ) + + +async def handle_mcp_source_preview(input: MCPSourcePreviewInput) -> MCPSourcePreviewOutput: + async with connections._errors(): + owner = await connections._owner(input.org) + connections._check_slot(input.slot) + if not await authz.row_in_scope(input.org, input.namespace, Role.WRITER): + raise AuthInsufficientError("destination writer access is required") + await sources._require_source_namespace(input.org, input.namespace) + await sources._require_no_erasure(input.org, input.namespace) + account = await account_store.get(input.org, owner, input.slot) + if account is None: + raise connections._Refused("MCP_CONNECTION_UNAVAILABLE") + connections._row_scope(account, input.org, owner, input.slot) + entry = await connections._entry(account) + approved = False + if entry.state == "configured": + await connections._validate(account) + profile, envelope = connections._binding(account) + contract = SourceContract( + version=1, + slot=input.slot, + generation=account.connection_id, + profile_id=envelope.profile_id, + profile_sha256=envelope.profile_sha256, + mode=input.mode, + reader_policy=input.reader_policy, + resources=tuple( + ResourceIdentity(type="resource", id=r) for r in input.resource_ids + ), + ) + validate_source_contract(contract) + approved = profile.metadata.allow_collection_copy + rule = access_rule( + input.mode, + input.reader_policy, + copy_approved=approved, + administrator=await authz.row_in_scope(input.org, input.namespace, Role.ADMIN), + ) + if entry.state != "configured": + rule.access, rule.reason = "unavailable", "connection_" + entry.state + rule.explanation = "The owner's connection is unavailable for this selection." + await connections._owner(input.org, owner) + if not await authz.row_in_scope(input.org, input.namespace, Role.WRITER): + raise AuthInsufficientError("destination writer access is required") + if entry.state == "configured": + await connections._validate(account) + refresh: Literal["not_applicable", "enabled", "disabled"] = "not_applicable" + if input.mode == "selected_refresh": + refresh = "enabled" if settings.knowledge_source_sync_enabled else "disabled" + return MCPSourcePreviewOutput( + namespace=input.namespace, + mode=input.mode, + rule=rule, + connection_state=entry.state, + refresh_state=refresh, + selected_count=len(input.resource_ids), + checked_at=datetime.now(UTC).isoformat(), + limitations=[ + "Remote compatibility and selected-resource readability are unchecked.", + "No upstream ACL, complete enumeration, deletion or group evidence is available.", + "Only selected identities are included; future matching items are excluded.", + "Preview grants no authority; mutation and every later read revalidate access.", + ], + ) diff --git a/server/operations/registry.py b/server/operations/registry.py index 5303336d2f..334bd02036 100644 --- a/server/operations/registry.py +++ b/server/operations/registry.py @@ -34,6 +34,7 @@ from server.knowledge.api import ops_knowledge as knowledge from server.knowledge.api import ops_mcp_connections as knowledge_mcp_connections from server.knowledge.api import ops_mcp_profiles as knowledge_mcp_profiles +from server.knowledge.api import ops_mcp_sources as knowledge_mcp_sources 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 @@ -71,6 +72,7 @@ knowledge_sources, knowledge_mcp_profiles, knowledge_mcp_connections, + knowledge_mcp_sources, connections, knowledge_source_push, knowledge_gaps, diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 22b7d5d16a..4852679929 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -6441,6 +6441,7 @@ class TrackerSettings(BaseModel): "knowledge.source.list": 300, # Verified owner lookup and a cold bounded operator catalog parse; no source request. "knowledge.source.mcp_profiles": 5000, + "knowledge.source.mcp_preview": 5000, # Local owner enrollment/retirement is bounded; discovery also waits for the MCP server. "knowledge.connection.mcp_connect": 30000, "knowledge.connection.mcp_disconnect": 30000, diff --git a/tests/unit/test_mcp_source_preview.py b/tests/unit/test_mcp_source_preview.py new file mode 100644 index 0000000000..5506a83570 --- /dev/null +++ b/tests/unit/test_mcp_source_preview.py @@ -0,0 +1,160 @@ +"""A destination never supplies missing upstream publication authority.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from server.knowledge.api.models_mcp_connections import MCPConnectionEntry +from server.knowledge.api.models_mcp_sources import MCPSourcePreviewInput +from server.knowledge.app import mcp_source_preview as preview +from server.knowledge.app.mcp_source_preview import access_rule +from server.operations.base import Role + + +@pytest.mark.parametrize("team", [False, True]) +def test_owner_only_is_independent_of_destination_membership(team: bool) -> None: + rule = access_rule("snapshot", "owner_only", copy_approved=False, administrator=team) + assert rule.access == "owner_only" + assert not rule.collection_readers_receive_copy + assert rule.upstream_permissions == "unsupported" + assert not rule.reader_list_complete + + +@pytest.mark.parametrize("mode", ["snapshot", "selected_refresh"]) +def test_copy_rule_names_inherited_and_future_readers(mode: str) -> None: + rule = access_rule(mode, "collection_copy", copy_approved=True, administrator=True) + assert rule.access == "collection_wide" + assert rule.collection_readers_receive_copy + assert rule.inherited_grants_apply + assert rule.membership_changes_affect_copy + assert rule.publication_confirmation_required + assert rule.upstream_permissions == "unsupported" + + +@pytest.mark.parametrize("approved,admin", [(False, False), (False, True), (True, False)]) +def test_copy_requires_operator_policy_and_current_destination_authority( + approved: bool, admin: bool +) -> None: + rule = access_rule("snapshot", "collection_copy", copy_approved=approved, administrator=admin) + assert rule.access == "unavailable" + assert not rule.collection_readers_receive_copy + assert rule.reason == "publication_not_authorized" + + +def test_live_copy_policy_cannot_create_implicit_shared_connection() -> None: + rule = access_rule("live", "collection_copy", copy_approved=True, administrator=True) + assert rule.access == "unavailable" and rule.reason == "shared_live_unsupported" + + +def test_live_owner_lookup_reports_no_stored_copy() -> None: + rule = access_rule("live", "owner_only", copy_approved=False, administrator=False) + assert rule.access == "owner_only" and not rule.stores_copy + assert not rule.future_items_included + + +@pytest.mark.parametrize("mode,policy", [("unknown", "owner_only"), ("snapshot", "mirrored")]) +def test_unknown_policy_is_unavailable_without_guessing(mode: str, policy: str) -> None: + rule = access_rule(mode, policy, copy_approved=True, administrator=True) + assert rule.access == "unavailable" + + +@pytest.fixture +def world(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + state = SimpleNamespace(admin=False, owner="owner-a", allowed=True, valid=True, enabled=True) + account = SimpleNamespace( + org="org-a", + subject="owner-a", + kind="mcp:" + "a" * 32, + connection_id="b" * 32 + "/1" + "c" * 31, + ) + + async def owner(org: str, expected: str | None = None) -> str: + if org != "org-a" or (expected is not None and expected != state.owner): + raise preview.connections._Refused("MCP_CONNECTION_UNAVAILABLE") + return state.owner + + async def scoped(org: str, namespace: str, role: Role) -> bool: + assert (org, namespace) == ("org-a", "col-destination") + return state.allowed and (state.admin or role == Role.WRITER) + + async def entry(account: object) -> MCPConnectionEntry: + return MCPConnectionEntry( + slot="mcp:" + "a" * 32, + generation="b" * 32 + "/1" + "c" * 31, + state="configured" if state.valid else "stopped", + ) + + monkeypatch.setattr(preview.connections, "_owner", owner) + monkeypatch.setattr(preview.connections, "_entry", entry) + state.get = AsyncMock(return_value=account) + monkeypatch.setattr(preview.connections.store, "get", state.get) + state.validate = AsyncMock() + monkeypatch.setattr(preview.connections, "_validate", state.validate) + monkeypatch.setattr(preview.authz, "row_in_scope", scoped) + monkeypatch.setattr(preview.sources, "_require_source_namespace", AsyncMock()) + monkeypatch.setattr(preview.sources, "_require_no_erasure", AsyncMock()) + monkeypatch.setattr( + preview.connections, + "_binding", + lambda account: ( + SimpleNamespace(metadata=SimpleNamespace(allow_collection_copy=True)), + SimpleNamespace(profile_id="approved", profile_sha256="d" * 64), + ), + ) + monkeypatch.setattr(preview, "settings", SimpleNamespace(knowledge_source_sync_enabled=False)) + state.input = MCPSourcePreviewInput( + org="org-a", + namespace="col-destination", + slot=account.kind, + mode="selected_refresh", + resource_ids=["opaque-selected-id"], + ) + return state + + +@pytest.mark.asyncio +async def test_preview_is_explicit_about_disabled_refresh_and_unchecked_remote( + world: SimpleNamespace, +) -> None: + result = await preview.handle_mcp_source_preview(world.input) + assert result.refresh_state == "disabled" + assert result.compatibility == "unchecked" and result.permission_evidence == "unsupported" + assert result.rule.access == "owner_only" and not result.preview_grants_authority + assert "opaque-selected-id" not in result.model_dump_json() + assert world.validate.await_count == 2 + + +@pytest.mark.asyncio +async def test_wrong_org_refuses_before_account_read(world: SimpleNamespace) -> None: + with pytest.raises(preview.connections._Refused): + await preview.handle_mcp_source_preview(world.input.model_copy(update={"org": "org-b"})) + world.get.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_owner_scope_is_checked_on_returned_account(world: SimpleNamespace) -> None: + world.owner = "owner-b" + with pytest.raises(preview.connections._Refused): + await preview.handle_mcp_source_preview(world.input) + world.get.assert_awaited_once_with("org-a", "owner-b", "mcp:" + "a" * 32) + + +@pytest.mark.asyncio +async def test_stopped_account_has_no_readable_or_publishable_rule(world: SimpleNamespace) -> None: + world.valid = False + result = await preview.handle_mcp_source_preview(world.input) + assert result.connection_state == "stopped" and result.rule.access == "unavailable" + assert result.rule.reason == "connection_stopped" + world.validate.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_preview_does_not_treat_explanatory_copy_rule_as_confirmation( + world: SimpleNamespace, +) -> None: + world.admin = True + input = world.input.model_copy(update={"reader_policy": "collection_copy"}) + result = await preview.handle_mcp_source_preview(input) + assert result.rule.access == "collection_wide" + assert result.rule.publication_confirmation_required and not result.preview_grants_authority diff --git a/tests/unit/test_mcp_source_profiles.py b/tests/unit/test_mcp_source_profiles.py index 639c3eb253..52a6dce458 100644 --- a/tests/unit/test_mcp_source_profiles.py +++ b/tests/unit/test_mcp_source_profiles.py @@ -396,21 +396,19 @@ def test_tampered_models_are_revalidated() -> None: client(profile, sealed, contract=contract) -def test_real_constructor_checks_schema_semantics_only_when_building() -> None: +def test_catalog_rejects_unsafe_schema_before_building() -> None: mapping = tool_mapping() mapping["input_schema"]["$ref"] = "https://unapproved.example/schema" - profiles = catalog( - row( - config={ - "endpoint": ENDPOINT, - "approved_tools": ["read_document"], - "read": mapping, - } - ) - ) - assert profiles.page("org-a").items[0].id == "approved" with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): - client(profiles.get("org-a", "approved")) + catalog( + row( + config={ + "endpoint": ENDPOINT, + "approved_tools": ["read_document"], + "read": mapping, + } + ) + ) def test_offline_catalog_does_not_instantiate_clients(monkeypatch: pytest.MonkeyPatch) -> None: From 1094ea2e59e1ba35ce7d90d6f5c69379e7d2cbf7 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 02:32:53 +0000 Subject: [PATCH 18/30] Export the generated analyzer manifest after a stale-shape failure Signed-off-by: zlareb1 --- .github/workflows/ci.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index be00082dd5..378d564e1f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -913,8 +913,19 @@ jobs: # with the builders. ~10 s; a rejection here is a statement that would # fail on a deployed server. - name: analyzer statement corpus + id: analyzer-corpus if: matrix.part == 'isolation' && steps.migrate.outcome == 'success' && !cancelled() run: pytest tests/analyzer -q + - name: Render analyzer manifest candidate after a failed corpus check + if: failure() && steps.analyzer-corpus.outcome == 'failure' + run: python -m tests.analyzer.corpus --write + - name: Upload analyzer manifest candidate + if: failure() && steps.analyzer-corpus.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: generated-analyzer-shapes + path: tests/analyzer/shapes.txt + if-no-files-found: error - name: Upload server log on failure if: failure() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 From 0d90d7c3fb4012c5b740af5ba4ea3e144540f6a8 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 02:32:55 +0000 Subject: [PATCH 19/30] Export the generated operation reach manifest after a failed check Signed-off-by: zlareb1 --- .github/workflows/ci.yml | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 378d564e1f..1258482052 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -110,11 +110,22 @@ jobs: # server/operations/reach_manifest.py are generated too; the unit suite # checks them, this step fails faster. - name: docs reference and reach manifest are current + id: generated-references run: | python scripts/codegen/settings_reference.py --check python scripts/codegen/settings_schema.py --check python scripts/codegen/docs_reference.py --check python scripts/codegen/op_reach_census.py --check + - name: Render reach manifest candidate after a generated-reference failure + if: failure() && steps.generated-references.outcome == 'failure' + run: python scripts/codegen/op_reach_census.py --write-manifest + - name: Upload reach manifest candidate + if: failure() && steps.generated-references.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: generated-reach-manifest + path: server/operations/reach_manifest.py + if-no-files-found: error # The SDK ships py.typed: it is type-checked strictly # on its own, apart from the server's ratchet below. - name: mypy --strict on the Python SDK From bdd5f2e183b7fea96d35a189bf4d3897d1ecc64f Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 03:35:25 +0000 Subject: [PATCH 20/30] Bind selected sources to owner publication authority Checkpoint source controls and scope revisions while per-document protected read admission is completed. Generic source execution and public surfaces remain unfinished. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-setup.md | 108 ++++ server/knowledge/api/models_mcp_sources.py | 142 ++++ server/knowledge/api/ops_mcp_sources.py | 120 +++- server/knowledge/app/mcp_connections.py | 4 +- server/knowledge/app/mcp_contracts.py | 16 +- server/knowledge/app/mcp_source_authority.py | 103 ++- server/knowledge/app/mcp_source_ops.py | 518 +++++++++++++++ server/knowledge/app/mcp_source_preview.py | 21 +- server/knowledge/app/source_access.py | 38 +- server/knowledge/app/source_sync_mcp.py | 12 +- server/knowledge/domain/mcp_sources.py | 33 + server/knowledge/store/sources.py | 31 + tests/unit/test_mcp_copy_consent.py | 84 +++ tests/unit/test_mcp_source_contract.py | 19 + tests/unit/test_mcp_source_ops.py | 642 +++++++++++++++++++ tests/unit/test_mcp_source_read_policy.py | 153 +++++ tests/unit/test_mcp_source_sync.py | 58 +- 17 files changed, 2047 insertions(+), 55 deletions(-) create mode 100644 docs/architecture/mcp-source-setup.md create mode 100644 server/knowledge/app/mcp_source_ops.py create mode 100644 tests/unit/test_mcp_copy_consent.py create mode 100644 tests/unit/test_mcp_source_ops.py create mode 100644 tests/unit/test_mcp_source_read_policy.py diff --git a/docs/architecture/mcp-source-setup.md b/docs/architecture/mcp-source-setup.md new file mode 100644 index 0000000000..445e63c365 --- /dev/null +++ b/docs/architecture/mcp-source-setup.md @@ -0,0 +1,108 @@ +# MCP source setup + +MCP source controls register a fixed selection against the signed-in owner's +connection and an ordinary destination namespace or collection. They use the +common operation transport and the existing source registry, state and retirement +machinery. The automatic personal namespace cannot hold these sources. + +## Setup and identity + +Connect an account, discover its configured read capabilities, choose exact +resource IDs and a destination, then preview the access rule before registration. +Connecting, listing and previewing import no documents. Registration discovers +whether the configured resources or reviewed read mapping are available. An +action-only server cannot pass this check. Discovery does not read the selection +or prove that the owner can read each document. + +`knowledge.source.mcp_add` takes `org`, `namespace`, the owner's `slot`, a UUID +`request_id`, ordered `resource_ids`, `mode`, `reader_policy`, an optional `label` +and `confirm_copy_authority`. It accepts no owner, endpoint, tool mapping, schema +or credential. Operator configuration and the authenticated connection supply +those values. The configured selection and UTF-8 byte limits apply before +admission. + +The registry name and source UUID derive from the organization, destination, +canonical owner, connection slot and request UUID. Labels are bounded display +metadata. Retrying a lost response returns only the exact active registration +with the same binding, selection, mode, audience and label. Changed arguments, +a stopped connection, a paused or retired source, or a replacement connection +refuse. A replacement binding requires a separate registration and consent; +existing copies, history and checkpoints keep their identity. + +## Modes and access + +| Mode | Stored content | Scope and refresh | +| --- | --- | --- | +| `live` | No knowledge copy | Only selected IDs; durable import and explicit refresh are unavailable | +| `snapshot` | A selected copy | One import per selection or explicit refresh | +| `selected_refresh` | A selected copy | Periodic attempts for those exact IDs when source sync is enabled | + +No mode includes recursion or future matching items. Notifications, incomplete +listings, read refusals and missing resources are not deletion instructions. +Upstream ACLs, complete enumeration and deletion tracking remain unsupported. +A registered state is not an attestation of current upstream access. Responses +report whether global source sync is disabled; accepting a refresh request does +not mean an import has completed. + +`owner_only` requires both the source owner and current destination access. +Adding collection members or broadening inherited grants does not publish this +material. `collection_copy` means intentional publication through the +destination's current, inherited and future reader grants. It does not mirror +upstream permissions. + +A collection copy requires an approved operator profile, current destination +administrator authority and explicit confirmation of publication authority over +the exact selected material. The handler creates a versioned consent record +binding the authenticated publisher, destination and hash of the ordered exact +IDs. The caller cannot supply this proof. An update of a collection copy requires +fresh confirmation. Consent cannot authorize live sharing, a different audience +or a wider selection. Admission still requires the execution authority helper to +accept the entire proposed row. The current execution authority refuses +collection copies; confirmation alone cannot register one. + +## Lifecycle controls + +| Operation | Effect on source and retained content | +| --- | --- | +| `knowledge.source.mcp_list` | Lists only the caller's registrations in the requested destination | +| `knowledge.source.mcp_inspect` | Returns only an owned source; a foreign ID answers as missing | +| `knowledge.source.mcp_update` | Replaces the fixed selection, mode, audience and label; retained IDs keep source document identity | +| `knowledge.source.mcp_pause` | Sets contract pause state; retains registration, copies and checkpoints | +| `knowledge.source.mcp_resume` | Revalidates the original connection binding before clearing pause | +| `knowledge.source.mcp_refresh` | Requests an explicit import attempt for a copy mode through existing source state | +| `knowledge.source.mcp_remove` | Retires the source, retaining copies unless `delete_documents=true` explicitly requests asynchronous erasure | + +Removing selected IDs does not declare upstream deletion or request erasure of +stored copies. Retirement and pause refuse source reads while retaining content; +retention does not promise that the copies remain readable. Erasure requests use +the existing retirement machinery and report `erasure_requested`, without +claiming deletion has finished. Unsupported contract versions remain opaque and +can be inspected as unsupported or retired without interpreting their payloads. + +Disabling self-service blocks registration before any remote discovery. Existing +list, inspect and remove controls remain available. Selection changes use the +existing connection and cannot replace credentials. + +## Write boundary + +Remote discovery finishes before writer locks are taken. Mutations acquire the +SCIM subject barrier, connection account lease and destination source lease in +that order. Under those locks they recheck the caller, destination grants, +namespace validity, erasure state and exact stored registration. Add also checks +name availability and existing quotas. Immediately before admission, the +registration authority checks the current connection, profile approval, standing, +fence and destination writer authority. + +Generic source rows carry `generic_config_json`, `generic_items_json`, +`connection_slot` and a contract version. The ordinary `config` and `items` +projections remain empty. Application codecs apply deployment limits to the +stored opaque columns. Source changes retain the registration UUID and use the +existing store's complete version-row writes; no separate source database or +worker framework is introduced. + +Refresh requests merge into existing state without clearing checkpoints. A +selection marker prevents a label-only change from requesting another snapshot. +Mutation audit subjects omit private source labels, resource IDs and counts. + +See [document sources](document-sources.md) for the shared document, retirement +and erasure lifecycle. diff --git a/server/knowledge/api/models_mcp_sources.py b/server/knowledge/api/models_mcp_sources.py index f4faf9e0c0..d240d89867 100644 --- a/server/knowledge/api/models_mcp_sources.py +++ b/server/knowledge/api/models_mcp_sources.py @@ -51,3 +51,145 @@ class MCPSourcePreviewOutput(BaseModel): checked_at: str preview_grants_authority: Literal[False] = False limitations: list[str] + + +class MCPSourceAddInput(MCPSourcePreviewInput): + request_id: str = Field( + max_length=36, description="A client UUID retained across uncertain registration retries." + ) + label: str | None = Field( + default=None, + max_length=256, + repr=False, + description="Optional source display label; default none; conveys no remote identity.", + ) + confirm_copy_authority: bool = Field( + default=False, + strict=True, + description=( + "Confirm authority to publish this selection through current and future " + "collection grants; default false." + ), + ) + + +class MCPSourceScopeInput(_Input): + namespace: str = Field(description="The ordinary destination collection or namespace.") + + +class MCPSourceListInput(MCPSourceScopeInput): + cursor: str | None = Field( + default=None, + max_length=2048, + description="Continuation for this exact listing; default none.", + ) + limit: int = Field( + default=20, + ge=1, + le=20, + strict=True, + description="Source summaries per page, from 1 to 20; default 20.", + ) + include_retired: bool = Field( + default=False, + strict=True, + description="Include this owner's retired registrations; default false.", + ) + + +class MCPSourceInput(MCPSourceScopeInput): + name: str = Field(max_length=64, description="The opaque source registry name returned by add.") + + +class MCPSourceUpdateInput(MCPSourceInput): + if_scope_revision: int | None = Field( + default=None, + ge=1, + le=2**63 - 1, + strict=True, + description=( + "Require this current scope revision before changing selection; default unconditional." + ), + ) + resource_ids: list[str] = Field( + min_length=1, + max_length=1000, + repr=False, + description="The complete ordered fixed selection replacing the current selected IDs.", + ) + mode: Literal["live", "snapshot", "selected_refresh"] = Field( + description="Live lookup, a selected snapshot, or periodic refresh of this fixed selection." + ) + label: str | None = Field( + default=None, + max_length=256, + repr=False, + description="Replacement display label, or none to clear it; default none.", + ) + confirm_copy_authority: bool = Field( + default=False, + strict=True, + description="Confirm publication authority for this replacement selection; default false.", + ) + + +class MCPSourceRemoveInput(MCPSourceInput): + confirm: str = Field( + max_length=64, description="Repeat the exact opaque source name to retire." + ) + delete_documents: bool = Field( + default=False, + strict=True, + description="Request asynchronous erasure of stored copies; default false retains them.", + ) + + +class MCPSourceSummary(BaseModel): + name: str + source_id: str + slot: str + namespace: str + state: Literal["registered", "paused", "retired", "unsupported"] + mode: Literal["live", "snapshot", "selected_refresh"] | None = None + reader_policy: Literal["owner_only", "collection_copy"] | None = None + scope_revision: int | None = None + label: str | None = None + selected_count: int | None = None + sync_enabled: bool + refresh_state: Literal[ + "not_applicable", "enabled", "disabled", "paused", "retired", "unsupported" + ] + compatibility: Literal["unchecked"] = "unchecked" + upstream_permissions: Literal["unsupported"] = "unsupported" + complete_enumeration: Literal[False] = False + upstream_deletion_tracking: Literal[False] = False + future_items_included: Literal[False] = False + current_access_attested: Literal[False] = False + local_authority: Literal["current", "unavailable", "unchecked"] = Field( + default="unchecked", + description="Current local source and account authority; no upstream ACL evidence.", + ) + pending_erasure: bool = False + rule: MCPAccessRule | None = None + + +class MCPSourceEntry(MCPSourceSummary): + resource_ids: list[str] = Field(default_factory=list, repr=False) + + +class MCPSourceOutput(BaseModel): + source: MCPSourceEntry + copies: Literal["retained", "erasure_requested"] = Field( + default="retained", description="Disposition of any copies, including earlier source modes." + ) + refresh_requested: bool = False + + +class MCPSourceListOutput(BaseModel): + sources: list[MCPSourceSummary] + next_cursor: str | None = None + + +class MCPSourceInspectOutput(BaseModel): + found: bool + source: MCPSourceEntry | None = None diff --git a/server/knowledge/api/ops_mcp_sources.py b/server/knowledge/api/ops_mcp_sources.py index a272d115ec..b2e89e808b 100644 --- a/server/knowledge/api/ops_mcp_sources.py +++ b/server/knowledge/api/ops_mcp_sources.py @@ -1,6 +1,28 @@ """Selected source setup uses the common transport and destination grants.""" -from server.knowledge.api.models_mcp_sources import MCPSourcePreviewInput, MCPSourcePreviewOutput +from server.knowledge.api.models_mcp_sources import ( + MCPSourceAddInput, + MCPSourceInput, + MCPSourceInspectOutput, + MCPSourceListInput, + MCPSourceListOutput, + MCPSourceOutput, + MCPSourcePreviewInput, + MCPSourcePreviewOutput, + MCPSourceRemoveInput, + MCPSourceUpdateInput, +) +from server.knowledge.app.mcp_source_ops import ( + handle_mcp_source_add, + handle_mcp_source_inspect, + handle_mcp_source_list, + handle_mcp_source_pause, + handle_mcp_source_refresh, + handle_mcp_source_remove, + handle_mcp_source_resume, + handle_mcp_source_update, + source_audit_subject, +) from server.knowledge.app.mcp_source_preview import handle_mcp_source_preview from server.operations.base import Operation, Role @@ -15,3 +37,99 @@ maturity="experimental", ), ] + + +OPERATIONS.extend( + [ + Operation( + name="knowledge.source.mcp_add", + input_model=MCPSourceAddInput, + output_model=MCPSourceOutput, + handler=handle_mcp_source_add, + idempotent=False, + required_role=Role.WRITER, + audit=True, + writes=True, + audit_subject=source_audit_subject, + maturity="experimental", + ), + Operation( + name="knowledge.source.mcp_update", + input_model=MCPSourceUpdateInput, + output_model=MCPSourceOutput, + handler=handle_mcp_source_update, + idempotent=False, + required_role=Role.WRITER, + audit=True, + writes=True, + audit_subject=source_audit_subject, + maturity="experimental", + ), + Operation( + name="knowledge.source.mcp_list", + input_model=MCPSourceListInput, + output_model=MCPSourceListOutput, + handler=handle_mcp_source_list, + idempotent=True, + required_role=Role.WRITER, + maturity="experimental", + ), + Operation( + name="knowledge.source.mcp_inspect", + input_model=MCPSourceInput, + output_model=MCPSourceInspectOutput, + handler=handle_mcp_source_inspect, + idempotent=True, + required_role=Role.WRITER, + maturity="experimental", + ), + Operation( + name="knowledge.source.mcp_pause", + input_model=MCPSourceInput, + output_model=MCPSourceOutput, + handler=handle_mcp_source_pause, + idempotent=False, + required_role=Role.WRITER, + audit=True, + writes=True, + audit_subject=source_audit_subject, + maturity="experimental", + ), + Operation( + name="knowledge.source.mcp_resume", + input_model=MCPSourceInput, + output_model=MCPSourceOutput, + handler=handle_mcp_source_resume, + idempotent=False, + required_role=Role.WRITER, + audit=True, + writes=True, + audit_subject=source_audit_subject, + maturity="experimental", + ), + Operation( + name="knowledge.source.mcp_refresh", + input_model=MCPSourceInput, + output_model=MCPSourceOutput, + handler=handle_mcp_source_refresh, + idempotent=False, + required_role=Role.WRITER, + audit=True, + writes=True, + audit_subject=source_audit_subject, + maturity="experimental", + ), + Operation( + name="knowledge.source.mcp_remove", + input_model=MCPSourceRemoveInput, + output_model=MCPSourceOutput, + handler=handle_mcp_source_remove, + idempotent=False, + required_role=Role.WRITER, + audit=True, + writes=True, + audit_subject=source_audit_subject, + maturity="experimental", + ), + ] +) diff --git a/server/knowledge/app/mcp_connections.py b/server/knowledge/app/mcp_connections.py index c7ebee07ae..58f0caa037 100644 --- a/server/knowledge/app/mcp_connections.py +++ b/server/knowledge/app/mcp_connections.py @@ -17,6 +17,7 @@ from server.clients.mcp_source import MCPSourceClient from server.core.ch import get_client from server.core.cursors import decode_bound_cursor, encode_bound_cursor +from server.core.diagnostics import private_work from server.core.errors import LoomServerError, ValidationError from server.core.secrets_at_rest import seal, unseal from server.knowledge.api.models_mcp_connections import ( @@ -59,7 +60,8 @@ class _Refused(ValidationError): @asynccontextmanager async def _errors() -> AsyncIterator[None]: try: - yield + with private_work(): + yield except _Refused: raise except Exception as e: # noqa: BLE001 — credentials and upstream errors must never escape diff --git a/server/knowledge/app/mcp_contracts.py b/server/knowledge/app/mcp_contracts.py index be2d699e16..c0a7bf3127 100644 --- a/server/knowledge/app/mcp_contracts.py +++ b/server/knowledge/app/mcp_contracts.py @@ -4,6 +4,7 @@ from server.knowledge.domain.mcp_sources import ( ConnectionEnvelope, MCPSourceContractError, + ResourceIdentity, SourceContract, ) from server.settings import settings @@ -34,9 +35,18 @@ def validate_source_contract(contract: SourceContract) -> None: contract = SourceContract.model_validate(contract) except (ValueError, TypeError, RecursionError): raise MCPSourceContractError() from None - if len(contract.resources) > settings.knowledge_mcp_selected_resources_max or any( - len(resource.id.encode("utf-8")) > settings.knowledge_mcp_resource_id_max_bytes - for resource in contract.resources + validate_resource_selection(contract.resources) + + +def validate_resource_selection(resources: tuple[ResourceIdentity, ...]) -> None: + if ( + not resources + or len(resources) > settings.knowledge_mcp_selected_resources_max + or len({resource.id for resource in resources}) != len(resources) + or any( + len(resource.id.encode("utf-8")) > settings.knowledge_mcp_resource_id_max_bytes + for resource in resources + ) ): raise MCPSourceContractError() diff --git a/server/knowledge/app/mcp_source_authority.py b/server/knowledge/app/mcp_source_authority.py index 93f971fbcc..5255cf5bac 100644 --- a/server/knowledge/app/mcp_source_authority.py +++ b/server/knowledge/app/mcp_source_authority.py @@ -4,11 +4,15 @@ import hashlib import json +import time from collections.abc import AsyncIterator, Awaitable, Callable from contextlib import asynccontextmanager from dataclasses import dataclass, replace from server.auth import aliases, authz +from server.auth.context import current_auth +from server.auth.jwt import AuthInfo +from server.auth.reader_identity import reader_subject, resolve_reader from server.clients.mcp_source import MCPSourceClient from server.core.ch import own_write_reads from server.core.errors import ValidationError @@ -120,9 +124,15 @@ def source_contract(src: KnowledgeSource) -> SourceContract: if (contract.generation, contract.slot) != (src.connection_id, src.connection_slot): raise MCPAuthorityError() resource_uri(src.source_id, contract.resources[0].id) - # No stored writer-consent proof exists for a deliberate collection copy. - if contract.reader_policy != "owner_only" or src.access != MIRRORED_ACCESS: + if contract.paused or src.access != MIRRORED_ACCESS: raise MCPAuthorityError() + if contract.reader_policy == "collection_copy": + consent = contract.copy_consent + if consent is None or (consent.publisher, consent.namespace) != ( + src.owner_subject, + src.namespace, + ): + raise MCPAuthorityError() return contract @@ -136,19 +146,14 @@ def contract(self) -> SourceContract: return self.connection.contract @property - def selection_sha256(self) -> str: - payload = [ - self.source.org, - self.source.namespace, - self.source.name, - self.source.source_id, - self.source.owner_subject, - self.source.connection_id, - self.contract.model_dump(mode="json"), - ] - return hashlib.sha256( - json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() - ).hexdigest() + def selected_uris(self) -> frozenset[str]: + return frozenset( + resource_uri(self.source.source_id, resource.id) for resource in self.contract.resources + ) + + @property + def scope_sha256(self) -> str: + return source_scope_sha256(self.source, self.contract) async def validate(self) -> None: fresh = await validate_source(self.source) @@ -159,6 +164,22 @@ def client(self) -> MCPSourceClient: return self.connection.client(self.validate) +def source_scope_sha256(source: KnowledgeSource, contract: SourceContract) -> str: + """Bind read evidence to source authority; labels and pause do not change the selection.""" + payload = [ + source.org, + source.namespace, + source.name, + source.source_id, + source.owner_subject, + source.connection_id, + contract.model_dump(mode="json", exclude={"label", "paused"}), + ] + return hashlib.sha256( + json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + async def validate_source(src: KnowledgeSource) -> SourceAuthority: """Recheck an exact active stored row and its current destination authority. @@ -194,13 +215,63 @@ async def validate_registration(src: KnowledgeSource) -> ConnectionAuthority: await aliases.verified_spellings(src.org, src.owner_subject) aliases.invalidate(src.org, [src.owner_subject]) role = await authz.grant_role_for(src.org, src.namespace, src.owner_subject) - if role is None or role < Role.WRITER: + minimum = Role.ADMIN if contract.reader_policy == "collection_copy" else Role.WRITER + if role is None or role < minimum: raise MCPAuthorityError() await source_ops._require_source_namespace(src.org, src.namespace) await source_ops._require_no_erasure(src.org, src.namespace) return connection +def _reader_context(src: KnowledgeSource, auth: AuthInfo | None) -> AuthInfo: + if ( + auth is None + or current_auth() is not auth + or auth.org != src.org + or (auth.expires_at is not None and auth.expires_at <= time.time()) + ): + raise MCPAuthorityError() + return auth + + +async def _reader_authority(src: KnowledgeSource, auth: AuthInfo | None) -> SourceAuthority: + async with _refusals(): + auth = _reader_context(src, auth) + if not await authz.row_in_scope(src.org, src.namespace, Role.VIEWER): + raise MCPAuthorityError() + bound = await validate_source(src) + if bound.contract.reader_policy == "owner_only": + subject = reader_subject(auth) + reader = await resolve_reader(src.org, subject) if subject else None + if reader is None or reader.subject != src.owner_subject or auth.issued_at is None: + raise MCPAuthorityError() + await accounts._standing( + src.org, + reader.subject, + min((auth.issued_at, *auth.parent_iats)), + (auth.subject, auth.token_id, auth.session_id, *auth.parents), + ) + _reader_context(src, auth) + if not await authz.row_in_scope(src.org, src.namespace, Role.VIEWER): + raise MCPAuthorityError() + _reader_context(src, auth) + return bound + + +async def validate_indexed_reader(src: KnowledgeSource, auth: AuthInfo | None) -> SourceAuthority: + bound = await _reader_authority(src, auth) + if bound.contract.mode == "live": + raise MCPAuthorityError() + return bound + + +async def validate_live_reader(src: KnowledgeSource, auth: AuthInfo | None) -> SourceAuthority: + bound = await _reader_authority(src, auth) + if bound.contract.mode != "live" or bound.contract.reader_policy != "owner_only": + raise MCPAuthorityError() + return bound + + @asynccontextmanager async def source_guard(src: KnowledgeSource) -> AsyncIterator[SourceAuthority]: """Fence a stored source check or live result release; does not grant reader access.""" diff --git a/server/knowledge/app/mcp_source_ops.py b/server/knowledge/app/mcp_source_ops.py new file mode 100644 index 0000000000..958367dbcb --- /dev/null +++ b/server/knowledge/app/mcp_source_ops.py @@ -0,0 +1,518 @@ +"""Owner-bound fixed MCP selections on the existing source lifecycle and stores.""" + +from __future__ import annotations + +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import replace +from datetime import UTC, datetime +from uuid import NAMESPACE_URL, UUID, uuid5 + +from server.auth import authz, scim +from server.core import request_work +from server.core.ch import own_write_reads +from server.core.cursors import decode_bound_cursor, encode_bound_cursor +from server.core.diagnostics import private_work +from server.core.errors import ValidationError +from server.knowledge.api.models_mcp_connections import MCPSlotInput +from server.knowledge.api.models_mcp_sources import ( + MCPSourceAddInput, + MCPSourceEntry, + MCPSourceInput, + MCPSourceInspectOutput, + MCPSourceListInput, + MCPSourceListOutput, + MCPSourceOutput, + MCPSourceRemoveInput, + MCPSourceUpdateInput, +) +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import mcp_connections as connections +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app import source_push, sources +from server.knowledge.app.mcp_contracts import decode_source, encode_source +from server.knowledge.app.mcp_source_preview import access_rule +from server.knowledge.domain.mcp_sources import ( + CopyConsent, + MCPSourceContractError, + ResourceIdentity, + SourceContract, + selection_sha256, +) +from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource +from server.knowledge.store import connected_accounts as account_store +from server.knowledge.store import sources as store +from server.operations.base import Role +from server.settings import settings + + +class _Refused(ValidationError): + def __init__(self) -> None: + super().__init__("MCP_SOURCE_UNAVAILABLE", code="MCP_SOURCE_UNAVAILABLE") + + +def source_audit_subject(_input: object, _response: object) -> dict[str, str]: + """Namespace audit readers do not inherit private source metadata access.""" + return {"kind": "mcp"} + + +@asynccontextmanager +async def _private() -> AsyncIterator[None]: + try: + if not request_work.mark_mirrored(): + raise _Refused() + with private_work(), own_write_reads(): + yield + except _Refused: + raise + except Exception as e: # noqa: BLE001 — source errors must not disclose private metadata + del e + raise _Refused() from None + + +async def _caller(org: str, namespace: str, expected: str | None = None) -> str: + owner = await connections._owner(org, expected) + if not await authz.row_in_scope(org, namespace, Role.WRITER): + raise _Refused() + return owner + + +async def _destination(org: str, namespace: str, owner: str) -> None: + await _caller(org, namespace, owner) + await sources._require_source_namespace(org, namespace) + await sources._require_no_erasure(org, namespace) + + +@asynccontextmanager +async def _locks(org: str, namespace: str, owner: str, slot: str) -> AsyncIterator[None]: + connections._check_slot(slot) + async with scim.subject_leases([owner]): + async with accounts.account_lease(org, owner, slot): + async with sources.sources_lease(org, namespace): + await _destination(org, namespace, owner) + yield + + +def _identity(input: MCPSourceAddInput, owner: str) -> tuple[str, str]: + nonce = str(UUID(input.request_id)) + key = json.dumps( + [input.org, input.namespace, owner, input.slot, nonce], + ensure_ascii=False, + separators=(",", ":"), + ) + source_id = uuid5(NAMESPACE_URL, key) + return "mcp-" + source_id.hex, str(source_id) + + +def _owned(src: KnowledgeSource | None, org: str, namespace: str, owner: str) -> bool: + return src is not None and ( + src.org, + src.namespace, + src.owner_subject, + src.kind, + src.credential_mode, + ) == (org, namespace, owner, "mcp", "connected") + + +async def _get(input: MCPSourceInput, owner: str) -> KnowledgeSource: + src = await store.latest_source(input.org, input.namespace, input.name) + if not _owned(src, input.org, input.namespace, owner): + raise _Refused() + assert src is not None + return src + + +def _contract(src: KnowledgeSource) -> SourceContract: + if src.source_contract_version != 1 or src.config or src.items: + raise MCPSourceContractError() + contract = decode_source(src.generic_config_json, src.generic_items_json) + if (src.connection_slot, src.connection_id) != (contract.slot, contract.generation): + raise MCPSourceContractError() + return contract + + +def _with_contract(src: KnowledgeSource, contract: SourceContract) -> KnowledgeSource: + config, items = encode_source(contract) + return replace( + src, + generic_config_json=config, + generic_items_json=items, + access=MIRRORED_ACCESS, + ) + + +async def _selection( + input: MCPSourceAddInput | MCPSourceUpdateInput, + owner: str, + binding: SourceContract, +) -> SourceContract: + resources = tuple(ResourceIdentity(type="resource", id=r) for r in input.resource_ids) + consent = None + policy = input.reader_policy if isinstance(input, MCPSourceAddInput) else binding.reader_policy + if policy == "collection_copy": + if not input.confirm_copy_authority or input.mode == "live": + raise _Refused() + if not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): + raise _Refused() + bound = await authority.validate_connection(input.org, owner, binding) + if not bound.profile.metadata.allow_collection_copy: + raise _Refused() + consent = CopyConsent( + version=1, + publisher=owner, + namespace=input.namespace, + resources_sha256=selection_sha256(resources), + ) + return SourceContract( + version=1, + slot=binding.slot, + generation=binding.generation, + profile_id=binding.profile_id, + profile_sha256=binding.profile_sha256, + resources=resources, + mode=input.mode, + reader_policy=policy, + scope_revision=binding.scope_revision, + copy_consent=consent, + label=input.label, + ) + + +async def _proposed(input: MCPSourceAddInput, owner: str) -> KnowledgeSource: + connections._check_slot(input.slot) + account = await account_store.get(input.org, owner, input.slot) + if account is None: + raise _Refused() + connections._row_scope(account, input.org, owner, input.slot) + await connections._validate(account) + _, envelope = connections._binding(account) + binding = SourceContract( + version=1, + slot=input.slot, + generation=account.connection_id, + profile_id=envelope.profile_id, + profile_sha256=envelope.profile_sha256, + mode="live", + reader_policy="owner_only", + resources=(ResourceIdentity(type="resource", id=input.resource_ids[0]),), + ) + contract = await _selection(input, owner, binding) + name, source_id = _identity(input, owner) + return _with_contract( + KnowledgeSource( + org=input.org, + namespace=input.namespace, + name=name, + kind="mcp", + source_id=source_id, + credential_mode="connected", + owner_subject=owner, + created_by=owner, + connection_slot=input.slot, + connection_id=account.connection_id, + source_contract_version=1, + ), + contract, + ) + + +async def _discover(src: KnowledgeSource) -> None: + result = await connections.handle_mcp_discover( + MCPSlotInput(org=src.org, slot=src.connection_slot) + ) + if not result.supported_reads or result.generation != src.connection_id: + raise _Refused() + + +def _entry(src: KnowledgeSource) -> MCPSourceEntry: + entry = MCPSourceEntry( + name=src.name, + source_id=src.source_id, + slot=src.connection_slot, + namespace=src.namespace, + state="unsupported" if src.active else "retired", + sync_enabled=bool(settings.knowledge_source_sync_enabled), + refresh_state="unsupported" if src.active else "retired", + pending_erasure=src.pending_delete, + ) + try: + contract = _contract(src) + except (ValueError, TypeError, RecursionError): + return entry + entry.state = "retired" if not src.active else "paused" if contract.paused else "registered" + entry.mode, entry.reader_policy, entry.label, entry.scope_revision = ( + contract.mode, + contract.reader_policy, + contract.label, + contract.scope_revision, + ) + entry.resource_ids = [r.id for r in contract.resources] + entry.selected_count = len(contract.resources) + entry.refresh_state = ( + "retired" + if not src.active + else "paused" + if contract.paused + else "not_applicable" + if contract.mode == "live" + else "enabled" + if entry.sync_enabled + else "disabled" + ) + entry.rule = access_rule( + contract.mode, + contract.reader_policy, + copy_approved=contract.copy_consent is not None, + administrator=True, + ) + if entry.state in {"paused", "retired"}: + entry.rule.access = "unavailable" + entry.rule.reason = "source_" + entry.state + entry.rule.explanation = ( + "This source is stopped; retained content has no current read grant." + ) + return entry + + +def _output(src: KnowledgeSource, *, requested: bool = False) -> MCPSourceOutput: + return MCPSourceOutput( + source=_entry(src), + refresh_requested=requested, + ) + + +async def _checked_entry(src: KnowledgeSource) -> MCPSourceEntry: + entry = _entry(src) + if entry.state != "registered": + return entry + try: + await authority.validate_source(src) + except authority.MCPAuthorityError: + entry.local_authority = "unavailable" + if entry.rule is not None: + entry.rule.access, entry.rule.reason = "unavailable", "source_authority_unavailable" + entry.rule.explanation = ( + "Current source authority is unavailable; stored policy grants no access." + ) + else: + entry.local_authority = "current" + return entry + + +async def handle_mcp_source_add(input: MCPSourceAddInput) -> MCPSourceOutput: + async with _private(): + owner = await _caller(input.org, input.namespace) + connections._policy() + await _destination(input.org, input.namespace, owner) + proposed = await _proposed(input, owner) + await _discover(proposed) + async with _locks(input.org, input.namespace, owner, input.slot): + connections._policy() + current = await store.latest_source(input.org, input.namespace, proposed.name) + if current is not None: + if ( + not _owned(current, input.org, input.namespace, owner) + or not current.active + or current.pending_delete + or _contract(current).paused + or replace(current, created_at=None, updated_at=None, mirror="") != proposed + ): + raise _Refused() + await authority.validate_registration(current) + return _output(current) + await sources._require_free( + input.org, + input.namespace, + proposed.name, + owner_subject=owner, + ) + await _destination(input.org, input.namespace, owner) + connections._policy() + await authority.validate_registration(proposed) + requested = await _request(proposed, only_if_changed=True) + await _destination(input.org, input.namespace, owner) + connections._policy() + await authority.validate_registration(proposed) + await store.insert_source(proposed) + return _output(proposed, requested=requested) + + +async def handle_mcp_source_list(input: MCPSourceListInput) -> MCPSourceListOutput: + async with _private(): + owner = await _caller(input.org, input.namespace) + scope = ( + "knowledge.source.mcp_list", + input.org, + input.namespace, + owner, + str(input.limit), + str(input.include_retired), + ) + anchor = datetime(1970, 1, 1, tzinfo=UTC) + after = "" + if input.cursor is not None: + observed, after = decode_bound_cursor(input.cursor, scope) + if observed != anchor: + raise _Refused() + rows = await store.mcp_sources_page( + input.org, + input.namespace, + owner, + after=after, + include_retired=input.include_retired, + limit=input.limit + 1, + ) + entries = [ + await _checked_entry(src) + for src in rows[: input.limit] + if _owned(src, input.org, input.namespace, owner) + ] + await _caller(input.org, input.namespace, owner) + return MCPSourceListOutput( + sources=entries, + next_cursor=encode_bound_cursor(scope, anchor, rows[input.limit - 1].name) + if len(rows) > input.limit + else None, + ) + + +async def handle_mcp_source_inspect(input: MCPSourceInput) -> MCPSourceInspectOutput: + async with _private(): + owner = await _caller(input.org, input.namespace) + src = await store.latest_source(input.org, input.namespace, input.name) + entry = ( + await _checked_entry(src) + if _owned(src, input.org, input.namespace, owner) and src + else None + ) + await _caller(input.org, input.namespace, owner) + return MCPSourceInspectOutput(found=entry is not None, source=entry) + + +def _require_running(src: KnowledgeSource, contract: SourceContract) -> None: + if not src.active or src.pending_delete or contract.paused: + raise _Refused() + + +async def _request(src: KnowledgeSource, *, only_if_changed: bool = False) -> bool: + contract = _contract(src) + if contract.mode == "live": + return False + state = await sources._read_state(src) + marker = authority.source_scope_sha256(src, contract) + detail = json.loads(state.get("detail") or "{}") + if only_if_changed and detail.get("mcp_selection") == marker: + return False + await sources._update_state( + src, + state, + {"requested_at": sources._now_iso(), "full": True, "mcp_selection": marker}, + ) + return True + + +async def handle_mcp_source_update(input: MCPSourceUpdateInput) -> MCPSourceOutput: + async with _private(): + owner = await _caller(input.org, input.namespace) + original = await _get(input, owner) + async with _locks(input.org, input.namespace, owner, original.connection_slot): + src = await _get(input, owner) + if src != original: + raise _Refused() + contract = _contract(src) + _require_running(src, contract) + if ( + input.if_scope_revision is not None + and input.if_scope_revision != contract.scope_revision + ): + raise _Refused() + chosen = await _selection(input, owner, contract) + if chosen.model_dump(exclude={"label"}) != contract.model_dump(exclude={"label"}): + chosen = SourceContract.model_validate( + { + **chosen.model_dump(), + "scope_revision": contract.scope_revision + 1, + } + ) + updated = _with_contract(src, chosen) + await authority.validate_registration(src) + await authority.validate_registration(updated) + if updated == src: + requested = await _request(src, only_if_changed=True) + return _output(src, requested=requested) + await source_push.retire(src) + requested = await _request(updated, only_if_changed=True) + await _destination(input.org, input.namespace, owner) + await authority.validate_registration(updated) + await store.insert_source(updated) + return _output(updated, requested=requested) + + +async def _pause(input: MCPSourceInput, *, paused: bool) -> MCPSourceOutput: + async with _private(): + owner = await _caller(input.org, input.namespace) + original = await _get(input, owner) + async with _locks(input.org, input.namespace, owner, original.connection_slot): + src = await _get(input, owner) + if src != original or not src.active or src.pending_delete: + raise _Refused() + contract = _contract(src) + unpaused = _with_contract(src, contract.model_copy(update={"paused": False})) + await authority.validate_registration(unpaused) + updated = _with_contract(src, contract.model_copy(update={"paused": paused})) + await source_push.retire(src) + await _destination(input.org, input.namespace, owner) + await authority.validate_registration(unpaused) + await store.insert_source(updated) + return _output(updated) + + +async def handle_mcp_source_pause(input: MCPSourceInput) -> MCPSourceOutput: + return await _pause(input, paused=True) + + +async def handle_mcp_source_resume(input: MCPSourceInput) -> MCPSourceOutput: + return await _pause(input, paused=False) + + +async def handle_mcp_source_refresh(input: MCPSourceInput) -> MCPSourceOutput: + async with _private(): + owner = await _caller(input.org, input.namespace) + original = await _get(input, owner) + async with _locks(input.org, input.namespace, owner, original.connection_slot): + src = await _get(input, owner) + if src != original: + raise _Refused() + contract = _contract(src) + _require_running(src, contract) + if contract.mode == "live": + raise _Refused() + await authority.validate_registration(src) + await _request(src) + return _output(src, requested=True) + + +async def handle_mcp_source_remove(input: MCPSourceRemoveInput) -> MCPSourceOutput: + async with _private(): + owner = await _caller(input.org, input.namespace) + original = await _get(input, owner) + if input.confirm != input.name: + raise _Refused() + async with _locks(input.org, input.namespace, owner, original.connection_slot): + src = await _get(input, owner) + if src != original: + raise _Refused() + pending = src.pending_delete + if input.delete_documents: + pending = True + if src.access == MIRRORED_ACCESS: + pending = await sources._queue_retirement(src) or pending + retired = replace(src, active=False, pending_delete=pending) + await source_push.retire(src) + await _destination(input.org, input.namespace, owner) + await store.insert_source(retired) + result = _output(retired) + if pending: + result.copies = "erasure_requested" + return result diff --git a/server/knowledge/app/mcp_source_preview.py b/server/knowledge/app/mcp_source_preview.py index 5b0bcf0e28..2de04dc806 100644 --- a/server/knowledge/app/mcp_source_preview.py +++ b/server/knowledge/app/mcp_source_preview.py @@ -12,8 +12,8 @@ ) from server.knowledge.app import mcp_connections as connections from server.knowledge.app import sources -from server.knowledge.app.mcp_contracts import validate_source_contract -from server.knowledge.domain.mcp_sources import ResourceIdentity, SourceContract +from server.knowledge.app.mcp_contracts import validate_resource_selection +from server.knowledge.domain.mcp_sources import ResourceIdentity from server.knowledge.store import connected_accounts as account_store from server.operations.base import Role from server.settings import settings @@ -83,20 +83,11 @@ async def handle_mcp_source_preview(input: MCPSourcePreviewInput) -> MCPSourcePr approved = False if entry.state == "configured": await connections._validate(account) - profile, envelope = connections._binding(account) - contract = SourceContract( - version=1, - slot=input.slot, - generation=account.connection_id, - profile_id=envelope.profile_id, - profile_sha256=envelope.profile_sha256, - mode=input.mode, - reader_policy=input.reader_policy, - resources=tuple( - ResourceIdentity(type="resource", id=r) for r in input.resource_ids - ), + profile, _envelope = connections._binding(account) + # Preview validates scope without issuing publication consent. + validate_resource_selection( + tuple(ResourceIdentity(type="resource", id=r) for r in input.resource_ids) ) - validate_source_contract(contract) approved = profile.metadata.allow_collection_copy rule = access_rule( input.mode, diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index a853d63800..564506f2bf 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -84,6 +84,7 @@ class ReadPlan: _connected_pins: dict[tuple[str, str], KnowledgeSource] = field( default_factory=dict, repr=False ) + _mcp_uris: dict[tuple[str, str], frozenset[str]] = field(default_factory=dict, repr=False) @property def discovery_sources(self) -> dict[tuple[str, str], str]: @@ -190,6 +191,11 @@ async def _check(self, candidates: list[dict[str, Any]], *, chunks: bool) -> lis continue if not original or (pg.enabled() and not _head_serves(heads[pair], candidate, chunks)): continue + pinned = self._connected_pins.get((original, sid)) + if pinned is not None and pinned.kind == "mcp": + selected = self._mcp_uris.get((original, sid)) + if selected is None or doc["source_uri"] not in selected: + continue if chunks and not pg.enabled() and int(candidate["revision"]) != doc["revision"]: continue access = permissions[pair] @@ -305,13 +311,15 @@ async def prepare(org: str, namespaces: list[str]) -> ReadPlan: async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) -> None: from server.knowledge.app.connected_accounts import validate_indexed + from server.knowledge.app.mcp_source_authority import validate_indexed_reader from server.knowledge.store import sources as source_store eligible = [] + mcp_uris: dict[tuple[str, str], frozenset[str]] = {} for row in sources: key = row["namespace"], row["source_id"] mode = row.get("credential_mode", "shared") - if opaque_payload( + if row.get("source_kind") != "mcp" and opaque_payload( kind=str(row.get("source_kind") or ""), mode=mode, version=int(row.get("source_contract_version") or 0), @@ -328,29 +336,33 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) if ( source is None or source.source_id != row["source_id"] - or opaque_payload( - kind=source.kind, - mode=source.credential_mode, - version=source.source_contract_version, + or (source.org, source.namespace, source.name) + != (plan.org, row["namespace"], row["name"]) + or ( + source.kind != "mcp" + and opaque_payload( + kind=source.kind, + mode=source.credential_mode, + version=source.source_contract_version, + ) ) ): continue pinned = plan._connected_pins.get(key) - if pinned is not None and ( - source.connection_id != pinned.connection_id - or source.owner_subject != pinned.owner_subject - or source.kind != pinned.kind - or source.items != pinned.items - or source.config != pinned.config - ): + if pinned is not None and source != pinned: continue - await validate_indexed(source, plan._auth) + if source.kind == "mcp": + bound = await validate_indexed_reader(source, plan._auth) + mcp_uris[key] = bound.selected_uris + else: + await validate_indexed(source, plan._auth) eligible.append(row) if not plan._scope_frozen: plan._connected_pins[key] = copy.deepcopy(source) except Exception: # noqa: BLE001 — one unverifiable connection admits no private leg continue sources = eligible + plan._mcp_uris = mcp_uris names = sorted({s["namespace"] for s in sources}) mirrors = await mirrors_repo.mirrors_of(plan.org, names, live_only=True) by_original: dict[str, list[str]] = {} diff --git a/server/knowledge/app/source_sync_mcp.py b/server/knowledge/app/source_sync_mcp.py index aaa7dea8de..1d25a053cd 100644 --- a/server/knowledge/app/source_sync_mcp.py +++ b/server/knowledge/app/source_sync_mcp.py @@ -40,7 +40,7 @@ def _progress( index = saved.get("mcp_next_index", 0) request = asked.get("requested_at", saved.get("mcp_requested_at", "")) if ( - saved.get("mcp_selection_sha256") != bound.selection_sha256 + saved.get("mcp_scope_sha256") != bound.scope_sha256 or saved.get("mcp_requested_at", "") != request or type(index) is not int or not 0 <= index <= count @@ -50,7 +50,7 @@ def _progress( index = 0 return { "mcp_mode": bound.contract.mode, - "mcp_selection_sha256": bound.selection_sha256, + "mcp_scope_sha256": bound.scope_sha256, "mcp_next_index": index, "mcp_selected_count": count, "mcp_requested_at": request, @@ -85,6 +85,7 @@ async def _publish( ) -> bool: digest = _receipt(client, selected, evidence) src = bound.source + copied = bound.contract.reader_policy == "collection_copy" return await sync.write_document( src, {"id": selected, "name": evidence.title, "mimeType": evidence.mime_type}, @@ -92,15 +93,16 @@ async def _publish( evidence.text, ingested_format="mcp_text", original=evidence.text.encode(), - permissions=AccessList(owner=src.owner_subject), + permissions=AccessList(anyone=True) if copied else AccessList(owner=src.owner_subject), extra_metadata={ "mcp_content_sha256": digest, - "mcp_selection_sha256": bound.selection_sha256, + "mcp_scope_sha256": bound.scope_sha256, "mcp_profile_sha256": bound.contract.profile_sha256, "mcp_connection_generation": bound.contract.generation, "mcp_source_id": src.source_id, "mcp_read_operation": "tools/call" if client.config.read else "resources/read", - "mcp_reader_policy": "owner_only", + "mcp_reader_policy": bound.contract.reader_policy, + **({"ingested_from": resource_uri(src.source_id, selected)} if copied else {}), }, ) diff --git a/server/knowledge/domain/mcp_sources.py b/server/knowledge/domain/mcp_sources.py index 8cc317ff2c..eb2d139beb 100644 --- a/server/knowledge/domain/mcp_sources.py +++ b/server/knowledge/domain/mcp_sources.py @@ -2,6 +2,7 @@ from __future__ import annotations +import hashlib import json import unicodedata from typing import Annotated, Any, Literal, Self @@ -102,6 +103,21 @@ class ResourceIdentity(_ContractModel): id: _Identifier +def selection_sha256(resources: tuple[ResourceIdentity, ...]) -> str: + """Hash ordered exact resource IDs without URL or Unicode normalization.""" + payload = json.dumps([r.id for r in resources], ensure_ascii=False, separators=(",", ":")) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +class CopyConsent(_ContractModel): + """Server-issued publication authority for one destination and exact selection.""" + + version: _Version + publisher: _Identifier + namespace: _Identifier + resources_sha256: _Digest + + class SourceContract(_ContractModel): """Reader policy is declarative; grants, consent and publication are checked elsewhere. @@ -116,7 +132,24 @@ class SourceContract(_ContractModel): profile_sha256: _Digest mode: Literal["live", "snapshot", "selected_refresh"] reader_policy: Literal["owner_only", "collection_copy"] + scope_revision: Annotated[int, Field(strict=True, ge=1, le=2**63 - 1)] = 1 resources: Annotated[tuple[ResourceIdentity, ...], Field(min_length=1, max_length=1000)] + copy_consent: CopyConsent | None = None + paused: bool = False + label: Annotated[_Identifier, Field(max_length=256)] | None = None + + @model_validator(mode="after") + def _copy_authority(self) -> Self: + if self.reader_policy == "owner_only": + if self.copy_consent is not None: + raise ValueError("unexpected copy consent") + elif ( + self.mode == "live" + or self.copy_consent is None + or self.copy_consent.resources_sha256 != selection_sha256(self.resources) + ): + raise ValueError("invalid copy consent") + return self @field_validator("resources") @classmethod diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index ae0eb5ae07..859f1264ea 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -293,6 +293,37 @@ async def erase_connected_owner( ) +async def mcp_sources_page( + org: str, + namespace: str, + owner: str, + *, + after: str, + include_retired: bool, + limit: int, + ch: _CHClient | None = None, +) -> list[KnowledgeSource]: + """One bounded exact-owner page; no other namespace's selections are fetched.""" + if type(limit) is not int or not 1 <= limit <= 21: + raise ValueError("mcp_source_page_bound") + rows = await (ch or _default_client()).query_all( + f"SELECT {_COLUMNS} FROM {TABLE} FINAL WHERE org = {{org:String}} " + "AND namespace = {ns:String} AND owner_subject = {subject:String} " + "AND source_kind = 'mcp' AND credential_mode = 'connected' " + "AND name > {after:String} AND ({include_retired:Bool} OR active = 1) " + "ORDER BY name LIMIT {limit:UInt64}", + params={ + "org": org, + "ns": namespace, + "subject": owner, + "after": after, + "include_retired": include_retired, + "limit": limit, + }, + ) + return [_source(dict(row)) for row in rows] + + async def insert_source(src: KnowledgeSource, *, ch: _CHClient | None = None) -> None: """Write `src` as a new full version row; `created_at` is carried forward. The version is left to the column's DEFAULT, the ClickHouse servers' clocks, not the diff --git a/tests/unit/test_mcp_copy_consent.py b/tests/unit/test_mcp_copy_consent.py new file mode 100644 index 0000000000..b36816464a --- /dev/null +++ b/tests/unit/test_mcp_copy_consent.py @@ -0,0 +1,84 @@ +"""Exact selection consent is a pure contract, not upstream permission evidence.""" + +import hashlib +import json + +import pytest +from pydantic import ValidationError + +from server.knowledge.domain.mcp_sources import ( + CopyConsent, + ResourceIdentity, + SourceContract, + selection_sha256, +) + + +def contract(**changes): + resources = (ResourceIdentity(type="resource", id="opaque:A"),) + values = dict( + version=1, + slot="mcp:" + "a" * 32, + generation="a" * 32 + "/1" + "b" * 31, + profile_id="reader", + profile_sha256="c" * 64, + mode="snapshot", + reader_policy="owner_only", + resources=resources, + ) + values.update(changes) + return SourceContract(**values) + + +def consent(resources): + return CopyConsent( + version=1, + publisher="owner", + namespace="destination", + resources_sha256=selection_sha256(resources), + ) + + +def test_copy_requires_explicit_selection_bound_consent(): + with pytest.raises(ValidationError): + contract(reader_policy="collection_copy") + original = contract() + accepted = contract(reader_policy="collection_copy", copy_consent=consent(original.resources)) + assert accepted.copy_consent.resources_sha256 == selection_sha256(original.resources) + with pytest.raises(ValidationError): + contract( + reader_policy="collection_copy", + copy_consent=accepted.copy_consent, + resources=original.resources + (ResourceIdentity(type="resource", id="opaque:B"),), + ) + + +@pytest.mark.parametrize("mode,policy", [("live", "collection_copy"), ("snapshot", "owner_only")]) +def test_consent_cannot_authorize_live_or_owner_only(mode, policy): + with pytest.raises(ValidationError): + contract(mode=mode, reader_policy=policy, copy_consent=consent(contract().resources)) + + +def test_digest_preserves_order_and_exact_unicode_ids(): + resources = tuple( + ResourceIdentity(type="resource", id=r) for r in ("é", "e\u0301", "https://x/A") + ) + expected = hashlib.sha256( + json.dumps([r.id for r in resources], ensure_ascii=False, separators=(",", ":")).encode( + "utf-8" + ) + ).hexdigest() + assert selection_sha256(resources) == expected + assert selection_sha256(resources) != selection_sha256(tuple(reversed(resources))) + + +def test_pause_and_label_are_bounded_metadata(): + assert contract(paused=True, label="Reading").paused is True + with pytest.raises(ValidationError): + contract(label="x" * 257) + with pytest.raises(ValidationError): + contract(label="bad\nlabel") + with pytest.raises(ValidationError): + CopyConsent( + version=2, publisher="owner", namespace="destination", resources_sha256="c" * 64 + ) diff --git a/tests/unit/test_mcp_source_contract.py b/tests/unit/test_mcp_source_contract.py index d0469bd086..e80da4347c 100644 --- a/tests/unit/test_mcp_source_contract.py +++ b/tests/unit/test_mcp_source_contract.py @@ -11,6 +11,7 @@ from server.knowledge.domain.mcp_sources import ( ConnectionEnvelope, + CopyConsent, MCPSourceContractError, ResourceIdentity, SourceContract, @@ -19,6 +20,7 @@ decode_source, encode_envelope, encode_source, + selection_sha256, ) _TOKEN = "fixture-secret-bearer" @@ -216,12 +218,29 @@ def test_source_splits_columns_without_duplicating_selection_and_preserves_order @pytest.mark.parametrize("mode", ["live", "snapshot", "selected_refresh"]) @pytest.mark.parametrize("policy", ["owner_only", "collection_copy"]) def test_policy_and_mode_are_declarations_not_authority(mode: str, policy: str) -> None: + if policy == "collection_copy": + with pytest.raises(ValidationError): + _source(mode=mode, reader_policy=policy) + return source = _source(mode=mode, reader_policy=policy) assert decode_source(*encode_source(source)) == source assert source.reader_policy == policy assert not hasattr(source, "authorized") +@pytest.mark.parametrize("mode", ["snapshot", "selected_refresh"]) +def test_copy_consent_is_scoped_metadata_not_runtime_authorization(mode: str) -> None: + consent = CopyConsent( + version=1, + publisher="person-one", + namespace="col-team", + resources_sha256=selection_sha256(_source().resources), + ) + source = _source(mode=mode, reader_policy="collection_copy", copy_consent=consent) + assert decode_source(*encode_source(source)) == source + assert not hasattr(source, "authorized") + + @pytest.mark.parametrize( "changes", [ diff --git a/tests/unit/test_mcp_source_ops.py b/tests/unit/test_mcp_source_ops.py new file mode 100644 index 0000000000..2e42cff9e0 --- /dev/null +++ b/tests/unit/test_mcp_source_ops.py @@ -0,0 +1,642 @@ +"""Synthetic I/O seams exercise real source codecs, stores, locks and authority. + +No database, provider or index runs here. Hosted qualification must exercise those +systems together with document publication and protected reads. +""" + +import json +from contextlib import asynccontextmanager +from copy import deepcopy +from dataclasses import replace +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +from server.knowledge.api.models_mcp_sources import ( + MCPSourceAddInput, + MCPSourceInput, + MCPSourceListInput, + MCPSourceRemoveInput, + MCPSourceUpdateInput, +) +from server.knowledge.app import mcp_source_ops as ops +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.knowledge.domain.mcp_sources import ConnectionEnvelope +from server.operations.base import Role + +ORG = "example" +NS = "collection" +OWNER = "person" +SLOT = "mcp:" + "a" * 32 +GEN = "a" * 32 + "/1" + "b" * 31 +NONCE = "d290f1ee-6c54-4b01-90e6-d701748f0851" + + +class SourceIO: + def __init__(self): + self.rows = {} + self.states = {} + self.held = [] + self.writes = [] + self.authorized = [] + self.deny_lease = False + self.readable = True + self.owner = OWNER + + @asynccontextmanager + async def lease(self, name, **kwargs): + self.held.append(name) + try: + yield not self.deny_lease + finally: + assert self.held.pop() == name + + async def insert(self, table, rows): + assert len(self.held) == 3 + assert self.held[0].startswith("scim-subject:") + assert self.held[1].startswith("connected-account:") + assert self.held[2] == "knowledge-source:example:collection" + for row in rows: + key = (row["org"], row["namespace"], row.get("name", row.get("state_key"))) + if table == ops.store.TABLE: + assert row["config_json"] and row["items_json"] + self.rows[key] = deepcopy(row) + elif table == ops.store.STATE_TABLE: + self.states[key] = deepcopy(row) + else: + raise AssertionError(table) + self.writes.append((table, deepcopy(row))) + + async def query_one(self, sql, *, params): + if "SELECT count() AS n" in sql: + assert "FROM loom.documents FINAL" in sql or "FROM loom.knowledge_sources FINAL" in sql + return {"n": 0} + assert "FROM loom.knowledge_sources FINAL" in sql + assert set(params) == {"org", "ns", "name"} + row = self.rows.get((params["org"], params["ns"], params["name"])) + if row and "AND active" in sql and not row["active"]: + return None + return deepcopy(row) + + async def query_all(self, sql, *, params): + if "AND name > {after:String}" in sql: + assert "FROM loom.knowledge_sources FINAL" in sql + assert "namespace = {ns:String}" in sql + assert "owner_subject = {subject:String}" in sql + assert "source_kind = 'mcp' AND credential_mode = 'connected'" in sql + assert set(params) == {"org", "ns", "subject", "after", "include_retired", "limit"} + assert 1 <= params["limit"] <= 21 + rows = [ + deepcopy(r) + for r in self.rows.values() + if (r["org"], r["namespace"], r["owner_subject"]) + == (params["org"], params["ns"], params["subject"]) + and r["source_kind"] == "mcp" + and r["credential_mode"] == "connected" + and r["name"] > params["after"] + and (params["include_retired"] or r["active"]) + ] + return sorted(rows, key=lambda r: r["name"])[: params["limit"]] + if "owner_subject = {subject:String}" in sql: + assert "FROM loom.knowledge_sources FINAL" in sql + assert set(params) == {"org", "subject", "limit"} + return [ + deepcopy(r) + for r in self.rows.values() + if r["org"] == params["org"] and r["owner_subject"] == params["subject"] + ] + assert "state_key IN {keys:Array(String)}" in sql + assert set(params) == {"org", "ns", "keys"} + return [ + deepcopy(r) + for r in self.states.values() + if (r["org"], r["namespace"]) == (params["org"], params["ns"]) + and r["state_key"] in params["keys"] + ] + + +class ReadClient: + def __init__(self, io): + self.io = io + self.config = SimpleNamespace(read=None, search=None) + + async def __aenter__(self): + assert not self.io.held + return self + + async def __aexit__(self, *args): + return None + + async def discover(self): + assert not self.io.held + return SimpleNamespace(resources=self.io.readable, tools={}) + + +def configure_authority(monkeypatch, io): + account = ConnectedAccount( + ORG, + OWNER, + SLOT, + GEN, + active=True, + credential_enc="sealed", + connected_at=datetime(2026, 1, 1, tzinfo=UTC), + ) + envelope = ConnectionEnvelope( + version=1, + org=ORG, + owner=OWNER, + slot=SLOT, + generation=GEN, + profile_id="reader", + profile_sha256="c" * 64, + endpoint="https://example.test/mcp", + audience=None, + auth="none", + ) + profile = SimpleNamespace(metadata=SimpleNamespace(allow_collection_copy=True)) + + async def owner(org, expected=None): + if org != ORG or (expected is not None and io.owner != expected): + raise ops._Refused() + return io.owner + + def bound_client(bound, validate): + assert bound.account == account + assert bound.contract.generation == account.connection_id + io.authorized.append((tuple(io.held), bound.contract)) + return ReadClient(io) + + monkeypatch.setattr(ops.connections, "_owner", owner) + monkeypatch.setattr(ops.connections, "_ready", AsyncMock()) + monkeypatch.setattr(ops.connections, "_binding", Mock(return_value=(profile, envelope))) + monkeypatch.setattr(ops.connections, "_bound_client", lambda current: ReadClient(io)) + monkeypatch.setattr(ops.authority.ConnectionAuthority, "client", bound_client) + monkeypatch.setattr(ops.account_store, "get", AsyncMock(return_value=account)) + monkeypatch.setattr(ops.accounts, "_fence_current", AsyncMock(return_value=True)) + monkeypatch.setattr(ops.accounts, "_standing", AsyncMock()) + monkeypatch.setattr( + ops.authority.aliases, "verified_spellings", AsyncMock(return_value=[OWNER]) + ) + monkeypatch.setattr(ops.authority.aliases, "invalidate", Mock()) + monkeypatch.setattr(ops.authz, "grant_role_for", AsyncMock(return_value=Role.ADMIN)) + return account + + +@pytest.fixture +def io(monkeypatch): + io = SourceIO() + monkeypatch.setattr(ops.store, "_default_client", lambda: io) + monkeypatch.setattr(ops.scim.leases, "holding", io.lease) + monkeypatch.setattr(ops.accounts.leases, "cluster_lease", io.lease) + monkeypatch.setattr(ops.request_work, "mark_mirrored", lambda: True) + monkeypatch.setattr(ops.authz, "row_in_scope", AsyncMock(return_value=True)) + monkeypatch.setattr(ops.sources, "_require_source_namespace", AsyncMock()) + monkeypatch.setattr(ops.sources, "_require_no_erasure", AsyncMock()) + monkeypatch.setattr(ops.source_push.store, "get", AsyncMock(return_value=None)) + monkeypatch.setattr(type(ops.settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(ops.settings, "knowledge_mirrored_sources_enabled", True) + monkeypatch.setattr(ops.settings, "knowledge_source_self_service_enabled", True) + monkeypatch.setattr(ops.settings, "knowledge_source_sync_enabled", False) + configure_authority(monkeypatch, io) + return io + + +def add_input(**changes): + values = dict( + org=ORG, + namespace=NS, + slot=SLOT, + request_id=NONCE, + mode="snapshot", + resource_ids=["opaque:A"], + label="Private label", + ) + values.update(changes) + return MCPSourceAddInput(**values) + + +def source_input(entry): + return MCPSourceInput(org=ORG, namespace=NS, name=entry.name) + + +@pytest.mark.asyncio +async def test_add_uses_actual_opaque_store_and_exact_retry(io): + result = await ops.handle_mcp_source_add(add_input()) + entry = result.source + row = await ops.store.latest_source(ORG, NS, entry.name) + expected = await ops._proposed(add_input(), OWNER) + assert row == replace(expected, created_at=row.created_at, updated_at=row.updated_at) + assert row.config == {} and row.items == [] + assert ops._contract(row).resources[0].id == "opaque:A" + assert row.connection_slot == SLOT and row.connection_id == GEN + assert entry.label == "Private label" and "Private" not in entry.name + assert result.source.refresh_state == "disabled" + assert io.authorized and len(io.authorized[-1][0]) == 3 + assert ops.sources._require_source_namespace.await_count >= 2 + assert ops.sources._require_no_erasure.await_count >= 2 + retried = await ops.handle_mcp_source_add(add_input()) + assert retried.source == result.source and len(io.writes) == 2 + assert not retried.refresh_requested + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input(resource_ids=["opaque:B"])) + assert len(io.writes) == 2 and not io.held + + +@pytest.mark.asyncio +async def test_pause_resume_preserves_identity_content_and_refuses_retry(io): + entry = (await ops.handle_mcp_source_add(add_input())).source + original = await ops.store.latest_source(ORG, NS, entry.name) + paused = await ops.handle_mcp_source_pause(source_input(entry)) + row = await ops.store.latest_source(ORG, NS, entry.name) + assert paused.source.state == "paused" and row.active and not row.pending_delete + assert ( + row.source_id == original.source_id + and row.generic_items_json == original.generic_items_json + ) + assert paused.copies == "retained" and len(io.states) == 1 + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_refresh(source_input(entry)) + resumed = await ops.handle_mcp_source_resume(source_input(entry)) + assert ( + resumed.source.state == "registered" + and not ops._contract(await ops.store.latest_source(ORG, NS, entry.name)).paused + ) + + +@pytest.mark.asyncio +async def test_selection_and_explicit_refresh_preserve_source_id_and_state(io): + entry = (await ops.handle_mcp_source_add(add_input())).source + update = MCPSourceUpdateInput( + org=ORG, + namespace=NS, + name=entry.name, + mode="snapshot", + resource_ids=["opaque:A", "opaque:B"], + label="Renamed", + ) + result = await ops.handle_mcp_source_update(update) + assert result.source.source_id == entry.source_id and result.source.selected_count == 2 + assert result.refresh_requested and result.copies == "retained" + assert len(io.states) == 1 + state = next(iter(io.states.values())) + assert json.loads(state["detail"])["full"] is True + before = len(io.writes) + unchanged = await ops.handle_mcp_source_update(update) + assert not unchanged.refresh_requested and len(io.writes) == before + refreshed = await ops.handle_mcp_source_refresh(source_input(entry)) + assert refreshed.refresh_requested and refreshed.source.refresh_state == "disabled" + assert len(io.writes) == before + 1 + + +@pytest.mark.asyncio +async def test_retirement_retains_raw_rows_and_never_reuses_nonce(io, monkeypatch): + entry = (await ops.handle_mcp_source_add(add_input())).source + queue = AsyncMock(return_value=True) + monkeypatch.setattr(ops.sources, "_queue_retirement", queue) + removal = MCPSourceRemoveInput(**source_input(entry).model_dump(), confirm=entry.name) + result = await ops.handle_mcp_source_remove(removal) + assert result.source.state == "retired" and result.copies == "retained" + queue.assert_not_awaited() + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + erased = await ops.handle_mcp_source_remove( + removal.model_copy(update={"delete_documents": True}) + ) + assert erased.copies == "erasure_requested" and erased.source.pending_erasure + queue.assert_awaited_once() + assert (await ops.store.latest_source(ORG, NS, entry.name)).generic_items_json + + +@pytest.mark.asyncio +async def test_foreign_owner_has_no_metadata_or_existence(io): + entry = (await ops.handle_mcp_source_add(add_input())).source + io.owner = "another-person" + listing = await ops.handle_mcp_source_list(MCPSourceListInput(org=ORG, namespace=NS)) + found = await ops.handle_mcp_source_inspect(source_input(entry)) + missing = await ops.handle_mcp_source_inspect( + MCPSourceInput(org=ORG, namespace=NS, name="absent") + ) + assert listing.sources == [] and found == missing + with pytest.raises(ops._Refused) as foreign: + await ops.handle_mcp_source_pause(source_input(entry)) + with pytest.raises(ops._Refused) as absent: + await ops.handle_mcp_source_pause(MCPSourceInput(org=ORG, namespace=NS, name="absent")) + assert str(foreign.value) == str(absent.value) + + +@pytest.mark.asyncio +async def test_self_service_disabled_blocks_add_before_discovery_but_not_existing_controls( + io, monkeypatch +): + entry = (await ops.handle_mcp_source_add(add_input())).source + monkeypatch.setattr(ops.settings, "knowledge_source_self_service_enabled", False) + discovery = AsyncMock(side_effect=AssertionError("no outbound call")) + monkeypatch.setattr(ops.connections, "handle_mcp_discover", discovery) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + assert (await ops.handle_mcp_source_inspect(source_input(entry))).found + assert ( + len((await ops.handle_mcp_source_list(MCPSourceListInput(org=ORG, namespace=NS))).sources) + == 1 + ) + result = await ops.handle_mcp_source_remove( + MCPSourceRemoveInput( + **source_input(entry).model_dump(), + confirm=entry.name, + ) + ) + assert result.source.state == "retired" + discovery.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_action_only_capability_or_denied_lock_never_admits(io): + io.readable = False + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + assert not io.writes + io.readable = True + io.deny_lease = True + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + assert not io.writes and not io.held + + +@pytest.mark.asyncio +async def test_admission_rechecks_current_destination_authority_under_locks(io, monkeypatch): + grant = AsyncMock(return_value=Role.VIEWER) + monkeypatch.setattr(ops.authz, "grant_role_for", grant) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + grant.assert_awaited_once_with(ORG, NS, OWNER) + assert not io.writes and len(io.authorized[-1][0]) == 3 + + +@pytest.mark.asyncio +async def test_collection_copy_requires_confirmation_and_records_exact_consent(io): + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input(reader_policy="collection_copy")) + assert not io.writes + result = await ops.handle_mcp_source_add( + add_input( + reader_policy="collection_copy", + confirm_copy_authority=True, + ) + ) + assert result.source.reader_policy == "collection_copy" + assert io.writes + + +@pytest.mark.asyncio +async def test_connection_replacement_prevents_resume_or_update(io, monkeypatch): + entry = (await ops.handle_mcp_source_add(add_input())).source + await ops.handle_mcp_source_pause(source_input(entry)) + account = await ops.account_store.get(ORG, OWNER, SLOT) + monkeypatch.setattr( + ops.account_store, + "get", + AsyncMock( + return_value=replace( + account, + connection_id="a" * 32 + "/1" + "d" * 31, + ) + ), + ) + before = len(io.writes) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_resume(source_input(entry)) + assert len(io.writes) == before + + +@pytest.mark.asyncio +async def test_unknown_contract_is_inspectable_and_retirable_without_decoding(io): + entry = (await ops.handle_mcp_source_add(add_input())).source + raw = io.rows[(ORG, NS, entry.name)] + raw["source_contract_version"] = 2 + raw["config_json"] = '{"version":2,"private":"opaque"}' + result = await ops.handle_mcp_source_inspect(source_input(entry)) + assert result.source.state == "unsupported" and result.source.resource_ids == [] + await ops.handle_mcp_source_remove( + MCPSourceRemoveInput( + **source_input(entry).model_dump(), + confirm=entry.name, + ) + ) + assert io.rows[(ORG, NS, entry.name)]["config_json"] == raw["config_json"] + + +@pytest.mark.asyncio +async def test_live_has_no_refresh_or_state_and_configured_limits_apply(io, monkeypatch): + entry = (await ops.handle_mcp_source_add(add_input(mode="live"))).source + assert entry.mode == "live" and not io.states + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_refresh(source_input(entry)) + monkeypatch.setattr(ops.settings, "knowledge_mcp_selected_resources_max", 1) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add( + add_input( + request_id="e290f1ee-6c54-4b01-90e6-d701748f0851", + resource_ids=["A", "B"], + ) + ) + monkeypatch.setattr(ops.settings, "knowledge_mcp_resource_id_max_bytes", 2) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add( + add_input( + request_id="e290f1ee-6c54-4b01-90e6-d701748f0851", + resource_ids=["éé"], + ) + ) + + +@pytest.mark.asyncio +async def test_copy_consent_is_server_issued_and_passes_through_real_admission_gate( + io, monkeypatch +): + real = ops.authority.validate_registration + gate = AsyncMock(wraps=real) + monkeypatch.setattr(ops.authority, "validate_registration", gate) + await ops.handle_mcp_source_add( + add_input( + reader_policy="collection_copy", + confirm_copy_authority=True, + ) + ) + proposed = gate.await_args.args[0] + consent = ops._contract(proposed).copy_consent + assert consent is not None + assert consent.publisher == OWNER and consent.namespace == NS + assert consent.resources_sha256 == ops.selection_sha256(ops._contract(proposed).resources) + assert proposed.access == ops.MIRRORED_ACCESS and io.writes + + +@pytest.mark.parametrize( + "field", ["owner_subject", "endpoint", "tool", "schema", "credential", "copy_consent"] +) +def test_source_api_refuses_caller_supplied_authority(field): + from pydantic import ValidationError + + values = add_input().model_dump() + values[field] = "private-value" + with pytest.raises(ValidationError) as refused: + MCPSourceAddInput.model_validate(values) + assert "private-value" not in str(refused.value) + + +@pytest.mark.asyncio +async def test_label_change_does_not_refresh_and_selection_removal_retains_copies(io): + entry = (await ops.handle_mcp_source_add(add_input(resource_ids=["A", "B"]))).source + initial_state = deepcopy(io.states) + label = MCPSourceUpdateInput( + org=ORG, + namespace=NS, + name=entry.name, + mode="snapshot", + resource_ids=["A", "B"], + label="Different label", + ) + changed = await ops.handle_mcp_source_update(label) + assert not changed.refresh_requested and io.states == initial_state + smaller = await ops.handle_mcp_source_update(label.model_copy(update={"resource_ids": ["A"]})) + assert smaller.source.source_id == entry.source_id and smaller.copies == "retained" + assert smaller.source.resource_ids == ["A"] and not smaller.source.pending_erasure + assert smaller.refresh_requested + + +@pytest.mark.asyncio +async def test_lost_add_response_reconciles_without_refresh_or_replacement(io, monkeypatch): + real_insert = io.insert + + async def lost(table, rows): + await real_insert(table, rows) + if table == ops.store.TABLE: + raise RuntimeError("lost response after successful insert") + + monkeypatch.setattr(io, "insert", lost) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + assert len(io.rows) == 1 and len(io.states) == 1 + before = deepcopy(io.writes) + result = await ops.handle_mcp_source_add(add_input()) + assert result.source.source_id == next(iter(io.rows.values()))["source_id"] + assert not result.refresh_requested and io.writes == before + + +@pytest.mark.asyncio +async def test_grant_revocation_before_lock_acquisition_prevents_writes(io, monkeypatch): + async def grant(org, namespace, role): + return not io.held + + monkeypatch.setattr(ops.authz, "row_in_scope", grant) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + assert not io.writes and not io.held + + +@pytest.mark.asyncio +@pytest.mark.parametrize("helper", ["_require_source_namespace", "_require_no_erasure"]) +async def test_invalid_destination_or_erasure_refuses_before_discovery(io, monkeypatch, helper): + monkeypatch.setattr(ops.sources, helper, AsyncMock(side_effect=ops._Refused())) + discovery = AsyncMock(side_effect=AssertionError("no outbound call")) + monkeypatch.setattr(ops.connections, "handle_mcp_discover", discovery) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + discovery.assert_not_awaited() + assert not io.writes + + +@pytest.mark.asyncio +async def test_actual_source_quota_helper_prevents_source_and_state_writes(io, monkeypatch): + monkeypatch.setattr(ops.settings, "knowledge_connected_sources_max_per_person", 0) + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_add(add_input()) + assert not io.writes and not io.held + + +def test_audit_subject_does_not_disclose_selection_labels_or_counts(): + from server.knowledge.api.ops_mcp_sources import OPERATIONS + + for operation in OPERATIONS: + if operation.audit: + assert operation.audit_subject(add_input(), object()) == {"kind": "mcp"} + + +@pytest.mark.asyncio +async def test_scope_revision_blocks_aba_and_stale_selection_updates(io): + entry = (await ops.handle_mcp_source_add(add_input(resource_ids=["A"]))).source + update = MCPSourceUpdateInput( + org=ORG, + namespace=NS, + name=entry.name, + mode="snapshot", + resource_ids=["B"], + if_scope_revision=1, + ) + second = (await ops.handle_mcp_source_update(update)).source + assert second.scope_revision == 2 + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_update(update.model_copy(update={"resource_ids": ["A"]})) + assert ops._contract(await ops.store.latest_source(ORG, NS, entry.name)).scope_revision == 2 + third = ( + await ops.handle_mcp_source_update( + update.model_copy(update={"resource_ids": ["A"], "if_scope_revision": 2}) + ) + ).source + assert third.scope_revision == 3 + assert third.source_id == entry.source_id + + +def test_update_cannot_change_publication_audience(): + from pydantic import ValidationError + + with pytest.raises(ValidationError): + MCPSourceUpdateInput( + org=ORG, + namespace=NS, + name="mcp-opaque", + mode="snapshot", + resource_ids=["A"], + reader_policy="collection_copy", + confirm_copy_authority=True, + ) + + +@pytest.mark.asyncio +async def test_list_pages_are_owner_namespace_bound_and_omit_resource_ids(io): + entries = [] + for i in range(3): + entries.append( + ( + await ops.handle_mcp_source_add( + add_input( + request_id=f"00000000-0000-4000-8000-{i:012d}", + resource_ids=[f"private:{i}"], + ) + ) + ).source + ) + first = await ops.handle_mcp_source_list(MCPSourceListInput(org=ORG, namespace=NS, limit=2)) + assert len(first.sources) == 2 and first.next_cursor + assert "private:" not in first.model_dump_json() + assert "resource_ids" not in first.model_dump_json() + second = await ops.handle_mcp_source_list( + MCPSourceListInput(org=ORG, namespace=NS, limit=2, cursor=first.next_cursor) + ) + assert len(second.sources) == 1 and second.next_cursor is None + assert {s.source_id for s in first.sources + second.sources} == {s.source_id for s in entries} + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_list( + MCPSourceListInput(org=ORG, namespace=NS, limit=1, cursor=first.next_cursor) + ) + io.owner = "another-person" + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_list( + MCPSourceListInput(org=ORG, namespace=NS, limit=2, cursor=first.next_cursor) + ) + empty = await ops.handle_mcp_source_list(MCPSourceListInput(org=ORG, namespace=NS)) + assert empty.sources == [] and empty.next_cursor is None diff --git a/tests/unit/test_mcp_source_read_policy.py b/tests/unit/test_mcp_source_read_policy.py new file mode 100644 index 0000000000..2710ce9143 --- /dev/null +++ b/tests/unit/test_mcp_source_read_policy.py @@ -0,0 +1,153 @@ +"""Current source authority cannot replace the requesting reader's authority.""" + +from collections.abc import Iterator +from dataclasses import replace +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from server.auth import reader_identity +from server.auth.context import current_auth_var +from server.auth.jwt import AuthInfo +from server.auth.reader_identity import ReaderIdentity +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app import source_access +from server.operations.base import Role +from tests.unit.test_mcp_source_sync import MIRROR, Harness +from tests.unit.test_mcp_source_sync import harness as harness + + +@pytest.fixture +def reader(harness: Harness, monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]: + auth = AuthInfo( + subject="owner", + org="org", + namespaces=("collection",), + roles=(Role.VIEWER,), + is_service_account=False, + issued_at=1000, + session_id="source-reader", + ) + monkeypatch.setattr( + reader_identity, "settings", SimpleNamespace(auth_actually_required=lambda: True) + ) + monkeypatch.setattr(authority.authz, "row_in_scope", AsyncMock(return_value=True)) + monkeypatch.setattr( + authority, + "resolve_reader", + AsyncMock( + side_effect=lambda org, subject: ReaderIdentity(subject, frozenset(), frozenset()) + ), + ) + token = current_auth_var.set(auth) + try: + yield SimpleNamespace(auth=auth, source=harness.source) + finally: + current_auth_var.reset(token) + + +@pytest.mark.asyncio +async def test_owner_can_read_selected_snapshot(reader: SimpleNamespace) -> None: + bound = await authority.validate_indexed_reader(reader.source, reader.auth) + assert len(bound.selected_uris) == 1 + + +@pytest.mark.asyncio +async def test_another_destination_reader_cannot_read_owner_only_material( + reader: SimpleNamespace, +) -> None: + other = replace(reader.auth, subject="other") + current_auth_var.set(other) + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_indexed_reader(reader.source, other) + + +@pytest.mark.asyncio +async def test_a_changed_auth_context_refuses_before_source_access(reader: SimpleNamespace) -> None: + current_auth_var.set(replace(reader.auth, subject="other")) + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_indexed_reader(reader.source, reader.auth) + + +@pytest.mark.asyncio +async def test_machine_identity_cannot_infer_a_personal_source_owner( + reader: SimpleNamespace, +) -> None: + machine = replace(reader.auth, subject="machine", is_service_account=True) + current_auth_var.set(machine) + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_indexed_reader(reader.source, machine) + + +@pytest.mark.asyncio +async def test_an_explicit_personal_reader_claim_keeps_existing_reader_semantics( + reader: SimpleNamespace, +) -> None: + personal = replace( + reader.auth, + subject="personal-token", + is_service_account=True, + reads_as_creator=True, + creator="owner", + ) + current_auth_var.set(personal) + await authority.validate_indexed_reader(reader.source, personal) + + +@pytest.mark.asyncio +async def test_live_mode_cannot_serve_a_retained_indexed_copy( + reader: SimpleNamespace, + harness: Harness, +) -> None: + harness.select(mode="live") + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_indexed_reader(harness.source, reader.auth) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("other", [False, True]) +async def test_read_plan_admits_only_the_personal_source_reader( + reader: SimpleNamespace, + harness: Harness, + monkeypatch: pytest.MonkeyPatch, + other: bool, +) -> None: + auth = replace(reader.auth, subject="other") if other else reader.auth + current_auth_var.set(auth) + plan = source_access.ReadPlan("org", _auth=auth) + monkeypatch.setattr( + authority.source_store, "latest_source", AsyncMock(side_effect=lambda *a: harness.source) + ) + monkeypatch.setattr( + source_access.mirrors_repo, "mirrors_of", AsyncMock(return_value={MIRROR: "collection"}) + ) + monkeypatch.setattr(source_access, "resolve_reader", authority.resolve_reader) + monkeypatch.setattr( + source_access.store, + "listings", + AsyncMock( + return_value=[ + { + "namespace": MIRROR, + "source_id": harness.source.source_id, + "started_at": datetime.now(UTC), + } + ] + ), + ) + row = { + "namespace": "collection", + "name": harness.source.name, + "source_id": harness.source.source_id, + "source_kind": "mcp", + "source_contract_version": 1, + "credential_mode": "connected", + } + await source_access._prepare(plan, [row], auth.subject) + if other: + assert not plan.sources and not plan._connected_pins and not plan._mcp_uris + else: + assert plan.sources == {(MIRROR, harness.source.source_id): "collection"} + assert len(plan._mcp_uris[("collection", harness.source.source_id)]) == 1 diff --git a/tests/unit/test_mcp_source_sync.py b/tests/unit/test_mcp_source_sync.py index 7c6dc6b307..10e90ef392 100644 --- a/tests/unit/test_mcp_source_sync.py +++ b/tests/unit/test_mcp_source_sync.py @@ -32,10 +32,12 @@ from server.knowledge.domain.mcp_identity import resource_uri from server.knowledge.domain.mcp_sources import ( ConnectionEnvelope, + CopyConsent, ResourceIdentity, SourceContract, encode_envelope, encode_source, + selection_sha256, ) from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource from server.knowledge.store import blobs, chunks, documents @@ -90,6 +92,18 @@ def select( payload["resources"].append({"type": "resource", "id": SECOND}) if resources is not None: payload["resources"] = [{"type": "resource", "id": item} for item in resources] + payload["copy_consent"] = ( + CopyConsent( + version=1, + publisher=self.source.owner_subject, + namespace=self.source.namespace, + resources_sha256=selection_sha256( + tuple(ResourceIdentity.model_validate(r) for r in payload["resources"]) + ), + ).model_dump(mode="json") + if policy == "collection_copy" + else None + ) self.contract = SourceContract.model_validate_json(json.dumps(payload)) config, items = encode_source(self.contract) self.source = replace(self.source, generic_config_json=config, generic_items_json=items) @@ -582,12 +596,54 @@ async def test_current_authority_refusals( @pytest.mark.asyncio -async def test_collection_copy_is_refused_even_with_operator_allow(harness: Harness) -> None: +async def test_collection_copy_requires_current_destination_administration( + harness: Harness, +) -> None: harness.select(policy="collection_copy") with pytest.raises(authority.MCPAuthorityError): await authority.validate_source(harness.source) +@pytest.mark.asyncio +async def test_explicit_collection_copy_uses_the_same_protected_write_path( + storage: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch +) -> None: + storage.select(policy="collection_copy") + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=Role.ADMIN)) + result = await execute(storage) + assert result.complete and result.status == "ok" and not result.full + document = storage.doc_rows[0] + assert document["namespace"] == MIRROR + assert access_list.from_json(document["access_json"]) == access_list.AccessList(anyone=True) + metadata = json.loads(document["metadata"]) + assert metadata["mcp_reader_policy"] == "collection_copy" + assert metadata["ingested_from"] == resource_uri(storage.source.source_id, RESOURCE) + + +@pytest.mark.parametrize("field,value", [("publisher", "other"), ("namespace", "other")]) +def test_copy_consent_cannot_be_reused_for_another_stored_binding( + harness: Harness, field: str, value: str +) -> None: + harness.select(policy="collection_copy") + consent = harness.contract.copy_consent + assert consent is not None + changed = harness.contract.model_copy( + update={"copy_consent": consent.model_copy(update={field: value})} + ) + config, items = encode_source(changed) + source = replace(harness.source, generic_config_json=config, generic_items_json=items) + with pytest.raises(authority.MCPAuthorityError): + authority.source_contract(source) + + +def test_pause_refuses_execution_without_retiring_copies(harness: Harness) -> None: + paused = harness.contract.model_copy(update={"paused": True}) + config, items = encode_source(paused) + source = replace(harness.source, generic_config_json=config, generic_items_json=items) + with pytest.raises(authority.MCPAuthorityError): + authority.source_contract(source) + + @pytest.mark.asyncio async def test_registration_checks_do_not_grant_unstored_source_execution( harness: Harness, From 5a6979353056a0f65c072688413c8a52e02b7e55 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 04:04:31 +0000 Subject: [PATCH 21/30] Bind selected document reads to current source authority Use successful per-document read evidence, guarded metadata refresh and the existing private live-publication and worker paths. Checkpoint the implementation while public surfaces, native removal and hosted privacy qualification remain in progress. Signed-off-by: zlareb1 --- docs/architecture/mcp-source-execution.md | 66 +++- docs/architecture/mcp-source-setup.md | 59 +++- server/knowledge/api/models_mcp_profiles.py | 5 +- server/knowledge/api/models_mcp_sources.py | 18 ++ server/knowledge/api/ops_mcp_sources.py | 3 +- server/knowledge/app/live_search.py | 56 +--- server/knowledge/app/mcp_live.py | 119 ++++++++ server/knowledge/app/mcp_profile_api.py | 1 + server/knowledge/app/mcp_profiles.py | 11 +- server/knowledge/app/mcp_read_receipt.py | 32 ++ server/knowledge/app/mcp_source_ops.py | 35 ++- server/knowledge/app/mcp_source_preview.py | 4 + server/knowledge/app/source_access.py | 38 ++- server/knowledge/app/source_sync.py | 55 +++- server/knowledge/app/source_sync_mcp.py | 174 ++++++++--- server/knowledge/domain/mcp_read_evidence.py | 50 +++ server/knowledge/domain/sources.py | 7 + server/knowledge/store/source_access.py | 18 +- server/memory/api/models_loom_search.py | 5 +- server/memory/app/loom_search/handler.py | 1 + tests/unit/test_mcp_profile_api.py | 4 +- tests/unit/test_mcp_source_live.py | 238 +++++++++++++++ tests/unit/test_mcp_source_ops.py | 47 ++- tests/unit/test_mcp_source_preview.py | 8 +- tests/unit/test_mcp_source_profiles.py | 21 +- tests/unit/test_mcp_source_read_policy.py | 119 +++++++- tests/unit/test_mcp_source_refresh.py | 305 +++++++++++++++++++ tests/unit/test_mcp_source_sync.py | 53 +++- tests/unit/test_mcp_source_worker.py | 105 +++++++ 29 files changed, 1498 insertions(+), 159 deletions(-) create mode 100644 server/knowledge/app/mcp_live.py create mode 100644 server/knowledge/app/mcp_read_receipt.py create mode 100644 server/knowledge/domain/mcp_read_evidence.py create mode 100644 tests/unit/test_mcp_source_live.py create mode 100644 tests/unit/test_mcp_source_refresh.py create mode 100644 tests/unit/test_mcp_source_worker.py diff --git a/docs/architecture/mcp-source-execution.md b/docs/architecture/mcp-source-execution.md index eba1cf5272..e56c6efdc1 100644 --- a/docs/architecture/mcp-source-execution.md +++ b/docs/architecture/mcp-source-execution.md @@ -15,7 +15,8 @@ progress, and limits. - `validate_registration(source)`: checks a proposed row's supported contract, connection binding, owner writer grant, and destination. The caller authorizes the human and holds the subject, account, and namespace locks through insertion. - This helper refuses collection copying and grants no stored-source execution. + Collection copying requires exact stored copy consent, current operator profile + approval, and an owner administrator grant. This grants no stored-source execution. - `validate_source(source)`: requires the exact current active source row, supported contract version, selected resources, owner, connection generation, current writer grant, and allowed destination. It returns `SourceAuthority`. @@ -36,8 +37,10 @@ relax foreground connection validation. `server/knowledge/app/source_sync_mcp.py` (`turn`) follows the existing `Pass`, `TurnResult`, pass deadline, stop checks, worker identity, and private accounting contracts. Its caller owns the normal source-turn lease and worker actor scope. -The turn uses `ensure_mirror` under the account lease, `mirror_costs`, and an -explicit owner access list. +The turn uses `ensure_mirror` under the account lease and `mirror_costs`. Both +reader policies publish into the protected mirror. Owner-only documents carry an +owner access list; collection copies carry an anyone access list under the +source's immutable audience and collection reader checks. ## Publication @@ -46,24 +49,45 @@ otherwise the client uses `resources/read`. Tool descriptions never choose an operation. Discovery validates approved tool schemas without enumerating resources or changing the stored selection. -Each accepted read has an identity-verified receipt matching the selected identity, -operation, client configuration digest, and text hash. Only text MIME types are -copied. Binary resources and plain tool text without verified result identity -refuse publication. There is no conversion or extraction step in this turn. +Each accepted read has a receipt matching the selected request identity, operation, +client configuration digest, and text hash. Resources and structured tool results +require verified result identity. An explicit tool read mapping with +`result_format=text` may return an unverified result identity: its receipt still +binds the actual selected request, body, configuration, and operation. Metadata +records `mcp_identity_verified` truthfully. + +Bounded SDK text resource bodies are text even when their declared MIME type is +`application/json`. Blob resource bodies remain unsupported. The original is +stored as UTF-8 `text/plain`; `mcp_declared_mime_type` retains the upstream +declaration in protected metadata. There is no conversion or extraction step. The address comes from `mcp_identity.resource_uri`, using the registered source ID and exact selected resource identity. Remote result URLs cannot change it. The same address identifies the document, its chunks, and citations. Metadata records the profile, generation, selection digest, read operation, and local text hash. The source revision is empty because no upstream revision guarantee is assumed. +After each successful selected read, the server stamps `mcp_read_at` with its UTC +read time and `mcp_scope_sha256` with the current bound scope. That digest includes +the server-controlled scope revision and excludes the label and pause flag. +`mcp_config_sha256` records the client configuration bound by the receipt. -Publication calls the existing `source_sync.write_document` and knowledge upsert -path, including original UTF-8 bytes, chunks, document metadata, indexing, imported +New or changed content calls the existing `source_sync.write_document` and +knowledge upsert path, including original UTF-8 bytes, chunks, document metadata, indexing, imported provenance, and source tags. The MCP commit guard is reacquired around original storage and around chunk/document commit after embedding. Both locks remain held through each storage boundary. A changed source, account, profile, owner standing, writer grant, or destination refuses the commit. +Unchanged content uses the current document head and existing document row builder. +The head must be active, published, owned by this source's sync worker, and match +the exact mirror, selected URI, source ID, title, text, content digest, and original +metadata. The MCP publication guard holds both leases while re-reading the head, +validating authority, and inserting a row over its exact optimistic version. Only +metadata, access, and row version change. Original fields, authorship, provenance, +revision, ingestion fields, and chunks carry forward. No embedding runs. Unsafe +or missing state uses the existing guarded upsert. A pending head never reports a +successful refresh. + ## Progress and invariants `live` mode creates no mirror and writes no knowledge. `snapshot` copies the @@ -77,17 +101,27 @@ mirror state. A failed or missing read leaves its index pending. A changed bindi or selection resets the index. A document bound holds new copies back while allowing already stored selected copies to refresh. +An explicit per-item remote `MCPSourceError` invalidates only that selected prior +owned copy under the MCP publication guard. A metadata-only row clears +`mcp_read_at` and `mcp_scope_sha256` and sets access to `UNREAD`. Original bytes, +history, revision, and other selected documents remain intact. A later successful +read can refresh that same original. Cancellation, authority failures, and +unexpected exceptions do not trigger this invalidation. Lost authority blocks +reads and cannot be bypassed to write an invalidation. + After every selected read and publication succeeds, with no pending publication, the turn records the existing protected listing timestamp under the commit guard. -This timestamp covers only the registered selected set and its owner permission -lists. `TurnResult.full` stays false. Selected-set completion proves no complete -upstream enumeration, remote ACL synchronization, deletion, or revision ordering. +This timestamp records progress only; it grants no document permission. +Protected read admission requires the exact selected document URI, a scope digest +equal to the current bound scope, and a server-controlled successful `mcp_read_at` +within the existing ACL stale TTL. Partial progress may publish independently fresh +selected documents. `TurnResult.full` stays false. Selected-set completion proves +no complete upstream enumeration, remote ACL synchronization, deletion, or revision ordering. Absence, errors, partial results, and selection changes never delete documents. -Without upstream ACL evidence, publication is owner-only. `collection_copy` is -refused even when the current operator profile permits it: the stored contract -does not prove durable writer consent for that publication. Admission must resolve -that missing authority before exposing this policy. +The audience is immutable for a source ID. Moving from a private audience to a +collection audience requires another registration and an upstream read; a policy +edit cannot republish a private copy as a collection copy. Source admission, worker dispatch, requesting-reader authorization, live result assembly, and source lifecycle routing are separate callers of these interfaces. diff --git a/docs/architecture/mcp-source-setup.md b/docs/architecture/mcp-source-setup.md index 445e63c365..4492a163cd 100644 --- a/docs/architecture/mcp-source-setup.md +++ b/docs/architecture/mcp-source-setup.md @@ -9,7 +9,9 @@ machinery. The automatic personal namespace cannot hold these sources. Connect an account, discover its configured read capabilities, choose exact resource IDs and a destination, then preview the access rule before registration. -Connecting, listing and previewing import no documents. Registration discovers +Connecting, listing and previewing import no documents. Approved profile responses +include the exact ASCII HTTPS credential-destination origin. A display label is +not a verified remote account identity. Registration discovers whether the configured resources or reviewed read mapping are available. An action-only server cannot pass this check. Discovery does not read the selection or prove that the owner can read each document. @@ -26,7 +28,9 @@ canonical owner, connection slot and request UUID. Labels are bounded display metadata. Retrying a lost response returns only the exact active registration with the same binding, selection, mode, audience and label. Changed arguments, a stopped connection, a paused or retired source, or a replacement connection -refuse. A replacement binding requires a separate registration and consent; +refuse. `knowledge.source.mcp_inspect` can reconcile the original owned slot and +request UUID without repeating the mutation. A replacement binding requires a +separate registration and consent; existing copies, history and checkpoints keep their identity. ## Modes and access @@ -55,10 +59,21 @@ administrator authority and explicit confirmation of publication authority over the exact selected material. The handler creates a versioned consent record binding the authenticated publisher, destination and hash of the ordered exact IDs. The caller cannot supply this proof. An update of a collection copy requires -fresh confirmation. Consent cannot authorize live sharing, a different audience -or a wider selection. Admission still requires the execution authority helper to -accept the entire proposed row. The current execution authority refuses -collection copies; confirmation alone cannot register one. +fresh confirmation. Every later read also requires current source, connection, +profile and destination authority. Publication audience is immutable for a +registration: a private-to-team change requires a new source and fresh upstream +reads. Existing private document history is never republished through an update. +Live sharing is unsupported. + +Every stored document carries the scope digest and server time of its actual +successful selected read. Reads require the current selected URI and digest, +within the reported `read_evidence_stale_seconds` bound. Selection and mode +changes advance a server-controlled `scope_revision`; removing and re-adding an +identity cannot reuse old read proof. Labels and pause preserve this revision. +A snapshot stops automatic refresh, so its read access expires until an explicit +refresh renews evidence. Bytes remain stored. Neither source-level completion +nor retained bytes grant read access. Both reader policies use protected mirrors; +collection grants alone cannot bypass the source checks. ## Lifecycle controls @@ -66,7 +81,7 @@ collection copies; confirmation alone cannot register one. | --- | --- | | `knowledge.source.mcp_list` | Lists only the caller's registrations in the requested destination | | `knowledge.source.mcp_inspect` | Returns only an owned source; a foreign ID answers as missing | -| `knowledge.source.mcp_update` | Replaces the fixed selection, mode, audience and label; retained IDs keep source document identity | +| `knowledge.source.mcp_update` | Replaces selection, mode and label; the audience is fixed, and retained IDs keep source document identity | | `knowledge.source.mcp_pause` | Sets contract pause state; retains registration, copies and checkpoints | | `knowledge.source.mcp_resume` | Revalidates the original connection binding before clearing pause | | `knowledge.source.mcp_refresh` | Requests an explicit import attempt for a copy mode through existing source state | @@ -97,8 +112,9 @@ Generic source rows carry `generic_config_json`, `generic_items_json`, `connection_slot` and a contract version. The ordinary `config` and `items` projections remain empty. Application codecs apply deployment limits to the stored opaque columns. Source changes retain the registration UUID and use the -existing store's complete version-row writes; no separate source database or -worker framework is introduced. +existing store's complete version-row writes. The common source worker dispatches +supported selected copies to the MCP engine; live and paused sources do not +schedule imports. No separate source database or worker framework is introduced. Refresh requests merge into existing state without clearing checkpoints. A selection marker prevents a label-only change from requesting another snapshot. @@ -106,3 +122,28 @@ Mutation audit subjects omit private source labels, resource IDs and counts. See [document sources](document-sources.md) for the shared document, retirement and erasure lifecycle. + + +## Live retrieval and retention + +The existing protected live-search route uses an explicitly approved search +mapping. It intersects one bounded candidate page with the saved selection, then +performs an actual selected read for each retained result. Search snippets and +resource listings carry no read proof. A resource-only server supports direct +selected live reads; it does not thereby expose a search operation. Neither path +imports content or saves a memory. Returned citations use the stable source +resource URI, not an untrusted result link. + +Protected publication rechecks the requesting reader, source and connection and +repeats retained reads before release. Changed content, schema drift or lost +authority drops the result. A configured preissued bearer is sent only to the +approved upstream origin; Loom credentials are never forwarded. Interactive +OAuth enrollment, refresh, local commands and legacy SSE are unsupported. + +The host holds live content while the request runs. Protected-result handling, +private diagnostics, session protection and the existing publication machinery +still apply; this is not a promise of zero host, client or conversation retention. +Imports persist ordinary documents, originals and chunks under the existing +storage authority and erasure rules. Pausing, disconnecting, removing a selection +or retiring a source retains those bytes unless the writer explicitly requests +erasure. No upgrade deletes content or infers a replacement service endpoint. diff --git a/server/knowledge/api/models_mcp_profiles.py b/server/knowledge/api/models_mcp_profiles.py index 444cb65369..51d4f3431c 100644 --- a/server/knowledge/api/models_mcp_profiles.py +++ b/server/knowledge/api/models_mcp_profiles.py @@ -1,4 +1,4 @@ -"""Operator approval metadata; no endpoint, credential or publication authority.""" +"""Operator approval metadata; no credential or publication authority.""" from typing import Literal @@ -36,6 +36,9 @@ class MCPProfileEntry(BaseModel): id: str label: str auth: Literal["none", "bearer"] + endpoint_origin: str = Field( + description="The approved HTTPS credential destination origin in ASCII form." + ) profile_sha256: str approved_tools: list[str] allow_collection_copy: bool = Field( diff --git a/server/knowledge/api/models_mcp_sources.py b/server/knowledge/api/models_mcp_sources.py index d240d89867..5b3bc051f9 100644 --- a/server/knowledge/api/models_mcp_sources.py +++ b/server/knowledge/api/models_mcp_sources.py @@ -49,6 +49,7 @@ class MCPSourcePreviewOutput(BaseModel): refresh_state: Literal["not_applicable", "enabled", "disabled"] selected_count: int checked_at: str + read_evidence_stale_seconds: int preview_grants_authority: Literal[False] = False limitations: list[str] @@ -101,6 +102,22 @@ class MCPSourceInput(MCPSourceScopeInput): name: str = Field(max_length=64, description="The opaque source registry name returned by add.") +class MCPSourceInspectInput(MCPSourceScopeInput): + name: str = Field( + default="", + max_length=64, + description="The exact source name, or empty for request reconciliation.", + ) + slot: str = Field( + default="", + max_length=36, + description="The original owned connection slot for request reconciliation.", + ) + request_id: str = Field( + default="", max_length=36, description="The original add UUID, with slot instead of name." + ) + + class MCPSourceUpdateInput(MCPSourceInput): if_scope_revision: int | None = Field( default=None, @@ -156,6 +173,7 @@ class MCPSourceSummary(BaseModel): label: str | None = None selected_count: int | None = None sync_enabled: bool + read_evidence_stale_seconds: int refresh_state: Literal[ "not_applicable", "enabled", "disabled", "paused", "retired", "unsupported" ] diff --git a/server/knowledge/api/ops_mcp_sources.py b/server/knowledge/api/ops_mcp_sources.py index b2e89e808b..53fa471230 100644 --- a/server/knowledge/api/ops_mcp_sources.py +++ b/server/knowledge/api/ops_mcp_sources.py @@ -3,6 +3,7 @@ from server.knowledge.api.models_mcp_sources import ( MCPSourceAddInput, MCPSourceInput, + MCPSourceInspectInput, MCPSourceInspectOutput, MCPSourceListInput, MCPSourceListOutput, @@ -76,7 +77,7 @@ ), Operation( name="knowledge.source.mcp_inspect", - input_model=MCPSourceInput, + input_model=MCPSourceInspectInput, output_model=MCPSourceInspectOutput, handler=handle_mcp_source_inspect, idempotent=True, diff --git a/server/knowledge/app/live_search.py b/server/knowledge/app/live_search.py index 90bed299d7..036f03375c 100644 --- a/server/knowledge/app/live_search.py +++ b/server/knowledge/app/live_search.py @@ -1,4 +1,4 @@ -"""Request-owned native search over the asker's connected registrations.""" +"""Request-owned MCP lookup over the asker's selected live registrations.""" from __future__ import annotations @@ -9,47 +9,32 @@ 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.clients._checked_access import CheckedAccess from server.core import request_tail, request_work from server.core.ch import set_query_tag from server.core.diagnostics import private_work -from server.knowledge.app import connected_accounts, live_provider_search, session_admission +from server.knowledge.app import connected_accounts, mcp_live, session_admission from server.knowledge.domain.sources import MIRRORED_ACCESS from server.knowledge.store import sources as source_store from server.settings import settings -@dataclass(frozen=True, repr=False) -class Contribution: - authority: connected_accounts.SourceAuthority - hits: tuple[live_provider_search.LiveProviderHit, ...] - - @dataclass(repr=False) class LiveResult: - contributions: tuple[Contribution, ...] + contributions: tuple[mcp_live.Contribution, ...] deadline: float _checked: bool = False @property - def hits(self) -> tuple[live_provider_search.LiveProviderHit, ...]: + def hits(self) -> tuple[mcp_live.LiveHit, ...]: return tuple(hit for part in self.contributions for hit in part.hits) async def check(self) -> None: - """Renew the original account/source and each selected remote membership.""" + """Recheck current authority and each retained successful selected read.""" self._checked = False with private_work(): async with asyncio.timeout_at(self.deadline): for part in self.contributions: - - async def verify(access: CheckedAccess, part: Contribution = part) -> None: - for hit in part.hits: - if not await live_provider_search.revalidate( - part.authority.source, access, hit, deadline=self.deadline - ): - raise RuntimeError("Live search unavailable") - - await part.authority.run(verify) + await part.check() self._checked = True def fresh(self) -> bool: @@ -89,7 +74,7 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> and source.credential_mode == "connected" and source.owner_subject == subject and source.access == MIRRORED_ACCESS - and source.kind in ("gdrive", "notion") + and mcp_live.is_live_source(source) ][: settings.knowledge_live_search_max_sources] if not selected: return None @@ -98,29 +83,10 @@ async def search(org: str, namespaces: list[str], query: str, *, top_k: int) -> contributions = [] remaining = min(top_k, settings.knowledge_live_search_max_hits) for source in selected: - authority = await connected_accounts.resolve( - org, - source.namespace, - source.name, - deadline=deadline, - expected_source_id=source.source_id, - ) - if authority.source != source: - continue # a changed registration cannot widen the discovered corpus - - async def native( - access: CheckedAccess, - authority: connected_accounts.SourceAuthority = authority, - remaining: int = remaining, - ) -> list[live_provider_search.LiveProviderHit]: - return await live_provider_search.search( - authority.source, access, query, top_k=remaining, deadline=deadline - ) - - hits = tuple(await authority.run(native))[:remaining] - if hits: - contributions.append(Contribution(authority, hits)) - remaining -= len(hits) + part = await mcp_live.search(source, auth, query, limit=remaining) + if part is not None: + contributions.append(part) + remaining -= len(part.hits) if not remaining: break return LiveResult(tuple(contributions), deadline) if contributions else None diff --git a/server/knowledge/app/mcp_live.py b/server/knowledge/app/mcp_live.py new file mode 100644 index 0000000000..9ccbd04c90 --- /dev/null +++ b/server/knowledge/app/mcp_live.py @@ -0,0 +1,119 @@ +"""Selected MCP live reads for the existing protected live-search response.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass +from typing import Literal + +from server.auth.jwt import AuthInfo +from server.clients.mcp_source import MCPEvidence, MCPSourceClient, MCPSourceError +from server.core.ch import set_query_tag +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app.mcp_read_receipt import require_read_receipt +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.domain.sources import KnowledgeSource + + +@dataclass(frozen=True, repr=False) +class LiveHit: + id: str + title: str + url: str + content: str + resource_identity_verified: bool + provider: Literal["mcp"] = "mcp" + + +@dataclass(frozen=True, repr=False) +class RetainedRead: + resource_id: str + content_sha256: str + title: str + + +@asynccontextmanager +async def _client(src: KnowledgeSource, auth: AuthInfo) -> AsyncIterator[MCPSourceClient]: + async def validate() -> None: + current = await authority.validate_live_reader(src, auth) + if current.source != src: + raise authority.MCPAuthorityError() + + bound = await authority.validate_live_reader(src, auth) + async with bound.connection.client(validate) as client: + yield client + + +@dataclass(frozen=True, repr=False) +class Contribution: + source: KnowledgeSource + auth: AuthInfo + hits: tuple[LiveHit, ...] + reads: tuple[RetainedRead, ...] + + async def check(self) -> None: + async with _client(self.source, self.auth) as client: + await client.discover() + for retained in self.reads: + set_query_tag("search.query.live.check") + evidence = await client.read(retained.resource_id) + digest = require_read_receipt(client, retained.resource_id, evidence) + if (digest, evidence.title) != (retained.content_sha256, retained.title): + raise MCPSourceError("denied") + + +async def search( + src: KnowledgeSource, auth: AuthInfo, query: str, *, limit: int +) -> Contribution | None: + """Read only selected IDs from one bounded mapped-search page; never import.""" + if limit < 1: + return None + hits, reads = [], [] + async with _client(src, auth) as client: + await client.discover() + if client.config.search is None: + return None + selected = {r.id for r in authority.source_contract(src).resources} + page = await client.search(query) + seen = set() + for item in page.items: + set_query_tag("search.query.live.read") + if item.resource_id not in selected or item.resource_id in seen: + continue + seen.add(item.resource_id) + evidence = await client.read(item.resource_id) + digest = require_read_receipt(client, item.resource_id, evidence) + receipt = evidence.receipt + assert receipt is not None + uri = resource_uri(src.source_id, item.resource_id) + hits.append( + LiveHit( + uri, evidence.title[:1024], uri, evidence.text[:200], receipt.identity_verified + ) + ) + reads.append(RetainedRead(item.resource_id, digest, evidence.title)) + if len(hits) == limit: + break + return Contribution(src, auth, tuple(hits), tuple(reads)) if hits else None + + +def is_live_source(src: KnowledgeSource) -> bool: + if src.kind != "mcp": + return False + try: + return authority.source_contract(src).mode == "live" + except authority.MCPAuthorityError: + return False + + +async def read_selected( + src: KnowledgeSource, auth: AuthInfo, resource_id: str +) -> tuple[MCPEvidence, Contribution]: + """Read one saved live selection; the caller must retain protected publication.""" + async with _client(src, auth) as client: + await client.discover() + evidence = await client.read(resource_id) + digest = require_read_receipt(client, resource_id, evidence) + proof = Contribution(src, auth, (), (RetainedRead(resource_id, digest, evidence.title),)) + return evidence, proof diff --git a/server/knowledge/app/mcp_profile_api.py b/server/knowledge/app/mcp_profile_api.py index 26395323b6..de2efb2c53 100644 --- a/server/knowledge/app/mcp_profile_api.py +++ b/server/knowledge/app/mcp_profile_api.py @@ -50,6 +50,7 @@ async def handle_mcp_profiles(input: MCPProfilesInput) -> MCPProfilesOutput: id=item.id, label=item.label, auth=item.auth, + endpoint_origin=item.endpoint_origin, profile_sha256=item.profile_sha256, approved_tools=list(item.approved_tools), allow_collection_copy=item.allow_collection_copy, diff --git a/server/knowledge/app/mcp_profiles.py b/server/knowledge/app/mcp_profiles.py index 541c070ef7..376fcd8982 100644 --- a/server/knowledge/app/mcp_profiles.py +++ b/server/knowledge/app/mcp_profiles.py @@ -11,6 +11,8 @@ from functools import lru_cache from typing import Any, Literal +import httpx + from server.clients.mcp_source import ( MCPBearer, MCPLimits, @@ -198,6 +200,7 @@ class MCPProfileMetadata: profile_sha256: str allow_collection_copy: bool approved_tools: tuple[str, ...] + endpoint_origin: str @dataclass(frozen=True, repr=False) @@ -244,7 +247,13 @@ def _profile(value: Any) -> FrozenProfileDefinition: snapshot = _canonical(approval, MAX_PROFILE_BYTES) digest = hashlib.sha256(snapshot.encode()).hexdigest() metadata = MCPProfileMetadata( - identity, label, auth, digest, copy_allowed, config.approved_tools + identity, + label, + auth, + digest, + copy_allowed, + config.approved_tools, + "https://" + httpx.URL(config.endpoint).netloc.decode("ascii"), ) return FrozenProfileDefinition(metadata, frozenset(orgs), snapshot) diff --git a/server/knowledge/app/mcp_read_receipt.py b/server/knowledge/app/mcp_read_receipt.py new file mode 100644 index 0000000000..069d537f23 --- /dev/null +++ b/server/knowledge/app/mcp_read_receipt.py @@ -0,0 +1,32 @@ +"""Validate successful selected-read evidence without guessing tool semantics.""" + +import hashlib + +from server.clients.mcp_source import MCPEvidence, MCPSourceClient, MCPSourceError + + +def require_read_receipt(client: MCPSourceClient, selected: str, evidence: MCPEvidence) -> str: + receipt = evidence.receipt + digest = hashlib.sha256(evidence.text.encode()).hexdigest() + mapping = client.config.read + operation = "tools/call" if mapping is not None else "resources/read" + if ( + receipt is None + or not evidence.text.strip() + or evidence.resource_id != selected + or receipt.requested_id != selected + or receipt.operation != operation + or receipt.content_sha256 != digest + or receipt.config_sha256 != client.config_sha256 + or not ( + receipt.identity_verified is True + or ( + mapping is not None + and mapping.result_format == "text" + and receipt.identity_verified is False + ) + ) + or len(evidence.text.encode()) > client.config.limits.max_content_bytes + ): + raise MCPSourceError("unsupported") + return digest diff --git a/server/knowledge/app/mcp_source_ops.py b/server/knowledge/app/mcp_source_ops.py index 958367dbcb..dba42c6054 100644 --- a/server/knowledge/app/mcp_source_ops.py +++ b/server/knowledge/app/mcp_source_ops.py @@ -20,11 +20,13 @@ MCPSourceAddInput, MCPSourceEntry, MCPSourceInput, + MCPSourceInspectInput, MCPSourceInspectOutput, MCPSourceListInput, MCPSourceListOutput, MCPSourceOutput, MCPSourceRemoveInput, + MCPSourceSummary, MCPSourceUpdateInput, ) from server.knowledge.app import connected_accounts as accounts @@ -94,10 +96,10 @@ async def _locks(org: str, namespace: str, owner: str, slot: str) -> AsyncIterat yield -def _identity(input: MCPSourceAddInput, owner: str) -> tuple[str, str]: - nonce = str(UUID(input.request_id)) +def _identity(org: str, namespace: str, owner: str, slot: str, request_id: str) -> tuple[str, str]: + nonce = str(UUID(request_id)) key = json.dumps( - [input.org, input.namespace, owner, input.slot, nonce], + [org, namespace, owner, slot, nonce], ensure_ascii=False, separators=(",", ":"), ) @@ -198,7 +200,7 @@ async def _proposed(input: MCPSourceAddInput, owner: str) -> KnowledgeSource: resources=(ResourceIdentity(type="resource", id=input.resource_ids[0]),), ) contract = await _selection(input, owner, binding) - name, source_id = _identity(input, owner) + name, source_id = _identity(input.org, input.namespace, owner, input.slot, input.request_id) return _with_contract( KnowledgeSource( org=input.org, @@ -233,6 +235,7 @@ def _entry(src: KnowledgeSource) -> MCPSourceEntry: namespace=src.namespace, state="unsupported" if src.active else "retired", sync_enabled=bool(settings.knowledge_source_sync_enabled), + read_evidence_stale_seconds=settings.knowledge_source_acl_stale_seconds, refresh_state="unsupported" if src.active else "retired", pending_erasure=src.pending_delete, ) @@ -364,7 +367,9 @@ async def handle_mcp_source_list(input: MCPSourceListInput) -> MCPSourceListOutp limit=input.limit + 1, ) entries = [ - await _checked_entry(src) + MCPSourceSummary.model_validate( + (await _checked_entry(src)).model_dump(exclude={"resource_ids"}) + ) for src in rows[: input.limit] if _owned(src, input.org, input.namespace, owner) ] @@ -377,10 +382,26 @@ async def handle_mcp_source_list(input: MCPSourceListInput) -> MCPSourceListOutp ) -async def handle_mcp_source_inspect(input: MCPSourceInput) -> MCPSourceInspectOutput: +async def handle_mcp_source_inspect(input: MCPSourceInspectInput) -> MCPSourceInspectOutput: async with _private(): owner = await _caller(input.org, input.namespace) - src = await store.latest_source(input.org, input.namespace, input.name) + name = input.name + expected_id = "" + if name: + if input.slot or input.request_id: + raise _Refused() + else: + connections._check_slot(input.slot) + name, expected_id = _identity( + input.org, input.namespace, owner, input.slot, input.request_id + ) + src = await store.latest_source(input.org, input.namespace, name) + if ( + src + and expected_id + and (src.source_id != expected_id or src.connection_slot != input.slot) + ): + raise _Refused() entry = ( await _checked_entry(src) if _owned(src, input.org, input.namespace, owner) and src diff --git a/server/knowledge/app/mcp_source_preview.py b/server/knowledge/app/mcp_source_preview.py index 2de04dc806..c521b1dd3f 100644 --- a/server/knowledge/app/mcp_source_preview.py +++ b/server/knowledge/app/mcp_source_preview.py @@ -114,10 +114,14 @@ async def handle_mcp_source_preview(input: MCPSourcePreviewInput) -> MCPSourcePr refresh_state=refresh, selected_count=len(input.resource_ids), checked_at=datetime.now(UTC).isoformat(), + read_evidence_stale_seconds=settings.knowledge_source_acl_stale_seconds, limitations=[ "Remote compatibility and selected-resource readability are unchecked.", "No upstream ACL, complete enumeration, deletion or group evidence is available.", "Only selected identities are included; future matching items are excluded.", "Preview grants no authority; mutation and every later read revalidate access.", + "Stored copies require current source authority and fresh read evidence. " + "Snapshot access expires without an explicit refresh; bytes remain stored.", + "Pausing or disconnecting stops access and retains stored bytes until erasure.", ], ) diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index 564506f2bf..32c6439d54 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -20,6 +20,7 @@ from server.core.naming import is_mirror_name from server.knowledge.domain.access_list import UNREAD, AccessList, allows, from_json from server.knowledge.domain.document_access import fresh, source_id +from server.knowledge.domain.mcp_read_evidence import ReadProof, ReadScope from server.knowledge.domain.serving import Serving from server.knowledge.domain.sources import KnowledgeSource, opaque_payload from server.knowledge.store import mirrors as mirrors_repo @@ -52,6 +53,7 @@ class AccessEvidence: canonical_owner: str groups: tuple[tuple[str, datetime], ...] reader_emails: frozenset[str] + mcp_proof: ReadProof | None = None @classmethod def from_admitted(cls, item: Admitted) -> AccessEvidence: @@ -63,6 +65,7 @@ def from_admitted(cls, item: Admitted) -> AccessEvidence: item.canonical_owner, item.groups, item.reader_emails, + ReadProof.from_row(doc), ) @@ -84,7 +87,7 @@ class ReadPlan: _connected_pins: dict[tuple[str, str], KnowledgeSource] = field( default_factory=dict, repr=False ) - _mcp_uris: dict[tuple[str, str], frozenset[str]] = field(default_factory=dict, repr=False) + _mcp_scopes: dict[tuple[str, str], ReadScope] = field(default_factory=dict, repr=False) @property def discovery_sources(self) -> dict[tuple[str, str], str]: @@ -105,7 +108,14 @@ def current(self, item: Admitted) -> bool: def current_evidence(self, item: AccessEvidence) -> bool: """Evaluate retained permission evidence against the latest shared reader view.""" at = now() - if not self.listing_current(item.namespace, item.source_id, at=at): + key = (item.namespace, item.source_id) + scope = self._mcp_scopes.get(key) + if scope is not None: + if not scope.admits( + item.mcp_proof, at=at, stale_seconds=settings.knowledge_source_acl_stale_seconds + ): + return False + elif item.mcp_proof is not None or not self.listing_current(*key, at=at): return False reader = self.reader return allows( @@ -157,6 +167,7 @@ async def _refresh_scope(self) -> None: key: started for key, started in snapshot.listing_starts.items() if key in self.sources } self.reader = snapshot.reader + self._mcp_scopes = snapshot._mcp_scopes async def _check(self, candidates: list[dict[str, Any]], *, chunks: bool) -> list[Admitted]: await self._refresh_scope() @@ -187,15 +198,10 @@ async def _check(self, candidates: list[dict[str, Any]], *, chunks: bool) -> lis sid = source_id(doc["source_uri"], doc["tags"]) key = (doc["namespace"], sid) original = self.sources.get(key) - if not self.listing_current(*key): + if key not in self._mcp_scopes and not self.listing_current(*key): continue if not original or (pg.enabled() and not _head_serves(heads[pair], candidate, chunks)): continue - pinned = self._connected_pins.get((original, sid)) - if pinned is not None and pinned.kind == "mcp": - selected = self._mcp_uris.get((original, sid)) - if selected is None or doc["source_uri"] not in selected: - continue if chunks and not pg.enabled() and int(candidate["revision"]) != doc["revision"]: continue access = permissions[pair] @@ -315,7 +321,7 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) from server.knowledge.store import sources as source_store eligible = [] - mcp_uris: dict[tuple[str, str], frozenset[str]] = {} + mcp_scopes: dict[tuple[str, str], ReadScope] = {} for row in sources: key = row["namespace"], row["source_id"] mode = row.get("credential_mode", "shared") @@ -325,6 +331,8 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) version=int(row.get("source_contract_version") or 0), ): continue + if row.get("source_kind") == "mcp" and mode != "connected": + continue if mode == "shared": if key not in plan._connected_pins: eligible.append(row) @@ -353,7 +361,7 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) continue if source.kind == "mcp": bound = await validate_indexed_reader(source, plan._auth) - mcp_uris[key] = bound.selected_uris + mcp_scopes[key] = ReadScope(bound.scope_sha256, bound.selected_uris) else: await validate_indexed(source, plan._auth) eligible.append(row) @@ -362,7 +370,6 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) except Exception: # noqa: BLE001 — one unverifiable connection admits no private leg continue sources = eligible - plan._mcp_uris = mcp_uris names = sorted({s["namespace"] for s in sources}) mirrors = await mirrors_repo.mirrors_of(plan.org, names, live_only=True) by_original: dict[str, list[str]] = {} @@ -374,7 +381,12 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) for s in sources if len(by_original.get(s["namespace"], [])) == 1 } - rows = await store.listings(plan.org, list(pairs)) + plan._mcp_scopes = { + key: mcp_scopes[(original, key[1])] + for key, original in pairs.items() + if (original, key[1]) in mcp_scopes + } + rows = await store.listings(plan.org, [key for key in pairs if key not in plan._mcp_scopes]) plan.reader = await resolve_reader(plan.org, subject) if subject else None plan.listing_starts = { (r["namespace"], r["source_id"]): r["started_at"] @@ -382,4 +394,4 @@ async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) if (r["namespace"], r["source_id"]) in pairs and fresh(r["started_at"], now(), settings.knowledge_source_acl_stale_seconds) } - plan.sources = {key: pairs[key] for key in plan.listing_starts} + plan.sources = {key: pairs[key] for key in plan.listing_starts | plan._mcp_scopes} diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index a9a15fb7f3..943a95c789 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -91,7 +91,7 @@ import logging import time from collections.abc import AsyncIterator, Awaitable, Callable, Iterator -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from datetime import UTC, datetime, timedelta from enum import StrEnum from typing import TYPE_CHECKING, Any, TypeGuard @@ -427,10 +427,20 @@ async def _usable(found: list[KnowledgeSource]) -> list[KnowledgeSource]: # With auth off there is no reader a mirror's lists could be checked against. mirrors_on = settings.auth_actually_required() syncable = [s for s in found if served(s) or (mirror_synced(s) and mirrors_on)] + syncable = [s for s in syncable if s.kind != "mcp" or _mcp_syncable(s)] inactive = await store.inactive_namespaces(sorted({(s.org, s.namespace) for s in syncable})) return [s for s in syncable if (s.org, s.namespace) not in inactive] +def _mcp_syncable(src: KnowledgeSource) -> bool: + from server.knowledge.app.mcp_source_authority import MCPAuthorityError, source_contract + + try: + return source_contract(src).mode != "live" + except (MCPAuthorityError, ValueError, TypeError): + return False + + async def _states(found: list[KnowledgeSource]) -> dict[str, dict[str, str]]: """Each source's stored sync state, by cursor.""" out: dict[str, dict[str, str]] = {} @@ -476,12 +486,10 @@ async def _sync_turn( async with _source_turn(src): try: if src.credential_mode == "connected": - from server.knowledge.app.source_sync_connected import ensure_current - - await ensure_current(src) + await _connected_current(src) turn = await _turn_of(src)(src, state, run) if src.credential_mode == "connected": - await ensure_current(src) + await _connected_current(src) except SourceGone: log.info("knowledge_source_sync: %s was removed during its turn", _cursor_of(src)) return None @@ -524,6 +532,15 @@ async def _sync_turn( return turn +async def _connected_current(src: KnowledgeSource) -> None: + if src.kind == "mcp": + await require_current(src) + else: + from server.knowledge.app.source_sync_connected import ensure_current + + await ensure_current(src) + + def _mirror_failure(src: KnowledgeSource, result: PassResult) -> None: """Report the same code for every cause without exporting turn details.""" result.errors.append(f"{_cursor_of(src)}: SYNC_FAILED") @@ -534,6 +551,12 @@ def _turn_of(src: KnowledgeSource) -> Callable[..., Awaitable[TurnResult]]: """The turn function of a source; this module's `_turn` reads a folder, and a mirrored folder source writes into its namespace's mirror.""" # Imported here: a kind's module builds on this one's helpers. + if src.kind == "mcp": + if not mirror_synced(src): + raise SourceGone(_cursor_of(src)) + from server.knowledge.app import source_sync_mcp + + return source_sync_mcp.turn if ( src.credential_mode == "connected" and src.kind in {"notion", "linear"} @@ -1261,6 +1284,11 @@ def ours(src: KnowledgeSource, doc: documents.DocumentRow) -> bool: async def require_current(src: KnowledgeSource) -> None: """SourceGone unless the source is still active as the registration this turn started with: a remove during the turn stops it before its next write.""" + if src.kind == "mcp": + from server.knowledge.app.mcp_source_authority import validate_source + + await validate_source(src) + return with sequential_reads(): fresh = await store.get_source(src.org, src.namespace, src.name) if fresh is None or not fresh.active or fresh.source_id != src.source_id: @@ -1277,7 +1305,12 @@ async def require_current(src: KnowledgeSource) -> None: @contextlib.asynccontextmanager async def publication_guard(src: KnowledgeSource) -> AsyncIterator[None]: - if src.credential_mode == "connected": + if src.kind == "mcp": + from server.knowledge.app import mcp_source_authority + + async with mcp_source_authority.publication_guard(src): + yield + elif src.credential_mode == "connected": from server.knowledge.app import connected_accounts async with connected_accounts.publication_guard(src): @@ -1405,7 +1438,11 @@ async def _write_state(src: KnowledgeSource, read: dict[str, str], turn: TurnRes fresh = await store.get_source(src.org, src.namespace, src.name) states = await store.read_states(src.org, src.namespace, [src.name]) mirror_row = await mirror_state(src, turn.mirror) if turn.mirror else {} - if fresh is None or fresh.source_id != src.source_id: + if ( + fresh is None + or fresh.source_id != src.source_id + or (src.kind == "mcp" and replace(fresh, mirror=src.mirror) != src) + ): return current = states.get(src.name) or {} if mirror_synced(src): @@ -1469,7 +1506,9 @@ async def _write_mirrored_state( last turn that returned recorded.""" now = _now_iso() stored = json_object(current.get("detail", "")) - shown: dict[str, Any] = {k: stored[k] for k in ("requested_at", "full") if k in stored} + shown: dict[str, Any] = { + k: stored[k] for k in ("requested_at", "full", "mcp_selection") if k in stored + } asked = json_object(read.get("detail", "")).get("requested_at") shown.update(last_synced_at=now, status=turn.status) if turn.complete and shown.get("requested_at") == asked: diff --git a/server/knowledge/app/source_sync_mcp.py b/server/knowledge/app/source_sync_mcp.py index 1d25a053cd..cfbb8d1b17 100644 --- a/server/knowledge/app/source_sync_mcp.py +++ b/server/knowledge/app/source_sync_mcp.py @@ -3,20 +3,23 @@ from __future__ import annotations import asyncio -import hashlib import json import time +from contextlib import suppress from dataclasses import replace from datetime import UTC, datetime from typing import Any from server.clients.mcp_source import MCPEvidence, MCPSourceClient, MCPSourceError -from server.core.ch import set_query_tag +from server.core.ch import sequential_reads, set_query_tag +from server.core.hashing import sha256_document_text +from server.core.pg_lease import PublicationPending from server.knowledge.app import connected_accounts as accounts from server.knowledge.app import mcp_source_authority as authority from server.knowledge.app import mirrors, private_sync from server.knowledge.app import source_sync as sync -from server.knowledge.domain.access_list import AccessList +from server.knowledge.app.mcp_read_receipt import require_read_receipt +from server.knowledge.domain.access_list import UNREAD, AccessList, to_json from server.knowledge.domain.mcp_identity import resource_uri from server.knowledge.domain.sources import KnowledgeSource, mirror_uri_suffix from server.knowledge.store import documents @@ -58,23 +61,107 @@ def _progress( } -def _receipt(client: MCPSourceClient, selected: str, evidence: MCPEvidence) -> str: - receipt = evidence.receipt - digest = hashlib.sha256(evidence.text.encode()).hexdigest() - operation = "tools/call" if client.config.read is not None else "resources/read" +async def _owned_head( + bound: authority.SourceAuthority, uri: str, selected: str +) -> tuple[documents.DocumentRow, dict[str, Any]] | None: + src = bound.source + if uri not in bound.selected_uris: + return None + with sequential_reads(): + rows = await documents.get_many_by_uris(src.org, src.mirror, [uri]) + if len(rows) != 1: + return None + doc = rows[0] + if ( + (doc.org, doc.namespace, doc.source_uri) != (src.org, src.mirror, uri) + or doc.superseded_at is not None + or not sync.ours(src, doc) + ): + return None + try: + metadata = json.loads(doc.metadata) + except (ValueError, TypeError): + return None + if not isinstance(metadata, dict) or ( + metadata.get("source_kind"), + metadata.get("source_name"), + metadata.get("mcp_source_id"), + ) != ("mcp", src.name, src.source_id): + return None + origin = uri if bound.contract.reader_policy == "collection_copy" else selected if ( - receipt is None - or not evidence.text.strip() - or not receipt.identity_verified - or evidence.resource_id != selected - or receipt.requested_id != selected - or receipt.operation != operation - or receipt.content_sha256 != digest - or receipt.config_sha256 != client.config_sha256 - or not evidence.mime_type.partition(";")[0].strip().lower().startswith("text/") + metadata.get("ingested_from") != origin + or metadata.get("ingested_format") != "mcp_text" + or metadata.get("mcp_reader_policy") != bound.contract.reader_policy ): - raise MCPSourceError("unsupported") - return digest + return None + return doc, metadata + + +async def _replace_head( + bound: authority.SourceAuthority, + doc: documents.DocumentRow, + metadata: dict[str, Any], + access: AccessList, +) -> bool: + row = documents.build_document_row( + doc, + version=documents.version_past(doc.version), + metadata=json.dumps(metadata, ensure_ascii=False), + access_json=to_json(access), + ) + await bound.validate() + pass_context.check_stop() + with suppress(PublicationPending): # committed; the worker publishes it + count = await documents.insert_many([row], over={doc.source_uri: doc.version}) + return count == 1 and not await documents.publications_owed( + doc.org, doc.namespace, doc.source_uri + ) + return False + + +async def _refresh( + bound: authority.SourceAuthority, + uri: str, + evidence: MCPEvidence, + metadata: dict[str, Any], + access: AccessList, +) -> bool | None: + async with authority.publication_guard(bound.source): + if await documents.publications_owed(bound.source.org, bound.source.mirror, uri): + return False + head = await _owned_head(bound, uri, evidence.resource_id) + if head is None: + return None + doc, previous = head + if ( + doc.title != evidence.title + or doc.content != evidence.text + or doc.content_sha256 != sha256_document_text(f"{doc.title}\n{doc.content}") + or previous.get("mcp_content_sha256") != metadata["mcp_content_sha256"] + or not doc.blob_path + or doc.blob_erased_at is not None + or doc.blob_size != len(evidence.text.encode()) + or doc.blob_content_type.partition(";")[0].strip().lower() != "text/plain" + or doc.revision < 1 + ): + return None + return await _replace_head(bound, doc, {**previous, **metadata}, access) + + +async def _invalidate(bound: authority.SourceAuthority, selected: str) -> None: + src = bound.source + uri = resource_uri(src.source_id, selected) + async with authority.publication_guard(src): + if await documents.publications_owed(src.org, src.mirror, uri): + return + head = await _owned_head(bound, uri, selected) + if head is None: + return + doc, metadata = head + metadata.pop("mcp_read_at", None) + metadata.pop("mcp_scope_sha256", None) + await _replace_head(bound, doc, metadata, UNREAD) async def _publish( @@ -82,29 +169,41 @@ async def _publish( client: MCPSourceClient, selected: str, evidence: MCPEvidence, + read_at: datetime, ) -> bool: - digest = _receipt(client, selected, evidence) + digest = require_read_receipt(client, selected, evidence) src = bound.source copied = bound.contract.reader_policy == "collection_copy" - return await sync.write_document( + uri = resource_uri(src.source_id, selected) + access = AccessList(anyone=True) if copied else AccessList(owner=src.owner_subject) + metadata = { + "mcp_content_sha256": digest, + "mcp_scope_sha256": bound.scope_sha256, + "mcp_config_sha256": client.config_sha256, + "mcp_profile_sha256": bound.contract.profile_sha256, + "mcp_connection_generation": bound.contract.generation, + "mcp_source_id": src.source_id, + "mcp_read_operation": "tools/call" if client.config.read else "resources/read", + "mcp_reader_policy": bound.contract.reader_policy, + "mcp_read_at": read_at.isoformat(), + "mcp_identity_verified": evidence.receipt.identity_verified if evidence.receipt else False, + "mcp_declared_mime_type": evidence.mime_type, + **({"ingested_from": uri} if copied else {}), + } + refreshed = await _refresh(bound, uri, evidence, metadata, access) + if refreshed is not None: + return refreshed + written = await sync.write_document( src, - {"id": selected, "name": evidence.title, "mimeType": evidence.mime_type}, - resource_uri(src.source_id, selected), + {"id": selected, "name": evidence.title, "mimeType": "text/plain; charset=utf-8"}, + uri, evidence.text, ingested_format="mcp_text", original=evidence.text.encode(), - permissions=AccessList(anyone=True) if copied else AccessList(owner=src.owner_subject), - extra_metadata={ - "mcp_content_sha256": digest, - "mcp_scope_sha256": bound.scope_sha256, - "mcp_profile_sha256": bound.contract.profile_sha256, - "mcp_connection_generation": bound.contract.generation, - "mcp_source_id": src.source_id, - "mcp_read_operation": "tools/call" if client.config.read else "resources/read", - "mcp_reader_policy": bound.contract.reader_policy, - **({"ingested_from": resource_uri(src.source_id, selected)} if copied else {}), - }, + permissions=access, + extra_metadata=metadata, ) + return written and not await documents.publications_owed(src.org, src.mirror, uri) async def _read_selected( @@ -126,14 +225,19 @@ async def _read_selected( result.fail("failed", "MCP_DOCUMENT_LIMIT") return run.left -= 1 - evidence = await client.read(selected) + try: + evidence = await client.read(selected) + except MCPSourceError: + await _invalidate(bound, selected) + raise + read_at = datetime.now(UTC) result.documents_seen += 1 if run.budget.exhausted(): result.mark(sync.TurnMark.PASS_BOUND) return await bound.validate() pass_context.check_stop() - if not await _publish(bound, client, selected, evidence): + if not await _publish(bound, client, selected, evidence, read_at): result.fail("failed", "MCP_DOCUMENT_HELD") return result.changed += 1 diff --git a/server/knowledge/domain/mcp_read_evidence.py b/server/knowledge/domain/mcp_read_evidence.py new file mode 100644 index 0000000000..46482a6461 --- /dev/null +++ b/server/knowledge/domain/mcp_read_evidence.py @@ -0,0 +1,50 @@ +"""Content-free successful-read proof for one exact selected MCP document.""" + +from __future__ import annotations + +from dataclasses import dataclass +from datetime import datetime +from typing import Any + +from server.knowledge.domain.document_access import fresh + + +@dataclass(frozen=True) +class ReadProof: + uri: str + scope_sha256: str + read_at: datetime + + @classmethod + def from_row(cls, row: dict[str, Any]) -> ReadProof | None: + digest, observed = row.get("mcp_scope_sha256"), row.get("mcp_read_at") + if ( + not isinstance(digest, str) + or len(digest) != 64 + or any(c not in "0123456789abcdef" for c in digest) + or not isinstance(observed, str) + or len(observed) > 64 + ): + return None + try: + at = datetime.fromisoformat(observed) + except ValueError: + return None + uri = row.get("source_uri") + if at.tzinfo is None or not isinstance(uri, str): + return None + return cls(uri, digest, at) + + +@dataclass(frozen=True) +class ReadScope: + scope_sha256: str + selected_uris: frozenset[str] + + def admits(self, proof: ReadProof | None, *, at: datetime, stale_seconds: int) -> bool: + return ( + proof is not None + and proof.scope_sha256 == self.scope_sha256 + and proof.uri in self.selected_uris + and fresh(proof.read_at, at, stale_seconds) + ) diff --git a/server/knowledge/domain/sources.py b/server/knowledge/domain/sources.py index 2305ca8c86..6cd0bb9faa 100644 --- a/server/knowledge/domain/sources.py +++ b/server/knowledge/domain/sources.py @@ -587,6 +587,13 @@ def served(src: KnowledgeSource) -> bool: def mirror_synced(src: KnowledgeSource) -> bool: """Whether the sync worker writes `src` into its namespace's mirror: a mirrored folder-store source or a person's connected page/project source.""" + if src.kind == "mcp": + return ( + src.credential_mode == "connected" + and type(src.source_contract_version) is int + and src.source_contract_version == 1 + and src.access == MIRRORED_ACCESS + ) return ( not opaque_payload( kind=src.kind, mode=src.credential_mode, version=src.source_contract_version diff --git a/server/knowledge/store/source_access.py b/server/knowledge/store/source_access.py index 2579072e54..8a96551e65 100644 --- a/server/knowledge/store/source_access.py +++ b/server/knowledge/store/source_access.py @@ -10,6 +10,8 @@ from server.knowledge.store.pg_documents import decode_row # Content and arbitrary metadata are read only after admission, at the checked version. +# Only these content-free MCP proof fields are projected before admission. +_MCP_PROOF_FIELDS = ("mcp_scope_sha256", "mcp_read_at") _METADATA = ( "org", "namespace", @@ -75,8 +77,12 @@ async def metadata( ) -> list[dict[str, Any]]: if not pairs: return [] + fields = [ + *_METADATA, + *(f"JSONExtractString(metadata, '{name}') AS {name}" for name in _MCP_PROOF_FIELDS), + ] return await (ch or _default_client()).query_all( - f"SELECT {', '.join(_METADATA)} FROM loom.documents FINAL " + f"SELECT {', '.join(fields)} FROM loom.documents FINAL " "WHERE org = {org:String} AND (namespace, source_uri) " "IN {pairs:Array(Tuple(String, String))} " "LIMIT {limit:UInt32}", @@ -102,7 +108,15 @@ async def heads(org: str, pairs: list[tuple[str, str]]) -> dict[tuple[str, str], pairs = sorted({p for p in pairs if not pg.unstorable(p)}) if not pairs or pg.unstorable(org): return {} - fields = ", ".join(f"'{col}', h.row -> '{col}'" for col in _METADATA) + fields = ", ".join( + [ + *(f"'{col}', h.row -> '{col}'" for col in _METADATA), + *( + f"'{name}', NULLIF(h.row ->> 'metadata', '')::jsonb ->> '{name}'" + for name in _MCP_PROOF_FIELDS + ), + ] + ) rows = await pg.fetch( f"SELECT h.namespace, h.source_uri, jsonb_build_object({fields}) AS row, " "h.deleted, h.revision, h.chunks_revision, h.chunks_version " diff --git a/server/memory/api/models_loom_search.py b/server/memory/api/models_loom_search.py index 6ea13deecd..987a485f06 100644 --- a/server/memory/api/models_loom_search.py +++ b/server/memory/api/models_loom_search.py @@ -68,7 +68,10 @@ class LiveSearchHit(BaseModel): id: str = Field(min_length=1, max_length=1024) title: str = Field(max_length=1024) url: str = Field(min_length=1, max_length=4096) - provider: Literal["gdrive", "notion", "linear"] + provider: Literal["mcp"] + resource_identity_verified: bool = Field( + description="Whether the selected read echoed its requested resource identity." + ) content: str = Field(default="", max_length=200) live: Literal[True] = True diff --git a/server/memory/app/loom_search/handler.py b/server/memory/app/loom_search/handler.py index 0f25d78b78..c35c1ba40b 100644 --- a/server/memory/app/loom_search/handler.py +++ b/server/memory/app/loom_search/handler.py @@ -92,6 +92,7 @@ async def handle_search(input: SearchInput) -> SearchOutput: title=hit.title, url=hit.url, provider=hit.provider, + resource_identity_verified=hit.resource_identity_verified, content=hit.content if input.bodies != "none" else "", ) for hit in result.hits diff --git a/tests/unit/test_mcp_profile_api.py b/tests/unit/test_mcp_profile_api.py index 7cf35cbf01..af9df28681 100644 --- a/tests/unit/test_mcp_profile_api.py +++ b/tests/unit/test_mcp_profile_api.py @@ -174,11 +174,13 @@ async def test_two_org_users_only_see_eligible_safe_metadata(world: SimpleNamesp "label", "auth", "profile_sha256", + "endpoint_origin", "approved_tools", "allow_collection_copy", } serialized = first.model_dump_json() - for forbidden in ("allowed_orgs", "endpoint", "offline.invalid", "audience", "config", "total"): + assert first.profiles[0].endpoint_origin == "https://offline.invalid" + for forbidden in ("allowed_orgs", '"endpoint"', "/mcp", "audience", "config", "total"): assert forbidden not in serialized first.profiles[0].approved_tools.append("unapproved") current_auth_var.set(auth()) diff --git a/tests/unit/test_mcp_source_live.py b/tests/unit/test_mcp_source_live.py new file mode 100644 index 0000000000..849ae1f029 --- /dev/null +++ b/tests/unit/test_mcp_source_live.py @@ -0,0 +1,238 @@ +"""Official SDK live results stay selected, private and publication checked.""" + +import asyncio +import json +import time +from dataclasses import replace +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from mcp import types + +from server.auth.context import current_auth_var +from server.clients.mcp_source import MCPSourceError +from server.knowledge.app import live_search, mcp_connections, mcp_live, mcp_profiles, writes +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app.mcp_contracts import encode_source +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.domain.mcp_sources import ConnectionEnvelope, encode_envelope +from tests.unit.test_mcp_source_read_policy import reader as reader +from tests.unit.test_mcp_source_sync import RESOURCE, SECOND, TOOL_OUTPUT +from tests.unit.test_mcp_source_sync import harness as harness +from tests.unit.test_mcp_source_sync import upstream as upstream + +SEARCH_INPUT = { + "type": "object", + "properties": {"query": {"type": "string"}}, + "required": ["query"], + "additionalProperties": False, +} +SEARCH_OUTPUT = { + "type": "object", + "properties": {"items": {"type": "array", "items": TOOL_OUTPUT}}, + "required": ["items"], + "additionalProperties": False, +} + + +@pytest.fixture +def live_setup(reader, harness, monkeypatch): + catalog = mcp_profiles.MCPProfileCatalog.parse( + json.dumps( + { + "version": 1, + "profiles": [ + { + "id": "approved", + "label": "Reader", + "auth": "none", + "allowed_orgs": ["org"], + "config": { + "endpoint": "https://selected.example/mcp", + "approved_tools": ["lookup"], + "search": { + "name": "lookup", + "argument_name": "query", + "input_schema": SEARCH_INPUT, + "output_schema": SEARCH_OUTPUT, + "items_path": ["items"], + }, + }, + } + ], + } + ) + ) + profile = catalog.get("org", "approved") + harness.contract = harness.contract.model_copy( + update={ + "mode": "live", + "profile_sha256": profile.metadata.profile_sha256, + } + ) + config, items = encode_source(harness.contract) + harness.source = replace(harness.source, generic_config_json=config, generic_items_json=items) + envelope = ConnectionEnvelope( + version=1, + org="org", + owner="owner", + slot=harness.contract.slot, + generation=harness.contract.generation, + profile_id="approved", + profile_sha256=profile.metadata.profile_sha256, + endpoint="https://selected.example/mcp", + audience=None, + auth="none", + ) + monkeypatch.setattr(mcp_connections, "load_mcp_profile_catalog", lambda: catalog) + monkeypatch.setattr(mcp_connections, "unseal", lambda *a, **k: encode_envelope(envelope)) + monkeypatch.setattr( + writes, + "handle_knowledge_upsert", + AsyncMock(side_effect=AssertionError("live retrieval must not import")), + ) + return SimpleNamespace(h=harness, auth=reader.auth, schema=SEARCH_OUTPUT) + + +@pytest.fixture +def live_tools(live_setup, upstream): + state = live_setup + + @upstream._mcp_server.list_tools() + async def listed(): + return [types.Tool(name="lookup", inputSchema=SEARCH_INPUT, outputSchema=state.schema)] + + @upstream._mcp_server.call_tool() + async def called(name, arguments): + assert name == "lookup" and arguments == {"query": "selected"} + rows = [ + { + "id": value, + "title": "Untrusted search title", + "text": "Search is not a read", + "uri": "https://untrusted.example/", + } + for value in (SECOND, RESOURCE, RESOURCE) + ] + return types.CallToolResult(content=[], structuredContent={"items": rows}) + + return state + + +@pytest.mark.asyncio +async def test_live_search_reads_only_selected_ids_and_imports_nothing(live_tools): + h, auth = live_tools.h, live_tools.auth + result = await mcp_live.search(h.source, auth, "selected", limit=2) + assert result is not None and len(result.hits) == 1 + hit = result.hits[0] + assert hit.id == hit.url == resource_uri(h.source.source_id, RESOURCE) + assert hit.provider == "mcp" and hit.resource_identity_verified + assert hit.content == h.text and hit.content != "Search is not a read" + assert h.reads == [RESOURCE] and not h.doc_rows and not h.originals + writes.handle_knowledge_upsert.assert_not_awaited() + await result.check() + assert h.reads == [RESOURCE, RESOURCE] + + +@pytest.mark.asyncio +async def test_live_result_loses_publication_when_the_resource_changes(live_tools): + result = await mcp_live.search(live_tools.h.source, live_tools.auth, "selected", limit=1) + live_tools.h.text = "Changed after retrieval" + with pytest.raises(MCPSourceError): + await result.check() + + +@pytest.mark.asyncio +async def test_live_revalidation_detects_schema_drift(live_tools): + result = await mcp_live.search(live_tools.h.source, live_tools.auth, "selected", limit=1) + live_tools.schema = {**SEARCH_OUTPUT, "description": "Changed contract"} + with pytest.raises(MCPSourceError): + await result.check() + + +@pytest.mark.asyncio +async def test_another_user_cannot_open_the_owned_live_source(live_tools): + other = replace(live_tools.auth, subject="other") + current_auth_var.set(other) + with pytest.raises(authority.MCPAuthorityError): + await mcp_live.search(live_tools.h.source, other, "selected", limit=1) + assert live_tools.h.reads == [] + + +@pytest.mark.asyncio +async def test_local_revocation_blocks_retained_live_results_before_another_read( + live_tools, monkeypatch +): + result = await mcp_live.search(live_tools.h.source, live_tools.auth, "selected", limit=1) + monkeypatch.setattr(authority.accounts, "_fence_current", AsyncMock(return_value=False)) + with pytest.raises(authority.MCPAuthorityError): + await result.check() + assert live_tools.h.reads == [RESOURCE] + + +@pytest.mark.asyncio +async def test_existing_live_pipeline_retains_its_final_publication_check(live_tools, monkeypatch): + h = live_tools.h + monkeypatch.setattr( + live_search, + "settings", + SimpleNamespace( + auth_actually_required=lambda: True, + knowledge_mirrored_sources_enabled=True, + knowledge_live_search_timeout_s=10, + knowledge_live_search_max_sources=4, + knowledge_live_search_max_hits=5, + ), + ) + monkeypatch.setattr(live_search, "protected_for", lambda auth: True) + monkeypatch.setattr(live_search.request_tail, "required_active", lambda: True) + monkeypatch.setattr(live_search.request_work, "mark_mirrored", lambda: True) + monkeypatch.setattr(live_search.session_admission, "require", AsyncMock()) + monkeypatch.setattr( + live_search.connected_accounts, "own_subject", AsyncMock(return_value=("org", "owner")) + ) + monkeypatch.setattr( + live_search.source_store, "connected_sources", AsyncMock(return_value=[h.source]) + ) + retained = [] + monkeypatch.setattr( + live_search.request_tail, "retain_publication", lambda *args: retained.append(args) or True + ) + result = await live_search.search("org", ["collection"], "selected", top_k=1) + assert result is not None and not result.fresh() + assert await live_search.publish(result) is result and result.fresh() + assert retained == [(result, result.check, result.fresh)] + h.text = "The remote result changed before final release" + with pytest.raises(MCPSourceError): + await retained[0][1]() + assert not result.fresh() + + +@pytest.mark.asyncio +async def test_cancelled_live_rpc_is_joined(live_tools, upstream): + started, stopped = asyncio.Event(), asyncio.Event() + + @upstream._mcp_server.call_tool() + async def blocked(name, arguments): + started.set() + try: + await asyncio.Event().wait() + finally: + stopped.set() + + task = asyncio.create_task( + mcp_live.search(live_tools.h.source, live_tools.auth, "selected", limit=1) + ) + async with asyncio.timeout(5): + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await stopped.wait() + assert not live_tools.h.reads and not live_tools.h.doc_rows + + +def test_expired_retained_live_result_is_not_fresh(): + result = live_search.LiveResult((), time.monotonic() - 1, _checked=True) + assert not result.fresh() diff --git a/tests/unit/test_mcp_source_ops.py b/tests/unit/test_mcp_source_ops.py index 2e42cff9e0..c8fd3681b3 100644 --- a/tests/unit/test_mcp_source_ops.py +++ b/tests/unit/test_mcp_source_ops.py @@ -17,6 +17,7 @@ from server.knowledge.api.models_mcp_sources import ( MCPSourceAddInput, MCPSourceInput, + MCPSourceInspectInput, MCPSourceListInput, MCPSourceRemoveInput, MCPSourceUpdateInput, @@ -317,9 +318,11 @@ async def test_foreign_owner_has_no_metadata_or_existence(io): entry = (await ops.handle_mcp_source_add(add_input())).source io.owner = "another-person" listing = await ops.handle_mcp_source_list(MCPSourceListInput(org=ORG, namespace=NS)) - found = await ops.handle_mcp_source_inspect(source_input(entry)) + found = await ops.handle_mcp_source_inspect( + MCPSourceInspectInput(**source_input(entry).model_dump()) + ) missing = await ops.handle_mcp_source_inspect( - MCPSourceInput(org=ORG, namespace=NS, name="absent") + MCPSourceInspectInput(org=ORG, namespace=NS, name="absent") ) assert listing.sources == [] and found == missing with pytest.raises(ops._Refused) as foreign: @@ -339,7 +342,11 @@ async def test_self_service_disabled_blocks_add_before_discovery_but_not_existin monkeypatch.setattr(ops.connections, "handle_mcp_discover", discovery) with pytest.raises(ops._Refused): await ops.handle_mcp_source_add(add_input()) - assert (await ops.handle_mcp_source_inspect(source_input(entry))).found + assert ( + await ops.handle_mcp_source_inspect( + MCPSourceInspectInput(**source_input(entry).model_dump()) + ) + ).found assert ( len((await ops.handle_mcp_source_list(MCPSourceListInput(org=ORG, namespace=NS))).sources) == 1 @@ -419,7 +426,9 @@ async def test_unknown_contract_is_inspectable_and_retirable_without_decoding(io raw = io.rows[(ORG, NS, entry.name)] raw["source_contract_version"] = 2 raw["config_json"] = '{"version":2,"private":"opaque"}' - result = await ops.handle_mcp_source_inspect(source_input(entry)) + result = await ops.handle_mcp_source_inspect( + MCPSourceInspectInput(**source_input(entry).model_dump()) + ) assert result.source.state == "unsupported" and result.source.resource_ids == [] await ops.handle_mcp_source_remove( MCPSourceRemoveInput( @@ -640,3 +649,33 @@ async def test_list_pages_are_owner_namespace_bound_and_omit_resource_ids(io): ) empty = await ops.handle_mcp_source_list(MCPSourceListInput(org=ORG, namespace=NS)) assert empty.sources == [] and empty.next_cursor is None + + +@pytest.mark.asyncio +async def test_uncertain_add_is_reconciled_by_original_owner_slot_and_uuid(io): + added = (await ops.handle_mcp_source_add(add_input())).source + query = MCPSourceInspectInput(org=ORG, namespace=NS, slot=SLOT, request_id=NONCE) + inspected = await ops.handle_mcp_source_inspect(query) + assert inspected.found and inspected.source.source_id == added.source_id + io.owner = "another-person" + assert not (await ops.handle_mcp_source_inspect(query)).found + io.owner = OWNER + with pytest.raises(ops._Refused): + await ops.handle_mcp_source_inspect(query.model_copy(update={"name": added.name})) + missing = query.model_copy(update={"request_id": "00000000-0000-4000-8000-000000000999"}) + assert not (await ops.handle_mcp_source_inspect(missing)).found + + +def test_inspect_operation_uses_the_request_reconciliation_contract(): + from server.knowledge.api.ops_mcp_sources import OPERATIONS + + operation = next(op for op in OPERATIONS if op.name == "knowledge.source.mcp_inspect") + query = operation.input_model.model_validate( + { + "org": ORG, + "namespace": NS, + "slot": SLOT, + "request_id": NONCE, + } + ) + assert isinstance(query, MCPSourceInspectInput) and query.name == "" diff --git a/tests/unit/test_mcp_source_preview.py b/tests/unit/test_mcp_source_preview.py index 5506a83570..58d437fac8 100644 --- a/tests/unit/test_mcp_source_preview.py +++ b/tests/unit/test_mcp_source_preview.py @@ -102,7 +102,13 @@ async def entry(account: object) -> MCPConnectionEntry: SimpleNamespace(profile_id="approved", profile_sha256="d" * 64), ), ) - monkeypatch.setattr(preview, "settings", SimpleNamespace(knowledge_source_sync_enabled=False)) + monkeypatch.setattr( + preview, + "settings", + SimpleNamespace( + knowledge_source_sync_enabled=False, knowledge_source_acl_stale_seconds=300 + ), + ) state.input = MCPSourcePreviewInput( org="org-a", namespace="col-destination", diff --git a/tests/unit/test_mcp_source_profiles.py b/tests/unit/test_mcp_source_profiles.py index 52a6dce458..cc1f9c903d 100644 --- a/tests/unit/test_mcp_source_profiles.py +++ b/tests/unit/test_mcp_source_profiles.py @@ -20,7 +20,13 @@ MCPProfileError, build_mcp_source_client, ) -from server.knowledge.domain.mcp_sources import ConnectionEnvelope, SourceContract +from server.knowledge.domain.mcp_sources import ( + ConnectionEnvelope, + CopyConsent, + ResourceIdentity, + SourceContract, + selection_sha256, +) SLOT = "mcp:" + "a" * 32 GENERATION = "b" * 32 + "/0" + "c" * 31 @@ -465,11 +471,20 @@ def test_digest_is_canonical_and_changes_with_approval() -> None: def test_collection_copy_policy_is_separate_from_publication_grants() -> None: + consent = CopyConsent( + version=1, + publisher="owner-a", + namespace="collection", + resources_sha256=selection_sha256( + (ResourceIdentity(type="resource", id="doc://selected"),) + ), + ) + changes = dict(reader_policy="collection_copy", mode="snapshot", copy_consent=consent) denied = catalog(row()).get("org-a", "approved") with pytest.raises(MCPProfileError): - client(denied, contract=selection(denied, reader_policy="collection_copy")) + client(denied, contract=selection(denied, **changes)) approved = catalog(row(allow_collection_copy=True)).get("org-a", "approved") - opened = client(approved, contract=selection(approved, reader_policy="collection_copy")) + opened = client(approved, contract=selection(approved, **changes)) assert opened.validate_access is access_check assert opened.config.approved_resource_ids == ("doc://selected",) with pytest.raises(MCPProfileError): diff --git a/tests/unit/test_mcp_source_read_policy.py b/tests/unit/test_mcp_source_read_policy.py index 2710ce9143..64024bc854 100644 --- a/tests/unit/test_mcp_source_read_policy.py +++ b/tests/unit/test_mcp_source_read_policy.py @@ -2,7 +2,7 @@ from collections.abc import Iterator from dataclasses import replace -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from types import SimpleNamespace from unittest.mock import AsyncMock @@ -14,6 +14,10 @@ from server.auth.reader_identity import ReaderIdentity from server.knowledge.app import mcp_source_authority as authority from server.knowledge.app import source_access +from server.knowledge.app.mcp_contracts import encode_source +from server.knowledge.domain.access_list import AccessList, to_json +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.domain.mcp_read_evidence import ReadProof from server.operations.base import Role from tests.unit.test_mcp_source_sync import MIRROR, Harness from tests.unit.test_mcp_source_sync import harness as harness @@ -147,7 +151,116 @@ async def test_read_plan_admits_only_the_personal_source_reader( } await source_access._prepare(plan, [row], auth.subject) if other: - assert not plan.sources and not plan._connected_pins and not plan._mcp_uris + assert not plan.sources and not plan._connected_pins and not plan._mcp_scopes else: assert plan.sources == {(MIRROR, harness.source.source_id): "collection"} - assert len(plan._mcp_uris[("collection", harness.source.source_id)]) == 1 + assert len(plan._mcp_scopes[(MIRROR, harness.source.source_id)].selected_uris) == 1 + + +async def installed_plan(reader, harness, monkeypatch, *, mode="connected"): + row = { + "namespace": "collection", + "name": harness.source.name, + "source_id": harness.source.source_id, + "source_kind": "mcp", + "source_contract_version": 1, + "credential_mode": mode, + } + monkeypatch.setattr( + authority.source_store, "latest_source", AsyncMock(side_effect=lambda *a: harness.source) + ) + monkeypatch.setattr( + source_access.mirrors_repo, "mirrors_of", AsyncMock(return_value={MIRROR: "collection"}) + ) + monkeypatch.setattr(source_access, "resolve_reader", authority.resolve_reader) + monkeypatch.setattr(source_access.store, "listings", AsyncMock(return_value=[])) + monkeypatch.setattr(source_access.store, "active_sources", AsyncMock(return_value=[row])) + monkeypatch.setattr(source_access.pg, "enabled", lambda: False) + monkeypatch.setattr(source_access, "canonical_subject", AsyncMock(side_effect=lambda org, s: s)) + plan = source_access.ReadPlan("org", _auth=reader.auth, _reader_subject=reader.auth.subject) + await source_access._prepare(plan, [row], reader.auth.subject) + plan._bindings = tuple( + (mirror, sid, original) for (mirror, sid), original in plan.sources.items() + ) + return plan + + +def checked_document(harness): + return { + "org": "org", + "namespace": MIRROR, + "source_uri": resource_uri(harness.source.source_id, harness.contract.resources[0].id), + "tags": ["source-id:" + harness.source.source_id], + "revision": 1, + "version": 1, + "access_json": to_json(AccessList(owner="owner")), + "mcp_scope_sha256": authority.source_scope_sha256(harness.source, harness.contract), + "mcp_read_at": datetime.now(UTC).isoformat(), + } + + +@pytest.mark.asyncio +async def test_mcp_shared_mode_header_cannot_bypass_owner_checks(reader, harness, monkeypatch): + plan = await installed_plan(reader, harness, monkeypatch, mode="shared") + assert not plan.sources and not plan._mcp_scopes + authority.source_store.latest_source.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_selected_document_requires_its_own_current_read_not_a_listing( + reader, harness, monkeypatch +): + plan = await installed_plan(reader, harness, monkeypatch) + doc = checked_document(harness) + monkeypatch.setattr(source_access.store, "metadata", AsyncMock(return_value=[doc])) + candidates = [{"namespace": MIRROR, "source_uri": doc["source_uri"]}] + assert not plan.listing_starts + admitted = await plan.check(candidates) + assert len(admitted) == 1 and plan.current(admitted[0]) + evidence = source_access.AccessEvidence.from_admitted(admitted[0]) + assert evidence.mcp_proof == ReadProof.from_row(doc) + assert "content" not in vars(evidence) + for mutation in ( + {"mcp_read_at": ""}, + {"mcp_scope_sha256": "f" * 64}, + {"mcp_read_at": (datetime.now(UTC) - timedelta(days=365)).isoformat()}, + {"mcp_read_at": (datetime.now(UTC) + timedelta(days=1)).isoformat()}, + ): + altered = {**doc, **mutation} + monkeypatch.setattr(source_access.store, "metadata", AsyncMock(return_value=[altered])) + assert await plan.check(candidates) == [] + assert not plan.failed + + +@pytest.mark.asyncio +async def test_removed_identity_and_aba_scope_cannot_reuse_published_evidence( + reader, harness, monkeypatch +): + plan = await installed_plan(reader, harness, monkeypatch) + doc = checked_document(harness) + monkeypatch.setattr(source_access.store, "metadata", AsyncMock(return_value=[doc])) + candidates = [{"namespace": MIRROR, "source_uri": doc["source_uri"]}] + admitted = await plan.check(candidates) + retained = source_access.AccessEvidence.from_admitted(admitted[0]) + assert plan.current_evidence(retained) + harness.contract = harness.contract.model_copy(update={"scope_revision": 3}) + config, items = encode_source(harness.contract) + harness.source = replace(harness.source, generic_config_json=config, generic_items_json=items) + assert await plan.check(candidates) == [] + assert not plan.current_evidence(retained) + # A new request also refuses the historical proof, despite the identical selected ID. + new_plan = await installed_plan(reader, harness, monkeypatch) + assert await new_plan.check(candidates) == [] + doc["mcp_scope_sha256"] = authority.source_scope_sha256(harness.source, harness.contract) + assert len(await new_plan.check(candidates)) == 1 + + +@pytest.mark.asyncio +async def test_unselected_uri_does_not_borrow_another_selected_read_proof( + reader, harness, monkeypatch +): + plan = await installed_plan(reader, harness, monkeypatch) + doc = checked_document(harness) + doc["source_uri"] = resource_uri(harness.source.source_id, "not-selected") + monkeypatch.setattr(source_access.store, "metadata", AsyncMock(return_value=[doc])) + assert await plan.check([{"namespace": MIRROR, "source_uri": doc["source_uri"]}]) == [] diff --git a/tests/unit/test_mcp_source_refresh.py b/tests/unit/test_mcp_source_refresh.py new file mode 100644 index 0000000000..066ce8f07a --- /dev/null +++ b/tests/unit/test_mcp_source_refresh.py @@ -0,0 +1,305 @@ +"""Per-document MCP refresh through real SDK and document row builders.""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import replace +from datetime import UTC, datetime +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from mcp.server.fastmcp import FastMCP + +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app import source_sync_mcp as engine +from server.knowledge.app import writes +from server.knowledge.app.mcp_read_receipt import require_read_receipt +from server.knowledge.domain import access_list +from server.knowledge.store import documents +from server.operations.base import Role +from tests.unit.test_mcp_source_sync import ( + JSON_TEXT, + MIRROR, + RESOURCE, + SECOND, + Harness, + execute, +) +from tests.unit.test_mcp_source_sync import ( + harness as harness, +) +from tests.unit.test_mcp_source_sync import ( + storage as storage, +) +from tests.unit.test_mcp_source_sync import ( + upstream as upstream, +) + + +@pytest.fixture +def heads(storage: Harness, monkeypatch: pytest.MonkeyPatch) -> Harness: + def latest(*args: Any, **kwargs: Any) -> list[documents.DocumentRow]: + by_uri = {row["source_uri"]: row for row in storage.doc_rows} + return [documents.DocumentRow(**by_uri[uri]) for uri in args[2] if uri in by_uri] + + monkeypatch.setattr(documents, "get_many_by_uris", AsyncMock(side_effect=latest)) + monkeypatch.setattr( + documents, + "get_one", + AsyncMock(side_effect=lambda *a, **k: next(iter(latest(*a[:2], [a[2]])), None)), + ) + return storage + + +@pytest.mark.asyncio +@pytest.mark.parametrize("policy", ["owner_only", "collection_copy"]) +async def test_unchanged_refresh_preserves_every_non_access_field( + heads: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch, policy: str +) -> None: + h = heads + h.select(mode="selected_refresh", policy=policy) + if policy == "collection_copy": + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=Role.ADMIN)) + await execute(h) + before = dict(h.doc_rows[-1]) + before.update(agent="author-agent", user_id="author", session_id="author-session") + h.doc_rows[-1] = before + embed = AsyncMock(side_effect=AssertionError("unchanged content must not embed")) + monkeypatch.setattr(writes, "_embed_inline_batch", embed) + earliest = datetime.now(UTC) + result = await execute(h) + assert result.complete and result.status == "ok" + after = h.doc_rows[-1] + assert len(h.doc_rows) == 2 and len(h.chunk_rows) == len(h.originals) == 1 + assert {k: v for k, v in before.items() if k not in {"metadata", "access_json", "version"}} == { + k: v for k, v in after.items() if k not in {"metadata", "access_json", "version"} + } + assert after["version"] > before["version"] + metadata = json.loads(after["metadata"]) + bound = await authority.validate_source(replace(h.source, mirror=MIRROR)) + assert metadata["mcp_scope_sha256"] == bound.scope_sha256 + assert earliest <= datetime.fromisoformat(metadata["mcp_read_at"]) <= datetime.now(UTC) + assert metadata["mcp_identity_verified"] is True + assert metadata["mcp_config_sha256"] + expected = ( + access_list.AccessList(anyone=True) + if policy == "collection_copy" + else (access_list.AccessList(owner="owner")) + ) + assert access_list.from_json(after["access_json"]) == expected + embed.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_changed_text_uses_actual_upsert(heads: Harness, upstream: FastMCP) -> None: + heads.select(mode="selected_refresh") + await execute(heads) + heads.text = "Changed selected text." + result = await execute(heads) + assert result.complete and len(heads.originals) == len(heads.chunk_rows) == 2 + assert heads.doc_rows[-1]["content"] == heads.text + assert heads.doc_rows[-1]["revision"] == heads.doc_rows[0]["revision"] + 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "field,value", + [ + ("blob_path", ""), + ("blob_size", 1), + ("content_sha256", "wrong"), + ("title", "Changed title"), + ("metadata", "{}"), + ], +) +async def test_unsafe_original_or_head_uses_upsert( + heads: Harness, upstream: FastMCP, field: str, value: Any +) -> None: + heads.select(mode="selected_refresh") + await execute(heads) + heads.doc_rows[-1][field] = value + result = await execute(heads) + assert result.complete and len(heads.originals) == len(heads.chunk_rows) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("late", ["source", "account"]) +async def test_late_authority_loss_prevents_refresh( + heads: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch, late: str +) -> None: + heads.select(mode="selected_refresh") + await execute(heads) + read = documents.get_many_by_uris + + async def replaced(*args: Any, **kwargs: Any) -> Any: + row = await read(*args, **kwargs) + if late == "source": + heads.source = replace(heads.source, active=False) + else: + heads.account = replace(heads.account, active=False) + return row + + monkeypatch.setattr(documents, "get_many_by_uris", replaced) + result = await execute(heads) + assert result.status == "unavailable" and not result.complete + assert len(heads.doc_rows) == len(heads.originals) == len(heads.chunk_rows) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("policy", ["owner_only", "collection_copy"]) +async def test_failed_item_clears_only_its_proof( + heads: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch, policy: str +) -> None: + heads.select(mode="selected_refresh", policy=policy, two=True) + if policy == "collection_copy": + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=Role.ADMIN)) + await execute(heads) + old = dict(heads.doc_rows[-1]) + heads.failing_resource = SECOND + result = await execute(heads) + assert result.status == "failed" and not result.complete and result.removed == 0 + assert result.kind_state["mcp_next_index"] == 1 + fresh, failed = heads.doc_rows[-2:] + assert json.loads(fresh["metadata"])["mcp_read_at"] + expected = ( + access_list.AccessList(anyone=True) + if policy == "collection_copy" + else access_list.AccessList(owner="owner") + ) + assert access_list.from_json(fresh["access_json"]) == expected + metadata = json.loads(failed["metadata"]) + assert "mcp_read_at" not in metadata and "mcp_scope_sha256" not in metadata + assert access_list.from_json(failed["access_json"]) == access_list.UNREAD + assert {k: v for k, v in failed.items() if k not in {"metadata", "access_json", "version"}} == { + k: v for k, v in old.items() if k not in {"metadata", "access_json", "version"} + } + assert len(heads.originals) == len(heads.chunk_rows) == 2 + heads.listing.assert_awaited_once() + heads.failing_resource = "" + heads.saved = result.kind_state + retry = await execute(heads) + assert retry.complete and json.loads(heads.doc_rows[-1]["metadata"])["mcp_read_at"] + assert len(heads.originals) == len(heads.chunk_rows) == 2 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("harness", ["text"], indirect=True) +async def test_plain_sdk_tool_receipt_is_honest(heads: Harness, upstream: FastMCP) -> None: + result = await execute(heads) + assert result.complete and heads.originals == ["Plain selected text. λ".encode()] + metadata = json.loads(heads.doc_rows[-1]["metadata"]) + assert metadata["mcp_identity_verified"] is False + assert metadata["mcp_read_operation"] == "tools/call" + assert metadata["mcp_read_at"] and metadata["mcp_scope_sha256"] + + +@pytest.mark.asyncio +async def test_sdk_text_resource_with_json_mime_is_text(heads: Harness, upstream: FastMCP) -> None: + heads.select(resources=(JSON_TEXT,)) + result = await execute(heads) + assert result.complete and heads.originals == [b'{"selected": "text"}'] + document = heads.doc_rows[-1] + assert document["blob_content_type"] == "text/plain; charset=utf-8" + assert json.loads(document["metadata"])["mcp_declared_mime_type"] == "application/json" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("existing", [False, True]) +async def test_pending_head_never_counts_as_success( + heads: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch, existing: bool +) -> None: + heads.select(mode="selected_refresh") + if existing: + await execute(heads) + monkeypatch.setattr( + documents, + "publications_owed", + AsyncMock(side_effect=lambda *a: "owed" if heads.doc_rows else ""), + ) + result = await execute(heads) + assert result.status == "failed" and not result.complete and result.changed == 0 + assert len(heads.doc_rows) == len(heads.originals) == len(heads.chunk_rows) == 1 + + +@pytest.mark.asyncio +async def test_refresh_uses_exact_optimistic_version( + heads: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch +) -> None: + heads.select(mode="selected_refresh") + await execute(heads) + before = heads.doc_rows[-1] + insert = AsyncMock(return_value=0) + monkeypatch.setattr(documents, "insert_many", insert) + result = await execute(heads) + assert result.status == "failed" and not result.complete + assert insert.await_args.kwargs == {"over": {before["source_uri"]: before["version"]}} + assert len(heads.doc_rows) == len(heads.originals) == len(heads.chunk_rows) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change", [{"actor": "foreign"}, {"tags": []}]) +async def test_foreign_head_is_never_refreshed( + heads: Harness, upstream: FastMCP, change: dict[str, Any] +) -> None: + heads.select(mode="selected_refresh") + await execute(heads) + heads.doc_rows[-1].update(change) + result = await execute(heads) + assert result.status == "failed" and not result.complete + assert len(heads.doc_rows) == len(heads.originals) == len(heads.chunk_rows) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("error", [RuntimeError("unexpected"), asyncio.CancelledError()]) +async def test_non_remote_failures_never_invalidate( + heads: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch, error: BaseException +) -> None: + heads.select(mode="selected_refresh") + await execute(heads) + monkeypatch.setattr(engine.MCPSourceClient, "read", AsyncMock(side_effect=error)) + with pytest.raises(type(error)): + await execute(heads) + assert len(heads.doc_rows) == 1 + assert json.loads(heads.doc_rows[-1]["metadata"])["mcp_read_at"] + + +@pytest.mark.asyncio +async def test_remote_failure_cannot_bypass_lost_authority( + heads: Harness, upstream: FastMCP, monkeypatch: pytest.MonkeyPatch +) -> None: + heads.select(mode="selected_refresh") + await execute(heads) + + async def failed(*args: Any) -> None: + heads.source = replace(heads.source, active=False) + raise engine.MCPSourceError("protocol") + + monkeypatch.setattr(engine.MCPSourceClient, "read", failed) + result = await execute(heads) + assert result.status == "unavailable" and not result.complete + assert len(heads.doc_rows) == len(heads.originals) == len(heads.chunk_rows) == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("harness", ["text"], indirect=True) +async def test_plain_receipt_still_binds_body_request_config_and_operation( + harness: Harness, upstream: FastMCP +) -> None: + bound = await authority.validate_source(harness.source) + client = bound.client() + async with client: + evidence = await client.read(RESOURCE) + assert evidence.receipt is not None and evidence.receipt.identity_verified is False + assert require_read_receipt(client, RESOURCE, evidence) == evidence.receipt.content_sha256 + for changed in ( + replace(evidence, text="tampered"), + replace(evidence, resource_id=SECOND), + replace(evidence, receipt=None), + replace(evidence, receipt=replace(evidence.receipt, requested_id=SECOND)), + replace(evidence, receipt=replace(evidence.receipt, config_sha256="0" * 64)), + replace(evidence, receipt=replace(evidence.receipt, operation="resources/read")), + ): + with pytest.raises(engine.MCPSourceError): + require_read_receipt(client, RESOURCE, changed) diff --git a/tests/unit/test_mcp_source_sync.py b/tests/unit/test_mcp_source_sync.py index 10e90ef392..d712956d0e 100644 --- a/tests/unit/test_mcp_source_sync.py +++ b/tests/unit/test_mcp_source_sync.py @@ -27,6 +27,7 @@ from server.knowledge.app import mcp_source_authority as authority from server.knowledge.app import source_sync as sync from server.knowledge.app import source_sync_mcp as engine +from server.knowledge.app.mcp_read_receipt import require_read_receipt from server.knowledge.domain import access_list from server.knowledge.domain.connected_accounts import ConnectedAccount from server.knowledge.domain.mcp_identity import resource_uri @@ -48,6 +49,7 @@ RESOURCE = "selected://document/one" SECOND = "selected://document/two" BINARY = "selected://document/binary" +JSON_TEXT = "selected://document/json-text" TOOL_INPUT = { "type": "object", "properties": {"resource_id": {"type": "string"}}, @@ -109,7 +111,7 @@ def select( self.source = replace(self.source, generic_config_json=config, generic_items_json=items) -def _catalog(tool: bool) -> mcp_profiles.MCPProfileCatalog: +def _catalog(tool: str) -> mcp_profiles.MCPProfileCatalog: config: dict[str, Any] = {"endpoint": "https://selected.example/mcp"} if tool: config.update( @@ -121,6 +123,10 @@ def _catalog(tool: bool) -> mcp_profiles.MCPProfileCatalog: "output_schema": TOOL_OUTPUT, }, ) + if tool == "text": + config["read"].update( + result_format="text", output_schema={"type": "string"}, require_output_schema=False + ) return mcp_profiles.MCPProfileCatalog.parse( json.dumps( { @@ -166,7 +172,7 @@ def test_authority_reads_the_actual_opaque_store_representation(harness: Harness @pytest.fixture def harness(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> Harness: - catalog = _catalog(getattr(request, "param", "") == "tool") + catalog = _catalog(getattr(request, "param", "")) profile = catalog.get("org", "approved") slot, generation = "mcp:" + "a" * 32, "a" * 32 + "/1" + "b" * 31 contract = SourceContract( @@ -321,6 +327,11 @@ async def binary() -> bytes: harness.reads.append(BINARY) return b"\x00\x01" + @server.resource(JSON_TEXT, mime_type="application/json") + async def json_text() -> str: + harness.reads.append(JSON_TEXT) + return '{"selected": "text"}' + _tools(server, harness) app = server.streamable_http_app() original_builder = authority.build_mcp_source_client @@ -360,14 +371,30 @@ async def lifetime() -> None: def _tools(server: FastMCP, h: Harness) -> None: + config = json.loads(h.source.generic_config_json) + # The envelope profile determines the wire schema, not the selected document. + plain = ( + _catalog("text").get("org", "approved").metadata.profile_sha256 == config["profile_sha256"] + ) + @server._mcp_server.list_tools() async def listed() -> list[types.Tool]: - return [types.Tool(name="read_selected", inputSchema=TOOL_INPUT, outputSchema=TOOL_OUTPUT)] + return [ + types.Tool( + name="read_selected", + inputSchema=TOOL_INPUT, + outputSchema=None if plain else TOOL_OUTPUT, + ) + ] @server._mcp_server.call_tool() async def called(name: str, arguments: dict[str, Any]) -> types.CallToolResult: assert name == "read_selected" and arguments == {"resource_id": RESOURCE} h.reads.append("tool:" + arguments["resource_id"]) + if plain: + return types.CallToolResult( + content=[types.TextContent(type="text", text="Plain selected text. λ")] + ) value = { "id": RESOURCE, "title": "Selected", @@ -396,6 +423,7 @@ def storage(harness: Harness, monkeypatch: pytest.MonkeyPatch) -> Harness: monkeypatch.setattr(chunks, "count_active_for_doc", AsyncMock(return_value=0)) monkeypatch.setattr(chunks, "count_matching_chunk_hashes", AsyncMock(return_value=0)) monkeypatch.setattr(documents, "get_one", AsyncMock(return_value=None)) + monkeypatch.setattr(documents, "get_many_by_uris", AsyncMock(return_value=[])) monkeypatch.setattr(writes, "_drop_own_chunks", AsyncMock()) async def blob(org: str, namespace: str, raw: bytes, **kwargs: Any) -> str: @@ -414,6 +442,15 @@ async def insert_document(row: Any, **kwargs: Any) -> None: monkeypatch.setattr(blobs, "put", blob) monkeypatch.setattr(chunks, "insert_chunks", insert_chunks) monkeypatch.setattr(documents, "insert_one", insert_document) + + async def insert_many(rows: list[Any], *, over: dict[str, int]) -> int: + assert h.locks == ["account", "namespace"] + for row in rows: + assert row["version"] > over[row["source_uri"]] + h.doc_rows.extend(rows) + return len(rows) + + monkeypatch.setattr(documents, "insert_many", insert_many) return h @@ -717,13 +754,13 @@ async def test_actual_receipt_rejects_tampering_and_unselected_reads( client = bound.client() async with client: evidence = await client.read(RESOURCE) - assert engine._receipt(client, RESOURCE, evidence) == evidence.receipt.content_sha256 + assert require_read_receipt(client, RESOURCE, evidence) == evidence.receipt.content_sha256 with pytest.raises(MCPSourceError): - engine._receipt(client, RESOURCE, replace(evidence, text="injected")) + require_read_receipt(client, RESOURCE, replace(evidence, text="injected")) with pytest.raises(MCPSourceError): - engine._receipt(client, SECOND, evidence) + require_read_receipt(client, SECOND, evidence) with pytest.raises(MCPSourceError): - engine._receipt(client, RESOURCE, replace(evidence, receipt=None)) + require_read_receipt(client, RESOURCE, replace(evidence, receipt=None)) assert evidence.receipt is not None for receipt in ( replace(evidence.receipt, identity_verified=False), @@ -731,7 +768,7 @@ async def test_actual_receipt_rejects_tampering_and_unselected_reads( replace(evidence.receipt, config_sha256="0" * 64), ): with pytest.raises(MCPSourceError): - engine._receipt(client, RESOURCE, replace(evidence, receipt=receipt)) + require_read_receipt(client, RESOURCE, replace(evidence, receipt=receipt)) with pytest.raises(MCPSourceError): await client.read(SECOND) assert harness.reads == [RESOURCE] diff --git a/tests/unit/test_mcp_source_worker.py b/tests/unit/test_mcp_source_worker.py new file mode 100644 index 0000000000..0453812267 --- /dev/null +++ b/tests/unit/test_mcp_source_worker.py @@ -0,0 +1,105 @@ +"""The shared worker routes selected MCP sources through protected execution.""" + +import json +import time +from contextlib import asynccontextmanager +from dataclasses import replace +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from server.code.app.index.pass_budget import PassBudget +from server.knowledge.app import source_sync as sync +from server.knowledge.app import source_sync_mcp as engine +from server.knowledge.app.mcp_contracts import encode_source +from server.knowledge.domain.sources import mirror_synced, served +from tests.unit.test_mcp_source_sync import MIRROR, RESOURCE +from tests.unit.test_mcp_source_sync import harness as harness +from tests.unit.test_mcp_source_sync import storage as storage +from tests.unit.test_mcp_source_sync import upstream as upstream + + +@pytest.mark.asyncio +async def test_shared_worker_runs_actual_mcp_engine_as_private_work(storage, upstream, monkeypatch): + h = storage + + @asynccontextmanager + async def lease(name, **kwargs): + assert name == sync.turn_lease_name(h.source.org, h.source.namespace, h.source.name) + yield SimpleNamespace() + + monkeypatch.setattr(sync.leases, "cluster_lease", lease) + recorded = AsyncMock() + monkeypatch.setattr(sync, "_write_state", recorded) + assert mirror_synced(h.source) and not served(h.source) + assert sync._turn_of(h.source) is engine.turn + result = sync.PassResult() + started = time.monotonic() + turn = await sync._sync_one( + h.source, {}, sync.Pass(PassBudget(started, started + 15), 10), result + ) + assert turn is not None and turn.complete and turn.changed == 1 + assert result.private_work and not result.errors + assert h.reads == [RESOURCE] and h.doc_rows and h.chunk_rows and h.originals + recorded.assert_awaited_once_with(h.source, {}, turn) + + +@pytest.mark.asyncio +async def test_only_supported_unpaused_indexed_mcp_selections_are_worker_candidates( + harness, monkeypatch +): + h = harness + monkeypatch.setattr(type(sync.settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(sync.store, "inactive_namespaces", AsyncMock(return_value=set())) + assert await sync._usable([h.source]) == [h.source] + assert not served(h.source) + for mode, paused in (("live", False), ("snapshot", True), ("selected_refresh", True)): + contract = h.contract.model_copy(update={"mode": mode, "paused": paused}) + config, items = encode_source(contract) + candidate = replace(h.source, generic_config_json=config, generic_items_json=items) + assert await sync._usable([candidate]) == [] + for change in ( + {"source_contract_version": 2}, + {"credential_mode": "shared"}, + {"access": "namespace"}, + {"generic_config_json": "invalid"}, + ): + assert await sync._usable([replace(h.source, **change)]) == [] + + +@pytest.mark.asyncio +async def test_worker_state_retains_request_scope_without_publishing_private_progress( + harness, monkeypatch +): + h = harness + writes = [] + + async def write(org, namespace, key, *, state_value, detail): + writes.append((org, namespace, key, state_value, detail)) + + monkeypatch.setattr(sync.store, "write_state", write) + current = { + "detail": json.dumps( + { + "requested_at": "request", + "full": True, + "mcp_selection": "scope", + "private": "must stay private", + } + ) + } + turn = sync.TurnResult( + complete=False, + mirror=MIRROR, + kind_state={"mcp_next_index": 1, "mcp_scope_sha256": "a" * 64}, + ) + await sync._write_mirrored_state(h.source, current, turn, current, {}) + assert len(writes) == 2 + private, public = writes + assert private[1:3] == (MIRROR, h.source.source_id) + assert private[4]["mcp_next_index"] == 1 + assert public[1:3] == (h.source.namespace, h.source.name) + assert public[4]["mcp_selection"] == "scope" + assert public[4]["requested_at"] == "request" + assert set(public[4]) == {"mcp_selection", "requested_at", "full", "last_synced_at", "status"} From 730f5095348f093f66dac6100dd6fc9ea8eb10e8 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 04:08:28 +0000 Subject: [PATCH 22/30] Regenerate lifecycle statement shapes Use the actual analyzer generator artifact from the lifecycle prerequisite head. The ordinary analyzer gate remains required, and later source changes need their own generated manifest. Signed-off-by: zlareb1 --- tests/analyzer/shapes.txt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/analyzer/shapes.txt b/tests/analyzer/shapes.txt index 14f0afebac..0312347ccc 100644 --- a/tests/analyzer/shapes.txt +++ b/tests/analyzer/shapes.txt @@ -404,6 +404,7 @@ 2fab97e447f4 SELECT count() AS n FROM loom.entity_vectors FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL 2fc0cc735773 SELECT toString(evidence_id) AS eid, session_id, role, actor, toString(observed_at) AS observed, content, matched FROM ( SELECT evidence_id, session_id, role, actor, observed_at, content, tombstoned_a 2fd8ca033214 DELETE FROM loom.memory_chunks WHERE org = {org:String} AND namespace = {ns:String} AND agent = {a:String} AND user_id = {u:String} AND parent_memory_key = {k:String} AND if(session_id = {ss:String}, +2fe865223145 SELECT namespace, name, credential_mode, source_kind, source_contract_version, toString(source_id) AS source_id FROM loom.knowledge_sources FINAL WHERE org = {org:String} AND namespace IN {names:Array 30364bf4b5e4 SELECT chunk_id, path, scope, kind, start_line, end_line, content, symbol_ids, context_description, arraySum(arrayMap((tok, idf) -> idf * countSubstrings(concat(?, lexemes, ?), concat(?, tok, ?)), {to 303a1827c22d SELECT DISTINCT msg_id FROM loom.conversations WHERE org = {org:String} AND namespace = {ns:String} AND thread_id = {tid:String} AND msg_id IN {mids:Array(String)} AND is_saved AND tombstoned_at IS NU 30406949d371 SELECT memory_id, version, agent, user_id, session_id, memory_key, created_at FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND memory_key IN {keys:Array(String)} AND tom @@ -1093,7 +1094,6 @@ 7dfbb777603e ALTER TABLE loom.memory_evidence DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? 7e34abf20d24 ALTER TABLE loom.memory_record_versions DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_syn 7e726e6f73c0 SELECT model, count() AS turns, uniqExact(session_id) AS sessions, sum(toUInt64(input_tokens)) AS input_tokens, sum(toUInt64(cache_read_tokens)) AS cache_read_tokens, sum(toUInt64(cache_creation_5m_to -7eccab6dfda3 SELECT org, namespace, name, source_id, kind, source_kind, config_json, items_json, credential_enc, secret_enc, access, credential_mode, owner_subject, connection_id, created_by, active, pending_delet 7ed9e5f6ceb3 ALTER TABLE loom.memory_chunk_sources UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace = {ns:String}) AND ({erasure_mutation_tag:String} = {erasu 7eea2ee7caf9 SELECT memory_key, (status != ? OR tombstoned_at IS NOT NULL OR redacted_at IS NOT NULL) AS taken_out FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND agent = {agent:Str 7ef1d533ac81 SELECT count() AS n FROM loom.memory_evidence WHERE org = {org:String} AND namespace = {ns:String} AND ? @@ -1813,7 +1813,6 @@ cbf399def5b1 SELECT org, namespace, agent, user_id, session_id, memory_key, vers cc115227ad18 SELECT count() AS n FROM loom.namespace_guides WHERE org = {org:String} AND namespace = {ns:String} cc216db24930 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user cc23f4e1f7d2 SELECT count() AS n FROM loom.memory_chunks FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} -cc5e9c8e7936 SELECT namespace, name, credential_mode, toString(source_id) AS source_id FROM loom.knowledge_sources FINAL WHERE org = {org:String} AND namespace IN {names:Array(String)} AND active AND access = ? OR cc63d1a2772c SELECT count() AS n FROM loom.session_summaries FINAL WHERE org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)} cc7a1e0e6cae SELECT count() AS n FROM loom.conflict_allowlist FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL cc814212d2f9 SELECT agent, user_id, session_id, memory_key, version FROM loom.memory_embeddings WHERE org = {org:String} AND namespace = {ns:String} AND (agent, user_id, session_id, memory_key, version) IN {ids:Ar @@ -1977,6 +1976,7 @@ dcb65c413049 ALTER TABLE loom.learnings_supporters DELETE WHERE (org = {org:Stri dceb7b1fc6e2 SELECT count() AS n FROM loom.working_memory FINAL WHERE org = {org:String} AND namespace IN {ns:Array(String)} AND tombstoned_at IS NULL dcec8269d95c SELECT org, namespace, path, chunk_id, version FROM loom.code_chunks WHERE (org, namespace) IN {repos:Array(Tuple(String, String))} AND embedding_model = {model:String} AND embedding_dim = ? AND tombs dcf30791d67e SELECT callee_name, path, line, from_symbol_id, argMax(from_qualified_name, version) AS from_qualified_name, argMax(call_text, version) AS call_text, argMax(disposition, version) AS disposition, argMa +dd1201806f23 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou dd4474955b2b SELECT category_id, name, description FROM loom.categories FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL dd4d7b25f19d SELECT m.namespace AS namespace, m.agent AS agent, m.user_id AS user_id, m.session_id AS session_id, m.memory_key AS memory_key, m.superseded_by AS superseded_by, s.memory_key AS successor_key, toStri dd5343c3124f SELECT cityHash64(namespace, entity_a, entity_b) AS h FROM loom.entity_edge_memories FINAL WHERE org = {org:String} GROUP BY namespace, entity_a, entity_b HAVING countIf(((namespace, memory_key) IN (S @@ -2002,6 +2002,7 @@ deb47fbf6e50 SELECT neighbor, role, sum(co_occur) AS co_occur FROM ( SELECT obje ded4dbaaf6b9 SELECT toString(schema_id) AS schema_id, name, description, status FROM loom.memory_schemas FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL ORDER BY name LIMIT {li dedc23bcedfb SELECT namespace, thread_id, ts, msg_id, row_bytes, bytes_before FROM ( SELECT namespace, thread_id, ts, msg_id, row_bytes, sum(row_bytes) OVER (ORDER BY namespace, thread_id, ts, msg_id ROWS BETWEEN deec6ef78a0a SELECT to_symbol_id, count() AS call_sites, countIf(match(caller_bare, {registrar:String})) AS registration FROM ( SELECT to_symbol_id, from_symbol_id, path, line, argMax(tombstoned_at IS NULL, versio +def7d9fdd17a SELECT org, namespace, name, source_id, kind, source_kind, config_json, items_json, credential_enc, secret_enc, access, credential_mode, owner_subject, connection_id, source_contract_version, connecti df065418883d DELETE FROM loom.chunks WHERE (org = {org:String} AND user_id = {uid:String}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS lightweight_deletes_sync = ? df0e1be64e2f SELECT count() OVER () AS total, memory_key, toString(memory_id) AS memory_id, confidence, agent FROM loom.memory FINAL WHERE org = {org:String} AND namespace = {ns:String} AND tombstoned_at IS NULL A df31f9f54e16 SELECT from_key, to_key, relation FROM loom.operator_edges FINAL WHERE org = {org:String} AND namespace = {ns:String} AND from_key IN {keys:Array(String)} AND relation IN {rels:Array(String)} AND tomb @@ -2206,7 +2207,6 @@ f52e30d82733 SELECT e.memory_key AS memory_key, e.memory_type AS memory_type, e. f5ddaf977ab5 SELECT state_key, state_value AS value FROM loom.code_index_state FINAL WHERE org = {org:String} AND namespace = {ns:String} AND state_key IN {keys:Array(String)} f60a04215196 SELECT concat(?, toString(c.session_id), ?, toString(c.chunk_index)) AS memory_key, ? AS memory_type, substring(c.content, ?, ?) AS content_excerpt, c.content AS content_full, c.agent AS agent, c.user f617d9867707 SELECT count() AS n FROM loom.memory_code_links WHERE org = {org:String} AND namespace IN {ns:Array(String)} -f6389b5cd8c4 -- schemas/schema.sql -- -- Reference dump of `loom.*` and `loom_telemetry.*`: what replaying schemas/migrations/*.sql -- produces, auto-generated by scripts/ops/dump_schema.py from a live -- ClickHou f646cb42e8e3 ALTER TABLE loom.derived_facts DELETE WHERE (org = {org:String} AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:String} = {erasure_mutation_tag:String}) SETTINGS mutations_sync = ? f65fc198c24d ALTER TABLE loom.memory_record_conflicts UPDATE tombstoned_at = {now:DateTime} WHERE (org = {org:String} AND tombstoned_at IS NULL AND namespace IN {ns:Array(String)}) AND ({erasure_mutation_tag:Strin f6669612c23e SELECT p.pr_number AS pr_number, p.merge_commit_sha AS merge_commit_sha, p.pack_tokens AS pack_tokens, p.created_at AS created_at, ifNull(h.title, ?) AS title, ifNull(h.author, ?) AS author, h.merged_ From d95fb2fc4e4da80fad289f9969c69bad7daa5ea4 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 04:37:28 +0000 Subject: [PATCH 23/30] Cancel queued notifications during normal MCP shutdown Keep foreground closed-session calls terminal while joining pending SDK notification work. Cover discovery-only resource and action-only servers without extra RPCs. Signed-off-by: zlareb1 --- server/clients/mcp_source.py | 15 ++++++++++++++- tests/unit/test_mcp_source_client.py | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/server/clients/mcp_source.py b/server/clients/mcp_source.py index 69a0ffb620..6a514b8e4f 100644 --- a/server/clients/mcp_source.py +++ b/server/clients/mcp_source.py @@ -791,6 +791,19 @@ async def _authorize(self) -> None: await self.validate_access() self._check_state() + async def _transport_authorize(self) -> None: + try: + await self._authorize() + except MCPSourceError as error: + if ( + error.code == "closed" + and self._closing + and asyncio.current_task() is not self._owner_task + ): + # Pending SDK notifications stop without poisoning expected shutdown. + raise asyncio.CancelledError from None + raise + async def __aenter__(self) -> MCPSourceClient: if self._owner_task is not None or self._deadline: raise MCPSourceError("closed") @@ -849,7 +862,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None: self._config, self.credential, self._deadline, - self._authorize, + self._transport_authorize, transport=self._test_transport, ) self._transport = transport diff --git a/tests/unit/test_mcp_source_client.py b/tests/unit/test_mcp_source_client.py index 4b1858b55e..3e50406a2f 100644 --- a/tests/unit/test_mcp_source_client.py +++ b/tests/unit/test_mcp_source_client.py @@ -1222,3 +1222,19 @@ async def reply(request: httpx.Request) -> httpx.Response: assert pins == [str(httpx.URL(endpoint))] assert requests == [] assert transport.failure == "denied" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("actions_only", [False, True]) +async def test_discovery_without_an_approved_tool_rpc_closes_cleanly( + monkeypatch: pytest.MonkeyPatch, actions_only: bool +) -> None: + async with synthetic_server(monkeypatch, tools=actions_only) as state: + opened = client() + async with opened: + discovered = await opened.discover() + assert discovered.resources is (not actions_only) + assert discovered.tools == () + assert state["calls"] == [] + assert opened._owner_task is not None and opened._owner_task.done() + assert opened._transport is not None and opened._transport.failure is None From a10c9e10a2cd94c8547178672dc80aa029dbef76 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 05:42:24 +0000 Subject: [PATCH 24/30] Execute selected document sources through MCP Preserve retained registrations while removing their native HTTP and OAuth execution paths. Reuse knowledge publication and recording work, and refuse stale selected-read authority. Signed-off-by: zlareb1 --- docs/architecture/mcp-document-sources.md | 219 ++ docs/reference/configuration.md | 38 +- loom.example.yaml | 105 +- schemas/loom-settings.schema.json | 183 +- .../migrations/117_mcp_source_admission.sql | 4 + scripts/gates/mcp_source_lifecycle.py | 11 +- server/clients/connected_oauth.py | 332 --- server/clients/gdrive.py | 449 ---- server/clients/gdrive_push.py | 85 - server/clients/linear.py | 446 ---- server/clients/notion.py | 290 --- server/knowledge/api/models_connections.py | 36 - .../knowledge/api/models_mcp_connections.py | 97 +- server/knowledge/api/models_mcp_reads.py | 33 + server/knowledge/api/models_mcp_sources.py | 6 +- .../knowledge/api/models_private_sources.py | 29 + server/knowledge/api/models_source_push.py | 71 - server/knowledge/api/models_sources.py | 261 +- server/knowledge/api/ops_connections.py | 34 - server/knowledge/api/ops_mcp_connections.py | 19 + server/knowledge/api/ops_mcp_reads.py | 17 + server/knowledge/api/ops_source_push.py | 50 - server/knowledge/api/ops_sources.py | 38 +- server/knowledge/app/connected_accounts.py | 685 +---- server/knowledge/app/connected_restore.py | 37 +- server/knowledge/app/connected_sources.py | 246 -- server/knowledge/app/connection_routes.py | 124 - server/knowledge/app/connections.py | 50 - server/knowledge/app/live_provider_search.py | 353 --- server/knowledge/app/mcp_browse.py | 229 ++ server/knowledge/app/mcp_connections.py | 5 +- server/knowledge/app/mcp_live.py | 5 +- server/knowledge/app/mcp_profiles.py | 66 +- server/knowledge/app/mcp_source_schedule.py | 388 +++ server/knowledge/app/mcp_source_sessions.py | 44 + server/knowledge/app/mcp_source_worker.py | 94 + server/knowledge/app/source_access.py | 79 +- server/knowledge/app/source_gdrive_items.py | 238 -- server/knowledge/app/source_probes.py | 323 +-- server/knowledge/app/source_push.py | 428 +--- server/knowledge/app/source_push_routes.py | 44 - server/knowledge/app/source_sync.py | 682 +---- server/knowledge/app/source_sync_connected.py | 114 - server/knowledge/app/source_sync_linear.py | 231 -- server/knowledge/app/source_sync_mcp.py | 8 +- server/knowledge/app/source_sync_mirror.py | 365 --- server/knowledge/app/source_sync_notion.py | 582 ----- server/knowledge/app/sources.py | 627 +---- server/knowledge/domain/source_links.py | 130 - server/knowledge/domain/sources.py | 481 +--- server/knowledge/store/mcp_source_schedule.py | 112 + server/knowledge/store/sources.py | 19 +- server/knowledge/workers/source_push.py | 55 - server/main.py | 7 +- server/operations/registry.py | 6 +- server/settings/catalog.py | 104 +- server/workers/registry.py | 7 - tests/unit/snapshots/settings_defaults.json | 33 +- tests/unit/snapshots/worker_registry.json | 14 - tests/unit/test_connected_account_cleanup.py | 49 +- .../unit/test_connected_account_contracts.py | 106 +- tests/unit/test_connected_account_refresh.py | 51 - .../test_connected_account_refresh_cancel.py | 78 - tests/unit/test_connected_oauth.py | 516 ---- tests/unit/test_connected_source_authority.py | 614 +---- ...t_connected_source_drive_linear_workers.py | 343 --- .../unit/test_connected_source_operations.py | 449 +--- .../unit/test_connected_source_publication.py | 47 +- tests/unit/test_connected_source_read_plan.py | 312 +-- tests/unit/test_connected_source_repair.py | 72 - tests/unit/test_connected_source_workers.py | 254 -- tests/unit/test_document_source_contract.py | 393 +++ tests/unit/test_gdrive_push.py | 89 - tests/unit/test_knowledge_source_items.py | 772 ------ .../unit/test_knowledge_source_mirror_pass.py | 422 +--- .../unit/test_knowledge_source_recordings.py | 54 +- .../unit/test_knowledge_source_retirements.py | 4 +- tests/unit/test_knowledge_source_sync.py | 2197 ++--------------- .../test_knowledge_source_sync_diagnostics.py | 59 +- .../unit/test_knowledge_source_sync_linear.py | 583 ----- .../unit/test_knowledge_source_sync_mirror.py | 820 +----- tests/unit/test_knowledge_sources.py | 1338 +--------- tests/unit/test_live_provider_search.py | 267 -- tests/unit/test_live_source_search.py | 202 +- tests/unit/test_mcp_connection_lifecycle.py | 132 +- tests/unit/test_mcp_connections.py | 2 +- tests/unit/test_mcp_profile_api.py | 10 +- tests/unit/test_mcp_source_browse.py | 237 ++ tests/unit/test_mcp_source_live.py | 2 + tests/unit/test_mcp_source_live_read.py | 266 ++ tests/unit/test_mcp_source_profiles.py | 40 +- tests/unit/test_mcp_source_schedule.py | 402 +++ .../unit/test_mcp_source_schema_quarantine.py | 94 + tests/unit/test_mcp_source_sync.py | 6 + tests/unit/test_mcp_source_worker.py | 107 + tests/unit/test_native_source_retirement.py | 168 ++ tests/unit/test_schema_baseline.py | 1 + tests/unit/test_source_push.py | 563 +---- tests/unit/test_source_push_proofs.py | 73 - tests/unit/test_source_push_routes.py | 113 - tests/unit/test_source_push_worker.py | 100 - 101 files changed, 4506 insertions(+), 17769 deletions(-) create mode 100644 docs/architecture/mcp-document-sources.md create mode 100644 schemas/migrations/117_mcp_source_admission.sql delete mode 100644 server/clients/connected_oauth.py delete mode 100644 server/clients/gdrive.py delete mode 100644 server/clients/gdrive_push.py delete mode 100644 server/clients/linear.py delete mode 100644 server/clients/notion.py delete mode 100644 server/knowledge/api/models_connections.py create mode 100644 server/knowledge/api/models_mcp_reads.py create mode 100644 server/knowledge/api/models_private_sources.py delete mode 100644 server/knowledge/api/models_source_push.py delete mode 100644 server/knowledge/api/ops_connections.py create mode 100644 server/knowledge/api/ops_mcp_reads.py delete mode 100644 server/knowledge/api/ops_source_push.py delete mode 100644 server/knowledge/app/connected_sources.py delete mode 100644 server/knowledge/app/connection_routes.py delete mode 100644 server/knowledge/app/connections.py delete mode 100644 server/knowledge/app/live_provider_search.py create mode 100644 server/knowledge/app/mcp_browse.py create mode 100644 server/knowledge/app/mcp_source_schedule.py create mode 100644 server/knowledge/app/mcp_source_sessions.py create mode 100644 server/knowledge/app/mcp_source_worker.py delete mode 100644 server/knowledge/app/source_gdrive_items.py delete mode 100644 server/knowledge/app/source_push_routes.py delete mode 100644 server/knowledge/app/source_sync_connected.py delete mode 100644 server/knowledge/app/source_sync_linear.py delete mode 100644 server/knowledge/app/source_sync_mirror.py delete mode 100644 server/knowledge/app/source_sync_notion.py delete mode 100644 server/knowledge/domain/source_links.py create mode 100644 server/knowledge/store/mcp_source_schedule.py delete mode 100644 server/knowledge/workers/source_push.py delete mode 100644 tests/unit/test_connected_account_refresh.py delete mode 100644 tests/unit/test_connected_account_refresh_cancel.py delete mode 100644 tests/unit/test_connected_oauth.py delete mode 100644 tests/unit/test_connected_source_drive_linear_workers.py delete mode 100644 tests/unit/test_connected_source_repair.py delete mode 100644 tests/unit/test_connected_source_workers.py create mode 100644 tests/unit/test_document_source_contract.py delete mode 100644 tests/unit/test_gdrive_push.py delete mode 100644 tests/unit/test_knowledge_source_items.py delete mode 100644 tests/unit/test_knowledge_source_sync_linear.py delete mode 100644 tests/unit/test_live_provider_search.py create mode 100644 tests/unit/test_mcp_source_browse.py create mode 100644 tests/unit/test_mcp_source_live_read.py create mode 100644 tests/unit/test_mcp_source_schedule.py create mode 100644 tests/unit/test_mcp_source_schema_quarantine.py create mode 100644 tests/unit/test_native_source_retirement.py delete mode 100644 tests/unit/test_source_push_proofs.py delete mode 100644 tests/unit/test_source_push_routes.py delete mode 100644 tests/unit/test_source_push_worker.py diff --git a/docs/architecture/mcp-document-sources.md b/docs/architecture/mcp-document-sources.md new file mode 100644 index 0000000000..2977e9bf2c --- /dev/null +++ b/docs/architecture/mcp-document-sources.md @@ -0,0 +1,219 @@ +# MCP document sources + +Needs authentication and `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED=true`; enrollment +also needs `LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED=true`. Loom reads explicitly +selected external resources through one outbound MCP client. +An operator approves a remote server and any tool mappings. A user connects their +own account, chooses content and mode, chooses an ordinary destination collection, +and previews effective access before saving a registration. Configuration supplies +service differences; tool descriptions and models do not decide permissions. + +## Transport and operation approval + +The client uses the official MCP SDK over remote HTTPS Streamable HTTP. Qualified +profiles support anonymous access or a preissued bearer bound to the exact approved +origin and audience. Loom credentials never authenticate to the remote server. +OAuth enrollment and refresh, local commands or stdio, legacy SSE, binary resources +and unstructured tool-result inference are outside this contract. Protocol support +does not establish that a particular service exposes readable content. + +The operator profile fixes the endpoint, allowed organizations, authentication +profile, approved operation names, JSON schemas, fixed arguments, resource identity +fields and request/result/page/byte/time bounds. Its digest covers configuration +and publication policy. Enrollment exposes the approved ASCII HTTPS origin and +the limits of remote identity verification. A changed approval requires a new +binding. Caller IDs, returned content, tool hints and model arguments cannot add an +endpoint, tool, account, tenant or namespace. + +Standard `resources/list` and `resources/read` work when advertised and supported. +A server exposing search or reads only through tools needs validated declarative +mappings. A mapping names an approved operation and exact input/output fields; +it does not infer semantics from descriptions or `readOnlyHint`. Action-only +servers can connect for inspection but cannot supply document reads without an +approved read capability. No native connector or provider-specific OAuth path +backs a failed MCP operation. + +## Identity and storage authority + +A connection belongs to the authenticated canonical owner in one organization. +A random request UUID reconciles a connect attempt to that owner's opaque slot. +Its sealed envelope binds organization, owner, slot, generation, profile digest, +endpoint and token audience. Current account standing, grants, revocation fences, +operator approval and fleet readiness are checked on use. The remote identity is +not presented as verified merely because a bearer or server title exists. + +A registration has an immutable source UUID, account generation, destination and +reader policy. Each selected resource is an exact UTF-8 identity, without URL +normalization, recursive expansion or guessed aliases. Its local citation uses +the existing source-copy URI with a SHA256 digest of those exact bytes and the +source UUID. This address is stable within the registration, grants no access and +is never an outbound fetch target or an asserted upstream citation. Reconfiguration +allocates a new registration rather than reusing another account's history. + +Connections use existing connected-account storage, leases, fences and owner +lifecycle. Registrations use `knowledge_sources`; their versioned raw configuration +and selection are opaque to builds that do not support the contract. Imports use +the existing knowledge document, chunk, original, revision, accounting, indexing +and erasure paths. The existing storage-authority choice applies to each path; +there is no separate MCP document store, agent executor or process-local authority. +Identity tuples, server-derived actors and source classes follow ordinary writes. + +## Modes and selected scope + +| Mode | Remote activity | Persistent content | +| --- | --- | --- | +| Live | Explicit bounded lookup or read, with final authority revalidation | No document import or automatic memory save | +| Snapshot | Read the explicitly selected identities once | Protected knowledge copies, originals and normal revisions | +| Selected refresh | Re-read that same selected set under bounded worker scheduling | Protected copies and current successful-read proof | + +Browsing returns one bounded metadata window. It reports truncation and capability +limits; it does not claim a complete catalog. A user may supply exact IDs when a +server cannot enumerate. Search results are intersected with the saved selection +and are read before content is returned. Direct live reads require one exact saved +identity. Neither path silently expands the selection or imports content. + +This contract has no continuous complete-enumeration, upstream ACL synchronization +or deletion guarantee. Partial pages, notifications, errors and absence from a +window never prove deletion. A source lacking revision evidence still permits +explicit re-read; Loom computes content identity and retains normal provenance. +An unchanged owned document receives a metadata/access refresh without rewriting +its original, chunks or content revision. + +Stored-copy work requires the ordinary source worker, +`LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED=true`. Saving a registration while that worker +is disabled does not import its content. + +Every imported document carries the current source-scope digest and server read +time. Scope changes increment a monotonic revision, including selection ABA. +A previous successful read cannot authorize a different selection revision. An +individual denied, oversized or unavailable resource loses its own read proof; +its bytes remain. An observed approved-mapping schema failure stops the exact +current connection under its account lease, invalidating reads from all sources +on that binding. The sealed credential, generation and retained content are not +erased. Restoring an operator schema does not reactivate that connection; the owner +must approve a new binding. + +## Who may read + +A destination grant alone does not publish private source material. Both reader +policies use the protected mirror and current source/connection checks. + +- Owner-only copies require the current canonical owner and destination access. + Missing upstream ACL evidence never grants team access. Unbound machine readers + cannot borrow an owner's connection. +- A collection copy requires operator publication approval, namespace administrator + authority, explicit confirmation of a server-issued exact-selection consent, + and current destination-reader authority. It discloses that access is an + intentional local publication, without claiming upstream ACL equivalence. + +The audience is immutable for a source UUID. Publishing to another audience needs +a new registration and read; private history is not republished. Ordinary collection +grant inheritance and the automatic personal-namespace restriction remain in force. +Setup can select or create an ordinary private or team collection without turning +a personal source credential into a shared credential. + +The existing successful-read freshness bound applies to every document proof. +Snapshot access therefore expires without an explicit refresh; retaining bytes does +not preserve access forever. Pause and disconnect stop use while retaining stored +content. Read, original, history, search, export, diagnostics, caches and derived +memory publication remain subject to the existing protected-result and publication +checks. A client must establish the supported durable session-protection protocol +before private results are returned. Merely adding a capability header does not +install its required automatic-capture barriers. + +Live response content lives in request/client memory until that request or retained +contribution is released. This layer has no persistent live-result cache and does +not save a memory as a side effect. A remote host can retain requests under its own +policy; connecting does not establish a remote retention or deletion promise. Loom +uses its existing private-work diagnostic handling and configured log/trace +retention. Imported bytes, originals, revisions and account history follow existing +storage and writer-requested retention/erasure policy. Operators and clients must +account for their own response, trace and conversation retention. + +## Lifecycle and bounded work + +Connection APIs provide approved profiles, enrollment, list, inspect, discovery, +browse and disconnect. Source APIs provide preview, add, inspect, bounded list, +update, pause, resume, refresh, direct live read and remove. Inspect can reconcile +the original slot/request UUID without replaying an uncertain mutation. Clients +receive no authority beyond the authenticated API caller. + +The background lane reads bounded metadata pages before hydrating a selected +source. Fair admission caps queued headers and concurrent turns globally, per +organization and per canonical endpoint. Each task reserves its own document +credits and has an outer deadline; cancellation joins owned work. Execution still +uses the existing source/account leases and publication fences. Scheduling headers +are hints, not authority. A separate opaque cursor in the existing worker-status +store leaves the recording lane's cursor intact. Physical query row, byte and time +limits apply even when the registry is larger than one returned page. + +Source removal and owner erasure reuse existing cleanup and audit machinery. +Only an explicit writer request retires or erases content. Disconnect and observed +schema refusal stop local access without pretending to revoke an upstream token. +The account owner must revoke that credential at its issuer when required. + +## Rolling upgrades and operator cutover + +The lifecycle preparation schema adds version and slot columns without converting +existing registrations. The MCP admission migration changes no schema object or +stored data; it establishes a code floor. Admission and every current connection +validation require all live replicas to advertise that floor. An older lifecycle +build preserves opaque rows and blocks admission while it remains live. An +unreadable fleet refuses. Rolling storage remains readable by adjacent builds. + +Native document-source registrations remain retained and unavailable in the +replacement build. Upgrade does not delete their credentials, documents, originals, +uploads, history or checkpoints, invent MCP endpoints, transfer account consent, +or use retired credentials. Explicit local retirement, erasure and offline reseal +remain available through their existing ownership rules. Recording sources and +unrelated model providers, tracker and code integrations remain separate. + +The operator completes normal source qualification and the fleet rollout, configures +approved profiles, verifies supported protected clients, and performs the normal +feature cutover. Running migration or merging code alone does not activate a remote +connection. Rollback retains MCP bytes and refuses unsupported access; it does not +translate an MCP registration into a native source. Existing native credentials +require owner-led reconfiguration and fresh selection/preview/consent. + +## Qualification boundaries + +Deterministic servers exercise resource-based and mapped-tool reads through the +same official SDK engine. Functional qualification uses owned stores and synthetic +identities, real knowledge writes and protected readbacks. Scale qualification +uses a frozen synthetic registry and measures query work, bounded scheduling and +latency. In-process ASGI transport does not qualify TCP, TLS, DNS, proxy behavior, +external vendor capacity or every server marketed as MCP. No provider or model +calls are needed for these tests. Only actual exact-head hosted receipts establish +a qualification result; authored tests and protocol compatibility are not provider +certification. + +## Source entry points + +- `server/clients/mcp_source.py` owns the official SDK session and bounded protocol + calls. `server/knowledge/app/mcp_profiles.py` validates trusted configuration. +- `server/knowledge/app/mcp_connections.py` binds owners, sealed credentials, + current approval and the fleet floor. `mcp_source_sessions.py` persists observed + schema refusal against the exact current binding. +- `server/knowledge/app/mcp_sources.py` and `mcp_source_controls.py` own preview, + selected-source mutation and reconciliation. `mcp_browse.py` and `mcp_live.py` + retain protected retrieval proofs. +- `server/knowledge/app/source_sync_mcp.py` reads selected content through the + shared knowledge write path. `mcp_source_worker.py` joins the bounded scheduler + to `source_sync.py` and its existing leases and state. +- `server/knowledge/app/source_access.py` checks current per-document proof; + the existing publication machinery checks retained contributions at the tail. + +## Invariants + +A connection is never widened by a source selection or model argument. A catalog +header and a citation grant no authority. Live retrieval saves no document or +memory. Retained bytes are not a current access grant. A shared destination cannot +convert private source material into a team publication. No failed or partial +listing is deletion evidence. Schema refusal, pause and disconnect retain data; +writer-requested erasure remains the only erasure authority. + +Copies already published into ordinary namespaces retain their existing namespace +access and erasure rules. Retiring an executable registration does not retroactively +change that publication or silently delete its documents. Unsupported protected +mirror registrations remain unreadable until an explicitly supported authority +contract exists. diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 8c59bad39c..d59f40e9f7 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -988,18 +988,6 @@ Knowledge documents and conversations: chunking, search floor, thread titles. | `LOOM_DOCUMENT_EXTRACTOR_TOKENS_JSON` | `str` | *(unset)* | | JSON {base URL: bearer token}: each extractor service's own token, so none holds another's. Each URL must be one an extractor URL setting names. | | `LOOM_DOCUMENT_EXTRACTOR_TIMEOUT_S` | `float` | `180.0` | | Seconds one call to an extractor may take as a whole: reading its capabilities, or sending the original and reading its artifact. | | `LOOM_DOCUMENT_EXTRACTOR_MAX_ARTIFACT_BYTES` | `int` | `67108864` | | Bytes of an extractor's response the server reads; a larger artifact is refused. | - -### Document sources - -| Variable | Type | Default | Live | Meaning | -| --- | --- | --- | --- | --- | -| `LOOM_CONNECT_GDRIVE_CLIENT_ID` | `str` | `''` | | OAuth client id for personal Drive connections; empty disables the provider. | -| `LOOM_CONNECT_GDRIVE_CLIENT_SECRET` | `str` | *(unset)* | | Secret of that Drive OAuth registration; kept outside source rows. | -| `LOOM_CONNECT_NOTION_CLIENT_ID` | `str` | `''` | | Public-integration client id for personal page-store connections; empty disables it. | -| `LOOM_CONNECT_NOTION_CLIENT_SECRET` | `str` | *(unset)* | | Secret of that page-store registration; kept outside source rows. | -| `LOOM_CONNECT_LINEAR_CLIENT_ID` | `str` | `''` | | OAuth client id for personal project-tracker connections; empty disables it. | -| `LOOM_CONNECT_LINEAR_CLIENT_SECRET` | `str` | *(unset)* | | Secret of that project-tracker registration; kept outside source rows. | -| `LOOM_CONNECT_NOTION_READ_CONTENT_ONLY` | `bool` | `False` | | The operator has restricted the public integration to read-content capability. Its token response cannot prove this registration setting; false disables it. | | `LOOM_KNOWLEDGE_LIVE_SEARCH_TIMEOUT_S` | `float` | `5.0` | | Seconds for the whole optional live-search leg, including final membership checks. At most five; provider credential deadlines may shorten it further. | | `LOOM_KNOWLEDGE_LIVE_SEARCH_MAX_SOURCES` | `int` | `3` | | Connected registrations searched per live-search request, from one to three. | | `LOOM_KNOWLEDGE_LIVE_SEARCH_MAX_HITS` | `int` | `10` | | Live hits across all registrations, and the per-provider page bound, from one to ten. | @@ -1010,6 +998,26 @@ Knowledge documents and conversations: chunking, search floor, thread titles. | `LOOM_KNOWLEDGE_CONNECTED_REVOKE_TIMEOUT_S` | `float` | `5.0` | | Seconds for best-effort provider revocation after every local stop has committed. | | `LOOM_KNOWLEDGE_CONNECTED_LEASE_TTL_S` | `float` | `60.0` | | Seconds the renewed account-generation lease lives. Source leases follow it; provider requests hold neither. | | `LOOM_KNOWLEDGE_CONNECTED_LEASE_WAIT_S` | `float` | `5.0` | | Seconds a connection change waits for another holder's account-generation lease. | +| `LOOM_KNOWLEDGE_MCP_ENVELOPE_MAX_BYTES` | `int` | `32768` | | Maximum sealed MCP plaintext bytes admitted by this deployment, up to the v1 wire ceiling. | +| `LOOM_KNOWLEDGE_MCP_SELECTED_RESOURCES_MAX` | `int` | `1000` | | Maximum explicitly selected MCP identities per source, without implicit recursion. | +| `LOOM_KNOWLEDGE_MCP_RESOURCE_ID_MAX_BYTES` | `int` | `2048` | | Maximum UTF-8 bytes in one selected MCP identity, up to the v1 wire ceiling. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_CATALOG_MAX_BYTES` | `int` | `8388608` | | Maximum trusted profile-catalog bytes admitted, up to the contract ceiling. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_CATALOG_MAX_PROFILES` | `int` | `10000` | | Maximum distinct approved profiles in one trusted catalog. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_PROFILE_MAX_BYTES` | `int` | `65536` | | Maximum canonical bytes in one approved profile. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEMA_MAX_BYTES` | `int` | `16384` | | Maximum canonical schema or schema-string bytes in one mapping. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_PROFILE_MAX_NODES` | `int` | `4096` | | Maximum JSON nodes visited while validating one approved profile. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_PROFILE_MAX_DEPTH` | `int` | `16` | | Maximum JSON nesting depth in one approved profile. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_PAGE_SIZE` | `int` | `100` | | MCP scheduling headers returned per bounded metadata query. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_SCAN_PAGES` | `int` | `16` | | Maximum metadata pages scanned in one MCP scheduling pass. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_READY` | `int` | `256` | | Maximum eligible source headers waiting for an execution slot. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_GLOBAL` | `int` | `16` | | Concurrent MCP source turns across this worker pass. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_PER_ORG` | `int` | `4` | | Concurrent MCP source turns for one organization. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_PER_ENDPOINT` | `int` | `2` | | Concurrent turns sharing one canonical approved MCP endpoint. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_DOCUMENTS` | `int` | `8` | | Document credits reserved before admitting one MCP source turn. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_SOURCE_SECONDS` | `float` | `20.0` | | Outer deadline in seconds for one MCP source turn, including cleanup. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_QUERY_ROWS` | `int` | `1000000` | | Physical rows one MCP metadata query may read before refusing. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_QUERY_BYTES` | `int` | `67108864` | | Physical bytes one MCP metadata query may read before refusing. | +| `LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_QUERY_SECONDS` | `float` | `5.0` | | Maximum execution seconds for one MCP metadata or progress query. | | `LOOM_KNOWLEDGE_CONNECTED_REGISTRY_SCAN_LIMIT` | `int` | `4096` | | Maximum complete owner scan; exceeding it refuses instead of stopping a subset. | | `LOOM_KNOWLEDGE_CONNECTED_REGISTRY_PAGE_SIZE` | `int` | `256` | | Registrations per page during root-secret resealing. | | `LOOM_KNOWLEDGE_CONNECTED_OAUTH_TIMEOUT_S` | `float` | `30.0` | | Seconds one connected-account OAuth request may take, including its response. The caller's remaining deadline can shorten this bound. | @@ -1025,12 +1033,6 @@ Knowledge documents and conversations: chunking, search floor, thread titles. | `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_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. | -| `LOOM_KNOWLEDGE_SOURCE_PUSH_INTERVAL_SECONDS` | `int` | `300` | | Seconds between bounded channel-renewal pages; channels renew a day before expiry. | -| `LOOM_KNOWLEDGE_SOURCE_PUSH_PROVIDER_TIMEOUT_S` | `float` | `40.0` | | Seconds one push setup or Drive renewal may spend on provider work, before cleanup. | -| `LOOM_KNOWLEDGE_SOURCE_PUSH_STOP_TIMEOUT_S` | `float` | `2.0` | | Seconds allowed to stop one superseded or unpublished Drive channel. | -| `LOOM_KNOWLEDGE_SOURCE_PUSH_CLEANUP_TIMEOUT_S` | `float` | `5.0` | | Seconds allowed for the whole Drive channel cleanup; at least the per-channel wait. | -| `LOOM_KNOWLEDGE_SOURCE_PUSH_MAX_PASS_SECONDS` | `float` | `120.0` | | Seconds a renewal pass may run; reserve one provider attempt and two cleanup windows. | | `LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS` | `int` | `900` | | Seconds between sync passes while there are sources. | | `LOOM_KNOWLEDGE_SOURCE_SYNC_IDLE_INTERVAL_SECONDS` | `int` | `1800` | | Seconds between passes that found no source to sync; one idle sleep plus one pass stays under three intervals, so the worker never reads as stalled. | | `LOOM_KNOWLEDGE_SOURCE_SYNC_MAX_PASS_SECONDS` | `int` | `600` | | 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. | diff --git a/loom.example.yaml b/loom.example.yaml index b76de84e4d..13701641eb 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -2903,24 +2903,6 @@ settings: # [restart] # document_extractor_max_artifact_bytes: 67108864 - # --- document sources --- - - # OAuth client id for personal Drive connections; empty disables the provider. - # [restart] - # connect_gdrive_client_id: "" - - # Public-integration client id for personal page-store connections; empty disables it. - # [restart] - # connect_notion_client_id: "" - - # OAuth client id for personal project-tracker connections; empty disables it. - # [restart] - # connect_linear_client_id: "" - - # The operator has restricted the public integration to read-content capability. Its - # token response cannot prove this registration setting; false disables it. [restart] - # connect_notion_read_content_only: false - # Seconds for the whole optional live-search leg, including final membership checks. # At most five; provider credential deadlines may shorten it further. [restart] # knowledge_live_search_timeout_s: 5.0 @@ -2961,6 +2943,70 @@ settings: # [restart] # knowledge_connected_lease_wait_s: 5.0 + # Maximum sealed MCP plaintext bytes admitted by this deployment, up to the v1 wire + # ceiling. [restart] + # knowledge_mcp_envelope_max_bytes: 32768 + + # Maximum explicitly selected MCP identities per source, without implicit recursion. + # [restart] + # knowledge_mcp_selected_resources_max: 1000 + + # Maximum UTF-8 bytes in one selected MCP identity, up to the v1 wire ceiling. + # [restart] + # knowledge_mcp_resource_id_max_bytes: 2048 + + # Maximum trusted profile-catalog bytes admitted, up to the contract ceiling. + # [restart] + # knowledge_source_mcp_catalog_max_bytes: 8388608 + + # Maximum distinct approved profiles in one trusted catalog. [restart] + # knowledge_source_mcp_catalog_max_profiles: 10000 + + # Maximum canonical bytes in one approved profile. [restart] + # knowledge_source_mcp_profile_max_bytes: 65536 + + # Maximum canonical schema or schema-string bytes in one mapping. [restart] + # knowledge_source_mcp_schema_max_bytes: 16384 + + # Maximum JSON nodes visited while validating one approved profile. [restart] + # knowledge_source_mcp_profile_max_nodes: 4096 + + # Maximum JSON nesting depth in one approved profile. [restart] + # knowledge_source_mcp_profile_max_depth: 16 + + # MCP scheduling headers returned per bounded metadata query. [restart] + # knowledge_source_mcp_schedule_page_size: 100 + + # Maximum metadata pages scanned in one MCP scheduling pass. [restart] + # knowledge_source_mcp_schedule_scan_pages: 16 + + # Maximum eligible source headers waiting for an execution slot. [restart] + # knowledge_source_mcp_schedule_ready: 256 + + # Concurrent MCP source turns across this worker pass. [restart] + # knowledge_source_mcp_schedule_global: 16 + + # Concurrent MCP source turns for one organization. [restart] + # knowledge_source_mcp_schedule_per_org: 4 + + # Concurrent turns sharing one canonical approved MCP endpoint. [restart] + # knowledge_source_mcp_schedule_per_endpoint: 2 + + # Document credits reserved before admitting one MCP source turn. [restart] + # knowledge_source_mcp_schedule_documents: 8 + + # Outer deadline in seconds for one MCP source turn, including cleanup. [restart] + # knowledge_source_mcp_schedule_source_seconds: 20.0 + + # Physical rows one MCP metadata query may read before refusing. [restart] + # knowledge_source_mcp_schedule_query_rows: 1000000 + + # Physical bytes one MCP metadata query may read before refusing. [restart] + # knowledge_source_mcp_schedule_query_bytes: 67108864 + + # Maximum execution seconds for one MCP metadata or progress query. [restart] + # knowledge_source_mcp_schedule_query_seconds: 5.0 + # Maximum complete owner scan; exceeding it refuses instead of stopping a subset. # [restart] # knowledge_connected_registry_scan_limit: 4096 @@ -3023,29 +3069,6 @@ settings: # larger list refuses publication rather than granting from a partial page. [restart] # knowledge_source_acl_max_entries: 10000 - # Enable optional source push setup, callbacks and Drive renewal; false keeps polling - # only. [restart] - # knowledge_source_push_enabled: false - - # Seconds between bounded channel-renewal pages; channels renew a day before expiry. - # [restart] - # knowledge_source_push_interval_seconds: 300 - - # Seconds one push setup or Drive renewal may spend on provider work, before cleanup. - # [restart] - # knowledge_source_push_provider_timeout_s: 40.0 - - # Seconds allowed to stop one superseded or unpublished Drive channel. [restart] - # knowledge_source_push_stop_timeout_s: 2.0 - - # Seconds allowed for the whole Drive channel cleanup; at least the per-channel wait. - # [restart] - # knowledge_source_push_cleanup_timeout_s: 5.0 - - # Seconds a renewal pass may run; reserve one provider attempt and two cleanup - # windows. [restart] - # knowledge_source_push_max_pass_seconds: 120.0 - # Seconds between sync passes while there are sources. [restart] # knowledge_source_sync_interval_seconds: 900 diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index d13b001524..50e51edd25 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -2376,26 +2376,6 @@ "type": "number", "description": "memory.set flags a write `conflicted` when an active peer in the same (org, namespace, memory_type) sits at cosine ≥ this. Tuned for text-embedding-3-*; 1.0 disables. Per-namespace override: loom.namespaces.conflict_threshold." }, - "connect_gdrive_client_id": { - "default": "", - "type": "string", - "description": "OAuth client id for personal Drive connections; empty disables the provider." - }, - "connect_linear_client_id": { - "default": "", - "type": "string", - "description": "OAuth client id for personal project-tracker connections; empty disables it." - }, - "connect_notion_client_id": { - "default": "", - "type": "string", - "description": "Public-integration client id for personal page-store connections; empty disables it." - }, - "connect_notion_read_content_only": { - "default": false, - "type": "boolean", - "description": "The operator has restricted the public integration to read-content capability. Its token response cannot prove this registration setting; false disables it." - }, "consolidation_merge_concurrency": { "default": 4, "type": "integer", @@ -3342,6 +3322,27 @@ "type": "integer", "description": "Active MCP connection slots one canonical person may hold per organization." }, + "knowledge_mcp_envelope_max_bytes": { + "default": 32768, + "maximum": 32768, + "minimum": 1024, + "type": "integer", + "description": "Maximum sealed MCP plaintext bytes admitted by this deployment, up to the v1 wire ceiling." + }, + "knowledge_mcp_resource_id_max_bytes": { + "default": 2048, + "maximum": 2048, + "minimum": 1, + "type": "integer", + "description": "Maximum UTF-8 bytes in one selected MCP identity, up to the v1 wire ceiling." + }, + "knowledge_mcp_selected_resources_max": { + "default": 1000, + "maximum": 1000, + "minimum": 1, + "type": "integer", + "description": "Maximum explicitly selected MCP identities per source, without implicit recursion." + }, "knowledge_mirrored_sources_enabled": { "default": false, "type": "boolean", @@ -3491,59 +3492,141 @@ "type": "integer", "description": "Documents one source holds: its stored ones plus the new ones a turn writes. At it a turn tries no new file, notes how many as `too_many_documents`, and still updates and retires. At most 200,000: each read of the stored copies grows with its square." }, + "knowledge_source_mcp_catalog_max_bytes": { + "default": 8388608, + "maximum": 8388608, + "minimum": 1024, + "type": "integer", + "description": "Maximum trusted profile-catalog bytes admitted, up to the contract ceiling." + }, + "knowledge_source_mcp_catalog_max_profiles": { + "default": 10000, + "maximum": 10000, + "minimum": 1, + "type": "integer", + "description": "Maximum distinct approved profiles in one trusted catalog." + }, + "knowledge_source_mcp_profile_max_bytes": { + "default": 65536, + "maximum": 65536, + "minimum": 1024, + "type": "integer", + "description": "Maximum canonical bytes in one approved profile." + }, + "knowledge_source_mcp_profile_max_depth": { + "default": 16, + "maximum": 16, + "minimum": 1, + "type": "integer", + "description": "Maximum JSON nesting depth in one approved profile." + }, + "knowledge_source_mcp_profile_max_nodes": { + "default": 4096, + "maximum": 4096, + "minimum": 16, + "type": "integer", + "description": "Maximum JSON nodes visited while validating one approved profile." + }, "knowledge_source_mcp_profiles_json": { "default": "", "maxLength": 8388608, "type": "string", "description": "Operator-approved MCP read profiles as version-1 JSON, at most 8 MiB UTF-8; empty approves none, and profile metadata grants no connection or publication access." }, - "knowledge_source_mirror_documents_per_pass": { - "default": 40, + "knowledge_source_mcp_schedule_documents": { + "default": 8, + "maximum": 1000, "minimum": 1, "type": "integer", - "description": "Documents one pass fetches, writes and retires for the mirrored sources, apart from the namespace sources' per-pass bound, so a mirror's size never takes their share." + "description": "Document credits reserved before admitting one MCP source turn." }, - "knowledge_source_probe_timeout_s": { - "default": 20.0, - "exclusiveMinimum": 0, - "maximum": 25.0, - "type": "number", - "description": "Seconds a document source's probe (add, update, check, rotate) or tracker short-id lookup may take in all; past it add, update and rotate answer SOURCE_UNREACHABLE and check answers reachable: false." + "knowledge_source_mcp_schedule_global": { + "default": 16, + "maximum": 256, + "minimum": 1, + "type": "integer", + "description": "Concurrent MCP source turns across this worker pass." + }, + "knowledge_source_mcp_schedule_page_size": { + "default": 100, + "maximum": 256, + "minimum": 1, + "type": "integer", + "description": "MCP scheduling headers returned per bounded metadata query." + }, + "knowledge_source_mcp_schedule_per_endpoint": { + "default": 2, + "maximum": 256, + "minimum": 1, + "type": "integer", + "description": "Concurrent turns sharing one canonical approved MCP endpoint." }, - "knowledge_source_push_cleanup_timeout_s": { + "knowledge_source_mcp_schedule_per_org": { + "default": 4, + "maximum": 256, + "minimum": 1, + "type": "integer", + "description": "Concurrent MCP source turns for one organization." + }, + "knowledge_source_mcp_schedule_query_bytes": { + "default": 67108864, + "minimum": 1, + "type": "integer", + "description": "Physical bytes one MCP metadata query may read before refusing." + }, + "knowledge_source_mcp_schedule_query_rows": { + "default": 1000000, + "minimum": 1, + "type": "integer", + "description": "Physical rows one MCP metadata query may read before refusing." + }, + "knowledge_source_mcp_schedule_query_seconds": { "default": 5.0, "exclusiveMinimum": 0, + "maximum": 60, "type": "number", - "description": "Seconds allowed for the whole Drive channel cleanup; at least the per-channel wait." + "description": "Maximum execution seconds for one MCP metadata or progress query." }, - "knowledge_source_push_enabled": { - "default": false, - "type": "boolean", - "description": "Enable optional source push setup, callbacks and Drive renewal; false keeps polling only." + "knowledge_source_mcp_schedule_ready": { + "default": 256, + "maximum": 4096, + "minimum": 1, + "type": "integer", + "description": "Maximum eligible source headers waiting for an execution slot." }, - "knowledge_source_push_interval_seconds": { - "default": 300, - "minimum": 60, + "knowledge_source_mcp_schedule_scan_pages": { + "default": 16, + "maximum": 1000, + "minimum": 1, "type": "integer", - "description": "Seconds between bounded channel-renewal pages; channels renew a day before expiry." + "description": "Maximum metadata pages scanned in one MCP scheduling pass." }, - "knowledge_source_push_max_pass_seconds": { - "default": 120.0, + "knowledge_source_mcp_schedule_source_seconds": { + "default": 20.0, "exclusiveMinimum": 0, + "maximum": 300, "type": "number", - "description": "Seconds a renewal pass may run; reserve one provider attempt and two cleanup windows." + "description": "Outer deadline in seconds for one MCP source turn, including cleanup." }, - "knowledge_source_push_provider_timeout_s": { - "default": 40.0, - "exclusiveMinimum": 0, - "type": "number", - "description": "Seconds one push setup or Drive renewal may spend on provider work, before cleanup." + "knowledge_source_mcp_schema_max_bytes": { + "default": 16384, + "maximum": 16384, + "minimum": 128, + "type": "integer", + "description": "Maximum canonical schema or schema-string bytes in one mapping." }, - "knowledge_source_push_stop_timeout_s": { - "default": 2.0, + "knowledge_source_mirror_documents_per_pass": { + "default": 40, + "minimum": 1, + "type": "integer", + "description": "Documents one pass fetches, writes and retires for the mirrored sources, apart from the namespace sources' per-pass bound, so a mirror's size never takes their share." + }, + "knowledge_source_probe_timeout_s": { + "default": 20.0, "exclusiveMinimum": 0, + "maximum": 25.0, "type": "number", - "description": "Seconds allowed to stop one superseded or unpublished Drive channel." + "description": "Seconds a document source's probe (add, update, check, rotate) or tracker short-id lookup may take in all; past it add, update and rotate answer SOURCE_UNREACHABLE and check answers reachable: false." }, "knowledge_source_retire_documents_per_pass": { "default": 40, diff --git a/schemas/migrations/117_mcp_source_admission.sql b/schemas/migrations/117_mcp_source_admission.sql new file mode 100644 index 0000000000..2bec00ed53 --- /dev/null +++ b/schemas/migrations/117_mcp_source_admission.sql @@ -0,0 +1,4 @@ +-- Code admission barrier: every live replica must understand selected MCP reads +-- and their per-document proof before any connection or source is admitted. +-- This migration changes no stored content or schema object. +SELECT 1; diff --git a/scripts/gates/mcp_source_lifecycle.py b/scripts/gates/mcp_source_lifecycle.py index 56efcbdc78..e87f489096 100644 --- a/scripts/gates/mcp_source_lifecycle.py +++ b/scripts/gates/mcp_source_lifecycle.py @@ -199,8 +199,8 @@ def prepare(self) -> None: from server.core.secrets_at_rest import seal from server.knowledge.app import connected_accounts as accounts - from server.knowledge.domain.connected_accounts import ConnectedAccount from server.knowledge.app.mcp_contracts import encode_envelope + from server.knowledge.domain.connected_accounts import ConnectedAccount from server.knowledge.domain.mcp_sources import ConnectionEnvelope a, b = self.orgs @@ -579,18 +579,17 @@ async def run_restore_phases( result: dict[str, Any], ) -> None: from server.erasure.app.connected_accounts import require_restore_erased - from server.knowledge.app import connected_accounts as accounts from server.knowledge.app import connected_restore as restore from server.settings import settings client_attempts: list[None] = [] - def refuse_native_client(*args: Any, **kwargs: Any) -> Any: - # Fail-only sentinel: no client or provider result can be supplied by this seam. + async def refuse_native_http(*args: Any, **kwargs: Any) -> Any: + # Any attempted HTTP execution fails before a provider request can leave. client_attempts.append(None) - raise AssertionError("MCP_LIFECYCLE_NATIVE_CLIENT_FORBIDDEN") + raise AssertionError("MCP_LIFECYCLE_NATIVE_HTTP_FORBIDDEN") - with patch.object(accounts, "client", new=refuse_native_client): + with patch("httpx.AsyncClient.send", new=refuse_native_http): result["stage"] = "dry_run" await restore.restore_all(apply=False, ch=ch) require(await snapshot(ch) == before) diff --git a/server/clients/connected_oauth.py b/server/clients/connected_oauth.py deleted file mode 100644 index d363a5b45f..0000000000 --- a/server/clients/connected_oauth.py +++ /dev/null @@ -1,332 +0,0 @@ -"""Fixed-provider OAuth wire contracts for document connections. - -This boundary neither authorizes a Loom subject nor persists credentials. Its caller -owns browser state, account/source generations, credential sealing and revocation -ordering. A returned provider identity is metadata, never namespace authority. -No request retries or follows redirects, including token rotation and revocation. -""" - -from __future__ import annotations - -import asyncio -import base64 -import hashlib -import json -import math -import re -import time -from dataclasses import dataclass, field -from typing import Any, Literal -from urllib.parse import urlencode, urlsplit - -import httpx - -from server.clients._http import get_client -from server.clients._vendor import read_capped -from server.clients.notion import API_VERSION -from server.settings import settings - -Kind = Literal["gdrive", "notion", "linear"] -_now = time.monotonic -_DRIVE_SCOPE = "https://www.googleapis.com/auth/drive.readonly" -_EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email" -_SCOPES = {"gdrive": frozenset({_DRIVE_SCOPE, "openid", "email"}), "linear": frozenset({"read"})} -_AUTHORIZE = { - "gdrive": "https://accounts.google.com/o/oauth2/v2/auth", - "notion": "https://api.notion.com/v1/oauth/authorize", - "linear": "https://linear.app/oauth/authorize", -} -_TOKEN = { - "gdrive": "https://oauth2.googleapis.com/token", - "notion": "https://api.notion.com/v1/oauth/token", - "linear": "https://api.linear.app/oauth/token", -} -_REVOKE = { - "gdrive": "https://oauth2.googleapis.com/revoke", - "notion": "https://api.notion.com/v1/oauth/revoke", - "linear": "https://api.linear.app/oauth/revoke", -} - - -class OAuthError(RuntimeError): - """Fixed failure codes only; provider bodies, URLs and requests are not retained.""" - - -@dataclass(frozen=True, repr=False) -class Tokens: - access_token: str - refresh_token: str - scopes: tuple[str, ...] - expires_in: int | None - - def __repr__(self) -> str: - return "Tokens()" - - -@dataclass(frozen=True, repr=False) -class AccountGrant: - tokens: Tokens - account_id: str - display_email: str | None - workspace_id: str | None = None - - def __repr__(self) -> str: - return "AccountGrant()" - - -def _text(value: Any, *, maximum: int = 8192) -> str: - if not isinstance(value, str) or not value or len(value) > maximum: - raise OAuthError("invalid_response") - if any(ord(c) < 32 or ord(c) == 127 for c in value): - raise OAuthError("invalid_response") - return value - - -def _email(value: Any) -> str | None: - return None if value is None else _text(value, maximum=512) - - -def _credential(value: Any) -> str: - if not isinstance(value, str) or not re.fullmatch(r"[\x21-\x7e]{1,8192}", value): - raise OAuthError("invalid_response") - return value - - -def _verifier(value: str | None) -> str: - if value is None or not re.fullmatch(r"[A-Za-z0-9._~-]{43,128}", value): - raise OAuthError("invalid_pkce") - return value - - -def _scopes(kind: Kind, value: Any) -> tuple[str, ...]: - if kind == "notion": - # An opaque introspection scope cannot prove registration capabilities. - return () - if isinstance(value, str): - values = value.split() - elif isinstance(value, (tuple, list)) and all(isinstance(v, str) for v in value): - values = list(value) - else: - raise OAuthError("scope_refused") - actual = frozenset("email" if v == _EMAIL_SCOPE and kind == "gdrive" else v for v in values) - if actual != _SCOPES[kind]: - raise OAuthError("scope_refused") - return tuple(sorted(actual)) - - -@dataclass(frozen=True, repr=False) -class OAuthClient: - kind: Kind - client_id: str = field(repr=False) - client_secret: str = field(repr=False) - public_base_url: str = field(repr=False) - - def __post_init__(self) -> None: - if self.kind not in _AUTHORIZE or not self.client_id or not self.client_secret: - raise OAuthError("not_configured") - if any(c.isspace() or ord(c) < 32 for c in self.public_base_url): - raise OAuthError("invalid_public_base") - try: - url = urlsplit(self.public_base_url) - port = url.port - valid = ( - url.scheme in {"https", "http"} - and url.hostname - and not url.username - and not url.password - and not url.query - and not url.fragment - and (port is None or 0 < port <= 65535) - and (url.scheme == "https" or url.hostname in {"localhost", "127.0.0.1", "::1"}) - ) - except ValueError: - valid = False - if not valid: - raise OAuthError("invalid_public_base") - - def __repr__(self) -> str: - return "OAuthClient()" - - @property - def redirect_uri(self) -> str: - return f"{self.public_base_url.rstrip('/')}/v1/connect/{self.kind}/callback" - - def authorization_url(self, state: str, *, verifier: str | None = None) -> str: - """The caller supplies its persisted browser-bound state and S256 verifier.""" - if not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", state): - raise OAuthError("invalid_state") - params = { - "client_id": self.client_id, - "redirect_uri": self.redirect_uri, - "response_type": "code", - "state": state, - } - if self.kind == "notion": - if verifier is not None: - raise OAuthError("unsupported_pkce") - params["owner"] = "user" - else: - challenge = hashlib.sha256(_verifier(verifier).encode("ascii")).digest() - params.update( - code_challenge=base64.urlsafe_b64encode(challenge).rstrip(b"=").decode("ascii"), - code_challenge_method="S256", - scope=" ".join(sorted(_SCOPES[self.kind])), - ) - if self.kind == "gdrive": - params.update( - access_type="offline", include_granted_scopes="false", prompt="consent" - ) - else: - params["actor"] = "user" - return f"{_AUTHORIZE[self.kind]}?{urlencode(params)}" - - async def _request( - self, method: str, url: str, *, deadline: float, empty: bool = False, **kw: Any - ) -> dict[str, Any]: - remaining = deadline - _now() - if not math.isfinite(remaining) or remaining <= 0: - raise OAuthError("deadline") - remaining = min(remaining, settings.knowledge_connected_oauth_timeout_s) - try: - async with asyncio.timeout(remaining): - async with get_client().stream( - method, url, timeout=remaining, follow_redirects=False, **kw - ) as response: - if response.status_code != 200: - # Do not read provider error bodies, which can echo credentials. - raise OAuthError("provider_refused") - if empty: - return {} - raw = await read_capped( - response, settings.knowledge_connected_oauth_response_max_bytes - ) - except (httpx.RequestError, TimeoutError): - raise OAuthError("unavailable") from None - if raw is None: - raise OAuthError("response_too_large") - try: - answer = json.loads(raw) - except (ValueError, RecursionError): - raise OAuthError("invalid_response") from None - if not isinstance(answer, dict) or answer.get("error") or answer.get("errors"): - raise OAuthError("invalid_response") - return answer - - def _token_request(self, fields: dict[str, str]) -> dict[str, Any]: - if self.kind == "notion": - return { - "json": fields, - "auth": httpx.BasicAuth(self.client_id, self.client_secret), - "headers": {"Notion-Version": API_VERSION}, - } - return { - "data": {**fields, "client_id": self.client_id, "client_secret": self.client_secret} - } - - def _tokens( - self, - answer: dict[str, Any], - *, - previous_refresh: str | None = None, - previous_scopes: tuple[str, ...] | None = None, - ) -> Tokens: - access = _credential(answer.get("access_token")) - token_type = answer.get("token_type") - if not (token_type is None and self.kind == "notion") and ( - not isinstance(token_type, str) or token_type.lower() != "bearer" - ): - raise OAuthError("invalid_response") - refresh = answer.get("refresh_token") - if self.kind == "gdrive" and refresh is None: - refresh = previous_refresh - refresh = _credential(refresh) - scopes = _scopes(self.kind, answer.get("scope", previous_scopes)) - expiry = answer.get("expires_in") - if not (expiry is None and self.kind == "notion") and ( - type(expiry) is not int or expiry <= 0 - ): - raise OAuthError("invalid_response") - return Tokens(access, refresh, scopes, expiry) - - async def exchange( - self, code: str, *, verifier: str | None = None, deadline: float - ) -> AccountGrant: - """Exchange once, then resolve provider identity under the same deadline.""" - fields = { - "grant_type": "authorization_code", - "code": _text(code), - "redirect_uri": self.redirect_uri, - } - if self.kind != "notion": - fields["code_verifier"] = _verifier(verifier) - elif verifier is not None: - raise OAuthError("unsupported_pkce") - answer = await self._request( - "POST", _TOKEN[self.kind], deadline=deadline, **self._token_request(fields) - ) - tokens = self._tokens(answer) - if self.kind == "notion": - owner = answer.get("owner") - user = ( - owner.get("user") - if isinstance(owner, dict) and owner.get("type") == "user" - else None - ) - if not isinstance(user, dict): - raise OAuthError("invalid_response") - person = user.get("person") - email = person.get("email") if isinstance(person, dict) else None - return AccountGrant( - tokens, - _text(user.get("id"), maximum=1024), - _email(email), - _text(answer.get("workspace_id"), maximum=1024), - ) - headers = {"Authorization": f"Bearer {tokens.access_token}"} - if self.kind == "gdrive": - user = await self._request( - "GET", - "https://openidconnect.googleapis.com/v1/userinfo", - deadline=deadline, - headers=headers, - ) - return AccountGrant( - tokens, _text(user.get("sub"), maximum=1024), _email(user.get("email")) - ) - identity = await self._request( - "POST", - "https://api.linear.app/graphql", - deadline=deadline, - headers=headers, - json={"query": "query { viewer { id name email } }"}, - ) - data = identity.get("data") - user = data.get("viewer") if isinstance(data, dict) else None - if not isinstance(user, dict): - raise OAuthError("invalid_response") - return AccountGrant(tokens, _text(user.get("id"), maximum=1024), _email(user.get("email"))) - - async def refresh( - self, refresh_token: str, *, scopes: tuple[str, ...], deadline: float - ) -> Tokens: - """No retry: the caller serializes and commits this account generation.""" - scopes = _scopes(self.kind, scopes) - fields = {"grant_type": "refresh_token", "refresh_token": _credential(refresh_token)} - answer = await self._request( - "POST", _TOKEN[self.kind], deadline=deadline, **self._token_request(fields) - ) - return self._tokens(answer, previous_refresh=refresh_token, previous_scopes=scopes) - - async def revoke(self, token: str, *, refresh: bool, deadline: float) -> None: - """Call only after local inactivation; no claim of whole-grant revocation.""" - token = _credential(token) - if self.kind == "notion": - if refresh: - raise OAuthError("unsupported_refresh_revocation") - kw = self._token_request({"token": token}) - else: - fields = {"token": token} - if self.kind == "linear": - fields["token_type_hint"] = "refresh_token" if refresh else "access_token" - kw = {"data": fields} - await self._request("POST", _REVOKE[self.kind], deadline=deadline, empty=True, **kw) diff --git a/server/clients/gdrive.py b/server/clients/gdrive.py deleted file mode 100644 index ff861138d0..0000000000 --- a/server/clients/gdrive.py +++ /dev/null @@ -1,449 +0,0 @@ -"""Minimal client for a shared-folder store, read with a service account. - -The credential is the service account's JSON key. It is exchanged for a short -access token at the store's token endpoint (a JWT signed with the key's private -key, the OAuth 2.0 JWT bearer grant) and the token goes in the `Authorization` -header only. Both hosts are constants here: a key's own `token_uri` is never -dialled. - -Errors are the shared ones of `server.clients._vendor`. -""" - -from __future__ import annotations - -import asyncio -import json -import re -import time -from dataclasses import dataclass, field -from typing import Any - -from server.clients._checked_access import Credential -from server.clients._http import get_client -from server.clients._vendor import ( - CredentialRefused, - NotFound, - RateLimited, - TooLarge, - VendorError, - bearer_get, - exchange_token, - get_capped, - json_object, -) - -_TOKEN_URL = "https://oauth2.googleapis.com/token" -_FILES_URL = "https://www.googleapis.com/drive/v3/files" -_DRIVES_URL = "https://www.googleapis.com/drive/v3/drives" -_SLIDES_URL = "https://slides.googleapis.com/v1/presentations" -_SCOPE = "https://www.googleapis.com/auth/drive.readonly" -_FOLDER_MIME = "application/vnd.google-apps.folder" -# Seconds between listing pages, so a long walk stays under the store's per-user -# rate limit. -PAGE_PACE_S = 0.7 # not a setting: the store's limit, the same on every deployment -# A modification stamp as the store reports it (RFC 3339, UTC). A stamp goes into the -# listing's query string, so nothing else is let through. -_STAMP_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z") -# A file id goes into a request path; the store's own ids are in this alphabet. -_FILE_ID_RE = re.compile(r"[A-Za-z0-9_-]{1,256}") -# Parent folders one listing query names, at most, so a query stays well inside the -# store's query length. -MAX_PARENTS = 50 # not a setting: a bound on one query, the same on every deployment -# What a listing reads of each file. -LISTED = "id,name,mimeType,modifiedTime,webViewLink,size" -# What a probe's first listing page reads of each file. -_PAGE_FIELDS = "id,name,mimeType,modifiedTime" -# What a mirrored source reads of each permission (`domain.access_list`). -_PERMISSION_FIELDS = "type,role,emailAddress,domain,allowFileDiscovery,deleted,view" -# A listing that also reads each file's permissions; the store leaves them out for a -# file the account cannot share, and for a shared drive's files (`file_permissions`). -LISTED_WITH_PERMISSIONS = f"{LISTED},permissions({_PERMISSION_FIELDS})" - - -@dataclass(frozen=True) -class ServiceAccount: - client_email: str - # Kept out of repr, so a logged or raised account never shows the key. - private_key: str = field(repr=False) - - -def parse_service_account(credential: str) -> ServiceAccount: - """The service account a JSON key names; CredentialRefused when it is not one.""" - try: - data = json.loads(credential) - except ValueError: - raise CredentialRefused("the credential is not a service account JSON key") from None - if not isinstance(data, dict) or data.get("type") != "service_account": - raise CredentialRefused("the credential is not a service account JSON key") - email = data.get("client_email") - key = data.get("private_key") - if not isinstance(email, str) or not email or not isinstance(key, str) or not key: - raise CredentialRefused("the service account key has no client_email or private_key") - return ServiceAccount(client_email=email, private_key=key) - - -async def access_token(account: ServiceAccount) -> str: - """A read-only access token for the service account.""" - import jwt - - now = int(time.time()) - claims = { - "iss": account.client_email, - "scope": _SCOPE, - "aud": _TOKEN_URL, - "iat": now, - "exp": now + 600, - } - try: - assertion = jwt.encode(claims, account.private_key, algorithm="RS256") - # A public key or a non-RSA key raises AttributeError or InvalidKeyError here. - except (ValueError, TypeError, AttributeError, jwt.PyJWTError): - raise CredentialRefused("the service account's private_key is not an RSA key") from None - answer = await exchange_token( - get_client(), - _TOKEN_URL, - "token exchange", - data={"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": assertion}, - ) - return str(answer["access_token"]) - - -async def require_folder(token: Credential, folder_id: str) -> dict[str, Any]: - """The folder's metadata, with its `driveId` (a shared drive's own id names its - root folder); NotFound when the account cannot see `folder_id` or it is no folder.""" - what = f"folder {folder_id}" - data = await bearer_get( - get_client(), - f"{_FILES_URL}/{folder_id}", - token, - what, - params={"fields": "mimeType,trashed,driveId", "supportsAllDrives": "true"}, - ) - if data.get("mimeType") != _FOLDER_MIME or data.get("trashed"): - raise NotFound(f"{what}: not a folder") - return data - - -async def require_drive(token: Credential, drive_id: str) -> None: - """NotFound when the account is no member of the shared drive `drive_id`.""" - if not valid_file_id(drive_id): - raise ValueError("not a drive id") - await bearer_get(get_client(), f"{_DRIVES_URL}/{drive_id}", token, f"shared drive {drive_id}") - - -def quoted(value: str) -> str: - """`value` as a quoted string of the store's query language.""" - return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'" - - -def _mime_clause(mime_types: list[str]) -> str: - return "(" + " or ".join(f"mimeType = {quoted(m)}" for m in mime_types) + ")" - - -def folder_query(folder_ids: list[str], mime_types: list[str]) -> str: - """The listing query for files of `mime_types` in any of `folder_ids`, not trashed. - The ids were checked by the caller (`parse_items`).""" - parents = " or ".join(f"{quoted(f)} in parents" for f in folder_ids) - return f"({parents}) and trashed = false and {_mime_clause(mime_types)}" - - -def drive_query(mime_types: list[str]) -> str: - """The listing query for a shared drive's files of `mime_types`, not trashed.""" - return f"trashed = false and {_mime_clause(mime_types)}" - - -def filter_query(item: dict[str, Any], mime_types: list[str]) -> str: - """The listing query of a `filter` item: each field it names, every value - quoted, so a field never widens the query past what it says.""" - parts = ["trashed = false", _mime_clause(mime_types)] - if "name_contains" in item: - parts.append(f"name contains {quoted(item['name_contains'])}") - if "modified_after" in item: - parts.append(f"modifiedTime > {quoted(item['modified_after'] + 'T00:00:00')}") - if "in" in item: - parts.append(f"{quoted(item['in'])} in parents") - return " and ".join(parts) - - -async def list_files( - token: Credential, query: str, *, drive_id: str = "", fields: str = _PAGE_FIELDS -) -> tuple[list[dict[str, Any]], bool]: - """One page (1000 at most) of the files `query` matches, most recently changed - first, and whether more may match: a next page, or a search the store did not - finish; with `drive_id`, of that shared drive only.""" - data = await bearer_get( - get_client(), - _FILES_URL, - token, - "listing", - params={ - **_corpus(drive_id), - "q": query, - "fields": f"nextPageToken,incompleteSearch,files({fields})", - "pageSize": "1000", - "orderBy": "modifiedTime desc", - }, - ) - files = [f for f in data.get("files") or [] if isinstance(f, dict)] - return files, bool(data.get("nextPageToken") or data.get("incompleteSearch")) - - -def _corpus(drive_id: str) -> dict[str, str]: - """The listing parameters that say where to look: the account's own corpus (the - files shared with it, and any folder's files by parent), or one shared drive.""" - params = {"supportsAllDrives": "true", "includeItemsFromAllDrives": "true"} - if drive_id: - if not valid_file_id(drive_id): - raise ValueError("not a drive id") - params.update({"corpora": "drive", "driveId": drive_id}) - return params - - -def valid_file_id(file_id: str) -> bool: - """Whether `file_id` is an id the store hands out, safe in a request path.""" - return bool(_FILE_ID_RE.fullmatch(file_id)) - - -def _file_url(file_id: str, suffix: str = "") -> str: - if not valid_file_id(file_id): - raise ValueError("not a file id") - return f"{_FILES_URL}/{file_id}{suffix}" - - -def valid_stamp(stamp: str) -> bool: - """Whether `stamp` is a modification time as the store reports it.""" - return bool(_STAMP_RE.fullmatch(stamp)) - - -async def list_all( - token: Credential, - folder_ids: list[str], - mime_types: list[str], - *, - modified_after: str = "", - fields: str = LISTED, - pace_s: float = PAGE_PACE_S, -) -> tuple[list[dict[str, Any]], bool]: - """Every file of `mime_types` in any of `folder_ids`, oldest change first, or only - those changed after `modified_after` (a `valid_stamp`), and whether the store - searched everything (`list_query`); MAX_PARENTS folders per query.""" - files: list[dict[str, Any]] = [] - whole = True - for start in range(0, len(folder_ids), MAX_PARENTS): - query = folder_query(folder_ids[start : start + MAX_PARENTS], mime_types) - found, complete = await list_query( - token, query, modified_after=modified_after, fields=fields, pace_s=pace_s - ) - files.extend(found) - whole = whole and complete - return files, whole - - -async def list_query( - token: Credential, - query: str, - *, - drive_id: str = "", - modified_after: str = "", - fields: str = LISTED, - pace_s: float = PAGE_PACE_S, - limit: int | None = None, -) -> tuple[list[dict[str, Any]], bool]: - """Every file `query` matches (with `drive_id`, in that shared drive), oldest - change first, or only those changed after `modified_after` (a `valid_stamp`), - and whether the store searched everything: False when any page says - `incompleteSearch`. Pages are paced; a failure on any page raises, so every page - was read. With `limit`, paging stops once more than `limit` files are in.""" - if modified_after and not valid_stamp(modified_after): - raise ValueError("modified_after is not a modification stamp") - if modified_after: - query += f" and modifiedTime > {quoted(modified_after)}" - params = { - **_corpus(drive_id), - "q": query, - "fields": f"nextPageToken,incompleteSearch,files({fields})", - "pageSize": "1000", - "orderBy": "modifiedTime", - } - files: list[dict[str, Any]] = [] - whole = True - while True: - data = await bearer_get(get_client(), _FILES_URL, token, "listing", params=params) - whole = whole and not data.get("incompleteSearch") - files.extend(f for f in data.get("files") or [] if isinstance(f, dict)) - page_token = data.get("nextPageToken") - if not isinstance(page_token, str) or not page_token: - return files, whole - if limit is not None and len(files) > limit: - return files, whole - params = {**params, "pageToken": page_token} - await asyncio.sleep(pace_s) - - -async def subfolders( - token: Credential, parent_ids: list[str], *, limit: int, pace_s: float = PAGE_PACE_S -) -> tuple[list[str], bool]: - """The ids of the folders directly in any of `parent_ids`, and whether the store - searched everything; MAX_PARENTS parents per query, and no page read once more - than `limit` ids are in.""" - found: list[str] = [] - whole = True - for start in range(0, len(parent_ids), MAX_PARENTS): - if len(found) > limit: - break - query = folder_query(parent_ids[start : start + MAX_PARENTS], [_FOLDER_MIME]) - folders, complete = await list_query( - token, query, fields="id", pace_s=pace_s, limit=limit - len(found) - ) - found.extend(str(f.get("id") or "") for f in folders) - whole = whole and complete - return [f for f in found if valid_file_id(f)], whole - - -async def any_subfolder(token: Credential, parent_ids: list[str], seen: set[str]) -> bool: - """Whether any of `parent_ids` holds a folder not in `seen`, from one page per - MAX_PARENTS parents; a page with more to follow, or from a search the store did not - finish, counts as holding one.""" - for start in range(0, len(parent_ids), MAX_PARENTS): - query = folder_query(parent_ids[start : start + MAX_PARENTS], [_FOLDER_MIME]) - files, unsure = await list_files(token, query, fields="id") - if unsure or any(str(f.get("id") or "") not in seen for f in files): - return True - return False - - -async def file_meta(token: Credential, file_id: str, *, fields: str = LISTED) -> dict[str, Any]: - """One file as a listing reads it (`fields`), with `trashed`; NotFound when the - account cannot see it.""" - return await bearer_get( - get_client(), - _file_url(file_id), - token, - f"file {file_id}", - params={"fields": f"{fields},trashed", "supportsAllDrives": "true"}, - ) - - -async def file_permissions( - token: Credential, file_id: str, *, pace_s: float = PAGE_PACE_S -) -> list[dict[str, Any]] | None: - """Every permission of one file, read page by page; None when the store will not - say (the file is gone, or the account may not see who it is shared with). A rate - limit or a refused credential raises.""" - params = { - "fields": f"nextPageToken,permissions({_PERMISSION_FIELDS})", - "pageSize": "100", - "supportsAllDrives": "true", - } - found: list[dict[str, Any]] = [] - while True: - try: - data = await bearer_get( - get_client(), - _file_url(file_id, "/permissions"), - token, - f"file {file_id}", - params=params, - ) - except NotFound: - return None - except CredentialRefused as e: - # A 403 here means the account may not see who the file is shared with (a - # rate limit is `RateLimited`); a 401 is the credential itself. - if e.status == 403: - return None - raise - found.extend(p for p in data.get("permissions") or [] if isinstance(p, dict)) - page_token = data.get("nextPageToken") - if not isinstance(page_token, str) or not page_token: - return found - params = {**params, "pageToken": page_token} - await asyncio.sleep(pace_s) - - -async def file_state(token: Credential, file_id: str) -> dict[str, Any]: - """What says whether a file is still a source's: `trashed`, `parents`, `driveId`, - and what a filter matches (`name`, `mimeType`, `modifiedTime`); NotFound when the - account cannot see it.""" - return await bearer_get( - get_client(), - _file_url(file_id), - token, - f"file {file_id}", - params={ - "fields": "trashed,parents,driveId,name,mimeType,modifiedTime", - "supportsAllDrives": "true", - }, - ) - - -async def export_markdown(token: Credential, file_id: str, *, max_bytes: int) -> str: - """A native document exported as Markdown.""" - data = await get_capped( - get_client(), - _file_url(file_id, "/export"), - token, - f"export {file_id}", - max_bytes=max_bytes, - params={"mimeType": "text/markdown"}, - ) - return data.decode("utf-8", errors="replace") - - -async def presentation(token: Credential, file_id: str, *, max_bytes: int) -> dict[str, Any]: - """A native presentation's slides, shapes and speaker notes, its description - read up to `max_bytes`.""" - if not valid_file_id(file_id): - raise ValueError("not a file id") - what = f"presentation {file_id}" - data = await get_capped( - get_client(), f"{_SLIDES_URL}/{file_id}", token, what, max_bytes=max_bytes - ) - return json_object(data, what) - - -async def download(token: Credential, file_id: str, *, max_bytes: int) -> bytes: - """An uploaded file's bytes.""" - return await get_capped( - get_client(), - _file_url(file_id), - token, - f"download {file_id}", - max_bytes=max_bytes, - params={"alt": "media", "supportsAllDrives": "true"}, - ) - - -__all__ = [ - "LISTED", - "LISTED_WITH_PERMISSIONS", - "MAX_PARENTS", - "PAGE_PACE_S", - "CredentialRefused", - "NotFound", - "RateLimited", - "ServiceAccount", - "TooLarge", - "VendorError", - "access_token", - "any_subfolder", - "download", - "drive_query", - "export_markdown", - "file_meta", - "file_permissions", - "file_state", - "filter_query", - "folder_query", - "list_all", - "list_files", - "list_query", - "parse_service_account", - "presentation", - "quoted", - "require_drive", - "require_folder", - "subfolders", - "valid_file_id", - "valid_stamp", -] diff --git a/server/clients/gdrive_push.py b/server/clients/gdrive_push.py deleted file mode 100644 index afeca0bd63..0000000000 --- a/server/clients/gdrive_push.py +++ /dev/null @@ -1,85 +0,0 @@ -"""Bounded Drive change-channel requests using an existing read-only token.""" - -from __future__ import annotations - -import time -from typing import Any - -from server.clients._http import get_client -from server.clients._vendor import VendorError, bearer_get, raise_for_status, request_json - -_ROOT = "https://www.googleapis.com/drive/v3" - - -async def member_drives(token: str) -> set[str]: - """The complete small membership set; a partial listing refuses push setup.""" - result = await bearer_get( - get_client(), - f"{_ROOT}/drives", - token, - "push corpora", - params={"pageSize": 20, "fields": "nextPageToken,drives(id)"}, - ) - drives = result.get("drives", []) - if result.get("nextPageToken") or not isinstance(drives, list) or len(drives) >= 20: - raise VendorError("push corpus bound exceeded") - ids = {str(d["id"]) for d in drives if isinstance(d, dict) and d.get("id")} - if len(ids) != len(drives): - raise VendorError("invalid push corpora") - return ids - - -async def watch( - token: str, *, channel_id: str, channel_token: str, address: str, drive_id: str -) -> dict[str, Any]: - params = {"supportsAllDrives": "true", **({"driveId": drive_id} if drive_id else {})} - start = await bearer_get( - get_client(), f"{_ROOT}/changes/startPageToken", token, "push cursor", params=params - ) - cursor = start.get("startPageToken") - if not isinstance(cursor, str) or not cursor: - raise VendorError("missing push cursor") - expires_ms = int((time.time() + 6 * 86400) * 1000) - answer = await request_json( - get_client(), - "POST", - f"{_ROOT}/changes/watch", - "push channel", - headers={"Authorization": f"Bearer {token}"}, - params={**params, "includeItemsFromAllDrives": "true", "pageToken": cursor}, - json={ - "id": channel_id, - "type": "web_hook", - "address": address, - "token": channel_token, - "expiration": str(expires_ms), - }, - ) - resource = answer.get("resourceId") - try: - expiration = int(answer.get("expiration", 0)) / 1000 - except (TypeError, ValueError): - raise VendorError("invalid push expiration") from None - if ( - answer.get("id") != channel_id - or not isinstance(resource, str) - or not resource - or not time.time() < expiration <= expires_ms / 1000 + 1 - ): - raise VendorError("invalid push channel") - return { - "id": channel_id, - "token": channel_token, - "resource_id": resource, - "expiration": expiration, - "drive_id": drive_id, - } - - -async def stop(token: str, channel: dict[str, Any]) -> None: - response = await get_client().post( - f"{_ROOT}/channels/stop", - headers={"Authorization": f"Bearer {token}"}, - json={"id": channel["id"], "resourceId": channel["resource_id"]}, - ) - raise_for_status(response, "stop push channel") diff --git a/server/clients/linear.py b/server/clients/linear.py deleted file mode 100644 index ec9be0b473..0000000000 --- a/server/clients/linear.py +++ /dev/null @@ -1,446 +0,0 @@ -"""Minimal client for a project tracker's documents, read over its GraphQL API with -an API key. - -The key goes in the `Authorization` header as it is (the tracker's API keys take -no `Bearer` prefix). The host is a constant here, and every id travels as a -GraphQL variable, never inside the query text. - -Errors carry the HTTP status and the error's type, never the response body, which -can name documents or the tracker's own hosts. The API reports most failures as -GraphQL errors, often with HTTP 200 or 400, so each error's `extensions.code` and -`extensions.type` are read as well as the status: a rate limit raises `RateLimited` -(a 429, or any error typed `ratelimited`), a refused key `CredentialRefused`, the -tracker's own not-found error `NotFound` (an answer that merely lacks the object is -a `LinearError`, never evidence of absence), an answer over the caller's size bound -`TooLarge`, and any other failure `LinearError`. An answer with any GraphQL error -raises, so a listing is never taken from a partial answer. Nothing here retries: the -sync worker's next pass is the retry. The errors are this client's own, not those of -`server.clients._vendor`: they carry the GraphQL error's type, which says more than -the status. -""" - -from __future__ import annotations - -import asyncio -import json -import re -from typing import Any - -import httpx - -from server.clients._checked_access import CheckedAccess, Credential -from server.clients._http import get_client -from server.clients._vendor import read_capped -from server.settings import settings - -_GRAPHQL_URL = "https://api.linear.app/graphql" -# Nodes per page (documents, or projects by short id): the API's own default page size. -PAGE_SIZE = 50 # not a setting: the API's page size, the same on every deployment -# Seconds between listing pages, so a long list stays under the API's hourly -# request limit per key. -PAGE_PACE_S = 0.5 # not a setting: the API's limit, the same on every deployment -_sleep = asyncio.sleep # the pause between pages; a test replaces it here alone -# A bound on one listing page's answer (50 nodes of ids, titles, stamps and links). -_PAGE_MAX_BYTES = 4 * 1024 * 1024 # not a setting: far above any real page -# The tracker's ids are UUIDs. -_ID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") -_KEY_RE = re.compile(r"[\x21-\x7e]{8,512}") - -_PROJECT_DOCUMENTS = """ -query ProjectDocuments($id: String!, $first: Int!, $after: String) { - project(id: $id) { - id - documents(first: $first, after: $after) { - nodes { id title updatedAt url } - pageInfo { hasNextPage endCursor } - } - } -} -""" - -# Projects by the short id their links carry, a page of them at a time. -_PROJECTS_BY_SLUG = """ -query ProjectsBySlug($slugs: [String!]!, $first: Int!) { - projects(filter: { slugId: { in: $slugs } }, first: $first) { - nodes { id slugId } - } -} -""" - -_DOCUMENT = """ -query Document($id: String!) { - document(id: $id) { id content updatedAt url } -} -""" - -_DOCUMENT_STATE = """ -query DocumentState($id: String!) { - document(id: $id) { id trashed archivedAt project { id } } -} -""" - -_PROJECT_TEAMS = """ -query ProjectTeams($id: String!, $first: Int!, $after: String) { - project(id: $id) { - teams(first: $first, after: $after) { - nodes { id } - pageInfo { hasNextPage endCursor } - } - } -} -""" - -_TEAM_MEMBERS = """ -query TeamMembers($id: String!, $first: Int!, $after: String) { - team(id: $id) { - members(first: $first, after: $after, includeDisabled: true) { - nodes { id email active } - pageInfo { hasNextPage endCursor } - } - } -} -""" - - -class LinearError(RuntimeError): - """`reason` is a short label for what failed (`http_500`, `not_found`, - `graphql_internal_error`); `status` is the HTTP status the tracker answered, 0 - when it gave none (a network error, a bound passed here); `kind` is the first - `extensions.type` or `extensions.code` among the errors, lower-cased with `_` as - a space, '' when there was none.""" - - def __init__(self, what: str, reason: str, *, status: int = 0, kind: str = "") -> None: - super().__init__(f"{what}: {reason}") - self.reason = reason - self.status = status - self.kind = kind - - @property - def refused(self) -> bool: - """The tracker refused this request, as opposed to failing to answer: by - the GraphQL error's type when it gave one (it answers most errors with a - 400, its internal errors too), else by a 4xx status.""" - return self.kind in _REFUSED_KINDS if self.kind else 400 <= self.status < 500 - - -class RateLimited(LinearError): - pass - - -class CredentialRefused(LinearError): - pass - - -class NotFound(LinearError): - pass - - -class TooLarge(LinearError): - pass - - -# GraphQL error types that say the request itself was refused. -_REFUSED_KINDS = {"forbidden", "invalid input", "feature not accessible", "user error"} - - -def valid_id(value: str) -> bool: - """Whether `value` is an id the tracker hands out (a lower-case UUID).""" - return bool(_ID_RE.fullmatch(value)) - - -def valid_key(api_key: Credential) -> bool: - """Whether `api_key` can be an API key: printable ASCII with no space, so it - travels in a header unchanged.""" - if isinstance(api_key, CheckedAccess): - return api_key.kind == "linear" - return bool(_KEY_RE.fullmatch(api_key)) - - -def _error_kinds(errors: list[Any]) -> list[str]: - """Each GraphQL error's `extensions.type` and `extensions.code`, lower-cased with - `_` read as a space (`RATELIMITED`, `AUTHENTICATION_ERROR`), in order.""" - kinds = [] - for error in errors: - ext = error.get("extensions") if isinstance(error, dict) else None - ext = ext if isinstance(ext, dict) else {} - for key in ("type", "code"): - if value := ext.get(key): - kinds.append(str(value).lower().replace("_", " ")) - return kinds - - -def _not_found(errors: list[Any]) -> bool: - """The tracker answers an id the key cannot see with `Entity not found`.""" - return any( - isinstance(e, dict) and str(e.get("message") or "").lower().startswith("entity not found") - for e in errors - ) - - -def _raise_for(status: int, body: Any, what: str) -> None: - errors = body.get("errors") if isinstance(body, dict) else None - errors = errors if isinstance(errors, list) else [] - kinds = _error_kinds(errors) - kind = kinds[0] if kinds else "" - if status == 429 or "ratelimited" in kinds: - raise RateLimited(what, "rate_limited", status=status, kind="ratelimited") - if status == 401 or "authentication error" in kinds: - raise CredentialRefused(what, "credential_refused", status=status, kind=kind) - if _not_found(errors): - raise NotFound(what, "not_found", status=status, kind=kind) - if kind: - # The error's own type says more than the status, which is often a 400. - raise LinearError(what, f"graphql_{kind.replace(' ', '_')}", status=status, kind=kind) - if status >= 400: - raise LinearError(what, f"http_{status}", status=status) - if errors: - raise LinearError(what, "graphql_error", status=status) - - -async def _query( - api_key: Credential, query: str, variables: dict[str, Any], what: str, *, max_bytes: int -) -> dict[str, Any]: - """The `data` of one GraphQL request, its answer read up to `max_bytes`.""" - checked = api_key if isinstance(api_key, CheckedAccess) else None - if isinstance(api_key, str): - api_key = api_key.strip() # a pasted key often ends in a newline - if not valid_key(api_key): - raise CredentialRefused(what, "not_an_api_key") - try: - async with asyncio.timeout_at(checked.deadline if checked is not None else None): - authorization = ( - await api_key.authorization(_GRAPHQL_URL) - if isinstance(api_key, CheckedAccess) - else api_key - ) - async with get_client().stream( - "POST", - _GRAPHQL_URL, - headers={"Authorization": authorization, "Content-Type": "application/json"}, - json={"query": query, "variables": variables}, - follow_redirects=False if checked is not None else httpx.USE_CLIENT_DEFAULT, - ) as resp: - raw = await read_capped(resp, max_bytes) - if checked is not None: - await checked.check() - except httpx.RequestError as e: - raise LinearError(what, "unreachable") from e - if raw is None: - raise TooLarge(what, "too_large") - try: - body = json.loads(raw) - except ValueError: - body = None - _raise_for(resp.status_code, body, what) - if checked is not None and not resp.is_success: - raise LinearError(what, f"http_{resp.status_code}", status=resp.status_code) - data = body.get("data") if isinstance(body, dict) else None - if not isinstance(data, dict): - raise LinearError(what, "no_data", status=resp.status_code) - return data - - -async def documents_page( - api_key: Credential, project_id: str, *, after: str = "" -) -> tuple[list[dict[str, Any]], str]: - """One page of a project's documents (id, title, updatedAt, url) and the cursor - of the next page, '' after the last. NotFound when the tracker says the key - cannot see the project.""" - what = f"project {project_id}" - variables: dict[str, Any] = {"id": project_id, "first": PAGE_SIZE} - if after: - variables["after"] = after - data = await _query(api_key, _PROJECT_DOCUMENTS, variables, what, max_bytes=_PAGE_MAX_BYTES) - project = data.get("project") - if not isinstance(project, dict): - # Not the tracker's not-found error: no evidence the project is gone. - raise LinearError(what, "no_project") - connection = project.get("documents") - if not isinstance(connection, dict): - raise LinearError(what, "no_documents") - nodes = [n for n in connection.get("nodes") or [] if isinstance(n, dict)] - info = connection.get("pageInfo") - if not isinstance(info, dict): - # Without it there is no telling whether more pages follow. - raise LinearError(what, "no_page_info") - if not info.get("hasNextPage"): - return nodes, "" - cursor = info.get("endCursor") - if not isinstance(cursor, str) or not cursor or cursor == after: - # A next page with no cursor to reach it: the listing cannot be completed. - raise LinearError(what, "no_cursor") - return nodes, cursor - - -async def _acl_nodes( - api_key: Credential, - query: str, - root: str, - field: str, - ident: str, - *, - limit: int, -) -> list[dict[str, Any]]: - """Read a complete bounded ACL connection; no partial page grants a reader.""" - cursor = "" - seen: set[str] = set() - found: list[dict[str, Any]] = [] - while True: - data = await _query( - api_key, - query, - {"id": ident, "first": PAGE_SIZE, "after": cursor or None}, - "permissions", - max_bytes=_PAGE_MAX_BYTES, - ) - parent = data.get(root) - connection = parent.get(field) if isinstance(parent, dict) else None - nodes = connection.get("nodes") if isinstance(connection, dict) else None - info = connection.get("pageInfo") if isinstance(connection, dict) else None - if ( - not isinstance(nodes, list) - or any( - not isinstance(node, dict) or not valid_id(str(node.get("id"))) for node in nodes - ) - or not isinstance(info, dict) - or not isinstance(info.get("hasNextPage"), bool) - ): - raise LinearError("permissions", "invalid_connection") - if len(found) + len(nodes) > limit or len(seen) >= limit: - raise TooLarge("permissions", "too_many_entries") - found.extend(nodes) - if not info["hasNextPage"]: - return found - next_cursor = info.get("endCursor") - if not isinstance(next_cursor, str) or not next_cursor or next_cursor in seen: - raise LinearError("permissions", "invalid_cursor") - seen.add(next_cursor) - cursor = next_cursor - await _sleep(PAGE_PACE_S) - - -async def project_member_emails(api_key: Credential, project_id: str) -> tuple[str, ...]: - """Only explicitly active members of the project's visible teams may match an ACL.""" - maximum = settings.knowledge_source_acl_max_entries - teams = await _acl_nodes(api_key, _PROJECT_TEAMS, "project", "teams", project_id, limit=maximum) - remaining = maximum - len(teams) - emails: set[str] = set() - for team in teams: - members = await _acl_nodes( - api_key, _TEAM_MEMBERS, "team", "members", team["id"], limit=remaining - ) - remaining -= len(members) - for member in members: - email = member.get("email") - if member.get("active") is True and isinstance(email, str) and email.strip(): - emails.add(email.strip().lower()) - return tuple(sorted(emails)) - - -async def organization_id(api_key: Credential) -> str: - """The credential's organization, for binding incoming notifications.""" - data = await _query( - api_key, "query { organization { id } }", {}, "push identity", max_bytes=4096 - ) - org = data.get("organization") - value = org.get("id") if isinstance(org, dict) else None - if not isinstance(value, str) or not value: - raise LinearError("push identity", "no_organization") - return value - - -async def project_documents(api_key: Credential, project_id: str) -> list[dict[str, Any]]: - """Every document of a project, every page read and paced; a failure on any page - raises.""" - found: list[dict[str, Any]] = [] - cursor = "" - while True: - nodes, cursor = await documents_page(api_key, project_id, after=cursor) - found.extend(nodes) - if not cursor: - return found - await _sleep(PAGE_PACE_S) - - -async def project_ids(api_key: Credential, slug_ids: list[str]) -> dict[str, str]: - """{short id: project UUID} of the projects the key sees among `slug_ids`, the - short ids a project's link carries; one the tracker does not answer for is - left out. One page answers them: the ops bound a call well under it.""" - if len(slug_ids) > PAGE_SIZE: - raise ValueError(f"at most {PAGE_SIZE} short ids in one lookup") - data = await _query( - api_key, - _PROJECTS_BY_SLUG, - {"slugs": slug_ids, "first": PAGE_SIZE}, - "projects", - max_bytes=_PAGE_MAX_BYTES, - ) - projects = data.get("projects") - nodes = projects.get("nodes") if isinstance(projects, dict) else None - if not isinstance(nodes, list): - # An answer without the list says nothing about which projects exist. - raise LinearError("projects", "no_projects") - found: dict[str, str] = {} - for node in nodes: - if not isinstance(node, dict): - continue - slug, project_id = str(node.get("slugId") or ""), str(node.get("id") or "") - if slug in slug_ids and valid_id(project_id): - found[slug] = project_id - return found - - -def _checked(document_id: str) -> str: - if not valid_id(document_id): - raise ValueError("not a document id") - return document_id - - -async def document(api_key: Credential, document_id: str, *, max_bytes: int) -> dict[str, Any]: - """One document's Markdown `content`, `updatedAt` and `url`, its answer read up to - `max_bytes`; NotFound when the tracker says the key cannot see it.""" - what = f"document {document_id}" - data = await _query( - api_key, _DOCUMENT, {"id": _checked(document_id)}, what, max_bytes=max_bytes - ) - doc = data.get("document") - if not isinstance(doc, dict): - # Not the tracker's not-found error: no evidence the document is gone. - raise LinearError(what, "no_document") - return doc - - -async def document_state(api_key: Credential, document_id: str) -> dict[str, Any]: - """A document's `trashed`, `archivedAt` and `project`; NotFound when the key - cannot see it.""" - what = f"document {document_id}" - data = await _query( - api_key, - _DOCUMENT_STATE, - {"id": _checked(document_id)}, - what, - max_bytes=_PAGE_MAX_BYTES, - ) - doc = data.get("document") - if not isinstance(doc, dict): - # Not the tracker's not-found error: no evidence the document is gone. - raise LinearError(what, "no_document") - return doc - - -__all__ = [ - "PAGE_PACE_S", - "PAGE_SIZE", - "CredentialRefused", - "LinearError", - "NotFound", - "RateLimited", - "TooLarge", - "document", - "document_state", - "documents_page", - "project_documents", - "project_ids", - "valid_id", - "valid_key", -] diff --git a/server/clients/notion.py b/server/clients/notion.py deleted file mode 100644 index 2e787d9fad..0000000000 --- a/server/clients/notion.py +++ /dev/null @@ -1,290 +0,0 @@ -"""Minimal client for a page store, read with an integration token. - -The credential is the integration's token, sent in the `Authorization` header -only, with the API version the shapes below were written against. The host is a -constant here, and every id that goes into a request path is checked first. - -Errors are the shared ones of `server.clients._vendor`: a refused token or -capability is `CredentialRefused` (a 401, or a 403 that is not a rate limit), a -page past the caller's bounds `TooLarge`. -""" - -from __future__ import annotations - -import asyncio -import hashlib -import re -import time -from typing import Any - -from server.clients._checked_access import CheckedAccess, Credential -from server.clients._http import get_client -from server.clients._vendor import ( - CredentialRefused, - NotFound, - RateLimited, - TooLarge, - VendorError, - request_json, -) - -_API_URL = "https://api.notion.com/v1" -# The API version the request and response shapes here follow. -API_VERSION = "2026-03-11" -# Seconds between two requests to the store, so a turn stays under its average of -# three requests a second per integration. -PAGE_PACE_S = 0.35 # not a setting: the store's limit, the same on every deployment -# Results per listing page. -_PAGE_SIZE = 100 # not a setting: the most the store hands out -# A timestamp as the store reports it (RFC 3339, UTC). Kept here, not shared: it -# guards this client's own query filter, so nothing else reaches the request body. -_STAMP_RE = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z") -# An id in the store's dashed form, the form a source's config stores. -_ID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") -# Block types whose children are other pages or databases, never read into a page. -_OTHER_PAGES = {"child_page", "child_database"} - - -def valid_id(value: str) -> bool: - """Whether `value` is an id in the store's dashed form, safe in a request path.""" - return bool(_ID_RE.fullmatch(value)) - - -def _valid_stamp(stamp: str) -> bool: - """Whether `stamp` is a timestamp as the store reports it.""" - return bool(_STAMP_RE.fullmatch(stamp)) - - -def valid_token(credential: Credential) -> bool: - """Whether `credential` can be an integration token: one printable word.""" - if isinstance(credential, CheckedAccess): - return credential.kind == "notion" - return bool(re.fullmatch(r"[\x21-\x7e]{8,256}", credential)) - - -# When the next request of each integration may go out (time.monotonic), by a digest -# of its token: the store limits each integration on its own, so two integrations do -# not wait on each other. -_next_request_at: dict[str, float] = {} - - -async def _pace(token: Credential) -> None: - """Wait until PAGE_PACE_S has passed since this integration's previous request.""" - now = time.monotonic() - if len(_next_request_at) > 64: - # Forget the integrations that are no longer waiting, so the map stays small. - for key, at in list(_next_request_at.items()): - if at <= now: - del _next_request_at[key] - key = ( - token.pacing_key() - if isinstance(token, CheckedAccess) - else hashlib.sha256(token.encode()).hexdigest()[:16] - ) - start = max(now, _next_request_at.get(key, 0.0)) - _next_request_at[key] = start + PAGE_PACE_S - if start > now: - await asyncio.sleep(start - now) - - -async def _call( - method: str, path: str, token: Credential, what: str, *, params: Any = None, body: Any = None -) -> dict[str, Any]: - checked = token if isinstance(token, CheckedAccess) else None - async with asyncio.timeout_at(checked.deadline if checked is not None else None): - await _pace(token) - headers = {"Notion-Version": API_VERSION} - if checked is None: - headers["Authorization"] = f"Bearer {token}" - return await request_json( - get_client(), - method, - f"{_API_URL}{path}", - what, - headers=headers, - params=params, - json=body, - checked=checked, - ) - - -def _checked(object_id: str) -> str: - if not valid_id(object_id): - raise ValueError("not an id") - return object_id - - -async def page(token: Credential, page_id: str) -> dict[str, Any]: - """A page's properties, address, last edit and trash flag.""" - return await _call("GET", f"/pages/{_checked(page_id)}", token, f"page {page_id}") - - -async def workspace_id(token: Credential) -> str: - """The bot credential's workspace, for binding incoming notifications.""" - answer = await _call("GET", "/users/me", token, "push identity") - bot = answer.get("bot") - value = bot.get("workspace_id") if isinstance(bot, dict) else None - if not isinstance(value, str) or not valid_id(value): - raise VendorError("push identity unavailable") - return value - - -async def block(token: Credential, block_id: str) -> dict[str, Any]: - """A block, with its parent (a page, another block or the workspace).""" - return await _call("GET", f"/blocks/{_checked(block_id)}", token, f"block {block_id}") - - -async def database(token: Credential, database_id: str) -> dict[str, Any]: - """A database's title, trash flag and data sources.""" - return await _call( - "GET", f"/databases/{_checked(database_id)}", token, f"database {database_id}" - ) - - -def data_source_ids(db: dict[str, Any]) -> list[str]: - """The ids of a database's data sources, the tables its pages live in.""" - ids = [str(d.get("id") or "") for d in db.get("data_sources") or [] if isinstance(d, dict)] - return [i for i in ids if valid_id(i)] - - -def _query_body(edited_after: str) -> dict[str, Any]: - if edited_after and not _valid_stamp(edited_after): - raise ValueError("edited_after is not a timestamp") - body: dict[str, Any] = { - "page_size": _PAGE_SIZE, - "result_type": "page", - "sorts": [{"timestamp": "last_edited_time", "direction": "ascending"}], - } - if edited_after: - body["filter"] = { - "timestamp": "last_edited_time", - "last_edited_time": {"after": edited_after}, - } - return body - - -async def _query(token: Credential, data_source_id: str, body: dict[str, Any]) -> dict[str, Any]: - path = f"/data_sources/{_checked(data_source_id)}/query" - return await _call("POST", path, token, f"data source {data_source_id}", body=body) - - -def _pages_of(data: dict[str, Any]) -> list[dict[str, Any]]: - return [ - r for r in data.get("results") or [] if isinstance(r, dict) and r.get("object") == "page" - ] - - -async def first_pages(token: Credential, data_source_id: str) -> tuple[list[dict[str, Any]], bool]: - """The first listing page (100 at most) of a data source's pages, newest edit - first, and whether more follow.""" - body = _query_body("") - body["sorts"] = [{"timestamp": "last_edited_time", "direction": "descending"}] - data = await _query(token, data_source_id, body) - return _pages_of(data), bool(data.get("has_more")) - - -async def query_pages( - token: Credential, data_source_id: str, *, edited_after: str = "" -) -> tuple[list[dict[str, Any]], bool]: - """Every page of a database's data source, oldest edit first, or only those edited - after `edited_after` (a stamp the store issued), and whether the store returned them all: - False when it says its result is incomplete. A failure on any listing page - raises, so every page was read.""" - body = _query_body(edited_after) - pages: list[dict[str, Any]] = [] - whole = True - while True: - data = await _query(token, data_source_id, body) - status = data.get("request_status") - whole = whole and not (isinstance(status, dict) and status.get("type") == "incomplete") - pages.extend(_pages_of(data)) - cursor = data.get("next_cursor") - if not data.get("has_more") or not isinstance(cursor, str) or not cursor: - return pages, whole - body = {**body, "start_cursor": cursor} - - -async def page_blocks( - token: Credential, page_id: str, *, max_requests: int -) -> list[dict[str, Any]]: - """A page's blocks in order, each block with children carrying them under - `children`; child pages and databases are not read into it. A synced copy whose - original the integration cannot see (404, 403) is marked `unreadable` and read - no further. TooLarge once the walk would take more than `max_requests` - requests.""" - requests = 0 - - async def children(block_id: str) -> list[dict[str, Any]]: - nonlocal requests - out: list[dict[str, Any]] = [] - params: dict[str, Any] = {"page_size": _PAGE_SIZE} - while True: - if requests >= max_requests: - raise TooLarge(f"page {page_id}: over {max_requests} requests") - requests += 1 - data = await _call( - "GET", - f"/blocks/{_checked(block_id)}/children", - token, - f"page {page_id}", - params=params, - ) - out.extend(b for b in data.get("results") or [] if isinstance(b, dict)) - cursor = data.get("next_cursor") - if not data.get("has_more") or not isinstance(cursor, str) or not cursor: - break - params = {**params, "start_cursor": cursor} - for block in out: - # A synced copy's content lives under the block it was synced from. - synced = (block.get("synced_block") or {}).get("synced_from") or {} - if block.get("type") in _OTHER_PAGES or not (block.get("has_children") or synced): - continue - nested = str(synced.get("block_id") or block.get("id") or "") - if not valid_id(nested): - continue - try: - block["children"] = await children(nested) - except (NotFound, CredentialRefused) as e: - # Only a copy's original lives elsewhere; any other block's is the page's. - if not synced or e.status == 401: - raise - block["unreadable"] = True - return out - - return await children(page_id) - - -def title_of(obj: dict[str, Any]) -> str: - """A page's title (its `title` property, whatever it is named) or a database's.""" - rich = obj.get("title") - if not isinstance(rich, list): - rich = next( - ( - p.get("title") - for p in (obj.get("properties") or {}).values() - if isinstance(p, dict) and p.get("type") == "title" - ), - [], - ) - return "".join(str(t.get("plain_text") or "") for t in rich or [] if isinstance(t, dict)) - - -__all__ = [ - "API_VERSION", - "PAGE_PACE_S", - "CredentialRefused", - "NotFound", - "RateLimited", - "TooLarge", - "VendorError", - "block", - "data_source_ids", - "database", - "first_pages", - "page", - "page_blocks", - "query_pages", - "title_of", - "valid_id", - "valid_token", -] diff --git a/server/knowledge/api/models_connections.py b/server/knowledge/api/models_connections.py deleted file mode 100644 index d0de937bb4..0000000000 --- a/server/knowledge/api/models_connections.py +++ /dev/null @@ -1,36 +0,0 @@ -"""The caller's own connected accounts; credentials are never part of the wire shape.""" - -from typing import Literal - -from pydantic import BaseModel, Field - - -class ConnectionListInput(BaseModel): - """List the signed-in caller's own connected provider accounts.""" - - org: str = Field(description="The caller's organization.") - - -class ConnectionEntry(BaseModel): - kind: Literal["gdrive", "notion", "linear"] - connected: bool - account_email: str | None = None - scopes: list[str] = Field(default_factory=list) - connect_url: str - - -class ConnectionListOutput(BaseModel): - connections: list[ConnectionEntry] - - -class ConnectionDisconnectInput(BaseModel): - """Disconnect the caller's own provider account and stop its connected sources.""" - - org: str = Field(description="The caller's organization.") - kind: Literal["gdrive", "notion", "linear"] = Field( - description="The connected provider to disconnect." - ) - - -class ConnectionDisconnectOutput(BaseModel): - disconnected: bool diff --git a/server/knowledge/api/models_mcp_connections.py b/server/knowledge/api/models_mcp_connections.py index 448f5d460b..29997b2acc 100644 --- a/server/knowledge/api/models_mcp_connections.py +++ b/server/knowledge/api/models_mcp_connections.py @@ -1,45 +1,13 @@ """Owner-only MCP connection controls; credentials are input-only secrets.""" -from typing import Any, Literal, Self - -from pydantic import ( - BaseModel, - ConfigDict, - Field, - ModelWrapValidatorHandler, - SecretStr, - model_validator, -) -from pydantic import ( - ValidationError as ModelValidationError, -) - - -class _Input(BaseModel): - model_config = ConfigDict(extra="forbid", hide_input_in_errors=True) - org: str = Field(description="The authenticated caller's organization.") - - @model_validator(mode="wrap") - @classmethod - def _redact_errors(cls, value: Any, handler: ModelWrapValidatorHandler[Self]) -> Self: - try: - return handler(value) - except ModelValidationError: - # HTTP serializes error inputs; hiding only their text repr is insufficient. - raise ModelValidationError.from_exception_data( - cls.__name__, - [ - { - "type": "value_error", - "loc": (), - "input": "", - "ctx": {"error": ValueError("MCP_CONNECTION_INPUT_INVALID")}, - } - ], - ) from None - - -class MCPConnectInput(_Input): +from typing import Literal + +from pydantic import BaseModel, Field, SecretStr + +from server.knowledge.api.models_private_sources import PrivateSourceInput + + +class MCPConnectInput(PrivateSourceInput): profile_id: str = Field( min_length=1, max_length=128, description="The operator-approved profile ID." ) @@ -60,7 +28,7 @@ class MCPConnectInput(_Input): ) -class MCPListInput(_Input): +class MCPListInput(PrivateSourceInput): cursor: str | None = Field( default=None, max_length=2048, @@ -75,7 +43,7 @@ class MCPListInput(_Input): ) -class MCPInspectInput(_Input): +class MCPInspectInput(PrivateSourceInput): slot: str = Field( default="", max_length=36, @@ -88,7 +56,7 @@ class MCPInspectInput(_Input): ) -class MCPSlotInput(_Input): +class MCPSlotInput(PrivateSourceInput): slot: str = Field(max_length=36, description="The exact owned MCP connection slot.") @@ -134,3 +102,46 @@ class MCPDisconnectOutput(BaseModel): disconnected: bool upstream_revoked: Literal[False] = False upstream_action: Literal["revoke_credential_upstream"] = "revoke_credential_upstream" + + +class MCPBrowseInput(MCPSlotInput): + mode: Literal["resources", "search"] = Field(description="The explicit metadata operation.") + query: str = Field( + default="", + max_length=1000, + repr=False, + description="The approved mapped-search query; empty for resources, default empty.", + ) + limit: int = Field( + default=100, + ge=1, + le=100, + strict=True, + description="Maximum metadata items in the first window, from 1 to 100; default 100.", + ) + + +class MCPBrowseItem(BaseModel): + id: str = Field(repr=False) + title: str = Field(repr=False) + uri: str = Field(repr=False, description="A stable display hint that grants no read authority.") + + +class MCPBrowseOutput(BaseModel): + slot: str + generation: str + mode: Literal["resources", "search"] + supported: bool = False + resources: bool | None + mapped_read: bool + mapped_search: bool + capabilities_checked: bool = False + items: list[MCPBrowseItem] = Field(default_factory=list) + complete: bool = Field( + default=False, description="The declared page fits this response window." + ) + truncated: bool = False + reason: str | None = None + limitations: list[str] + manual_resource_ids_supported: Literal[True] = True + remote_identity_verified: Literal[False] = False diff --git a/server/knowledge/api/models_mcp_reads.py b/server/knowledge/api/models_mcp_reads.py new file mode 100644 index 0000000000..ae0a0fd748 --- /dev/null +++ b/server/knowledge/api/models_mcp_reads.py @@ -0,0 +1,33 @@ +"""Selected live MCP reads use saved source authority, never a caller endpoint.""" + +from typing import Literal + +from pydantic import BaseModel, Field + +from server.knowledge.api.models_private_sources import PrivateSourceInput + + +class MCPReadInput(PrivateSourceInput): + namespace: str = Field(min_length=1, max_length=255, description="The source collection.") + name: str = Field( + min_length=1, max_length=256, repr=False, description="The opaque saved source name." + ) + resource_id: str = Field( + min_length=1, + max_length=2048, + repr=False, + description="An exact resource ID explicitly selected in the saved live source.", + ) + + +class MCPReadOutput(BaseModel): + source_id: str + resource_id: str = Field(repr=False) + uri: str = Field(repr=False) + title: str = Field(repr=False) + text: str = Field(repr=False) + mime_type: str + resource_identity_verified: bool + remote_identity_verified: Literal[False] = False + upstream_acl_verified: Literal[False] = False + limitations: list[str] diff --git a/server/knowledge/api/models_mcp_sources.py b/server/knowledge/api/models_mcp_sources.py index 5b3bc051f9..4d339d2dfd 100644 --- a/server/knowledge/api/models_mcp_sources.py +++ b/server/knowledge/api/models_mcp_sources.py @@ -4,10 +4,10 @@ from pydantic import BaseModel, Field -from server.knowledge.api.models_mcp_connections import _Input +from server.knowledge.api.models_private_sources import PrivateSourceInput -class MCPSourcePreviewInput(_Input): +class MCPSourcePreviewInput(PrivateSourceInput): org: str = Field(description="The authenticated organization.") namespace: str = Field(description="The ordinary destination collection or namespace.") slot: str = Field(max_length=36, description="The signed-in owner's MCP connection slot.") @@ -74,7 +74,7 @@ class MCPSourceAddInput(MCPSourcePreviewInput): ) -class MCPSourceScopeInput(_Input): +class MCPSourceScopeInput(PrivateSourceInput): namespace: str = Field(description="The ordinary destination collection or namespace.") diff --git a/server/knowledge/api/models_private_sources.py b/server/knowledge/api/models_private_sources.py new file mode 100644 index 0000000000..c77204a171 --- /dev/null +++ b/server/knowledge/api/models_private_sources.py @@ -0,0 +1,29 @@ +"""Private source input errors omit credentials, selected IDs and queries.""" + +from typing import Any, Self + +from pydantic import BaseModel, ConfigDict, Field, ModelWrapValidatorHandler, model_validator +from pydantic import ValidationError as ModelValidationError + + +class PrivateSourceInput(BaseModel): + model_config = ConfigDict(extra="forbid", hide_input_in_errors=True) + org: str = Field(description="The authenticated caller's organization.") + + @model_validator(mode="wrap") + @classmethod + def _redact_errors(cls, value: Any, handler: ModelWrapValidatorHandler[Self]) -> Self: + try: + return handler(value) + except ModelValidationError: + raise ModelValidationError.from_exception_data( + cls.__name__, + [ + { + "type": "value_error", + "loc": (), + "input": "", + "ctx": {"error": ValueError("PRIVATE_SOURCE_INPUT_INVALID")}, + } + ], + ) from None diff --git a/server/knowledge/api/models_source_push.py b/server/knowledge/api/models_source_push.py deleted file mode 100644 index 037b0115ec..0000000000 --- a/server/knowledge/api/models_source_push.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Admin setup for provider notifications; source reads never reveal this state.""" - -from __future__ import annotations - -from pydantic import BaseModel, Field - - -class PushSourceInput(BaseModel): - org: str = Field(..., description="The org.") - namespace: str = Field(..., description="The source's namespace.") - name: str = Field(..., max_length=100, description="The registered source name.") - - -class PushConfigureInput(PushSourceInput): - """Enable provider sync hints for an existing source, or disable its setup. - Polling remains enabled. Requires a namespace admin and a configured HTTPS - public base URL. Drive creates bounded change channels; Notion requires - manual verification before confirmation; Linear takes its webhook secret - at confirmation after the provider has its notification address.""" - - enabled: bool = Field(default=True, description="Enable a fresh setup; false disables push.") - agent: str = Field(default="-", description="The configuring agent, default '-'.") - user_id: str = Field(default="-", description="The configuring user, default '-'.") - session_id: str = Field(default="-", description="The configuring session, default '-'.") - - -class PushStatusInput(PushSourceInput): - """Read push setup as a namespace admin. - - Explicit reveal returns only a pending Notion verification token, for copying - to the provider's verification form. - """ - - reveal_challenge: bool = Field( - default=False, description="Reveal a pending Notion challenge, default false." - ) - - -class PushConfirmInput(PushSourceInput): - """Activate the exact pending setup. - - For Notion, first verify in the provider UI and name the inspected challenge - fingerprint. For Linear, supply the signing secret of the webhook created - with this generation's notification address. - """ - - generation: str = Field(..., max_length=36, description="The pending setup generation.") - challenge_fingerprint: str = Field( - default="", - max_length=64, - description="The inspected Notion challenge's SHA-256 fingerprint; empty for Linear.", - ) - signing_secret: str = Field( - default="", - max_length=512, - repr=False, - description="The Linear webhook signing secret; empty for Notion.", - ) - - -class PushStatusOutput(BaseModel): - enabled: bool = False - status: str = "disabled" - provider: str = "" - generation: str = "" - callback_url: str = "" - provider_id: str = "" - challenge_fingerprint: str = "" - verification_token: str = Field(default="", repr=False) - channels: int = 0 - expires_at: float = 0 diff --git a/server/knowledge/api/models_sources.py b/server/knowledge/api/models_sources.py index 2a8c6c7e06..5e778ef670 100644 --- a/server/knowledge/api/models_sources.py +++ b/server/knowledge/api/models_sources.py @@ -3,40 +3,22 @@ from __future__ import annotations -from typing import Annotated, Any, Literal +from typing import Any, Literal -from pydantic import BaseModel, Field +from pydantic import BaseModel, ConfigDict, Field -from server.knowledge.domain.sources import ( - MAX_DEPTH, - MAX_ITEMS, - MAX_PAGE_STORE_IDS, - MAX_PROJECTS, - MAX_WALK_FOLDERS, -) - -# A pasted link is short; anything longer is no link to a folder or a page. -MAX_LINK_CHARS = 2048 # not a setting: the wire's bound on one link -_Link = Annotated[str, Field(max_length=MAX_LINK_CHARS)] +from server.knowledge.api.models_private_sources import PrivateSourceInput class KnowledgeSourceProbe(BaseModel): """What a probe that succeeded found; a probe that fails refuses the call.""" - # Documents the source lists now: the first page, 1000 at most, of the folders, of - # each shared drive and of each filter, and each file item (gdrive); at most 1000 - # (recording); each project's first page (linear); the listed pages and the first - # 100 pages of each of up to three databases (notion). + # Selected recordings found, at most 1000; `more` marks a lower bound. documents: int = 0 # True when more documents match than were listed, so `documents` is a lower bound. more: bool = False # Up to five document titles, most recently changed first. sample: list[str] = Field(default_factory=list) - # Items the probe checked: every item of the probed set while there are at most 20, - # else the 20 given or added last. - checked: int = 0 - # True when the probed items were more than the 20 checked. - sampled: bool = False class KnowledgeSourceSync(BaseModel): @@ -101,10 +83,7 @@ class KnowledgeSourceSync(BaseModel): class KnowledgeSourceEntry(BaseModel): # The source's name, unique in the namespace. name: str - # The source's kind (`gdrive`: a shared folder of docs, slides, PDFs, .pptx decks - # and .docx documents; `linear`: a project tracker's project documents; `notion`: a - # page store's pages and databases; `recording`: the transcripts of a meeting - # store's recordings). + # Recording, or an unavailable retained kind. kind: str # The registration's credential class; never the credential or account identity. credential_mode: str = "shared" @@ -112,13 +91,7 @@ class KnowledgeSourceEntry(BaseModel): access: str = "namespace" # Canonical connected owner, only in the owner's permitted detail projection. owner_subject: str = "" - # The things the source reads (folders, files, shared drives, filters, pages, - # databases, projects); [] for a recording source. - items: list[dict[str, Any]] = Field(default_factory=list) - # The file kinds a gdrive source reads; [] for another kind. - include: list[str] = Field(default_factory=list) - # The source's config in the form that names ids per kind, or {} when an item - # has no place in it; never a credential. + # Recording provider and selected IDs; {} for an unavailable retained source. config: dict[str, Any] = Field(default_factory=dict) # Token subject of the admin who added it; '' with auth off. created_by: str = "" @@ -147,85 +120,28 @@ class KnowledgeSourceListOutput(BaseModel): accepts_sources: bool = True -_ITEMS_DESCRIPTION = ( - f"The things the source reads, each an object with a `type`: " - f"1-{MAX_ITEMS} for gdrive, 1-{MAX_PROJECTS} for linear and 1-{MAX_PAGE_STORE_IDS} " - f"for notion; gdrive: " - f"{{type: folder, id, recursive (default false; subfolders to a depth of " - f"{MAX_DEPTH}, at most {MAX_WALK_FOLDERS} subfolders per source)}}, " - f"{{type: file, id}}, " - f"{{type: shared_drive, id}} (a folder of the same id given beside it adds nothing), " - f"{{type: filter, any of name_contains (the store matches it at the start of a word in " - f"the name), kinds (as include), modified_after (YYYY-MM-DD), in (a folder id)}}; " - f"notion: {{type: page | database, id}}; " - f"linear: {{type: project, id (a UUID) or slug_id (the 12 hex characters a project " - f"link ends with)}}." -) -_LINKS_DESCRIPTION = ( - "Links to folders, files, documents, slides, pages, databases or projects, read as " - "items (`knowledge.source.parse_links`); an unreadable link refuses the call (BAD_LINK)." -) - - -class KnowledgeSourceAddInput(BaseModel): - """Register a document source on a namespace: a kind, what it reads (items - and links, or a config) and a read-only credential. A namespace admin may. The - credential is probed (a check of every item, or of the 20 given last, and a - listing) before anything is stored; a probe that fails stores nothing. A name is - refused while documents the sync worker wrote for an earlier source of that name - are live. The credential is stored encrypted and never returned.""" +class KnowledgeSourceAddInput(PrivateSourceInput): + """Register a shared recording source after checking its read-only credential.""" - org: str = Field(..., description="The org.") - namespace: str = Field( - ..., - description=( - "The namespace or collection the documents live in; a person's own " - "(personal-…, single sign-on u--, col-me-…, or one claimed at " - "sign-up) is refused." - ), - ) + model_config = ConfigDict(extra="ignore", hide_input_in_errors=True) + + namespace: str = Field(description="An ordinary destination namespace or collection.") name: str = Field( - ..., - description="Source name: 2-32 lower-case letters, digits, - or _, starting with a " - "letter; trimmed and lower-cased.", - ) - kind: str = Field( - ..., - description="The source kind: `gdrive` (a shared-folder store), `linear` (a project " - "tracker's project documents), `notion` (a page store's pages and databases) or " - "`recording` (Zoom recording transcripts). Meet transcripts and notes use `gdrive`.", - ) - items: list[dict[str, Any]] | None = Field( - None, max_length=MAX_ITEMS, description=_ITEMS_DESCRIPTION - ) - links: list[_Link] | None = Field(None, max_length=MAX_ITEMS, description=_LINKS_DESCRIPTION) - config: dict[str, Any] | None = Field( - None, - description="What the source reads in the form that names ids per kind, instead of " - "items or links; gdrive: {folder_ids: [1-20 folder ids], include: [docs, slides, pdf, " - "pptx, docx] (default all but docx)}; linear: {project_ids: [1-20 project ids, " - "UUIDs]}; notion: {page_ids: [...], database_ids: [...]} (1-20 ids in all); " - "recording (config only): {provider: zoom, ids: [1-20 meeting ids]}.", + description="Source name: 2-32 lower-case letters, digits, - or _, starting with a letter." ) - include: list[str] | None = Field( - None, - description="gdrive with items or links: the file kinds read, of docs, slides, pdf, " - "pptx, docx (default all but docx).", - ) - credential_mode: Literal["shared", "connected"] = Field( - "shared", - description="Use the supplied shared credential, or your own mirrored connected account.", + kind: Literal["recording"] = "recording" + config: dict[str, Any] = Field( + description="Recording provider and explicitly selected recording IDs." ) credential: str = Field( - "", - description="The source's read-only credential (gdrive: a service account's JSON key, " - "with the folders shared to the account read-only; linear: a read-only API key of an " - "account that sees the projects; notion: an integration token with read content " - "access, the pages and databases shared to it; recording: a server-to-server app's " - "{account_id, client_id, client_secret} with read-only " - "scopes); stored encrypted, never returned.", + min_length=1, + repr=False, + exclude=True, + description="Read-only recording credential; sealed and never returned.", + ) + dry_run: bool = Field( + default=False, description="Check the credential and selection without saving." ) - dry_run: bool = Field(False, description="Probe and write nothing.") class KnowledgeSourceAddOutput(BaseModel): @@ -235,11 +151,7 @@ class KnowledgeSourceAddOutput(BaseModel): kind: str # The namespace the source was registered on. namespace: str - # The items as stored; [] for a recording source. - items: list[dict[str, Any]] = Field(default_factory=list) - # The file kinds a gdrive source reads; [] for another kind. - include: list[str] = Field(default_factory=list) - # The config in the form that names ids per kind, or {} when an item has no place in it. + # Recording provider and selected IDs; {} for an unavailable retained source. config: dict[str, Any] = Field(default_factory=dict) # What the probe with the credential found. probe: KnowledgeSourceProbe = Field(default_factory=KnowledgeSourceProbe) @@ -247,106 +159,8 @@ class KnowledgeSourceAddOutput(BaseModel): dry_run: bool = False -class KnowledgeSourceUpdateInput(BaseModel): - """Add items to a registered document source or remove them, or change a gdrive - source's file kinds. A namespace admin may. The added items are probed with the - stored credential (every one, or the 20 given last) before anything is stored, and - a changed `include` probes the file items the source keeps; a probe that fails - stores nothing. Removing every item is refused: remove the source instead.""" - - org: str = Field(..., description="The org.") - namespace: str = Field(..., description="The namespace the source's documents live in.") - name: str = Field(..., description="The source name.") - add_items: list[dict[str, Any]] = Field( - default_factory=list, - max_length=MAX_ITEMS, - description="Items to add, of the forms add takes; one of the same type and id " - "replaces the stored one, and a folder of the id of a shared drive the source keeps " - "or is given adds nothing.", - ) - add_links: list[_Link] = Field( - default_factory=list, - max_length=MAX_ITEMS, - description=( - "Links to add, read as items; a link to something the source holds names it as " - "held (a recursive folder, a drive at its root), and an add_items entry for the " - "same thing wins." - ), - ) - remove_items: list[dict[str, Any]] = Field( - default_factory=list, - max_length=MAX_ITEMS, - description=( - "Items to remove, matched by type and id (a filter by its fields); a folder " - "entry also removes a shared drive of the same id the source holds. One the " - "source does not hold is refused (BAD_CONFIG), so a retry after a timeout " - "inspects the source first." - ), - ) - remove_links: list[_Link] = Field( - default_factory=list, - max_length=MAX_ITEMS, - description=( - "Links to remove, read as items; a folder link also removes a shared drive of " - "the same id the source holds." - ), - ) - include: list[str] | None = Field( - None, - description="gdrive only: the new file kinds read, of docs, slides, pdf, pptx, docx; " - "default unchanged.", - ) - - -class KnowledgeSourceUpdateOutput(BaseModel): - # The source updated. - name: str - # The source's items as now stored. - items: list[dict[str, Any]] = Field(default_factory=list) - # The file kinds a gdrive source reads; [] for another kind. - include: list[str] = Field(default_factory=list) - # The config in the form that names ids per kind, or {} when an item has no place in it. - config: dict[str, Any] = Field(default_factory=dict) - # The items this call added. - added: list[dict[str, Any]] = Field(default_factory=list) - # The items this call removed, as the source held them. - removed: list[dict[str, Any]] = Field(default_factory=list) - # What the probe of the added items found, or with none added, of the kept file items - # a changed `include` probes; nothing checked when neither ran. - probe: KnowledgeSourceProbe = Field(default_factory=KnowledgeSourceProbe) - - -class KnowledgeSourceParseLinksInput(BaseModel): - """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. - Any reader of the namespace may.""" - - org: str = Field(..., description="The org.") - namespace: str = Field(..., description="The namespace the source would live in.") - links: list[_Link] = Field( - ..., min_length=1, max_length=MAX_ITEMS, description=f"1-{MAX_ITEMS} links." - ) - - -class KnowledgeSourceParsedLink(BaseModel): - # The link as given. - link: str - # The source kind that reads it (gdrive, notion, linear); '' when unreadable. - kind: str = "" - # The item it names; {} when unreadable. - item: dict[str, Any] = Field(default_factory=dict) - # Why the link names no item (another host, no id, a spreadsheet, a single - # issue); '' when it does. - unreadable: str = "" - - -class KnowledgeSourceParseLinksOutput(BaseModel): - # Each link, in the order given. - links: list[KnowledgeSourceParsedLink] = Field(default_factory=list) - - class KnowledgeSourceInspectInput(BaseModel): - """One registered document source: its items, its sync state and the + """One registered document source: its config, its sync state and the documents it wrote (the 200 most recently ingested). Any reader of the namespace may; the credential is never returned.""" @@ -377,12 +191,7 @@ class KnowledgeSourceInspectOutput(BaseModel): access: str = "namespace" # Canonical connected owner, only in the owner's permitted detail projection. owner_subject: str = "" - # The things the source reads; [] for a recording source. - items: list[dict[str, Any]] = Field(default_factory=list) - # The file kinds a gdrive source reads; [] for another kind. - include: list[str] = Field(default_factory=list) - # The source's config in the form that names ids per kind, or {} when an item - # has no place in it; never a credential. + # Recording provider and selected IDs; {} for an unavailable retained source. config: dict[str, Any] = Field(default_factory=dict) # Token subject of the admin who added it; '' with auth off. created_by: str = "" @@ -395,10 +204,10 @@ class KnowledgeSourceInspectOutput(BaseModel): class KnowledgeSourceCheckInput(BaseModel): - """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. A namespace - admin may; a connected owner may also check their own source. An administrator - checking another person's connection receives source-level standing only.""" + """Probe a shared recording with its stored credential without writing. + + A namespace admin may check; unavailable retained sources refuse the probe. + """ org: str = Field(..., description="The org.") namespace: str = Field(..., description="The namespace the source's documents live in.") @@ -410,27 +219,19 @@ class KnowledgeSourceCheckOutput(BaseModel): name: str # False when the probe failed; `summary` says why. reachable: bool = True - # Documents the source lists now: the first page, 1000 at most, of the folders, of - # each shared drive and of each filter, and each file item (gdrive); at most 1000 - # (recording); each project's first page (linear); the listed pages and the first - # 100 pages of each of up to three databases (notion). + # Selected recordings found, at most 1000; `more` marks a lower bound. documents: int = 0 # True when more documents match than were listed, so `documents` is a lower bound. more: bool = False # Up to five document titles, most recently changed first. sample: list[str] = Field(default_factory=list) - # Items the probe checked: every item while there are at most 20, else the 20 - # added last. - checked: int = 0 - # True when the source holds more items than were checked. - sampled: bool = False # One line: what was found, or why it failed. summary: str = "" # When the probe ran, ISO UTC. checked_at: str = "" -class KnowledgeSourceRotateInput(BaseModel): +class KnowledgeSourceRotateInput(PrivateSourceInput): """Replace a registered document source's credential. A namespace admin may; the new credential is probed first, and a probe that fails stores nothing.""" diff --git a/server/knowledge/api/ops_connections.py b/server/knowledge/api/ops_connections.py deleted file mode 100644 index 146fda1271..0000000000 --- a/server/knowledge/api/ops_connections.py +++ /dev/null @@ -1,34 +0,0 @@ -"""Personal connected-account operations; their handlers derive ownership from auth.""" - -from server.knowledge.api.models_connections import ( - ConnectionDisconnectInput, - ConnectionDisconnectOutput, - ConnectionListInput, - ConnectionListOutput, -) -from server.knowledge.app.connections import handle_connection_disconnect, handle_connection_list -from server.operations.base import Operation, Role - -OPERATIONS: list[Operation] = [ - Operation( - name="connection.list", - input_model=ConnectionListInput, - output_model=ConnectionListOutput, - handler=handle_connection_list, - idempotent=True, - required_role=Role.VIEWER, - skip_namespace_authz=True, - maturity="experimental", - ), - Operation( - name="connection.disconnect", - input_model=ConnectionDisconnectInput, - output_model=ConnectionDisconnectOutput, - handler=handle_connection_disconnect, - idempotent=True, - required_role=Role.VIEWER, - skip_namespace_authz=True, - writes=True, - maturity="experimental", - ), -] diff --git a/server/knowledge/api/ops_mcp_connections.py b/server/knowledge/api/ops_mcp_connections.py index 2a8a81bff8..24827c2d6d 100644 --- a/server/knowledge/api/ops_mcp_connections.py +++ b/server/knowledge/api/ops_mcp_connections.py @@ -90,3 +90,22 @@ def _disconnect_audit(input: MCPSlotInput, output: MCPDisconnectOutput) -> dict[ maturity="experimental", ), ] + + +def _browse_operation() -> Operation: + from server.knowledge.api.models_mcp_connections import MCPBrowseInput, MCPBrowseOutput + from server.knowledge.app.mcp_browse import handle_mcp_browse + + return Operation( + name="knowledge.connection.mcp_browse", + input_model=MCPBrowseInput, + output_model=MCPBrowseOutput, + handler=handle_mcp_browse, + idempotent=True, + required_role=Role.VIEWER, + skip_namespace_authz=True, + maturity="experimental", + ) + + +OPERATIONS.append(_browse_operation()) diff --git a/server/knowledge/api/ops_mcp_reads.py b/server/knowledge/api/ops_mcp_reads.py new file mode 100644 index 0000000000..79344d7ce3 --- /dev/null +++ b/server/knowledge/api/ops_mcp_reads.py @@ -0,0 +1,17 @@ +"""Direct live reads require the selected source's current owner authority.""" + +from server.knowledge.api.models_mcp_reads import MCPReadInput, MCPReadOutput +from server.knowledge.app.mcp_browse import handle_mcp_read +from server.operations.base import Operation, Role + +OPERATIONS: list[Operation] = [ + Operation( + name="knowledge.source.mcp_read", + input_model=MCPReadInput, + output_model=MCPReadOutput, + handler=handle_mcp_read, + idempotent=True, + required_role=Role.VIEWER, + maturity="experimental", + ), +] diff --git a/server/knowledge/api/ops_source_push.py b/server/knowledge/api/ops_source_push.py deleted file mode 100644 index de4f47f65c..0000000000 --- a/server/knowledge/api/ops_source_push.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Namespace-admin setup for authenticated source sync notifications.""" - -from server.knowledge.api.models_source_push import ( - PushConfigureInput, - PushConfirmInput, - PushStatusInput, - PushStatusOutput, -) -from server.knowledge.app.source_push import ( - audit_subject, - handle_configure, - handle_confirm, - handle_status, -) -from server.operations.base import Operation, Role - -OPERATIONS = [ - Operation( - name="knowledge.source.push_configure", - maturity="experimental", - input_model=PushConfigureInput, - output_model=PushStatusOutput, - handler=handle_configure, - idempotent=False, - required_role=Role.ADMIN, - audit=True, - audit_subject=audit_subject, - ), - Operation( - name="knowledge.source.push_status", - maturity="experimental", - input_model=PushStatusInput, - output_model=PushStatusOutput, - handler=handle_status, - # A pending challenge must never enter the ordinary idempotency cache. - idempotent=False, - required_role=Role.ADMIN, - ), - Operation( - name="knowledge.source.push_confirm", - maturity="experimental", - input_model=PushConfirmInput, - output_model=PushStatusOutput, - handler=handle_confirm, - idempotent=False, - required_role=Role.ADMIN, - audit=True, - audit_subject=audit_subject, - ), -] diff --git a/server/knowledge/api/ops_sources.py b/server/knowledge/api/ops_sources.py index f9927632b0..04f13cee3b 100644 --- a/server/knowledge/api/ops_sources.py +++ b/server/knowledge/api/ops_sources.py @@ -1,8 +1,7 @@ -"""The `knowledge.source.*` operation declarations; their wire models are in -`models_sources`. Each op is addressed by the namespace the source's documents -live in, so the transport's namespace gate decides: readers list, inspect and -parse links; writers manage their connected sources, and shared sources require -namespace administration inside the handler.""" +"""Shared recording controls and generic retention through namespace grants. + +MCP registrations use their separate owner-bound protocol operations. +""" from __future__ import annotations @@ -15,30 +14,23 @@ KnowledgeSourceInspectOutput, KnowledgeSourceListInput, KnowledgeSourceListOutput, - KnowledgeSourceParseLinksInput, - KnowledgeSourceParseLinksOutput, KnowledgeSourceRemoveInput, KnowledgeSourceRemoveOutput, KnowledgeSourceRotateInput, KnowledgeSourceRotateOutput, KnowledgeSourceSyncNowInput, KnowledgeSourceSyncNowOutput, - KnowledgeSourceUpdateInput, - KnowledgeSourceUpdateOutput, ) from server.knowledge.app.sources import ( handle_knowledge_source_add, handle_knowledge_source_check, handle_knowledge_source_inspect, handle_knowledge_source_list, - handle_knowledge_source_parse_links, handle_knowledge_source_remove, handle_knowledge_source_rotate, handle_knowledge_source_sync_now, - handle_knowledge_source_update, source_add_audit_subject, source_rotate_audit_subject, - source_update_audit_subject, ) from server.operations.base import Operation, Role @@ -71,27 +63,7 @@ audit=True, audit_subject=source_add_audit_subject, ) -knowledge_source_update = Operation( - name="knowledge.source.update", - maturity="experimental", - input_model=KnowledgeSourceUpdateInput, - output_model=KnowledgeSourceUpdateOutput, - handler=handle_knowledge_source_update, - idempotent=False, - required_role=Role.WRITER, - audit=True, - audit_subject=source_update_audit_subject, -) # No store request and nothing written: a reader may preview what links name. -knowledge_source_parse_links = Operation( - name="knowledge.source.parse_links", - maturity="experimental", - input_model=KnowledgeSourceParseLinksInput, - output_model=KnowledgeSourceParseLinksOutput, - handler=handle_knowledge_source_parse_links, - idempotent=True, - required_role=Role.VIEWER, -) # The owner may probe their connection; other callers need namespace administration. knowledge_source_check = Operation( name="knowledge.source.check", @@ -138,8 +110,6 @@ knowledge_source_list, knowledge_source_inspect, knowledge_source_add, - knowledge_source_update, - knowledge_source_parse_links, knowledge_source_check, knowledge_source_rotate, knowledge_source_remove, diff --git a/server/knowledge/app/connected_accounts.py b/server/knowledge/app/connected_accounts.py index 646d3748d6..cbb54c4b0e 100644 --- a/server/knowledge/app/connected_accounts.py +++ b/server/knowledge/app/connected_accounts.py @@ -1,55 +1,35 @@ -"""Canonical-owner connection lifecycle and source-bound credential authority. - -Account changes precede namespace source leases. HTTP exchanges run outside both; -the connection identity and rotation reservation fence late completions. -""" +"""Canonical-owner connection standing, fencing and local credential erasure.""" from __future__ import annotations import asyncio import dataclasses import hashlib -import math import secrets import time -from collections.abc import AsyncIterator, Awaitable, Callable +from collections.abc import AsyncIterator from contextlib import asynccontextmanager from datetime import UTC, datetime -from typing import Any, SupportsIndex, TypeVar, cast +from typing import Any -from server.auth import aliases, authz, claims, revocation, scim -from server.auth.context import current_auth +from server.auth import aliases, claims, revocation, scim from server.auth.jwt import AuthInfo -from server.auth.oauth_store import PENDING_TTL, ClickHouseStore, token_id from server.auth.reader_identity import reader_subject, resolve_reader -from server.clients._checked_access import CheckedAccess -from server.clients.connected_oauth import Kind, OAuthClient, OAuthError, Tokens -from server.core import leases, shielded -from server.core.ch import get_client, own_write_reads, set_query_tag +from server.core import leases +from server.core.ch import get_client, set_query_tag from server.core.errors import AuthInsufficientError, ValidationError -from server.core.secrets_at_rest import seal, unseal +from server.core.secrets_at_rest import unseal from server.knowledge.domain.connected_accounts import ( CREDENTIAL_PURPOSE, EMAIL_PURPOSE, - KINDS, - PKCE_PURPOSE, ConnectedAccount, - accepts_callback, - refreshing, - rotated, source_account_key, - source_matches, stopped, ) -from server.knowledge.domain.sources import MIRRORED_ACCESS, KnowledgeSource, opaque_payload from server.knowledge.store import connected_accounts as store from server.knowledge.store import sources as source_store -from server.observability import audit -from server.operations.base import Role from server.settings import settings -pending_store = ClickHouseStore() -_T = TypeVar("_T") # KeeperMap's UInt32 epoch ceiling; a registration's fence never expires while it lives. _FENCE_EXPIRY = 2**32 - 1 @@ -109,23 +89,6 @@ async def _move_fence(previous: str | None, current: str, *, ch: Any = None) -> raise unavailable() -def client(kind: str) -> OAuthClient: - if kind == "gdrive": - ident, secret = settings.connect_gdrive_client_id, settings.connect_gdrive_client_secret - elif kind == "notion": - if not settings.connect_notion_read_content_only: - raise unavailable() - ident, secret = settings.connect_notion_client_id, settings.connect_notion_client_secret - elif kind == "linear": - ident, secret = settings.connect_linear_client_id, settings.connect_linear_client_secret - else: - raise unavailable() - try: - return OAuthClient(cast(Kind, kind), ident, secret, settings.public_base_url) - except OAuthError: - raise unavailable() from None - - @asynccontextmanager async def account_lease( org: str, subject: str, kind: str, *, ch: Any = None @@ -156,26 +119,6 @@ async def _standing(org: str, subject: str, since: int, keys: tuple[str, ...] = raise OwnerUnavailable() -def _primary(auth: AuthInfo | None) -> AuthInfo: - if ( - auth is None - or not settings.auth_actually_required() - or not auth.session_id - or not auth.first_party - or auth.is_service_account - or auth.impersonated_by - or auth.creator - or auth.parents - or auth.agent_principal - or auth.read_user_id - or auth.reads_as_creator - or auth.issued_at is None - or auth.org in ("", "*") - ): - raise AuthInsufficientError("a primary sign-in session is required") - return auth - - async def own_subject(auth: AuthInfo | None) -> tuple[str, str]: subject = reader_subject(auth) if ( @@ -199,154 +142,6 @@ async def own_subject(auth: AuthInfo | None) -> tuple[str, str]: return auth.org, canonical -async def start(auth: AuthInfo | None, kind: str) -> tuple[str, str, str]: - auth = _primary(auth) - provider = client(kind) # Missing configuration does no Keeper or provider work. - seal(CREDENTIAL_PURPOSE, "sealable") - org, subject = await own_subject(auth) - state, binding = secrets.token_urlsafe(32), secrets.token_urlsafe(32) - verifier = secrets.token_urlsafe(48) if kind != "notion" else "" - async with account_lease(org, subject, kind): - current = await store.get(org, subject, kind) - if current is None: - current = ConnectedAccount(org, subject, kind, _next_connection()) - await _move_fence(None, current.connection_id) - await store.put(current) - if not await _fence_current(current): - raise unavailable() - expected = current.connection_id - await pending_store.save_pending( - "connect:" + token_id(state), - { - "kind": "connected_account", - "provider": kind, - "org": org, - "subject": subject, - "binding": token_id(binding), - "session_id": auth.session_id, - "token_id": auth.token_id, - "issued_at": auth.issued_at, - "expires_at": auth.expires_at, - "expected_connection": expected, - "client_id": provider.client_id, - "redirect_uri": provider.redirect_uri, - "verifier_enc": seal(PKCE_PURPOSE, verifier), - }, - ttl=PENDING_TTL, - ) - return provider.authorization_url(state, verifier=verifier or None), state, binding - - -async def _pending_standing(pending: dict[str, Any]) -> None: - expires = pending.get("expires_at") - if expires is not None and (not isinstance(expires, int) or expires <= time.time()): - raise unavailable() - await _standing( - pending["org"], - pending["subject"], - pending["issued_at"], - (pending["session_id"], pending["token_id"]), - ) - - -async def verified_callback_pending( - kind: str, state: str, binding: str -) -> tuple[str, dict[str, Any]]: - """Read browser-bound pending authority without consuming it or calling a provider.""" - provider = client(kind) - if not state or len(state) > 256 or not binding: - raise unavailable() - key = "connect:" + token_id(state) - pending = await pending_store.pending(key) - if ( - pending is None - or pending.get("kind") != "connected_account" - or pending.get("provider") != kind - or pending.get("client_id") != provider.client_id - or pending.get("redirect_uri") != provider.redirect_uri - or not isinstance(pending.get("org"), str) - or not pending["org"] - or not secrets.compare_digest(str(pending.get("binding") or ""), token_id(binding)) - ): - raise unavailable() - return key, pending - - -async def callback(kind: str, state: str, binding: str, code: str, *, denied: bool = False) -> None: - deadline = time.monotonic() + settings.knowledge_connected_oauth_timeout_s - async with asyncio.timeout_at(deadline): - await _callback(kind, state, binding, code, denied=denied, deadline=deadline) - - -async def _callback( - kind: str, state: str, binding: str, code: str, *, denied: bool, deadline: float -) -> None: - provider = client(kind) - key, pending = await verified_callback_pending(kind, state, binding) - consumed = await pending_store.take_pending(key) - if consumed is None or denied or not code or len(code) > 8192: - raise unavailable() - pending = consumed - await _pending_standing(pending) - org, subject = pending["org"], pending["subject"] - async with account_lease(org, subject, kind): - current = await store.get(org, subject, kind) - if ( - current is None - or not accepts_callback(current, pending["expected_connection"]) - or not await _fence_current(current) - ): - raise unavailable() - verifier = unseal(PKCE_PURPOSE, pending["verifier_enc"], warn=False) - if kind != "notion" and not verifier: - raise unavailable() - grant = await provider.exchange(code, verifier=verifier or None, deadline=deadline) - old: ConnectedAccount | None = None - old_credential = "" - async with account_lease(org, subject, kind): - await _pending_standing(pending) - current = await store.get(org, subject, kind) - if ( - current is None - or not accepts_callback(current, pending["expected_connection"]) - or not await _fence_current(current) - ): - raise unavailable() - # First fence the old registration, then all of its source ids, before replacing it. - old = current - old_credential = unseal(CREDENTIAL_PURPOSE, current.credential_enc, warn=False) or "" - ended = await _stop_locked(current, strict=True) - account = ConnectedAccount( - org, - subject, - kind, - _next_connection(ended.connection_id), - account_id=grant.account_id, - workspace_id=grant.workspace_id or "", - scopes=grant.tokens.scopes, - account_email_enc=seal(EMAIL_PURPOSE, grant.display_email or ""), - credential_enc=seal(CREDENTIAL_PURPOSE, grant.tokens.refresh_token), - active=True, - connected_at=datetime.now(UTC), - ) - await store.put(account) - await _move_fence(ended.connection_id, account.connection_id) - # Google's revoke ends the user's project grant, including a replacement for that - # same provider identity. Such a reconnect keeps its grant and drops the old secret. - if old is not None and (old.account_id, old.workspace_id) != ( - account.account_id, - account.workspace_id, - ): - await _revoke(old, credential=old_credential, deadline=deadline) - await audit.emit( - "connection.connected", - org=org, - namespace="-", - actor=subject, - subject={"kind": kind, "subject": subject, "scopes": list(account.scopes)}, - ) - - async def _stop_locked(account: ConnectedAccount, *, strict: bool = False) -> ConnectedAccount: from server.knowledge.app import source_push from server.knowledge.app import sources as source_ops @@ -452,51 +247,6 @@ async def _erase_locked(account: ConnectedAccount, *, keep_marker: bool) -> None ) -async def _revoke( - account: ConnectedAccount, *, credential: str, deadline: float | None = None -) -> None: - if not credential or account.kind not in KINDS: - return - try: - provider = client(account.kind) - limit = time.monotonic() + settings.knowledge_connected_revoke_timeout_s - deadline = min(deadline, limit) if deadline is not None else limit - async with asyncio.timeout_at(deadline): - if account.kind == "notion": - # The provider revokes an access token, not a refresh token. Mint only - # after local inactivation; the rotated pair is never persisted. - tokens = await provider.refresh( - credential, scopes=account.scopes, deadline=deadline - ) - await provider.revoke(tokens.access_token, refresh=False, deadline=deadline) - else: - await provider.revoke(credential, refresh=True, deadline=deadline) - except (OAuthError, TimeoutError, ValidationError): - return # Local inactivation and cleared credentials are already durable. - - -async def disconnect(org: str, subject: str, kind: str) -> None: - if kind not in KINDS: - raise unavailable() - set_query_tag("knowledge.connected_accounts.disconnect") - async with asyncio.timeout(settings.knowledge_connected_stop_timeout_s): - async with account_lease(org, subject, kind): - account = await store.get(org, subject, kind) - if account is None: - account = ConnectedAccount(org, subject, kind, _next_connection()) - await _move_fence(None, account.connection_id) - credential = unseal(CREDENTIAL_PURPOSE, account.credential_enc, warn=False) or "" - await _stop_locked(account) - await _revoke(account, credential=credential) - await audit.emit( - "connection.disconnected", - org=org, - namespace="-", - actor=subject, - subject={"kind": kind, "subject": subject}, - ) - - async def _owner_cutoff_allows( owner: tuple[str, str, str], current: ConnectedAccount | None ) -> bool: @@ -521,14 +271,17 @@ async def stop_subjects( erase_owner: bool = False, respect_cutoff: bool = False, ) -> None: - """Revocation callers pass every spelling they covered, including repeat/error tails.""" + """Fence local accounts for every covered spelling, including repeat/error tails. + + The lifecycle hook's revoke flag never dispatches provider HTTP. Upstream + credential revocation requires the owner's provider administration tools. + """ set_query_tag("knowledge.connected_accounts.stop_subjects") - ended = [] async with asyncio.timeout(settings.knowledge_connected_stop_timeout_s): if erase_owner: from server.knowledge.app.connected_restore import erase_subjects - ended = await erase_subjects( + await erase_subjects( subjects, org=org, respect_cutoff=respect_cutoff, revoke=revoke, ch=get_client() ) else: @@ -558,419 +311,7 @@ async def stop_subjects( ) if not any(revocation.kills(row, since) for row in cutoffs.values()): continue - credential = ( - unseal(CREDENTIAL_PURPOSE, current.credential_enc, warn=False) or "" - if revoke - else "" - ) await _stop_locked(current) - ended.append((current, credential)) - if not revoke: - return - # All local owners and sources are fenced before the first slow provider call. - deadline = time.monotonic() + settings.knowledge_connected_revoke_timeout_s - for account, credential in ended: - await _revoke(account, credential=credential, deadline=deadline) - - -async def _source_standing(source: KnowledgeSource, account: ConnectedAccount) -> None: - from server.knowledge.app import sources as source_ops - - if opaque_payload( - kind=source.kind, mode=source.credential_mode, version=source.source_contract_version - ): - raise unavailable() - if ( - account.org != source.org - or account.subject != source.owner_subject - or account.kind != source.kind - ): - raise unavailable() - if not account.active or account.connection_id != source.connection_id: - raise OwnerUnavailable() - if ( - source.credential_mode != "connected" - or source.access != MIRRORED_ACCESS - or not settings.auth_actually_required() - or not settings.knowledge_mirrored_sources_enabled - or not source.owner_subject - or not source.active - or not source_matches( - account, - org=source.org, - owner=source.owner_subject, - kind=source.kind, - connection_id=source.connection_id, - ) - ): - raise unavailable() - await _require_source_fence(account) - since = int(account.connected_at.timestamp()) if account.connected_at else 0 - await _standing(source.org, source.owner_subject, since) - # Invalidate the alias cache after an uncached verified tie read; the existing grant - # contract then reads this person's current spellings rather than a departed alias. - await aliases.verified_spellings(source.org, source.owner_subject) - aliases.invalidate(source.org, [source.owner_subject]) - with own_write_reads(): - role = await authz.grant_role_for(source.org, source.namespace, source.owner_subject) - current = await source_store.latest_source(source.org, source.namespace, source.name) - if role is None or role < Role.WRITER: - raise OwnerUnavailable() - if ( - current is None - or not current.active - or current.source_id != source.source_id - or current.connection_id != source.connection_id - or current.owner_subject != source.owner_subject - or current.kind != source.kind - or current.credential_mode != "connected" - or current.access != MIRRORED_ACCESS - or current.items != source.items - or current.config != source.config - or opaque_payload( - kind=current.kind, - mode=current.credential_mode, - version=current.source_contract_version, - ) - ): - raise unavailable() - await source_ops._require_source_namespace(source.org, source.namespace) - await source_ops._require_no_erasure(source.org, source.namespace) - await _require_source_fence(account) - - -@asynccontextmanager -async def publication_guard(source: KnowledgeSource) -> AsyncIterator[None]: - """Fence a durable publication against disconnect and source replacement. - - Provider and model waits precede this guard; only the bounded store commit holds - both leases, in the same account-before-namespace order as local retirement. - """ - from server.knowledge.app import sources as source_ops - - async with account_lease(source.org, source.owner_subject, source.kind): - async with source_ops.sources_lease(source.org, source.namespace): - account = await store.get(source.org, source.owner_subject, source.kind) - if account is None: - raise unavailable() - await _source_standing(source, account) - yield - - -async def _draft_standing(source: KnowledgeSource, account: ConnectedAccount) -> None: - """A probe may use its owner's connection before the new source row exists.""" - from server.knowledge.app import sources as source_ops - - auth = current_auth() - org, subject = await own_subject(auth) - if ( - org != source.org - or subject != source.owner_subject - or source.credential_mode != "connected" - or source.access != MIRRORED_ACCESS - or not source.active - or not settings.knowledge_mirrored_sources_enabled - or not source_matches( - account, - org=org, - owner=subject, - kind=source.kind, - connection_id=source.connection_id, - ) - or not await _fence_current(account) - or not await authz.row_in_scope(org, source.namespace, Role.WRITER) - ): - raise unavailable() - await aliases.verified_spellings(org, subject) - aliases.invalidate(org, [subject]) - with own_write_reads(): - role = await authz.grant_role_for(org, source.namespace, subject) - if role is None or role < Role.WRITER: - raise unavailable() - await source_ops._require_source_namespace(org, source.namespace) - await source_ops._require_no_erasure(org, source.namespace) - if current_auth() is not auth or not await _fence_current(account): - raise unavailable() - - -async def token_for( - source: KnowledgeSource, - *, - deadline: float, - pending: bool = False, - request_guard: Callable[[], Awaitable[None]] | None = None, -) -> tuple[Tokens, ConnectedAccount]: - """A source-bound, serialized rotation. Access material remains in memory only.""" - if not math.isfinite(deadline) or deadline <= time.monotonic(): - raise unavailable() - standing = _draft_standing if pending else _source_standing - provider = client(source.kind) - account: ConnectedAccount | None = None - reservation = "" - dispatched = False - try: - async with account_lease(source.org, source.owner_subject, source.kind): - account = await store.get(source.org, source.owner_subject, source.kind) - if account is None or account.refresh_id: - raise unavailable() - await standing(source, account) - if request_guard is not None: - await request_guard() - credential = unseal(CREDENTIAL_PURPOSE, account.credential_enc, warn=False) - if not credential: - raise unavailable() - reservation = secrets.token_hex(16) - await store.put(refreshing(account, refresh_id=reservation)) - if request_guard is not None: - await request_guard() - dispatched = True - tokens = await provider.refresh(credential, scopes=account.scopes, deadline=deadline) - async with account_lease(account.org, account.subject, account.kind): - current = await store.get(account.org, account.subject, account.kind) - if current is None or (current.org, current.subject, current.kind) != ( - account.org, - account.subject, - account.kind, - ): - raise unavailable() - # A returned rotation belongs to the owner, independently of the - # presenter's namespace role or the continued existence of this source. - since = int(current.connected_at.timestamp()) if current.connected_at else 0 - await _standing(current.org, current.subject, since) - await _require_source_fence(current) - try: - updated = rotated( - current, - expected_connection=account.connection_id, - refresh_id=reservation, - credential_enc=seal(CREDENTIAL_PURPOSE, tokens.refresh_token), - ) - except ValueError: - raise unavailable() from None - await store.put(updated) - except BaseException: # A lost rotating response cannot leave a reusable old secret. - if account is not None and reservation: - try: - await shielded.shielded( - _abort_refresh(account, reservation, dispatched=dispatched), - name="connected refresh cleanup", - ) - except Exception: # noqa: BLE001 — keep the original failure; its reservation refuses reuse - pass - raise - # Credential maintenance is complete. Delivery can still be refused without - # discarding the owner's valid rotation or stopping unrelated sources. - await standing(source, updated) - if request_guard is not None: - await request_guard() - return tokens, updated - - -async def checked_for( - source: KnowledgeSource, *, deadline: float, pending: bool = False -) -> CheckedAccess: - """Worker and registration probes retain the exact owner/source generation.""" - tokens, account = await token_for(source, deadline=deadline, pending=pending) - auth = current_auth() if pending else None - - async def validate() -> None: - if pending and current_auth() is not auth: - raise unavailable() - current = await store.get(account.org, account.subject, account.kind) - if current is None or current.connection_id != account.connection_id: - raise unavailable() - if pending: - await _draft_standing(source, current) - else: - await _source_standing(source, current) - - return CheckedAccess( - tokens.access_token, kind=cast(Kind, source.kind), deadline=deadline, validate=validate - ) - - -async def _abort_refresh(account: ConnectedAccount, reservation: str, *, dispatched: bool) -> None: - async with asyncio.timeout(settings.knowledge_connected_stop_timeout_s): - async with account_lease(account.org, account.subject, account.kind): - current = await store.get(account.org, account.subject, account.kind) - if ( - current is not None - and current.connection_id == account.connection_id - and current.refresh_id == reservation - ): - if dispatched: - await _stop_locked(current) - else: - # No provider request could have consumed the old refresh token. - await store.put(dataclasses.replace(current, refresh_id="")) - - -class SourceAuthority: - """An internal credential checkout bound to the selected source and requester.""" - - __slots__ = ("source", "requester", "_account", "_access", "_auth", "_deadline", "_role") - - def __init__( - self, - source: KnowledgeSource, - requester: str, - account: ConnectedAccount, - tokens: Tokens, - auth: AuthInfo, - deadline: float, - *, - required_role: Role = Role.VIEWER, - ) -> None: - self.source, self.requester = source, requester - self._account, self._auth = account, auth - self._deadline = deadline - self._role = required_role - self._access = CheckedAccess( - tokens.access_token, - kind=cast(Kind, source.kind), - deadline=deadline, - validate=self.validate, - ) - - def __repr__(self) -> str: - return "SourceAuthority()" - - async def validate(self) -> None: - if time.monotonic() >= self._deadline: - raise unavailable() - auth = current_auth() - if auth is not self._auth: - raise unavailable() - org, subject = await own_subject(auth) - if org != self.source.org or subject != self.requester: - raise unavailable() - if not await authz.row_in_scope(org, self.source.namespace, self._role): - raise unavailable() - current = await store.get(self._account.org, self._account.subject, self._account.kind) - if current is None or current.connection_id != self._account.connection_id: - raise unavailable() - await _source_standing(self.source, current) - await _requester_standing(self._auth, self.source, self.requester, self._role) - - def __reduce_ex__(self, protocol: SupportsIndex) -> Any: - raise TypeError("a connected authority cannot be serialized") - - async def run(self, call: Callable[[CheckedAccess], Awaitable[_T]]) -> _T: - async with asyncio.timeout_at(self._deadline): - await self.validate() - result = await call(self._access) - await self.validate() - return result - - -async def resolve( - org: str, - namespace: str, - name: str, - *, - deadline: float, - expected_source_id: str = "", -) -> SourceAuthority: - if not math.isfinite(deadline) or deadline <= time.monotonic(): - raise unavailable() - auth = current_auth() - actual_org, subject = await own_subject(auth) - if actual_org != org or not await authz.row_in_scope(org, namespace, Role.VIEWER): - raise unavailable() - source = await source_store.get_source(org, namespace, name) - if ( - source is None - or source.owner_subject != subject - or (expected_source_id and source.source_id != expected_source_id) - ): - raise unavailable() - if auth is None: - raise unavailable() - - async def requester_standing() -> None: - await _requester_standing(auth, source, subject, Role.VIEWER) - - async with asyncio.timeout_at(deadline): - tokens, account = await token_for( - source, deadline=deadline, request_guard=requester_standing - ) - return SourceAuthority(source, subject, account, tokens, auth, deadline) - - -async def _requester_standing( - auth: AuthInfo, source: KnowledgeSource, requester: str, role: Role -) -> None: - if current_auth() is not auth: - raise unavailable() - org, subject = await own_subject(auth) - if ( - org != source.org - or subject != requester - or not await authz.row_in_scope(org, source.namespace, role) - or current_auth() is not auth - ): - raise unavailable() - - -async def resolve_probe(source: KnowledgeSource, *, deadline: float) -> SourceAuthority: - """An explicit administrative probe retains its caller's admin standing. - - This narrow control-plane exception never participates in live document checkout. - """ - if not math.isfinite(deadline) or deadline <= time.monotonic(): - raise unavailable() - auth = current_auth() - org, subject = await own_subject(auth) - if auth is None or org != source.org: - raise unavailable() - role = Role.WRITER if subject == source.owner_subject else Role.ADMIN - - async def requester_standing() -> None: - await _requester_standing(auth, source, subject, role) - - async with asyncio.timeout_at(deadline): - await requester_standing() - tokens, account = await token_for( - source, deadline=deadline, request_guard=requester_standing - ) - await requester_standing() - return SourceAuthority(source, subject, account, tokens, auth, deadline, required_role=role) - - -async def validate_indexed(source: KnowledgeSource, auth: AuthInfo | None) -> None: - """Indexed content needs current owner authority, without minting an access token.""" - if auth is None or current_auth() is not auth: - raise unavailable() - # The source owner's standing is independent of which admitted reader matches - # its stored ACL. Live provider checkout remains restricted by resolve(). - if auth.org != source.org: - raise unavailable() - if not await authz.row_in_scope(source.org, source.namespace, Role.VIEWER): - raise unavailable() - client(source.kind) - account = await store.get(source.org, source.owner_subject, source.kind) - if account is None or account.refresh_id: - raise unavailable() - await _source_standing(source, account) - if not unseal(CREDENTIAL_PURPOSE, account.credential_enc, warn=False): - raise unavailable() - if current_auth() is not auth: - raise unavailable() - - -async def available(account: ConnectedAccount) -> bool: - """An owner-visible active projection must honor the same authoritative fence.""" - if not account.active or not account.credential_enc: - return False - try: - client(account.kind) - since = int(account.connected_at.timestamp()) if account.connected_at else 0 - await _standing(account.org, account.subject, since) - return bool( - unseal(CREDENTIAL_PURPOSE, account.credential_enc, warn=False) - ) and await _fence_current(account) - except Exception: # noqa: BLE001 — unknown registration standing is never reported usable - return False async def reseal_registry( diff --git a/server/knowledge/app/connected_restore.py b/server/knowledge/app/connected_restore.py index 7ce78dd72d..d1df124c54 100644 --- a/server/knowledge/app/connected_restore.py +++ b/server/knowledge/app/connected_restore.py @@ -4,7 +4,6 @@ import asyncio import dataclasses -import time from collections import defaultdict from datetime import UTC, datetime from typing import Any @@ -12,13 +11,11 @@ from server.auth import aliases, claims from server.core import ch as ch_module from server.core.ch import set_query_tag -from server.core.secrets_at_rest import unseal from server.erasure.app.connected_accounts import require_restore_erased from server.knowledge.app import connected_accounts as accounts from server.knowledge.app import source_push from server.knowledge.app import sources as source_ops from server.knowledge.domain.connected_accounts import ( - CREDENTIAL_PURPOSE, ConnectedAccount, known_account_kind, source_account_key, @@ -158,31 +155,24 @@ async def _restore_owner( ch: Any, *, respect_cutoff: bool = False, - revoke: bool = True, -) -> tuple[ConnectedAccount, str] | None: +) -> None: async with accounts.account_lease(*owner, ch=ch): current = await account_store.get(*owner, ch=ch) if current is not None and (current.org, current.subject, current.kind) != owner: raise accounts.unavailable() if respect_cutoff and not await accounts._owner_cutoff_allows(owner, current): - return None + return keys, sources = await _metadata(ch, owner) if current is not None: keys.append((current.org, current.subject, current.kind, current.connection_id)) _include(groups, prefixes, keys) if not keys: - return None + return stopped: dict[str, str] = {} for connection in sorted(groups[owner]): key = accounts._fence_key(connection) if key not in stopped: stopped[key] = await _stop_key(connection, ch) - credential = "" - if revoke and current is not None and current.credential_enc: - try: - credential = unseal(CREDENTIAL_PURPOSE, current.credential_enc, warn=False) or "" - except Exception: # noqa: BLE001 — local deletion never depends on recovering a remote secret - pass registration = current.connection_id if current is not None else min(row[3] for row in keys) marker = ConnectedAccount(*owner, registration, disconnected_at=datetime.now(UTC)) # Retain an inventoried registration so recovery cannot expand its admitted workset. @@ -192,7 +182,6 @@ async def _restore_owner( ) await _retire_history(sources, ch) await accounts._erase_locked(ended, keep_marker=False) - return (current, credential) if current is not None else None async def _erasure_owners( @@ -226,23 +215,18 @@ async def _erasure_owners( async def erase_subjects( subjects: list[str], *, org: str | None, respect_cutoff: bool, revoke: bool, ch: Any -) -> list[tuple[ConnectedAccount, str]]: - """Owner-deletion callers authorize only their selected identities, never global restore.""" +) -> None: + """Erase selected identities locally; the lifecycle revoke flag permits no provider HTTP.""" if not subjects: - return [] + return owners = await _erasure_owners(subjects, org=org, respect_cutoff=respect_cutoff, ch=ch) groups: dict[Owner, set[str]] = defaultdict(set) prefixes: dict[str, Owner] = {} for owner in sorted(owners): keys, _sources = await _metadata(ch, owner) _include(groups, prefixes, keys) - ended = [] for owner in sorted(owners): - if account := await _restore_owner( - owner, groups, prefixes, ch, respect_cutoff=respect_cutoff, revoke=revoke - ): - ended.append(account) - return ended + await _restore_owner(owner, groups, prefixes, ch, respect_cutoff=respect_cutoff) async def restore_all(*, apply: bool, ch: Any) -> None: @@ -263,15 +247,10 @@ async def restore_all(*, apply: bool, ch: Any) -> None: _include(groups, prefixes, keys) if not apply: return - revocations = [] async with asyncio.timeout(settings.knowledge_connected_stop_timeout_s): for owner in sorted(groups): why = await offline_refusal(ch) if why: raise RuntimeError(why) - if ended := await _restore_owner(owner, groups, prefixes, ch): - revocations.append(ended) + await _restore_owner(owner, groups, prefixes, ch) await require_restore_erased(ch=ch) - deadline = time.monotonic() + settings.knowledge_connected_revoke_timeout_s - for account, credential in revocations: - await accounts._revoke(account, credential=credential, deadline=deadline) diff --git a/server/knowledge/app/connected_sources.py b/server/knowledge/app/connected_sources.py deleted file mode 100644 index a6cedfab41..0000000000 --- a/server/knowledge/app/connected_sources.py +++ /dev/null @@ -1,246 +0,0 @@ -"""Registration of an owner's mirrored source with a checked connection.""" - -from __future__ import annotations - -import dataclasses -import time -import uuid -from typing import Any - -from server.auth import authz, machines -from server.auth.context import current_auth -from server.clients._checked_access import CheckedAccess -from server.core import request_work -from server.core.ch import get_client, set_query_tag -from server.core.diagnostics import private_work -from server.core.errors import OverloadedError, ValidationError -from server.knowledge.api.models_sources import ( - KnowledgeSourceAddInput, - KnowledgeSourceAddOutput, - KnowledgeSourceCheckOutput, - KnowledgeSourceProbe, - KnowledgeSourceUpdateInput, - KnowledgeSourceUpdateOutput, -) -from server.knowledge.app import connected_accounts as accounts -from server.knowledge.app import sources as source_ops -from server.knowledge.domain import sources as domain -from server.knowledge.domain.connected_accounts import KINDS -from server.knowledge.domain.sources import KnowledgeSource -from server.knowledge.store import connected_accounts as account_store -from server.knowledge.store import sources as source_store -from server.operations.base import Role -from server.settings import settings - -# The first binary that understands the source's owner and connection fence. -_CONNECTIONS_MIGRATION = 111 - - -async def require_operator(source: KnowledgeSource) -> None: - """Local sync/retirement controls admit the owner or the namespace administrator.""" - auth = current_auth() - if source.credential_mode != "connected" or not request_work.mark_mirrored(): - raise accounts.unavailable() - if await authz.row_in_scope(source.org, source.namespace, Role.ADMIN): - if current_auth() is not auth: - raise accounts.unavailable() - return - org, owner = await accounts.own_subject(auth) - if ( - org != source.org - or owner != source.owner_subject - or not await authz.row_in_scope(org, source.namespace, Role.WRITER) - or current_auth() is not auth - ): - raise accounts.unavailable() - - -async def add( - input: KnowledgeSourceAddInput, - *, - name: str, - kind: str, - config: dict[str, Any], - items: list[dict[str, Any]], - sent: list[str], -) -> KnowledgeSourceAddOutput: - if not request_work.mark_mirrored(): - raise accounts.unavailable() - with private_work(): - return await _add(input, name=name, kind=kind, config=config, items=items, sent=sent) - - -async def _add( - input: KnowledgeSourceAddInput, - *, - name: str, - kind: str, - config: dict[str, Any], - items: list[dict[str, Any]], - sent: list[str], -) -> KnowledgeSourceAddOutput: - set_query_tag("knowledge.connected_sources.add") - accounts.client(kind) # An unconfigured provider refuses before credential access. - if input.credential or kind not in KINDS: - raise ValidationError( - "a connected source takes its own account, without a supplied credential", - code="CREDENTIAL_REFUSED", - ) - if not await machines.fleet_at(get_client(), _CONNECTIONS_MIGRATION): - raise OverloadedError( - "not every process enforces connected-source ownership yet; retry after the rollout", - retry_after_s=30, - ) - org, owner = await accounts.own_subject(current_auth()) - if org != input.org: - raise accounts.unavailable() - await source_ops._require_source_namespace(org, input.namespace) - await source_ops._require_no_erasure(org, input.namespace) - await source_ops._require_free(org, input.namespace, name, owner_subject=owner) - async with accounts.account_lease(org, owner, kind): - account = await account_store.get(org, owner, kind) - if account is None: - raise accounts.unavailable() - source = KnowledgeSource( - org=org, - namespace=input.namespace, - name=name, - kind=kind, - source_id=str(uuid.uuid4()), - config=config, - items=items, - access=domain.MIRRORED_ACCESS, - credential_mode="connected", - owner_subject=owner, - connection_id=account.connection_id, - created_by=owner, - ) - deadline = time.monotonic() + settings.knowledge_source_probe_timeout_s - access = await accounts.checked_for(source, deadline=deadline, pending=True) - items = domain.unique_items(await source_ops._resolved(kind, items, access)) - source_ops._require_count(kind, items, sent) - probe, items = await source_ops._probe_items(kind, items, config, access) - source = dataclasses.replace(source, items=items) - await access.check() - out = KnowledgeSourceAddOutput( - name=name, - kind=kind, - namespace=input.namespace, - items=items, - include=source_ops._answered_include(source), - config=domain.id_list_config(source) or {}, - probe=KnowledgeSourceProbe(checked=probe.checked, sampled=probe.sampled), - dry_run=input.dry_run, - ) - if input.dry_run: - return out - async with accounts.account_lease(org, owner, kind): - await access.check() - async with source_ops.sources_lease(org, input.namespace): - await access.check() - await source_ops._require_free(org, input.namespace, name, owner_subject=owner) - await source_store.write_state(org, input.namespace, name, state_value="", detail={}) - await source_store.insert_source(source) - return out - - -async def check(source: KnowledgeSource) -> KnowledgeSourceCheckOutput: - """A probe admits the owner or an administrator while retaining that caller's standing.""" - from server.knowledge.app import source_probes - - if not request_work.mark_mirrored(): - raise accounts.unavailable() - with private_work(): - deadline = time.monotonic() + settings.knowledge_source_probe_timeout_s - authority = await accounts.resolve_probe(source, deadline=deadline) - checked = source_probes.sample(source.items) - if authority.requester != source.owner_subject: - # An administrator may check source-level credential standing. Reading - # the owner's selected items would make item failures an existence oracle. - await authority.validate() - return KnowledgeSourceCheckOutput( - name=source.name, - reachable=True, - summary="the connected credential was accepted", - checked_at=source_ops._now_iso(), - ) - - async def probe(access: CheckedAccess) -> source_probes.Probe: - return await source_probes.probe(source.kind, source.config, access, items=checked) - - checked_at = source_ops._now_iso() - try: - await authority.run(probe) - except source_probes.CredentialRefused: - return KnowledgeSourceCheckOutput( - name=source.name, - reachable=False, - summary="the connected credential was refused", - checked_at=checked_at, - ) - except source_probes.SourceUnreachable: - return KnowledgeSourceCheckOutput( - name=source.name, - reachable=False, - summary="the connected source is unavailable", - checked_at=checked_at, - ) - return KnowledgeSourceCheckOutput( - name=source.name, - reachable=True, - checked=len(checked), - sampled=len(checked) < len(source.items), - summary="the connected source was reached", - checked_at=checked_at, - ) - - -async def update( - source: KnowledgeSource, input: KnowledgeSourceUpdateInput -) -> KnowledgeSourceUpdateOutput: - """Only the owner chooses new reads with their connection; provider waits hold no lease.""" - if not request_work.mark_mirrored(): - raise accounts.unavailable() - with private_work(): - deadline = time.monotonic() + settings.knowledge_source_probe_timeout_s - authority = await accounts.resolve( - source.org, - source.namespace, - source.name, - deadline=deadline, - expected_source_id=source.source_id, - ) - - async def prepare(access: CheckedAccess) -> source_ops._UpdatePlan | None: - return await source_ops._update_plan(source, input, credential=access) - - plan = await authority.run(prepare) - if plan is None: - return KnowledgeSourceUpdateOutput( - name=source.name, - items=source.items, - include=source_ops._answered_include(source), - config=domain.id_list_config(source) or {}, - ) - change = source_ops._updated(source, plan.added, plan.removed, plan.include) - async with accounts.publication_guard(source): - # The guard retains exactly the registration used by the probe, including - # its items and config; a replacement cannot inherit that result. - await authority.validate() - from server.knowledge.app.source_push import retire - - await retire(source) - await source_store.insert_source(change.source) - state = await source_ops._read_state(change.source) - await source_ops._update_state( - change.source, state, {"requested_at": source_ops._now_iso(), "full": True} - ) - return KnowledgeSourceUpdateOutput( - name=source.name, - items=change.source.items, - include=source_ops._answered_include(change.source), - config=domain.id_list_config(change.source) or {}, - added=change.added, - removed=change.removed, - probe=KnowledgeSourceProbe(checked=plan.probe.checked, sampled=plan.probe.sampled), - ) diff --git a/server/knowledge/app/connection_routes.py b/server/knowledge/app/connection_routes.py deleted file mode 100644 index c7e2e90941..0000000000 --- a/server/knowledge/app/connection_routes.py +++ /dev/null @@ -1,124 +0,0 @@ -"""Browser binding for personal provider consent; account authority lives in knowledge.""" - -from __future__ import annotations - -import asyncio -from urllib.parse import urlsplit - -from fastapi import APIRouter, FastAPI, Request -from fastapi.responses import JSONResponse, RedirectResponse, Response - -from server.auth import account_lifecycle, tenancy -from server.auth.bearer import missing_bearer, verify_bearer_header -from server.auth.oauth_store import PENDING_TTL, token_id -from server.clients.connected_oauth import OAuthError -from server.core import request_work -from server.core.diagnostics import private_work -from server.knowledge.app import connected_accounts as accounts -from server.settings import settings - -router = APIRouter() - - -def _cookie(state: str) -> str: - return "loom_connection_" + token_id(state)[:16] - - -@router.post("/v1/connect/{kind}/start") -async def start(kind: str, request: Request) -> JSONResponse: - auth = await verify_bearer_header(request.headers.get("Authorization")) - if auth is None: - raise missing_bearer() - # This route never applies an on-behalf header, including from a trusted caller. - if request.headers.get("X-Loom-On-Behalf-Of"): - raise accounts.unavailable() - url, state, binding = await accounts.start(auth, kind) - redirect = urlsplit(accounts.client(kind).redirect_uri) - response = JSONResponse({"authorization_url": url}, headers={"Cache-Control": "no-store"}) - response.set_cookie( - _cookie(state), - binding, - max_age=PENDING_TTL, - path=redirect.path, - secure=redirect.scheme == "https", - httponly=True, - samesite="lax", - ) - return response - - -@router.get("/v1/connect/{kind}/callback") -async def callback(kind: str, request: Request) -> Response: - # Preserve the privacy mark through middleware and access-log completion, - # including malformed requests whose URL still contains a code or state. - with request_work.bind(request_work.RequestWork()): - request_work.mark_mirrored() - with private_work(): - try: - async with asyncio.timeout(settings.knowledge_connected_oauth_timeout_s): - return await _callback(kind, request) - except (OAuthError, TimeoutError): - raise accounts.unavailable() from None - - -def _prefers_html(accept: str) -> bool: - """Prefer JSON on ties and wildcards; browsers explicitly prefer HTML.""" - ranges = [] - for part in accept.lower().split(","): - media, *params = part.strip().split(";") - quality = 1.0 - for param in params: - name, _, value = param.strip().partition("=") - if name == "q": - try: - quality = float(value) - except ValueError: - quality = 0.0 - if not 0 <= quality <= 1: - quality = 0.0 - ranges.append((media.strip(), quality)) - - def quality_for(media: str) -> float: - family = media.split("/")[0] + "/*" - matches = [ - (2 if name == media else 1 if name == family else 0, quality) - for name, quality in ranges - if name in (media, family, "*/*") - ] - return max(matches, default=(-1, 0.0))[1] - - return quality_for("text/html") > quality_for("application/json") - - -async def _callback(kind: str, request: Request) -> Response: - query = request.query_params - if any(len(query.getlist(key)) > 1 for key in ("state", "code", "error")): - raise accounts.unavailable() - state = query.get("state", "") - binding = request.cookies.get(_cookie(state), "") - _key, pending = await accounts.verified_callback_pending(kind, state, binding) - if not await tenancy.is_held(pending["org"]): - raise accounts.unavailable() - await accounts.callback( - kind, - state, - binding, - query.get("code", ""), - denied=bool(query.get("error")), - ) - headers = {"Cache-Control": "no-store", "Referrer-Policy": "no-referrer", "Vary": "Accept"} - response: Response - if _prefers_html(request.headers.get("accept", "")): - response = RedirectResponse( - "/settings/connected-accounts", status_code=302, headers=headers - ) - else: - response = JSONResponse({"connected": True}, headers=headers) - redirect = urlsplit(accounts.client(kind).redirect_uri) - response.delete_cookie(_cookie(state), path=redirect.path) - return response - - -def attach(app: FastAPI) -> None: - account_lifecycle.bind(accounts.stop_subjects) - app.include_router(router) diff --git a/server/knowledge/app/connections.py b/server/knowledge/app/connections.py deleted file mode 100644 index 45737c12ef..0000000000 --- a/server/knowledge/app/connections.py +++ /dev/null @@ -1,50 +0,0 @@ -"""Own-only connection operations, independent of namespace administration.""" - -from typing import Literal, cast - -from server.auth.context import current_auth -from server.core.secrets_at_rest import unseal -from server.knowledge.api.models_connections import ( - ConnectionDisconnectInput, - ConnectionDisconnectOutput, - ConnectionEntry, - ConnectionListInput, - ConnectionListOutput, -) -from server.knowledge.app import connected_accounts as accounts -from server.knowledge.domain.connected_accounts import EMAIL_PURPOSE, KINDS -from server.knowledge.store import connected_accounts as store -from server.settings import settings - - -async def handle_connection_list(input: ConnectionListInput) -> ConnectionListOutput: - org, subject = await accounts.own_subject(current_auth()) - if org != input.org: - raise accounts.unavailable() - found = {account.kind: account for account in await store.owned([subject], org=org)} - entries = [] - for kind in sorted(KINDS): - account = found.get(kind) - connected = account is not None and await accounts.available(account) - entries.append( - ConnectionEntry( - kind=cast(Literal["gdrive", "notion", "linear"], kind), - connected=connected, - account_email=(unseal(EMAIL_PURPOSE, account.account_email_enc, warn=False) or None) - if connected and account is not None - else None, - scopes=list(account.scopes) if connected and account is not None else [], - connect_url=f"{settings.public_base_url.rstrip('/')}/settings/connected-accounts?kind={kind}", - ) - ) - return ConnectionListOutput(connections=entries) - - -async def handle_connection_disconnect( - input: ConnectionDisconnectInput, -) -> ConnectionDisconnectOutput: - org, subject = await accounts.own_subject(current_auth()) - if org != input.org: - raise accounts.unavailable() - await accounts.disconnect(org, subject, input.kind) - return ConnectionDisconnectOutput(disconnected=True) diff --git a/server/knowledge/app/live_provider_search.py b/server/knowledge/app/live_provider_search.py deleted file mode 100644 index e58fc2434a..0000000000 --- a/server/knowledge/app/live_provider_search.py +++ /dev/null @@ -1,353 +0,0 @@ -"""Bounded native search within a connected source's registered corpus.""" - -from __future__ import annotations - -import asyncio -import math -import time -from dataclasses import dataclass -from datetime import UTC, datetime -from typing import Any, Literal -from urllib.parse import urlsplit, urlunsplit - -from server.clients import gdrive, notion -from server.clients._checked_access import CheckedAccess -from server.clients._http import get_client -from server.clients._vendor import VendorError, request_json -from server.core.ch import set_query_tag -from server.knowledge.domain.sources import ( - KnowledgeSource, - include_in, - include_mime_types, - item_ids, -) -from server.settings import settings - -_DRIVE_FILES = "https://www.googleapis.com/drive/v3/files" -_NOTION_API = "https://api.notion.com/v1" -_DRIVE_FIELDS = "id,name,webViewLink,mimeType,trashed,parents,driveId,modifiedTime" - - -@dataclass(frozen=True) -class LiveProviderHit: - id: str - title: str - url: str - provider: Literal["gdrive", "notion", "linear"] - content: str = "" - - -class SearchUnavailable(ValueError): - """The native search cannot establish a bounded source-scoped result.""" - - -def _deadline(source: KnowledgeSource, access: CheckedAccess, deadline: float) -> float: - if ( - not isinstance(access, CheckedAccess) - or source.kind != access.kind - or source.credential_mode != "connected" - or not math.isfinite(deadline) - or deadline <= time.monotonic() - ): - raise SearchUnavailable("live source is unavailable") - return min(deadline, access.deadline) - - -def _text(value: Any, limit: int) -> str: - if not isinstance(value, str): - return "" - return " ".join(value.split())[:limit] - - -def _hit( - provider: Literal["gdrive", "notion", "linear"], - ident: Any, - title: Any, - url: Any, -) -> LiveProviderHit | None: - if ( - not isinstance(ident, str) - or not ident - or len(ident) > 1024 - or any(ord(c) < 33 or ord(c) == 127 for c in ident) - or not isinstance(url, str) - or len(url) > 4096 - or any(ord(c) < 33 or ord(c) == 127 for c in url) - or "\\" in url - ): - return None - try: - parsed = urlsplit(url) - host = parsed.hostname or "" - allowed = { - "gdrive": host in {"drive.google.com", "docs.google.com"}, - "notion": host in {"notion.so", "www.notion.so"} or host.endswith(".notion.site"), - "linear": host == "linear.app", - }[provider] - if ( - parsed.scheme != "https" - or not allowed - or parsed.username is not None - or parsed.password is not None - or parsed.port not in (None, 443) - ): - return None - except ValueError: - return None - return LiveProviderHit( - id=ident, - title=_text(title, 1024), - url=urlunsplit((parsed.scheme, parsed.netloc, parsed.path, "", "")), - provider=provider, - ) - - -async def _json(access: CheckedAccess, method: str, url: str, **kwargs: Any) -> dict[str, Any]: - return await request_json( - get_client(), - method, - url, - "live search", - checked=access, - max_bytes=settings.knowledge_live_search_response_max_bytes, - **kwargs, - ) - - -def _drive_scope(source: KnowledgeSource, item: dict[str, Any]) -> tuple[str, str] | None: - types = include_mime_types(include_in(source.config), item.get("kinds")) - if not types: - return None - kind = item.get("type") - ident = item.get("id") - if kind == "filter": - return gdrive.filter_query(item, types), "" - if not isinstance(ident, str) or not gdrive.valid_file_id(ident): - return None - if kind == "folder": - # A bounded search covers direct children even for a recursive registration. - return gdrive.folder_query([ident], types), "" - if kind == "shared_drive": - return gdrive.drive_query(types), ident - # Drive's search language has no file-id equality term; never widen a file item. - return None - - -def _drive_member(source: KnowledgeSource, ident: str, row: dict[str, Any]) -> bool: - if row.get("trashed") is not False or row.get("mimeType") not in include_mime_types( - include_in(source.config) - ): - return False - parents = row.get("parents") - if not isinstance(parents, list) or any(not isinstance(p, str) for p in parents): - return False - for item in source.items: - kind = item.get("type") - if kind == "file" and item.get("id") == ident: - return True - if kind == "folder" and item.get("id") in parents: - return True - if kind == "shared_drive" and item.get("id") == row.get("driveId"): - return True - if kind != "filter": - continue - if row.get("mimeType") not in include_mime_types( - include_in(source.config), item.get("kinds") - ): - continue - if "in" in item and item["in"] not in parents: - continue - name, modified = row.get("name"), row.get("modifiedTime") - if "name_contains" in item and ( - not isinstance(name, str) - or not name.casefold().startswith(item["name_contains"].casefold()) - ): - continue - if "modified_after" in item: - if not isinstance(modified, str) or not gdrive.valid_stamp(modified): - continue - try: - at = datetime.fromisoformat(modified) - cutoff = datetime.fromisoformat(item["modified_after"]).replace(tzinfo=UTC) - except ValueError: - continue - if at <= cutoff: - continue - return True - return False - - -async def _drive( - source: KnowledgeSource, access: CheckedAccess, query: str, top_k: int -) -> list[LiveProviderHit]: - found: dict[str, LiveProviderHit] = {} - for item in source.items[: settings.knowledge_live_search_max_items]: - scope = _drive_scope(source, item) - if scope is None: - continue - clause, drive_id = scope - params = { - "q": f"({clause}) and fullText contains {gdrive.quoted(query)}", - "pageSize": str(top_k), - "fields": f"incompleteSearch,files({_DRIVE_FIELDS})", - "supportsAllDrives": "true", - "includeItemsFromAllDrives": "true", - "corpora": "drive" if drive_id else "user", - } - if drive_id: - params["driveId"] = drive_id - data = await _json(access, "GET", _DRIVE_FILES, params=params) - rows = data.get("files") - if data.get("incompleteSearch") is True: - continue - if not isinstance(rows, list) or len(rows) > top_k: - raise SearchUnavailable("invalid native search result") - for row in rows: - if not isinstance(row, dict): - continue - ident = row.get("id") - if not isinstance(ident, str) or not gdrive.valid_file_id(ident): - continue - if _drive_member(source, ident, row): - hit = _hit("gdrive", ident, row.get("name"), row.get("webViewLink")) - if hit is not None: - found.setdefault(hit.id, hit) - if len(found) >= top_k: - break - return list(found.values())[:top_k] - - -async def _notion_json( - access: CheckedAccess, method: str, path: str, **kwargs: Any -) -> dict[str, Any]: - await notion._pace(access) - return await _json( - access, - method, - _NOTION_API + path, - headers={"Notion-Version": notion.API_VERSION}, - **kwargs, - ) - - -async def _notion_member( - source: KnowledgeSource, access: CheckedAccess, row: dict[str, Any] -) -> bool: - pages = set(item_ids(source.items, "page")) - databases = set(item_ids(source.items, "database")) - max_ancestors = settings.knowledge_live_search_max_ancestors - for hop in range(max_ancestors + 1): - ident = row.get("id") - if ( - not isinstance(ident, str) - or not notion.valid_id(ident) - or row.get("in_trash") is not False - ): - return False - if row.get("object") == "page" and ident in pages: - return True - parent = row.get("parent") - if not isinstance(parent, dict): - return False - kind = parent.get("type") - if kind in {"database_id", "data_source_id"}: - return parent.get("database_id") in databases - if kind not in {"page_id", "block_id"}: - return False - ancestor = parent.get(kind) - if not isinstance(ancestor, str) or not notion.valid_id(ancestor): - return False - if hop == max_ancestors: - return False - path = "/pages/" if kind == "page_id" else "/blocks/" - row = await _notion_json(access, "GET", path + ancestor) - if row.get("id") != ancestor: - return False - return False - - -async def _notion( - source: KnowledgeSource, access: CheckedAccess, query: str, top_k: int -) -> list[LiveProviderHit]: - data = await _notion_json( - access, - "POST", - "/search", - json={ - "query": query, - "page_size": top_k, - "filter": {"property": "object", "value": "page"}, - }, - ) - rows = data.get("results") - if not isinstance(rows, list) or len(rows) > top_k: - raise SearchUnavailable("invalid native search result") - found: dict[str, LiveProviderHit] = {} - for row in rows: - if not isinstance(row, dict) or row.get("object") != "page": - continue - if await _notion_member(source, access, row): - hit = _hit("notion", row.get("id"), notion.title_of(row), row.get("url")) - if hit is not None: - found.setdefault(hit.id, hit) - return list(found.values())[:top_k] - - -async def search( - source: KnowledgeSource, - access: CheckedAccess, - query: str, - *, - top_k: int, - deadline: float, -) -> list[LiveProviderHit]: - """One bounded search; incomplete coverage is never evidence that a document is absent.""" - set_query_tag("knowledge.live.search") - stop = _deadline(source, access, deadline) - if not query.strip() or len(query) > 1000 or top_k < 1: - return [] - async with asyncio.timeout_at(stop): - await access.check() - if source.kind == "gdrive": - result = await _drive( - source, access, query, min(top_k, settings.knowledge_live_search_max_hits) - ) - elif source.kind == "notion": - result = await _notion( - source, access, query, min(top_k, settings.knowledge_live_search_max_hits) - ) - else: - raise SearchUnavailable("native search is unavailable for this source") - await access.check() - return result - - -async def revalidate( - source: KnowledgeSource, - access: CheckedAccess, - hit: LiveProviderHit, - *, - deadline: float, -) -> bool: - """Recheck the retained hit's current native membership without replacing it.""" - set_query_tag("knowledge.live.membership") - stop = _deadline(source, access, deadline) - if hit.provider != source.kind: - return False - async with asyncio.timeout_at(stop): - await access.check() - try: - if source.kind == "gdrive" and gdrive.valid_file_id(hit.id): - row = await _json( - access, - "GET", - _DRIVE_FILES + "/" + hit.id, - params={"fields": _DRIVE_FIELDS, "supportsAllDrives": "true"}, - ) - return row.get("id") == hit.id and _drive_member(source, hit.id, row) - if source.kind == "notion" and notion.valid_id(hit.id): - row = await _notion_json(access, "GET", "/pages/" + hit.id) - return row.get("id") == hit.id and await _notion_member(source, access, row) - except VendorError: - return False - return False diff --git a/server/knowledge/app/mcp_browse.py b/server/knowledge/app/mcp_browse.py new file mode 100644 index 0000000000..87d8e7c2a8 --- /dev/null +++ b/server/knowledge/app/mcp_browse.py @@ -0,0 +1,229 @@ +"""Protected metadata windows and direct reads of saved live selections.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +import time +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.diagnostics import private_work +from server.knowledge.api.models_mcp_connections import ( + MCPBrowseInput, + MCPBrowseItem, + MCPBrowseOutput, +) +from server.knowledge.api.models_mcp_reads import MCPReadInput, MCPReadOutput +from server.knowledge.app import mcp_connections as connections +from server.knowledge.app import mcp_live, session_admission +from server.knowledge.app.mcp_source_sessions import checked_session +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.store import connected_accounts as account_store +from server.knowledge.store import sources as source_store +from server.operations.base import Role +from server.settings import settings + +_LIMITATIONS = [ + "no_verified_remote_identity", + "no_acl_or_permission_sync_proof", + "no_deletion_or_complete_enumeration_proof", + "no_import_or_publication_grant", +] + + +def _context(org: str) -> AuthInfo: + auth = current_auth() + if ( + auth is None + 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) and not auth.answer_mirrors) + ): + raise connections._Refused("MCP_PROTECTED_SESSION_REQUIRED") + return auth + + +async def _admit(org: str) -> AuthInfo: + auth = _context(org) + if not request_tail.required_active() or not request_work.mark_mirrored(): + raise connections._Refused("MCP_PROTECTED_SESSION_REQUIRED") + await session_admission.require(auth) + if _context(org) is not auth: + raise connections._Refused("MCP_PROTECTED_SESSION_REQUIRED") + return auth + + +@dataclass(repr=False) +class _Publication: + org: str + auth: AuthInfo + validate: Callable[[], Awaitable[None]] + deadline: float + _checked: bool = False + + async def check(self) -> None: + self._checked = False + async with connections._errors(): + async with asyncio.timeout_at(self.deadline): + if _context(self.org) is not self.auth: + raise connections._Refused("MCP_PUBLICATION_UNAVAILABLE") + await session_admission.require(self.auth) + await self.validate() + if _context(self.org) is not self.auth: + raise connections._Refused("MCP_PUBLICATION_UNAVAILABLE") + self._checked = True + + def fresh(self) -> bool: + return self._checked and time.monotonic() < self.deadline + + +async def _retain(proof: _Publication) -> None: + await proof.check() + if not proof.fresh() or not request_tail.retain_publication(proof, proof.check, proof.fresh): + raise connections._Refused("MCP_PUBLICATION_UNAVAILABLE") + + +def _hint(row: ConnectedAccount, resource_id: str) -> str: + scope = [row.org, row.subject, row.kind, row.connection_id, resource_id] + digest = hashlib.sha256(json.dumps(scope, separators=(",", ":")).encode()).hexdigest() + return "mcp-resource-hint:" + digest + + +async def _window(input: MCPBrowseInput, row: ConnectedAccount) -> MCPBrowseOutput: + await connections._validate(row) + client = connections._bound_client(row) + config = client.config + if input.mode == "search" and config.search is None: + result = MCPBrowseOutput( + slot=row.kind, + generation=row.connection_id, + mode=input.mode, + resources=None, + mapped_read=config.read is not None, + mapped_search=False, + reason="unsupported_mode", + limitations=[*_LIMITATIONS, "remote_capabilities_unchecked"], + ) + await connections._validate(row) + return result + async with checked_session(row, client): + await connections._validate(row) + discovered = await client.discover() + await connections._validate(row) + config = client.config + result = MCPBrowseOutput( + slot=row.kind, + generation=row.connection_id, + mode=input.mode, + resources=discovered.resources, + mapped_read=config.read is not None and config.read.name in discovered.tools, + mapped_search=config.search is not None and config.search.name in discovered.tools, + capabilities_checked=True, + limitations=[*_LIMITATIONS, "first_window_only_manual_ids_supported"], + ) + result.supported = ( + discovered.resources if input.mode == "resources" else result.mapped_search + ) + if not result.supported: + result.reason = "unsupported_mode" + else: + await connections._validate(row) + page = ( + await client.list_resources() + if input.mode == "resources" + else await client.search(input.query) + ) + await connections._validate(row) + limit = min(input.limit, config.limits.max_results) + result.items = [ + MCPBrowseItem( + id=item.resource_id, title=item.title, uri=_hint(row, item.resource_id) + ) + for item in page.items[:limit] + ] + unknown = input.mode == "search" and ( + config.search is None or config.search.next_cursor_path is None + ) + result.complete = page.complete and len(page.items) <= limit and not unknown + result.truncated = not result.complete + result.reason = ( + "result_limit" + if len(page.items) > limit + else "first_window_only" + if not page.complete + else "search_completeness_unavailable" + if unknown + else None + ) + await connections._validate(row) + return result + + +async def handle_mcp_browse(input: MCPBrowseInput) -> MCPBrowseOutput: + async with connections._errors(): + with private_work(): + auth = await _admit(input.org) + if ( + (input.mode == "resources" and input.query) + or (input.mode == "search" and not input.query.strip()) + or len(input.query.encode()) > 4096 + ): + raise connections._Refused("MCP_BROWSE_QUERY_INVALID") + deadline = time.monotonic() + settings.knowledge_live_search_timeout_s + async with asyncio.timeout_at(deadline): + owner = await connections._owner(input.org) + connections._check_slot(input.slot) + row = await account_store.get(input.org, owner, input.slot) + if row is None: + raise connections._Refused("MCP_CONNECTION_UNAVAILABLE") + connections._row_scope(row, input.org, owner, input.slot) + result = await _window(input, row) + + async def validate() -> None: + await connections._validate(row) + + await _retain(_Publication(input.org, auth, validate, deadline)) + return result + + +async def handle_mcp_read(input: MCPReadInput) -> MCPReadOutput: + async with connections._errors(): + with private_work(): + auth = await _admit(input.org) + deadline = time.monotonic() + settings.knowledge_live_search_timeout_s + async with asyncio.timeout_at(deadline): + if not await authz.row_in_scope(input.org, input.namespace, Role.VIEWER): + raise connections._Refused("MCP_SOURCE_UNAVAILABLE") + src = await source_store.get_source(input.org, input.namespace, input.name) + if src is None or (src.org, src.namespace, src.name) != ( + input.org, + input.namespace, + input.name, + ): + raise connections._Refused("MCP_SOURCE_UNAVAILABLE") + evidence, contribution = await mcp_live.read_selected(src, auth, input.resource_id) + await _retain(_Publication(input.org, auth, contribution.check, deadline)) + receipt = evidence.receipt + if receipt is None: + raise connections._Refused("MCP_SOURCE_UNAVAILABLE") + return MCPReadOutput( + source_id=src.source_id, + resource_id=input.resource_id, + uri=resource_uri(src.source_id, input.resource_id), + title=evidence.title, + text=evidence.text, + mime_type=evidence.mime_type, + resource_identity_verified=receipt.identity_verified, + limitations=_LIMITATIONS, + ) diff --git a/server/knowledge/app/mcp_connections.py b/server/knowledge/app/mcp_connections.py index 58f0caa037..f552b69978 100644 --- a/server/knowledge/app/mcp_connections.py +++ b/server/knowledge/app/mcp_connections.py @@ -40,6 +40,7 @@ build_mcp_source_client, load_mcp_profile_catalog, ) +from server.knowledge.app.mcp_source_sessions import checked_session from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE, ConnectedAccount from server.knowledge.domain.mcp_sources import ( ConnectionEnvelope, @@ -77,7 +78,7 @@ async def _owner(org: str, expected: str | None = None) -> str: async def _ready() -> None: - if not await machines.fleet_at(get_client(), 116): + if not await machines.fleet_at(get_client(), 117): raise _Refused("MCP_CONNECTION_FLEET_UNAVAILABLE") @@ -383,7 +384,7 @@ async def handle_mcp_discover(input: MCPSlotInput) -> MCPDiscoverOutput: _row_scope(account, input.org, owner, input.slot) await _validate(account) client = _bound_client(account) - async with client: + async with checked_session(account, client): discovered = await client.discover() await _validate(account) config = client.config diff --git a/server/knowledge/app/mcp_live.py b/server/knowledge/app/mcp_live.py index 9ccbd04c90..d6962c9807 100644 --- a/server/knowledge/app/mcp_live.py +++ b/server/knowledge/app/mcp_live.py @@ -12,6 +12,7 @@ from server.core.ch import set_query_tag from server.knowledge.app import mcp_source_authority as authority from server.knowledge.app.mcp_read_receipt import require_read_receipt +from server.knowledge.app.mcp_source_sessions import checked_session from server.knowledge.domain.mcp_identity import resource_uri from server.knowledge.domain.sources import KnowledgeSource @@ -41,7 +42,9 @@ async def validate() -> None: raise authority.MCPAuthorityError() bound = await authority.validate_live_reader(src, auth) - async with bound.connection.client(validate) as client: + async with checked_session( + bound.connection.account, bound.connection.client(validate) + ) as client: yield client diff --git a/server/knowledge/app/mcp_profiles.py b/server/knowledge/app/mcp_profiles.py index 376fcd8982..16f6fca67e 100644 --- a/server/knowledge/app/mcp_profiles.py +++ b/server/knowledge/app/mcp_profiles.py @@ -31,13 +31,6 @@ ) from server.settings import settings -MAX_CATALOG_BYTES = 8 * 1024 * 1024 -MAX_PROFILES = 10_000 -MAX_PROFILE_BYTES = 65_536 -MAX_SCHEMA_BYTES = 16_384 -MAX_PROFILE_NODES = 4096 -MAX_PROFILE_DEPTH = 16 - class MCPProfileError(ValueError): """Configuration and binding failures reveal no supplied values.""" @@ -86,16 +79,16 @@ def _nonfinite(value: str) -> None: def _bounded_tree(value: Any) -> None: - remaining = MAX_PROFILE_NODES + remaining = settings.knowledge_source_mcp_profile_max_nodes def visit(node: Any, depth: int, *, schema_data: bool = False) -> None: nonlocal remaining remaining -= 1 - if remaining < 0 or depth > MAX_PROFILE_DEPTH: + if remaining < 0 or depth > settings.knowledge_source_mcp_profile_max_depth: raise MCPProfileError() if isinstance(node, dict): for key, child in node.items(): - _text(key, MAX_SCHEMA_BYTES, empty=True) + _text(key, settings.knowledge_source_mcp_schema_max_bytes, empty=True) visit( child, depth + 1, @@ -107,10 +100,10 @@ def visit(node: Any, depth: int, *, schema_data: bool = False) -> None: visit(child, depth + 1, schema_data=schema_data) elif isinstance(node, str): if schema_data: - if len(node.encode()) > MAX_SCHEMA_BYTES: + if len(node.encode()) > settings.knowledge_source_mcp_schema_max_bytes: raise MCPProfileError() else: - _text(node, MAX_SCHEMA_BYTES, empty=True) + _text(node, settings.knowledge_source_mcp_schema_max_bytes, empty=True) elif isinstance(node, float) and not math.isfinite(node): raise MCPProfileError() @@ -143,7 +136,7 @@ def _mapping(value: Any, *, search: bool = False) -> MCPToolMapping | None: if name in data: if not isinstance(data[name], dict): raise MCPProfileError() - _canonical(data[name], MAX_SCHEMA_BYTES) + _canonical(data[name], settings.knowledge_source_mcp_schema_max_bytes) for name in ( "items_path", "id_path", @@ -189,7 +182,7 @@ def _snapshot(config: MCPSourceConfig) -> str: data = asdict(config) # Selection has one authority: the source contract, never the operator prototype. del data["approved_resource_ids"] - return _canonical(data, MAX_PROFILE_BYTES) + return _canonical(data, settings.knowledge_source_mcp_profile_max_bytes) @dataclass(frozen=True) @@ -217,7 +210,7 @@ def allows(self, org: str) -> bool: def _profile(value: Any) -> FrozenProfileDefinition: _bounded_tree(value) - _canonical(value, MAX_PROFILE_BYTES) + _canonical(value, settings.knowledge_source_mcp_profile_max_bytes) data = _object( value, {"id", "label", "auth", "allowed_orgs", "allow_collection_copy", "config"}, @@ -244,7 +237,7 @@ def _profile(value: Any) -> FrozenProfileDefinition: "allow_collection_copy": copy_allowed, "config": json.loads(snapshot), } - snapshot = _canonical(approval, MAX_PROFILE_BYTES) + snapshot = _canonical(approval, settings.knowledge_source_mcp_profile_max_bytes) digest = hashlib.sha256(snapshot.encode()).hexdigest() metadata = MCPProfileMetadata( identity, @@ -271,16 +264,23 @@ class MCPProfileCatalog: _profiles: tuple[FrozenProfileDefinition, ...] = () sha256: str = hashlib.sha256(b"[]").hexdigest() + @property + def empty(self) -> bool: + return not self._profiles + @classmethod def parse(cls, payload: str | bytes | None = None) -> MCPProfileCatalog: try: if payload is None: return cls() if isinstance(payload, bytes): - if len(payload) > MAX_CATALOG_BYTES: + if len(payload) > settings.knowledge_source_mcp_catalog_max_bytes: raise MCPProfileError() payload = payload.decode("utf-8") - if not isinstance(payload, str) or len(payload.encode()) > MAX_CATALOG_BYTES: + if ( + not isinstance(payload, str) + or len(payload.encode()) > settings.knowledge_source_mcp_catalog_max_bytes + ): raise MCPProfileError() data = _object( json.loads(payload, object_pairs_hook=_pairs, parse_constant=_nonfinite), @@ -290,16 +290,23 @@ def parse(cls, payload: str | bytes | None = None) -> MCPProfileCatalog: if type(data["version"]) is not int or data["version"] != 1: raise MCPProfileError() rows = data["profiles"] - if not isinstance(rows, list) or len(rows) > MAX_PROFILES: + if ( + not isinstance(rows, list) + or len(rows) > settings.knowledge_source_mcp_catalog_max_profiles + ): raise MCPProfileError() profiles = tuple(sorted((_profile(row) for row in rows), key=lambda p: p.metadata.id)) - if sum(len(p.config_snapshot.encode()) for p in profiles) > MAX_CATALOG_BYTES: + if ( + sum(len(p.config_snapshot.encode()) for p in profiles) + > settings.knowledge_source_mcp_catalog_max_bytes + ): raise MCPProfileError() if len({p.metadata.id for p in profiles}) != len(profiles): raise MCPProfileError() digest = hashlib.sha256( _canonical( - [p.metadata.profile_sha256 for p in profiles], MAX_CATALOG_BYTES + [p.metadata.profile_sha256 for p in profiles], + settings.knowledge_source_mcp_catalog_max_bytes, ).encode() ).hexdigest() return cls(profiles, digest) @@ -417,13 +424,24 @@ def build_mcp_source_client( raise MCPProfileError() from None +def _bounds() -> tuple[int, ...]: + return ( + settings.knowledge_source_mcp_catalog_max_bytes, + settings.knowledge_source_mcp_catalog_max_profiles, + settings.knowledge_source_mcp_profile_max_bytes, + settings.knowledge_source_mcp_schema_max_bytes, + settings.knowledge_source_mcp_profile_max_nodes, + settings.knowledge_source_mcp_profile_max_depth, + ) + + @lru_cache(maxsize=1) -def _catalog_from_setting(payload: str) -> MCPProfileCatalog: - if not isinstance(payload, str): +def _catalog_from_setting(payload: str, bounds: tuple[int, ...]) -> MCPProfileCatalog: + if not isinstance(payload, str) or bounds != _bounds(): raise MCPProfileError() return MCPProfileCatalog.parse(None if payload == "" else payload) def load_mcp_profile_catalog() -> MCPProfileCatalog: """Read trusted operator configuration; retain at most one immutable snapshot.""" - return _catalog_from_setting(settings.knowledge_source_mcp_profiles_json) + return _catalog_from_setting(settings.knowledge_source_mcp_profiles_json, _bounds()) diff --git a/server/knowledge/app/mcp_source_schedule.py b/server/knowledge/app/mcp_source_schedule.py new file mode 100644 index 0000000000..ba00da059a --- /dev/null +++ b/server/knowledge/app/mcp_source_schedule.py @@ -0,0 +1,388 @@ +"""Fair bounded admission around the existing leased MCP source engine.""" + +from __future__ import annotations + +import asyncio +import re +import time +from collections import Counter, deque +from collections.abc import Awaitable, Callable +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import Protocol + +from server.core.ch import set_query_tag +from server.knowledge.store.mcp_source_schedule import Header +from server.workers import pass_context, status_store + +PROGRESS_WORKER = "knowledge_source_sync.mcp" + + +class Budget(Protocol): + left: int + + +Page = Callable[[str, int], Awaitable[list[Header]]] + + +@dataclass(frozen=True) +class Limits: + page_size: int + scan_pages: int + ready: int + global_inflight: int + per_org: int + per_endpoint: int + documents: int + source_seconds: float + + def __post_init__(self) -> None: + for value in ( + self.page_size, + self.scan_pages, + self.ready, + self.global_inflight, + self.per_org, + self.per_endpoint, + self.documents, + ): + if type(value) is not int or value <= 0: + raise ValueError("mcp_schedule_limit") + if not 0 < self.source_seconds < float("inf"): + raise ValueError("mcp_schedule_limit") + + +@dataclass +class Metrics: + pages: int = 0 + scanned: int = 0 + started: int = 0 + completed: int = 0 + failed: int = 0 + timed_out: int = 0 + rejected: int = 0 + deferred: int = 0 + queue_highwater: int = 0 + inflight_highwater: int = 0 + org_highwater: int = 0 + endpoint_highwater: int = 0 + wraps: int = 0 + deadline_cut: int = 0 + + +def _resume(value: str) -> str: + if not value: + return "" + if re.fullmatch(r"mcp1:[0-9A-F]{64}", value) is None: + raise ValueError("mcp_schedule_cursor") + return value[5:] + + +@dataclass +class _Job: + header: Header + endpoint: str + budget: Budget + reserved: int + + +class _Ready: + def __init__(self) -> None: + self.groups: dict[str, deque[tuple[Header, str]]] = {} + self.order: deque[str] = deque() + self.size = 0 + + def append(self, header: Header, endpoint: str) -> None: + if header.org not in self.groups: + self.groups[header.org] = deque() + self.order.append(header.org) + self.groups[header.org].append((header, endpoint)) + self.size += 1 + + def pop( + self, orgs: Counter[str], endpoints: Counter[str], limits: Limits + ) -> tuple[Header, str] | None: + for _ in range(len(self.order)): + org = self.order.popleft() + group = self.groups[org] + chosen = None + if orgs[org] < limits.per_org: + for _ in range(len(group)): + header, endpoint = group.popleft() + if endpoints[endpoint] < limits.per_endpoint: + chosen = header, endpoint + self.size -= 1 + break + group.append((header, endpoint)) + if group: + self.order.append(org) + else: + del self.groups[org] + if chosen is not None: + return chosen + return None + + +async def _execute[B: Budget]( + execute: Callable[[Header, B], Awaitable[None]], header: Header, budget: B, seconds: float +) -> str: + set_query_tag("worker.knowledge_source_sync") + owner = pass_context.current() + child_context = pass_context.begin(owner.worker if owner else "knowledge_source_sync") + if owner is not None: + child_context.stopped = owner.stopped + try: + async with asyncio.timeout(seconds): + await execute(header, budget) + return "completed" + except TimeoutError: + return "timed_out" + except Exception: # noqa: BLE001 — one source failure must not stop other tenants + return "failed" + finally: + pass_context.clear() + + +def _refund(parent: Budget, job: _Job) -> None: + if type(job.budget.left) is not int or not 0 <= job.budget.left <= job.reserved: + raise ValueError("mcp_schedule_budget") + parent.left += job.budget.left + + +class _Dispatch[B: Budget]: + def __init__( + self, + limits: Limits, + parent: Budget, + make_pass: Callable[[int], B], + execute: Callable[[Header, B], Awaitable[None]], + endpoint_key: Callable[[Header], str], + deadline: float, + page: Page, + resume_cursor: str, + checkpoint: Callable[[str], None], + ) -> None: + self.limits, self.parent, self.make_pass = limits, parent, make_pass + self.execute, self.endpoint_key, self.deadline, self.page = ( + execute, + endpoint_key, + deadline, + page, + ) + self.metrics, self.ready = Metrics(), _Ready() + self.running: dict[asyncio.Task[str], _Job] = {} + self.orgs: Counter[str] = Counter() + self.endpoints: Counter[str] = Counter() + self.after, self.exhausted = _resume(resume_cursor), False + self.save_cursor = checkpoint + self.pending: dict[str, str] = {} + + async def fill(self) -> None: + size = min(self.limits.page_size, self.limits.ready - self.ready.size) + async with asyncio.timeout_at(self.deadline): + rows = await self.page(self.after, size) + self.metrics.pages += 1 + if len(rows) > size: + raise ValueError("mcp_schedule_page_overflow") + for header in rows: + if ( + re.fullmatch("[0-9A-F]{64}", header.schedule_key) is None + or header.schedule_key <= self.after + ): + raise ValueError("mcp_schedule_page_order") + previous, self.after = self.after, header.schedule_key + self.metrics.scanned += 1 + try: + endpoint = self.endpoint_key(header) + if not endpoint: + raise ValueError("mcp_schedule_endpoint") + except (ValueError, KeyError): + self.metrics.rejected += 1 + continue + self.ready.append(header, endpoint) + self.pending[header.schedule_key] = previous + self.metrics.queue_highwater = max(self.metrics.queue_highwater, self.ready.size) + if len(rows) < size: + self.exhausted = True + self.metrics.wraps += 1 + self.checkpoint() + + def checkpoint(self) -> None: + # Replay the first unstarted header rather than skipping a full ready window + # whenever a small document budget ends a pass. Already started work is leased. + cursor = self.pending[min(self.pending)] if self.pending else self.after + if not self.pending and self.exhausted: + cursor = "" + self.save_cursor("mcp1:" + (cursor or "0" * 64)) + + def start(self) -> None: + while len(self.running) < self.limits.global_inflight and self.parent.left > 0: + item = self.ready.pop(self.orgs, self.endpoints, self.limits) + if item is None: + break + header, endpoint = item + reserved = min(self.parent.left, self.limits.documents) + child = self.make_pass(reserved) + if ( + child is self.parent + or type(child.left) is not int + or child.left != reserved + or any(child is job.budget for job in self.running.values()) + ): + raise ValueError("mcp_schedule_budget") + self.parent.left -= reserved + seconds = min(self.limits.source_seconds, max(0.0, self.deadline - time.monotonic())) + task = asyncio.create_task(_execute(self.execute, header, child, seconds)) + self.running[task] = _Job(header, endpoint, child, reserved) + del self.pending[header.schedule_key] + self.checkpoint() + self.orgs[header.org] += 1 + self.endpoints[endpoint] += 1 + self.metrics.started += 1 + self.metrics.inflight_highwater = max( + self.metrics.inflight_highwater, len(self.running) + ) + self.metrics.org_highwater = max(self.metrics.org_highwater, self.orgs[header.org]) + self.metrics.endpoint_highwater = max( + self.metrics.endpoint_highwater, self.endpoints[endpoint] + ) + + async def finish(self) -> None: + async with asyncio.timeout_at(self.deadline): + done, _ = await asyncio.wait(self.running, return_when=asyncio.FIRST_COMPLETED) + for task in done: + job = self.running.pop(task) + self.orgs[job.header.org] -= 1 + self.endpoints[job.endpoint] -= 1 + _refund(self.parent, job) + outcome = task.result() + setattr(self.metrics, outcome, getattr(self.metrics, outcome) + 1) + + async def close(self) -> None: + for task in self.running: + task.cancel() + if self.running: + await asyncio.gather(*self.running, return_exceptions=True) + invalid = False + for job in self.running.values(): + try: + _refund(self.parent, job) + except ValueError: + invalid = True + self.metrics.deferred = self.ready.size + if invalid: + raise ValueError("mcp_schedule_budget") + + async def run(self) -> Metrics: + try: + while time.monotonic() < self.deadline: + pass_context.check_stop() + if ( + not self.exhausted + and self.ready.size < self.limits.ready + and self.metrics.pages < self.limits.scan_pages + ): + await self.fill() + self.start() + if not self.running: + if ( + not self.parent.left + or (self.exhausted or self.metrics.pages >= self.limits.scan_pages) + and not self.ready.size + ): + break + continue + await self.finish() + finally: + await self.close() + return self.metrics + + +async def dispatch[B: Budget]( + *, + limits: Limits, + parent: Budget, + make_pass: Callable[[int], B], + execute: Callable[[Header, B], Awaitable[None]], + endpoint_key: Callable[[Header], str], + deadline: float, + page: Page, + resume_cursor: str, + checkpoint: Callable[[str], None], +) -> Metrics: + """Execute retains source/account leases and revalidates publication authority. + + make_pass returns an independent Pass.left with the parent's existing deadline. + endpoint_key resolves the current approved profile without opening a session. + checkpoint receives only an opaque cursor. run_pass persists it in worker_status. + """ + if type(parent.left) is not int or parent.left < 0: + raise ValueError("mcp_schedule_budget") + set_query_tag("worker.knowledge_source_sync") + state = _Dispatch( + limits, parent, make_pass, execute, endpoint_key, deadline, page, resume_cursor, checkpoint + ) + try: + await state.run() + except TimeoutError: + if time.monotonic() < deadline: + raise + state.metrics.deadline_cut = 1 + else: + state.metrics.deadline_cut = int(time.monotonic() >= deadline) + return state.metrics + + +async def run_pass[B: Budget]( + *, + limits: Limits, + parent: Budget, + make_pass: Callable[[int], B], + execute: Callable[[Header, B], Awaitable[None]], + endpoint_key: Callable[[Header], str], + deadline: float, + page: Page, + progress_timeout: float, +) -> Metrics: + """Use existing durable worker progress without replacing the recording lane cursor.""" + if not 0 < progress_timeout < float("inf"): + raise ValueError("mcp_schedule_progress_bound") + set_query_tag("worker.knowledge_source_sync") + resumed = await status_store.resume_cursor(PROGRESS_WORKER, timeout_s=progress_timeout) + cursor = resumed or "mcp1:" + "0" * 64 + + def checkpoint(value: str) -> None: + nonlocal cursor + cursor = value + + started = datetime.now(UTC) + status = "failed" + try: + result = await dispatch( + limits=limits, + parent=parent, + make_pass=make_pass, + execute=execute, + endpoint_key=endpoint_key, + deadline=deadline, + page=page, + resume_cursor=resumed, + checkpoint=checkpoint, + ) + status = "ok" + return result + finally: + row = await status_store.record_manual_pass( + PROGRESS_WORKER, + namespace="", + status=status, + started=started, + finished=datetime.now(UTC), + timeout_s=progress_timeout, + resume_cursor=cursor, + ) + if row is None: + raise RuntimeError("mcp_schedule_progress_unwritten") + observed = await status_store.resume_cursor(PROGRESS_WORKER, timeout_s=progress_timeout) + if observed != cursor: + raise RuntimeError("mcp_schedule_progress_unwritten") diff --git a/server/knowledge/app/mcp_source_sessions.py b/server/knowledge/app/mcp_source_sessions.py new file mode 100644 index 0000000000..ab074b8090 --- /dev/null +++ b/server/knowledge/app/mcp_source_sessions.py @@ -0,0 +1,44 @@ +"""Schema refusal stops its exact MCP binding without erasing retained content.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import replace + +from server.clients.mcp_source import MCPSourceClient, MCPSourceError +from server.core.ch import own_write_reads +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.knowledge.domain.mcp_sources import is_mcp_slot +from server.knowledge.store import connected_accounts as store + + +async def quarantine_mapping(expected: ConnectedAccount) -> None: + from server.knowledge.app.connected_accounts import account_lease + + if not is_mcp_slot(expected.kind): + return + async with account_lease(expected.org, expected.subject, expected.kind): + with own_write_reads(): + current = await store.get(expected.org, expected.subject, expected.kind) + if ( + current is None + or not current.active + or (current.org, current.subject, current.kind, current.connection_id) + != (expected.org, expected.subject, expected.kind, expected.connection_id) + ): + return + await store.put(replace(current, active=False)) + + +@asynccontextmanager +async def checked_session( + account: ConnectedAccount, client: MCPSourceClient +) -> AsyncIterator[MCPSourceClient]: + try: + async with client: + yield client + except MCPSourceError as error: + if error.code == "schema": + await quarantine_mapping(account) + raise diff --git a/server/knowledge/app/mcp_source_worker.py b/server/knowledge/app/mcp_source_worker.py new file mode 100644 index 0000000000..0b97200adf --- /dev/null +++ b/server/knowledge/app/mcp_source_worker.py @@ -0,0 +1,94 @@ +"""Bind bounded MCP admission to the existing leased document-source engine.""" + +from __future__ import annotations + +import asyncio +import hashlib +import json +from functools import partial +from typing import TYPE_CHECKING + +import httpx + +from server.knowledge.app import mcp_source_schedule as scheduler +from server.knowledge.app.mcp_profiles import load_mcp_profile_catalog +from server.knowledge.store import mcp_source_schedule as headers +from server.knowledge.store import sources as store +from server.settings import settings + +if TYPE_CHECKING: + from server.code.app.index.pass_budget import PassBudget + from server.knowledge.app.source_sync import PassResult + + +def limits() -> scheduler.Limits: + return scheduler.Limits( + page_size=settings.knowledge_source_mcp_schedule_page_size, + scan_pages=settings.knowledge_source_mcp_schedule_scan_pages, + ready=settings.knowledge_source_mcp_schedule_ready, + global_inflight=settings.knowledge_source_mcp_schedule_global, + per_org=settings.knowledge_source_mcp_schedule_per_org, + per_endpoint=settings.knowledge_source_mcp_schedule_per_endpoint, + documents=settings.knowledge_source_mcp_schedule_documents, + source_seconds=settings.knowledge_source_mcp_schedule_source_seconds, + ) + + +def query_limits() -> headers.QueryLimits: + return headers.QueryLimits( + rows=settings.knowledge_source_mcp_schedule_query_rows, + bytes=settings.knowledge_source_mcp_schedule_query_bytes, + seconds=settings.knowledge_source_mcp_schedule_query_seconds, + ) + + +async def run(whole: PassBudget, result: PassResult, *, full: bool = False) -> None: + from server.knowledge.app import source_sync, sources + + parent = source_sync.Pass( + budget=whole, left=settings.knowledge_source_mirror_documents_per_pass + ) + catalog = load_mcp_profile_catalog() + if catalog.empty: + return + registry_lock = asyncio.Lock() + registry_ready = False + + def endpoint_key(header: headers.Header) -> str: + profile = catalog.get(header.org, header.profile_id) + if profile.metadata.profile_sha256 != header.profile_sha256: + raise ValueError("mcp_schedule_profile_changed") + endpoint = str(httpx.URL(json.loads(profile.config_snapshot)["config"]["endpoint"])) + return hashlib.sha256(endpoint.encode()).hexdigest() + + async def execute(header: headers.Header, child: source_sync.Pass) -> None: + nonlocal registry_ready + source = await store.get_source(header.org, header.namespace, header.name) + if source is None or source.source_id != header.source_id: + return + usable = await source_sync._usable([source]) + if not usable: + return + async with registry_lock: + if not registry_ready: + await source_sync.require_source_registry() + registry_ready = True + if full: + await sources.request_full_sync(source) + state = (await source_sync._states([source])).get(source_sync._cursor_of(source), {}) + result.sources += 1 + await source_sync._sync_one(source, state, child, result) + + query = query_limits() + measured = await scheduler.run_pass( + limits=limits(), + parent=parent, + make_pass=lambda credits: source_sync.Pass(budget=whole, left=credits), + execute=execute, + endpoint_key=endpoint_key, + deadline=whole.stop_after, + page=partial(headers.candidate_page, query_limits=query), + progress_timeout=query.seconds, + ) + result.private_work |= measured.started > 0 + result.cut |= measured.deferred > 0 or measured.timed_out > 0 or bool(measured.deadline_cut) diff --git a/server/knowledge/app/source_access.py b/server/knowledge/app/source_access.py index 32c6439d54..e1f2c21cfc 100644 --- a/server/knowledge/app/source_access.py +++ b/server/knowledge/app/source_access.py @@ -22,7 +22,7 @@ from server.knowledge.domain.document_access import fresh, source_id from server.knowledge.domain.mcp_read_evidence import ReadProof, ReadScope from server.knowledge.domain.serving import Serving -from server.knowledge.domain.sources import KnowledgeSource, opaque_payload +from server.knowledge.domain.sources import KnowledgeSource from server.knowledge.store import mirrors as mirrors_repo from server.knowledge.store import source_access as store from server.operations.base import Role @@ -316,82 +316,53 @@ async def prepare(org: str, namespaces: list[str]) -> ReadPlan: async def _prepare(plan: ReadPlan, sources: list[dict[str, Any]], subject: str) -> None: - from server.knowledge.app.connected_accounts import validate_indexed from server.knowledge.app.mcp_source_authority import validate_indexed_reader from server.knowledge.store import sources as source_store eligible = [] - mcp_scopes: dict[tuple[str, str], ReadScope] = {} + scopes: dict[tuple[str, str], ReadScope] = {} for row in sources: - key = row["namespace"], row["source_id"] - mode = row.get("credential_mode", "shared") - if row.get("source_kind") != "mcp" and opaque_payload( - kind=str(row.get("source_kind") or ""), - mode=mode, - version=int(row.get("source_contract_version") or 0), + if ( + row.get("source_kind") != "mcp" + or row.get("credential_mode") != "connected" + or row.get("source_contract_version") != 1 ): continue - if row.get("source_kind") == "mcp" and mode != "connected": - continue - if mode == "shared": - if key not in plan._connected_pins: - eligible.append(row) - continue - if mode != "connected" or (plan._scope_frozen and key not in plan._connected_pins): + key = row["namespace"], row["source_id"] + if plan._scope_frozen and key not in plan._connected_pins: continue try: source = await source_store.latest_source(plan.org, row["namespace"], row["name"]) - if ( - source is None - or source.source_id != row["source_id"] - or (source.org, source.namespace, source.name) - != (plan.org, row["namespace"], row["name"]) - or ( - source.kind != "mcp" - and opaque_payload( - kind=source.kind, - mode=source.credential_mode, - version=source.source_contract_version, - ) - ) - ): + if source is None or ( + source.org, + source.namespace, + source.name, + source.source_id, + source.kind, + ) != (plan.org, row["namespace"], row["name"], row["source_id"], "mcp"): continue pinned = plan._connected_pins.get(key) if pinned is not None and source != pinned: continue - if source.kind == "mcp": - bound = await validate_indexed_reader(source, plan._auth) - mcp_scopes[key] = ReadScope(bound.scope_sha256, bound.selected_uris) - else: - await validate_indexed(source, plan._auth) + bound = await validate_indexed_reader(source, plan._auth) + scopes[key] = ReadScope(bound.scope_sha256, bound.selected_uris) eligible.append(row) if not plan._scope_frozen: plan._connected_pins[key] = copy.deepcopy(source) - except Exception: # noqa: BLE001 — one unverifiable connection admits no private leg + except Exception: # noqa: BLE001 — unverifiable source authority admits no private leg continue - sources = eligible - names = sorted({s["namespace"] for s in sources}) - mirrors = await mirrors_repo.mirrors_of(plan.org, names, live_only=True) + mirrors = await mirrors_repo.mirrors_of( + plan.org, sorted({s["namespace"] for s in eligible}), live_only=True + ) by_original: dict[str, list[str]] = {} for mirror, original in mirrors.items(): if is_mirror_name(mirror): by_original.setdefault(original, []).append(mirror) - pairs = { + plan.sources = { (by_original[s["namespace"]][0], s["source_id"]): s["namespace"] - for s in sources + for s in eligible if len(by_original.get(s["namespace"], [])) == 1 } - plan._mcp_scopes = { - key: mcp_scopes[(original, key[1])] - for key, original in pairs.items() - if (original, key[1]) in mcp_scopes - } - rows = await store.listings(plan.org, [key for key in pairs if key not in plan._mcp_scopes]) + plan._mcp_scopes = {key: scopes[(original, key[1])] for key, original in plan.sources.items()} + plan.listing_starts = {} plan.reader = await resolve_reader(plan.org, subject) if subject else None - plan.listing_starts = { - (r["namespace"], r["source_id"]): r["started_at"] - for r in rows - if (r["namespace"], r["source_id"]) in pairs - and fresh(r["started_at"], now(), settings.knowledge_source_acl_stale_seconds) - } - plan.sources = {key: pairs[key] for key in plan.listing_starts | plan._mcp_scopes} diff --git a/server/knowledge/app/source_gdrive_items.py b/server/knowledge/app/source_gdrive_items.py deleted file mode 100644 index 5d43cea2fb..0000000000 --- a/server/knowledge/app/source_gdrive_items.py +++ /dev/null @@ -1,238 +0,0 @@ -"""A `gdrive` source's listing from its items, for the folder turn in -`source_sync`: folders (with `recursive`, every subfolder to MAX_DEPTH, and -MAX_WALK_FOLDERS subfolders per source), shared drives, single files and filters, at most -`gdrive.MAX_PARENTS` parent folders per query. - -The listing also says what the items reach (`Listing.reaches`), so a file a -complete listing lacks is retired only when the store says it is outside every -item. -""" - -from __future__ import annotations - -from collections.abc import Callable -from dataclasses import dataclass, field -from typing import Any - -from server.clients import gdrive -from server.clients._checked_access import Credential -from server.knowledge.domain.sources import ( - MAX_DEPTH, - MAX_WALK_FOLDERS, - include_mime_types, - unread_file_note, -) - - -@dataclass -class Listing: - files: list[dict[str, Any]] = field(default_factory=list) - # The store searched everything every query asked for. - whole: bool = True - # The pass ran out before every query was asked. - ran_out: bool = False - # An item listed nothing, which says nothing is absent (a shared drive the account left). - lost_item: bool = False - # Why the listing does not say what is absent (a walk cut at its bound); '' when it does. - walk_cut: str = "" - # Items that answered 404, are in the trash, or list nothing the source reads: - # "item : ". - notes: list[str] = field(default_factory=list) - # What the items reach. - folders: set[str] = field(default_factory=set) - drives: set[str] = field(default_factory=set) - file_ids: set[str] = field(default_factory=set) - # Each filter with the file types it reads: `include` narrowed to its `kinds`. - filters: list[tuple[dict[str, Any], list[str]]] = field(default_factory=list) - mime_types: list[str] = field(default_factory=list) - - def reads_kind(self, state: dict[str, Any]) -> bool: - """Whether `include` names the file's kind; a file whose kind the store did not - say counts as read.""" - mime = state.get("mimeType") - return not mime or mime in self.mime_types - - def reaches(self, file_id: str, state: dict[str, Any]) -> bool: - """Whether a file, as `gdrive.file_state` reads it, is still one an item - reaches. A filter is matched more broadly than the store matches it (a name - fragment anywhere), so a doubt keeps the file. A file of a kind `include` no - longer names is reached by none.""" - if not self.reads_kind(state): - return False - if file_id in self.file_ids or str(state.get("driveId") or "") in self.drives: - return True - parents = {str(p) for p in state.get("parents") or []} - if parents & self.folders: - return True - return any(_matches(f, mime_types, state) for f, mime_types in self.filters) - - -def _matches(item: dict[str, Any], mime_types: list[str], state: dict[str, Any]) -> bool: - if str(state.get("mimeType") or "") not in mime_types: - return False - name = str(state.get("name") or "").lower() - if "name_contains" in item and item["name_contains"].lower() not in name: - return False - modified = str(state.get("modifiedTime") or "") - if "modified_after" in item and modified <= item["modified_after"] + "T00:00:00": - return False - return "in" not in item or item["in"] in {str(p) for p in state.get("parents") or []} - - -async def walk( - token: Credential, - roots: list[str], - out: Listing, - *, - pace_s: float, - out_of_time: Callable[[], bool] = lambda: False, -) -> None: - """Add `roots` and their subfolders to `out.folders`, breadth first and level by - level together, to MAX_DEPTH levels and at most MAX_WALK_FOLDERS subfolders, and - record on `out` whether the store searched everything, the pass ran out, or the - walk stopped at a bound with folders left unread.""" - seen = set(roots) - out.folders.update(roots) - frontier = list(roots) - walked = 0 - for _ in range(MAX_DEPTH): - if out_of_time(): - out.ran_out = True - return - # Enough ids to fill the walk's room even if every folder already seen is among - # them; past that the walk is cut anyway. - room = MAX_WALK_FOLDERS - walked + len(seen) - children, complete = await gdrive.subfolders(token, frontier, limit=room, pace_s=pace_s) - out.whole = out.whole and complete - frontier = [] - for child in children: - if child in seen: - continue - if walked >= MAX_WALK_FOLDERS: - out.walk_cut = "more subfolders than a walk reads" - return - walked += 1 - seen.add(child) - out.folders.add(child) - frontier.append(child) - if not frontier: - return - # The last level is cut only if it holds folders of its own: one page is enough to - # tell, and an unsure answer counts as cut. - if out_of_time(): - out.ran_out = True - elif await gdrive.any_subfolder(token, frontier, seen): - out.walk_cut = "more subfolders than a walk reads" - - -async def list_items( - token: Credential, - items: list[dict[str, Any]], - include: list[str], - *, - modified_after: str = "", - fields: str = gdrive.LISTED, - pace_s: float = gdrive.PAGE_PACE_S, - out_of_time: Callable[[], bool] = lambda: False, -) -> Listing: - """Every file the items list, each once, or only those changed after - `modified_after`. A rate limit, a refused credential or a failed query raises; - a single file or a shared drive that answers 404 is noted and the rest listed. - The recursive folders are walked on every listing, together, so a new file in a new - subfolder comes in with the next turn (files moved in keep their change time, so they - come with the next full listing); once `out_of_time()`, no further walk level, - folder listing or other item starts, and the listing records that it ran out, so - the turn keeps its stamp and lists again. A `file` item is one metadata read on - every listing, an incremental one too. `fields`: what is read of each file - (`gdrive.LISTED_WITH_PERMISSIONS` adds its permissions).""" - out = Listing(mime_types=include_mime_types(include)) - files: dict[str, dict[str, Any]] = {} - - def add(found: list[dict[str, Any]]) -> None: - for f in found: - files.setdefault(str(f.get("id") or ""), f) - - roots = [i["id"] for i in items if i["type"] == "folder" and i.get("recursive")] - if roots: - await walk(token, roots, out, pace_s=pace_s, out_of_time=out_of_time) - out.folders.update(i["id"] for i in items if i["type"] == "folder" and not i.get("recursive")) - if out.ran_out or out_of_time(): - out.ran_out = True - return out - found, whole = await gdrive.list_all( - token, - sorted(out.folders), - out.mime_types, - modified_after=modified_after, - fields=fields, - pace_s=pace_s, - ) - add(found) - out.whole = out.whole and whole - for n, item in enumerate(items): - # A folder item was listed above; every other type asks the store. - if item["type"] != "folder" and out_of_time(): - out.ran_out = True - break - if item["type"] == "shared_drive": - out.drives.add(item["id"]) - try: - found, whole = await gdrive.list_query( - token, - gdrive.drive_query(out.mime_types), - drive_id=item["id"], - modified_after=modified_after, - fields=fields, - pace_s=pace_s, - ) - except gdrive.NotFound: - # A drive the account left lists nothing, which says nothing is absent. - out.notes.append(f"item {n}: http_404") - out.lost_item = True - continue - add(found) - out.whole = out.whole and whole - elif item["type"] == "filter": - # Add and update refuse a filter whose kinds share none with include. - mime_types = include_mime_types(include, item.get("kinds")) - out.filters.append((item, mime_types)) - found, whole = await gdrive.list_query( - token, - gdrive.filter_query(item, mime_types), - modified_after=modified_after, - fields=fields, - pace_s=pace_s, - ) - add(found) - out.whole = out.whole and whole - elif item["type"] == "file": - out.file_ids.add(item["id"]) - meta = await _file_item(token, n, item["id"], out, fields) - if meta and not ( - modified_after and str(meta.get("modifiedTime") or "") <= modified_after - ): - add([meta]) - out.files = [f for k, f in files.items() if k] - return out - - -async def _file_item( - token: Credential, n: int, file_id: str, out: Listing, fields: str -) -> dict[str, Any] | None: - """The metadata of the `file` item `n`, or None with a note on `out` when it lists - nothing (gone, trashed, or of a kind the source does not read).""" - try: - meta = await gdrive.file_meta(token, file_id, fields=fields) - except gdrive.NotFound: - out.notes.append(f"item {n}: http_404") - return None - if meta.get("trashed"): - out.notes.append(f"item {n}: in the trash") - return None - if meta.get("mimeType") not in out.mime_types: - out.notes.append(f"item {n}: {unread_file_note(str(meta.get('mimeType') or ''))}") - return None - return meta - - -__all__ = ["Listing", "list_items", "walk"] diff --git a/server/knowledge/app/source_probes.py b/server/knowledge/app/source_probes.py index b7fafe0490..5a14744f9f 100644 --- a/server/knowledge/app/source_probes.py +++ b/server/knowledge/app/source_probes.py @@ -1,285 +1,33 @@ -"""The probe of a document source: an authenticated check and listing with the -credential, before anything is stored (add, update, rotate) or on request (check), -bounded as a whole by LOOM_KNOWLEDGE_SOURCE_PROBE_TIMEOUT_S. - -Each kind has one probe function, over the items its caller checks (`sample` picks -them). It answers a `Probe` or raises `SourceUnreachable` / `CredentialRefused`; the -credential is held only for the call. A tracker project named by its short id is -resolved to its UUID first (`resolve`). -""" +"""Bounded credential and transcript checks for shared recording sources.""" from __future__ import annotations import asyncio -from collections.abc import Awaitable, Callable from dataclasses import dataclass, field from typing import Any -from server.clients._checked_access import CheckedAccess, Credential -from server.knowledge.domain.sources import ( - SAMPLE_ITEMS, - include_in, - include_mime_types, - item_ids, -) from server.settings import settings -# Titles a probe returns, at most. SAMPLE_TITLES = 5 @dataclass(frozen=True) class Probe: - # Documents the source lists now: the first page, 1000 at most, of the folders, of - # each shared drive and of each filter, and each file item (gdrive); at most 1000 - # (recording); each project's first page (linear); the listed pages and the first - # 100 pages of each of up to three databases (notion). documents: int - # Up to five of their titles, most recently changed first. sample: list[str] = field(default_factory=list) - # True when more match than were listed, so `documents` is a lower bound. more: bool = False - # The items checked, as the store named them: a recursive `folder` item that is a - # shared drive's root comes back as a `shared_drive` one. [] from a kind without items. - items: list[dict[str, Any]] = field(default_factory=list) - # The file items checked whose kind the source's `include` does not name, by id, - # with the store's type of each. - foreign: dict[str, str] = field(default_factory=dict) - # The file items checked that are in the trash. - trashed: list[str] = field(default_factory=list) class SourceUnreachable(Exception): - def __init__(self, message: str, item_id: str = "") -> None: - super().__init__(message) - # The id the refusal names, when it is about one: an item's, or a filter's `in` - # folder. - self.item_id = item_id + pass class CredentialRefused(Exception): pass -def sample(items: list[dict[str, Any]]) -> list[dict[str, Any]]: - """The items a probe checks: all of them, or the SAMPLE_ITEMS added last.""" - return items[-SAMPLE_ITEMS:] - - -async def _check_gdrive_item( - gdrive: Any, token: Credential, item: dict[str, Any] -) -> tuple[dict[str, Any], dict[str, Any] | None]: - """Check one item is one the account sees: the item as the store names it, and a - file item's metadata (so the listing reads it once), else None.""" - try: - if item["type"] == "folder": - folder = await gdrive.require_folder(token, item["id"]) - # A recursive walk of a drive's root reads the drive: stored as the drive, it - # is listed in one query. A folder that is not recursive reads the root's own - # files. - if item.get("recursive") and folder.get("driveId") == item["id"]: - return {"type": "shared_drive", "id": item["id"]}, None - elif item["type"] == "shared_drive": - await gdrive.require_drive(token, item["id"]) - elif item["type"] == "file": - return item, await gdrive.file_meta(token, item["id"]) - elif item["type"] == "filter" and "in" in item: - await gdrive.require_folder(token, item["in"]) - except gdrive.NotFound as e: - # A filter's `in` folder is what was checked. - seen = item["in"] if item["type"] == "filter" else item["id"] - what = {"shared_drive": "shared drive", "file": "file"}.get(item["type"], "folder") - # A 404 is a missing share (a drive's: no membership); an id the store answered is - # no folder, or trashed. - why = "not found; share it with the service account" - if item["type"] == "shared_drive": - why = "not found; add the service account as a member of the drive" - elif e.status != 404: - why = "not a folder, or in the trash" - raise SourceUnreachable(f"{what} {seen}: {why}", seen) from None - return item, None - - -async def _check_items( - gdrive: Any, token: Credential, items: list[dict[str, Any]] -) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]]]: - """Check every item at once: the items as the store names them, and the file items' - metadata by id. The first failure cancels the rest and is raised.""" - try: - async with asyncio.TaskGroup() as group: - checks = [group.create_task(_check_gdrive_item(gdrive, token, i)) for i in items] - except ExceptionGroup as failed: - raise failed.exceptions[0] from None - results = [c.result() for c in checks] - files = {item["id"]: meta for item, meta in results if meta is not None} - return [item for item, _ in results], files - - -async def _probe_gdrive( - items: list[dict[str, Any]], config: dict[str, Any], credential: Credential -) -> Probe: - from server.clients import gdrive - - include = include_in(config) - mime_types = include_mime_types(include) - try: - token: Credential - if isinstance(credential, CheckedAccess): - if credential.kind != "gdrive": - raise CredentialRefused("the connection is not a folder-store account") - token = credential - else: - account = gdrive.parse_service_account(credential) - token = await gdrive.access_token(account) - # Every item must be one the account sees (an unshared folder lists empty, - # not refused); the checks run together, then one listing page per query. - checked, files = await _check_items(gdrive, token, items) - found, more = await _gdrive_first_pages(gdrive, token, checked, files, mime_types, include) - except gdrive.CredentialRefused as e: - raise CredentialRefused(str(e)) from None - except gdrive.NotFound as e: - raise SourceUnreachable(f"{e}; share it with the service account") from None - except gdrive.VendorError as e: - raise SourceUnreachable(str(e)) from None - found.sort(key=lambda f: str(f.get("modifiedTime") or ""), reverse=True) - titles = [str(f.get("name") or "") for f in found[:SAMPLE_TITLES]] - # A trashed file, or one of a kind the source does not read, lists nothing: add and - # update refuse it; check and rotate, which test the credential, do not. - trashed = sorted(i for i, meta in files.items() if meta.get("trashed")) - foreign = { - i: str(meta.get("mimeType") or "") - for i, meta in sorted(files.items()) - if meta.get("mimeType") not in mime_types and not meta.get("trashed") - } - # The first page reads a recursive folder's own files, not its subfolders'. - more = more or any(i["type"] == "folder" and i.get("recursive") for i in checked) - return Probe( - documents=len(found), - sample=titles, - more=more, - items=checked, - foreign=foreign, - trashed=trashed, - ) - - -async def _gdrive_first_pages( - gdrive: Any, - token: Credential, - items: list[dict[str, Any]], - files: dict[str, dict[str, Any]], - mime_types: list[str], - include: list[str], -) -> tuple[list[dict[str, Any]], bool]: - """The first listing page of the items' folders, of each shared drive and of - each filter, and each file item (its metadata in `files`, read by the check): the - files found, each once, and whether more follow.""" - # (query, drive id) for each first page, read together as the checks are. - queries: list[tuple[str, str]] = [] - folders = [i["id"] for i in items if i["type"] == "folder"] - if folders: - queries.append((gdrive.folder_query(folders, mime_types), "")) - pages: list[tuple[list[dict[str, Any]], bool]] = [] - for item in items: - if item["type"] == "shared_drive": - queries.append((gdrive.drive_query(mime_types), item["id"])) - elif item["type"] == "filter": - # Add and update refuse a filter whose kinds share none with include. - filter_types = include_mime_types(include, item.get("kinds")) - queries.append((gdrive.filter_query(item, filter_types), "")) - elif item["type"] == "file": - meta = files[item["id"]] - readable = meta.get("mimeType") in mime_types and not meta.get("trashed") - pages.append(([meta] if readable else [], False)) - try: - async with asyncio.TaskGroup() as group: - tasks = [group.create_task(gdrive.list_files(token, q, drive_id=d)) for q, d in queries] - except ExceptionGroup as failed: - raise failed.exceptions[0] from None - pages += [t.result() for t in tasks] - found = {str(f.get("id")): f for page, _ in pages for f in page} - return list(found.values()), any(more for _, more in pages) - - -async def _probe_linear( - items: list[dict[str, Any]], config: dict[str, Any], credential: Credential -) -> Probe: - from server.clients import linear - - try: - # One page of each project: every project must be one the key sees. - async with asyncio.TaskGroup() as group: - pages = [ - group.create_task(linear.documents_page(credential, project_id)) - for project_id in item_ids(items, "project") - ] - except ExceptionGroup as failed: - e = failed.exceptions[0] - if isinstance(e, linear.CredentialRefused): - raise CredentialRefused(str(e)) from None - if isinstance(e, linear.NotFound): - raise SourceUnreachable(f"{e}; the key's account must see the project") from None - if isinstance(e, linear.LinearError): - raise SourceUnreachable(str(e)) from None - raise e from None - found = [node for page in pages for node in page.result()[0]] - found.sort(key=lambda node: str(node.get("updatedAt") or ""), reverse=True) - titles = [str(node.get("title") or "") for node in found[:SAMPLE_TITLES]] - more = any(page.result()[1] for page in pages) - return Probe(documents=len(found), sample=titles, more=more, items=items) - - -# Databases whose pages a page-store probe samples. Every listed id is read; only -# this many first data sources are queried, so a probe of 20 ids stays well inside -# its time bound at the store's pace of about three requests a second. -_SAMPLED_DATABASES = 3 # not a setting: a bound on one probe's requests - - -async def _probe_notion( - items: list[dict[str, Any]], config: dict[str, Any], credential: Credential -) -> Probe: - from server.clients import notion - - if not notion.valid_token(credential): - raise CredentialRefused("the credential is not an integration token") - found: list[dict[str, Any]] = [] - more = False - sampled = 0 - try: - # Every listed page and database must be one the integration sees: one - # shared with it answers, one that is not answers 404. - for page_id in item_ids(items, "page"): - page = await notion.page(credential, page_id) - if page.get("in_trash"): - raise SourceUnreachable(f"page {page_id}: in the trash") - found.append(page) - for database_id in item_ids(items, "database"): - db = await notion.database(credential, database_id) - if db.get("in_trash"): - raise SourceUnreachable(f"database {database_id}: in the trash") - sources = notion.data_source_ids(db) - if sources and sampled < _SAMPLED_DATABASES: - sampled += 1 - pages, has_more = await notion.first_pages(credential, sources[0]) - found.extend(pages) - more = more or has_more or len(sources) > 1 - elif sources: - more = True # not sampled: its pages are not counted - except notion.CredentialRefused as e: - raise CredentialRefused(str(e)) from None - except notion.NotFound as e: - raise SourceUnreachable(f"{e}; share it with the integration") from None - except notion.VendorError as e: - raise SourceUnreachable(str(e)) from None - # A listed page may also be a listed database's. - found = list({str(p.get("id")): p for p in found}.values()) - found.sort(key=lambda p: str(p.get("last_edited_time") or ""), reverse=True) - titles = [notion.title_of(p) for p in found[:SAMPLE_TITLES]] - return Probe(documents=len(found), sample=titles, more=more, items=items) - - async def _probe_recording( - items: list[dict[str, Any]], config: dict[str, Any], credential: Credential + items: list[dict[str, Any]], config: dict[str, Any], credential: str ) -> Probe: from server.clients import recording from server.knowledge.app import source_sync_recording @@ -300,69 +48,12 @@ async def _probe_recording( return Probe(documents=min(len(found), 1000), sample=titles, more=len(found) > 1000) -PROBES: dict[ - str, Callable[[list[dict[str, Any]], dict[str, Any], Credential], Awaitable[Probe]] -] = { - "gdrive": _probe_gdrive, - "linear": _probe_linear, - "notion": _probe_notion, - "recording": _probe_recording, -} - - -async def probe( - kind: str, - config: dict[str, Any], - credential: Credential, - *, - items: list[dict[str, Any]], -) -> Probe: - """The kind's probe of `items`, with the options `config` holds (`include`, a - recording's provider and ids), bounded by LOOM_KNOWLEDGE_SOURCE_PROBE_TIMEOUT_S as a - whole.""" +async def probe(kind: str, config: dict[str, Any], credential: str) -> Probe: + if kind != "recording": + raise SourceUnreachable("this source kind is unavailable") limit = float(settings.knowledge_source_probe_timeout_s) try: async with asyncio.timeout(limit): - return await PROBES[kind](items, config, credential) + return await _probe_recording([], config, credential) except TimeoutError: raise SourceUnreachable(f"the source did not answer within {limit:g} s") from None - - -async def resolve( - kind: str, items: list[dict[str, Any]], credential: Credential -) -> list[dict[str, Any]]: - """`items` with each tracker project named by its short id (a link's) named by - its UUID, bounded by LOOM_KNOWLEDGE_SOURCE_PROBE_TIMEOUT_S; SourceUnreachable - names a short id the tracker does not know.""" - slugs = [i["slug_id"] for i in items if "slug_id" in i] - if kind != "linear" or not slugs: - return items - from server.clients import linear - - limit = float(settings.knowledge_source_probe_timeout_s) - try: - async with asyncio.timeout(limit): - found = await linear.project_ids(credential, slugs) - except TimeoutError: - raise SourceUnreachable(f"the tracker did not answer within {limit:g} s") from None - except linear.CredentialRefused: - raise CredentialRefused("the tracker refused the key") from None - except linear.LinearError: - raise SourceUnreachable("the tracker could not look the projects up") from None - lost = [s for s in slugs if s not in found] - if lost: - raise SourceUnreachable( - f"project {lost[0]}: not found; the key's account must see it", lost[0] - ) - return [{"type": "project", "id": found[i["slug_id"]]} if "slug_id" in i else i for i in items] - - -__all__ = [ - "PROBES", - "CredentialRefused", - "Probe", - "SourceUnreachable", - "probe", - "resolve", - "sample", -] diff --git a/server/knowledge/app/source_push.py b/server/knowledge/app/source_push.py index 245950383d..271c233fec 100644 --- a/server/knowledge/app/source_push.py +++ b/server/knowledge/app/source_push.py @@ -1,152 +1,44 @@ -"""Source-bound notification setup and authenticated sync hints.""" +"""Local retirement and resealing of retained source notification registrations.""" from __future__ import annotations -import asyncio -import contextlib import dataclasses -import hmac -import json -import logging -import secrets -import time -import uuid from typing import Any -from urllib.parse import quote, urlencode, urlsplit -from server.auth import machines -from server.clients import gdrive, gdrive_push, linear, notion -from server.core import leases -from server.core.ch import get_client, sequential_reads -from server.core.errors import BadConfigError, OverloadedError, ValidationError +from server.core.ch import sequential_reads, set_query_tag from server.core.lease_writes import fenced -from server.core.secrets_at_rest import resealed, seal, unseal -from server.knowledge.api.models_source_push import ( - PushConfigureInput, - PushConfirmInput, - PushSourceInput, - PushStatusInput, - PushStatusOutput, -) +from server.core.secrets_at_rest import resealed, unseal from server.knowledge.app import sources from server.knowledge.domain import source_push as domain -from server.knowledge.domain.source_push import DeliveryRefused, PushRegistration -from server.knowledge.domain.sources import KnowledgeSource, json_object +from server.knowledge.domain.source_push import PushRegistration +from server.knowledge.domain.sources import KnowledgeSource from server.knowledge.store import source_push as store -from server.knowledge.store import sources as source_store from server.memory.app.provenance import writer_actor -from server.settings import settings -log = logging.getLogger(__name__) -PUSH_MIGRATION = 109 - -def _require_enabled() -> None: - if not settings.knowledge_source_push_enabled: - raise BadConfigError("an operator must enable source push on this deployment") - - -async def require_ready(*, ch: Any = None) -> None: - if not await machines.fleet_at(ch or get_client(), PUSH_MIGRATION): - raise BadConfigError("push setup requires every live build to support its erasure") - - -def _fingerprint(src: KnowledgeSource) -> str: - credential = sources.credential_of(src) - if not credential: - raise DeliveryRefused("source credential unavailable") - return domain.fingerprint(credential=credential, items=src.items, config=src.config) - - -def _secrets(reg: PushRegistration) -> dict[str, Any]: - raw = unseal(domain.SECRET_PURPOSE, reg.secret_enc) - if not raw: - raise DeliveryRefused("push secret unavailable") - return domain.payload(raw.encode()) - - -def _sealed(data: dict[str, Any]) -> str: - value = seal(domain.SECRET_PURPOSE, json.dumps(data, sort_keys=True)) - if not value: - raise BadConfigError("a signing root is required to seal push setup") - return value - - -def callback_url(reg: PushRegistration) -> str: - base = str(settings.public_base_url).strip().rstrip("/") - try: - parsed = urlsplit(base) - except ValueError as exc: - raise BadConfigError( - "push setup requires LOOM_PUBLIC_BASE_URL with an HTTPS origin" - ) from exc - if ( - parsed.scheme != "https" - or not parsed.hostname - or parsed.username - or parsed.password - or parsed.query - or parsed.fragment - or parsed.path - ): - raise BadConfigError("push setup requires LOOM_PUBLIC_BASE_URL with an HTTPS origin") - return ( - f"{base}/hooks/knowledge/{quote(reg.namespace, safe='')}/{reg.source_id}" - f"/{reg.generation}?{urlencode({'org': reg.org})}" - ) - - -async def _source(input: PushSourceInput) -> KnowledgeSource: - src = await sources._source_or_404(input.org, input.namespace, input.name) - sources._require_served(src) - await sources._require_source_namespace(src.org, src.namespace) - return src - - -async def _fresh(reg: PushRegistration) -> KnowledgeSource: - """Called under sources_lease, with current strong reads.""" - fresh = await source_store.get_source(reg.org, reg.namespace, reg.name) - current = await store.get(reg.org, reg.namespace, reg.source_id) - if ( - fresh is None - or current is None - or current.generation != reg.generation - or current.status == "retired" - or fresh.source_id != reg.source_id - or fresh.kind != reg.provider - ): - raise DeliveryRefused("push setup no longer current") - sources._require_served(fresh) - await sources._require_source_namespace(reg.org, reg.namespace) - await sources._require_no_erasure(reg.org, reg.namespace) - if _fingerprint(fresh) != reg.fingerprint: - raise DeliveryRefused("source setup changed") - return fresh - - -async def _put(reg: PushRegistration, *, retiring: bool = False, ch: Any = None) -> None: +async def _put(reg: PushRegistration, *, ch: Any = None) -> None: async with fenced(domain.writer_lease_name(reg.org, reg.namespace), ch=ch) as uncertain: - if not retiring: - await require_ready(ch=ch) uncertain(True) await store.put(dataclasses.replace(reg, actor=writer_actor("process:source-push")), ch=ch) uncertain(False) async def retire(src: KnowledgeSource) -> None: - """Caller holds the source lease; clearing setup cannot enable an old build.""" + """Retire a stored notification binding only for the caller's explicit source action.""" current = await store.get(src.org, src.namespace, src.source_id) if current and current.status != "retired": - await _put(dataclasses.replace(current, status="retired", secret_enc=""), retiring=True) + await _put(dataclasses.replace(current, status="retired", secret_enc="")) async def reseal_registry(*, dry_run: bool, ch: Any = None) -> tuple[int, list[str]]: - """Re-read under the lifecycle lease; a scanned row cannot recreate an erased one.""" + """Preserve retained registration state while rotating its sealed secret locally.""" after = ("", "", "") count = 0 lost: list[str] = [] + set_query_tag("knowledge.source.reseal") while page := await store.sealed_page(after, ch=ch): for observed in page: + set_query_tag("knowledge.source.reseal") async with sources.sources_lease(observed.org, observed.namespace, ch=ch): with sequential_reads(): await sources._require_no_erasure(observed.org, observed.namespace, ch=ch) @@ -155,17 +47,6 @@ async def reseal_registry(*, dry_run: bool, ch: Any = None) -> tuple[int, list[s ) if current is None or not current.secret_enc: continue - fresh = await source_store.get_source( - current.org, current.namespace, current.name, ch=ch - ) - if fresh is None or fresh.source_id != current.source_id: - if not dry_run: - await _put( - dataclasses.replace(current, status="retired", secret_enc=""), - retiring=True, - ch=ch, - ) - continue new = resealed(domain.SECRET_PURPOSE, current.secret_enc) if new is None: if not unseal(domain.SECRET_PURPOSE, current.secret_enc, warn=False): @@ -176,290 +57,3 @@ async def reseal_registry(*, dry_run: bool, ch: Any = None) -> tuple[int, list[s await _put(dataclasses.replace(current, secret_enc=new), ch=ch) after = (page[-1].org, page[-1].namespace, page[-1].source_id) return count, lost - - -async def handle_configure(input: PushConfigureInput) -> PushStatusOutput: - src = await _source(input) - if not input.enabled: - async with sources.sources_lease(src.org, src.namespace): - with sequential_reads(): - fresh = await _source(input) - if fresh.source_id != src.source_id: - raise OverloadedError("source changed; retry") - await retire(fresh) - return PushStatusOutput( - provider=src.kind, enabled=bool(settings.knowledge_source_push_enabled) - ) - _require_enabled() - await require_ready() - if src.kind not in {"gdrive", "notion", "linear"}: - raise ValidationError("push supports gdrive, notion and linear sources") - reg = PushRegistration( - org=src.org, - namespace=src.namespace, - name=src.name, - source_id=src.source_id, - provider=src.kind, - generation=str(uuid.uuid4()), - fingerprint=_fingerprint(src), - agent=input.agent, - user_id=input.user_id, - session_id=input.session_id, - actor=writer_actor("process:source-push"), - ) - callback_url(reg) - credential = sources.credential_of(src) - async with asyncio.timeout(settings.knowledge_source_push_provider_timeout_s): - if src.kind == "notion": - reg = dataclasses.replace(reg, provider_id=await notion.workspace_id(credential)) - elif src.kind == "linear": - reg = dataclasses.replace(reg, provider_id=await linear.organization_id(credential)) - reg = dataclasses.replace(reg, secret_enc=_sealed({})) - async with sources.sources_lease(src.org, src.namespace): - with sequential_reads(): - fresh = await _source(input) - await sources._require_no_erasure(src.org, src.namespace) - if fresh.source_id != src.source_id or _fingerprint(fresh) != reg.fingerprint: - raise OverloadedError("source changed during setup; retry") - await _put(reg) - if src.kind == "gdrive": - await renew_drive(reg, initial=True) - return await handle_status(PushStatusInput(org=src.org, namespace=src.namespace, name=src.name)) - - -async def handle_status(input: PushStatusInput) -> PushStatusOutput: - src = await _source(input) - with sequential_reads(): - reg = await store.get(src.org, src.namespace, src.source_id) - if reg is None or reg.status == "retired": - return PushStatusOutput( - provider=src.kind, enabled=bool(settings.knowledge_source_push_enabled) - ) - if _fingerprint(src) != reg.fingerprint: - return PushStatusOutput( - status="obsolete", - provider=src.kind, - enabled=bool(settings.knowledge_source_push_enabled), - ) - data = _secrets(reg) - challenge = str(data.get("challenge") or "") if reg.status == "pending" else "" - channels = data.get("channels") or [] - expiration = min((float(c["expiration"]) for c in channels), default=0) - status = "expired" if channels and expiration <= time.time() else reg.status - try: - address = callback_url(reg) - except BadConfigError: - # A paused deployment may have removed its public origin; admins must - # still be able to inspect and retire existing setup. - address = "" - return PushStatusOutput( - enabled=bool(settings.knowledge_source_push_enabled), - status=status, - provider=reg.provider, - generation=reg.generation, - callback_url=address, - provider_id=reg.provider_id, - challenge_fingerprint=domain.challenge_fingerprint(challenge) if challenge else "", - verification_token=challenge if input.reveal_challenge else "", - channels=len(channels), - expires_at=expiration, - ) - - -async def handle_confirm(input: PushConfirmInput) -> PushStatusOutput: - _require_enabled() - src = await _source(input) - async with sources.sources_lease(src.org, src.namespace): - with sequential_reads(): - reg = await store.get(src.org, src.namespace, src.source_id) - if ( - reg is None - or reg.provider not in {"notion", "linear"} - or reg.status != "pending" - or reg.generation != input.generation - ): - raise ValidationError("the pending setup changed") - await _fresh(reg) - if reg.provider == "linear": - if not input.signing_secret.strip() or input.challenge_fingerprint: - raise ValidationError("the Linear webhook signing secret is required") - reg = dataclasses.replace( - reg, secret_enc=_sealed({"signing_secret": input.signing_secret}) - ) - else: - challenge = str(_secrets(reg).get("challenge") or "") - if ( - input.signing_secret - or not challenge - or not hmac.compare_digest( - domain.challenge_fingerprint(challenge), input.challenge_fingerprint - ) - ): - raise ValidationError("the pending challenge changed") - await _put(dataclasses.replace(reg, status="active")) - return await handle_status(PushStatusInput(org=src.org, namespace=src.namespace, name=src.name)) - - -async def receive( - org: str, namespace: str, source_id: str, generation: str, raw: bytes, headers: dict[str, str] -) -> None: - if not settings.knowledge_source_push_enabled: - raise DeliveryRefused("push is disabled") - with sequential_reads(): - reg = await store.get(org, namespace, source_id) - if reg is None or reg.generation != generation or reg.status not in {"pending", "active"}: - raise DeliveryRefused("unverifiable delivery") - async with sources.sources_lease(reg.org, reg.namespace): - with sequential_reads(): - fresh = await _fresh(reg) - current = await store.get(org, namespace, source_id) - if current is None: - raise DeliveryRefused("unverifiable delivery") - data = _secrets(current) - if current.provider == "notion" and current.status == "pending": - body = domain.payload(raw) - challenge = body.get("verification_token") - if ( - not isinstance(challenge, str) - or not 16 <= len(challenge) <= 512 - or set(body) != {"verification_token"} - ): - raise DeliveryRefused("invalid verification challenge") - existing = data.get("challenge") - if existing and existing != challenge: - raise DeliveryRefused("verification challenge already captured") - if not existing: - await _put( - dataclasses.replace( - current, secret_enc=_sealed({**data, "challenge": challenge}) - ) - ) - return - if current.provider == "notion": - domain.verify_notion( - raw, - headers.get("x-notion-signature", ""), - str(data.get("challenge") or ""), - current.provider_id, - ) - elif current.provider == "linear": - domain.verify_linear( - raw, - headers.get("linear-signature", ""), - str(data.get("signing_secret") or ""), - current.provider_id, - now=time.time(), - ) - elif current.provider == "gdrive": - pending = data.get("pending_channels") or [] - if headers.get("x-goog-resource-state") == "sync" and any( - c["id"] == headers.get("x-goog-channel-id") - and hmac.compare_digest( - str(c["token"]).encode(), headers.get("x-goog-channel-token", "").encode() - ) - for c in pending - ): - return - if not domain.verify_drive(headers, data.get("channels") or [], now=time.time()): - return - else: - raise DeliveryRefused("unverifiable delivery") - state = await sources._read_state(fresh) - detail = json_object(state.get("detail", "")) - if not detail.get("requested_at"): - async with fenced(domain.writer_lease_name(reg.org, reg.namespace)) as uncertain: - uncertain(True) - await sources._update_state( - fresh, state, {"requested_at": sources._now_iso(), "full": False} - ) - uncertain(False) - - -async def _stop_channels(token: str, channels: list[dict[str, Any]]) -> None: - for channel in channels: - try: - async with asyncio.timeout(settings.knowledge_source_push_stop_timeout_s): - await gdrive_push.stop(token, channel) - except Exception: # noqa: BLE001 — expiry and polling recover failed channel cleanup - log.warning("source push channel cleanup failed") - - -async def renew_drive(reg: PushRegistration, *, initial: bool = False) -> None: - _require_enabled() - async with leases.holding( - f"knowledge-push:{reg.org}:{reg.source_id}", ttl_s=120, wait_s=0 - ) as held: - if not held: - raise OverloadedError("source push renewal already running") - await _renew_drive(reg, initial=initial) - - -async def _renew_drive(reg: PushRegistration, *, initial: bool) -> None: - created: list[dict[str, Any]] = [] - publication_attempted = False - token = "" - async with asyncio.timeout(settings.knowledge_source_push_provider_timeout_s): - async with sources.sources_lease(reg.org, reg.namespace): - with sequential_reads(): - src = await _fresh(reg) - current = await store.get(reg.org, reg.namespace, reg.source_id) - if current is None: - raise DeliveryRefused("setup missing") - data = _secrets(current) - old = data.get("channels") or [] - if ( - not initial - and old - and min(float(c["expiration"]) for c in old) > time.time() + 86400 - ): - return - token = await gdrive.access_token(gdrive.parse_service_account(sources.credential_of(src))) - drives = await gdrive_push.member_drives(token) - corpora = ["", *sorted(drives)] - pending = [ - {"id": str(uuid.uuid4()), "token": secrets.token_urlsafe(32), "drive_id": d} - for d in corpora - ] - async with sources.sources_lease(reg.org, reg.namespace): - with sequential_reads(): - await _fresh(reg) - await _put( - dataclasses.replace( - current, secret_enc=_sealed({**data, "pending_channels": pending}) - ) - ) - try: - for channel in pending: - created.append( - await gdrive_push.watch( - token, - channel_id=channel["id"], - channel_token=channel["token"], - address=callback_url(reg), - drive_id=channel["drive_id"], - ) - ) - async with sources.sources_lease(reg.org, reg.namespace): - with sequential_reads(): - await _fresh(reg) - publication_attempted = True - await _put( - dataclasses.replace( - current, status="active", secret_enc=_sealed({"channels": created}) - ) - ) - except BaseException: - # Cancellation can follow a successful provider request; stop every - # known channel without publishing a response to a retired generation. - if token and created and not publication_attempted: - with contextlib.suppress(TimeoutError): - async with asyncio.timeout(settings.knowledge_source_push_cleanup_timeout_s): - await _stop_channels(token, created) - raise - with contextlib.suppress(TimeoutError): - async with asyncio.timeout(settings.knowledge_source_push_cleanup_timeout_s): - await _stop_channels(token, old) - - -def audit_subject(input: Any, response: Any) -> dict[str, str]: - return {"org": str(input.org), "namespace": str(input.namespace), "name": str(input.name)} diff --git a/server/knowledge/app/source_push_routes.py b/server/knowledge/app/source_push_routes.py deleted file mode 100644 index 5902ba638f..0000000000 --- a/server/knowledge/app/source_push_routes.py +++ /dev/null @@ -1,44 +0,0 @@ -"""Public provider ingress, authenticated by provider proof rather than a Loom token.""" - -from __future__ import annotations - -import asyncio -from typing import Any -from uuid import UUID - -from fastapi import APIRouter, Request, Response - -from server.auth import tenancy -from server.core.ch import set_query_tag -from server.knowledge.app.source_push import receive -from server.knowledge.domain.source_push import MAX_BODY_BYTES, DeliveryRefused - -router = APIRouter() -CALLBACK_TIMEOUT_S = 4.0 # not a setting: acknowledge inside the provider's five-second limit - - -@router.post("/hooks/knowledge/{namespace}/{source_id}/{generation}") -async def notification( - request: Request, org: str, namespace: str, source_id: UUID, generation: UUID -) -> Response: - set_query_tag("knowledge.source.push") - try: - async with asyncio.timeout(CALLBACK_TIMEOUT_S): - # Public callbacks may use an existing placement, never create one. - if not await tenancy.is_held(org): - return Response(status_code=403) - raw = bytearray() - async for chunk in request.stream(): - if len(raw) + len(chunk) > MAX_BODY_BYTES: - return Response(status_code=413) - raw.extend(chunk) - await receive( - org, namespace, str(source_id), str(generation), bytes(raw), dict(request.headers) - ) - except DeliveryRefused: - return Response(status_code=403) - return Response(status_code=200) - - -def attach(app: Any) -> None: - app.include_router(router) diff --git a/server/knowledge/app/source_sync.py b/server/knowledge/app/source_sync.py index 943a95c789..ae7b953b25 100644 --- a/server/knowledge/app/source_sync.py +++ b/server/knowledge/app/source_sync.py @@ -1,84 +1,10 @@ -"""The sync of registered document sources into their namespaces' documents, or for a -mirrored folder source into the namespace's mirror: one pass over every active source, -run by the `knowledge_source_sync` worker and by `loom knowledge sync`. The -shared-folder turn, over its items (`source_gdrive_items`), is below; each other kind, -and a mirrored folder source, has its own turn module (`source_sync_linear`, -`source_sync_notion`, `source_sync_recording`, `source_sync_mirror`), chosen by -`_turn_of`, which builds on the public helpers here (`__all__`). A kind's own -bookkeeping goes in `TurnResult.kind_state`, which the sync state keeps. - -A pass reads the active sources and drops those whose namespace is inactive. The -mirrored sources go first, starting work during the first quarter of the pass under -their own document bound (`_sync_mirrored`); the namespace sources then have the rest of -the pass. Among the namespace sources, those a namespace's admin asked to sync -(`sync_now`) go first, the rest from where the previous pass stopped. Each source's turn -holds the source's own lease, so two copies of the worker never sync it at once. - -A turn lists the source's files: every file on its first turn, when asked (`full`) and -once `knowledge_source_sync_full_interval_seconds` have passed since the last full -listing; otherwise those changed after the stored stamp. A file whose stored copy has -the listed revision, and whose chunks are those of its version or of its revision, is -skipped without a fetch, unless a full listing finds a native document whose stored text -still holds its pictures' bytes and that the sync state has not recorded as checked at -this revision. A changed file is fetched, turned into Markdown and written with -`knowledge.upsert` as `worker:knowledge-source-sync`, `imported`, tagged `source:` -(and, in a mirror, `source-id:`). A native document is exported as Markdown, a -presentation converted slide by slide, and a PDF, `.pptx` or `.docx` file sent to the -extractor service its format is routed to (the server parses no original itself); the -bytes are kept as the document's original. A file that cannot be stored is counted -`unconverted` with its reason and not written. One the store or the extractor refuses, -one over the size bound and one whose write is refused are also given up on their -revision at once, so later passes skip them without a fetch; one with no https link or a -format no extractor declares costs no fetch and is counted again each pass. A file whose -fetch, extraction or write fails in a way that may pass (a 5xx or a timeout on that -file, its extractor call, the write) waits: the turn stays incomplete for `_WAIT_PASSES` -passes on the same revision, then the file is given up on. A given-up file is tried -again when it changes, once after each completed full listing, and on a full sync -request. What fails for every file stays the turn's: the token exchange, the listing, a -401, a rate limit, an extractor whose capabilities cannot be read. - -The source and the address are read again before each write. A source removed or -replaced during its turn stops the turn, which records nothing. A document another -writer saved at the address during the fetch is left alone, and the file is counted -`skipped`. - -A document is retired only on positive evidence that the source dropped it: -absence from a complete full listing whose folders and shared drives the account can -still see, confirmed by a lookup of that file; an address that is no longer its file's; -or an admin's `remove(delete_documents=true)`. A fetch error, a rate limit or a lost -folder or drive retires nothing; past a walk cut at its bound, only the store's word on -a file (trashed, deleted, or of a kind no longer read) retires it. A document another -writer or another source holds is never written or retired. - -The stamp moves only when every listed file was handled (new files held back at -`LOOM_KNOWLEDGE_SOURCE_MAX_DOCUMENTS` wait for the next full listing), so a cut turn is -listed again and its written files are skipped by revision. A listing that outlasts the -pass budget writes nothing (no time is left to write), so a source's listing must fit in -one pass; the item and walk bounds keep it there. - -After the sync, the extraction leg mines into decision rows in the same namespace -(`decision_extract.extract_document`, as `loom decisions extract` does) each of a -namespace source's documents (a mirror's are never mined) whose stored revision is not -the one last mined for it. The mined revision is kept per document in the source's sync -state and written only after that document's extraction settled, so a document a turn -wrote is mined on a later pass whatever stopped this one. A native document is written -with a hash of its title and text, which its mined key carries, so a copy written again -at its mined revision with other text (a reconversion, or its redo after a cut write) is -mined again. The leg holds the source's lease and bills its model calls to the -namespace. A namespace whose own spend on this leg reached -`knowledge_source_sync_cap_share` of its daily cost cap (read before each document; a -cap that cannot be read counts as reached), an org whose model calls are switched off -and a namespace whose calls are held are left for a later pass. A document whose -extraction fails waits like a file: it is tried again for `_WAIT_PASSES` passes on the -same revision, then left until it is written again. Its model reads stop shortly before -the pass's deadline (a try, nothing written; one that had a whole pass's read time is -given up on at once). Each decision's writes run whole with their audit row, and the run -stops writing before the next one once the pass is stopped or the source's lease is -lost. - -`knowledge_source_sync_documents_per_pass` bounds the files fetched, documents -retired and documents mined for namespace sources in one pass. Mirrored sources -have the separate `knowledge_source_mirror_documents_per_pass` bound. +"""Common worker, publication and accounting for selected MCP copies and recordings. + +Each source turn holds its own lease and rechecks current registration authority +before publication. MCP imports use the fixed selected set and protected mirror +engine. Recording sources retain their transcript and decision-extraction path. +Errors and incomplete work never authorize deletion; explicit writer erasure +requests retain the existing retirement pipeline. """ from __future__ import annotations @@ -89,15 +15,14 @@ import dataclasses import functools import logging +import re import time -from collections.abc import AsyncIterator, Awaitable, Callable, Iterator +from collections.abc import AsyncIterator, Awaitable, Callable from dataclasses import dataclass, field, replace from datetime import UTC, datetime, timedelta from enum import StrEnum from typing import TYPE_CHECKING, Any, TypeGuard -from server.clients import gdrive -from server.clients._checked_access import CheckedAccess, Credential from server.code.app.index import repo_registry from server.code.app.index.pass_budget import PassBudget, rotate_to from server.code.domain.index.remote import repo_tag @@ -108,23 +33,19 @@ ) from server.core import leases from server.core.ch import sequential_reads -from server.core.errors import OverloadedError, ValidationError -from server.core.hashing import sha256_text +from server.core.errors import OverloadedError from server.core.pg_lease import PublicationPending from server.knowledge.api.models_knowledge import KnowledgeDeleteInput, KnowledgeUpsertInput -from server.knowledge.app import extractors, private_sync, writes -from server.knowledge.app import source_gdrive_items as gdrive_items +from server.knowledge.app import private_sync, writes from server.knowledge.app import sources as source_ops -from server.knowledge.domain import access_list, convert, transcripts +from server.knowledge.domain import access_list, convert from server.knowledge.domain.sources import ( - GDRIVE_MIME_TYPES, + NAMESPACE_ACCESS, SYNC_WORKER_ACTOR, KnowledgeSource, home, - include_in, json_object, mirror_synced, - mirror_uri, served, source_key, source_tag, @@ -158,10 +79,6 @@ # the default interval, past a restart or a redeploy of the service it needs, and # short enough that one file cannot hold a source's stamp for good. _WAIT_PASSES = 3 # not a setting: a bound on how long one file may stall a stamp -# The sync-state key of the files the picture check flagged but found unchanged. -_PICTURES_CHECKED = "pictures_checked" -# Folder and drive checks a full turn has in flight at once. -_CHECKS_AT_ONCE = 10 # not a setting: a bound on one turn's requests at once # How far behind the listing's start the stamp stays: a file the store stamps just # before the listing but indexes just after it is listed again next turn. _STAMP_SKEW_S = 60.0 # not a setting: a margin on the store's own indexing delay @@ -175,11 +92,7 @@ # finish in any pass: the sync before the leg rarely takes more than a quarter of the # read time. _FULL_READ_SHARE = 0.75 # not a setting: a bound on how much of a pass one document may need -_FORMAT_OF_MIME = { - GDRIVE_MIME_TYPES["pdf"]: "pdf", - GDRIVE_MIME_TYPES["pptx"]: "pptx", - GDRIVE_MIME_TYPES["docx"]: "docx", -} + # Namespaces whose model calls are held, each until its hold ends: the extraction leg # leaves their documents pending. _HELD: Held[tuple[str, str]] = Held() @@ -334,6 +247,11 @@ def _budget() -> PassBudget: return PassBudget(started, started + seconds) +async def require_source_registry() -> None: + await repo_registry.refresh_db_repos() + require_registry_read() + + async def run_sync( *, org: str = "", namespace: str = "", only: str = "", full: bool = False ) -> PassResult: @@ -343,6 +261,10 @@ async def run_sync( result = PassResult() run = Pass(budget=_budget(), left=int(settings.knowledge_source_sync_documents_per_pass)) found = await store.all_active_sources() + if only: + selected = await store.get_source(org, namespace, only) + if selected is not None and mirror_synced(selected): + found.append(selected) if org: found = [s for s in found if (s.org, s.namespace) == (org, namespace)] if only: @@ -350,11 +272,25 @@ async def run_sync( # An admin's delete request goes first, before the backlog of changed files and # before anything that reads the code registry. await _retire_removed_sources(run, result, org=org, namespace=namespace, only=only) + if ( + not org + and settings.auth_actually_required() + and settings.knowledge_mirrored_sources_enabled + ): + from server.knowledge.app.mcp_source_worker import run as run_mcp + + try: + await run_mcp(run.budget.phase(1 - _MIRROR_SHARE), result, full=full) + except Exception as e: # noqa: BLE001 — failed MCP discovery must not stop recording work + result.private_work = True + result.failed += 1 + result.errors.append("MCP_SCHEDULER_UNAVAILABLE") + pass_context.note_failure(RuntimeError("MCP_SCHEDULER_UNAVAILABLE"), "") + log.warning("knowledge_source_sync: MCP admission failed: %s", type(e).__name__) if found: # The repository tags come from the registry: refresh it once per pass, and # stop the pass (RegistryUnread) while it has never been read. - await repo_registry.refresh_db_repos() - require_registry_read() + await require_source_registry() usable = await _usable(found) if full: for src in usable: @@ -372,7 +308,7 @@ async def run_sync( ) rest = [s for s in usable if not _requested(states, s)] order = asked + rotate_to(rest, pass_context.resume_cursor(), key=_cursor_of) - result.sources = len(order) + len(mirrored) + result.sources += len(order) + len(mirrored) for i, src in enumerate(order): if run.spent(): pass_context.set_cursor(_cursor_of(src)) @@ -389,7 +325,7 @@ async def run_sync( pass_context.set_cursor(_cursor_of(src)) break await _extract_pending(order, run, result) - if not order and not mirrored and not result.retired: + if not order and not mirrored and not result.retired and not result.private_work: pass_context.mark_idle() return result @@ -533,12 +469,7 @@ async def _sync_turn( async def _connected_current(src: KnowledgeSource) -> None: - if src.kind == "mcp": - await require_current(src) - else: - from server.knowledge.app.source_sync_connected import ensure_current - - await ensure_current(src) + await require_current(src) def _mirror_failure(src: KnowledgeSource, result: PassResult) -> None: @@ -548,44 +479,15 @@ def _mirror_failure(src: KnowledgeSource, result: PassResult) -> None: def _turn_of(src: KnowledgeSource) -> Callable[..., Awaitable[TurnResult]]: - """The turn function of a source; this module's `_turn` reads a folder, and a - mirrored folder source writes into its namespace's mirror.""" - # Imported here: a kind's module builds on this one's helpers. - if src.kind == "mcp": - if not mirror_synced(src): - raise SourceGone(_cursor_of(src)) + if src.kind == "mcp" and mirror_synced(src): from server.knowledge.app import source_sync_mcp return source_sync_mcp.turn - if ( - src.credential_mode == "connected" - and src.kind in {"notion", "linear"} - and mirror_synced(src) - ): - from server.knowledge.app import source_sync_connected - - return source_sync_connected.turn - if mirror_synced(src): - from server.knowledge.app import source_sync_mirror - - return source_sync_mirror.turn - if not served(src): - # `_usable` keeps such a source out; reaching here is a bug, never a folder turn. - raise ValueError(f"this build does not sync a {src.access} {src.kind!r} source") - kind = src.kind - if kind == "linear": - from server.knowledge.app import source_sync_linear - - return source_sync_linear.turn - if kind == "notion": - from server.knowledge.app import source_sync_notion - - return source_sync_notion.turn - if kind == "recording": + if src.kind == "recording" and served(src): from server.knowledge.app import source_sync_recording return source_sync_recording.turn - return _turn + raise SourceGone(_cursor_of(src)) def full_due(detail: dict[str, Any]) -> bool: @@ -598,133 +500,6 @@ def full_due(detail: dict[str, Any]) -> bool: return age >= int(settings.knowledge_source_sync_full_interval_seconds) -async def _turn(src: KnowledgeSource, state: dict[str, str], run: Pass) -> TurnResult: - """List, fetch, convert and write one source's changed files; retire those a - complete full listing no longer has.""" - detail = json_object(state.get("detail", "")) - stamp = state.get("state_value", "") - turn = TurnResult() - turn.full = bool(detail.get("full")) or not valid_stamp(stamp) or full_due(detail) - start_waits(turn, detail) - # Files whose stored copy the picture check flags but whose conversion changes - # nothing (a definition in a code sample): file id -> the revision checked. - checked = detail.get(_PICTURES_CHECKED) - checked = checked if isinstance(checked, dict) else {} - listed_at = datetime.now(UTC) - opened = await open_listing( - src, turn, run, modified_after="" if turn.full else stamp, check_items=turn.full - ) - if opened is None: - return turn - token, listing, files = opened - # Only a whole listing of items the account still sees, every folder walked, - # says what is absent; past a cut walk only the store's word on a file retires it. - trusted = turn.full and turn.complete and not listing.walk_cut - turn.newest = capped( - max((str(f.get("modifiedTime") or "") for f in files), default=""), listed_at - ) - # A record of a file listed at another revision, or (on a trusted listing) not - # listed at all, no longer says anything. - listed_at_revision = {str(f["id"]): str(f.get("modifiedTime") or "") for f in files} - turn.kind_state[_PICTURES_CHECKED] = { - k: v - for k, v in checked.items() - if (rev := listed_at_revision.get(k)) == v or (rev is None and not trusted) - } - if trusted: - listed_ids = set(listed_at_revision) - turn.waits = {k: v for k, v in turn.waits.items() if k in listed_ids} - # Only a full listing lists an unchanged file, so only it asks for the pictures. - stored = await stored_copies_with_room(src, turn, pictures=turn.full) - for f in files: - if not await sync_file( - src, token, f, source_uri_of(f), stored.get(str(f["id"])), run, turn - ): - break - if turn.full and turn.complete: - # A file listed without an address it can be stored at counts as absent, so - # its document is kept only if the lookup finds the file still there. - addresses = {str(f["id"]): source_uri_of(f) for f in files} - listed = {k: v for k, v in addresses.items() if v.startswith("https://")} - gone = functools.partial(file_gone, token, listing=listing, turn=turn) - await retire_absent(src, listed, gone, run, turn) - return turn - - -async def open_listing( - src: KnowledgeSource, - turn: TurnResult, - run: Pass, - *, - modified_after: str = "", - fields: str = gdrive.LISTED, - check_items: bool = True, -) -> tuple[Credential, gdrive_items.Listing, list[dict[str, Any]]] | None: - """A folder turn's token, listing and listed files with valid ids, after checking - (with `check_items`) that the account still sees every item; None when the turn - must write nothing (a credential that does not open, a failed listing, the pass - running out), with the reason on `turn`.""" - try: - credential = await source_ops.credential_for( - src, - deadline=run.budget.stop_after, - ) - if not credential: - turn.fail("credential_invalid", "the stored credential no longer opens; rotate it") - return None - token: Credential = ( - credential - if isinstance(credential, CheckedAccess) - else await gdrive.access_token(gdrive.parse_service_account(credential)) - ) - listing = await gdrive_items.list_items( - token, - src.items, - include_in(src.config), - modified_after=modified_after, - fields=fields, - out_of_time=run.budget.exhausted, - ) - except (ValidationError, TimeoutError): - turn.fail("credential_invalid", "the source connection is unavailable") - return None - except gdrive.VendorError as e: - vendor_failure(turn, e) - return None - _note_listing(turn, listing) - if listing.ran_out: - return None # out of pass time: nothing more is written or retired this turn - if check_items and not await _items_visible(token, src.items, turn, run.budget.exhausted): - return None - files = [f for f in listing.files if gdrive.valid_file_id(str(f.get("id") or ""))] - turn.documents_seen = len(files) - return token, listing, files - - -def vendor_failure(turn: TurnResult, e: gdrive.VendorError) -> None: - """The turn's status for a failed call to the folder store.""" - if isinstance(e, gdrive.RateLimited): - turn.fail("rate_limited", "rate_limited") - elif isinstance(e, gdrive.CredentialRefused): - turn.fail("credential_invalid", client_error(e)) - else: - turn.fail("failed", client_error(e)) - - -def _note_listing(turn: TurnResult, listing: gdrive_items.Listing) -> None: - """The listing's notes on the turn. An incomplete listing (the store could not search - everything, or an item listed nothing) has its files written, but the turn keeps its - stamp, retires nothing and lists again next pass; a listing the pass ran out on - writes nothing.""" - turn.note = "; ".join([n for n in (listing.walk_cut, *listing.notes) if n]) - if not listing.whole: - turn.mark(TurnMark.INCOMPLETE_SEARCH) - if listing.lost_item: - turn.mark(TurnMark.ITEM_LOST) - if listing.ran_out: - turn.mark(TurnMark.PASS_BOUND) - - async def stored_copies_with_room( src: KnowledgeSource, turn: TurnResult, *, pictures: bool = False ) -> dict[str, dict[str, str]]: @@ -793,113 +568,7 @@ def stamp_of(at: datetime) -> str: def valid_stamp(stamp: str) -> bool: """Whether a stored stamp is one a store reported or `stamp_of` wrote: RFC 3339, UTC, the one form every store's stamps take (the folder client's check).""" - return gdrive.valid_stamp(stamp) - - -def _visibility_checks( - items: list[dict[str, Any]], -) -> Iterator[tuple[Callable[[Credential, str], Awaitable[Any]], str]]: - for item in items: - if item["type"] == "folder": - yield gdrive.require_folder, item["id"] - elif item["type"] == "shared_drive": - yield gdrive.require_drive, item["id"] - elif item["type"] == "filter" and "in" in item: - yield gdrive.require_folder, item["in"] - - -async def _items_visible( - token: Credential, - items: list[dict[str, Any]], - turn: TurnResult, - out_of_time: Callable[[], bool], -) -> bool: - """Whether the turn may go on after checking that the account still sees every folder - and shared drive its items name (a filter's `in` folder too): a lost folder lists - empty rather than refused. False on a rate limit, a 401 or the pass running out (the - turn writes nothing); True after any other failed check, which leaves the turn - failed, so it writes what it listed and retires nothing.""" - checks = list(dict.fromkeys(_visibility_checks(items))) # each folder once - for start in range(0, len(checks), _CHECKS_AT_ONCE): - if out_of_time(): - turn.mark(TurnMark.PASS_BOUND) - return False - batch = checks[start : start + _CHECKS_AT_ONCE] - answers = await asyncio.gather(*(r(token, i) for r, i in batch), return_exceptions=True) - errors = [a for a in answers if isinstance(a, BaseException)] - if any(isinstance(e, gdrive.RateLimited) for e in errors): - turn.fail("rate_limited", "rate_limited") - return False - for e in errors: - if not isinstance(e, gdrive.VendorError): - raise e - if e.status == 401: - turn.fail("credential_invalid", client_error(e)) - return False - if errors: - turn.fail("failed", client_error(errors[0])) - return True - return True - - -async def retire_absent( - src: KnowledgeSource, - listed: dict[str, str], - gone: Callable[[str], Awaitable[bool | None]], - run: Pass, - turn: TurnResult, -) -> None: - """Retire the source's documents whose item a complete listing lacks, or that - sit at an address that is no longer their item's. `listed` maps each listed - item's id to its address. An item missing from the listing is looked up first - with `gone(id)`: a listing paged while items changed can miss one, so only an - item the store reports gone counts. `gone` answers False when the lookup fails - (nothing is retired) and None when the turn must stop (it records why).""" - docs = await store.source_revisions(src.org, *home(src), searchable_only=False) - for doc in docs: - address = listed.get(doc["file_id"]) - if address == doc["source_uri"]: - continue - if run.spent(): - turn.mark(TurnMark.PASS_BOUND) - return - run.left -= 1 - if address is None: - found_gone = await gone(doc["file_id"]) - if found_gone is None: - return - if not found_gone: - continue - await require_current(src) - if await retire(src, doc["source_uri"]): - turn.removed += 1 - - -async def file_gone( - token: Credential, file_id: str, listing: gdrive_items.Listing, turn: TurnResult -) -> bool | None: - """Whether the store says the file is gone: not found, trashed, or reached by none - of the source's items (`Listing.reaches`; after a cut walk, only a kind `include` no - longer names). A lookup that fails retires nothing; a rate limit or a 401 is the - turn's, and None stops the retiring.""" - try: - state = await gdrive.file_state(token, file_id) - except gdrive.NotFound: - return True - except gdrive.RateLimited: - turn.fail("rate_limited", "rate_limited") - return None - except gdrive.VendorError as e: - if e.status == 401: - turn.fail("credential_invalid", client_error(e)) - return None - return False - if state.get("trashed"): - return True - if listing.walk_cut: - # Below the cut a file may still be the source's; a kind it no longer reads is not. - return not listing.reads_kind(state) - return not listing.reaches(file_id, state) + return bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z", stamp)) def client_error(e: BaseException) -> str: @@ -907,18 +576,6 @@ def client_error(e: BaseException) -> str: return str(e)[:200] -def source_uri_of(f: dict[str, Any]) -> str: - """A file's address: the link the store reports, without its query or fragment, - so it reads the same however the link was shared and stays one citation token.""" - link = str(f.get("webViewLink") or "") - return link.split("#", 1)[0].split("?", 1)[0] - - -def bound_source_uri(src: KnowledgeSource, uri: str) -> str: - """Personal copies keep their source identity even when two sources list one URL.""" - return mirror_uri(uri, src.source_id) if src.credential_mode == "connected" and uri else uri - - def _spent(entry: Any) -> TypeGuard[list[Any]]: """Whether a wait entry ([revision, passes, reason]) waited all its passes.""" return isinstance(entry, list) and len(entry) == 3 and int(entry[1]) >= _WAIT_PASSES @@ -1006,165 +663,12 @@ async def sync_item( return True -async def sync_file( - src: KnowledgeSource, - token: Credential, - f: dict[str, Any], - uri: str, - prior: dict[str, str] | None, - run: Pass, - turn: TurnResult, - *, - read_access: Callable[[], Awaitable[access_list.AccessList]] | None = None, -) -> bool: - """Handle one listed file at address `uri`; False when the turn must stop listing. - `read_access` runs at the start of the fetch and gives the permission list the - write carries (`unread` without it). A native document whose stored text still - holds its pictures' bytes (an earlier conversion's) is fetched and converted again - at its same revision when a full listing lists it.""" - revision = str(f.get("modifiedTime") or "") - # A copy stored with its pictures' bytes, at this revision and address, is converted - # again; a moved file takes the ordinary write-and-retire path. - reconvert = bool( - prior is not None - and f.get("mimeType") == GDRIVE_MIME_TYPES["docs"] - and prior.get("inline_pictures") - and prior["source_revision"] == revision - and prior["source_uri"] == uri - # Checked at this revision already: its conversion changed nothing. - and turn.kind_state[_PICTURES_CHECKED].get(str(f["id"])) != revision - ) - if reconvert and _given_up(turn, f): - # Its older copy is still served: not counted unconverted; the waits say when it - # is tried again. - return True - # The stored content's hash, from the full listing's read. - stored_content_sha256 = prior["stored_content_sha256"] if reconvert and prior else "" - before_fetch = functools.partial(_fetchable, f, run, turn) - - async def fetch_and_write() -> str: - # Read last, once the pass bound let the fetch go ahead. - permissions = await read_access() if read_access else access_list.UNREAD - return await _fetch_and_write( - src, - token, - f, - uri, - turn, - stored_content_sha256=stored_content_sha256, - permissions=permissions, - ) - - return await sync_item( - src, f, uri, prior, run, turn, fetch_and_write, before_fetch, refetch=reconvert - ) - - def _given_up(turn: TurnResult, f: dict[str, Any]) -> bool: """Whether the file waited its passes on its listed revision and was given up on.""" entry = turn.waits.get(str(f["id"])) return _spent(entry) and entry[0] == str(f.get("modifiedTime") or "") -async def _fetchable(f: dict[str, Any], run: Pass, turn: TurnResult) -> bool: - """Whether a file goes on to its fetch; one that does not is counted here, at no - fetch and none of the bound.""" - try: - if not await _servable(f, run): - turn.waits.pop(str(f["id"]), None) - turn.unconverted_for("no_extractor") - return False - except extractors.ExtractorUnavailable as e: - # The service its format is routed to cannot be read: the whole format waits, - # the turn's, not this file's. - turn.fail("failed", f"extractor_unavailable: {e}"[:200]) - return False - if _over_size(f): - give_up(f, turn, "too_large") # the listing says so - return False - return True - - -async def _fetch_and_write( - src: KnowledgeSource, - token: Credential, - f: dict[str, Any], - uri: str, - turn: TurnResult, - *, - stored_content_sha256: str, - permissions: access_list.AccessList, -) -> str: - """Fetch, convert and write one file: `written`, `unchanged` (a reconversion whose - text equals the stored copy), `skipped` (another writer took the address during the - fetch), `waiting` (a failure that may pass holds the turn for `_WAIT_PASSES` passes), - `given_up` (a refusal gives the file up at once; for both the wait entry is kept, and - `start_waits` says when it is tried again) or `stop` (the turn's own failure: a rate - limit, a refused credential).""" - try: - fetched = await _fetch(token, f) - except gdrive.RateLimited: - turn.fail("rate_limited", "rate_limited") - return "stop" - except gdrive.TooLarge: - return give_up(f, turn, "too_large") - except gdrive.VendorError as e: - if e.status == 401: - turn.fail("credential_invalid", client_error(e)) - return "stop" - if e.refused: - # The store refuses this one file (an export over its limit, a download - # turned off, an API not enabled): the others go on. - return give_up(f, turn, f"http_{e.status}") - # A 5xx, a timeout, an answer that is not JSON: this file may fetch next time. - reason = f"http_{e.status}" if e.status else "unreachable" - return wait(f, turn, reason, client_error(e)) - except extractors.ExtractionFailed as e: - if not mirror_synced(src): - log.info("knowledge_source_sync: %s not extracted: %s", f["id"], e.code) - return give_up(f, turn, f"extraction_failed:{e.code}") - except extractors.ExtractorUnavailable as e: - # This one file's extraction: the format's other files may still go through. - return wait(f, turn, "extractor_unavailable", f"extractor_unavailable: {e}") - except Exception as e: # noqa: BLE001 — one file's conversion must not stop the others - if not mirror_synced(src): - log.warning("knowledge_source_sync: reading %s failed: %s", f["id"], e) - return wait(f, turn, f"fetch_failed:{type(e).__name__}", type(e).__name__) - await require_current(src) - extra: dict[str, Any] = {"extraction_coverage": fetched.coverage} if fetched.coverage else {} - # A reconversion of a stored copy that held pictures' bytes. - if stored_content_sha256 and sha256_text(fetched.content) == stored_content_sha256: - # The stored text only shows a definition (in a code sample, say): nothing to - # write, mine or embed again, and not fetched again at this revision. - turn.kind_state[_PICTURES_CHECKED][str(f["id"])] = str(f.get("modifiedTime") or "") - return "unchanged" - if f.get("mimeType") == GDRIVE_MIME_TYPES["docs"]: - # The mining step keys a document that carries a text hash by its revision and - # that hash, so text written again at the same revision with other content (a - # reconversion, or its redo after a write cut before its chunks) is mined again; - # a write that fails leaves the old copy and its old key. - extra["text_sha256"] = sha256_text(f"{f.get('name') or ''}\n{fetched.content}") - try: - written = await write_document( - src, - f, - uri, - fetched.content, - ingested_format=fetched.ingested_format, - original=fetched.original, - extra_metadata=extra or None, - permissions=permissions, - ) - except ValidationError as e: - # The write refuses this file whatever the pass: it will not go through. - return give_up(f, turn, f"write_refused:{e.to_detail().get('code') or 'invalid'}") - except Exception as e: # noqa: BLE001 — one file's write must not stop the others - if not mirror_synced(src): - log.warning("knowledge_source_sync: writing %s failed: %s", f["id"], e) - return wait(f, turn, f"write_failed:{type(e).__name__}", type(e).__name__) - return counted(turn, written) - - def give_up(f: dict[str, Any], turn: TurnResult, reason: str) -> str: """A file refused for good: unconverted now, and recorded as given up on its revision, so later passes skip it without a fetch or any of the bound until it @@ -1174,17 +678,6 @@ def give_up(f: dict[str, Any], turn: TurnResult, reason: str) -> str: return "given_up" -def _over_size(f: dict[str, Any]) -> bool: - """Whether the listing already says an uploaded file is over the size bound.""" - if str(f.get("mimeType") or "") not in _FORMAT_OF_MIME: - return False - try: - size = int(f.get("size") or 0) - except (TypeError, ValueError): - size = 0 # unknown: the download's own bound catches it - return size > int(settings.knowledge_source_sync_max_file_bytes) - - def wait(f: dict[str, Any], turn: TurnResult, reason: str, error: str) -> str: """One more pass this file waited on its revision; unconverted once it waited `_WAIT_PASSES`, else the turn stays incomplete. Always `waiting`: the entry @@ -1201,62 +694,6 @@ def wait(f: dict[str, Any], turn: TurnResult, reason: str, error: str) -> str: return "waiting" -@dataclass(frozen=True) -class _Fetched: - content: str - ingested_format: str - original: bytes = b"" - # How much of an uploaded file the extractor read (`convert.coverage_of`). - coverage: dict[str, Any] = field(default_factory=dict) - - -async def _servable(f: dict[str, Any], run: Pass) -> bool: - """Whether the file can be turned into text here: a native document or deck, or - an uploaded file whose format an extractor service declares. ExtractorUnavailable - when the service its format is routed to could not be read: down is not the - same as not serving the format.""" - mime = str(f.get("mimeType") or "") - if mime in (GDRIVE_MIME_TYPES["docs"], GDRIVE_MIME_TYPES["slides"]): - return True - fmt = _FORMAT_OF_MIME.get(mime) - if fmt is None: - return False - if fmt not in run.formats: - url = extractors.endpoint_for(fmt, mime) - if not url: - run.formats[fmt] = False - else: - try: - run.formats[fmt] = fmt in (await extractors.capabilities(url)).formats - except extractors.ExtractorUnavailable: - run.formats[fmt] = None - supported = run.formats[fmt] - if supported is None: - raise extractors.ExtractorUnavailable(f"the extractor for {fmt} could not be read") - return supported - - -async def _fetch(token: Credential, f: dict[str, Any]) -> _Fetched: - """The file as Markdown, with its bytes when it is an uploaded file (`_servable`).""" - file_id, mime = str(f["id"]), str(f.get("mimeType") or "") - max_bytes = int(settings.knowledge_source_sync_max_file_bytes) - if mime == GDRIVE_MIME_TYPES["docs"]: - text = await gdrive.export_markdown(token, file_id, max_bytes=max_bytes) - content = convert.exported_markdown(text) - fmt = "transcript" if transcripts.is_drive_transcript_markdown(content) else "markdown" - return _Fetched(content, fmt) - if mime == GDRIVE_MIME_TYPES["slides"]: - deck = await gdrive.presentation(token, file_id, max_bytes=max_bytes) - return _Fetched(convert.presentation_markdown(deck), "slides") - fmt = _FORMAT_OF_MIME[mime] - data = await gdrive.download(token, file_id, max_bytes=max_bytes) - from server.core.diagnostics import codes_only - - name = f"source.{fmt}" if codes_only() else str(f.get("name") or file_id) - artifact = await extractors.extract(data, name=name, media_type=mime, declared_format=fmt) - return _Fetched(convert.artifact_markdown(artifact), fmt, data, convert.coverage_of(artifact)) - - def counted(turn: TurnResult, written: bool) -> str: """The outcome of a write step: `written`, or `skipped` for an address another writer took during the fetch (counted as the check before the fetch counts it).""" @@ -1293,14 +730,8 @@ async def require_current(src: KnowledgeSource) -> None: fresh = await store.get_source(src.org, src.namespace, src.name) if fresh is None or not fresh.active or fresh.source_id != src.source_id: raise SourceGone(_cursor_of(src)) - if src.credential_mode == "connected": - from server.knowledge.app import connected_accounts - from server.knowledge.store import connected_accounts as accounts_store - - account = await accounts_store.get(src.org, src.owner_subject, src.kind) - if account is None: - raise connected_accounts.unavailable() - await connected_accounts._source_standing(src, account) + if not served(src): + raise SourceGone(_cursor_of(src)) @contextlib.asynccontextmanager @@ -1310,11 +741,6 @@ async def publication_guard(src: KnowledgeSource) -> AsyncIterator[None]: async with mcp_source_authority.publication_guard(src): yield - elif src.credential_mode == "connected": - from server.knowledge.app import connected_accounts - - async with connected_accounts.publication_guard(src): - yield else: yield @@ -1416,7 +842,7 @@ async def retire(src: KnowledgeSource, uri: str) -> bool: deleted = out.deleted except PublicationPending: # the delete is committed; the worker publishes it deleted = True - if deleted and served(src): + if deleted and src.access == NAMESPACE_ACCESS: await audit.emit( "knowledge.delete", org=src.org, @@ -1535,8 +961,8 @@ async def _retire_removed_sources( continue if only and src.name != only: continue - if not served(src): - continue # its documents are in a mirror, which a later build retires + if src.access != NAMESPACE_ACCESS: + continue # protected copies use the existing mirror retirement queue if run.spent(): result.cut = True return @@ -2004,25 +1430,19 @@ async def _write_mined( "capped", "client_error", "counted", - "file_gone", "full_due", "give_up", "index_with_room", "mirror_state", - "open_listing", "ours", "require_current", "retire", - "retire_absent", "run_sync", - "source_uri_of", "stamp_of", "start_waits", "stored_copies_with_room", - "sync_file", "sync_item", "valid_stamp", - "vendor_failure", "wait", "write_document", ] diff --git a/server/knowledge/app/source_sync_connected.py b/server/knowledge/app/source_sync_connected.py deleted file mode 100644 index 56857965aa..0000000000 --- a/server/knowledge/app/source_sync_connected.py +++ /dev/null @@ -1,114 +0,0 @@ -"""Personal page sources reuse their native turn inside the checked mirror boundary.""" - -from __future__ import annotations - -import dataclasses -import functools -import json -from datetime import UTC, datetime - -from server.knowledge.app import ( - connected_accounts, - mirrors, - private_sync, - source_sync_linear, - source_sync_notion, -) -from server.knowledge.app import source_sync as sync -from server.knowledge.app import sources as source_ops -from server.knowledge.domain.sources import KnowledgeSource, json_object, mirror_uri_suffix -from server.knowledge.store import connected_accounts as account_store -from server.knowledge.store import documents -from server.knowledge.store import mirrors as mirror_store -from server.knowledge.store import sources as source_store -from server.workers import pass_context -from server.workers.status import set_worker_identity - - -async def ensure_current(src: KnowledgeSource) -> None: - """Repair a missed lifecycle hook without stopping another namespace's source.""" - try: - await sync.require_current(src) - return - except connected_accounts.OwnerUnavailable: - pass - async with connected_accounts.account_lease(src.org, src.owner_subject, src.kind): - async with source_ops.sources_lease(src.org, src.namespace): - current = await source_store.latest_source(src.org, src.namespace, src.name) - if ( - current is None - or not current.active - or current.source_id != src.source_id - or current.connection_id != src.connection_id - or current.owner_subject != src.owner_subject - or current.credential_mode != "connected" - or current.kind != src.kind - or current.items != src.items - or current.config != src.config - ): - raise sync.SourceGone(sync._cursor_of(src)) - account = await account_store.get(src.org, src.owner_subject, src.kind) - if account is None: - raise connected_accounts.unavailable() - try: - await connected_accounts._source_standing(current, account) - return - except connected_accounts.OwnerUnavailable: - pass - pending = await source_ops._queue_retirement(current) - from server.knowledge.app.source_push import retire - - await retire(current) - await source_store.insert_source( - dataclasses.replace( - current, - active=False, - credential_enc="", - secret_enc="", - pending_delete=pending or current.pending_delete, - ) - ) - await source_store.write_state( - current.org, - current.namespace, - current.name, - state_value="", - detail={"status": "owner_inactive"}, - ) - raise sync.SourceGone(sync._cursor_of(src)) - - -async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: - """Only a complete full listing with current authority vouches for these copies.""" - await sync.require_current(src) - mirror = await mirrors.ensure_mirror( - src.org, - src.namespace, - still_current=functools.partial(sync.require_current, src), - ) - own = await sync.mirror_state(src, mirror) - detail = json_object(own.get("detail", "")) - asked = json_object(state.get("detail", "")) - detail.update({key: asked[key] for key in ("requested_at", "full") if key in asked}) - src = dataclasses.replace(src, mirror=mirror) - started = datetime.now(UTC) - async with private_sync.mirror_costs(src.org, mirror, sync.WORKER): - set_worker_identity(sync.WORKER, org=src.org, namespace=mirror) - # A personal mirror always lists all items. Linear refreshes team ACLs even - # for unchanged text; Notion's owner entry is fixed by its source generation. - native_turn = source_sync_notion.turn if src.kind == "notion" else source_sync_linear.turn - result = await native_turn(src, {"detail": json.dumps(detail), "state_value": ""}, run) - result.mirror = mirror - if ( - result.complete - and result.status == "ok" - and result.full - and not run.budget.exhausted() - and not await documents.publications_owed( - src.org, mirror, mirror_uri_suffix(src.source_id) - ) - ): - pass_context.check_stop() - async with sync.publication_guard(src): - await mirror_store.record_listing(src.org, mirror, src.source_id, src.name, started) - return result diff --git a/server/knowledge/app/source_sync_linear.py b/server/knowledge/app/source_sync_linear.py deleted file mode 100644 index eb13173eb1..0000000000 --- a/server/knowledge/app/source_sync_linear.py +++ /dev/null @@ -1,231 +0,0 @@ -"""One sync turn of a `linear` source: a project tracker's documents, read over its -GraphQL API (`server.clients.linear`). The pass, its bounds, the waits and the -state it records are `server.knowledge.app.source_sync`'s; this module lists, -fetches and retires the documents of one source. - -A project's document list is small, so every turn reads each project's whole list -(ids, titles, stamps and links, every page), with no incremental listing. A -document whose stored copy has the listed revision (`updatedAt`) and address is -skipped without a fetch; a changed one is fetched (its content is Markdown -already) and written with `knowledge.upsert` like a folder's files. Its address -is the document's own link, which changes with its title, so a renamed document is -written at its new address and its old one retired. - -The list is the positive evidence for removals: only when every project was read -on every page is a stored document missing from it looked up, and retired when -the tracker reports it not found, trashed, archived or in none of the source's -projects. A project the key cannot see, or any other listing failure, leaves the -turn failed and retires nothing, while the other projects' documents are written. - -Trouble with one document is that document's, as for a folder's files: a refusal -or a document over the size bound is given up on its revision at once, any other -failure on it waits. A rate limit (a 429 or a GraphQL error typed `ratelimited`) -and a refused key are the turn's. -""" - -from __future__ import annotations - -import functools -import logging -from datetime import UTC, datetime -from typing import Any - -from server.clients import linear -from server.clients._checked_access import Credential -from server.core.ch import sequential_reads -from server.core.errors import ValidationError -from server.knowledge.app import source_sync as sync -from server.knowledge.app import sources as source_ops -from server.knowledge.domain import access_list -from server.knowledge.domain.sources import KnowledgeSource, home, item_ids, json_object -from server.knowledge.store import documents -from server.knowledge.store import sources as store -from server.settings import settings - -log = logging.getLogger("loom.knowledge.source_sync") - - -def _as_file(node: dict[str, Any]) -> dict[str, Any]: - """A listed document under the keys the shared helpers read (`id`, `name`, - `modifiedTime`), with its address.""" - return { - "id": str(node.get("id") or ""), - "name": str(node.get("title") or ""), - "modifiedTime": str(node.get("updatedAt") or ""), - # Without query or fragment, so it stays one citation token. - "uri": str(node.get("url") or "").split("#", 1)[0].split("?", 1)[0], - } - - -async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: - """List every project's documents, write the changed ones, and retire those a - complete list no longer has.""" - detail = json_object(state.get("detail", "")) - result = sync.TurnResult() - # Every list is whole; `full` (the first turn, a full request, the periodic - # one) only grants the given-up documents their retry. - result.full = bool(detail.get("full")) or not state.get("state_value") or sync.full_due(detail) - sync.start_waits(result, detail) - try: - key = await source_ops.credential_for( - src, - deadline=run.budget.stop_after, - ) - except (ValidationError, TimeoutError): - result.fail("credential_invalid", "the source connection is unavailable") - return result - if not key: - # Fail closed: a credential that no longer opens is never read as "no auth". - result.fail("credential_invalid", "the stored credential no longer opens; rotate it") - return result - projects = item_ids(src.items, "project") - listed_at = datetime.now(UTC) - files: dict[str, dict[str, Any]] = {} - for project_id in projects: - try: - permissions = access_list.UNREAD - if src.credential_mode == "connected": - permissions = access_list.AccessList( - owner=src.owner_subject, - emails=await linear.project_member_emails(key, project_id), - ) - nodes = await linear.project_documents(key, project_id) - except linear.RateLimited: - result.fail("rate_limited", "rate_limited") - return result - except linear.CredentialRefused as e: - result.fail("credential_invalid", sync.client_error(e)) - return result - except linear.LinearError as e: - # This project's documents are unknown: nothing is retired this turn, - # and the other projects' documents are still written. - result.fail("failed", sync.client_error(e)) - continue - for node in nodes: - f = _as_file(node) - if src.credential_mode == "connected": - f["uri"] = sync.bound_source_uri(src, f["uri"]) - f["access"] = permissions - if linear.valid_id(f["id"]): - files.setdefault(f["id"], f) - # Only a list read whole, every project on every page, says what is absent. - trusted = result.complete - result.documents_seen = len(files) - newest = max((f["modifiedTime"] for f in files.values()), default="") - result.newest = sync.capped(newest, listed_at) - if trusted: - result.waits = {k: v for k, v in result.waits.items() if k in files} - stored = await sync.stored_copies_with_room(src, result) - if src.credential_mode == "connected": - await _refresh_permissions(src, files, whole=trusted) - for f in files.values(): - fetch_and_write = functools.partial(_fetch_and_write, src, key, f, result) - prior = stored.get(f["id"]) - if not await sync.sync_item(src, f, f["uri"], prior, run, result, fetch_and_write): - break - if trusted and result.complete: - # A document listed without an https link counts as absent, so its stored - # copy is kept only if the lookup finds it still in a project. - listed = {k: f["uri"] for k, f in files.items() if f["uri"].startswith("https://")} - gone = functools.partial(_document_gone, key, projects=set(projects), result=result) - await sync.retire_absent(src, listed, gone, run, result) - return result - - -async def _fetch_and_write( - src: KnowledgeSource, key: Credential, f: dict[str, Any], result: sync.TurnResult -) -> str: - """Fetch and write one document: `written`, `skipped` (another writer took the - address during the fetch), `waiting`, `given_up` or `stop`, as `sync.sync_item` - expects.""" - max_bytes = int(settings.knowledge_source_sync_max_file_bytes) - try: - doc = await linear.document(key, f["id"], max_bytes=max_bytes) - except linear.RateLimited: - result.fail("rate_limited", "rate_limited") - return "stop" - except linear.CredentialRefused as e: - result.fail("credential_invalid", sync.client_error(e)) - return "stop" - except (linear.TooLarge, linear.NotFound) as e: - # Over the bound, or gone since the listing: the next list says which. - return sync.give_up(f, result, e.reason) - except linear.LinearError as e: - if e.refused: - return sync.give_up(f, result, e.reason) - # A 5xx, a timeout, an answer without the document: it may fetch next time. - return sync.wait(f, result, e.reason, sync.client_error(e)) - await sync.require_current(src) - content = str(doc.get("content") or "") - try: - written = await sync.write_document( - src, - f, - f["uri"], - content, - ingested_format="markdown", - permissions=f.get("access", access_list.UNREAD), - ) - except ValidationError as e: - # The write refuses this document whatever the pass: it will not go through. - code = e.to_detail().get("code") or "invalid" - return sync.give_up(f, result, f"write_refused:{code}") - except Exception as e: # noqa: BLE001 — one document's write must not stop the others - log.warning("knowledge_source_sync: writing %s failed: %s", f["id"], e) - return sync.wait(f, result, f"write_failed:{type(e).__name__}", type(e).__name__) - return sync.counted(result, written) - - -async def _refresh_permissions( - src: KnowledgeSource, files: dict[str, dict[str, Any]], *, whole: bool -) -> None: - """Revocation reaches unchanged copies; changed text cannot inherit a wider ACL.""" - from server.knowledge.app import source_sync_mirror - - with sequential_reads(): - copies = await store.every_copy(src.org, *home(src)) - held = {copy["source_uri"]: copy["access_json"] for copy in copies} - held.update(await documents.committed_lists(src.org, src.mirror, list(held))) - listed = {f["uri"]: f for f in files.values()} - changed = {} - for copy in copies: - uri = copy["source_uri"] - f = listed.get(uri) - if f is None and not whole: - continue - previous = access_list.from_json(held[uri]) - current = f["access"] if f is not None else access_list.UNREAD - if f is not None and copy["source_revision"] != f["modifiedTime"]: - current = access_list.common(previous, current) - if current != previous: - changed[uri] = current - if not await source_sync_mirror._write_lists(src, changed): - raise ValidationError("a source copy changed during its permission refresh") - - -async def _document_gone( - key: Credential, document_id: str, projects: set[str], result: sync.TurnResult -) -> bool | None: - """Whether the tracker says the document is gone: not found, trashed, archived, - or in none of the source's projects. A lookup that fails retires nothing; a rate - limit or a refused key is the turn's, and None stops the retiring.""" - if not linear.valid_id(document_id): - return False # not an id the tracker could be asked about: no evidence - try: - state = await linear.document_state(key, document_id) - except linear.NotFound: - return True - except linear.RateLimited: - result.fail("rate_limited", "rate_limited") - return None - except linear.CredentialRefused as e: - result.fail("credential_invalid", sync.client_error(e)) - return None - except linear.LinearError: - return False - project = state.get("project") - project_id = project.get("id") if isinstance(project, dict) else None - return bool(state.get("trashed") or state.get("archivedAt")) or project_id not in projects - - -__all__ = ["turn"] diff --git a/server/knowledge/app/source_sync_mcp.py b/server/knowledge/app/source_sync_mcp.py index cfbb8d1b17..0d702ebf20 100644 --- a/server/knowledge/app/source_sync_mcp.py +++ b/server/knowledge/app/source_sync_mcp.py @@ -19,6 +19,7 @@ from server.knowledge.app import mirrors, private_sync from server.knowledge.app import source_sync as sync from server.knowledge.app.mcp_read_receipt import require_read_receipt +from server.knowledge.app.mcp_source_sessions import checked_session from server.knowledge.domain.access_list import UNREAD, AccessList, to_json from server.knowledge.domain.mcp_identity import resource_uri from server.knowledge.domain.sources import KnowledgeSource, mirror_uri_suffix @@ -212,7 +213,7 @@ async def _read_selected( stored = await sync.stored_copies_with_room(bound.source, result) progress = result.kind_state client = bound.client() - async with client: + async with checked_session(bound.connection.account, client): await client.discover() for index in range(progress["mcp_next_index"], len(bound.contract.resources)): set_query_tag("worker." + sync.WORKER) @@ -227,8 +228,9 @@ async def _read_selected( run.left -= 1 try: evidence = await client.read(selected) - except MCPSourceError: - await _invalidate(bound, selected) + except MCPSourceError as error: + if error.code != "schema": + await _invalidate(bound, selected) raise read_at = datetime.now(UTC) result.documents_seen += 1 diff --git a/server/knowledge/app/source_sync_mirror.py b/server/knowledge/app/source_sync_mirror.py deleted file mode 100644 index 956ade8832..0000000000 --- a/server/knowledge/app/source_sync_mirror.py +++ /dev/null @@ -1,365 +0,0 @@ -"""A mirrored folder-store source's turn: every listing is a full one (no -`modified_after`), and each file is written into the namespace's mirror with the -permission list the store gives it (docs/architecture/document-sources.md, The mirror; -Every complete listing reads the lists again). - -The turn first brings every stored copy's list to what the store says now: the list of -the file listed at its address, or `unread` for a copy a whole listing does not have -there. A copy behind its file's revision takes only the entries both lists hold: its -text was shared under that list, and the content write widens it. A changed list is -written as a new row over the stored one that keeps its chunks, so nothing is embedded -again, and the same list writes nothing. The reads stop at half of what is left of the -mirrors' share when they start, never at the document bound, and what was read is -written. Then each new or changed file is fetched and written with its list, as a folder -turn writes (a mirrored copy is never converted again for the pictures its stored text -holds, as a folder turn does on a full listing), and at the full interval a copy whose -file is gone is retired on the store's word. The listing row lands once every stored -copy's list was brought up to date by a listing that searched everything. - -A source with more files lacking a list than a turn can read goes on from a cursor in the -next turn, and the row of that cycle carries the start of the turn that began it. The -turn's state (that cursor, its waits, counts and error) is under the mirror and the -source's id, the namespace row keeping only the request, status and time. Its model -calls are attributed to the mirror.""" - -from __future__ import annotations - -import asyncio -import contextlib -import dataclasses -import functools -import time -from datetime import UTC, datetime -from typing import Any - -from server.clients import gdrive -from server.clients._checked_access import Credential -from server.code.app.index.pass_budget import PassBudget -from server.core.ch import sequential_reads -from server.core.pg_lease import PublicationPending -from server.knowledge.app import mirrors, private_sync -from server.knowledge.app import source_gdrive_items as gdrive_items -from server.knowledge.app import source_sync as sync -from server.knowledge.domain import access_list -from server.knowledge.domain.sources import ( - KnowledgeSource, - home, - json_object, - mirror_uri, - mirror_uri_suffix, -) -from server.knowledge.store import documents -from server.knowledge.store import mirrors as mirror_store -from server.knowledge.store import sources as store -from server.workers import pass_context -from server.workers.status import set_worker_identity - -# Seconds between two files' permission reads: ten a second stay well under the store's -# per-user rate limit. -PERMISSIONS_PACE_S = 0.1 # not a setting: the store's limit, the same on every deployment -# Why a listing row waits on a publication: one owed passes, one parked needs an operator. -_HELD_BACK = { - "owed": "publication: a write is not in ClickHouse yet", - "parked": "publication: a write is parked; see the knowledge delivery backlog", -} -# List rewrites read and written in one round trip each. -_REWRITE_BATCH = 100 # not a setting: a bound on one statement's size - - -async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: - """List every file of a mirrored source, bring every stored copy's list up to date, - then write its new and changed files and retire the gone ones. `state` is the - namespace row, which holds only the source's sync request; the turn's own state is - under the mirror (`sync.mirror_state`).""" - asked = json_object(state.get("detail", "")) - known = await mirrors.live_mirror(src.org, src.namespace) - detail = await _own_state(src, known, asked) - result = sync.TurnResult() - # Every listing is a full one; `full` is the periodic full interval, which gives - # each given-up file its one more try. - result.full = bool(detail.get("full")) or sync.full_due(detail) - sync.start_waits(result, detail) - started = datetime.now(UTC) - opened = await sync.open_listing(src, result, run, fields=gdrive.LISTED_WITH_PERMISSIONS) - if opened is None: - return result - current = functools.partial(sync.require_current, src) - mirror = await mirrors.ensure_mirror(src.org, src.namespace, still_current=current) - if mirror != known: # a new mirror: nothing the old state says is about it - detail = await _own_state(src, "", asked) - result.full = bool(detail.get("full")) or sync.full_due(detail) - sync.start_waits(result, detail) - result.mirror = mirror - src = dataclasses.replace(src, mirror=mirror) - async with private_sync.mirror_costs(src.org, mirror, sync.WORKER): - set_worker_identity(sync.WORKER, org=src.org, namespace=mirror) - await _in_mirror(src, opened, detail, started, run, result) - return result - - -async def _own_state(src: KnowledgeSource, mirror: str, asked: dict[str, Any]) -> dict[str, Any]: - """The turn's state from under `mirror` ({} without one), with the namespace row's - sync request.""" - own = json_object((await sync.mirror_state(src, mirror)).get("detail", "")) if mirror else {} - return own | {k: asked[k] for k in ("requested_at", "full") if k in asked} - - -async def _in_mirror( - src: KnowledgeSource, - opened: tuple[Credential, gdrive_items.Listing, list[dict[str, Any]]], - detail: dict[str, Any], - started: datetime, - run: sync.Pass, - result: sync.TurnResult, -) -> None: - token, listing, files = opened - if result.complete and not listing.walk_cut: - listed_ids = {str(f["id"]) for f in files} - result.waits = {k: v for k, v in result.waits.items() if k in listed_ids} - # The listed files by the address their copy is stored at. - listed = {u: f for f in files if (u := _address(src, f)).startswith("https://")} - whole = listing.whole and not listing.lost_item - # A head whose row ClickHouse does not have yet is not among the copies read, so one - # owed when they are read leaves the listing vouching for nothing. - suffix = mirror_uri_suffix(src.source_id) - owed = await documents.publications_owed(src.org, src.mirror, suffix) - with sequential_reads(): # a replica behind the last turn would show an older list - copies = await store.every_copy(src.org, *home(src)) - cycle = _Cycle.of(detail) - try: - all_written, stopped_at = await _refresh_lists( - src, token, cycle.rotated(copies), listed, whole, run, result - ) - except _Refused: - return # the store refused the account: nothing more is read or written - lists_good = all_written and whole - vouched = cycle.advance(started, stopped_at, result) if lists_good else None - stored = sync.index_with_room(result, [c for c in copies if c["searchable"]]) - try: - for f in files: - read_access = functools.partial(_source_access, src, token, f, result) - prior = stored.get(str(f["id"])) - uri = _address(src, f) - if not await sync.sync_file( - src, token, f, uri, prior, run, result, read_access=read_access - ): - break - except _Refused: - pass # every stored list is written: the listing row may still land - # As in a folder turn, only a turn at the full interval looks up what the listing no - # longer has: such a copy already reads `unread`, so the wait costs nothing. - if result.full and result.complete: - gone = functools.partial(sync.file_gone, token, listing=listing, turn=result) - by_id = {str(f["id"]): uri for uri, f in listed.items()} - await sync.retire_absent(src, by_id, gone, run, result) - if not lists_good: - return - # Parked at the end outranks owed at the read (that head was not among the copies); - # either holds the row and the cycle back. - held_back = await documents.publications_owed(src.org, src.mirror, suffix) or owed - if held_back: - cycle.keep(result) # the lists read count for nothing: the cycle stays as it was - note = _HELD_BACK[held_back] - if result.error: # the state shows the error alone: the note goes with it - result.error = f"{note}; {result.error}" - else: - _note(result, note, first=True) - return - if vouched is None: - return # the cycle goes on from its cursor in the next turn - pass_context.check_stop() - await sync.require_current(src) # an erasure since the last write lands no row - async with sync.publication_guard(src): - await mirror_store.record_listing(src.org, src.mirror, src.source_id, src.name, vouched) - - -@dataclasses.dataclass(frozen=True) -class _Cycle: - """Where the lists' reads stand across turns: a source with more files lacking a - list than one turn can read goes on from `cursor` (an address) in the next, and the - cycle's listing row carries `since`, the start of the turn that began it.""" - - cursor: str - since: str - - @classmethod - def of(cls, detail: dict[str, Any]) -> _Cycle: - cursor, since = str(detail.get("lists_cursor") or ""), str(detail.get("lists_since") or "") - return cls(cursor, since) if cursor and since else cls("", "") - - def rotated(self, copies: list[dict[str, str]]) -> list[dict[str, str]]: - """The copies from the cursor on, then those before it (they are in address - order).""" - return [c for c in copies if c["source_uri"] >= self.cursor] + [ - c for c in copies if c["source_uri"] < self.cursor - ] - - def advance( - self, started: datetime, stopped_at: str | None, result: sync.TurnResult - ) -> datetime | None: - """Record where the next turn goes on, and return the start a listing row - may carry: this turn's when it read every list, the cycle's when it read the - rest of the cycle's, else None.""" - start = started.isoformat() - if stopped_at is None: - nxt, vouched = _Cycle("", ""), started - elif self.cursor and stopped_at < self.cursor: # past the wrap: the cycle is done - nxt, vouched = _Cycle(stopped_at, start), datetime.fromisoformat(self.since) - else: - nxt, vouched = _Cycle(stopped_at, self.since or start), None - nxt.keep(result) - return vouched - - def keep(self, result: sync.TurnResult) -> None: - result.kind_state.update(lists_cursor=self.cursor, lists_since=self.since) - - -def _address(src: KnowledgeSource, f: dict[str, Any]) -> str: - return mirror_uri(sync.source_uri_of(f), src.source_id) - - -class _Refused(Exception): - """The store refused the account a permission read (a rate limit, a refused - credential); the turn's status says which.""" - - -def _note(result: sync.TurnResult, note: str, *, first: bool = False) -> None: - """Add `note` once, however many files it was for; `first` puts it ahead of the - rest, so the state's 200-character cut keeps it.""" - if note not in result.note: - notes = [note, result.note] if first else [result.note, note] - result.note = "; ".join(filter(None, notes)) - - -async def _refresh_lists( - src: KnowledgeSource, - token: Credential, - copies: list[dict[str, str]], - listed: dict[str, dict[str, Any]], - whole: bool, - run: sync.Pass, - result: sync.TurnResult, -) -> tuple[bool, str | None]: - """Rewrite each stored copy's list to the store's, in the order given, compared - with the one the storage authority holds and written a batch at a time. Whether - every changed list was written (a copy not this source's keeps its own), and the - first copy whose list the lists' half of the share left unread, None when there was - none.""" - all_written = True - stopped_at: str | None = None - # Half of what is left of the leg, so the new and changed files still get time. - now = time.monotonic() - lists_budget = PassBudget(now, now + max(0.0, run.budget.stop_after - now) / 2) - for start in range(0, len(copies), _REWRITE_BATCH): - batch = copies[start : start + _REWRITE_BATCH] - held = {c["source_uri"]: c["access_json"] for c in batch} - revision = {c["source_uri"]: c["source_revision"] for c in batch} - held |= await documents.committed_lists(src.org, src.mirror, list(held)) - changed: dict[str, access_list.AccessList] = {} - try: - for uri in held: - f = listed.get(uri) - if f is None and not whole: - continue # an incomplete search may have missed it: it keeps its list - if f is not None and "permissions" not in f and lists_budget.exhausted(): - # Past the lists' half of the share no list is read, but every one - # that needs no read is still compared; this one keeps its list. The - # cursor carries the cut, so the turn stays complete: retirement and - # the full interval do not wait on a source's lists fitting one turn. - stopped_at = stopped_at or uri - continue - access = ( - access_list.UNREAD if f is None else await _source_access(src, token, f, result) - ) - stored = access_list.from_json(held[uri]) - if f is not None and revision[uri] != str(f.get("modifiedTime") or ""): - # The copy is behind the file: its text was shared under the old - # list, so only a narrowing reaches it; the content write widens. - access = access_list.common(stored, access) - if stored != access: - changed[uri] = access - except _Refused: - await _write_lists(src, changed) # what was read is written all the same - raise - if not await _write_lists(src, changed): - # A listing must not vouch for a list it could not write; later batches go on. - _note(result, "permissions: a stored copy is not this source's to write") - all_written = False - if stopped_at is not None: - _note(result, "permissions: the lists go on from a cursor next turn") - return all_written, stopped_at - - -async def _source_access( - src: KnowledgeSource, token: Credential, f: dict[str, Any], result: sync.TurnResult -) -> access_list.AccessList: - access = await _file_access(token, f, result) - if src.credential_mode != "connected": - return access - # Being listed by this person's own account proves the owner arm even when - # the provider withholds its share list. Discoverable explicit shares remain. - return dataclasses.replace( - access if not access.unread else access_list.AccessList(), owner=src.owner_subject - ) - - -async def _file_access( - token: Credential, f: dict[str, Any], result: sync.TurnResult -) -> access_list.AccessList: - """The file's permission list. The listing leaves it out for a shared drive's files - and for one the account may not share, so it is read then and kept on `f`. A file - the store will not say for, or whose read failed, reads `unread`. _Refused when the - store refused the account.""" - if "permissions" not in f: - pass_context.check_stop() - try: - f["permissions"] = await gdrive.file_permissions(token, str(f["id"])) - except (gdrive.RateLimited, gdrive.CredentialRefused) as e: - sync.vendor_failure(result, e) - raise _Refused from e - except gdrive.VendorError: - f["permissions"] = None # read again next turn - _note(result, "permissions: a file's list could not be read") - else: - if f["permissions"] is None: # a 403 (a Viewer account) or a file gone since - _note(result, "permissions: the store gave no list for a file") - await asyncio.sleep(PERMISSIONS_PACE_S) - return access_list.from_drive_permissions(f.get("permissions")) - - -async def _write_lists(src: KnowledgeSource, lists: dict[str, access_list.AccessList]) -> bool: - """Write each stored document's new list as a new row with everything else as it - was: its chunks are kept, so nothing is embedded again. False when a document is - no longer this source's (a guard: this turn is its addresses' only writer), so its - list stays as it was.""" - if not lists: - return True - if len(lists) > _REWRITE_BATCH: - items = list(lists.items()) - complete = True - for start in range(0, len(items), _REWRITE_BATCH): - complete = ( - await _write_lists(src, dict(items[start : start + _REWRITE_BATCH])) and complete - ) - return complete - pass_context.check_stop() - with sequential_reads(): # a replica behind the last write would carry old content - found = await documents.get_many_by_uris(src.org, src.mirror, list(lists)) - docs = [d for d in found if sync.ours(src, d)] - if docs: - await sync.require_current(src) - rows = [ - documents.build_document_row( - d, - version=documents.version_past(d.version), - access_json=access_list.to_json(lists[d.source_uri]), - ) - for d in docs - ] - async with sync.publication_guard(src): - with contextlib.suppress(PublicationPending): # committed; the worker publishes it - await documents.insert_many(rows, over={d.source_uri: d.version for d in docs}) - return len(docs) == len(found) - - -__all__ = ["PERMISSIONS_PACE_S", "turn"] diff --git a/server/knowledge/app/source_sync_notion.py b/server/knowledge/app/source_sync_notion.py deleted file mode 100644 index 2627b73396..0000000000 --- a/server/knowledge/app/source_sync_notion.py +++ /dev/null @@ -1,582 +0,0 @@ -"""A page store source's turn of the sync pass (`source_sync`): its listed pages, the -pages of its listed databases and the child pages found in them, each written as -one document. - -The pass, its bounds, the waits and the state it records are `source_sync`'s; each -listed page goes through `sync.sync_item`. A turn lists every page on its first -turn, when asked and once a day; otherwise each listed page, each known child page -and the database pages edited after the stored stamp. A page whose stored copy has -the listed revision (its last edit time) and was read at least 90 s after it is -skipped without a fetch; one read sooner is read and written again with its new read -time, so it is skipped once that is past the margin. A changed page's blocks are -read and turned into Markdown (`convert.page_markdown`). The child pages a read page -holds are recorded in the sync state and listed on every later turn, so a child page -is a document of its own; a child found during a turn is synced in the same turn. -How a known child is forgotten is told at `_Turn.known`. - -A listed page or a known child that is in the trash is left out of the listing, so -a full turn's lookup retires its document. A listed page, database or data source -the integration no longer sees, or a database in the trash, fails the turn and -retires nothing, while the pages it still sees are written. A document is retired -only after a complete full listing lacks its page and a lookup of that page finds -it gone: not found, in the trash, or under none of the listed pages, listed -databases, pages the turn listed and children the store refused this turn (for a -page under a block whose holding page is unknown, after walking the block's parents -to that page). -""" - -from __future__ import annotations - -import functools -import json -import logging -from dataclasses import dataclass, field -from datetime import UTC, datetime, timedelta -from typing import Any - -from server.clients import notion -from server.clients._checked_access import Credential -from server.core.errors import ValidationError -from server.core.hashing import sha256_text -from server.knowledge.app import source_sync as sync -from server.knowledge.app import sources as source_ops -from server.knowledge.domain import convert -from server.knowledge.domain.sources import KnowledgeSource, home, item_ids, json_object -from server.knowledge.store import sources as store -from server.settings import settings - -log = logging.getLogger("loom.knowledge.source_sync") - -# Requests one page's blocks may take: about two minutes at the store's pace, so one -# page cannot hold a pass. A page past it is given up as too large. -_MAX_BLOCK_REQUESTS = 300 # not a setting: a bound on one page's share of a pass -# Child pages one source keeps track of. Each is read once a turn for its revision, -# so this many take about 70 s of a turn at the store's pace; more are left out of -# their parent and counted in its `skipped_blocks`. -_MAX_CHILD_PAGES = 200 # not a setting: a bound on one source's share of a pass -# How long after a page's revision a read of it is final: the store's edit stamps -# may be coarser than its edits, and its clock may differ from ours, so a page read -# sooner is read again. -_SETTLE_S = 90.0 # not a setting: a margin on the store's stamp resolution and clock skew -# Blocks a lookup walks up from a page under a block to the page that holds it, when the -# source does not know that page: a column inside a toggle inside a page is three. -_MAX_BLOCK_HOPS = 4 # not a setting: a bound on one lookup's requests - - -def _now() -> datetime: - return datetime.now(UTC) - - -class _TurnStop(Exception): - """A rate limit or a refused token while listing: the turn's, not one page's.""" - - def __init__(self, error: notion.VendorError) -> None: - super().__init__(str(error)) - self.error = error - - -@dataclass -class _Turn: - """One turn's source, token and result, and the pages it handles.""" - - src: KnowledgeSource - token: Credential - result: sync.TurnResult - # Known child pages: child page id -> the id of the page it was found on. A child - # is forgotten in three ways only: its page is read and no longer holds it; a - # complete full turn's lookup finds it gone (and retires its document); or a - # complete full turn read it as not found or trashed and it holds no document. A - # child the store refuses (403) stays known: it waits like a file's trouble. - known: dict[str, str] = field(default_factory=dict) - # The source's stored revisions, by page id. - stored: dict[str, dict[str, str]] = field(default_factory=dict) - # The pages this turn handles, in order; a child found during the turn is appended. - items: list[dict[str, Any]] = field(default_factory=list) - ids: set[str] = field(default_factory=set) - # Known children this turn found gone: not found or trashed. - absent: set[str] = field(default_factory=set) - # Known children the store refused (403) this turn: unread, but still in scope, so - # the pages under them are not taken for moved. - refused: set[str] = field(default_factory=set) - - def add(self, page: dict[str, Any]) -> None: - item = _item(page) - if notion.valid_id(item["id"]) and item["id"] not in self.ids: - self.items.append(item) - self.ids.add(item["id"]) - - -async def turn(src: KnowledgeSource, state: dict[str, str], run: sync.Pass) -> sync.TurnResult: - """List, fetch, convert and write one source's changed pages; retire those a - complete full listing no longer has.""" - detail = json_object(state.get("detail", "")) - stamp = state.get("state_value", "") - result = sync.TurnResult() - result.full = bool(detail.get("full")) or not sync.valid_stamp(stamp) or sync.full_due(detail) - sync.start_waits(result, detail) - try: - token = await source_ops.credential_for( - src, - deadline=run.budget.stop_after, - ) - except (ValidationError, TimeoutError): - result.fail("credential_invalid", "the source connection is unavailable") - return result - if not token: - # Fail closed: a credential that no longer opens is never read as "no auth". - result.fail("credential_invalid", "the stored credential no longer opens; rotate it") - return result - stored_children = detail.get("child_pages") - known = { - str(k): str(v) - for k, v in (stored_children if isinstance(stored_children, dict) else {}).items() - if notion.valid_id(str(k)) - } - stored = await sync.stored_copies_with_room(src, result) - t = _Turn(src, token, result, known=known, stored=stored) - result.kind_state["child_pages"] = t.known - listed_at = _now() - try: - await _list(t, "" if result.full else stamp) - except _TurnStop as stop: - _fail_turn(result, stop.error) - return result - # Only a complete listing of containers the integration still sees says what is absent. - trusted = result.full and result.complete - if trusted: - _drop_out_of_scope(t) - # A known child that waits is not listed while the store refuses it. - result.waits = {k: v for k, v in result.waits.items() if k in t.ids or k in t.known} - # The stamp trails the listing by 150 s, the shared minute plus the settle margin, - # so a database page read within the margin is listed again by the next turn. - newest = max((f["modifiedTime"] for f in t.items), default="") - result.newest = sync.capped(newest, listed_at - timedelta(seconds=_SETTLE_S)) - # Changed pages first: a pass bound spent on settling re-reads delays no edit. - t.items.sort(key=lambda f: not _changed(f, stored.get(f["id"]), src)) - for f in t.items: # a child found while syncing is appended and handled too - if not await _sync_page(t, f, stored.get(f["id"]), run): - break - result.documents_seen = len(t.items) - if trusted and result.complete: - addresses = {f["id"]: sync.bound_source_uri(src, sync.source_uri_of(f)) for f in t.items} - listed = {k: v for k, v in addresses.items() if v.startswith("https://")} - - gone = functools.partial(_page_gone, t) - await sync.retire_absent(src, listed, gone, run, result) - if result.complete: - await _forget_unlisted_without_documents(t) - return result - - -async def _forget_unlisted_without_documents(t: _Turn) -> None: - """After a complete full turn: forget the known children this turn found not found - or trashed that hold no document (never written, or retired), so a child gone for - good costs no read each turn.""" - src = t.src - held = { - d["file_id"] - for d in await store.source_revisions(src.org, *home(src), searchable_only=False) - } - for child_id in list(t.known): - if child_id in t.absent and child_id not in held: - t.known.pop(child_id) - - -def _changed( - f: dict[str, Any], stored: dict[str, str] | None, src: KnowledgeSource | None = None -) -> bool: - """Whether a listed page differs from its stored copy: none stored, another - revision or another address.""" - if stored is None: - return True - uri = sync.source_uri_of(f) - if src is not None: - uri = sync.bound_source_uri(src, uri) - return stored["source_revision"] != f["modifiedTime"] or stored["source_uri"] != uri - - -def _item(page: dict[str, Any]) -> dict[str, Any]: - """A listed page in the shape the shared turn helpers read, with its parent.""" - parent = page.get("parent") or {} - return { - "id": str(page.get("id") or ""), - "name": notion.title_of(page), - "modifiedTime": str(page.get("last_edited_time") or ""), - "webViewLink": str(page.get("url") or ""), - "parent_page": str(parent.get("page_id") or ""), - # A page under a block (a column, a toggle, a list item, a synced block) names - # the block, not the page that holds it. - "parent_block": str(parent.get("block_id") or ""), - "parent_database": str(parent.get("database_id") or ""), - } - - -def _ends_turn(e: notion.VendorError) -> bool: - """A rate limit or a refused token: the turn's, not one page's.""" - return isinstance(e, notion.RateLimited) or e.status == 401 - - -# The wait reason of a known child the store refuses (403). -_CHILD_REFUSED = "child_http_403" - - -def _child_refused(t: _Turn, child_id: str, e: notion.VendorError) -> None: - """A known child the store refuses (403): a refused permission says nothing of - whether the page still exists, so the child stays known and its document is kept. - It waits like a file's trouble, keyed by its stored revision: the turn fails for - the passes a file may wait, then the child is counted unconverted and no longer - holds the turn (or the source's retirements) back.""" - t.refused.add(child_id) - stored = t.stored.get(child_id) - f = {"id": child_id, "modifiedTime": stored["source_revision"] if stored else ""} - sync.wait(f, t.result, _CHILD_REFUSED, sync.client_error(e)) - - -def _read_again(t: _Turn, child_id: str) -> None: - """A known child readable again: its refusal wait no longer applies.""" - entry = t.result.waits.get(child_id) - if isinstance(entry, list) and len(entry) == 3 and entry[2] == _CHILD_REFUSED: - del t.result.waits[child_id] - - -def _fail_turn(result: sync.TurnResult, e: notion.VendorError) -> None: - if isinstance(e, notion.RateLimited): - result.fail("rate_limited", "rate_limited") - else: - result.fail("credential_invalid", sync.client_error(e)) - - -def _container_failed(result: sync.TurnResult, e: notion.VendorError) -> None: - """A listed page, database or data source, or a known child, that could not be - read: the turn fails and retires nothing, but goes on with the others. A rate - limit or a 401 stops it.""" - if _ends_turn(e): - raise _TurnStop(e) - result.fail("failed", sync.client_error(e)) - - -async def _list(t: _Turn, edited_after: str) -> None: - """The listed pages, the pages of the listed databases (only those edited after - `edited_after` when it is set) and the known child pages. A page in the trash or - a child the store no longer has is left out, so a full listing's lookup retires - its document.""" - for page_id in item_ids(t.src.items, "page"): - try: - page = await notion.page(t.token, page_id) - except notion.VendorError as e: - _container_failed(t.result, e) - continue - if not page.get("in_trash"): - t.add(page) - for database_id in item_ids(t.src.items, "database"): - try: - db = await notion.database(t.token, database_id) - except notion.VendorError as e: - _container_failed(t.result, e) - continue - if db.get("in_trash"): - # Its pages are not removed one by one, so nothing says which to retire. - t.result.fail("failed", f"database {database_id}: in the trash") - continue - for data_source_id in notion.data_source_ids(db): - try: - found, whole = await notion.query_pages( - t.token, data_source_id, edited_after=edited_after - ) - except notion.VendorError as e: - _container_failed(t.result, e) - continue - for page in found: - if not page.get("in_trash"): - t.add(page) - if not whole: - # Write what it listed, but keep the stamp and retire nothing. - t.result.mark(sync.TurnMark.INCOMPLETE_RESULT) - for child_id in list(t.known): - try: - page = await notion.page(t.token, child_id) - except notion.NotFound: - t.absent.add(child_id) # a full turn's lookup decides - continue - except notion.VendorError as e: - # A 403 that is a rate limit ends the turn (`_container_failed`). - if isinstance(e, notion.CredentialRefused) and e.status == 403: - _child_refused(t, child_id, e) - else: - _container_failed(t.result, e) - continue - _read_again(t, child_id) - if page.get("in_trash"): - t.absent.add(child_id) - else: - t.add(page) - - -def _holder(t: _Turn, f: dict[str, Any]) -> str: - """The page a child page sits in: its parent page, or for a page under a block, - the page whose blocks held it when that page was last read.""" - if f["parent_block"]: - return t.known.get(f["id"], "") - return str(f["parent_page"]) - - -def _drop_out_of_scope(t: _Turn) -> None: - """After a complete full listing: leave out the known children no longer under a - listed page, a listed database's page or another such child (a child moved - elsewhere), so their documents count as absent and the lookup decides. A child the - store refused this turn counts as in scope: nothing says it moved.""" - in_scope = {f["id"] for f in t.items if f["id"] not in t.known} | t.refused - children = [f for f in t.items if f["id"] in t.known] - grew = True - while grew: - grew = False - for f in children: - if f["id"] not in in_scope and _holder(t, f) in in_scope: - in_scope.add(f["id"]) - grew = True - t.items = [f for f in t.items if f["id"] in in_scope] - t.ids = in_scope - t.refused - - -async def _page_gone(t: _Turn, page_id: str) -> bool | None: - """Whether the store says the page is gone, as `_lookup` answers; a known child - found gone is forgotten. A child refused this turn is kept with no second read.""" - if page_id in t.refused: - return False - gone = await _lookup(t, page_id) - if gone: - t.known.pop(page_id, None) - return gone - - -async def _lookup(t: _Turn, page_id: str) -> bool | None: - """Whether the store says the page is gone: not found, in the trash, or under none - of the listed pages, listed databases, pages this turn listed and children the - store refused this turn. For a page under a block whose holding page the source - does not know, the block's parents are walked up to that page (`_block_page`). A - page the store refuses (403) or fails on, or whose walk fails, is kept; a rate - limit or a 401 is the turn's, and None stops the retiring.""" - try: - page = await notion.page(t.token, page_id) - except notion.VendorError as e: - if _ends_turn(e): - _fail_turn(t.result, e) - return None - # Only a 404 says the page is gone; a refusal (403) or a failure keeps it. - return isinstance(e, notion.NotFound) - if page.get("in_trash"): - return True - item = _item(page) - if page_id in item_ids(t.src.items, "page") or item["parent_database"] in item_ids( - t.src.items, "database" - ): - return False - holder = _holder(t, item) - if item["parent_block"] and not holder: - try: - walked = await _block_page(t, item["parent_block"]) - except notion.VendorError as e: - _fail_turn(t.result, e) # a rate limit or a 401 - return None - if walked is None: - return False # the walk could not tell: kept - holder = walked - if holder not in t.ids and holder not in t.refused: - return True - # Still under a page this turn listed, but not known (left out at the cap, or - # dropped when its page was read without it): known again, so it is synced. - if page_id not in t.known and len(t.known) < _MAX_CHILD_PAGES: - t.known[page_id] = holder - return False - - -async def _block_page(t: _Turn, block_id: str) -> str | None: - """The page a block sits in, walking its parents up (at most `_MAX_BLOCK_HOPS` - requests): its id, "" when the walk reaches no page (the workspace, or a block the - store answers 404 for), or None when it cannot tell (another failure, an unexpected - parent, the bound). A block the store answers 404 for is not shared with the - integration, while every block under the listed pages and databases is, so the - page is outside the source. A rate limit or a 401 is raised.""" - for _ in range(_MAX_BLOCK_HOPS): - if not notion.valid_id(block_id): - return None - try: - block = await notion.block(t.token, block_id) - except notion.NotFound: - return "" - except notion.VendorError as e: - if _ends_turn(e): - raise - return None - parent = block.get("parent") or {} - if parent.get("type") == "page_id": - page_id = str(parent.get("page_id") or "") - return page_id if notion.valid_id(page_id) else None - if parent.get("type") == "workspace": - return "" - if parent.get("type") != "block_id": - return None - block_id = str(parent.get("block_id") or "") - return None - - -def _settled(revision: str, read_at: str) -> bool: - """Whether a copy read at `read_at` holds every edit stamped `revision`.""" - try: - edited, read = datetime.fromisoformat(revision), datetime.fromisoformat(read_at) - except ValueError: - return False - return (read - edited).total_seconds() >= _SETTLE_S - - -async def _sync_page( - t: _Turn, f: dict[str, Any], prior: dict[str, str] | None, run: sync.Pass -) -> bool: - """Handle one listed page; False when the turn must stop listing.""" - uri = sync.bound_source_uri(t.src, sync.source_uri_of(f)) - # Read too soon after its revision: a later edit may share the stamp, so the page is - # read and written again, with the new read time; once that is past the margin, the - # stored copy lets the page be skipped. - unsettled = bool( - prior - and prior["source_uri"] == uri - and not _settled(f["modifiedTime"], prior.get("read_at", "")) - ) - fetch_and_write = functools.partial(_fetch_and_write, t, f, uri) - if not await sync.sync_item( - t.src, f, uri, prior, run, t.result, fetch_and_write, refetch=unsettled - ): - return False - # A rate limit or a refused token while listing the page's new children. - return t.result.status not in ("rate_limited", "credential_invalid") - - -async def _fetch_and_write(t: _Turn, f: dict[str, Any], uri: str) -> str: - """Read one page's blocks, record its child pages, convert and write them: - `written`, `skipped` (another writer took the address during the fetch), `waiting`, - `given_up` or `stop`, as `sync.sync_item` expects.""" - result = t.result - read_at = _now() - try: - blocks = await notion.page_blocks(t.token, f["id"], max_requests=_MAX_BLOCK_REQUESTS) - content, skipped = convert.page_markdown(blocks) - except notion.TooLarge: - return sync.give_up(f, result, "too_large") - except notion.VendorError as e: - if _ends_turn(e): - _fail_turn(result, e) - return "stop" - if e.refused: - return sync.give_up(f, result, f"http_{e.status}") - reason = f"http_{e.status}" if e.status else "unreachable" - return sync.wait(f, result, reason, sync.client_error(e)) - except Exception as e: # noqa: BLE001 — one page's conversion must not stop the others - log.warning("knowledge_source_sync: reading %s failed: %s", f["id"], e) - return sync.wait(f, result, f"fetch_failed:{type(e).__name__}", type(e).__name__) - children = convert.child_page_ids(blocks) - found = _record_children( - t, f["id"], children, skipped, whole=not convert.unreadable_blocks(blocks) - ) - if not content.strip(): - outcome = sync.give_up(f, result, "no_text") - elif len(content.encode()) > int(settings.knowledge_source_sync_max_file_bytes): - outcome = sync.give_up(f, result, "too_large") - else: - outcome = await _write(t, f, uri, content, skipped, read_at) - # A rate limit or a refused token here ends the turn after this page's outcome, - # so a written page's old address is still retired (`_sync_page`). - await _add_new_children(t, found) - return outcome - - -def _exact_hash(f: dict[str, Any], content: str, skipped: dict[str, int]) -> str: - """A hash of exactly what a write stores for the page: its title, its Markdown as - written (whitespace included) and the blocks left out. The mining step keys the - document by it, so a copy written again with the same text is not mined again.""" - left_out = json.dumps(skipped, sort_keys=True) - return sha256_text(f"{f['name']}\n{content}\n{left_out}") - - -async def _write( - t: _Turn, - f: dict[str, Any], - uri: str, - content: str, - skipped: dict[str, int], - read_at: datetime, -) -> str: - await sync.require_current(t.src) - metadata: dict[str, Any] = { - "read_at": sync.stamp_of(read_at), - "text_sha256": _exact_hash(f, content, skipped), - } - if skipped: - metadata["skipped_blocks"] = skipped - try: - written = await sync.write_document( - t.src, f, uri, content, ingested_format="blocks", extra_metadata=metadata - ) - except ValidationError as e: - # The write refuses this page whatever the pass: it will not go through. - code = e.to_detail().get("code") or "invalid" - return sync.give_up(f, t.result, f"write_refused:{code}") - except Exception as e: # noqa: BLE001 — one page's write must not stop the others - log.warning("knowledge_source_sync: writing %s failed: %s", f["id"], e) - return sync.wait(f, t.result, f"write_failed:{type(e).__name__}", type(e).__name__) - return sync.counted(t.result, written) - - -def _record_children( - t: _Turn, parent: str, children: list[str], skipped: dict[str, int], *, whole: bool -) -> list[str]: - """Record the child pages a read page holds, replacing what it held before when its - blocks were read `whole`; when some could not be read (a synced copy of an - unshared original), the children it held before stay. The ones past - `_MAX_CHILD_PAGES` are counted in its `skipped_blocks`. Returns the recorded ones - this turn has not listed.""" - for child, held_by in list(t.known.items()): - if whole and held_by == parent and child not in children: - t.known.pop(child) - listed_pages = set(item_ids(t.src.items, "page")) - over = 0 - for child in children: - if child in listed_pages or not notion.valid_id(child): - continue - if child not in t.known and len(t.known) >= _MAX_CHILD_PAGES: - over += 1 - continue - t.known[child] = parent - if over: - skipped["child_page"] = skipped.get("child_page", 0) + over - # A child refused this turn is not read again in it, so its wait moves once a turn. - return [c for c in children if c in t.known and c not in t.ids and c not in t.refused] - - -async def _add_new_children(t: _Turn, children: list[str]) -> None: - """List the children a read page holds that this turn has not, so they are synced - in this turn. A rate limit or a refused token ends the turn (its status says so). - A child that cannot be read now stays known and is read next turn: a refused one - (403) waits like a file's trouble, and any other failure but not found leaves the - turn incomplete, so a failed or cut turn forgets no child it could not read.""" - for child in children: - try: - page = await notion.page(t.token, child) - except notion.VendorError as e: - if _ends_turn(e): - _fail_turn(t.result, e) - return - if isinstance(e, notion.NotFound): - t.absent.add(child) - elif e.status == 403: - _child_refused(t, child, e) - else: - t.result.fail("failed", sync.client_error(e)) - continue - _read_again(t, child) - if page.get("in_trash"): - t.absent.add(child) - else: - t.add(page) - - -__all__ = ["turn"] diff --git a/server/knowledge/app/sources.py b/server/knowledge/app/sources.py index ee0599b09c..6059f9b6fb 100644 --- a/server/knowledge/app/sources.py +++ b/server/knowledge/app/sources.py @@ -1,26 +1,8 @@ -"""knowledge.source.* — the document sources a namespace's admins register for -Loom to pull from. - -Every op is addressed by the namespace the source's documents live in, so the -transport's namespace gate decides who may call: -readers list and inspect and parse links, the namespace's admins add, update, -check, rotate, remove and ask for a sync. The credential is sealed at rest under -its own purpose (one for a source a build without items can read, another for the -rest, see `store`), held in memory only for a probe, and never returned or -audited. - -Nothing here fetches documents: the sync worker does, outside the request path -(`server.knowledge.app.source_sync`). `sync_now` records what the worker should do -next in the source's sync state; `remove(delete_documents=true)` records it on the -inactive registry row it writes. - -Every write of a namespace's sources, registry rows and sync state alike (add, -update, rotate, remove, sync_now, and the retirement when the namespace goes: -code.repo.remove, namespace.delete, collection.delete and the erasure step -`knowledge_sources.retire`), runs under `sources_lease`, which serializes them; the -probes run outside it. - -Which documents are a source's: see `SYNC_WORKER_ACTOR`. +"""Shared recording setup and generic source retirement under destination leases. + +MCP connection and selected-resource controls use their dedicated common-protocol +operations. Unsupported stored registrations remain opaque; retiring them and +explicitly erasing their copies require the existing destination authority. """ from __future__ import annotations @@ -30,22 +12,20 @@ import dataclasses import time import uuid -from collections.abc import AsyncIterator, Container, Iterator +from collections.abc import AsyncIterator, Iterator from datetime import UTC, datetime -from typing import Any, NamedTuple +from typing import Any -from server.auth import authz, machines +from server.auth import authz from server.auth.context import current_auth, current_caller 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.ch import sequential_reads from server.core.datetimes import as_aware_utc from server.core.diagnostics import private_work from server.core.errors import ( AuthInsufficientError, - BadConfigError, ErasureRunningError, NotFoundError, OverloadedError, @@ -64,9 +44,6 @@ KnowledgeSourceInspectOutput, KnowledgeSourceListInput, KnowledgeSourceListOutput, - KnowledgeSourceParsedLink, - KnowledgeSourceParseLinksInput, - KnowledgeSourceParseLinksOutput, KnowledgeSourceProbe, KnowledgeSourceRemoveInput, KnowledgeSourceRemoveOutput, @@ -75,12 +52,9 @@ KnowledgeSourceSync, KnowledgeSourceSyncNowInput, KnowledgeSourceSyncNowOutput, - KnowledgeSourceUpdateInput, - KnowledgeSourceUpdateOutput, ) from server.knowledge.app import source_access, source_probes, source_publication, source_titles 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 sources as store from server.operations.base import Role @@ -106,23 +80,15 @@ def _now_iso() -> str: def credential_of(src: KnowledgeSource) -> str: """The source's credential, '' when it no longer opens.""" - if src.credential_mode != "shared": - return "" # A connected source never falls back to an ingestion credential. - if src.secret_enc: - return unseal(_SECRET_PURPOSE, src.secret_enc) + if not domain.served(src): + return "" return unseal(_CREDENTIAL_PURPOSE, src.credential_enc) -async def credential_for(src: KnowledgeSource, *, deadline: float) -> Credential: - """A connected row selects only its exact owner and generation, never shared auth.""" - if src.credential_mode == "connected": - from server.knowledge.app.connected_accounts import checked_for - - return await checked_for(src, deadline=deadline) - if src.credential_mode != "shared": - raise ValidationError( - "the source credential mode is unavailable", code="CREDENTIAL_REFUSED" - ) +async def credential_for(src: KnowledgeSource, *, deadline: float) -> str: + del deadline + if not domain.served(src): + raise ValidationError("this source credential is unavailable", code="CREDENTIAL_REFUSED") return credential_of(src) @@ -143,158 +109,18 @@ def _require_sealable(credential: str) -> None: def _with_credential(src: KnowledgeSource, credential: str) -> KnowledgeSource: - """`src` with `credential` sealed where its storage rule puts it.""" - if domain.id_list_config(src) is not None: - return dataclasses.replace( - src, credential_enc=_sealed(_CREDENTIAL_PURPOSE, credential), secret_enc="" - ) + if not domain.served(src): + raise ValidationError("this source kind is unavailable", code="BAD_KIND") return dataclasses.replace( - src, credential_enc="", secret_enc=_sealed(_SECRET_PURPOSE, credential) + src, credential_enc=_sealed(_CREDENTIAL_PURPOSE, credential), secret_enc="" ) -def _stored_options(kind: str, items: list[dict[str, Any]], include: list[str]) -> dict[str, Any]: - """The config a source of `items` stores: a `gdrive` source's `include`, checked - against its filters; nothing for the other kinds.""" - if kind != "gdrive": - return {} - domain.check_filters(items, include) - return {"include": include} - - -async def _require_fleet_for(kind: str, items: list[dict[str, Any]]) -> None: - """Refuse a source that would be stored with `kind` empty while a live process of - any deployment may run a build without items: it would list the source with no kind - (docs/architecture/rolling-upgrades.md). An unread fleet refuses too.""" - if kind == "recording" or domain.fits_id_list(kind, items): - return - if not await machines.fleet_at(ch.get_client(), _ITEMS_MIGRATION): - raise OverloadedError( - "not every Loom process reads a source of these items yet; retry once the " - "rollout is done", - retry_after_s=30, - ) - - -def _items_of( - kind: str, - items: list[dict[str, Any]], - links: list[str], - prefix: str = "", - held: KnowledgeSource | None = None, -) -> list[dict[str, Any]]: - """`items` and the items `links` name, checked, a refusal naming the fields they - came in (`items`, `links`); BAD_LINK names the first links that - name none or one of another kind, and counts the rest. A link to something `held` - holds takes the held form (a recursive folder, a drive at its root); an item given - for the same thing wins over the link.""" - given = domain.parse_items(kind, items, f"{prefix}items") if items else [] - linked: list[dict[str, Any]] = [] - unread: list[str] = [] - for parsed in parse_links(links): - if parsed.unreadable: - unread.append(f"{domain.shown(parsed.link)}: {parsed.unreadable[:100]}") - elif parsed.kind != kind: - unread.append(f"{domain.shown(parsed.link)}: a {parsed.kind} link, not {kind}") - else: - linked.append(parsed.item) - if unread: - more = f"; and {len(unread) - _LINKS_NAMED} more" if len(unread) > _LINKS_NAMED else "" - message = f"unreadable {prefix}links: " + "; ".join(unread[:_LINKS_NAMED]) + more - raise ValidationError(message, code="BAD_LINK") - if held is not None: - linked = _as_held(held, linked) - keys = {domain.item_key(i) for i in given} - return domain.unique_items(given + [i for i in linked if domain.item_key(i) not in keys]) - - -def _without_drive_folders(items: list[dict[str, Any]]) -> list[dict[str, Any]]: - """`items` less each folder a shared drive of its id is given beside: the drive reads - all the folder does.""" - drives = {i["id"] for i in items if i["type"] == "shared_drive"} - return [i for i in items if not (i["type"] == "folder" and i.get("id") in drives)] - - -def _named(items: list[dict[str, Any]]) -> int: - """How many things `items` (each once) name at least: a short id and an id may name - the same project.""" - slugs = sum(1 for i in items if "slug_id" in i) - return max(len(items) - slugs, slugs) - - -def _require_count(kind: str, items: list[dict[str, Any]], fields: list[str]) -> None: - """BAD_CONFIG naming `fields` when `items` name more than a source of `kind` holds; a - lower bound before short ids are resolved (`_named`).""" - if _named(items) > domain.max_items(kind): - sent = " and ".join(fields) - raise BadConfigError(f"{sent}: at most {domain.max_items(kind)} items for a {kind} source") - - -def _include(include: list[str] | None, kind: str) -> list[str] | None: - if include is None: - return None - if kind != "gdrive": - raise BadConfigError("include: a gdrive source's option") - return domain.parse_include(include) - - -def _registration( - input: KnowledgeSourceAddInput, kind: str, sent: list[str] -) -> tuple[dict[str, Any], list[dict[str, Any]]]: - """The config and items an add registers, from its config or its items and links - (the fields `sent`).""" - if input.config is None and not sent: - raise BadConfigError("give config, or items or links") - if input.config is not None and sent: - raise BadConfigError("config takes no items or links") - include = _include(input.include, kind) - if input.config is not None: - if include is not None: - raise BadConfigError("with config, give include inside it") - config = domain.parse_config(kind, input.config) - return domain.options_in(kind, config), domain.items_from_config(kind, config) - if kind == "recording": - raise BadConfigError("a recording source takes config, not items") - items = _without_drive_folders(_items_of(kind, input.items or [], input.links or [])) - if not items: - raise BadConfigError(f"{' and '.join(sent)}: 1 to {domain.max_items(kind)} items") - _require_count(kind, items, sent) - return _stored_options(kind, items, include or list(domain.GDRIVE_DEFAULT_INCLUDE)), items - - -async def _probe_items( - kind: str, - items: list[dict[str, Any]], - config: dict[str, Any], - credential: Credential, - suffix: str = "", -) -> tuple[KnowledgeSourceProbe, list[dict[str, Any]]]: - """Probe the sample of `items` (`source_probes.sample`); the probe and `items` as - the store names them, each once (a recursive folder the probe found is a shared - drive's root becomes that drive). A refusal about one item ends with `suffix`.""" - checked = source_probes.sample(items) - with _store_refusals(suffix): - found = await source_probes.probe(kind, config, credential, items=checked) - if found.trashed: - message = f"the source could not be listed: file {found.trashed[0]}: in the trash" - raise ValidationError(f"{message}; restore it first{suffix}", code="SOURCE_UNREACHABLE") - if found.foreign: - fid, mime = next(iter(found.foreign.items())) - message = f"file {fid}: {domain.unread_file_note(mime)}" - raise BadConfigError(message + suffix) - if found.items: - items = domain.unique_items(items[: len(items) - len(checked)] + found.items) - return _probe_answer(found, len(checked), len(items)), items - - -def _probe_answer(found: source_probes.Probe, checked: int, of: int) -> KnowledgeSourceProbe: - """What a probe of `checked` of a source's `of` items found, as an op answers it.""" +def _probe_answer(found: source_probes.Probe) -> KnowledgeSourceProbe: return KnowledgeSourceProbe( documents=found.documents, more=found.more, sample=found.sample, - checked=checked, - sampled=checked < of, ) @@ -355,6 +181,8 @@ def _require_kind(kind: str) -> None: async def _source_or_404(org: str, namespace: str, name: str) -> KnowledgeSource: src = await store.get_source(org, namespace, domain.normalize_name(name)) + if src is not None and src.kind == "mcp": + raise NotFoundError("no document source", code="SOURCE_NOT_FOUND") if src is None: raise NotFoundError( f"no document source {domain.shown(name)} in {namespace!r}", code="SOURCE_NOT_FOUND" @@ -379,26 +207,15 @@ def _require_served(src: KnowledgeSource) -> None: @contextlib.contextmanager -def _store_refusals(suffix: str = "", about: Container[str] | None = None) -> Iterator[None]: - """A probe's or a lookup's refusal, as the op answers it; one about an item (of - `about`, when given) ends with `suffix`, which carries its own separator.""" +def _store_refusals() -> Iterator[None]: try: yield - except source_probes.CredentialRefused as e: + except source_probes.CredentialRefused: raise ValidationError( - f"the source refused the credential: {e}", code="CREDENTIAL_REFUSED" + "the source refused the credential", code="CREDENTIAL_REFUSED" ) from None - except source_probes.SourceUnreachable as e: - named = e.item_id and (about is None or e.item_id in about) - message = f"the source could not be listed: {e}" - raise ValidationError( - message + (suffix if named else ""), code="SOURCE_UNREACHABLE" - ) from None - - -def _answered_include(src: KnowledgeSource) -> list[str]: - """`include` as the ops answer it: [] for a kind without file kinds.""" - return domain.include_in(src.config) if src.kind == "gdrive" else [] + except source_probes.SourceUnreachable: + raise ValidationError("the source could not be listed", code="SOURCE_UNREACHABLE") from None def _sync(src: KnowledgeSource, state: dict[str, str] | None) -> KnowledgeSourceSync: @@ -406,28 +223,20 @@ def _sync(src: KnowledgeSource, state: dict[str, str] | None) -> KnowledgeSource async def _details_allowed(src: KnowledgeSource) -> bool: - if domain.opaque_payload( - kind=src.kind, mode=src.credential_mode, version=src.source_contract_version - ): + if src.kind == "mcp": return False if src.credential_mode == "shared": return True if src.credential_mode != "connected" or not request_work.mark_mirrored(): return False from server.knowledge.app import connected_accounts as accounts - from server.knowledge.store import connected_accounts as account_store with private_work(): try: - org, owner = await accounts.own_subject(current_auth()) - if org != src.org or owner != src.owner_subject: - return False - account = await account_store.get(org, owner, src.kind) - if account is None: - return False - await accounts._source_standing(src, account) - return True - except Exception: # noqa: BLE001 — unverifiable personal-source details stay private + auth = current_auth() + org, owner = await accounts.own_subject(auth) + return org == src.org and owner == src.owner_subject and current_auth() is auth + except Exception: # noqa: BLE001 — unverifiable retained source details stay private return False @@ -435,7 +244,7 @@ async def handle_knowledge_source_list( input: KnowledgeSourceListInput, ) -> KnowledgeSourceListOutput: ch.set_query_tag("knowledge.source.list") - found = await store.list_sources(input.org, input.namespace) + found = await store.list_sources(input.org, input.namespace, include_mcp=False) states = await store.read_states(input.org, input.namespace, [s.name for s in found]) entries = [] for s in found: @@ -447,8 +256,6 @@ async def handle_knowledge_source_list( credential_mode=s.credential_mode, access=s.access, owner_subject=s.owner_subject if details else "", - items=s.items if details else [], - include=_answered_include(s) if details else [], config=(domain.id_list_config(s) or {}) if details else {}, created_by=s.created_by if details else "", created_at=_iso(s.created_at), @@ -476,8 +283,6 @@ async def handle_knowledge_source_inspect( credential_mode=src.credential_mode, access=src.access, owner_subject=src.owner_subject if details else "", - items=src.items if details else [], - include=_answered_include(src) if details else [], config=(domain.id_list_config(src) or {}) if details else {}, created_by=src.created_by if details else "", created_at=_iso(src.created_at), @@ -516,17 +321,11 @@ async def handle_knowledge_source_add(input: KnowledgeSourceAddInput) -> Knowled name = domain.normalize_name(input.name) if not domain.valid_name(name): raise ValidationError( - "source name: 2-32 lower-case letters, digits, - or _, starting with a letter", - code="BAD_NAME", + "source name must be 2-32 lower-case letters, digits, - or _", code="BAD_NAME" ) - kind = input.kind.strip().lower() + kind = input.kind _require_kind(kind) - sent = [f for f in ("items", "links") if getattr(input, f) is not None] - config, items = _registration(input, kind, sent) - if input.credential_mode == "connected": - from server.knowledge.app.connected_sources import add - - return await add(input, name=name, kind=kind, config=config, items=items, sent=sent) + config = domain.parse_config(kind, input.config) if not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): raise AuthInsufficientError("a namespace administrator is required for a shared source") if not input.credential.strip(): @@ -534,52 +333,40 @@ async def handle_knowledge_source_add(input: KnowledgeSourceAddInput) -> Knowled await _require_source_namespace(input.org, input.namespace) await _require_no_erasure(input.org, input.namespace) await _require_free(input.org, input.namespace, name) - # A deployment that cannot store the credential says so before the probe. _require_sealable(input.credential) - # A project may be named by its short id (a link's, or an item's `slug_id`); the - # store's id is the UUID. - items = domain.unique_items(await _resolved(kind, items, input.credential)) - _require_count(kind, items, sent) - if not input.dry_run: - # The probe only turns a recursive folder into a drive, neither of which the - # id-list form holds; a dry run stores nothing. - await _require_fleet_for(kind, items) - probe, items = await _probe_items(kind, items, config, input.credential) + with _store_refusals(): + found = await source_probes.probe(kind, config, input.credential) + probe = _probe_answer(found) subject, _org = current_caller() - src = KnowledgeSource( - org=input.org, - namespace=input.namespace, - name=name, - kind=kind, - source_id=str(uuid.uuid4()), - config=config, - items=items, - created_by=subject, + src = _with_credential( + KnowledgeSource( + org=input.org, + namespace=input.namespace, + name=name, + kind=kind, + source_id=str(uuid.uuid4()), + config=config, + created_by=subject, + ), + input.credential, ) - src = _with_credential(src, input.credential) out = KnowledgeSourceAddOutput( name=name, kind=kind, namespace=input.namespace, - items=src.items, - include=_answered_include(src), - config=domain.id_list_config(src) or {}, + config=config, probe=probe, dry_run=input.dry_run, ) if input.dry_run: return out async with sources_lease(input.org, input.namespace): - # Under the lease nothing else writes this namespace's sources, so the checks - # hold until the insert: the probe took seconds and ran outside it. - # A namespace deleted during the probe (code.repo.remove deletes its own) has - # retired its sources under this lease; the add must not land after it. with sequential_reads(): await _require_source_namespace(input.org, input.namespace) await _require_no_erasure(input.org, input.namespace) + if not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): + raise AuthInsufficientError("a namespace administrator is required for a shared source") await _require_free(input.org, input.namespace, name) - # A new source starts with a full listing, never on the stamp an earlier - # source of this name left; reset before the row goes active. await store.write_state(input.org, input.namespace, name, state_value="", detail={}) await store.insert_source(src) return out @@ -669,19 +456,13 @@ async def _require_free(org: str, namespace: str, name: str, *, owner_subject: s def _require_supported_recording_provider(src: KnowledgeSource) -> None: if src.kind == "recording" and src.config.get("provider") == "meet": - raise ValidationError( - "Meet transcripts and notes use a gdrive shared-folder source", code="BAD_CONFIG" - ) + raise ValidationError("this retired recording provider is unavailable", code="BAD_CONFIG") async def handle_knowledge_source_check( input: KnowledgeSourceCheckInput, ) -> KnowledgeSourceCheckOutput: src = await _source_or_404(input.org, input.namespace, input.name) - if src.credential_mode == "connected": - from server.knowledge.app.connected_sources import check - - return await check(src) if not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): raise AuthInsufficientError("a namespace administrator is required for a shared source") _require_served(src) @@ -696,9 +477,8 @@ async def handle_knowledge_source_check( summary="credential_invalid: the stored credential no longer opens; rotate it", checked_at=checked_at, ) - checked = source_probes.sample(src.items) try: - found = await source_probes.probe(src.kind, src.config, credential, items=checked) + found = await source_probes.probe(src.kind, src.config, credential) except source_probes.CredentialRefused as e: return KnowledgeSourceCheckOutput( name=src.name, @@ -717,8 +497,6 @@ async def handle_knowledge_source_check( documents=found.documents, more=found.more, sample=found.sample, - checked=len(checked), - sampled=len(checked) < len(src.items), summary=f"{found.documents}{plus} documents listed", checked_at=checked_at, ) @@ -735,10 +513,9 @@ async def handle_knowledge_source_rotate( # A deployment that cannot store the credential says so before the probe. _require_sealable(input.credential) await _require_source_namespace(input.org, input.namespace) - checked = source_probes.sample(src.items) with _store_refusals(): - found = await source_probes.probe(src.kind, src.config, input.credential, items=checked) - probe = _probe_answer(found, len(checked), len(src.items)) + found = await source_probes.probe(src.kind, src.config, input.credential) + probe = _probe_answer(found) async with sources_lease(input.org, input.namespace): # The probe ran outside the lease: the source may have been removed, or removed # and added again as another source this credential was not probed against. @@ -763,142 +540,6 @@ async def handle_knowledge_source_rotate( return KnowledgeSourceRotateOutput(name=src.name, probe=probe, rotated_at=_now_iso()) -async def handle_knowledge_source_update( - input: KnowledgeSourceUpdateInput, -) -> KnowledgeSourceUpdateOutput: - src = await _source_or_404(input.org, input.namespace, input.name) - if src.credential_mode == "connected": - from server.knowledge.app.connected_sources import update - - return await update(src, input) - if not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): - raise AuthInsufficientError("a namespace administrator is required for a shared source") - _require_served(src) - _require_supported_recording_provider(src) - if src.kind not in domain.ITEM_FIELDS: - raise ValidationError(f"a {src.kind} source has no items", code="BAD_KIND") - plan = await _update_plan(src, input) - if plan is None: - return KnowledgeSourceUpdateOutput( - name=src.name, - items=src.items, - include=_answered_include(src), - config=domain.id_list_config(src) or {}, - ) - async with sources_lease(input.org, input.namespace): - # The probe ran outside the lease: what it checked holds only for the source as - # it was read, so a source another change moved meanwhile is retried. - with sequential_reads(): - fresh = await _source_or_404(input.org, input.namespace, src.name) - # A namespace that went, or an erasure that started, during the probe. - await _require_source_namespace(input.org, input.namespace) - await _require_no_erasure(input.org, input.namespace) - if fresh.source_id != src.source_id: - raise SourceReplacedError( - f"source {src.name!r} was removed and added again while its new items were " - "probed; update the current source" - ) - if _moved(fresh, src): - raise OverloadedError("the source changed during the probe; retry", retry_after_s=1) - change = _updated(fresh, plan.added, plan.removed, plan.include) - updated = change.source - # The probe can name an added folder as a drive the source already holds. - if updated.items != fresh.items or plan.include is not None: - from server.knowledge.app.source_push import retire - - await retire(fresh) - # Sealed again: the change may move the credential to the other column. - await store.insert_source(_with_credential(updated, _stored_credential(fresh))) - # A fresh full request, so the next turn lists the added items' older files; - # to the microsecond, so it never equals one a running turn read and clears. - asked = datetime.now(UTC).isoformat() - state = await _read_state(updated) - await _update_state(updated, state, {"requested_at": asked, "full": True}) - return KnowledgeSourceUpdateOutput( - name=updated.name, - items=updated.items, - include=_answered_include(updated), - config=domain.id_list_config(updated) or {}, - added=change.added, - removed=change.removed, - probe=plan.probe, - ) - - -class _UpdatePlan(NamedTuple): - """An update's change, checked and probed before the lease.""" - - added: list[dict[str, Any]] - removed: list[dict[str, Any]] - include: list[str] | None - probe: KnowledgeSourceProbe - - -async def _update_plan( - src: KnowledgeSource, - input: KnowledgeSourceUpdateInput, - *, - credential: Credential | None = None, -) -> _UpdatePlan | None: - """The change `input` asks of `src`, refused before any probe when it cannot be - made, its added items (and, for a new `include`, the kept file items) probed; None - when it changes nothing (an `include` restated, items added as they are held).""" - # A link sent again names what the source holds, so it changes nothing. - added = _items_of(src.kind, input.add_items, input.add_links, "add_", held=src) - # A folder entry and a drive entry of one id both name the held drive: once. - removed = domain.unique_items( - _as_held(src, _items_of(src.kind, input.remove_items, input.remove_links, "remove_")) - ) - added_fields = [f for f in ("add_items", "add_links") if getattr(input, f)] - _require_count(src.kind, added, added_fields) - # Each removed entry must match a held item, so this bounds the short-id lookup. - if _named(removed) > len(src.items): - fields = " and ".join(f for f in ("remove_items", "remove_links") if getattr(input, f)) - raise BadConfigError(f"{fields}: names more items than the source holds") - include = _include(input.include, src.kind) - if include == domain.include_in(src.config): - include = None # restated as it is: no change to check or store - if not added and not removed and input.include is None: - raise BadConfigError("name an item, a link or include to change") - await _require_source_namespace(src.org, src.namespace) - await _require_no_erasure(src.org, src.namespace) - if not added and not removed and include is None: - return None - if credential is None: - credential = _stored_credential(src) - removing = {i["slug_id"] for i in removed if "slug_id" in i} - # Short ids to UUIDs, the added and the removed in one lookup; a held project is - # removed by its id, as knowledge.source.list shows. - resolved = await _resolved( - src.kind, added + removed, credential, "; remove a source's own project by its id", removing - ) - n = len(added) - added, removed = domain.unique_items(resolved[:n]), domain.unique_items(resolved[n:]) - _require_count(src.kind, added, added_fields) - # Refuses a change it cannot make, before the probe: a rollout one too. - change = _updated(src, added, removed, include) - pending, new = change.source, change.added - if pending.items == src.items and include is None: - return None # every added item is held as it is, as a retried call sends them - await _require_fleet_for(pending.kind, pending.items) - probe = KnowledgeSourceProbe() - options = {"include": include} if include is not None else src.config - probed = new - if new: - # The items as the probe names them (a recursive folder at a drive's root: the drive). - probe, probed = await _probe_items(src.kind, new, options, credential) - # A new `include` that names no kind of a file the source keeps would leave it - # listing nothing: the kept files, not the added ones or the removed. - kept = _kept_files(pending, probed) if include is not None else [] - if kept: - kept_probe, _ = await _probe_items( - src.kind, kept, options, credential, ", or remove it with remove_items" - ) - if not probed: - probe = kept_probe - return _UpdatePlan(probed, removed, include, probe) - - def _stored_credential(src: KnowledgeSource) -> str: credential = credential_of(src) if not credential: @@ -908,20 +549,6 @@ def _stored_credential(src: KnowledgeSource) -> str: return credential -async def _resolved( - kind: str, - items: list[dict[str, Any]], - credential: Credential, - suffix: str = "", - about: Container[str] | None = None, -) -> list[dict[str, Any]]: - """`items` with each tracker project's short id resolved, in the same order and - number; the caller drops what then names the same project twice (`domain.unique_items`). - A short id the tracker does not know (one of `about`) ends its refusal with `suffix`.""" - with _store_refusals(suffix, about): - return await source_probes.resolve(kind, items, credential) - - def _moved(fresh: KnowledgeSource, src: KnowledgeSource) -> bool: """Whether another write changed the source between `src`'s read and `fresh`'s: its items, config or sealed credential, which a write rewrites and nothing else.""" @@ -933,81 +560,6 @@ def _moved(fresh: KnowledgeSource, src: KnowledgeSource) -> bool: ) -def _kept_files(src: KnowledgeSource, added: list[dict[str, Any]]) -> list[dict[str, Any]]: - """The file items `src` holds that `added` did not bring.""" - return [i for i in src.items if i["type"] == "file" and i not in added] - - -def _as_held(src: KnowledgeSource, items: list[dict[str, Any]]) -> list[dict[str, Any]]: - """`items` as `src` holds them, so an answer and an audit row name the stored item: - a folder link parses as `recursive: false`, so it takes the held folder's form, or - the held drive's at a shared drive's root.""" - held = {domain.item_key(i): i for i in src.items} - - def held_form(item: dict[str, Any]) -> dict[str, Any]: - key = domain.item_key(item) - if key in held: - return held[key] - if item["type"] == "folder": - return held.get(domain.item_key({"type": "shared_drive", "id": item["id"]}), item) - return item - - return [held_form(i) for i in items] - - -class _Change(NamedTuple): - """A source after an update, the items it added, and every held item it dropped.""" - - source: KnowledgeSource - added: list[dict[str, Any]] - removed: list[dict[str, Any]] - - -def _updated( - src: KnowledgeSource, - added: list[dict[str, Any]], - removed: list[dict[str, Any]], - include: list[str] | None, -) -> _Change: - """`src` changed: `removed` out and `added` in, answering every held item the change - drops as removed. BAD_CONFIG for an item it does not hold, one both added and - removed, no item left and too many.""" - held = {domain.item_key(i) for i in src.items} - both = {domain.item_key(i) for i in added} & {domain.item_key(i) for i in removed} - if both: - raise BadConfigError(f"an item both added and removed: {sorted(both)[0]}") - absent = [i for i in removed if domain.item_key(i) not in held] - if absent: - raise BadConfigError(f"not an item of the source: {domain.item_key(absent[0])}") - # An added item held as it is changes nothing; one in another form (a folder made - # recursive) replaces the held one, and a drive drops a folder of its id beside it. - incoming = [i for i in added if i not in src.items] - gone = {domain.item_key(i) for i in removed + incoming} - kept = [i for i in src.items if domain.item_key(i) not in gone] - items = _without_drive_folders(kept + incoming) - added_now = [i for i in incoming if i in items] - dropped = [i for i in src.items if i not in items] - if not items: - raise BadConfigError("that removes every item; knowledge.source.remove ends a source") - if len(items) > domain.max_items(src.kind): - raise BadConfigError(f"at most {domain.max_items(src.kind)} items for a {src.kind} source") - config = _stored_options(src.kind, items, include or domain.include_in(src.config)) - return _Change(dataclasses.replace(src, items=items, config=config), added_now, dropped) - - -async def handle_knowledge_source_parse_links( - input: KnowledgeSourceParseLinksInput, -) -> KnowledgeSourceParseLinksOutput: - return KnowledgeSourceParseLinksOutput( - links=[ - KnowledgeSourceParsedLink( - link=p.link, kind=p.kind, item=p.item, unreadable=p.unreadable - ) - for p in parse_links(input.links) - ] - ) - - async def handle_knowledge_source_remove( input: KnowledgeSourceRemoveInput, ) -> KnowledgeSourceRemoveOutput: @@ -1029,14 +581,10 @@ async def handle_knowledge_source_remove( f"no document source {domain.shown(name)} in {input.namespace!r}", code="SOURCE_NOT_FOUND", ) - if domain.opaque_payload( - kind=src.kind, mode=src.credential_mode, version=src.source_contract_version - ): - _require_served(src) + if src.source_contract_version != 0 or src.kind == "mcp": + raise NotFoundError("no document source", code="SOURCE_NOT_FOUND") if src.credential_mode == "connected": - from server.knowledge.app.connected_sources import require_operator - - await require_operator(src) + await _require_connection_operator(src) elif not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): raise AuthInsufficientError( "a namespace administrator is required for a shared source" @@ -1072,9 +620,7 @@ async def handle_knowledge_source_sync_now( ) -> KnowledgeSourceSyncNowOutput: src = await _source_or_404(input.org, input.namespace, input.name) if src.credential_mode == "connected": - from server.knowledge.app.connected_sources import require_operator - - await require_operator(src) + await _require_connection_operator(src) else: if not await authz.row_in_scope(input.org, input.namespace, Role.ADMIN): raise AuthInsufficientError("a namespace administrator is required for a shared source") @@ -1092,7 +638,7 @@ async def handle_knowledge_source_sync_now( "knowledge.source.sync_now again for the current source" ) if fresh.credential_mode == "connected": - await require_operator(fresh) + await _require_connection_operator(fresh) state = await _read_state(fresh) # A full request waiting (an update's) already asks for more: a plain sync now # leaves it as it is, neither narrowed nor started over. @@ -1225,43 +771,15 @@ async def _wait_until_free(lease_name: str, deadline: float, busy: str) -> None: def source_add_audit_subject(input: KnowledgeSourceAddInput, response: Any) -> dict[str, Any]: - """What an add's audit row records: the source as stored, never the - credential. `loom.audit_log` outlives the source and must hold no secret.""" - if input.credential_mode == "connected": - return { - "org": input.org, - "namespace": input.namespace, - "name": response["name"], - "kind": response["kind"], - "credential_mode": "connected", - "dry_run": input.dry_run, - } return { "org": input.org, "namespace": input.namespace, "name": response["name"], - "kind": response["kind"], - "items": response["items"], - "include": response["include"], - "config": response["config"], + "kind": "recording", "dry_run": input.dry_run, } -def source_update_audit_subject(input: KnowledgeSourceUpdateInput, response: Any) -> dict[str, Any]: - """Which source changed and the items added and removed, never the credential.""" - if request_work.mirror_marked(): - return {"org": input.org, "namespace": input.namespace, "name": response["name"]} - return { - "org": input.org, - "namespace": input.namespace, - "name": response["name"], - "added": response["added"], - "removed": response["removed"], - "include": response["include"] if input.include is not None else None, - } - - def source_rotate_audit_subject(input: KnowledgeSourceRotateInput, response: Any) -> dict[str, Any]: """Which source's credential was replaced, never the credential.""" return {"org": input.org, "namespace": input.namespace, "name": response["name"]} @@ -1277,12 +795,29 @@ def source_rotate_audit_subject(input: KnowledgeSourceRotateInput, response: Any "handle_knowledge_source_check", "handle_knowledge_source_inspect", "handle_knowledge_source_list", - "handle_knowledge_source_parse_links", "handle_knowledge_source_remove", "handle_knowledge_source_rotate", "handle_knowledge_source_sync_now", - "handle_knowledge_source_update", "source_add_audit_subject", "source_rotate_audit_subject", - "source_update_audit_subject", ] + + +async def _require_connection_operator(source: KnowledgeSource) -> None: + from server.knowledge.app import connected_accounts as accounts + + auth = current_auth() + if source.credential_mode != "connected" or not request_work.mark_mirrored(): + raise accounts.unavailable() + if await authz.row_in_scope(source.org, source.namespace, Role.ADMIN): + if current_auth() is not auth: + raise accounts.unavailable() + return + org, owner = await accounts.own_subject(auth) + if ( + org != source.org + or owner != source.owner_subject + or not await authz.row_in_scope(org, source.namespace, Role.WRITER) + or current_auth() is not auth + ): + raise accounts.unavailable() diff --git a/server/knowledge/domain/source_links.py b/server/knowledge/domain/source_links.py deleted file mode 100644 index 9d1d18ee66..0000000000 --- a/server/knowledge/domain/source_links.py +++ /dev/null @@ -1,130 +0,0 @@ -"""Pasted links to a document store's folders, files, pages and projects, turned -into a source's items (`knowledge.source.parse_links`, and the `links` of add and -update). Pure: no request to any store, so a link is read by its form alone. - -A link of another host, with no id, or to something the sync does not read (a -spreadsheet, a single issue) is `unreadable`, with the reason. -""" - -from __future__ import annotations - -import re -from dataclasses import dataclass, field -from typing import Any -from urllib.parse import parse_qs, urlsplit - -from server.core.errors import BadConfigError -from server.knowledge.domain.sources import parse_items - -_DRIVE_FOLDER_RE = re.compile(r"/drive(?:/u/\d+)?(?:/mobile)?/folders/([^/]+)") -_DRIVE_FILE_RE = re.compile(r"/file(?:/u/\d+)?/d/([^/]+)") -_DOCS_RE = re.compile( - r"(?:/a/[^/]+)?/(document|presentation|spreadsheets|forms|drawings)(?:/u/\d+)?/d/([^/]+)" -) -_NOTION_ID_RE = re.compile(r"(?:^|-)([0-9a-fA-F]{32})$") -_LINEAR_RE = re.compile(r"/[^/]+/(project|issue|document|team|view)/([^/]+)") -_LINEAR_SLUG_RE = re.compile(r"(?:.*-)?([0-9a-f]{12})") -_NOTION_HOSTS = {"notion.so", "www.notion.so"} -_DOCS_UNREAD = {"spreadsheets": "a spreadsheet", "forms": "a form", "drawings": "a drawing"} - - -@dataclass(frozen=True) -class ParsedLink: - """One link: the item it names and the source kind that reads it, or why not.""" - - link: str - kind: str = "" - item: dict[str, Any] = field(default_factory=dict) - unreadable: str = "" - - -def parse_links(links: list[str]) -> list[ParsedLink]: - """Each link, in order, as an item or an `unreadable` reason.""" - return [_parse(link) for link in links] - - -def _parse(link: str) -> ParsedLink: - text = link.strip() - if not text: - return ParsedLink(link, unreadable="not a link") - if "://" not in text: - text = "https://" + text - try: - url = urlsplit(text) - except ValueError: - return ParsedLink(link, unreadable="not a link") - host = (url.hostname or "").lower() - if url.scheme not in ("https", "http"): - return ParsedLink(link, unreadable="not a web link") - path = url.path.rstrip("/") - query = parse_qs(url.query) - if host == "drive.google.com": - found = _drive(path) - elif host == "docs.google.com": - found = _docs(path) - elif host in _NOTION_HOSTS or host.endswith(".notion.site"): - found = _notion(path, query) - elif host == "linear.app": - found = _linear(path) - else: - return ParsedLink(link, unreadable=f"{host or 'no host'}: not a store a source reads") - if isinstance(found, str): - return ParsedLink(link, unreadable=found) - kind, item = found - try: - [checked] = parse_items(kind, [item]) - except BadConfigError as e: - return ParsedLink(link, unreadable=e.message.removeprefix("items[0].")) - return ParsedLink(link, kind=kind, item=checked) - - -def _drive(path: str) -> tuple[str, dict[str, Any]] | str: - if m := _DRIVE_FOLDER_RE.fullmatch(path): - return "gdrive", {"type": "folder", "id": m.group(1)} - if m := _DRIVE_FILE_RE.match(path): - return "gdrive", {"type": "file", "id": m.group(1)} - if path == "/open": - return "an open link names a folder or a file alike; copy the link of the one you mean" - return "a shared-folder link with no folder or file id" - - -def _docs(path: str) -> tuple[str, dict[str, Any]] | str: - m = _DOCS_RE.match(path) - if not m: - return "a document link with no id" - if m.group(1) in _DOCS_UNREAD: - return f"{_DOCS_UNREAD[m.group(1)]}: the sync reads documents, slides and files" - if m.group(2) == "e": - return "a published copy; link the document itself" - return "gdrive", {"type": "file", "id": m.group(2)} - - -def _notion(path: str, query: dict[str, list[str]]) -> tuple[str, dict[str, Any]] | str: - # A page opened beside its database carries the page in `p`. - peeked = query.get("p", [""])[0] - if m := _NOTION_ID_RE.fullmatch(peeked): - return "notion", {"type": "page", "id": m.group(1)} - last = path.rsplit("/", 1)[-1] - m = _NOTION_ID_RE.search(last) - if not m: - return "a page-store link with no page id" - # A database's link opens one of its views. - item_type = "database" if query.get("v") else "page" - return "notion", {"type": item_type, "id": m.group(1)} - - -def _linear(path: str) -> tuple[str, dict[str, Any]] | str: - m = _LINEAR_RE.match(path) - if not m: - return "a tracker link with no project" - if m.group(1) in ("team", "view"): - return f"a {m.group(1)} link: link one of its projects" - if m.group(1) != "project": - return f"a single {m.group(1)}: the sync reads a project's documents; link the project" - slug = _LINEAR_SLUG_RE.fullmatch(m.group(2).lower()) - if not slug: - return "a project link with no project id" - return "linear", {"type": "project", "slug_id": slug.group(1)} - - -__all__ = ["ParsedLink", "parse_links"] diff --git a/server/knowledge/domain/sources.py b/server/knowledge/domain/sources.py index 6cd0bb9faa..e68477dd65 100644 --- a/server/knowledge/domain/sources.py +++ b/server/knowledge/domain/sources.py @@ -1,23 +1,11 @@ -"""Document sources a namespace's admins register (`knowledge.source.*`): the -kinds, the name rule, each kind's items and the configuration form a build -without items reads. Pure: no I/O. - -A source's items and configuration hold ids and filters only, never a host or a -URL: each kind's API host is a constant of its client module, so no -caller-supplied host is ever connected to. - -A `gdrive`, `notion` or `linear` source reads a list of items (`parse_items`); -`config` in the id-list form (`folder_ids`, `page_ids`, `project_ids`) is turned into -items (`items_from_config`) and written alongside them while every item fits in -it (`config_from_items`). A `recording` source keeps its config and has no items. -""" +"""Recording admission and opaque document-source lifecycle metadata. Pure: no I/O.""" from __future__ import annotations import json import re from dataclasses import dataclass, field -from datetime import date, datetime +from datetime import datetime from typing import Any from server.core.errors import BadConfigError @@ -25,30 +13,7 @@ # The kinds a source may be. Each has a config parser here and a probe in # `server.knowledge.app.source_probes`. -KINDS = ("gdrive", "linear", "notion", "recording") - -# The shared-folder store's type of a folder: a folder, never a file the sync reads. -_FOLDER_MIME = "application/vnd.google-apps.folder" -# A shared-folder store's file kinds, by the name a config's `include` uses. -GDRIVE_MIME_TYPES = { - "docs": "application/vnd.google-apps.document", - "slides": "application/vnd.google-apps.presentation", - "pdf": "application/pdf", - "pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation", - "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document", -} -# The kinds a config without `include` takes. `docx` is read when a config names it and -# is left out of the default, so a build that does not know it still syncs every source -# a default config made (docs/architecture/rolling-upgrades.md). -GDRIVE_DEFAULT_INCLUDE = ("docs", "slides", "pdf", "pptx") -# A folder id goes into the store's query string, so only its own alphabet passes. -_FOLDER_ID_RE = re.compile(r"[A-Za-z0-9_-]{10,128}") -MAX_FOLDERS = 20 # not a setting: the add op's wire contract (1 to 20 folders) -# A tracker project id is a UUID; it travels as a GraphQL variable. -_PROJECT_ID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}") -MAX_PROJECTS = 20 # not a setting: the add op's wire contract (1 to 20 projects) -# A page store's page and database ids, together, at most. -MAX_PAGE_STORE_IDS = 20 # not a setting: the add op's wire contract, few enough to probe each +KINDS = ("recording",) # Zoom recording registrations use numeric meeting ids. RECORDING_ID_RE = { @@ -56,35 +21,6 @@ } MAX_RECORDING_IDS = 20 # not a setting: the add op's wire contract (1 to 20 ids) -# A source's items, at most. -MAX_ITEMS = 300 # not a setting: the add and update ops' wire contract -# Items a probe checks, at most: every item while there are this many, else the -# ones added last. -SAMPLE_ITEMS = 20 # not a setting: the add and update ops' wire contract -# A source's walk of its recursive folders: levels of subfolders, and subfolders in all, -# at most. The roots are walked together, so a turn spends a bounded number of queries -# however many recursive items the source holds. -MAX_DEPTH = 8 # not a setting: the items' wire contract -MAX_WALK_FOLDERS = 500 # not a setting: the items' wire contract -# Each kind's item types and the fields each takes besides `type`. -ITEM_FIELDS: dict[str, dict[str, frozenset[str]]] = { - "gdrive": { - "folder": frozenset({"id", "recursive"}), - "file": frozenset({"id"}), - "shared_drive": frozenset({"id"}), - "filter": frozenset({"name_contains", "kinds", "modified_after", "in"}), - }, - "notion": {"page": frozenset({"id"}), "database": frozenset({"id"})}, - "linear": {"project": frozenset({"id", "slug_id"})}, -} -# A filter's fields go into a store query (escaped by the client), so each has a -# narrow pattern: a name fragment of printable characters and an ISO date. -_NAME_FRAGMENT_RE = re.compile(r"[^\x00-\x1f\x7f]{1,100}") -_DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}") -# A tracker project's short id, as its link carries it; the probe resolves it to the -# project's UUID. -_PROJECT_SLUG_ID_RE = re.compile(r"[0-9a-f]{12}") - # The actor the sync worker writes a source's documents as. Its kind is neither # `human` nor `process`, the only kinds a token maps to, so no request writes as # it. A source's documents are the live documents tagged `source:` that this @@ -113,16 +49,13 @@ class KnowledgeSource: kind: str # One registration's id: written once by add, carried by every later write. source_id: str - # The options the source reads (`options_in`): a gdrive source's `include`, a - # recording source's provider and ids. The store writes `stored_config(src)`. - config: dict[str, Any] = field(default_factory=dict) - # The things the source reads (`parse_items`); a row an older build wrote has them - # filled from `config_json` by the store. - items: list[dict[str, Any]] = field(default_factory=list) - # The sealed credential: in `credential_enc` while the source fits the id-list config - # (a build without items can use it), else in `secret_enc`. - credential_enc: str = "" - secret_enc: str = "" + # A shared recording's provider and selected IDs; opaque rows keep raw JSON below. + config: dict[str, Any] = field(default_factory=dict, repr=False) + # Retained lifecycle metadata, never interpreted as native source selections. + items: list[dict[str, Any]] = field(default_factory=list, repr=False) + # Existing sealed columns retain their distinct encryption purposes. + credential_enc: str = field(default="", repr=False) + secret_enc: str = field(default="", repr=False) # Who the documents are shown to: NAMESPACE_ACCESS or MIRRORED_ACCESS; a later build # may write another value, which `served` refuses. access: str = NAMESPACE_ACCESS @@ -147,8 +80,8 @@ class KnowledgeSource: def opaque_payload(*, kind: str, mode: str, version: int) -> bool: - """Preserve new formats without interpreting them through a native source codec.""" - return version != 0 or kind == "mcp" or mode == "mcp" + """Only shared recording rows have an interpreted configuration.""" + return kind != "recording" or mode != "shared" or version != 0 def shown(value: Any) -> str: @@ -231,109 +164,9 @@ def source_tags(tags: list[str]) -> set[str]: def parse_config(kind: str, config: dict[str, Any]) -> dict[str, Any]: - """The stored form of `config` for `kind`; BadConfigError when unusable.""" - if kind == "gdrive": - return _gdrive_config(config) - if kind == "linear": - return _linear_config(config) - if kind == "notion": - return _notion_config(config) - if kind == "recording": - return _recording_config(config) - raise BadConfigError(f"no config rule for kind {shown(kind)}") - - -def _gdrive_config(config: dict[str, Any]) -> dict[str, Any]: - unknown = sorted(set(config) - {"folder_ids", "include"}) - if unknown: - raise BadConfigError(f"unknown config {unknown_keys(unknown)}") - folder_ids = config.get("folder_ids") - if not isinstance(folder_ids, list) or not folder_ids: - raise BadConfigError("config.folder_ids: a list of 1 to 20 folder ids") - folders: list[str] = [] - for folder in folder_ids: - if not isinstance(folder, str) or not _FOLDER_ID_RE.fullmatch(folder): - raise BadConfigError( - f"config.folder_ids: {shown(folder)} is not a folder id (letters, digits, - and _)" - ) - if folder not in folders: - folders.append(folder) - if len(folders) > MAX_FOLDERS: - raise BadConfigError(f"config.folder_ids: at most {MAX_FOLDERS} folders") - include = parse_include(config.get("include", list(GDRIVE_DEFAULT_INCLUDE)), "config.include") - return {"folder_ids": folders, "include": include} - - -def parse_include(include: Any, where: str = "include") -> list[str]: - """A `gdrive` source's file kinds, in the table's own order, so two equal - configs store the same text; BadConfigError when unusable.""" - if not isinstance(include, list) or not include: - raise BadConfigError(f"{where}: a list of " + ", ".join(GDRIVE_MIME_TYPES)) - # Type first: a list or an object element is unhashable for the membership test. - bad = [k for k in include if not isinstance(k, str) or k not in GDRIVE_MIME_TYPES] - if bad: - raise BadConfigError( - f"{where}: {shown(bad[0])} is not one of " + ", ".join(GDRIVE_MIME_TYPES) - ) - return [k for k in GDRIVE_MIME_TYPES if k in include] - - -def _linear_config(config: dict[str, Any]) -> dict[str, Any]: - unknown = sorted(set(config) - {"project_ids"}) - if unknown: - raise BadConfigError(f"unknown config {unknown_keys(unknown)}") - project_ids = config.get("project_ids") - if not isinstance(project_ids, list) or not project_ids: - raise BadConfigError("config.project_ids: a list of 1 to 20 project ids") - projects: list[str] = [] - for project in project_ids: - # Lower-cased: a document's project is compared with these ids as the API - # reports them. - value = project.strip().lower() if isinstance(project, str) else project - if not isinstance(value, str) or not _PROJECT_ID_RE.fullmatch(value): - raise BadConfigError( - f"config.project_ids: {shown(project)} is not a project id (a UUID)" - ) - if value not in projects: - projects.append(value) - if len(projects) > MAX_PROJECTS: - raise BadConfigError(f"config.project_ids: at most {MAX_PROJECTS} projects") - return {"project_ids": projects} - - -def _page_store_ids(config: dict[str, Any], key: str) -> list[str]: - raw = config.get(key, []) - if not isinstance(raw, list): - raise BadConfigError(f"config.{key}: a list of ids") - ids: list[str] = [] - for value in raw: - normal = _page_store_id(value) if isinstance(value, str) else "" - if not normal: - raise BadConfigError(f"config.{key}: {shown(value)} is not an id (32 hex digits)") - if normal not in ids: - ids.append(normal) - return ids - - -def _page_store_id(value: str) -> str: - """The dashed lower-case form of an id given with or without dashes, or "".""" - hexes = value.strip().lower().replace("-", "") - if not re.fullmatch(r"[0-9a-f]{32}", hexes): - return "" - return f"{hexes[:8]}-{hexes[8:12]}-{hexes[12:16]}-{hexes[16:20]}-{hexes[20:]}" - - -def _notion_config(config: dict[str, Any]) -> dict[str, Any]: - unknown = sorted(set(config) - {"page_ids", "database_ids"}) - if unknown: - raise BadConfigError(f"unknown config {unknown_keys(unknown)}") - pages = _page_store_ids(config, "page_ids") - databases = _page_store_ids(config, "database_ids") - if not 1 <= len(pages) + len(databases) <= MAX_PAGE_STORE_IDS: - raise BadConfigError( - f"config.page_ids and config.database_ids: 1 to {MAX_PAGE_STORE_IDS} ids in all" - ) - return {"page_ids": pages, "database_ids": databases} + if kind != "recording": + raise BadConfigError("this source kind is unavailable") + return _recording_config(config) def _recording_config(config: dict[str, Any]) -> dict[str, Any]: @@ -360,268 +193,35 @@ def _recording_config(config: dict[str, Any]) -> dict[str, Any]: return {"provider": provider, "ids": ids} -def parse_items(kind: str, items: list[Any], where: str = "items") -> list[dict[str, Any]]: - """The stored form of `items` for `kind`, duplicates dropped (a later item of the - same type and id replaces the earlier one); BadConfigError when unusable, naming - the field the caller sent them in (`where`). It does not count them: the op does, once - short ids are resolved.""" - return unique_items([_item(kind, raw, f"{where}[{n}]") for n, raw in enumerate(items)]) - - -def unique_items(items: list[dict[str, Any]]) -> list[dict[str, Any]]: - """`items` with a later one of the same type and id replacing an earlier one.""" - found: dict[str, dict[str, Any]] = {} - for item in items: - key = item_key(item) - found.pop(key, None) # re-inserted, so a later item also takes the later place - found[key] = item - return list(found.values()) - - -def check_filters(items: list[dict[str, Any]], include: list[str]) -> None: - """Refuse a filter whose `kinds` share none with `include`: it would list nothing on - every turn.""" - for item in items: - if item["type"] == "filter" and "kinds" in item and not set(item["kinds"]) & set(include): - kinds = ", ".join(item["kinds"]) - raise BadConfigError(f"a filter's kinds ({kinds}): none of them is in include") - - -def max_items(kind: str) -> int: - """Items a source of `kind` holds, at most. A tracker or page-store turn reads every - item on every pass and its listing has no pass-time bound, so those keep their 20; a - `gdrive` turn stops at the pass deadline between walk levels and between items, though - it walks its recursive folders and reads each `file` item's metadata on every pass.""" - return {"linear": MAX_PROJECTS, "notion": MAX_PAGE_STORE_IDS}.get(kind, MAX_ITEMS) - - -def item_key(item: dict[str, Any]) -> str: - """What makes two items the same: type and id, or a filter's every field.""" - if "id" in item: - return f"{item['type']}:{item['id']}" - if "slug_id" in item: - return f"{item['type']}:slug:{item['slug_id']}" - return json.dumps(item, sort_keys=True) - - -def _item(kind: str, raw: Any, where: str) -> dict[str, Any]: - if not isinstance(raw, dict): - raise BadConfigError(f"{where}: an object with a `type`") - types = ITEM_FIELDS[kind] - item_type = raw.get("type") - if not isinstance(item_type, str) or item_type not in types: - raise BadConfigError(f"{where}.type: one of " + ", ".join(types)) - unknown = sorted(set(raw) - types[item_type] - {"type"}) - if unknown: - raise BadConfigError(f"{where}: unknown {unknown_keys(unknown)}") - if item_type == "filter": - return _filter_item(raw, where) - if item_type == "project": - return _project_item(raw, where) - item_id = raw.get("id") - if item_type in ("page", "database"): - normal = _page_store_id(item_id) if isinstance(item_id, str) else "" - if not normal: - raise BadConfigError(f"{where}.id: {shown(item_id)} is not an id (32 hex digits)") - return {"type": item_type, "id": normal} - if not isinstance(item_id, str) or not _FOLDER_ID_RE.fullmatch(item_id): - raise BadConfigError( - f"{where}.id: {shown(item_id)} is not an id (letters, digits, - and _)" - ) - if item_type != "folder": - return {"type": item_type, "id": item_id} - recursive = raw.get("recursive", False) - if not isinstance(recursive, bool): - raise BadConfigError(f"{where}.recursive: true or false") - return {"type": "folder", "id": item_id, "recursive": recursive} - - -def _project_item(raw: dict[str, Any], where: str) -> dict[str, Any]: - if ("id" in raw) == ("slug_id" in raw): - raise BadConfigError(f"{where}: an `id` (a UUID) or a `slug_id`, not both") - if "slug_id" in raw: - slug_id = raw["slug_id"] - value = slug_id.strip().lower() if isinstance(slug_id, str) else "" - if not _PROJECT_SLUG_ID_RE.fullmatch(value): - raise BadConfigError(f"{where}.slug_id: {shown(slug_id)} is not a project's short id") - return {"type": "project", "slug_id": value} - project = raw["id"] - value = project.strip().lower() if isinstance(project, str) else "" - if not _PROJECT_ID_RE.fullmatch(value): - raise BadConfigError(f"{where}.id: {shown(project)} is not a project id (a UUID)") - return {"type": "project", "id": value} - - -def _filter_item(raw: dict[str, Any], where: str) -> dict[str, Any]: - item: dict[str, Any] = {"type": "filter"} - if "name_contains" in raw: - name = raw["name_contains"] - if not isinstance(name, str) or not _NAME_FRAGMENT_RE.fullmatch(name.strip()): - raise BadConfigError(f"{where}.name_contains: 1 to 100 printable characters") - item["name_contains"] = name.strip() - if "kinds" in raw: - kinds = raw["kinds"] - if ( - not isinstance(kinds, list) - or not kinds - or not all(isinstance(k, str) and k in GDRIVE_MIME_TYPES for k in kinds) - ): - raise BadConfigError(f"{where}.kinds: a list of " + ", ".join(GDRIVE_MIME_TYPES)) - item["kinds"] = [k for k in GDRIVE_MIME_TYPES if k in kinds] - if "modified_after" in raw: - when = raw["modified_after"] - if not isinstance(when, str) or not _valid_date(when): - raise BadConfigError(f"{where}.modified_after: a date, YYYY-MM-DD") - item["modified_after"] = when - if "in" in raw: - folder = raw["in"] - if not isinstance(folder, str) or not _FOLDER_ID_RE.fullmatch(folder): - raise BadConfigError(f"{where}.in: a folder id (letters, digits, - and _)") - item["in"] = folder - if len(item) == 1: - raise BadConfigError( - f"{where}: a filter names at least one of name_contains, kinds, modified_after, in" - ) - return item - - -def _valid_date(value: str) -> bool: - if not _DATE_RE.fullmatch(value): - return False - try: - date.fromisoformat(value) - except ValueError: - return False - return True - - -def items_from_config(kind: str, config: dict[str, Any]) -> list[dict[str, Any]]: - """The items the id-list `config` of `kind` names, in its order; [] for a kind - without items. The config was checked when it was stored.""" - if kind == "gdrive": - return [ - {"type": "folder", "id": f, "recursive": False} for f in config.get("folder_ids") or [] - ] - if kind == "notion": - return [{"type": "page", "id": p} for p in config.get("page_ids") or []] + [ - {"type": "database", "id": d} for d in config.get("database_ids") or [] - ] - if kind == "linear": - return [{"type": "project", "id": p} for p in config.get("project_ids") or []] - return [] - - -def config_from_items( - kind: str, items: list[dict[str, Any]], include: list[str] -) -> dict[str, Any] | None: - """The id-list config form of `items` (at most `max_items(kind)`, as the ops count - them), or None when it cannot hold them (`fits_id_list`).""" - if not fits_id_list(kind, items): - return None - ids = [str(item["id"]) for item in items] - if kind == "gdrive": - return {"folder_ids": ids, "include": list(include)} - if kind == "notion": - return { - "page_ids": item_ids(items, "page"), - "database_ids": item_ids(items, "database"), - } - return {"project_ids": ids} - - -def fits_id_list(kind: str, items: list[dict[str, Any]]) -> bool: - """Whether the id-list config form holds `items`: not when an item is a gdrive item - other than a plain folder, there are more folders than the form holds, or a project - is named only by its short id.""" - if not items or not all(item.get("id") for item in items): - return False - if kind == "gdrive": - plain = all(i["type"] == "folder" and not i.get("recursive") for i in items) - return plain and len(items) <= MAX_FOLDERS - return kind in ("notion", "linear") - - -def item_ids(items: list[dict[str, Any]], item_type: str) -> list[str]: - """The ids of the items of one type, in order.""" - return [str(i["id"]) for i in items if i["type"] == item_type and i.get("id")] - - -def unread_file_note(mime: str) -> str: - """Why a `file` item of the store's type `mime` lists nothing.""" - if mime == _FOLDER_MIME: - return "a folder; add it as a folder item" - if mime in GDRIVE_MIME_TYPES.values(): - return "not a kind the source's include names; name its kind in include" - return f"{shown(mime)} is a type the sync does not read" - - -def include_mime_types(include: list[str], kinds: list[str] | None = None) -> list[str]: - """The file types `include` names, narrowed to a filter's `kinds` when given.""" - return [GDRIVE_MIME_TYPES[k] for k in include if kinds is None or k in kinds] - - -def include_in(config: dict[str, Any]) -> list[str]: - """The file kinds a `gdrive` config reads: its `include`, or the default.""" - return list(config.get("include") or GDRIVE_DEFAULT_INCLUDE) - - -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": - return config - return {"include": include_in(config)} if kind == "gdrive" else {} - - def served(src: KnowledgeSource) -> bool: - """Whether this build serves `src`: one shown to every reader of its namespace. A - mirrored one, or any `access` a later build writes, is that build's.""" + """Only supported shared recordings are ordinary namespace documents.""" return ( - not opaque_payload( - kind=src.kind, mode=src.credential_mode, version=src.source_contract_version - ) + src.kind == "recording" and src.credential_mode == "shared" + and src.source_contract_version == 0 and src.access == NAMESPACE_ACCESS ) def mirror_synced(src: KnowledgeSource) -> bool: - """Whether the sync worker writes `src` into its namespace's mirror: a mirrored - folder-store source or a person's connected page/project source.""" - if src.kind == "mcp": - return ( - src.credential_mode == "connected" - and type(src.source_contract_version) is int - and src.source_contract_version == 1 - and src.access == MIRRORED_ACCESS - ) + """Only the supported connected MCP contract can publish protected copies.""" return ( - not opaque_payload( - kind=src.kind, mode=src.credential_mode, version=src.source_contract_version - ) + src.kind == "mcp" + and src.credential_mode == "connected" + and type(src.source_contract_version) is int + and src.source_contract_version == 1 and src.access == MIRRORED_ACCESS - and ( - src.kind == "gdrive" - or (src.credential_mode == "connected" and src.kind in {"notion", "linear"}) - ) ) def id_list_config(src: KnowledgeSource) -> dict[str, Any] | None: - """The config a build without items reads for `src`, or None when that build must - not read it, so `src` is stored with `kind` empty: a source it cannot express, or - one this build does not serve, whose documents that build would show to every - reader. `list`, `inspect` and `update` answer the same `config`.""" - if not served(src): - return None - if src.kind == "recording": - return src.config - return config_from_items(src.kind, src.items, include_in(src.config)) + """Recording config for a served row; opaque registrations expose no config.""" + return src.config if served(src) else None def stored_config(src: KnowledgeSource) -> dict[str, Any]: - """What `config_json` holds: the id-list config, or the options alone.""" - config = id_list_config(src) - return options_in(src.kind, src.config) if config is None else config + """Recording config; opaque lifecycle writes use their original JSON bytes.""" + return src.config def json_object(raw: str) -> dict[str, Any]: @@ -635,7 +235,7 @@ def json_object(raw: str) -> dict[str, Any]: # The parts of a stored sync state a reader sees, with their types. The rest # (`full`, `full_listed_at`, `file_waits`, `waits_reset_for`, `retry_granted_for`, and -# a page store's `child_pages`) is the worker's own bookkeeping. +# legacy checkpoints) is the worker's own bookkeeping. SYNC_FIELDS: dict[str, type] = { "requested_at": str, "last_synced_at": str, @@ -677,45 +277,24 @@ def sync_shown(src: KnowledgeSource, detail: str) -> dict[str, Any]: __all__ = [ - "GDRIVE_DEFAULT_INCLUDE", - "GDRIVE_MIME_TYPES", - "ITEM_FIELDS", "KINDS", "KnowledgeSource", - "MAX_DEPTH", - "MAX_FOLDERS", - "MAX_ITEMS", - "MAX_PAGE_STORE_IDS", - "MAX_PROJECTS", "MAX_RECORDING_IDS", - "MAX_WALK_FOLDERS", "MIRRORED_ACCESS", "NAMESPACE_ACCESS", "RECORDING_ID_RE", - "SAMPLE_ITEMS", "STATE_KEY_PREFIX", "SYNC_FIELDS", "SYNC_WORKER_ACTOR", - "check_filters", - "config_from_items", - "fits_id_list", "home", "id_list_config", - "include_in", - "include_mime_types", - "item_ids", - "item_key", - "items_from_config", "json_object", - "max_items", "mirror_synced", "mirror_uri", "mirror_uri_suffix", "normalize_name", - "options_in", + "opaque_payload", "parse_config", - "parse_include", - "parse_items", "served", "shown", "source_id_tag", @@ -725,8 +304,6 @@ def sync_shown(src: KnowledgeSource, detail: str) -> dict[str, Any]: "stored_config", "sync_of", "sync_shown", - "unique_items", "unknown_keys", - "unread_file_note", "valid_name", ] diff --git a/server/knowledge/store/mcp_source_schedule.py b/server/knowledge/store/mcp_source_schedule.py new file mode 100644 index 0000000000..475095daf4 --- /dev/null +++ b/server/knowledge/store/mcp_source_schedule.py @@ -0,0 +1,112 @@ +"""Bounded MCP scheduling headers; source bodies stay in their existing store.""" + +from __future__ import annotations + +import re +from dataclasses import dataclass +from typing import Protocol + +from server.core.ch import get_client, set_query_tag + +# Random source_id prevents this worker-global digest from encoding a tenant address. +_KEY = "hex(SHA256(toJSONString(tuple(org, namespace, name, source_id))))" +_ELIGIBLE = """ + active AND source_kind = 'mcp' AND credential_mode = 'connected' + AND source_contract_version = 1 + AND JSONExtractUInt(config_json, 'version') = 1 + AND JSONHas(config_json, 'paused') AND JSONType(config_json, 'paused') = 'Bool' + AND NOT JSONExtractBool(config_json, 'paused') + AND JSONExtractString(config_json, 'mode') IN ('snapshot', 'selected_refresh') + AND source_id != '' +""" +PAGE_SQL = f""" +SELECT org, namespace, name, source_id, + JSONExtractString(config_json, 'profile_id') AS profile_id, + JSONExtractString(config_json, 'profile_sha256') AS profile_sha256, + {_KEY} AS schedule_key +FROM loom.knowledge_sources FINAL +WHERE {_ELIGIBLE} + AND schedule_key > {{after:String}} + AND ({{org:String}} = '' OR org = {{org:String}}) + AND ({{ns:String}} = '' OR namespace = {{ns:String}}) + AND ({{only:String}} = '' OR name = {{only:String}}) +ORDER BY schedule_key +LIMIT {{limit:UInt64}} +""" + + +class HeaderClient(Protocol): + async def query_all( + self, sql: str, params: dict[str, object], *, settings: dict[str, object] + ) -> list[dict[str, object]]: ... + + +@dataclass(frozen=True) +class QueryLimits: + rows: int + bytes: int + seconds: float + + def __post_init__(self) -> None: + if ( + type(self.rows) is not int + or self.rows <= 0 + or type(self.bytes) is not int + or self.bytes <= 0 + or not 0 < self.seconds < float("inf") + ): + raise ValueError("mcp_schedule_query_bound") + + +@dataclass(frozen=True, repr=False) +class Header: + org: str + namespace: str + name: str + source_id: str + profile_id: str + profile_sha256: str + schedule_key: str + + +async def candidate_page( + after: str, + limit: int, + *, + query_limits: QueryLimits, + org: str = "", + namespace: str = "", + only: str = "", + ch: HeaderClient | None = None, +) -> list[Header]: + """Metadata eligibility is a hint; the leased engine revalidates authority.""" + if type(limit) is not int or limit <= 0: + raise ValueError("mcp_schedule_page_bound") + if after and re.fullmatch("[0-9A-F]{64}", after) is None: + raise ValueError("mcp_schedule_cursor") + if (namespace or only) and not org: + raise ValueError("mcp_schedule_scope") + if only and not namespace: + raise ValueError("mcp_schedule_scope") + set_query_tag("worker.knowledge_source_sync") + rows = await (ch or get_client()).query_all( + PAGE_SQL, + params={"after": after, "limit": limit, "org": org, "ns": namespace, "only": only}, + settings={ + "max_rows_to_read": query_limits.rows, + "max_bytes_to_read": query_limits.bytes, + "max_execution_time": query_limits.seconds, + "read_overflow_mode": "throw", + }, + ) + if len(rows) > limit: + raise ValueError("mcp_schedule_page_overflow") + result = [Header(**{key: str(row[key]) for key in Header.__dataclass_fields__}) for row in rows] + if any( + re.fullmatch("[0-9A-F]{64}", row.schedule_key) is None + or not row.source_id + or row.schedule_key <= (result[i - 1].schedule_key if i else after) + for i, row in enumerate(result) + ): + raise ValueError("mcp_schedule_page_order") + return result diff --git a/server/knowledge/store/sources.py b/server/knowledge/store/sources.py index 859f1264ea..882997e74e 100644 --- a/server/knowledge/store/sources.py +++ b/server/knowledge/store/sources.py @@ -36,10 +36,8 @@ SYNC_WORKER_ACTOR, KnowledgeSource, id_list_config, - items_from_config, json_object, opaque_payload, - options_in, state_key, stored_config, ) @@ -97,9 +95,8 @@ def _source(row: dict[str, Any]) -> KnowledgeSource: name=str(row.get("name") or ""), kind=kind, source_id=str(row.get("source_id") or ""), - config=options_in(kind, config), - # A row an older build wrote holds its items in `config` alone. - items=[] if generic else (_items(items_raw) or items_from_config(kind, config)), + config=config, + items=[] if generic else _items(items_raw), credential_enc=str(row.get("credential_enc") or ""), secret_enc=str(row.get("secret_enc") or ""), access=str(row.get("access") or NAMESPACE_ACCESS), @@ -119,13 +116,14 @@ def _source(row: dict[str, Any]) -> KnowledgeSource: async def list_sources( - org: str, namespace: str, *, ch: _CHClient | None = None + org: str, namespace: str, *, include_mcp: bool = True, ch: _CHClient | None = None ) -> list[KnowledgeSource]: """The namespace's active sources, by name.""" rows = await (ch or _default_client()).query_all( f"SELECT {_COLUMNS} FROM {TABLE} FINAL " "WHERE org = {org:String} AND namespace = {ns:String} AND active " - "ORDER BY name", + + ("AND source_kind != 'mcp' " if not include_mcp else "") + + "ORDER BY name", params={"org": org, "ns": namespace}, ) return [_source(r) for r in rows] @@ -167,10 +165,11 @@ async def connected_sources( async def all_active_sources(*, ch: _CHClient | None = None) -> list[KnowledgeSource]: - """Every active source of every org, in (org, namespace, name) order: the sync - worker's work list.""" + """Ordinary recording work; MCP discovery uses bounded metadata pages.""" rows = await (ch or _default_client()).query_all( - f"SELECT {_COLUMNS} FROM {TABLE} FINAL WHERE active ORDER BY org, namespace, name" + f"SELECT {_COLUMNS} FROM {TABLE} FINAL WHERE active " + "AND source_kind = 'recording' AND credential_mode = 'shared' " + "AND source_contract_version = 0 ORDER BY org, namespace, name" ) return [_source(r) for r in rows] diff --git a/server/knowledge/workers/source_push.py b/server/knowledge/workers/source_push.py deleted file mode 100644 index 9944f7fc37..0000000000 --- a/server/knowledge/workers/source_push.py +++ /dev/null @@ -1,55 +0,0 @@ -"""Renew bounded Drive channel sets; ordinary source polling remains independent.""" - -from __future__ import annotations - -import json -import logging -import time - -from server.core.ch import set_query_tag -from server.knowledge.app.source_push import renew_drive, require_ready -from server.knowledge.store.source_push import drive_page -from server.settings import settings -from server.workers import pass_context -from server.workers.status import record_pass - -log = logging.getLogger(__name__) - - -async def run_pass() -> dict[str, int]: - set_query_tag("knowledge_source_push") - await require_ready() - try: - after = json.loads(pass_context.resume_cursor() or '["", "", ""]') - except ValueError: - after = ["", "", ""] - if not isinstance(after, list) or len(after) != 3 or not all(isinstance(s, str) for s in after): - after = ["", "", ""] - rows = await drive_page((after[0], after[1], after[2])) - result = {"items_planned": len(rows), "items_done": 0, "failed": 0} - # Leave one provider attempt and cleanup/status time before the supervisor cancels. - deadline = ( - time.monotonic() - + settings.knowledge_source_push_max_pass_seconds - - settings.knowledge_source_push_provider_timeout_s - - 2 * settings.knowledge_source_push_cleanup_timeout_s - ) - with record_pass("knowledge_source_push") as rec: - for reg in rows: - pass_context.check_stop() - if time.monotonic() >= deadline: - break - try: - await renew_drive(reg) - result["items_done"] += 1 - except Exception as e: # noqa: BLE001 — one failed source must not starve renewal of others - pass_context.note_failure(e, "channel renewal") - log.warning("source push renewal failed: %s", type(e).__name__) - result["failed"] += 1 - pass_context.set_cursor(json.dumps([reg.org, reg.namespace, reg.source_id])) - if result["items_done"] + result["failed"] == len(rows): - # A nonempty canonical cursor also resets a supervisor's older cursor. - if len(rows) < 20: - pass_context.set_cursor('["", "", ""]') - rec.outcome = result - return result diff --git a/server/main.py b/server/main.py index 777b0b78ac..87d390999f 100644 --- a/server/main.py +++ b/server/main.py @@ -549,6 +549,7 @@ def attach_browser_middleware(target: FastAPI) -> None: app.add_middleware(RetirementMiddleware) +from server.auth import account_lifecycle as _account_lifecycle # noqa: E402 from server.auth import login as _login # noqa: E402 from server.auth import oauth as _oauth # noqa: E402 from server.auth import scim_routes as _scim_routes # noqa: E402 @@ -557,11 +558,11 @@ def attach_browser_middleware(target: FastAPI) -> None: from server.identity.app import claim_release as _claim_release # noqa: E402 from server.identity.app import password_link as _password_link # noqa: E402 from server.identity.app import scim_groups as _scim_groups # noqa: E402 -from server.knowledge.app import connection_routes as _connected_accounts # noqa: E402 +from server.knowledge.app import connected_accounts as _connected_accounts # noqa: E402 +_account_lifecycle.bind(_connected_accounts.stop_subjects) _self_signup.attach(app) _login.attach(app) -_connected_accounts.attach(app) _claim_release.attach(app) # Sign-in (device grant, SSO) wherever auth is on; MCP connect only with LOOM_OAUTH_ENABLED. _oauth.attach(app) @@ -600,7 +601,6 @@ def attach_browser_middleware(target: FastAPI) -> None: from server.assistant.app import routes as _assistant_routes # noqa: E402 from server.auth import routes as _auth_routes # noqa: E402 from server.knowledge.app import download_routes as _knowledge_download # noqa: E402 -from server.knowledge.app import source_push_routes as _source_push # noqa: E402 from server.knowledge.app import upload_routes as _knowledge_upload # noqa: E402 _assistant_routes.attach(app) @@ -608,7 +608,6 @@ def attach_browser_middleware(target: FastAPI) -> None: _health.attach(app) _knowledge_download.attach(app) _knowledge_upload.attach(app) -_source_push.attach(app) @app.get("/v1/api/openapi.json") diff --git a/server/operations/registry.py b/server/operations/registry.py index 334bd02036..ce54841939 100644 --- a/server/operations/registry.py +++ b/server/operations/registry.py @@ -28,15 +28,14 @@ from server.insights.api import ops_mentor as mentor from server.insights.api import ops_ops as ops from server.insights.api import ops_ui as ui -from server.knowledge.api import ops_connections as connections from server.knowledge.api import ops_conversations as conversations from server.knowledge.api import ops_gaps as knowledge_gaps from server.knowledge.api import ops_knowledge as knowledge from server.knowledge.api import ops_mcp_connections as knowledge_mcp_connections from server.knowledge.api import ops_mcp_profiles as knowledge_mcp_profiles +from server.knowledge.api import ops_mcp_reads as knowledge_mcp_reads from server.knowledge.api import ops_mcp_sources as knowledge_mcp_sources 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.memory.api import ops_blacklist as blacklist from server.memory.api import ops_brief as memory_brief @@ -73,8 +72,7 @@ knowledge_mcp_profiles, knowledge_mcp_connections, knowledge_mcp_sources, - connections, - knowledge_source_push, + knowledge_mcp_reads, knowledge_gaps, query_history, help_docs, diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 4852679929..93ae020aa7 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -2410,22 +2410,6 @@ class KnowledgeSettings(BaseModel): # Bytes of an extractor's response the server reads; a larger artifact is refused. document_extractor_max_artifact_bytes: int = Field(default=64 * 1024 * 1024, ge=1024) - # ---- document sources ---- - # OAuth client id for personal Drive connections; empty disables the provider. - connect_gdrive_client_id: str = "" - # Secret of that Drive OAuth registration; kept outside source rows. - connect_gdrive_client_secret: str = "" - # Public-integration client id for personal page-store connections; empty disables it. - connect_notion_client_id: str = "" - # Secret of that page-store registration; kept outside source rows. - connect_notion_client_secret: str = "" - # OAuth client id for personal project-tracker connections; empty disables it. - connect_linear_client_id: str = "" - # Secret of that project-tracker registration; kept outside source rows. - connect_linear_client_secret: str = "" - # The operator has restricted the public integration to read-content capability. - # Its token response cannot prove this registration setting; false disables it. - connect_notion_read_content_only: bool = False # Seconds for the whole optional live-search leg, including final membership checks. # At most five; provider credential deadlines may shorten it further. knowledge_live_search_timeout_s: float = Field(default=5.0, gt=0, le=5.0) @@ -2456,6 +2440,40 @@ class KnowledgeSettings(BaseModel): knowledge_mcp_selected_resources_max: int = Field(default=1000, ge=1, le=1000) # Maximum UTF-8 bytes in one selected MCP identity, up to the v1 wire ceiling. knowledge_mcp_resource_id_max_bytes: int = Field(default=2048, ge=1, le=2048) + # Maximum trusted profile-catalog bytes admitted, up to the contract ceiling. + knowledge_source_mcp_catalog_max_bytes: int = Field(default=8388608, ge=1024, le=8388608) + # Maximum distinct approved profiles in one trusted catalog. + knowledge_source_mcp_catalog_max_profiles: int = Field(default=10000, ge=1, le=10000) + # Maximum canonical bytes in one approved profile. + knowledge_source_mcp_profile_max_bytes: int = Field(default=65536, ge=1024, le=65536) + # Maximum canonical schema or schema-string bytes in one mapping. + knowledge_source_mcp_schema_max_bytes: int = Field(default=16384, ge=128, le=16384) + # Maximum JSON nodes visited while validating one approved profile. + knowledge_source_mcp_profile_max_nodes: int = Field(default=4096, ge=16, le=4096) + # Maximum JSON nesting depth in one approved profile. + knowledge_source_mcp_profile_max_depth: int = Field(default=16, ge=1, le=16) + # MCP scheduling headers returned per bounded metadata query. + knowledge_source_mcp_schedule_page_size: int = Field(default=100, ge=1, le=256) + # Maximum metadata pages scanned in one MCP scheduling pass. + knowledge_source_mcp_schedule_scan_pages: int = Field(default=16, ge=1, le=1000) + # Maximum eligible source headers waiting for an execution slot. + knowledge_source_mcp_schedule_ready: int = Field(default=256, ge=1, le=4096) + # Concurrent MCP source turns across this worker pass. + knowledge_source_mcp_schedule_global: int = Field(default=16, ge=1, le=256) + # Concurrent MCP source turns for one organization. + knowledge_source_mcp_schedule_per_org: int = Field(default=4, ge=1, le=256) + # Concurrent turns sharing one canonical approved MCP endpoint. + knowledge_source_mcp_schedule_per_endpoint: int = Field(default=2, ge=1, le=256) + # Document credits reserved before admitting one MCP source turn. + knowledge_source_mcp_schedule_documents: int = Field(default=8, ge=1, le=1000) + # Outer deadline in seconds for one MCP source turn, including cleanup. + knowledge_source_mcp_schedule_source_seconds: float = Field(default=20.0, gt=0, le=300) + # Physical rows one MCP metadata query may read before refusing. + knowledge_source_mcp_schedule_query_rows: int = Field(default=1000000, ge=1) + # Physical bytes one MCP metadata query may read before refusing. + knowledge_source_mcp_schedule_query_bytes: int = Field(default=67108864, ge=1) + # Maximum execution seconds for one MCP metadata or progress query. + knowledge_source_mcp_schedule_query_seconds: float = Field(default=5.0, gt=0, le=60) # Maximum complete owner scan; exceeding it refuses instead of stopping a subset. knowledge_connected_registry_scan_limit: int = Field(default=4096, ge=1) # Registrations per page during root-secret resealing. @@ -2512,18 +2530,6 @@ def _mcp_profiles_size(cls, value: str) -> str: # 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. knowledge_source_acl_max_entries: int = Field(default=10000, ge=1) - # Enable optional source push setup, callbacks and Drive renewal; false keeps polling only. - knowledge_source_push_enabled: bool = False - # Seconds between bounded channel-renewal pages; channels renew a day before expiry. - knowledge_source_push_interval_seconds: int = Field(default=300, ge=60) - # Seconds one push setup or Drive renewal may spend on provider work, before cleanup. - knowledge_source_push_provider_timeout_s: float = Field(default=40.0, gt=0) - # Seconds allowed to stop one superseded or unpublished Drive channel. - knowledge_source_push_stop_timeout_s: float = Field(default=2.0, gt=0) - # Seconds allowed for the whole Drive channel cleanup; at least the per-channel wait. - knowledge_source_push_cleanup_timeout_s: float = Field(default=5.0, gt=0) - # Seconds a renewal pass may run; reserve one provider attempt and two cleanup windows. - knowledge_source_push_max_pass_seconds: float = Field(default=120.0, gt=0) # Seconds between sync passes while there are sources. knowledge_source_sync_interval_seconds: int = Field(default=900, ge=60) # Seconds between passes that found no source to sync; one idle sleep plus one @@ -2574,31 +2580,6 @@ def document_extractor_token_map(self) -> dict[str, str]: items = json_map_items(raw, "document_extractor_tokens_json", strings_only=True) return {url.rstrip("/"): token for url, token in items} - @model_validator(mode="after") - def _check_source_push_budgets(self) -> KnowledgeSettings: - provider = self.knowledge_source_push_provider_timeout_s - cleanup = self.knowledge_source_push_cleanup_timeout_s - if self.knowledge_source_push_stop_timeout_s > cleanup: - raise ValueError( - "LOOM_KNOWLEDGE_SOURCE_PUSH_STOP_TIMEOUT_S must not exceed " - "LOOM_KNOWLEDGE_SOURCE_PUSH_CLEANUP_TIMEOUT_S" - ) - # holding() permits work for 40% of renew_drive's 120-second lease. - # Keep this window in sync with leases.work_left; the regression checks both. - if provider + cleanup >= 48: - raise ValueError( - "LOOM_KNOWLEDGE_SOURCE_PUSH_PROVIDER_TIMEOUT_S plus " - "LOOM_KNOWLEDGE_SOURCE_PUSH_CLEANUP_TIMEOUT_S must stay below the " - "48-second renewal work window" - ) - if provider + 2 * cleanup >= self.knowledge_source_push_max_pass_seconds: - raise ValueError( - "LOOM_KNOWLEDGE_SOURCE_PUSH_MAX_PASS_SECONDS must exceed " - "LOOM_KNOWLEDGE_SOURCE_PUSH_PROVIDER_TIMEOUT_S plus twice " - "LOOM_KNOWLEDGE_SOURCE_PUSH_CLEANUP_TIMEOUT_S" - ) - return self - @model_validator(mode="after") def _check_document_extractors(self) -> KnowledgeSettings: """Every extractor URL is http(s) with a host. The error names the entry, @@ -6181,8 +6162,6 @@ class TrackerSettings(BaseModel): OP_BUDGETS_P99_MS: dict[str, int] = { # Own connection listing rechecks current identity and provider registration; # disconnect includes bounded local retirement followed by best-effort revocation. - "connection.list": 1000, - "connection.disconnect": 30000, "admin.users": 300, "agents.connected": 120, # One agent answer: a model turn per tool call (measured p95 10.7 s, at most 15 s @@ -6448,14 +6427,19 @@ class TrackerSettings(BaseModel): "knowledge.connection.mcp_discover": 30000, "knowledge.connection.mcp_inspect": 5000, "knowledge.connection.mcp_list": 5000, - "knowledge.source.parse_links": 50, + "knowledge.connection.mcp_browse": 5000, + "knowledge.source.mcp_read": 5000, + "knowledge.source.mcp_add": 30000, + "knowledge.source.mcp_update": 5000, + "knowledge.source.mcp_list": 5000, + "knowledge.source.mcp_inspect": 5000, + "knowledge.source.mcp_pause": 5000, + "knowledge.source.mcp_resume": 5000, + "knowledge.source.mcp_refresh": 5000, + "knowledge.source.mcp_remove": 5000, "knowledge.source.remove": 400, "knowledge.source.rotate": 30000, "knowledge.source.sync_now": 300, - "knowledge.source.push_configure": 60000, - "knowledge.source.push_status": 1000, - "knowledge.source.push_confirm": 1000, - "knowledge.source.update": 60000, # One LLM call per window plus the reduce; bounded by max_windows. "knowledge.synthesize": 60000, # A read and an insert; an ingested document's edit also takes the source's claim diff --git a/server/workers/registry.py b/server/workers/registry.py index de9c0e576d..88e276dde0 100644 --- a/server/workers/registry.py +++ b/server/workers/registry.py @@ -452,13 +452,6 @@ def _spec_for(row: _Worker) -> WorkerSpec: idle_interval="knowledge_source_sync_idle_interval_seconds", max_pass_attr="MAX_PASS_SECONDS", ), - _Worker( - "knowledge_source_push", - "server.knowledge.workers.source_push", - "knowledge_source_push_enabled", - "knowledge_source_push_interval_seconds", - max_pass_setting="knowledge_source_push_max_pass_seconds", - ), _Worker( "code_embed_recovery", "server.code.workers.embed_recovery", diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 51a1fd6e4c..8e9311db37 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -426,10 +426,6 @@ "code_vector_tables": "", "conflict_resolver_model": "gpt-6.1-sol", "conflict_threshold": 0.85, - "connect_gdrive_client_id": "", - "connect_linear_client_id": "", - "connect_notion_client_id": "", - "connect_notion_read_content_only": false, "consolidation_merge_concurrency": 4, "context_offload_max_bytes": 8000000, "conversation_search_excerpt_chars": 240, @@ -595,6 +591,10 @@ "knowledge_live_search_max_sources": 3, "knowledge_live_search_response_max_bytes": 262144, "knowledge_live_search_timeout_s": 5.0, + "knowledge_mcp_connections_max_per_person": 32, + "knowledge_mcp_envelope_max_bytes": 32768, + "knowledge_mcp_resource_id_max_bytes": 2048, + "knowledge_mcp_selected_resources_max": 1000, "knowledge_mirrored_sources_enabled": false, "knowledge_noise_filter": true, "knowledge_orphan_chunk_min_age_seconds": 3600, @@ -619,15 +619,28 @@ "knowledge_source_acl_max_entries": 10000, "knowledge_source_acl_stale_seconds": 3600, "knowledge_source_max_documents": 50000, + "knowledge_source_mcp_catalog_max_bytes": 8388608, + "knowledge_source_mcp_catalog_max_profiles": 10000, + "knowledge_source_mcp_profile_max_bytes": 65536, + "knowledge_source_mcp_profile_max_depth": 16, + "knowledge_source_mcp_profile_max_nodes": 4096, + "knowledge_source_mcp_profiles_json": "", + "knowledge_source_mcp_schedule_documents": 8, + "knowledge_source_mcp_schedule_global": 16, + "knowledge_source_mcp_schedule_page_size": 100, + "knowledge_source_mcp_schedule_per_endpoint": 2, + "knowledge_source_mcp_schedule_per_org": 4, + "knowledge_source_mcp_schedule_query_bytes": 67108864, + "knowledge_source_mcp_schedule_query_rows": 1000000, + "knowledge_source_mcp_schedule_query_seconds": 5.0, + "knowledge_source_mcp_schedule_ready": 256, + "knowledge_source_mcp_schedule_scan_pages": 16, + "knowledge_source_mcp_schedule_source_seconds": 20.0, + "knowledge_source_mcp_schema_max_bytes": 16384, "knowledge_source_mirror_documents_per_pass": 40, "knowledge_source_probe_timeout_s": 20.0, - "knowledge_source_push_cleanup_timeout_s": 5.0, - "knowledge_source_push_enabled": false, - "knowledge_source_push_interval_seconds": 300, - "knowledge_source_push_max_pass_seconds": 120.0, - "knowledge_source_push_provider_timeout_s": 40.0, - "knowledge_source_push_stop_timeout_s": 2.0, "knowledge_source_retire_documents_per_pass": 40, + "knowledge_source_self_service_enabled": true, "knowledge_source_sync_cap_share": 0.25, "knowledge_source_sync_documents_per_pass": 40, "knowledge_source_sync_enabled": false, diff --git a/tests/unit/snapshots/worker_registry.json b/tests/unit/snapshots/worker_registry.json index 14e6b96699..fd40e802fc 100644 --- a/tests/unit/snapshots/worker_registry.json +++ b/tests/unit/snapshots/worker_registry.json @@ -576,20 +576,6 @@ "id": "server.knowledge.workers.source_retirements:run_pass" } }, - { - "deadline_seconds()": 120.0, - "due_scope": null, - "first_pass_due": null, - "has_first_pass_hook": false, - "idle_interval_seconds": null, - "interval_seconds": 300, - "max_pass_seconds": 120.0, - "name": "knowledge_source_push", - "owned_tables": [], - "pass_callable": { - "id": "server.knowledge.workers.source_push:run_pass" - } - }, { "deadline_seconds()": 120.0, "due_scope": null, diff --git a/tests/unit/test_connected_account_cleanup.py b/tests/unit/test_connected_account_cleanup.py index f7c4053da2..18335fcf89 100644 --- a/tests/unit/test_connected_account_cleanup.py +++ b/tests/unit/test_connected_account_cleanup.py @@ -1,9 +1,10 @@ -"""Disconnect fences credentials and source work before any remote cleanup.""" +"""Local retirement fences credentials and source work without provider HTTP.""" from contextlib import asynccontextmanager from datetime import UTC, datetime from typing import Any +import httpx import pytest from server.erasure.store import census @@ -60,8 +61,8 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch, kinds: tuple[str, ...] = ("g monkeypatch.setattr(connections.source_store, "insert_source", self.insert_source) monkeypatch.setattr(sources, "_queue_retirement", self.queue) monkeypatch.setattr(source_push, "retire", self.retire_push) - monkeypatch.setattr(connections, "_revoke", self.revoke) - monkeypatch.setattr(connections.audit, "emit", self.audit) + monkeypatch.setattr(httpx.AsyncClient, "send", self.forbid_http) + monkeypatch.setattr(connections, "unseal", self.forbid_decryption) @asynccontextmanager async def lease(self, *_args: Any, **_kw: Any): @@ -148,45 +149,45 @@ async def queue(self, source: KnowledgeSource): async def retire_push(self, source: KnowledgeSource): self.events.append(("push", source.source_id)) - async def revoke(self, account: ConnectedAccount, **_kw: Any): - assert self.depth == 0, "provider cleanup ran under an account/source lease" - assert all(not a.active and not a.credential_enc for a in self.accounts.values()) - assert all(not s.active and s.pending_delete for s in self.sources.values()) - self.events.append(("provider", account.kind)) + async def forbid_http(self, *_args: Any, **_kw: Any): + raise AssertionError("local retirement cannot dispatch provider HTTP") - async def audit(self, *_args: Any, **_kw: Any): - return None + def forbid_decryption(self, *_args: Any, **_kw: Any): + raise AssertionError("local retirement cannot decrypt legacy credentials") + + +async def _stop(world: _World, kind: str = "gdrive") -> None: + async with connections.account_lease("team", "person", kind): + await connections._stop_locked(world.accounts["team", "person", kind]) @pytest.mark.asyncio -async def test_disconnect_queues_source_retirement_before_inactivation_and_remote_revoke( +async def test_stop_queues_source_retirement_before_inactivation_without_native_execution( monkeypatch: pytest.MonkeyPatch, ): world = _World(monkeypatch) previous = world.accounts["team", "person", "gdrive"].connection_id - await connections.disconnect("team", "person", "gdrive") + await _stop(world) account = world.accounts["team", "person", "gdrive"] assert account.connection_id != previous assert world.fences[connections._fence_key(account.connection_id)] == account.connection_id assert world.events.index(("retire", "source-gdrive")) < world.events.index( ("source", "source-gdrive") ) - assert world.events[-1] == ("provider", "gdrive") + assert not account.active and account.credential_enc == account.account_email_enc == "" + assert world.sources["gdrive"].pending_delete and not world.sources["gdrive"].active assert world.sources["gdrive"].credential_enc == world.sources["gdrive"].secret_enc == "" @pytest.mark.asyncio -async def test_subject_revocation_stops_every_local_account_and_source_before_first_provider( +async def test_subject_revocation_stops_every_local_account_and_source_without_native_execution( monkeypatch: pytest.MonkeyPatch, ): world = _World(monkeypatch, ("gdrive", "notion")) await connections.stop_subjects(["person"], org="team") - assert [item for item in world.events if item[0] == "provider"] == [ - ("provider", "gdrive"), - ("provider", "notion"), - ] - first_provider = next(i for i, event in enumerate(world.events) if event[0] == "provider") - assert all(event[0] == "provider" for event in world.events[first_provider:]) + assert all(not a.active and not a.credential_enc for a in world.accounts.values()) + assert all(not s.active and s.pending_delete for s in world.sources.values()) + assert {kind for event, kind in world.events if event == "erase"} == {"gdrive", "notion"} @pytest.mark.asyncio @@ -197,13 +198,13 @@ async def test_disconnect_retry_repairs_cleanup_after_generation_fence_outlives_ account = world.accounts["team", "person", "gdrive"] world.fail_next_account_write = True with pytest.raises(RuntimeError, match="account write lost"): - await connections.disconnect("team", "person", "gdrive") + await _stop(world) assert world.fences[connections._fence_key(account.connection_id)] != account.connection_id assert not any(event[0] == "provider" for event in world.events) - await connections.disconnect("team", "person", "gdrive") + await _stop(world) assert not world.accounts["team", "person", "gdrive"].active assert not world.sources["gdrive"].active and world.sources["gdrive"].pending_delete - assert world.events[-1] == ("provider", "gdrive") + assert world.accounts["team", "person", "gdrive"].credential_enc == "" @pytest.mark.asyncio @@ -216,7 +217,7 @@ async def test_stale_account_row_cannot_stop_a_newer_live_connection( replacement = account.connection_id.partition("/")[0] + "/1" + "b" * 31 world.fences[key] = replacement with pytest.raises(connections.ValidationError): - await connections.disconnect("team", "person", "gdrive") + await _stop(world) assert world.fences[key] == replacement assert world.accounts["team", "person", "gdrive"] is account assert world.sources["gdrive"].active diff --git a/tests/unit/test_connected_account_contracts.py b/tests/unit/test_connected_account_contracts.py index e7b9c805d1..819cf2fc71 100644 --- a/tests/unit/test_connected_account_contracts.py +++ b/tests/unit/test_connected_account_contracts.py @@ -1,8 +1,7 @@ -"""Canonical-owner persistence, cleanup, own-list and configured lifecycle bounds.""" +"""Canonical-owner persistence, cleanup and configured lifecycle bounds.""" from __future__ import annotations -import time from contextlib import asynccontextmanager from dataclasses import asdict from types import SimpleNamespace @@ -11,22 +10,12 @@ import pytest from server.auth import account_lifecycle -from server.auth.context import current_auth_var -from server.core.errors import BackendUnavailableError, ValidationError -from server.core.secrets_at_rest import unseal +from server.core.errors import BackendUnavailableError from server.erasure.store import census -from server.knowledge.api.models_connections import ConnectionListInput from server.knowledge.app import connected_accounts as accounts -from server.knowledge.app.connections import handle_connection_list -from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE, ConnectedAccount +from server.knowledge.domain.connected_accounts import ConnectedAccount from server.knowledge.store import connected_accounts as store -from tests.unit.test_connected_account_callbacks import ( - _auth, - _World, -) -from tests.unit.test_connected_account_callbacks import ( - world as world, -) +from tests.unit.test_connected_account_cleanup import _World class _Rows: @@ -114,19 +103,19 @@ async def test_owner_scan_refuses_truncation_and_reseal_page_uses_configured_bou async def test_account_lease_forwards_configured_ttl_and_wait_and_stop_bound( - world: _World, monkeypatch: pytest.MonkeyPatch, ) -> None: + account_lease = accounts.account_lease + world = _World(monkeypatch) + world.sources.clear() held = [] timeouts = [] - lease = accounts.leases.cluster_lease timeout = accounts.asyncio.timeout @asynccontextmanager async def tracked_lease(key: str, **kw: Any): held.append((key, kw)) - async with lease(key, **kw): - yield + yield def tracked_timeout(seconds: float): timeouts.append(seconds) @@ -135,15 +124,15 @@ def tracked_timeout(seconds: float): monkeypatch.setattr(accounts.settings, "knowledge_connected_lease_ttl_s", 41.0) monkeypatch.setattr(accounts.settings, "knowledge_connected_lease_wait_s", 1.25) monkeypatch.setattr(accounts.settings, "knowledge_connected_stop_timeout_s", 7.0) + monkeypatch.setattr(accounts, "account_lease", account_lease) monkeypatch.setattr(accounts.leases, "cluster_lease", tracked_lease) monkeypatch.setattr(accounts, "asyncio", SimpleNamespace(timeout=tracked_timeout)) - await accounts.disconnect("team", "person", "gdrive") + await accounts.stop_subjects(["person"], org="team") assert timeouts == [7.0] assert len(held) == 1 and held[0][0].startswith("connected-account:") assert held[0][1]["ttl_s"] == 41.0 and held[0][1]["wait_s"] == 1.25 - assert not world.requests - assert set(world.rows) == {("team", "person", "gdrive")} - ended = world.rows[("team", "person", "gdrive")] + assert set(world.accounts) == {("team", "person", "gdrive")} + ended = world.accounts[("team", "person", "gdrive")] assert asdict(ended) == { "org": "team", "subject": "person", @@ -160,65 +149,11 @@ def tracked_timeout(seconds: float): "disconnected_at": ended.disconnected_at, "version": ended.version, } - assert ended.disconnected_at is not None and ended.version > 0 + assert ended.disconnected_at is not None prefix, generation = ended.connection_id.split("/") assert len(prefix) == len(generation) == 32 and generation.startswith("0") assert set(prefix + generation) <= set("0123456789abcdef") - assert world.keeper == { - "connected-account-generation:" + prefix: (ended.connection_id, accounts._FENCE_EXPIRY) - } - - -async def test_provider_revoke_uses_its_own_bound_after_local_stop( - monkeypatch: pytest.MonkeyPatch, -) -> None: - captured = [] - - async def revoke(token: str, **kw: Any): - captured.append((token, kw)) - - monkeypatch.setattr(accounts.settings, "knowledge_connected_revoke_timeout_s", 2.5) - monkeypatch.setattr(accounts, "client", lambda _kind: SimpleNamespace(revoke=revoke)) - before = time.monotonic() - await accounts._revoke( - ConnectedAccount("team", "person", "gdrive", "stopped"), credential="old" - ) - after = time.monotonic() - assert len(captured) == 1 and captured[0][0] == "old" - assert captured[0][1]["refresh"] is True - assert before + 2.5 <= captured[0][1]["deadline"] <= after + 2.5 - - -async def test_connection_list_uses_own_subject_and_hides_a_stopped_generation( - world: _World, - monkeypatch: pytest.MonkeyPatch, -) -> None: - _url, state, binding = await accounts.start(_auth(), "gdrive") - await accounts.callback("gdrive", state, binding, "older-code") - account = world.account() - - async def owned(subjects: list[str], *, org: str): - assert subjects == ["person"] and org == "team" - return [account] - - monkeypatch.setattr(store, "owned", owned) - token = current_auth_var.set(_auth()) - try: - result = await handle_connection_list(ConnectionListInput(org="team")) - entry = next(x for x in result.connections if x.kind == "gdrive") - assert entry.connected and entry.account_email == "display@example.com" - with pytest.raises(ValidationError): - await handle_connection_list(ConnectionListInput(org="other")) - world.keeper[accounts._fence_key(account.connection_id)] = ( - "stopped", - int(time.time()) + 60, - ) - result = await handle_connection_list(ConnectionListInput(org="team")) - entry = next(x for x in result.connections if x.kind == "gdrive") - assert not entry.connected and entry.account_email is None and entry.scopes == [] - finally: - current_auth_var.reset(token) - assert unseal(CREDENTIAL_PURPOSE, account.credential_enc) + assert world.fences == {"connected-account-generation:" + prefix: ended.connection_id} async def test_uncomposed_auth_retirement_refuses_instead_of_skipping_cleanup( @@ -229,13 +164,10 @@ async def test_uncomposed_auth_retirement_refuses_instead_of_skipping_cleanup( await account_lifecycle.stop_connections(["person"], erase_owner=True) -async def test_http_composition_binds_real_revocation_cleanup_before_serving( - world: _World, monkeypatch: pytest.MonkeyPatch +async def test_lifecycle_binding_runs_real_revocation_cleanup( + monkeypatch: pytest.MonkeyPatch, ) -> None: - from fastapi import FastAPI - - from server.knowledge.app import connection_routes - + _World(monkeypatch) scans = [] async def identities(*, org=None): @@ -250,7 +182,7 @@ async def owned(subjects, *, org=None): monkeypatch.setattr(store, "owner_identities", identities) monkeypatch.setattr(store, "owned", owned) - connection_routes.attach(FastAPI()) + account_lifecycle.bind(accounts.stop_subjects) assert account_lifecycle._stopper is accounts.stop_subjects await account_lifecycle.stop_connections(["person"], respect_cutoff=True) - assert scans == [None] and not world.requests + assert scans == [None] diff --git a/tests/unit/test_connected_account_refresh.py b/tests/unit/test_connected_account_refresh.py deleted file mode 100644 index aea5b75e56..0000000000 --- a/tests/unit/test_connected_account_refresh.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Refusing an unsent checkout does not destroy another person's provider grant.""" - -from __future__ import annotations - -import time - -import httpx -import pytest - -from server.core import request_work -from server.core.errors import ValidationError -from server.core.secrets_at_rest import unseal -from server.knowledge.app import connected_accounts as accounts -from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE -from server.operations.base import Role -from tests.unit.principals import acting_as -from tests.unit.test_connected_source_authority import _KEY, _REFRESH -from tests.unit.test_connected_source_operations import _operator, _World - - -async def test_presenter_lost_before_refresh_dispatch_releases_only_its_reservation( - monkeypatch: pytest.MonkeyPatch, -) -> None: - async def provider(request: httpx.Request) -> httpx.Response: - return await state.handle(request) - - async with httpx.AsyncClient(transport=httpx.MockTransport(provider)) as http: - state = _World(monkeypatch, http) - original = state.rows[_KEY] - put = state.put - - async def persisted(row, **kwargs): - await put(row, **kwargs) - if row.active and row.refresh_id: - state.roles["operator"] = Role.VIEWER - - monkeypatch.setattr(accounts.store, "put", persisted) - assert state.source is not None - with ( - request_work.bind(request_work.RequestWork()), - acting_as(_operator(Role.VIEWER)), - pytest.raises(ValidationError, match="^the connected account is unavailable$"), - ): - await accounts.resolve_probe(state.source, deadline=time.monotonic() + 30) - current = state.rows[_KEY] - assert current.active and not current.refresh_id - assert current.connection_id == original.connection_id - assert unseal(CREDENTIAL_PURPOSE, current.credential_enc) == _REFRESH - assert state.source is not None and state.source.active - assert state.refresh_requests == state.native_requests == [] - assert state.source_writes == state.retirement_rows == [] diff --git a/tests/unit/test_connected_account_refresh_cancel.py b/tests/unit/test_connected_account_refresh_cancel.py deleted file mode 100644 index fd0a626cd6..0000000000 --- a/tests/unit/test_connected_account_refresh_cancel.py +++ /dev/null @@ -1,78 +0,0 @@ -"""Cancellation of an unsent reserved checkout leaves the owner's grant usable.""" - -from __future__ import annotations - -import asyncio -import time -from contextlib import asynccontextmanager - -import httpx -import pytest - -from server.core import request_work -from server.core.secrets_at_rest import unseal -from server.knowledge.app import connected_accounts as accounts -from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE -from server.operations.base import Role -from tests.unit.principals import acting_as -from tests.unit.test_connected_source_authority import _KEY, _REFRESH -from tests.unit.test_connected_source_operations import _operator, _World - - -@pytest.mark.parametrize("stage", ("store-write", "lease-exit")) -async def test_cancellation_after_reservation_write_releases_only_the_unsent_checkout( - monkeypatch: pytest.MonkeyPatch, - stage: str, -) -> None: - async def provider(request: httpx.Request) -> httpx.Response: - raise AssertionError("the cancelled reservation must never reach the provider") - - async with httpx.AsyncClient(transport=httpx.MockTransport(provider)) as http: - state = _World(monkeypatch, http) - original = state.rows[_KEY] - persisted = asyncio.Event() - release = asyncio.Event() - put = state.put - - async def paused_put(row, **kwargs): - await put(row, **kwargs) - if stage == "store-write" and row.active and row.refresh_id: - persisted.set() - await release.wait() - - paused = False - - @asynccontextmanager - async def paused_lease(key, **kwargs): - nonlocal paused - async with state.lease(key, **kwargs): - yield - if stage == "lease-exit" and not paused and state.rows[_KEY].refresh_id: - paused = True - persisted.set() - await release.wait() - - monkeypatch.setattr(accounts.store, "put", paused_put) - monkeypatch.setattr(accounts.leases, "cluster_lease", paused_lease) - assert state.source is not None - with request_work.bind(request_work.RequestWork()), acting_as(_operator(Role.VIEWER)): - work = asyncio.create_task( - accounts.resolve_probe(state.source, deadline=time.monotonic() + 30) - ) - try: - await state.await_stage(persisted, work) - work.cancel() - with pytest.raises(asyncio.CancelledError): - await work - finally: - release.set() - if not work.done(): - work.cancel() - await asyncio.gather(work, return_exceptions=True) - current = state.rows[_KEY] - assert current.active and not current.refresh_id - assert current.connection_id == original.connection_id - assert unseal(CREDENTIAL_PURPOSE, current.credential_enc) == _REFRESH - assert state.source is not None and state.source.active - assert state.refresh_requests == state.native_requests == [] - assert state.source_writes == state.retirement_rows == [] diff --git a/tests/unit/test_connected_oauth.py b/tests/unit/test_connected_oauth.py deleted file mode 100644 index 6648b03037..0000000000 --- a/tests/unit/test_connected_oauth.py +++ /dev/null @@ -1,516 +0,0 @@ -"""Connected OAuth clients send provider-specific requests to fixed origins.""" - -from __future__ import annotations - -import asyncio -import base64 -import inspect -import json -import traceback -from collections.abc import AsyncIterator, Awaitable, Callable -from contextlib import asynccontextmanager -from typing import Any -from urllib.parse import parse_qs, urlsplit - -import httpx -import pytest - -from server.clients import connected_oauth as oauth -from server.clients.notion import API_VERSION - -_STATE = "browser_binding_0123456789abcdef0123456789abcdef" -# RFC 7636's S256 example, independently fixing the expected wire challenge. -_VERIFIER = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk" -_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" -_DRIVE = "https://www.googleapis.com/auth/drive.readonly" -_EMAIL = "https://www.googleapis.com/auth/userinfo.email" - - -@pytest.fixture(autouse=True) -def clock(monkeypatch: pytest.MonkeyPatch) -> list[float]: - value = [100.0] - monkeypatch.setattr(oauth, "_now", lambda: value[0]) - return value - - -def _client(kind: oauth.Kind) -> oauth.OAuthClient: - return oauth.OAuthClient(kind, "client", "client-secret", "https://app.example/prefix/") - - -def _tokens(kind: oauth.Kind, **extra: Any) -> dict[str, Any]: - body: dict[str, Any] = { - "access_token": "access-private", - "refresh_token": "refresh-private", - "token_type": "Bearer", - } - if kind != "notion": - body.update( - expires_in=3600, scope=f"{_DRIVE} openid {_EMAIL}" if kind == "gdrive" else "read" - ) - return {**body, **extra} - - -@asynccontextmanager -async def _wire( - monkeypatch: pytest.MonkeyPatch, - handler: Callable[[httpx.Request], httpx.Response | Awaitable[httpx.Response]], -) -> AsyncIterator[list[httpx.Request]]: - seen: list[httpx.Request] = [] - - async def respond(request: httpx.Request) -> httpx.Response: - seen.append(request) - reply = handler(request) - return await reply if inspect.isawaitable(reply) else reply - - async with httpx.AsyncClient( - transport=httpx.MockTransport(respond), follow_redirects=True, trust_env=False - ) as client: - monkeypatch.setattr(oauth, "get_client", lambda: client) - yield seen - - -def _form(request: httpx.Request) -> dict[str, list[str]]: - assert request.headers["content-type"] == "application/x-www-form-urlencoded" - return parse_qs(request.content.decode()) - - -@pytest.mark.parametrize("kind", ["gdrive", "notion", "linear"]) -def test_consent_has_fixed_provider_callback_state_and_supported_pkce(kind: oauth.Kind) -> None: - client = _client(kind) - url = urlsplit( - client.authorization_url(_STATE, verifier=None if kind == "notion" else _VERIFIER) - ) - expected = { - "gdrive": ("accounts.google.com", "/o/oauth2/v2/auth"), - "notion": ("api.notion.com", "/v1/oauth/authorize"), - "linear": ("linear.app", "/oauth/authorize"), - } - assert url.scheme == "https" and (url.netloc, url.path) == expected[kind] - query = parse_qs(url.query) - assert query["client_id"] == ["client"] and query["state"] == [_STATE] - assert query["response_type"] == ["code"] - assert query["redirect_uri"] == [f"https://app.example/prefix/v1/connect/{kind}/callback"] - assert "client-secret" not in url.geturl() and _VERIFIER not in url.geturl() - if kind == "notion": - assert query["owner"] == ["user"] - assert not {"scope", "code_challenge", "access_type"}.intersection(query) - else: - assert query["code_challenge"] == [_CHALLENGE] - assert query["code_challenge_method"] == ["S256"] - assert set(query["scope"][0].split()) == ( - {_DRIVE, "openid", "email"} if kind == "gdrive" else {"read"} - ) - if kind == "gdrive": - assert query["access_type"] == ["offline"] - assert query["include_granted_scopes"] == ["false"] - assert query["prompt"] == ["consent"] - else: - assert query["actor"] == ["user"] and "access_type" not in query - - -def test_invalid_configuration_state_and_pkce_refuse_before_building_a_consent_url() -> None: - for base in ( - "http://external.example", - "https://user:password@app.example", - "https://app.example:broken", - "https://app.example/?redirect=https://other.example", - "https://app.example/\r\nredirect", - ): - with pytest.raises(oauth.OAuthError, match="^invalid_public_base$"): - oauth.OAuthClient("gdrive", "client", "secret", base) - with pytest.raises(oauth.OAuthError, match="^not_configured$"): - oauth.OAuthClient("gdrive", "client", "", "https://app.example") - with pytest.raises(oauth.OAuthError, match="^invalid_state$"): - _client("gdrive").authorization_url( - "state&redirect_uri=https://other.example", verifier=_VERIFIER - ) - with pytest.raises(oauth.OAuthError, match="^invalid_pkce$"): - _client("gdrive").authorization_url(_STATE, verifier="short") - with pytest.raises(oauth.OAuthError, match="^unsupported_pkce$"): - _client("notion").authorization_url(_STATE, verifier=_VERIFIER) - - -@pytest.mark.asyncio -async def test_google_exchange_uses_form_pkce_canonical_scopes_and_stable_userinfo_subject( - monkeypatch: pytest.MonkeyPatch, clock: list[float] -) -> None: - def reply(request: httpx.Request) -> httpx.Response: - if request.url.host == "oauth2.googleapis.com": - assert request.method == "POST" and request.url.path == "/token" - assert _form(request) == { - "grant_type": ["authorization_code"], - "code": ["opaque-code"], - "redirect_uri": ["https://app.example/prefix/v1/connect/gdrive/callback"], - "code_verifier": [_VERIFIER], - "client_id": ["client"], - "client_secret": ["client-secret"], - } - assert request.extensions["timeout"]["read"] == 30 - clock[0] = 112 - return httpx.Response(200, json=_tokens("gdrive")) - assert str(request.url) == "https://openidconnect.googleapis.com/v1/userinfo" - assert request.method == "GET" and not request.content - assert request.headers["authorization"] == "Bearer access-private" - assert request.extensions["timeout"]["read"] == 18 - return httpx.Response(200, json={"sub": "stable-sub", "email": "display@example.com"}) - - async with _wire(monkeypatch, reply) as seen: - grant = await _client("gdrive").exchange("opaque-code", verifier=_VERIFIER, deadline=130) - assert len(seen) == 2 - assert grant.account_id == "stable-sub" and grant.display_email == "display@example.com" - assert grant.workspace_id is None - assert set(grant.tokens.scopes) == {_DRIVE, "openid", "email"} - assert grant.tokens.expires_in == 3600 and grant.tokens.refresh_token == "refresh-private" - assert "private" not in repr(grant) + repr(grant.tokens) - assert "client-secret" not in repr(_client("gdrive")) - - -@pytest.mark.asyncio -async def test_notion_exchange_uses_basic_json_owner_id_and_optional_display_email( - monkeypatch: pytest.MonkeyPatch, -) -> None: - def reply(request: httpx.Request) -> httpx.Response: - assert str(request.url) == "https://api.notion.com/v1/oauth/token" - assert ( - request.headers["authorization"] - == "Basic " + base64.b64encode(b"client:client-secret").decode() - ) - assert request.headers["Notion-Version"] == API_VERSION - assert json.loads(request.content) == { - "grant_type": "authorization_code", - "code": "opaque-code", - "redirect_uri": "https://app.example/prefix/v1/connect/notion/callback", - } - return httpx.Response( - 200, - json=_tokens( - "notion", - owner={"type": "user", "user": {"id": "human-id", "person": {}}}, - workspace_id="workspace-id", - bot_id="authorization-bot", - scope="opaque-capability-text", - ), - ) - - async with _wire(monkeypatch, reply) as seen: - grant = await _client("notion").exchange("opaque-code", deadline=130) - assert len(seen) == 1 - assert grant.account_id == "human-id" and grant.account_id != "authorization-bot" - assert grant.workspace_id == "workspace-id" and grant.display_email is None - assert grant.tokens.expires_in is None and grant.tokens.scopes == () - - -@pytest.mark.asyncio -async def test_linear_exchange_resolves_bearer_viewer_and_accepts_legacy_read_scope_array( - monkeypatch: pytest.MonkeyPatch, -) -> None: - def reply(request: httpx.Request) -> httpx.Response: - if request.url.path == "/oauth/token": - assert str(request.url) == "https://api.linear.app/oauth/token" - assert _form(request) == { - "grant_type": ["authorization_code"], - "code": ["opaque-code"], - "redirect_uri": ["https://app.example/prefix/v1/connect/linear/callback"], - "code_verifier": [_VERIFIER], - "client_id": ["client"], - "client_secret": ["client-secret"], - } - return httpx.Response(200, json=_tokens("linear", scope=["read"])) - assert str(request.url) == "https://api.linear.app/graphql" - assert request.headers["authorization"] == "Bearer access-private" - assert json.loads(request.content) == {"query": "query { viewer { id name email } }"} - return httpx.Response( - 200, json={"data": {"viewer": {"id": "viewer-id", "email": "display@example.com"}}} - ) - - async with _wire(monkeypatch, reply) as seen: - grant = await _client("linear").exchange("opaque-code", verifier=_VERIFIER, deadline=130) - assert len(seen) == 2 and grant.account_id == "viewer-id" - assert grant.tokens.scopes == ("read",) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("kind", ["gdrive", "notion", "linear"]) -async def test_refresh_sends_provider_credentials_and_retains_or_rotates_only_documented_material( - monkeypatch: pytest.MonkeyPatch, kind: oauth.Kind -) -> None: - response = _tokens(kind, access_token="new-access", refresh_token="new-refresh") - if kind == "gdrive": - del response["refresh_token"] - del response["scope"] - - def reply(request: httpx.Request) -> httpx.Response: - assert ( - str(request.url) - == { - "gdrive": "https://oauth2.googleapis.com/token", - "notion": "https://api.notion.com/v1/oauth/token", - "linear": "https://api.linear.app/oauth/token", - }[kind] - ) - fields = {"grant_type": "refresh_token", "refresh_token": "old-refresh"} - if kind == "notion": - assert json.loads(request.content) == fields - assert request.headers["authorization"].startswith("Basic ") - assert request.headers["Notion-Version"] == API_VERSION - else: - assert _form(request) == { - k: [v] - for k, v in { - **fields, - "client_id": "client", - "client_secret": "client-secret", - }.items() - } - return httpx.Response(200, json=response) - - scopes = ( - tuple(sorted({_DRIVE, "openid", "email"})) - if kind == "gdrive" - else ("read",) - if kind == "linear" - else () - ) - async with _wire(monkeypatch, reply) as seen: - tokens = await _client(kind).refresh("old-refresh", scopes=scopes, deadline=130) - assert len(seen) == 1 and tokens.access_token == "new-access" - assert tokens.refresh_token == ("old-refresh" if kind == "gdrive" else "new-refresh") - assert tokens.scopes == scopes and tokens.expires_in == (None if kind == "notion" else 3600) - - -@pytest.mark.asyncio -@pytest.mark.parametrize("kind", ["notion", "linear"]) -async def test_rotating_provider_refuses_missing_or_null_replacement_refresh_without_retry( - monkeypatch: pytest.MonkeyPatch, kind: oauth.Kind -) -> None: - for present in (False, True): - response = _tokens(kind) - if present: - response["refresh_token"] = None - else: - del response["refresh_token"] - async with _wire( - monkeypatch, lambda _request, reply=response: httpx.Response(200, json=reply) - ) as seen: - with pytest.raises(oauth.OAuthError, match="^invalid_response$"): - await _client(kind).refresh( - "old-refresh", scopes=("read",) if kind == "linear" else (), deadline=130 - ) - assert len(seen) == 1 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("kind", ["gdrive", "linear"]) -async def test_exchange_refuses_expanded_scope_before_identity_lookup( - monkeypatch: pytest.MonkeyPatch, kind: oauth.Kind -) -> None: - response = _tokens(kind) - response["scope"] += " write" - async with _wire(monkeypatch, lambda _request: httpx.Response(200, json=response)) as seen: - with pytest.raises(oauth.OAuthError, match="^scope_refused$"): - await _client(kind).exchange("opaque-code", verifier=_VERIFIER, deadline=130) - assert len(seen) == 1 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("access", ["has whitespace", "nonascii-\u00e9"]) -async def test_invalid_bearer_material_is_refused_before_identity_http( - monkeypatch: pytest.MonkeyPatch, access: str -) -> None: - response = _tokens("gdrive", access_token=access) - async with _wire(monkeypatch, lambda _request: httpx.Response(200, json=response)) as seen: - with pytest.raises(oauth.OAuthError, match="^invalid_response$"): - await _client("gdrive").exchange("opaque-code", verifier=_VERIFIER, deadline=130) - assert len(seen) == 1 - - -@pytest.mark.asyncio -@pytest.mark.parametrize("kind", ["gdrive", "notion", "linear"]) -async def test_revocation_uses_documented_token_body_and_no_notion_refresh_guess( - monkeypatch: pytest.MonkeyPatch, kind: oauth.Kind -) -> None: - async with _wire(monkeypatch, lambda _request: httpx.Response(200, content=b"")) as seen: - client = _client(kind) - if kind == "notion": - with pytest.raises(oauth.OAuthError, match="^unsupported_refresh_revocation$"): - await client.revoke("refresh-private", refresh=True, deadline=130) - assert not seen - await client.revoke("revoke-private", refresh=kind != "notion", deadline=130) - (request,) = seen - assert ( - str(request.url) - == { - "gdrive": "https://oauth2.googleapis.com/revoke", - "notion": "https://api.notion.com/v1/oauth/revoke", - "linear": "https://api.linear.app/oauth/revoke", - }[kind] - ) - if kind == "notion": - assert json.loads(request.content) == {"token": "revoke-private"} - assert request.headers["authorization"].startswith("Basic ") - else: - assert _form(request) == ( - {"token": ["revoke-private"], "token_type_hint": ["refresh_token"]} - if kind == "linear" - else {"token": ["revoke-private"]} - ) - - -@pytest.mark.asyncio -async def test_provider_redirect_never_forwards_credentials_even_when_http_client_follows( - monkeypatch: pytest.MonkeyPatch, -) -> None: - def reply(request: httpx.Request) -> httpx.Response: - if request.url.host == "oauth2.googleapis.com": - return httpx.Response( - 307, headers={"Location": "https://other.example/credential-sink"} - ) - return httpx.Response(200, json=_tokens("gdrive")) - - async with _wire(monkeypatch, reply) as seen: - with pytest.raises(oauth.OAuthError, match="^provider_refused$"): - await _client("gdrive").refresh( - "refresh-private", scopes=tuple(sorted({_DRIVE, "openid", "email"})), deadline=130 - ) - assert len(seen) == 1 and seen[0].url.host == "oauth2.googleapis.com" - - -@pytest.mark.asyncio -@pytest.mark.parametrize("failure", ["http", "network"]) -async def test_provider_failures_are_redacted_and_never_retried( - monkeypatch: pytest.MonkeyPatch, failure: str -) -> None: - class ErrorBody(httpx.AsyncByteStream): - async def __aiter__(self) -> AsyncIterator[bytes]: - raise AssertionError("an error body must not be read") - yield b"" - - def reply(request: httpx.Request) -> httpx.Response: - if failure == "network": - raise httpx.ConnectError( - "access-private refresh-private https://other.example/private", request=request - ) - return httpx.Response(503, stream=ErrorBody()) - - refresh = "refresh-private" - async with _wire(monkeypatch, reply) as seen: - with pytest.raises(oauth.OAuthError) as caught: - await _client("linear").refresh(refresh, scopes=("read",), deadline=130) - assert len(seen) == 1 - assert str(caught.value) == ("provider_refused" if failure == "http" else "unavailable") - rendered = repr(caught.value) + "".join(traceback.format_exception(caught.value)) - for secret in ( - "access-private", - "refresh-private", - "client-secret", - "https://other.example/private", - ): - assert secret not in rendered - - -@pytest.mark.asyncio -async def test_stream_body_stops_at_the_metadata_cap_and_closes_the_response( - monkeypatch: pytest.MonkeyPatch, -) -> None: - class Body(httpx.AsyncByteStream): - pieces = 0 - closed = False - - async def __aiter__(self) -> AsyncIterator[bytes]: - for chunk in (b"x" * 32768, b"x" * 32768, b"x", b"tail-must-not-be-read"): - self.pieces += 1 - yield chunk - - async def aclose(self) -> None: - self.closed = True - - body = Body() - async with _wire(monkeypatch, lambda _request: httpx.Response(200, stream=body)) as seen: - with pytest.raises(oauth.OAuthError, match="^response_too_large$"): - await _client("linear").refresh("refresh-private", scopes=("read",), deadline=130) - assert len(seen) == 1 and body.pieces == 3 and body.closed - - -@pytest.mark.asyncio -async def test_expired_or_nonfinite_deadline_sends_no_http(monkeypatch: pytest.MonkeyPatch) -> None: - async with _wire(monkeypatch, lambda _request: httpx.Response(200, json={})) as seen: - for deadline in (100, float("nan"), float("inf")): - with pytest.raises(oauth.OAuthError, match="^deadline$"): - await _client("linear").refresh( - "refresh-private", scopes=("read",), deadline=deadline - ) - assert not seen - - -@pytest.mark.asyncio -async def test_body_read_cancellation_propagates_and_closes_without_retry( - monkeypatch: pytest.MonkeyPatch, -) -> None: - entered, never = asyncio.Event(), asyncio.Event() - - class Body(httpx.AsyncByteStream): - closed = False - - async def __aiter__(self) -> AsyncIterator[bytes]: - entered.set() - await never.wait() - yield b"{}" - - async def aclose(self) -> None: - self.closed = True - - body = Body() - async with _wire(monkeypatch, lambda _request: httpx.Response(200, stream=body)) as seen: - call = asyncio.create_task( - _client("linear").refresh("refresh-private", scopes=("read",), deadline=130) - ) - try: - await entered.wait() - call.cancel() - with pytest.raises(asyncio.CancelledError): - await call - finally: - call.cancel() - await asyncio.gather(call, return_exceptions=True) - assert len(seen) == 1 and body.closed - - -@pytest.mark.asyncio -async def test_operator_response_bound_limits_stream_without_reading_tail( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setattr(oauth.settings, "knowledge_connected_oauth_response_max_bytes", 1024) - - class Body(httpx.AsyncByteStream): - pieces = 0 - closed = False - - async def __aiter__(self) -> AsyncIterator[bytes]: - for chunk in (b"x" * 1024, b"x", b"unread-tail"): - self.pieces += 1 - yield chunk - - async def aclose(self) -> None: - self.closed = True - - body = Body() - async with _wire(monkeypatch, lambda _request: httpx.Response(200, stream=body)) as seen: - with pytest.raises(oauth.OAuthError, match="^response_too_large$"): - await _client("linear").refresh("refresh-private", scopes=("read",), deadline=130) - assert len(seen) == 1 - assert body.pieces == 2 and body.closed - - -@pytest.mark.asyncio -async def test_request_timeout_obeys_operator_bound_and_shorter_caller_deadline( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setattr(oauth.settings, "knowledge_connected_oauth_timeout_s", 2.5) - async with _wire( - monkeypatch, lambda _request: httpx.Response(200, json=_tokens("linear")) - ) as seen: - await _client("linear").refresh("refresh-private", scopes=("read",), deadline=130) - await _client("linear").refresh("refresh-private", scopes=("read",), deadline=101) - assert len(seen) == 2 - assert all(value == 2.5 for value in seen[0].extensions["timeout"].values()) - assert all(value == 1.0 for value in seen[1].extensions["timeout"].values()) diff --git a/tests/unit/test_connected_source_authority.py b/tests/unit/test_connected_source_authority.py index 3da772a48d..a98e4ca756 100644 --- a/tests/unit/test_connected_source_authority.py +++ b/tests/unit/test_connected_source_authority.py @@ -1,574 +1,148 @@ -"""Connected reads retain the requester, source and refresh generation across awaits.""" - -from __future__ import annotations +"""Generic account/source fences shared by publication tests.""" import asyncio -import json -import time -from collections import OrderedDict -from collections.abc import AsyncIterator from contextlib import asynccontextmanager -from dataclasses import asdict, replace -from datetime import UTC, datetime, timedelta -from typing import Any -from urllib.parse import parse_qs +from dataclasses import replace +from types import SimpleNamespace -import httpx import pytest -from server.auth.context import current_auth_var -from server.auth.jwt import AuthInfo -from server.clients import _vendor, connected_oauth -from server.clients._checked_access import CheckedAccess -from server.core import ch, grant_cache -from server.core.errors import AuthInsufficientError, ValidationError -from server.core.secrets_at_rest import seal, unseal -from server.erasure.app import ledger_reads -from server.erasure.store import census from server.knowledge.app import connected_accounts as accounts -from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE, ConnectedAccount, stopped -from server.knowledge.domain.sources import KnowledgeSource -from server.operations.base import Role, grant_rank -from tests.unit.principals import acting_as - -_ACCESS = "source-private-access" -_REFRESH = "source-private-refresh" -_ROTATED = "source-private-rotated-refresh" -_SCOPES = ( - "https://www.googleapis.com/auth/drive.readonly", - "openid", - "https://www.googleapis.com/auth/userinfo.email", -) -_KEY = ("team", "person", "gdrive") - - -def _auth(**changes: Any) -> AuthInfo: - now = int(time.time()) - return replace( - AuthInfo( - subject="person@example.com", - org="team", - namespaces=("shared-space",), - roles=(Role.WRITER,), - is_service_account=False, - session_id="primary-session", - token_id="primary-token", - first_party=True, - issued_at=now - 10, - expires_at=now + 3600, - ), - **changes, - ) +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app import sources +from server.operations.base import Role +from tests.unit.test_mcp_source_sync import harness as harness class _World: - """External account/source rows, Keeper CAS, directory/grant SQL and HTTP.""" - - def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient) -> None: + def __init__(self, monkeypatch, harness): + self.source = harness.source + self.key = (self.source.org, self.source.owner_subject, self.source.connection_slot) + self.rows = {self.key: harness.account} + self.fences = { + accounts._fence_key(harness.account.connection_id): harness.account.connection_id + } + self.locks = {} + self.holders = {} + self.writes = [] + self.grant = Role.WRITER self.account_active = True self.scim_ended = False - self.cutoffs: dict[str, int | None] = {} - self.grant: Role | None = Role.WRITER - self.locks: dict[str, asyncio.Lock] = {} - self.holders: dict[asyncio.Task[Any], int] = {} - self.fences: dict[str, str] = {} - self.rows: dict[tuple[str, str, str], ConnectedAccount] = {} - self.writes: list[ConnectedAccount] = [] - self.refresh_requests: list[httpx.Request] = [] - self.native_requests: list[httpx.Request] = [] - self.pause_refresh = False - self.refresh_entered = asyncio.Event() - self.refresh_release = asyncio.Event() - self.directory_reads = 0 - configured = { - "auth_required": True, - "identity_provider": "gateway", - "cell": "", - "jwt_secret": "connected-source-authority-test-root", - "jwt_secret_previous": "", - "public_base_url": "https://app.example/prefix", - "connect_gdrive_client_id": "document-client", - "connect_gdrive_client_secret": "document-client-secret", - "knowledge_mirrored_sources_enabled": True, - "grant_cache_ttl_seconds": 0, - } - for name, value in configured.items(): - monkeypatch.setattr(accounts.settings, name, value) - monkeypatch.setattr(ch, "get_client", lambda: self) - monkeypatch.setattr(accounts, "get_client", lambda: self) - monkeypatch.setattr(accounts.source_store, "_default_client", lambda: self) - monkeypatch.setattr(census, "_default_client", lambda: self) - monkeypatch.setattr(accounts.authz, "directory", lambda: self) - monkeypatch.setattr(accounts.aliases, "_CACHE", {}) - monkeypatch.setattr(accounts.aliases, "_GENERATION", {}) - monkeypatch.setattr(grant_cache, "_entries", OrderedDict()) - monkeypatch.setattr(grant_cache, "_loading", {}) - monkeypatch.setattr(grant_cache, "_watching", False) + self.cutoffs = {} monkeypatch.setattr(accounts.leases, "cluster_lease", self.lease) + monkeypatch.setattr(accounts, "account_lease", self.account_lease) + monkeypatch.setattr(sources, "sources_lease", self.sources_lease) monkeypatch.setattr(accounts.claims, "get", self.claim_get) monkeypatch.setattr(accounts.claims, "swap", self.claim_swap) + monkeypatch.setattr(accounts, "_fence_current", self.fence_current) monkeypatch.setattr(accounts.store, "get", self.get) monkeypatch.setattr(accounts.store, "put", self.put) - monkeypatch.setattr(accounts.store, "erase", self.erase) monkeypatch.setattr(accounts.store, "account_active", self.active) monkeypatch.setattr(accounts.source_store, "get_source", self.get_source) monkeypatch.setattr(accounts.source_store, "latest_source", self.get_source) monkeypatch.setattr(accounts.source_store, "connected_sources", self.connected_sources) - monkeypatch.setattr(accounts.scim, "deactivated", self.deactivated) monkeypatch.setattr(accounts.revocation, "cutoffs", self.revoked) - monkeypatch.setattr(ledger_reads.ledger, "open_namespace_erasures", self.erasures) - monkeypatch.setattr(connected_oauth, "get_client", lambda: http) - account = ConnectedAccount( - *_KEY, - "a" * 32 + "/1" + "b" * 31, - account_id="provider-person", - credential_enc=seal(CREDENTIAL_PURPOSE, _REFRESH), - scopes=_SCOPES, - active=True, - connected_at=datetime.now(UTC) - timedelta(minutes=1), - ) - self.rows[_KEY] = account - self.fences[accounts._fence_key(account.connection_id)] = account.connection_id - self.source: KnowledgeSource | None = KnowledgeSource( - "team", - "shared-space", - "documents", - "gdrive", - "source-id", - config={"include": ["file"]}, - items=[{"id": "file", "kind": "file"}], - access="mirrored", - credential_mode="connected", - owner_subject="person", - connection_id=account.connection_id, - created_by="audit-attribution-is-not-authority", - ) - - async def query_all(self, query: str, params: dict[str, Any], **_kw: Any): - assert "FROM loom.namespaces" in query and params["org"] == "team" - self.directory_reads += 1 - return [ - { - "namespace": "personal-person", - "owner_email": "person", - "contact_email": "person@example.com", - "password_hash": "verified-password-hash", - "hosted_domain": "", - "issuer": "", - } - ] - - async def query_one(self, query: str, params: dict[str, Any], **_kw: Any): - assert params["org"] == "team" - if "AS grants" in query: - assert params["sub"] in ("person", "person@example.com") - rank = grant_rank(self.grant.name.lower()) if self.grant else 0 - return { - "grants": [("shared-space", rank)], - "spellings": ["person", "person@example.com"], - "held": ["person", "person@example.com"], - } - if "SELECT role FROM loom.namespace_grants" in query: - assert params["ns"] == "shared-space" and "person" in params["subs"] - return {"role": self.grant.name.lower()} if self.grant else None - if "owner_email = namespace AS claimed" in query: - assert params["ns"] == "shared-space" - return {"active": True, "claimed": False} - assert "SELECT count() AS n FROM loom.connected_accounts WHERE" in query - assert "FINAL" not in query - row = self.rows.get((params["org"], params["subject"], params["kind"])) - return { - "n": int( - row is not None - and not ( - row.connection_id == params.get("keep") - and not row.active - and not row.account_id - and not row.workspace_id - and not row.account_email_enc - and not row.credential_enc - and not row.scopes - and not row.refresh_id - and row.connected_at is None - ) - ) - } - - async def is_restricted(self, org: str, namespace: str) -> bool: - assert (org, namespace) == ("team", "shared-space") - return False - - def code_entry(self, _org: str, _namespace: str) -> None: - return None - - async def active(self, org: str, spellings: list[str]) -> bool: - assert org == "team" and "person" in spellings - return self.account_active - - async def deactivated(self, email: str) -> bool: - assert email == "person@example.com" - return self.scim_ended - - async def revoked(self, subjects: list[str]) -> dict[str, int | None]: - return {key: self.cutoffs[key] for key in subjects if key in self.cutoffs} - - async def erasures(self, org: str, **_kw: Any) -> list[dict[str, Any]]: - assert org == "team" - return [] + monkeypatch.setattr(accounts.scim, "refuses_subject", self.deactivated) + monkeypatch.setattr(authority.authz, "grant_role_for", self.role) @asynccontextmanager - async def lease(self, key: str, **_kw: Any) -> AsyncIterator[None]: + async def lease(self, key, **kwargs): async with self.locks.setdefault(key, asyncio.Lock()): task = asyncio.current_task() - assert task is not None self.holders[task] = self.holders.get(task, 0) + 1 try: - yield + yield SimpleNamespace(held=True) finally: self.holders[task] -= 1 - async def claim_get(self, _ch: Any, key: str) -> str | None: + @asynccontextmanager + async def account_lease(self, org, owner, slot): + assert (org, owner, slot) == self.key + async with self.lease("connected-account:" + slot): + yield + + @asynccontextmanager + async def sources_lease(self, org, namespace, **kwargs): + assert (org, namespace) == ("org", "collection") + async with self.lease("knowledge-source:org:collection"): + yield + + async def claim_get(self, ch, key): return self.fences.get(key) - async def claim_swap( - self, _ch: Any, key: str, previous: str | None, value: str, _expires: int - ) -> str | None: + async def claim_swap(self, ch, key, previous, value, expires): current = self.fences.get(key) if current == previous: self.fences[key] = value return value return current - async def get(self, org: str, subject: str, kind: str, **_kw: Any): - return self.rows.get((org, subject, kind)) + async def fence_current(self, account, **kwargs): + return self.fences.get(accounts._fence_key(account.connection_id)) == account.connection_id + + async def get(self, org, owner, slot, **kwargs): + return self.rows.get((org, owner, slot)) - async def put(self, row: ConnectedAccount, **_kw: Any) -> None: + async def put(self, row, **kwargs): assert self.holders.get(asyncio.current_task(), 0) self.rows[row.org, row.subject, row.kind] = row self.writes.append(row) - async def erase(self, org: str, subjects: list[str], *, kind: str, **_kw: Any) -> None: - for key in list(self.rows): - if key[0] == org and key[1] in subjects and key[2] == kind: - del self.rows[key] - - async def get_source(self, org: str, namespace: str, name: str, **_kw: Any): - assert (org, namespace, name) == ("team", "shared-space", "documents") + async def get_source(self, org, namespace, name, **kwargs): + assert (org, namespace, name) == ("org", "collection", "selected") return self.source - async def connected_sources(self, org: str, subject: str, **_kw: Any): - assert (org, subject) == ("team", "person") + async def connected_sources(self, org, owner, **kwargs): + assert (org, owner) == ("org", "owner") return [self.source] if self.source is not None else [] - async def handle(self, request: httpx.Request) -> httpx.Response: - assert not self.holders.get(asyncio.current_task(), 0) - if str(request.url) == "https://oauth2.googleapis.com/token": - self.refresh_requests.append(request) - form = parse_qs(request.content.decode()) - assert form["grant_type"] == ["refresh_token"] - assert form["refresh_token"] == [_REFRESH] - assert self.rows[_KEY].refresh_id - self.refresh_entered.set() - if self.pause_refresh: - await self.refresh_release.wait() - return httpx.Response( - 200, - json={ - "access_token": _ACCESS, - "refresh_token": _ROTATED, - "token_type": "Bearer", - "expires_in": 3600, - "scope": " ".join(_SCOPES), - }, - ) - assert str(request.url) == "https://www.googleapis.com/drive/v3/files/file" - assert request.method == "GET" and request.headers["Authorization"] == "Bearer " + _ACCESS - self.native_requests.append(request) - return httpx.Response(200, json={"id": "file"}) - - async def entered_or_finished(self, work: asyncio.Task[Any]) -> None: - entered = asyncio.create_task(self.refresh_entered.wait()) - try: - done, _ = await asyncio.wait({work, entered}, return_when=asyncio.FIRST_COMPLETED) - if work in done: - await work - pytest.fail("the refresh did not remain reserved") - finally: - if not entered.done(): - entered.cancel() - await asyncio.gather(entered, return_exceptions=True) - - -@pytest.fixture -async def world(monkeypatch: pytest.MonkeyPatch): - async def handle(request: httpx.Request) -> httpx.Response: - return await state.handle(request) - - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http: - state = _World(monkeypatch, http) - yield state, http - - -async def _resolve() -> accounts.SourceAuthority: - return await accounts.resolve( - "team", "shared-space", "documents", deadline=time.monotonic() + 60 - ) - - -async def test_canonical_owner_reads_through_a_checked_native_checkout(world) -> None: - state, http = world - with acting_as(_auth()): - authority = await _resolve() - assert authority.requester == "person" and authority.source.owner_subject == "person" - - async def read(access: CheckedAccess): - assert isinstance(access, CheckedAccess) - with pytest.raises(TypeError): - str(access) - return await _vendor.bearer_get( - http, "https://www.googleapis.com/drive/v3/files/file", access, "metadata" - ) - - assert await authority.run(read) == {"id": "file"} - assert len(state.refresh_requests) == len(state.native_requests) == 1 - assert state.directory_reads > 0 and len(state.writes) == 2 - assert state.writes[0].refresh_id and not state.writes[1].refresh_id - assert unseal(CREDENTIAL_PURPOSE, state.rows[_KEY].credential_enc) == _ROTATED - assert _ACCESS not in json.dumps([asdict(row) for row in state.writes], default=str) - assert _ACCESS not in repr(authority) and _ROTATED not in repr(authority) - + async def active(self, *args, **kwargs): + return self.account_active -@pytest.mark.parametrize("refusal", ("source-id", "owner", "org")) -async def test_resolution_refuses_a_different_source_owner_or_tenant_before_refresh( - world, refusal: str -) -> None: - state, _http = world - assert state.source is not None - if refusal == "owner": - state.source = replace(state.source, owner_subject="another-person", created_by="person") - with acting_as(_auth()): - with pytest.raises(ValidationError, match="^the connected account is unavailable$"): - await accounts.resolve( - "other-team" if refusal == "org" else "team", - "shared-space", - "documents", - deadline=time.monotonic() + 60, - expected_source_id="replacement-id" if refusal == "source-id" else "", - ) - assert state.refresh_requests == [] and state.writes == [] + async def deactivated(self, *args, **kwargs): + return self.scim_ended + async def revoked(self, spellings): + assert spellings == ["owner"] + return self.cutoffs -@pytest.mark.parametrize("principal", ("service", "delegated")) -async def test_service_or_creator_attribution_cannot_select_the_persons_account( - world, principal: str -) -> None: - state, _http = world - auth = ( - _auth(is_service_account=True) - if principal == "service" - else _auth(reads_as_creator=True, creator="person") - ) - with acting_as(auth), pytest.raises(AuthInsufficientError): - await _resolve() - assert state.refresh_requests == [] and state.writes == [] + async def role(self, *args, **kwargs): + return self.grant -async def test_source_metadata_and_keeper_fence_are_required_before_refresh(world) -> None: - state, _http = world - source = state.source - assert source is not None - changes = ( - {"access": "namespace"}, - {"credential_mode": "shared"}, - {"active": False}, - {"items": [{"id": "different-file"}]}, - {"config": {"include": ["different-file"]}}, +@pytest.fixture +def world(monkeypatch, harness): + return _World(monkeypatch, harness) + + +@pytest.mark.asyncio +async def test_generic_source_requires_its_exact_account_slot_and_generation(world): + bound = await authority.validate_source(world.source) + assert bound.source is world.source + assert bound.connection.account == world.rows[world.key] + current = world.rows[world.key] + world.rows[world.key] = replace( + current, connection_id=accounts._next_connection(current.connection_id) ) - with acting_as(_auth()): - for change in changes: - state.source = replace(source, **change) - with pytest.raises(ValidationError): - await accounts.token_for(source, deadline=time.monotonic() + 60) - state.source = source - state.fences.clear() - with pytest.raises(ValidationError): - await accounts.token_for(source, deadline=time.monotonic() + 60) - assert state.refresh_requests == [] and state.writes == [] - - -async def test_owner_account_scim_and_outright_revocation_are_live_before_refresh(world) -> None: - state, _http = world - with acting_as(_auth()): - state.account_active = False - with pytest.raises(ValidationError): - await _resolve() - state.account_active = True - state.scim_ended = True - with pytest.raises(ValidationError): - await _resolve() - state.scim_ended = False - state.cutoffs["person"] = None - with pytest.raises(ValidationError): - await _resolve() - assert state.refresh_requests == [] and state.writes == [] - - -@pytest.mark.parametrize("change", ("writer-grant", "scim", "auth-object", "source-config")) -async def test_authority_withholds_a_read_when_its_post_call_standing_changes( - world, change: str -) -> None: - state, http = world - auth = _auth() - with acting_as(auth): - authority = await _resolve() - - async def read(access: CheckedAccess): - answer = await _vendor.bearer_get( - http, "https://www.googleapis.com/drive/v3/files/file", access, "metadata" - ) - if change == "writer-grant": - state.grant = Role.VIEWER - elif change == "scim": - state.scim_ended = True - elif change == "auth-object": - current_auth_var.set(replace(auth)) - else: - assert state.source is not None - state.source = replace(state.source, config={"include": ["different-file"]}) - return answer - - with pytest.raises(ValidationError): - await authority.run(read) - assert len(state.native_requests) == len(state.refresh_requests) == 1 - - -async def test_an_outstanding_rotation_refuses_a_second_presenter(world) -> None: - state, _http = world - state.pause_refresh = True - source = state.source - assert source is not None - with acting_as(_auth()): - work = asyncio.create_task(accounts.token_for(source, deadline=time.monotonic() + 60)) - try: - await state.entered_or_finished(work) - assert state.rows[_KEY].refresh_id - with pytest.raises(ValidationError): - await accounts.token_for(source, deadline=time.monotonic() + 60) - assert len(state.refresh_requests) == 1 - state.refresh_release.set() - tokens, _account = await work - assert tokens.access_token == _ACCESS - finally: - if not work.done(): - state.source = None - work.cancel() - await asyncio.gather(work, return_exceptions=True) - assert not state.rows[_KEY].refresh_id - - -@pytest.mark.parametrize("replacement", (False, True), ids=("disconnected", "replaced")) -async def test_a_late_rotation_cannot_restore_an_ended_or_replaced_generation( - world, replacement: bool -) -> None: - state, _http = world - state.pause_refresh = True - source = state.source - assert source is not None - with acting_as(_auth()): - work = asyncio.create_task(accounts.token_for(source, deadline=time.monotonic() + 60)) - try: - await state.entered_or_finished(work) - old = state.rows[_KEY] - generation = accounts._next_connection(old.connection_id, inactive=not replacement) - ended = ( - replace( - old, - connection_id=generation, - refresh_id="", - credential_enc=seal(CREDENTIAL_PURPOSE, "replacement-refresh"), - ) - if replacement - else stopped(old, connection_id=generation, at=datetime.now(UTC)) - ) - state.rows[_KEY] = ended - state.fences[accounts._fence_key(generation)] = generation - state.source = replace(source, active=False) - state.refresh_release.set() - with pytest.raises(ValidationError): - await work - assert state.rows[_KEY] == ended - assert state.fences[accounts._fence_key(generation)] == generation - finally: - if not work.done(): - state.source = None - work.cancel() - await asyncio.gather(work, return_exceptions=True) - assert len(state.refresh_requests) == 1 - - -async def test_a_changed_rotation_reservation_cannot_be_committed_or_cleared(world) -> None: - state, _http = world - state.pause_refresh = True - source = state.source - assert source is not None - with acting_as(_auth()): - work = asyncio.create_task(accounts.token_for(source, deadline=time.monotonic() + 60)) - try: - await state.entered_or_finished(work) - other = replace(state.rows[_KEY], refresh_id="another-reservation") - state.rows[_KEY] = other - state.refresh_release.set() - with pytest.raises(ValidationError): - await work - assert state.rows[_KEY] == other - assert unseal(CREDENTIAL_PURPOSE, other.credential_enc) == _REFRESH - finally: - if not work.done(): - state.source = None - work.cancel() - await asyncio.gather(work, return_exceptions=True) - - -async def test_draft_probe_needs_its_current_owner_and_writer_grant_without_a_source_row( - world, -) -> None: - state, _http = world - draft = state.source - assert draft is not None - state.source = None - with acting_as(_auth()): - access = await accounts.checked_for(draft, deadline=time.monotonic() + 60, pending=True) - await access.check() - state.grant = Role.VIEWER - with pytest.raises(ValidationError): - await access.check() - assert len(state.refresh_requests) == 1 and state.native_requests == [] - - -async def test_source_deleted_during_rotation_withholds_delivery_and_keeps_owner_rotation( - world, -) -> None: - state, _http = world - state.pause_refresh = True - source = state.source - assert source is not None - with acting_as(_auth()): - work = asyncio.create_task(accounts.token_for(source, deadline=time.monotonic() + 60)) - try: - await state.entered_or_finished(work) - state.source = None - state.refresh_release.set() - with pytest.raises(ValidationError): - await work - finally: - if not work.done(): - state.source = None - work.cancel() - await asyncio.gather(work, return_exceptions=True) - retained = state.rows[_KEY] - assert state.source is None and state.native_requests == [] - assert retained.active and not retained.refresh_id - assert retained.connection_id == source.connection_id - assert state.fences[accounts._fence_key(retained.connection_id)] == retained.connection_id - assert unseal(CREDENTIAL_PURPOSE, retained.credential_enc) == _ROTATED - assert retained.connected_at is not None and len(state.refresh_requests) == 1 + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_source(world.source) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("change", ["fence", "owner", "scim", "grant", "cutoff"]) +async def test_generic_owner_standing_refuses_without_executing_credentials(world, change): + await authority.validate_source(world.source) + if change == "fence": + world.fences.clear() + elif change == "owner": + world.account_active = False + elif change == "scim": + world.scim_ended = True + elif change == "grant": + world.grant = Role.VIEWER + else: + account = world.rows[world.key] + world.cutoffs = {"owner": int(account.connected_at.timestamp()) + 1} + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_source(world.source) + assert world.writes == [] diff --git a/tests/unit/test_connected_source_drive_linear_workers.py b/tests/unit/test_connected_source_drive_linear_workers.py deleted file mode 100644 index 07e757ff3e..0000000000 --- a/tests/unit/test_connected_source_drive_linear_workers.py +++ /dev/null @@ -1,343 +0,0 @@ -"""Connected native turns retain checked provider ACLs through guarded publication.""" - -from __future__ import annotations - -import asyncio -import json -from dataclasses import replace -from typing import Literal -from urllib.parse import parse_qs - -import httpx -import pytest - -from server.clients import gdrive, linear -from server.knowledge.app import connected_accounts as accounts -from server.knowledge.domain.access_list import AccessList, from_json -from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, mirror_uri -from server.knowledge.store import documents -from server.knowledge.store import sources as source_store -from tests.unit.test_connected_source_authority import _REFRESH as _INITIAL_REFRESH -from tests.unit.test_connected_source_authority import _SCOPES as _DRIVE_SCOPES -from tests.unit.test_connected_source_publication import _MIRROR -from tests.unit.test_connected_source_workers import _turn -from tests.unit.test_connected_source_workers import _World as _NotionWorld - -_PROJECT = "11111111-1111-4111-8111-111111111111" -_TEAM = "22222222-2222-4222-8222-222222222222" -_DOCUMENT = "33333333-3333-4333-8333-333333333333" -_DRIVE_FILE = "connected-native-document" -_TEXT = "The connected worker keeps the provider's current permission list." -_ACCESS = "drive-linear-worker-access" -_REPLACEMENT = "drive-linear-worker-refresh" -_REVISION = "2026-01-01T00:00:00.000Z" -_KINDS = ("gdrive", "linear") - - -class _World(_NotionWorld): - """Reuse real authority/publication code, replacing only external I/O.""" - - def __init__( - self, - monkeypatch: pytest.MonkeyPatch, - http: httpx.AsyncClient, - kind: Literal["gdrive", "linear"], - ) -> None: - super().__init__(monkeypatch, http) - assert self.source is not None - self.kind = kind - self.address = ( - "https://docs.google.com/document/d/connected-native-document/edit" - if kind == "gdrive" - else "https://linear.app/example/document/connected-native-document" - ) - previous = self.rows.pop(self.key) - account = replace( - previous, - kind=kind, - scopes=_DRIVE_SCOPES if kind == "gdrive" else ("read",), - ) - self.key = account.org, account.subject, kind - self.rows[self.key] = account - self.source = replace( - self.source, - kind=kind, - config={"include": ["docs"]} if kind == "gdrive" else {"project_ids": [_PROJECT]}, - items=[{"type": "file", "id": _DRIVE_FILE}] - if kind == "gdrive" - else [{"type": "project", "id": _PROJECT}], - ) - self.selected_source = self.source - self.request = self.request.model_copy( - update={"source_uri": mirror_uri(self.address, self.source.source_id)} - ) - self.graphql: list[str] = [] - self.permission_pages: list[str] = [] - monkeypatch.setattr(accounts.settings, f"connect_{kind}_client_id", "worker-client") - monkeypatch.setattr(accounts.settings, f"connect_{kind}_client_secret", "worker-secret") - monkeypatch.setattr(gdrive, "get_client", lambda: http) - monkeypatch.setattr(linear, "get_client", lambda: http) - monkeypatch.setattr(source_store, "every_copy", self.every_copy) - monkeypatch.setattr(documents, "committed_lists", self.committed_lists) - - async def every_copy(self, org: str, namespace: str, tag: str): - assert (org, namespace, tag) == ("team", _MIRROR, "source-id:source-id") - return [] - - async def committed_lists(self, org: str, namespace: str, uris: list[str]): - assert (org, namespace, uris) == ("team", _MIRROR, []) - return {} - - async def handle(self, request: httpx.Request) -> httpx.Response: - assert not self.holders.get(asyncio.current_task(), 0) - token_url = ( - "https://oauth2.googleapis.com/token" - if self.kind == "gdrive" - else "https://api.linear.app/oauth/token" - ) - if str(request.url) == token_url: - assert request.method == "POST" - assert parse_qs(request.content.decode()) == { - "grant_type": ["refresh_token"], - "refresh_token": [_INITIAL_REFRESH], - "client_id": ["worker-client"], - "client_secret": ["worker-secret"], - } - assert self.rows[self.key].refresh_id - self.refresh_requests.append(request) - return httpx.Response( - 200, - json={ - "access_token": _ACCESS, - "refresh_token": _REPLACEMENT, - "token_type": "Bearer", - "expires_in": 3600, - "scope": " ".join(_DRIVE_SCOPES) if self.kind == "gdrive" else "read", - }, - ) - assert request.headers["authorization"] == "Bearer " + _ACCESS - self.native_requests.append(request) - return self.drive(request) if self.kind == "gdrive" else self.tracker(request) - - def drive(self, request: httpx.Request) -> httpx.Response: - assert request.url.scheme == "https" and request.url.host == "www.googleapis.com" - assert request.method == "GET" - path = f"/drive/v3/files/{_DRIVE_FILE}" - if request.url.path == path: - assert request.url.params["fields"] == f"{gdrive.LISTED_WITH_PERMISSIONS},trashed" - assert request.url.params["supportsAllDrives"] == "true" - # No inline share list: the actual client must fetch every permission page. - return httpx.Response( - 200, - json={ - "id": _DRIVE_FILE, - "name": "Connected native document", - "mimeType": "application/vnd.google-apps.document", - "modifiedTime": _REVISION, - "webViewLink": self.address, - "trashed": False, - }, - ) - if request.url.path == path + "/permissions": - assert request.url.params["supportsAllDrives"] == "true" - assert request.url.params["pageSize"] == "100" - page = request.url.params.get("pageToken", "") - self.permission_pages.append(page) - if not page: - return httpx.Response( - 200, - json={ - "permissions": [ - { - "type": "user", - "role": "reader", - "emailAddress": "Reader@EXAMPLE.COM", - }, - { - "type": "user", - "role": "reader", - "emailAddress": "deleted@example.com", - "deleted": True, - }, - ], - "nextPageToken": "second-permission-page", - }, - ) - assert page == "second-permission-page" - return httpx.Response( - 200, - json={ - "permissions": [ - {"type": "anyone", "role": "reader", "allowFileDiscovery": False}, - { - "type": "domain", - "role": "reader", - "domain": "link-only.example", - "allowFileDiscovery": False, - }, - { - "type": "domain", - "role": "reader", - "domain": "WORKSPACE.EXAMPLE", - "allowFileDiscovery": True, - }, - ] - }, - ) - assert request.url.path == path + "/export" - assert request.url.params["mimeType"] == "text/markdown" - return httpx.Response(200, text=_TEXT, headers={"Content-Type": "text/markdown"}) - - def tracker(self, request: httpx.Request) -> httpx.Response: - assert str(request.url) == "https://api.linear.app/graphql" - assert request.method == "POST" - body = json.loads(request.content) - operation = body["query"].split("query ", 1)[1].split("(", 1)[0] - self.graphql.append(operation) - variables = body["variables"] - page = {"hasNextPage": False, "endCursor": None} - if operation == "ProjectTeams": - assert variables == {"id": _PROJECT, "first": linear.PAGE_SIZE, "after": None} - data = {"project": {"teams": {"nodes": [{"id": _TEAM}], "pageInfo": page}}} - elif operation == "TeamMembers": - assert "includeDisabled: true" in body["query"] - assert variables == {"id": _TEAM, "first": linear.PAGE_SIZE, "after": None} - nodes = [ - { - "id": "44444444-4444-4444-8444-444444444444", - "email": "Reader@EXAMPLE.COM", - "active": True, - }, - { - "id": "55555555-5555-4555-8555-555555555555", - "email": "disabled@example.com", - "active": False, - }, - {"id": "66666666-6666-4666-8666-666666666666", "email": "unknown@example.com"}, - ] - data = {"team": {"members": {"nodes": nodes, "pageInfo": page}}} - elif operation == "ProjectDocuments": - assert variables == {"id": _PROJECT, "first": linear.PAGE_SIZE} - node = { - "id": _DOCUMENT, - "title": "Connected native document", - "updatedAt": _REVISION, - "url": self.address, - } - data = {"project": {"id": _PROJECT, "documents": {"nodes": [node], "pageInfo": page}}} - else: - assert operation == "Document" and variables == {"id": _DOCUMENT} - data = { - "document": { - "id": _DOCUMENT, - "content": _TEXT, - "updatedAt": _REVISION, - "url": self.address, - } - } - return httpx.Response(200, json={"data": data}) - - -@pytest.fixture -async def world(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest): - async def provider(message: httpx.Request) -> httpx.Response: - return await state.handle(message) - - async with httpx.AsyncClient(transport=httpx.MockTransport(provider)) as http: - state = _World(monkeypatch, http, request.param) - yield state - - -def _expected_acl(world: _World) -> AccessList: - return AccessList( - owner="person", - emails=("reader@example.com",), - domains=("workspace.example",) if world.kind == "gdrive" else (), - ) - - -def _assert_native_reads(world: _World) -> None: - assert len(world.refresh_requests) == 1 - if world.kind == "gdrive": - assert world.permission_pages == ["", "second-permission-page"] - assert [request.url.path for request in world.native_requests] == [ - f"/drive/v3/files/{_DRIVE_FILE}", - f"/drive/v3/files/{_DRIVE_FILE}/permissions", - f"/drive/v3/files/{_DRIVE_FILE}/permissions", - f"/drive/v3/files/{_DRIVE_FILE}/export", - ] - else: - assert world.graphql == ["ProjectTeams", "TeamMembers", "ProjectDocuments", "Document"] - - -@pytest.mark.parametrize("world", _KINDS, indirect=True) -async def test_connected_native_provider_content_keeps_checked_acl_and_listing(world) -> None: - result = await _turn(world) - assert (result.status, result.complete, result.full, result.changed, result.documents_seen) == ( - "ok", - True, - True, - 1, - 1, - ) - assert result.mirror == _MIRROR and result.unconverted == result.skipped == 0 - _assert_native_reads(world) - assert len(world.document_writes) == len(world.chunk_writes) == len(world.listings) == 1 - row, chunk = world.document_writes[0], world.chunk_writes[0] - assert row["content"].strip() == chunk["content"] == _TEXT - assert row["actor"] == SYNC_WORKER_ACTOR - assert from_json(row["access_json"]) == _expected_acl(world) - assert row["version"] == chunk["doc_version"] and row["revision"] == 1 - for stored in (row, chunk): - assert (stored["org"], stored["namespace"], stored["source_uri"]) == ( - "team", - _MIRROR, - world.request.source_uri, - ) - assert stored["tags"] == [ - "source-kind:design_doc", - "source:documents", - "source-id:source-id", - ] - assert ( - stored["agent"], - stored["user_id"], - stored["session_id"], - stored["source_class"], - ) == ("-", "-", "-", "imported") - metadata = json.loads(row["metadata"]) - assert metadata["source_kind"] == world.kind - assert metadata["ingested_from"] == (_DRIVE_FILE if world.kind == "gdrive" else _DOCUMENT) - assert metadata["source_revision"] == _REVISION and metadata["ingested_format"] == "markdown" - assert json.loads(chunk["doc_metadata"]) == metadata - assert chunk["embedding"] == [1.0, 0.0, 0.0, 0.0] - assert chunk["embedding_model"] == world.model_name and chunk["embedding_dim"] == 4 - assert world.debt_checks == (2 if world.kind == "gdrive" else 1) - assert world.events.index("head-end") < world.events.index("listing") - assert world.listings[0]["namespace"] == _MIRROR - assert world.listings[0]["source_id"] == "source-id" - assert world.blob_writes == world.chunk_retirements == [] - - -@pytest.mark.parametrize("world", _KINDS, indirect=True) -async def test_connected_native_provider_generation_loss_during_embedding_cannot_publish( - world, -) -> None: - world.pause_embedding = True - work = asyncio.create_task(_turn(world)) - try: - await world.await_stage(world.embedding_entered, work) - _assert_native_reads(world) - assert world.chunk_writes == world.document_writes == world.listings == [] - async with accounts.account_lease(*world.key): - world.end_generation() - world.embedding_release.set() - with pytest.raises(accounts.OwnerUnavailable): - await work - assert world.chunk_writes == world.document_writes == world.listings == [] - assert len(world.chunk_retirements) == 1 - assert world.chunk_retirements[0][0][0] == world.request.source_uri - finally: - if not work.done(): - work.cancel() - await asyncio.gather(work, return_exceptions=True) diff --git a/tests/unit/test_connected_source_operations.py b/tests/unit/test_connected_source_operations.py index 5ce1aa701d..f4d514b56d 100644 --- a/tests/unit/test_connected_source_operations.py +++ b/tests/unit/test_connected_source_operations.py @@ -1,407 +1,130 @@ -"""Connected source controls keep the real caller, native checks and mirror privacy.""" - -from __future__ import annotations +"""Local controls retain legacy ownership without executing retired connectors.""" import asyncio import json -import time -from collections.abc import AsyncIterator -from contextlib import asynccontextmanager from dataclasses import replace -from typing import Any +from types import SimpleNamespace -import httpx import pytest -from server.auth.context import current_auth -from server.clients import gdrive -from server.clients._checked_access import CheckedAccess from server.core import request_work from server.core.errors import ValidationError -from server.core.secrets_at_rest import unseal from server.knowledge.api.models_sources import ( - KnowledgeSourceCheckInput, KnowledgeSourceRemoveInput, KnowledgeSourceSyncNowInput, - KnowledgeSourceUpdateInput, ) from server.knowledge.app import connected_accounts as accounts from server.knowledge.app import sources -from server.knowledge.domain.connected_accounts import CREDENTIAL_PURPOSE -from server.knowledge.domain.sources import KnowledgeSource -from server.knowledge.store import mirrors, source_push, source_retirements -from server.operations.base import Role, grant_rank -from tests.unit.principals import acting_as -from tests.unit.test_connected_source_authority import ( - _ACCESS, - _KEY, - _ROTATED, - _auth, -) -from tests.unit.test_connected_source_authority import ( - _World as _AuthorityWorld, -) - -_SOURCE_ID = "11111111-2222-4333-8444-555555555555" -_FILE = "owned-file-0001" -_ADDED = "added-file-0002" -_TITLE = "private provider title canary" -_MIRROR = "acl-" + "a" * 24 -_SCOPE = {"org": "team", "namespace": "shared-space", "name": "documents"} - - -class _World(_AuthorityWorld): - """External rows/lease store and HTTP; source and account decisions stay real.""" - - def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient) -> None: - super().__init__(monkeypatch, http) - assert self.source is not None - self.source = replace( - self.source, - source_id=_SOURCE_ID, - config={"include": ["pdf"]}, - items=[{"type": "file", "id": _FILE}], - mirror=_MIRROR, - ) - self.roles = {"person": Role.WRITER, "operator": Role.ADMIN} - self.source_writes: list[KnowledgeSource] = [] - self.state_writes: list[dict[str, Any]] = [] - self.retirement_rows: list[dict[str, Any]] = [] - self.native_callers: list[str] = [] - self.pause_native = False - self.native_entered = asyncio.Event() - self.native_release = asyncio.Event() - monkeypatch.setattr(accounts.leases, "holding", self.holding) - monkeypatch.setattr(sources.store, "insert_source", self.insert_source) - monkeypatch.setattr(sources.store, "read_states", self.read_states) - monkeypatch.setattr(sources.store, "write_state", self.write_state) - monkeypatch.setattr(sources.store, "count_documents", self.no_document_count) - monkeypatch.setattr(mirrors, "_default_client", lambda: self) - monkeypatch.setattr(source_retirements, "_default_client", lambda: self) - monkeypatch.setattr(source_push, "get", self.no_push) - monkeypatch.setattr(gdrive, "get_client", lambda: http) - - @staticmethod - def row_owner(subject: str) -> str: - return { - "person": "person", - "person@example.com": "person", - "operator": "operator", - "operator@example.com": "operator", - }[subject.lower()] - - async def query_all(self, query: str, params: dict[str, Any], **_kw: Any): - if "argMax(schema_version" in query: - assert params["all_deployments"] is True - return [{"schema_version": 111}] - assert params["org"] == "team" - if "FROM loom.knowledge_mirrors" in query: - assert params["namespaces"] == ["shared-space"] - return [{"mirror": _MIRROR, "namespace": "shared-space"}] - assert "FROM loom.namespaces" in query - self.directory_reads += 1 - subject = self.row_owner(params["sub"]) - assert subject in self.roles - return [ - { - "namespace": "personal-" + subject, - "owner_email": subject, - "contact_email": subject + "@example.com", - "password_hash": "verified-password-hash", - "hosted_domain": "", - "issuer": "", - } - ] - - async def query_one(self, query: str, params: dict[str, Any], **kw: Any): - if "AS grants" in query: - subject = self.row_owner(params["sub"]) - role = self.roles[subject] - spellings = [subject, subject + "@example.com"] - return { - "grants": [("shared-space", grant_rank(role.name.lower()))], - "spellings": spellings, - "held": spellings, - } - if "SELECT role FROM loom.namespace_grants" in query: - assert params["org"] == "team" and params["ns"] == "shared-space" - role = max(self.roles[self.row_owner(subject)] for subject in params["subs"]) - return {"role": role.name.lower()} - return await super().query_one(query, params, **kw) - - async def active(self, org: str, spellings: list[str]) -> bool: - assert org == "team" and all(self.row_owner(s) in self.roles for s in spellings) - return self.account_active - - async def deactivated(self, email: str) -> bool: - assert self.row_owner(email) in self.roles - return self.scim_ended - - @asynccontextmanager - async def holding(self, key: str, **kw: Any) -> AsyncIterator[bool]: - async with self.lease(key, **kw): - yield True - - async def insert_source(self, source: KnowledgeSource, **_kw: Any) -> None: - assert self.holders.get(asyncio.current_task(), 0) - self.source_writes.append(source) - self.source = source - - async def read_states(self, org: str, namespace: str, names: list[str], **_kw: Any): - assert (org, namespace, names) == ("team", "shared-space", ["documents"]) - return {} - - async def write_state(self, org: str, namespace: str, name: str, **kw: Any) -> None: - assert (org, namespace, name) == ("team", "shared-space", "documents") - assert self.holders.get(asyncio.current_task(), 0) - self.state_writes.append(kw) - - async def no_document_count(self, *_args: Any, **_kw: Any) -> int: - raise AssertionError("a mirrored control must not count provider documents") - - async def no_push(self, org: str, namespace: str, source_id: str, **_kw: Any): - assert (org, namespace, source_id) == ("team", "shared-space", _SOURCE_ID) - return None - - async def insert(self, table: str, rows: list[dict[str, Any]], **_kw: Any) -> None: - assert table == "loom.code_index_state" - assert self.holders.get(asyncio.current_task(), 0) - self.retirement_rows.extend(dict(row) for row in rows) - - async def handle(self, request: httpx.Request) -> httpx.Response: - if request.url.host == "oauth2.googleapis.com": - return await super().handle(request) - assert not self.holders.get(asyncio.current_task(), 0) - assert request.url.host == "www.googleapis.com" and request.method == "GET" - assert request.url.path in ("/drive/v3/files/" + _FILE, "/drive/v3/files/" + _ADDED) - assert request.headers["Authorization"] == "Bearer " + _ACCESS - auth = current_auth() - assert auth is not None - self.native_callers.append(auth.subject) - self.native_requests.append(request) - self.native_entered.set() - if self.pause_native: - await self.native_release.wait() - return httpx.Response( - 200, - json={ - "id": request.url.path.rsplit("/", 1)[1], - "name": _TITLE, - "mimeType": "application/pdf", - "trashed": False, - "modifiedTime": "2020-01-01T00:00:00Z", - }, - ) - - async def await_stage(self, event: asyncio.Event, work: asyncio.Task[Any]) -> None: - entered = asyncio.create_task(event.wait()) - try: - done, _ = await asyncio.wait({entered, work}, return_when=asyncio.FIRST_COMPLETED) - if work in done: - await work - pytest.fail("the operation completed before its external I/O boundary") - finally: - if not entered.done(): - entered.cancel() - await asyncio.gather(entered, return_exceptions=True) +from server.knowledge.domain.sources import MIRRORED_ACCESS +from server.operations.base import Role +from tests.unit.principals import acting_as, principal +from tests.unit.test_knowledge_sources import NS, ORG, _add +from tests.unit.test_knowledge_sources import fake as fake @pytest.fixture -async def world(monkeypatch: pytest.MonkeyPatch): - async def handle(request: httpx.Request) -> httpx.Response: - return await state.handle(request) - - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as http: - state = _World(monkeypatch, http) - yield state, request_work.RequestWork() - - -def _operator(role: Role = Role.ADMIN): - return _auth(subject="operator@example.com", roles=(role,)) - - -def _private_answer(result: Any, bag: request_work.RequestWork) -> dict[str, Any]: - assert bag.mirror_marked - answer = request_work.flag_response(result.model_dump()) - assert answer["mirrored"] is True - assert _TITLE not in json.dumps(answer) and _ACCESS not in json.dumps(answer) - return answer - - -async def test_owner_update_probes_and_commits_only_the_selected_connected_source(world) -> None: - state, bag = world - with request_work.bind(bag), acting_as(_auth()): - result = await sources.handle_knowledge_source_update( - KnowledgeSourceUpdateInput(**_SCOPE, add_items=[{"type": "file", "id": _ADDED}]) - ) - answer = _private_answer(result, bag) - assert result.added == [{"type": "file", "id": _ADDED}] - assert result.items == [{"type": "file", "id": _FILE}, {"type": "file", "id": _ADDED}] - assert result.probe.documents == 0 and result.probe.sample == [] and not result.probe.more - assert len(state.source_writes) == len(state.state_writes) == 1 - saved = state.source_writes[0] - assert (saved.source_id, saved.owner_subject, saved.access) == ( - _SOURCE_ID, - "person", - "mirrored", +def world(fake, monkeypatch): + asyncio.run(sources.handle_knowledge_source_add(_add())) + key = ORG, NS, "design-decks" + source = replace( + fake.rows[key], + kind="gdrive", + credential_mode="connected", + owner_subject="owner", + access=MIRRORED_ACCESS, + mirror="acl-" + "a" * 24, + config={}, + generic_config_json='{"retained":true}', + generic_items_json='[{"opaque":true}]', ) - assert saved.connection_id == state.rows[_KEY].connection_id and saved.credential_enc == "" - assert state.state_writes[0]["detail"]["full"] is True - assert state.state_writes[0]["detail"]["requested_at"] - assert len(state.refresh_requests) == len(state.native_requests) == 1 - assert state.native_callers == ["person@example.com"] - assert answer["probe"]["documents"] == 0 - - -async def test_namespace_admin_cannot_choose_new_items_for_another_owners_account(world) -> None: - state, bag = world - with ( - request_work.bind(bag), - acting_as(_operator()), - pytest.raises(ValidationError, match="^the connected account is unavailable$"), - ): - await sources.handle_knowledge_source_update( - KnowledgeSourceUpdateInput(**_SCOPE, add_items=[{"type": "file", "id": _ADDED}]) - ) - assert bag.mirror_marked - assert state.refresh_requests == state.native_requests == state.source_writes == [] - + fake.rows[key] = source + state = SimpleNamespace(store=fake, source=source, key=key, queued=[], role=Role.WRITER) -async def test_admin_check_accepts_credential_standing_without_an_item_existence_oracle( - world, -) -> None: - state, bag = world - assert state.source is not None - state.source = replace(state.source, items=[{"type": "file", "id": "not-shared-with-owner"}]) - with request_work.bind(bag), acting_as(_operator()): - result = await sources.handle_knowledge_source_check(KnowledgeSourceCheckInput(**_SCOPE)) - answer = _private_answer(result, bag) - assert result.reachable and result.summary == "the connected credential was accepted" - assert (result.documents, result.more, result.sample, result.checked) == (0, False, [], 0) - assert len(state.refresh_requests) == 1 and state.native_requests == [] - assert "not-shared-with-owner" not in json.dumps(answer) - assert state.source_writes == [] and state.state_writes == [] + async def subject(auth): + assert auth.org == ORG and not auth.is_service_account + return ORG, auth.subject + async def queue(selected): + state.queued.append(selected) + return True -async def test_owner_check_withholds_provider_counts_titles_and_marks_the_response(world) -> None: - state, bag = world - with request_work.bind(bag), acting_as(_auth()): - result = await sources.handle_knowledge_source_check(KnowledgeSourceCheckInput(**_SCOPE)) - _private_answer(result, bag) - assert result.reachable and result.summary == "the connected source was reached" - assert (result.documents, result.more, result.sample) == (0, False, []) - assert result.checked == 1 - assert len(state.refresh_requests) == len(state.native_requests) == 1 - assert state.source_writes == [] and state.state_writes == [] + monkeypatch.setattr(accounts, "own_subject", subject) + async def in_scope(org, namespace, role): + assert (org, namespace) == (ORG, NS) + return state.role >= role -@pytest.mark.parametrize("stage", ("refresh", "native")) -async def test_admin_probe_keeps_its_actual_role_across_external_waits(world, stage: str) -> None: - state, bag = world - # A namespace grant supplies ADMIN; the token itself must not retain global ADMIN. - auth = _operator(Role.VIEWER) - with request_work.bind(bag), acting_as(auth): - if stage == "refresh": - state.pause_refresh = True - work = asyncio.create_task( - sources.handle_knowledge_source_check(KnowledgeSourceCheckInput(**_SCOPE)) - ) - entered, release = state.refresh_entered, state.refresh_release - else: - assert state.source is not None - authority = await accounts.resolve_probe(state.source, deadline=time.monotonic() + 60) - assert authority.requester == "operator" and authority.source.owner_subject == "person" + monkeypatch.setattr(sources.authz, "row_in_scope", in_scope) + monkeypatch.setattr(sources, "_queue_retirement", queue) + fake.probes.clear() + return state - async def native_read(access: CheckedAccess): - return await gdrive.file_meta(access, _FILE) - state.pause_native = True - work = asyncio.create_task(authority.run(native_read)) - entered, release = state.native_entered, state.native_release - try: - await state.await_stage(entered, work) - state.roles["operator"] = Role.VIEWER - release.set() - with pytest.raises(ValidationError, match="^the connected account is unavailable$"): - await work - assert current_auth() is auth - finally: - release.set() - if not work.done(): - work.cancel() - await asyncio.gather(work, return_exceptions=True) - assert len(state.refresh_requests) == 1 - if stage == "refresh": - assert state.native_requests == [] - assert state.rows[_KEY].active and not state.rows[_KEY].refresh_id - assert unseal(CREDENTIAL_PURPOSE, state.rows[_KEY].credential_enc) == _ROTATED - assert state.source is not None and state.source.active - assert state.source_writes == state.retirement_rows == [] - else: - assert len(state.native_requests) == 1 - assert state.native_callers == ["operator@example.com"] - assert state.source_writes == [] +def _auth(subject="owner", role=Role.WRITER): + return principal(role, subject=subject, org=ORG, namespaces=(NS,), service_account=False) -async def _local_operation(operation: str): +async def _local_operation(operation): + scope = {"org": ORG, "namespace": NS, "name": "design-decks"} if operation == "sync": return await sources.handle_knowledge_source_sync_now( - KnowledgeSourceSyncNowInput(**_SCOPE, full=True) + KnowledgeSourceSyncNowInput(**scope, full=True) ) - assert operation == "remove" return await sources.handle_knowledge_source_remove( - KnowledgeSourceRemoveInput(**_SCOPE, confirm="documents", delete_documents=True) + KnowledgeSourceRemoveInput(**scope, confirm="design-decks", delete_documents=True) ) -def _assert_local_result(state: _World, result: Any, operation: str) -> None: - assert state.refresh_requests == state.native_requests == [] +def _assert_result(state, result, operation): + assert state.store.probes == [] if operation == "sync": - assert len(state.state_writes) == 1 and state.state_writes[0]["detail"]["full"] is True - assert state.source_writes == [] and state.retirement_rows == [] - return - assert result.documents_pending == 0 and len(state.retirement_rows) == 1 - assert len(state.source_writes) == 1 - saved = state.source_writes[0] - assert not saved.active and saved.pending_delete - assert saved.credential_enc == saved.secret_enc == "" and saved.owner_subject == "person" - queued = state.retirement_rows[0] - assert (queued["org"], queued["namespace"], queued["state_key"]) == ( - "team", - _MIRROR, - "knowledge_source_retire:" + _SOURCE_ID, - ) - assert queued["state_value"] == "pending" - assert json.loads(queued["detail"])["source_id"] == _SOURCE_ID + assert state.store.rows[state.key] == state.source + assert state.queued == [] + detail = json.loads(state.store.states["design-decks"]["detail"]) + assert detail["full"] and detail["requested_at"] + else: + assert result.documents_pending == 0 + assert state.queued == [state.source] + saved = state.store.rows[state.key] + assert saved == replace( + state.source, active=False, pending_delete=True, credential_enc="", secret_enc="" + ) -@pytest.mark.parametrize("operation", ("sync", "remove")) -async def test_owner_can_request_local_sync_or_retirement_without_provider_work( - world, operation: str -) -> None: - state, bag = world +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["remove"]) +async def test_owner_can_request_local_sync_or_retirement_without_provider_work(world, operation): + bag = request_work.RequestWork() with request_work.bind(bag), acting_as(_auth()): result = await _local_operation(operation) - _private_answer(result, bag) - _assert_local_result(state, result, operation) + assert bag.mirror_marked + assert request_work.flag_response(result.model_dump())["mirrored"] is True + _assert_result(world, result, operation) -@pytest.mark.parametrize("operation", ("sync", "remove")) -async def test_foreign_writer_is_refused_but_current_admin_can_run_local_controls( - world, operation: str -) -> None: - state, bag = world - state.roles["operator"] = Role.WRITER - with ( - request_work.bind(bag), - acting_as(_operator(Role.WRITER)), - pytest.raises(ValidationError, match="^the connected account is unavailable$"), - ): +@pytest.mark.asyncio +@pytest.mark.parametrize("operation", ["remove"]) +async def test_foreign_writer_is_refused_but_current_admin_can_run_local_controls(world, operation): + bag = request_work.RequestWork() + with request_work.bind(bag), acting_as(_auth("operator")), pytest.raises(ValidationError): await _local_operation(operation) - assert state.source_writes == state.state_writes == state.retirement_rows == [] - assert state.refresh_requests == state.native_requests == [] - state.roles["operator"] = Role.ADMIN - with request_work.bind(bag), acting_as(_operator()): + assert world.store.rows[world.key] == world.source + assert world.store.states["design-decks"]["detail"] == "{}" + assert world.queued == [] and world.store.probes == [] + world.role = Role.ADMIN + with request_work.bind(bag), acting_as(_auth("operator", Role.ADMIN)): result = await _local_operation(operation) - _private_answer(result, bag) - _assert_local_result(state, result, operation) + assert bag.mirror_marked + assert request_work.flag_response(result.model_dump())["mirrored"] is True + _assert_result(world, result, operation) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("role", [Role.WRITER, Role.ADMIN]) +async def test_retained_native_source_sync_refuses_without_executing_or_mutating(world, role): + before = dict(world.store.states) + with acting_as(_auth(role=role)), pytest.raises(ValidationError) as caught: + await _local_operation("sync") + assert caught.value.to_detail()["code"] == "SOURCE_NOT_SERVED" + assert world.store.rows[world.key] == world.source + assert world.store.states == before and world.queued == [] and world.store.probes == [] diff --git a/tests/unit/test_connected_source_publication.py b/tests/unit/test_connected_source_publication.py index 7c3020b749..779137b334 100644 --- a/tests/unit/test_connected_source_publication.py +++ b/tests/unit/test_connected_source_publication.py @@ -13,13 +13,12 @@ from functools import partial from typing import Any -import httpx import pytest -from server.core.errors import ValidationError from server.core.vectors import codes_state from server.knowledge.api.models_knowledge import KnowledgeUpsertInput from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import mcp_source_authority as authority from server.knowledge.app import writes from server.knowledge.domain.access_list import AccessList, from_json from server.knowledge.domain.connected_accounts import stopped @@ -28,6 +27,7 @@ from server.memory.domain.provenance import pipeline_actor from tests.unit.principals import acting_as from tests.unit.test_connected_source_authority import _World as _AuthorityWorld +from tests.unit.test_mcp_source_sync import harness as harness _ORIGINAL = b"the original connected document" _CONTENT = "# Connected document\n\nThe owner publishes this revision." @@ -41,14 +41,14 @@ class _World(_AuthorityWorld): model_name = "publication-test-embedder" dim = 4 - def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient) -> None: + def __init__(self, monkeypatch: pytest.MonkeyPatch, harness) -> None: self.events: list[str] = [] self.held: dict[asyncio.Task[Any], list[str]] = {} - super().__init__(monkeypatch, http) + super().__init__(monkeypatch, harness) assert self.source is not None self.source = replace(self.source, mirror=_MIRROR) self.selected_source = self.source - self.key = self.source.org, self.source.owner_subject, self.source.kind + self.key = self.source.org, self.source.owner_subject, self.source.connection_slot namespace, tag = home(self.source) self.request = KnowledgeUpsertInput( org=self.source.org, @@ -58,7 +58,7 @@ def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient) -> content=_CONTENT, description="An imported source document.", tags=[tag], - metadata={"source_kind": "gdrive", "source_name": "documents"}, + metadata={"source_kind": "mcp", "source_name": "documents"}, original_bytes_b64=base64.b64encode(_ORIGINAL).decode(), original_filename="document.txt", blob_content_type="text/plain", @@ -122,24 +122,24 @@ def assert_storage_leases(self) -> None: return assert len(held) == 2 assert held[0].startswith("connected-account:") - assert held[1] == "knowledge-source:team:shared-space" + assert held[1] == "knowledge-source:org:collection" async def no_duplicate(self, org: str, namespace: str, _sha: str, **_kw: Any): - assert (org, namespace) == ("team", _MIRROR) + assert (org, namespace) == ("org", _MIRROR) return None async def no_active_chunks(self, org: str, namespace: str, uri: str, **_kw: Any) -> int: - assert (org, namespace, uri) == ("team", _MIRROR, self.request.source_uri) + assert (org, namespace, uri) == ("org", _MIRROR, self.request.source_uri) return 0 async def no_prior_document(self, org: str, namespace: str, uri: str, **kw: Any): - assert (org, namespace, uri) == ("team", _MIRROR, self.request.source_uri) + assert (org, namespace, uri) == ("org", _MIRROR, self.request.source_uri) assert kw == {"include_superseded": True} return None async def put_blob(self, org: str, namespace: str, raw: bytes, **kw: Any) -> str: self.assert_storage_leases() - assert (org, namespace, raw) == ("team", _MIRROR, _ORIGINAL) + assert (org, namespace, raw) == ("org", _MIRROR, _ORIGINAL) assert kw == {"uploader": "-"} self.events.append("blob") self.blob_writes.append({"org": org, "namespace": namespace, "raw": raw, **kw}) @@ -177,7 +177,7 @@ async def no_matching_chunks(self, *_args: Any, **_kw: Any) -> int: async def retire_versions( self, org: str, namespace: str, own: list[tuple[str, int]], **_kw: Any ) -> None: - assert (org, namespace) == ("team", _MIRROR) + assert (org, namespace) == ("org", _MIRROR) self.chunk_retirements.append(own) async def await_stage(self, event: asyncio.Event, work: asyncio.Task[Any]) -> None: @@ -194,12 +194,8 @@ async def await_stage(self, event: asyncio.Event, work: asyncio.Task[Any]) -> No @pytest.fixture -async def world(monkeypatch: pytest.MonkeyPatch): - async def no_provider(_request: httpx.Request) -> httpx.Response: - raise AssertionError("publication does not contact a provider") - - async with httpx.AsyncClient(transport=httpx.MockTransport(no_provider)) as http: - yield _World(monkeypatch, http) +def world(monkeypatch, harness): + return _World(monkeypatch, harness) async def _write(state: _World, *, guarded: bool = True): @@ -207,7 +203,7 @@ async def _write(state: _World, *, guarded: bool = True): return await writes.handle_knowledge_upsert( state.request, permissions=_PERMISSIONS, - commit_guard=partial(accounts.publication_guard, state.selected_source) + commit_guard=partial(authority.publication_guard, state.selected_source) if guarded else None, ) @@ -224,7 +220,7 @@ async def test_a_valid_publication_keeps_real_rows_permissions_and_worker_identi assert chunk["content"] == "The owner publishes this revision." for stored in (row, chunk): assert (stored["org"], stored["namespace"], stored["source_uri"]) == ( - "team", + "org", _MIRROR, world.request.source_uri, ) @@ -239,7 +235,7 @@ async def test_a_valid_publication_keeps_real_rows_permissions_and_worker_identi "source-sync-pass", "imported", ) - assert stored["tags"] == ["source-id:source-id"] + assert stored["tags"] == ["source-id:00000000-0000-4000-8000-000000000001"] assert row["actor"] == SYNC_WORKER_ACTOR assert from_json(row["access_json"]) == _PERMISSIONS assert json.loads(row["metadata"]) == world.request.metadata @@ -280,7 +276,7 @@ async def test_standing_lost_during_embedding_prevents_all_final_chunk_and_head_ assert world.source is not None world.source = replace(world.source, active=False) world.embedding_release.set() - with pytest.raises(ValidationError, match="^the connected account is unavailable$"): + with pytest.raises(authority.MCPAuthorityError): await work assert world.chunk_writes == world.document_writes == [] assert len(world.chunk_retirements) == 1 @@ -294,7 +290,7 @@ async def test_standing_lost_during_embedding_prevents_all_final_chunk_and_head_ async def test_source_replacement_before_the_first_guard_prevents_even_blob_storage(world) -> None: assert world.source is not None world.source = replace(world.source, source_id="replacement-source") - with pytest.raises(ValidationError, match="^the connected account is unavailable$"): + with pytest.raises(authority.MCPAuthorityError): await _write(world) assert world.blob_writes == world.chunk_writes == world.document_writes == [] assert world.embedded == world.chunk_retirements == [] @@ -312,7 +308,10 @@ async def local_stop() -> None: world.events.append("stop-acquired") # The registry deletion is external; this stop has no source left to retire. world.source = None - await accounts._stop_locked(world.rows[world.key]) + current = world.rows[world.key] + generation = accounts._next_connection(current.connection_id, inactive=True) + await accounts._move_fence(current.connection_id, generation) + await world.put(stopped(current, connection_id=generation, at=datetime.now(UTC))) world.events.append("stop-finished") try: diff --git a/tests/unit/test_connected_source_read_plan.py b/tests/unit/test_connected_source_read_plan.py index 1f8b0bd5ab..0c0c498bca 100644 --- a/tests/unit/test_connected_source_read_plan.py +++ b/tests/unit/test_connected_source_read_plan.py @@ -1,205 +1,149 @@ -"""Indexed connected content retains its owner generation and the actual reader ACL.""" - -from __future__ import annotations +"""Retained MCP source evidence keeps its owner, selection and reader boundaries.""" from dataclasses import replace -from datetime import UTC, datetime -from typing import Any +from types import SimpleNamespace +from unittest.mock import AsyncMock -import httpx import pytest from server.auth.context import current_auth_var +from server.auth.reader_identity import ReaderIdentity from server.core import request_work -from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import mcp_source_authority as authority from server.knowledge.app import source_access as app +from server.knowledge.app.mcp_contracts import encode_source from server.knowledge.domain.access_list import AccessList, to_json -from server.operations.base import Role, grant_rank -from tests.unit.principals import acting_as -from tests.unit.test_connected_source_authority import _auth -from tests.unit.test_connected_source_authority import _World as _AuthorityWorld - -_SID = "11111111-1111-4111-8111-111111111111" -_MIRROR = "acl-" + "a" * 24 -_URI = "https://docs.example/file#" + _SID - - -class _World(_AuthorityWorld): - """External directory, source discovery and indexed permission metadata.""" - - def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient) -> None: - super().__init__(monkeypatch, http) - assert self.source is not None - self.source = replace(self.source, source_id=_SID, mirror=_MIRROR) - self.started = datetime.now(UTC) - self.source_queries: list[str] = [] - self.document = { - "org": "team", - "namespace": _MIRROR, - "source_uri": _URI, - "tags": ["source-id:" + _SID], - "version": 10, - "revision": 1, - "title": "A checked document", - "superseded_at": None, - "access_json": to_json(AccessList(owner="person", emails=("reader@example.com",))), - } - monkeypatch.setattr(app.store, "_default_client", lambda: self) - monkeypatch.setattr(app.mirrors_repo, "mirrors_of", self.mirrors) - monkeypatch.setattr(app.store, "listings", self.listings) - monkeypatch.setattr(app.store, "metadata", self.metadata) - monkeypatch.setattr(app.pg, "enabled", lambda: False) - monkeypatch.setattr(app.settings, "knowledge_source_acl_stale_seconds", 3600) - - async def query_all(self, query: str, params: dict[str, Any], **kw: Any): - if "FROM loom.knowledge_sources FINAL" in query: - assert params == {"org": "team", "names": ["shared-space"]} - self.source_queries.append(query) - # This fake applies the discovery SQL's persisted credential-mode predicate. - if self.source is None or "credential_mode = 'shared'" in query: - return [] - return [ - { - "namespace": "shared-space", - "name": "documents", - "credential_mode": self.source.credential_mode, - "source_id": self.source.source_id, - } - ] - if params.get("sub") in {"reader", "reader@example.com"}: - assert "FROM loom.namespaces" in query and params["org"] == "team" - return [ - { - "namespace": "personal-reader", - "owner_email": "reader", - "contact_email": "reader@example.com", - "password_hash": "verified-reader-password-hash", - "hosted_domain": "", - "issuer": "", - } - ] - return await super().query_all(query, params, **kw) - - async def query_one(self, query: str, params: dict[str, Any], **kw: Any): - if "AS grants" in query and params["sub"] in {"reader", "reader@example.com"}: - assert params["org"] == "team" - return { - "grants": [("shared-space", grant_rank("viewer"))], - "spellings": ["reader", "reader@example.com"], - "held": ["reader", "reader@example.com"], - } - if "SELECT role FROM loom.namespace_grants" in query and "reader" in params["subs"]: - assert params["org"] == "team" and params["ns"] == "shared-space" - return {"role": "viewer"} - return await super().query_one(query, params, **kw) - - async def deactivated(self, email: str) -> bool: - if email == "reader@example.com": - return False - return await super().deactivated(email) - - async def mirrors(self, org: str, namespaces: list[str], **kw: Any): - assert org == "team" and kw == {"live_only": True} - return {_MIRROR: "shared-space"} if "shared-space" in namespaces else {} - - async def listings(self, org: str, pairs: list[tuple[str, str]]): - assert org == "team" - return ( - [{"namespace": _MIRROR, "source_id": _SID, "started_at": self.started}] - if (_MIRROR, _SID) in pairs - else [] - ) +from server.operations.base import Role +from tests.unit.test_mcp_source_read_policy import checked_document, installed_plan +from tests.unit.test_mcp_source_read_policy import reader as reader +from tests.unit.test_mcp_source_sync import MIRROR +from tests.unit.test_mcp_source_sync import harness as harness - async def metadata(self, org: str, pairs: list[tuple[str, str]]): - assert org == "team" and pairs == [(_MIRROR, _URI)] - return [dict(self.document)] +pytestmark = pytest.mark.asyncio @pytest.fixture -async def world(monkeypatch: pytest.MonkeyPatch): - async def no_provider(_request: httpx.Request) -> httpx.Response: - raise AssertionError("indexed reads cannot mint or use a provider token") - +def world(reader, harness, monkeypatch): token = request_work._current.set(None) bag = request_work.begin() + document = checked_document(harness) + monkeypatch.setattr(app.store, "metadata", AsyncMock(side_effect=lambda *a: [dict(document)])) try: - async with httpx.AsyncClient(transport=httpx.MockTransport(no_provider)) as http: - state = _World(monkeypatch, http) - yield state, bag - assert state.refresh_requests == state.native_requests == [] - assert state.writes == [] + yield SimpleNamespace(reader=reader, harness=harness, bag=bag, document=document) finally: request_work._current.reset(token) -def _candidate() -> dict[str, Any]: - return {"namespace": _MIRROR, "source_uri": _URI, "doc_version": 10, "revision": 1} - - -@pytest.mark.parametrize("subject", ("person@example.com", "reader@example.com")) -async def test_current_connected_owner_and_independently_admitted_reader_can_read( - world, subject: str -) -> None: - state, bag = world - with acting_as(_auth(subject=subject)): - plan = await app.prepare("team", ["shared-space"]) - assert plan.sources == {(_MIRROR, _SID): "shared-space"} - [admitted] = await plan.check([_candidate()], chunks=True) - assert admitted.document == state.document and admitted.namespace == "shared-space" - assert plan.current(admitted) - assert plan.marked and not plan.unread and bag.mirror_marked - assert state.source_queries - - -async def test_namespace_viewer_without_the_documents_acl_is_not_its_owner(world) -> None: - state, bag = world - state.document["access_json"] = to_json(AccessList(owner="person")) - with acting_as(_auth(subject="reader@example.com")): - plan = await app.prepare("team", ["shared-space"]) - assert plan.sources == {(_MIRROR, _SID): "shared-space"} - assert await plan.check([_candidate()], chunks=True) == [] - assert bag.mirror_marked - - -@pytest.mark.parametrize("change", ("generation", "owner-grant", "scim", "items", "auth")) +def _candidate(world): + return { + "namespace": MIRROR, + "source_uri": world.document["source_uri"], + "doc_version": 1, + "revision": 1, + } + + +async def _plan(world, monkeypatch): + await installed_plan(world.reader, world.harness, monkeypatch) + monkeypatch.setattr(app, "check_authorized", AsyncMock()) + monkeypatch.setattr(app.settings, "auth_required", True) + return await app.prepare("org", ["collection"]) + + +async def test_current_connected_owner_reads_exact_selected_document(world, monkeypatch): + plan = await _plan(world, monkeypatch) + assert plan.sources == {(MIRROR, world.harness.source.source_id): "collection"} + [admitted] = await plan.check([_candidate(world)], chunks=True) + assert admitted.document == world.document and admitted.namespace == "collection" + assert plan.current(admitted) + assert plan.marked and not plan.unread and world.bag.mirror_marked + assert not world.harness.reads and not world.harness.doc_rows + + +async def test_namespace_viewer_with_a_document_acl_cannot_borrow_owner_only_authority( + world, monkeypatch +): + world.document["access_json"] = to_json( + AccessList(owner="owner", emails=("reader@example.test",)) + ) + world.reader.auth = replace(world.reader.auth, subject="reader@example.test") + current_auth_var.set(world.reader.auth) + plan = await _plan(world, monkeypatch) + assert plan.sources == {} + assert await plan.check([_candidate(world)], chunks=True) == [] + assert not world.harness.reads and not world.harness.doc_rows + + +@pytest.mark.parametrize( + "change", ["generation", "owner-grant", "scim", "selection", "scope", "auth"] +) async def test_scope_refresh_removes_retained_evidence_after_authority_changes( - world, change: str -) -> None: - state, _bag = world - auth = _auth() - with acting_as(auth): - plan = await app.prepare("team", ["shared-space"]) - [admitted] = await plan.check([_candidate()], chunks=True) - evidence = app.AccessEvidence.from_admitted(admitted) - assert plan.current_evidence(evidence) - assert state.source is not None - if change == "generation": - account = state.rows["team", "person", "gdrive"] - generation = accounts._next_connection(account.connection_id) - state.rows["team", "person", "gdrive"] = replace(account, connection_id=generation) - state.fences[accounts._fence_key(generation)] = generation - state.source = replace(state.source, connection_id=generation) - elif change == "owner-grant": - state.grant = Role.VIEWER - elif change == "scim": - state.scim_ended = True - elif change == "items": - # In-place mutation must not mutate the request's deep-copied source pin. - state.source.items.append({"id": "another-file", "kind": "file"}) - else: - current_auth_var.set(replace(auth)) - assert await plan.check([_candidate()], chunks=True) == [] - assert not plan.current_evidence(evidence) - assert plan.sources == {} and plan.listing_starts == {} - - -async def test_a_replaced_registration_cannot_join_an_existing_discovery_plan(world) -> None: - state, _bag = world - with acting_as(_auth()): - plan = await app.prepare("team", ["shared-space"]) - [admitted] = await plan.check([_candidate()], chunks=True) - assert state.source is not None - state.source = replace(state.source, source_id="22222222-2222-4222-8222-222222222222") - assert await plan.check([_candidate()], chunks=True) == [] - assert not plan.current(admitted) - assert plan.discovery_sources == {(_MIRROR, _SID): "shared-space"} + world, monkeypatch, change +): + h = world.harness + plan = await _plan(world, monkeypatch) + [admitted] = await plan.check([_candidate(world)], chunks=True) + evidence = app.AccessEvidence.from_admitted(admitted) + assert plan.current_evidence(evidence) + if change == "generation": + h.account = replace( + h.account, connection_id=authority.accounts._next_connection(h.account.connection_id) + ) + elif change == "owner-grant": + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=Role.VIEWER)) + elif change == "scim": + monkeypatch.setattr( + authority.accounts.scim, "refuses_subject", AsyncMock(return_value=True) + ) + elif change == "selection": + h.select(resources=("different-resource",)) + elif change == "scope": + h.contract = h.contract.model_copy(update={"scope_revision": h.contract.scope_revision + 1}) + config, items = encode_source(h.contract) + h.source = replace(h.source, generic_config_json=config, generic_items_json=items) + else: + current_auth_var.set(replace(world.reader.auth)) + assert await plan.check([_candidate(world)], chunks=True) == [] + assert not plan.current_evidence(evidence) + assert plan.sources == {} and plan.listing_starts == {} + assert not h.reads and not h.doc_rows + + +async def test_a_replaced_registration_cannot_join_an_existing_discovery_plan(world, monkeypatch): + h = world.harness + plan = await _plan(world, monkeypatch) + [admitted] = await plan.check([_candidate(world)], chunks=True) + original = h.source.source_id + h.source = replace(h.source, source_id="22222222-2222-4222-8222-222222222222") + assert await plan.check([_candidate(world)], chunks=True) == [] + assert not plan.current(admitted) + assert plan.discovery_sources == {(MIRROR, original): "collection"} + + +@pytest.mark.parametrize("has_acl", [True, False]) +async def test_explicit_collection_copy_keeps_independent_reader_acl(world, monkeypatch, has_acl): + h = world.harness + h.select(policy="collection_copy") + monkeypatch.setattr(authority.authz, "grant_role_for", AsyncMock(return_value=Role.ADMIN)) + world.document.update(checked_document(h)) + world.document["access_json"] = to_json( + AccessList(owner="owner", emails=("reader@example.test",) if has_acl else ()) + ) + world.reader.auth = replace(world.reader.auth, subject="reader") + monkeypatch.setattr( + authority, + "resolve_reader", + AsyncMock( + return_value=ReaderIdentity("reader", frozenset({"reader@example.test"}), frozenset()) + ), + ) + current_auth_var.set(world.reader.auth) + plan = await _plan(world, monkeypatch) + assert plan.sources == {(MIRROR, h.source.source_id): "collection"} + admitted = await plan.check([_candidate(world)], chunks=True) + if has_acl: + assert len(admitted) == 1 and plan.current(admitted[0]) + assert admitted[0].document == world.document + else: + assert admitted == [] + assert world.bag.mirror_marked and not h.reads and not h.doc_rows diff --git a/tests/unit/test_connected_source_repair.py b/tests/unit/test_connected_source_repair.py deleted file mode 100644 index f70152596d..0000000000 --- a/tests/unit/test_connected_source_repair.py +++ /dev/null @@ -1,72 +0,0 @@ -"""Missed owner lifecycle hooks retire only the checked source generation.""" - -from __future__ import annotations - -from dataclasses import replace - -import httpx -import pytest - -from server.core.errors import ValidationError -from server.knowledge.app import connected_accounts as accounts -from server.knowledge.app import source_sync as sync -from server.knowledge.app import source_sync_connected -from server.operations.base import Role -from tests.unit.principals import acting_as -from tests.unit.test_connected_source_authority import _KEY -from tests.unit.test_connected_source_operations import _World - - -@pytest.fixture -async def world(monkeypatch: pytest.MonkeyPatch): - async def provider(request: httpx.Request) -> httpx.Response: - raise AssertionError("local owner repair must perform no provider request") - - async with httpx.AsyncClient(transport=httpx.MockTransport(provider)) as http: - yield _World(monkeypatch, http) - - -@pytest.mark.parametrize("loss", ("writer", "scim", "stopped-generation")) -async def test_confirmed_owner_loss_retires_only_the_checked_source(world, loss: str) -> None: - source = world.source - assert source is not None - account = world.rows[_KEY] - if loss == "writer": - world.roles["person"] = Role.VIEWER - elif loss == "scim": - world.scim_ended = True - else: - world.fences[accounts._fence_key(account.connection_id)] = accounts._next_connection( - account.connection_id, inactive=True - ) - with acting_as(None), pytest.raises(sync.SourceGone): - await source_sync_connected.ensure_current(source) - assert world.rows[_KEY] == account - assert world.source is not None and not world.source.active - assert world.source.source_id == source.source_id - assert len(world.source_writes) == len(world.state_writes) == 1 - assert world.retirement_rows - assert world.refresh_requests == world.native_requests == [] - - -async def test_missing_fence_refuses_without_retiring_unverified_owner(world) -> None: - source = world.source - assert source is not None - account = world.rows[_KEY] - world.fences.clear() - with acting_as(None), pytest.raises(ValidationError): - await source_sync_connected.ensure_current(source) - assert world.rows[_KEY] == account and world.source == source - assert world.source_writes == world.state_writes == world.retirement_rows == [] - - -async def test_a_reused_source_name_is_not_retired_as_the_original_generation(world) -> None: - original = world.source - assert original is not None - world.roles["person"] = Role.VIEWER - replacement = replace(original, source_id="aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee") - world.source = replacement - with acting_as(None), pytest.raises(sync.SourceGone): - await source_sync_connected.ensure_current(original) - assert world.source == replacement and replacement.active - assert world.source_writes == world.state_writes == world.retirement_rows == [] diff --git a/tests/unit/test_connected_source_workers.py b/tests/unit/test_connected_source_workers.py deleted file mode 100644 index c521ab2c8d..0000000000 --- a/tests/unit/test_connected_source_workers.py +++ /dev/null @@ -1,254 +0,0 @@ -"""Connected native turns publish checked content and vouch only while still current.""" - -from __future__ import annotations - -import asyncio -import base64 -import json -import time -from dataclasses import replace -from datetime import datetime -from typing import Any - -import httpx -import pytest - -from server.clients import notion -from server.knowledge.app import connected_accounts as accounts -from server.knowledge.app import mirrors, private_sync -from server.knowledge.app import source_sync as sync -from server.knowledge.domain.access_list import AccessList, from_json -from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, mirror_uri -from server.knowledge.store import documents -from server.knowledge.store import mirrors as mirror_store -from server.knowledge.store import sources as source_store -from server.memory.domain.provenance import pipeline_actor -from tests.unit.principals import acting_as -from tests.unit.test_connected_source_publication import _MIRROR -from tests.unit.test_connected_source_publication import _World as _PublicationWorld -from tests.unit.test_notion_source_sync import PAGE, _page, _para - -_ADDRESS = "https://pages.example.com/connected-notes" -_TEXT = "The owner publishes this connected revision." -_ACCESS = "worker-private-access" -_REFRESH = "worker-private-refresh" - - -class _World(_PublicationWorld): - """Fake only provider, registry, lease, embedding and persistent-store I/O.""" - - def __init__(self, monkeypatch: pytest.MonkeyPatch, http: httpx.AsyncClient) -> None: - super().__init__(monkeypatch, http) - assert self.source is not None - previous = self.rows.pop(self.key) - account = replace(previous, kind="notion", scopes=()) - self.key = account.org, account.subject, account.kind - self.rows[self.key] = account - self.source = replace( - self.source, - kind="notion", - config={"page_ids": [PAGE], "database_ids": []}, - items=[{"type": "page", "id": PAGE}], - ) - self.selected_source = self.source - self.request = self.request.model_copy( - update={"source_uri": mirror_uri(_ADDRESS, self.source.source_id)} - ) - self.listings: list[dict[str, Any]] = [] - self.debt_checks = 0 - self.lose_before_listing = False - self.native_requests: list[httpx.Request] = [] - self.refresh_requests: list[httpx.Request] = [] - self.page = _page(PAGE, "2026-01-01T00:00:00.000Z", title="Connected notes") - self.page["url"] = _ADDRESS - monkeypatch.setattr(accounts.settings, "connect_notion_client_id", "page-client") - monkeypatch.setattr(accounts.settings, "connect_notion_client_secret", "page-secret") - monkeypatch.setattr(accounts.settings, "connect_notion_read_content_only", True) - monkeypatch.setattr(notion, "get_client", lambda: http) - monkeypatch.setattr(notion, "_next_request_at", {}) - monkeypatch.setattr(mirrors, "mirrors_of", self.mirror_rows) - monkeypatch.setattr(mirror_store, "_default_client", lambda: self) - monkeypatch.setattr(source_store, "read_states", self.read_states) - monkeypatch.setattr(source_store, "source_revisions", self.source_revisions) - monkeypatch.setattr(documents, "publications_owed", self.publications_owed) - - async def mirror_rows(self, org: str, namespaces: list[str], **kw: Any): - assert (org, namespaces, kw) == ("team", ["shared-space"], {"live_only": True}) - return {_MIRROR: "shared-space"} - - async def read_states(self, org: str, namespace: str, names: list[str]): - assert (org, namespace, names) == ("team", _MIRROR, ["source-id"]) - return {} - - async def source_revisions( - self, org: str, namespace: str, tag: str, **_kw: Any - ) -> list[dict[str, str]]: - assert (org, namespace, tag) == ("team", _MIRROR, "source-id:source-id") - return [] - - async def no_prior_document(self, org: str, namespace: str, uri: str, **kw: Any): - assert (org, namespace, uri) == ("team", _MIRROR, self.request.source_uri) - assert set(kw) == {"include_superseded"} - return None - - async def publications_owed(self, org: str, namespace: str, suffix: str) -> bool: - assert (org, namespace, suffix) == ("team", _MIRROR, "#source-id") - self.debt_checks += 1 - if self.lose_before_listing: - assert len(self.document_writes) == 1 - self.end_generation() - return False - - async def insert(self, table: str, rows: list[dict[str, Any]], **_kw: Any) -> None: - assert table == mirror_store.LISTINGS - self.assert_storage_leases() - self.events.append("listing") - self.listings.extend(dict(row) for row in rows) - - def end_generation(self) -> None: - account = self.rows[self.key] - self.fences[accounts._fence_key(account.connection_id)] = accounts._next_connection( - account.connection_id, inactive=True - ) - - async def handle(self, request: httpx.Request) -> httpx.Response: - assert not self.holders.get(asyncio.current_task(), 0) - if request.url.path == "/v1/oauth/token": - assert str(request.url) == "https://api.notion.com/v1/oauth/token" - assert request.method == "POST" - assert request.headers["authorization"] == ( - "Basic " + base64.b64encode(b"page-client:page-secret").decode() - ) - assert json.loads(request.content) == { - "grant_type": "refresh_token", - "refresh_token": "source-private-refresh", - } - assert self.rows[self.key].refresh_id - self.refresh_requests.append(request) - return httpx.Response( - 200, - json={ - "access_token": _ACCESS, - "refresh_token": _REFRESH, - "token_type": "bearer", - }, - ) - assert request.url.host == "api.notion.com" - assert request.method == "GET" - assert request.headers["authorization"] == "Bearer " + _ACCESS - assert request.headers["Notion-Version"] == notion.API_VERSION - self.native_requests.append(request) - if request.url.path == f"/v1/pages/{PAGE}": - return httpx.Response(200, json=self.page) - assert request.url.path == f"/v1/blocks/{PAGE}/children" - return httpx.Response(200, json={"results": [_para(_TEXT)], "has_more": False}) - - -@pytest.fixture -async def world(monkeypatch: pytest.MonkeyPatch): - async def provider(request: httpx.Request) -> httpx.Response: - return await state.handle(request) - - async with httpx.AsyncClient(transport=httpx.MockTransport(provider)) as http: - state = _World(monkeypatch, http) - yield state - - -async def _turn(state: _World) -> sync.TurnResult: - assert state.selected_source is not None - started = time.monotonic() - run = sync.Pass(budget=sync.PassBudget(started, started + 60), left=4) - with acting_as(None), pipeline_actor(SYNC_WORKER_ACTOR), private_sync.scope(): - return await sync._turn_of(state.selected_source)(state.selected_source, {}, run) - - -async def test_native_connected_notion_turn_publishes_real_rows_then_a_guarded_listing( - world, -) -> None: - result = await _turn(world) - assert (result.status, result.complete, result.full, result.changed, result.documents_seen) == ( - "ok", - True, - True, - 1, - 1, - ) - assert result.mirror == _MIRROR and result.unconverted == result.skipped == 0 - assert len(world.refresh_requests) == 1 - assert [request.url.path for request in world.native_requests] == [ - f"/v1/pages/{PAGE}", - f"/v1/blocks/{PAGE}/children", - ] - assert len(world.document_writes) == len(world.chunk_writes) == len(world.listings) == 1 - row, chunk = world.document_writes[0], world.chunk_writes[0] - assert row["content"].strip() == chunk["content"] == _TEXT - assert row["title"] == "Connected notes" - assert row["actor"] == SYNC_WORKER_ACTOR - assert from_json(row["access_json"]) == AccessList(owner="person") - assert row["version"] == chunk["doc_version"] and row["revision"] == 1 - for stored in (row, chunk): - assert (stored["org"], stored["namespace"], stored["source_uri"]) == ( - "team", - _MIRROR, - world.request.source_uri, - ) - assert ( - stored["agent"], - stored["user_id"], - stored["session_id"], - stored["source_class"], - ) == ("-", "-", "-", "imported") - assert stored["tags"] == [ - "source-kind:design_doc", - "source:documents", - "source-id:source-id", - ] - metadata = json.loads(row["metadata"]) - assert metadata["source_kind"] == "notion" and metadata["source_name"] == "documents" - assert metadata["ingested_from"] == PAGE and metadata["ingested_format"] == "blocks" - assert metadata["source_revision"] == world.page["last_edited_time"] - assert json.loads(chunk["doc_metadata"]) == metadata - assert chunk["embedding"] == [1.0, 0.0, 0.0, 0.0] - assert chunk["embedding_model"] == world.model_name and chunk["embedding_dim"] == 4 - listing = world.listings[0] - assert {key: value for key, value in listing.items() if key != "started_at"} == { - "org": "team", - "namespace": _MIRROR, - "source_id": "source-id", - "name": "documents", - } - assert isinstance(listing["started_at"], datetime) - assert world.debt_checks == 1 and world.events.index("head-end") < world.events.index("listing") - assert world.blob_writes == world.chunk_retirements == [] - - -async def test_native_connected_turn_cannot_vouch_after_owner_generation_ends(world) -> None: - world.lose_before_listing = True - with pytest.raises(accounts.OwnerUnavailable): - await _turn(world) - assert len(world.document_writes) == len(world.chunk_writes) == 1 - assert world.debt_checks == 1 and world.listings == [] - assert len(world.refresh_requests) == 1 and len(world.native_requests) == 2 - - -async def test_native_connected_turn_rechecks_generation_after_embedding_before_final_rows( - world, -) -> None: - world.pause_embedding = True - work = asyncio.create_task(_turn(world)) - try: - await world.await_stage(world.embedding_entered, work) - assert len(world.native_requests) == 2 - assert world.chunk_writes == world.document_writes == world.listings == [] - async with accounts.account_lease(*world.key): - world.end_generation() - world.embedding_release.set() - with pytest.raises(accounts.OwnerUnavailable): - await work - assert world.chunk_writes == world.document_writes == world.listings == [] - assert len(world.chunk_retirements) == 1 - assert world.chunk_retirements[0][0][0] == world.request.source_uri - finally: - if not work.done(): - work.cancel() - await asyncio.gather(work, return_exceptions=True) diff --git a/tests/unit/test_document_source_contract.py b/tests/unit/test_document_source_contract.py new file mode 100644 index 0000000000..7165ce6c21 --- /dev/null +++ b/tests/unit/test_document_source_contract.py @@ -0,0 +1,393 @@ +"""Recording admission and retained opaque source privacy.""" + +from __future__ import annotations + +import asyncio +import contextlib +from collections.abc import AsyncIterator +from dataclasses import replace +from datetime import datetime +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from server.core.errors import BadConfigError, ValidationError +from server.knowledge.api.models_sources import ( + KnowledgeSourceAddInput, + KnowledgeSourceAddOutput, + KnowledgeSourceCheckOutput, + KnowledgeSourceEntry, + KnowledgeSourceInspectOutput, + KnowledgeSourceProbe, + KnowledgeSourceRemoveInput, +) +from server.knowledge.domain import sources as domain + + +def _recording(**kwargs: Any) -> domain.KnowledgeSource: + return domain.KnowledgeSource( + org="org", namespace="notes", name="meetings", source_id="source-id", **kwargs + ) + + +def test_recording_config_deduplicates_valid_ids_without_changing_order() -> None: + assert domain.parse_config( + "recording", {"provider": "zoom", "ids": [123456789, "987654321", "123456789"]} + ) == {"provider": "zoom", "ids": ["123456789", "987654321"]} + + +@pytest.mark.parametrize( + "config", + [ + {}, + {"provider": "unknown", "ids": ["123456789"]}, + {"provider": "zoom", "ids": []}, + {"provider": "zoom", "ids": [True]}, + {"provider": "zoom", "ids": ["not-an-id"]}, + {"provider": "zoom", "ids": ["123456789"], "include": ["docs"]}, + {"provider": "zoom", "ids": [str(100000000 + n) for n in range(21)]}, + ], +) +def test_recording_config_refuses_invalid_selection(config: dict[str, Any]) -> None: + with pytest.raises(BadConfigError): + domain.parse_config("recording", config) + + +@pytest.mark.parametrize("kind", ["gdrive", "notion", "linear", "mcp", "unknown"]) +def test_unavailable_kinds_have_no_native_config_admission(kind: str) -> None: + with pytest.raises(BadConfigError, match="unavailable"): + domain.parse_config(kind, {"provider": "zoom", "ids": ["123456789"]}) + + +def test_recording_api_keeps_config_and_probe_without_native_output_fields() -> None: + config = {"provider": "zoom", "ids": ["123456789"]} + request = KnowledgeSourceAddInput( + org="org", namespace="notes", name="meetings", config=config, credential="private-key" + ) + assert request.kind == "recording" + assert request.config == config + assert "private-key" not in repr(request) + assert "credential" not in request.model_dump() + output = KnowledgeSourceAddOutput( + name="meetings", + kind="recording", + namespace="notes", + config=config, + probe=KnowledgeSourceProbe(documents=2, sample=["Meeting"], more=True), + ) + assert output.config == config + assert output.probe.model_dump() == {"documents": 2, "more": True, "sample": ["Meeting"]} + for model in (KnowledgeSourceAddOutput, KnowledgeSourceEntry, KnowledgeSourceInspectOutput): + assert "items" not in model.model_fields + assert "include" not in model.model_fields + for model in (KnowledgeSourceProbe, KnowledgeSourceCheckOutput): + assert "checked" not in model.model_fields + assert "sampled" not in model.model_fields + + +def test_native_add_arguments_are_removed_fields_for_ignored_args_reporting() -> None: + request = KnowledgeSourceAddInput( + org="org", + namespace="notes", + name="meetings", + config={"provider": "zoom", "ids": ["123456789"]}, + credential="recording-key", + items=[{"type": "folder", "id": "legacy-folder"}], + links=["https://example.com/legacy"], + include=["docs"], + credential_mode="connected", + ) + assert request.kind == "recording" + for field in ("items", "links", "include", "credential_mode"): + assert field not in KnowledgeSourceAddInput.model_fields + assert field not in request.model_dump() + + +@pytest.mark.parametrize( + ("kind", "mode", "version", "access"), + [ + ("gdrive", "shared", 0, domain.NAMESPACE_ACCESS), + ("notion", "shared", 0, domain.NAMESPACE_ACCESS), + ("linear", "connected", 0, domain.MIRRORED_ACCESS), + ("unknown", "shared", 0, domain.NAMESPACE_ACCESS), + ("recording", "connected", 0, domain.NAMESPACE_ACCESS), + ("recording", "shared", 1, domain.NAMESPACE_ACCESS), + ("recording", "shared", 0, domain.MIRRORED_ACCESS), + ], +) +def test_retained_registrations_are_unavailable_and_redact_sync_details( + kind: str, mode: str, version: int, access: str +) -> None: + source = _recording( + kind=kind, credential_mode=mode, source_contract_version=version, access=access + ) + assert not domain.served(source) + assert not domain.mirror_synced(source) + assert domain.id_list_config(source) is None + assert domain.sync_shown( + source, + '{"status":"failed","requested_at":"requested","last_synced_at":"finished",' + '"documents_seen":9,"error":"private title","unconverted_reasons":{"private":1}}', + ) == {"status": "failed", "requested_at": "requested", "last_synced_at": "finished"} + + +def test_recording_retains_its_config_and_operational_sync_counts() -> None: + config = {"provider": "zoom", "ids": ["123456789"]} + source = _recording(kind="recording", config=config) + assert domain.served(source) + assert not domain.opaque_payload(kind=source.kind, mode=source.credential_mode, version=0) + assert domain.id_list_config(source) == config + assert domain.stored_config(source) == config + assert domain.sync_shown(source, '{"status":"ok","documents_seen":2,"cursor":"private"}') == { + "status": "ok", + "documents_seen": 2, + } + + +def test_only_current_mcp_contract_can_sync_protected_copies() -> None: + source = _recording( + kind="mcp", + credential_mode="connected", + source_contract_version=1, + access=domain.MIRRORED_ACCESS, + ) + assert domain.mirror_synced(source) + assert not domain.served(source) + assert not domain.mirror_synced(replace(source, source_contract_version=2)) + + +@pytest.mark.parametrize("kind", ["gdrive", "notion", "linear", "mcp", "unknown"]) +@pytest.mark.parametrize("native_kind_column", [True, False]) +@pytest.mark.parametrize("mode", ["shared", "connected"]) +def test_opaque_lifecycle_roundtrip_preserves_bytes_identity_and_sealed_columns( + monkeypatch: pytest.MonkeyPatch, kind: str, native_kind_column: bool, mode: str +) -> None: + from server.knowledge.store import sources as store + + row = { + "org": "org", + "namespace": "notes", + "name": "retained", + "source_id": "immutable-id", + "kind": kind if native_kind_column else "", + "source_kind": "" if native_kind_column else kind, + "config_json": ' { "unknown" : [3,2,1], "private" : "original" } ', + "items_json": ' [ { "opaque" : "item" } ] ', + "credential_enc": "sealed-original", + "secret_enc": "sealed-items", + "access": domain.MIRRORED_ACCESS, + "credential_mode": mode, + "owner_subject": "canonical-owner", + "connection_id": "account-key", + "connection_slot": "generic-slot", + "source_contract_version": 0, + "created_by": "writer", + "active": False, + "pending_delete": True, + } + written: list[dict[str, Any]] = [] + stamp = datetime(2024, 1, 1) + row.update(created_at=stamp, updated_at=stamp) + monkeypatch.setattr(store, "naive_utc_now_seconds", lambda: stamp) + + class Client: + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + assert table == store.TABLE + written.extend(rows) + + monkeypatch.setattr(store, "_default_client", Client) + source = store._source(row) + assert source.kind == kind + assert source.config == {} + assert source.items == [] + assert "original" not in repr(source) + assert '"opaque"' not in repr(source) + assert not domain.served(source) + assert not domain.mirror_synced(source) + asyncio.run(store.insert_source(source)) + assert len(written) == 1 + saved = written[0] + for key in ( + "org", + "namespace", + "name", + "source_id", + "config_json", + "items_json", + "credential_enc", + "secret_enc", + "access", + "credential_mode", + "owner_subject", + "connection_id", + "connection_slot", + "source_contract_version", + "created_by", + "active", + "pending_delete", + ): + assert saved[key] == row[key], key + assert saved["kind"] == "" + assert saved["source_kind"] == kind + assert store._source(saved) == source + + +def test_recording_probe_checks_selected_ids_and_returns_recent_titles( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from server.knowledge.app import source_probes, source_sync_recording + + config = {"provider": "zoom", "ids": ["123456789", "987654321"]} + session = object() + open_session = AsyncMock(return_value=session) + list_recordings = AsyncMock( + return_value=( + [ + {"name": "Earlier meeting", "modifiedTime": "2024-01-01T00:00:00Z"}, + {"name": "Later meeting", "modifiedTime": "2024-01-02T00:00:00Z"}, + ], + [], + ) + ) + monkeypatch.setattr(source_sync_recording, "open_session", open_session) + monkeypatch.setattr(source_sync_recording, "list_recordings", list_recordings) + result = asyncio.run(source_probes.probe("recording", config, "recording-key")) + open_session.assert_awaited_once_with("zoom", "recording-key") + list_recordings.assert_awaited_once_with(session, config["ids"]) + assert result.documents == 2 + assert result.sample == ["Later meeting", "Earlier meeting"] + assert not result.more + + +def test_recording_row_roundtrip_keeps_config(monkeypatch: pytest.MonkeyPatch) -> None: + from server.knowledge.store import sources as store + + config = {"provider": "zoom", "ids": ["123456789"]} + source = _recording(kind="recording", config=config, credential_enc="sealed-recording") + written: list[dict[str, Any]] = [] + + class Client: + async def insert(self, table: str, rows: list[dict[str, Any]]) -> None: + assert table == store.TABLE + written.extend(rows) + + monkeypatch.setattr(store, "_default_client", Client) + asyncio.run(store.insert_source(source)) + restored = store._source(written[0]) + assert restored.config == config + assert restored.items == [] + assert restored.credential_enc == "sealed-recording" + assert not restored.secret_enc + assert not restored.generic_config_json + assert domain.served(restored) + + +def test_recording_credential_uses_its_column_purpose(monkeypatch: pytest.MonkeyPatch) -> None: + from server.knowledge.app import sources as app + from server.settings import settings + + monkeypatch.setattr(settings, "jwt_secret", "unit-test-root-secret") + source = _recording(kind="recording", config={"provider": "zoom", "ids": ["123456789"]}) + sealed = app._with_credential(source, "recording-key") + assert sealed.credential_enc + assert not sealed.secret_enc + assert app.credential_of(sealed) == "recording-key" + assert ( + app.credential_of(replace(sealed, credential_enc="", secret_enc=sealed.credential_enc)) + == "" + ) + retained = replace( + source, kind="gdrive", secret_enc=app.seal(app._SECRET_PURPOSE, "retained-key") + ) + assert retained.secret_enc and app.credential_of(retained) == "" + with pytest.raises(ValidationError): + app._with_credential(retained, "replacement-key") + + +@pytest.mark.parametrize( + ("access", "delete_documents", "active"), + [ + (domain.NAMESPACE_ACCESS, False, True), + (domain.NAMESPACE_ACCESS, True, True), + (domain.NAMESPACE_ACCESS, True, False), + (domain.MIRRORED_ACCESS, False, True), + (domain.MIRRORED_ACCESS, True, True), + ], +) +def test_explicit_legacy_retirement_preserves_opaque_metadata_and_hides_mirror_counts( + monkeypatch: pytest.MonkeyPatch, access: str, delete_documents: bool, active: bool +) -> None: + from server.knowledge.app import source_push + from server.knowledge.app import sources as app + + source = _recording( + kind="gdrive", + access=access, + active=active, + credential_enc="sealed-original", + secret_enc="sealed-items", + owner_subject="stored-owner", + connection_id="stored-account", + generic_config_json=' { "opaque" : "original config" } ', + generic_items_json=' [ { "opaque" : "original item" } ] ', + ) + + @contextlib.asynccontextmanager + async def lease(org: str, namespace: str) -> AsyncIterator[None]: + assert (org, namespace) == (source.org, source.namespace) + yield + + get_source = AsyncMock(return_value=source if active else None) + latest_source = AsyncMock(return_value=source) + count_documents = AsyncMock(return_value=7) + insert_source = AsyncMock() + queue_retirement = AsyncMock(return_value=True) + retire = AsyncMock() + monkeypatch.setattr(app, "sources_lease", lease) + monkeypatch.setattr(app, "sequential_reads", contextlib.nullcontext) + monkeypatch.setattr(app.authz, "row_in_scope", AsyncMock(return_value=True)) + monkeypatch.setattr(app.store, "get_source", get_source) + monkeypatch.setattr(app.store, "latest_source", latest_source) + monkeypatch.setattr(app.store, "count_documents", count_documents) + monkeypatch.setattr(app.store, "insert_source", insert_source) + monkeypatch.setattr(app, "_queue_retirement", queue_retirement) + monkeypatch.setattr(source_push, "retire", retire) + output = asyncio.run( + app.handle_knowledge_source_remove( + KnowledgeSourceRemoveInput( + org=source.org, + namespace=source.namespace, + name=source.name, + confirm=source.name, + delete_documents=delete_documents, + ) + ) + ) + insert_source.assert_awaited_once() + retired = insert_source.await_args.args[0] + assert retired == replace( + source, + active=False, + credential_enc="", + secret_enc="", + pending_delete=delete_documents or access == domain.MIRRORED_ACCESS, + ) + retire.assert_awaited_once_with(source) + if access == domain.MIRRORED_ACCESS: + queue_retirement.assert_awaited_once_with(source) + count_documents.assert_not_awaited() + assert output.documents_pending == 0 + else: + queue_retirement.assert_not_awaited() + if delete_documents: + count_documents.assert_awaited_once_with( + source.org, source.namespace, domain.source_tag(source.name) + ) + else: + count_documents.assert_not_awaited() + assert output.documents_pending == (7 if delete_documents else 0) + if active: + latest_source.assert_not_awaited() + else: + latest_source.assert_awaited_once_with(source.org, source.namespace, source.name) diff --git a/tests/unit/test_gdrive_push.py b/tests/unit/test_gdrive_push.py deleted file mode 100644 index 075a2d606d..0000000000 --- a/tests/unit/test_gdrive_push.py +++ /dev/null @@ -1,89 +0,0 @@ -"""Drive channel requests use the provider API and bounded complete corpora.""" - -from __future__ import annotations - -from unittest.mock import AsyncMock - -import pytest - -from server.clients import gdrive_push as client -from server.clients._vendor import VendorError - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "result,expected", [({}, set()), ({"drives": [{"id": "drive"}]}, {"drive"})] -) -async def test_complete_memberships_include_empty_account( - monkeypatch: pytest.MonkeyPatch, result: dict, expected: set -) -> None: - monkeypatch.setattr(client, "bearer_get", AsyncMock(return_value=result)) - assert await client.member_drives("token") == expected - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "result", - [ - {"nextPageToken": "more"}, - {"drives": [{"id": str(i)} for i in range(20)]}, - {"drives": [{}]}, - {"drives": "wrong"}, - ], -) -async def test_incomplete_or_over_limit_memberships_refuse( - monkeypatch: pytest.MonkeyPatch, result: dict -) -> None: - monkeypatch.setattr(client, "bearer_get", AsyncMock(return_value=result)) - with pytest.raises(VendorError): - await client.member_drives("token") - - -@pytest.mark.asyncio -async def test_shared_drive_cursor_and_watch_name_same_corpus( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setattr(client.time, "time", lambda: 1000) - cursor = AsyncMock(return_value={"startPageToken": "cursor"}) - watch = AsyncMock( - return_value={"id": "channel", "resourceId": "resource", "expiration": "2000000"} - ) - monkeypatch.setattr(client, "bearer_get", cursor) - monkeypatch.setattr(client, "request_json", watch) - result = await client.watch( - "token", - channel_id="channel", - channel_token="proof", - address="https://loom.example/hook", - drive_id="drive", - ) - assert cursor.call_args.kwargs["params"]["driveId"] == "drive" - assert watch.call_args.kwargs["params"]["driveId"] == "drive" - assert watch.call_args.kwargs["params"]["pageToken"] == "cursor" - assert watch.call_args.kwargs["json"]["token"] == "proof" - assert result["resource_id"] == "resource" and result["expiration"] == 2000 - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "response", - [ - {"id": "other", "resourceId": "resource", "expiration": "2000000"}, - {"id": "channel", "expiration": "2000000"}, - {"id": "channel", "resourceId": "resource", "expiration": "bad"}, - ], -) -async def test_watch_response_must_bind_requested_channel( - monkeypatch: pytest.MonkeyPatch, response: dict -) -> None: - monkeypatch.setattr(client.time, "time", lambda: 1000) - monkeypatch.setattr(client, "bearer_get", AsyncMock(return_value={"startPageToken": "cursor"})) - monkeypatch.setattr(client, "request_json", AsyncMock(return_value=response)) - with pytest.raises(VendorError): - await client.watch( - "token", - channel_id="channel", - channel_token="proof", - address="https://loom.example/hook", - drive_id="", - ) diff --git a/tests/unit/test_knowledge_source_items.py b/tests/unit/test_knowledge_source_items.py deleted file mode 100644 index cdc7502360..0000000000 --- a/tests/unit/test_knowledge_source_items.py +++ /dev/null @@ -1,772 +0,0 @@ -"""A source's items: their parser, the link parser, the config form a build -without items reads, the storage rule that keeps such a build off a source it -cannot read, and the shared-folder listing the items build (queries, a recursive -walk, a shared drive, single files, filters). Every response is written here.""" - -from __future__ import annotations - -import asyncio -import json -import uuid -from typing import Any - -import httpx -import pydantic -import pytest - -from server.clients import gdrive, linear -from server.core.errors import BadConfigError -from server.knowledge.api import models_sources -from server.knowledge.app import source_gdrive_items as items_listing -from server.knowledge.app import source_probes -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 sources as store -from tests.unit.ch_fake import RecordingCH - -FOLDER = "1AbCdEfGhIjKlMnOp" -FILE = "1FiLeIdOfADocument_x" -DRIVE = "0AbCdEfGhIjKlUk9PVA" -PAGE = "0123456789abcdef0123456789abcdef" -PAGE_DASHED = "01234567-89ab-cdef-0123-456789abcdef" -PROJECT = "0b6d7a52-1c1e-4c2b-9a4e-5d0f3b1e2a01" -DOCS = "application/vnd.google-apps.document" - - -def _folder(folder_id: str = FOLDER, recursive: bool = False) -> dict[str, Any]: - return {"type": "folder", "id": folder_id, "recursive": recursive} - - -# ---- parse_items ----------------------------------------------------------------- - - -def test_every_item_type_is_stored_in_one_form() -> None: - found = domain.parse_items( - "gdrive", - [ - {"type": "folder", "id": FOLDER}, - {"type": "file", "id": FILE}, - {"type": "shared_drive", "id": DRIVE}, - { - "type": "filter", - "name_contains": " Roadmap ", - "kinds": ["pdf", "docs"], - "modified_after": "2026-01-31", - "in": FOLDER, - }, - ], - ) - assert found == [ - _folder(), - {"type": "file", "id": FILE}, - {"type": "shared_drive", "id": DRIVE}, - { - "type": "filter", - "name_contains": "Roadmap", - "kinds": ["docs", "pdf"], - "modified_after": "2026-01-31", - "in": FOLDER, - }, - ] - assert domain.parse_items("notion", [{"type": "database", "id": PAGE}]) == [ - {"type": "database", "id": PAGE_DASHED} - ] - assert domain.parse_items("linear", [{"type": "project", "id": PROJECT.upper()}]) == [ - {"type": "project", "id": PROJECT} - ] - assert domain.parse_items("linear", [{"type": "project", "slug_id": "1a2b3c4d5e6f"}]) == [ - {"type": "project", "slug_id": "1a2b3c4d5e6f"} - ] - - -def test_a_later_item_of_the_same_type_and_id_replaces_the_earlier() -> None: - found = domain.parse_items( - "gdrive", [_folder(), {"type": "file", "id": FILE}, _folder(recursive=True)] - ) - assert found == [{"type": "file", "id": FILE}, _folder(recursive=True)] - - -@pytest.mark.parametrize( - ("kind", "item"), - [ - ("gdrive", {"type": "folder", "id": "x' or '1"}), - ("gdrive", {"type": "folder", "id": FOLDER, "recursive": "yes"}), - ("gdrive", {"type": "folder", "id": FOLDER, "query": "x"}), - ("gdrive", {"type": "page", "id": PAGE}), - ("gdrive", {"type": "filter"}), - ("gdrive", {"type": "filter", "name_contains": "a\nb"}), - ("gdrive", {"type": "filter", "name_contains": "x" * 101}), - ("gdrive", {"type": "filter", "owner": "a.person@example.com"}), - ("gdrive", {"type": "filter", "modified_after": "2026-02-30"}), - ("gdrive", {"type": "filter", "modified_after": "2026-01-01T00:00:00"}), - ("gdrive", {"type": "filter", "kinds": ["xlsx"]}), - ("gdrive", {"type": "filter", "kinds": []}), - ("gdrive", {"type": "filter", "in": "../x"}), - ("notion", {"type": "page", "id": "short"}), - ("linear", {"type": "project", "id": "not-a-uuid"}), - ("linear", {"type": "project", "slug_id": "zz"}), - ("linear", {"type": "project", "id": PROJECT, "slug_id": "1a2b3c4d5e6f"}), - ("gdrive", "a folder"), - ], -) -def test_a_malformed_item_is_refused(kind: str, item: Any) -> None: - with pytest.raises(BadConfigError): - domain.parse_items(kind, [item]) - - -def test_many_items_are_left_to_the_count() -> None: - many = [{"type": "file", "id": f"{FILE}{n:03d}"} for n in range(domain.MAX_ITEMS + 1)] - # The op counts, once short ids are resolved; the parser only checks each item. - assert len(domain.parse_items("gdrive", many)) == domain.MAX_ITEMS + 1 - - -# ---- config and items ------------------------------------------------------------ - - -def test_id_list_config_turns_into_items_and_back() -> None: - config = {"folder_ids": [FOLDER, "2QrStUvWxYzAbCdEf"], "include": ["docs", "pdf"]} - items = domain.items_from_config("gdrive", config) - assert items == [_folder(), _folder("2QrStUvWxYzAbCdEf")] - assert domain.config_from_items("gdrive", items, ["docs", "pdf"]) == config - notion = {"page_ids": [PAGE_DASHED], "database_ids": [PROJECT]} - assert ( - domain.config_from_items("notion", domain.items_from_config("notion", notion), []) == notion - ) - linear_config = {"project_ids": [PROJECT]} - items = domain.items_from_config("linear", linear_config) - assert domain.config_from_items("linear", items, []) == linear_config - assert domain.items_from_config("recording", {"provider": "zoom", "ids": ["123456789"]}) == [] - - -@pytest.mark.parametrize( - "items", - [ - [_folder(recursive=True)], - [_folder(), {"type": "file", "id": FILE}], - [{"type": "shared_drive", "id": DRIVE}], - [_folder(f"{FOLDER}{n:02d}") for n in range(domain.MAX_FOLDERS + 1)], - ], -) -def test_an_item_id_list_config_cannot_hold_has_no_config_form(items: list[Any]) -> None: - assert domain.config_from_items("gdrive", items, ["docs"]) is None - - -def test_a_project_named_by_its_short_id_has_no_config_form() -> None: - assert ( - domain.config_from_items("linear", [{"type": "project", "slug_id": "1a2b3c4d5e6f"}], []) - is None - ) - - -# ---- the link parser ------------------------------------------------------------- - - -@pytest.mark.parametrize( - ("link", "kind", "item"), - [ - (f"https://drive.google.com/drive/folders/{FOLDER}?usp=sharing", "gdrive", _folder()), - (f"https://drive.google.com/drive/u/2/folders/{FOLDER}", "gdrive", _folder()), - (f"drive.google.com/drive/folders/{FOLDER}/", "gdrive", _folder()), - ( - f"https://drive.google.com/drive/mobile/folders/{FOLDER}?usp=sharing", - "gdrive", - _folder(), - ), - (f"https://drive.google.com/file/d/{FILE}/view?usp=drive_link", "gdrive", None), - (f"https://docs.google.com/document/d/{FILE}/edit#heading=h.1", "gdrive", None), - (f"https://docs.google.com/a/example.com/document/d/{FILE}/edit", "gdrive", None), - (f"https://docs.google.com/presentation/d/{FILE}/edit", "gdrive", None), - ( - f"https://www.notion.so/Design-Notes-{PAGE}", - "notion", - {"type": "page", "id": PAGE_DASHED}, - ), - (f"https://notion.so/acme/{PAGE.upper()}", "notion", {"type": "page", "id": PAGE_DASHED}), - ( - f"https://acme.notion.site/Design-Notes-{PAGE}", - "notion", - {"type": "page", "id": PAGE_DASHED}, - ), - ( - f"https://www.notion.so/acme/{PAGE}?v=abc", - "notion", - {"type": "database", "id": PAGE_DASHED}, - ), - ( - f"https://www.notion.so/acme/{'b' * 32}?v=abc&p={PAGE}&pm=s", - "notion", - {"type": "page", "id": PAGE_DASHED}, - ), - ( - "https://linear.app/acme/project/q3-planning-1a2b3c4d5e6f/overview", - "linear", - {"type": "project", "slug_id": "1a2b3c4d5e6f"}, - ), - ( - "https://linear.app/acme/project/1a2b3c4d5e6f", - "linear", - {"type": "project", "slug_id": "1a2b3c4d5e6f"}, - ), - ], -) -def test_each_link_form_names_its_item(link: str, kind: str, item: Any) -> None: - [parsed] = parse_links([link]) - assert (parsed.kind, parsed.item, parsed.unreadable) == ( - kind, - item or {"type": "file", "id": FILE}, - "", - ) - - -@pytest.mark.parametrize( - ("link", "reason"), - [ - ("https://example.com/drive/folders/x", "not a store"), - ("ftp://drive.google.com/drive/folders/x", "not a web link"), - ("https://drive.google.com/drive/my-drive", "no folder or file id"), - ("https://drive.google.com/drive/folders/x'%20or%20'1", "is not an id"), - (f"https://docs.google.com/spreadsheets/d/{FILE}/edit", "a spreadsheet"), - ("https://www.notion.so/acme/Design-Notes", "no page id"), - (f"https://drive.google.com/open?id={FILE}", "a folder or a file alike"), - (f"https://docs.google.com/drawings/d/{FILE}/edit", "a drawing"), - ("https://docs.google.com/document/d/e/2PACX-1vAbC/pub", "a published copy"), - ("https://linear.app/acme/issue/ENG-12/a-bug", "a single issue"), - ("https://linear.app/acme/team/ENG/all", "a team link: link one of its projects"), - ("https://linear.app/acme/project/q3-planning", "no project id"), - ("", "not a link"), - ], -) -def test_a_link_that_names_no_item_says_why(link: str, reason: str) -> None: - [parsed] = parse_links([link]) - assert parsed.kind == "" and parsed.item == {} - assert reason in parsed.unreadable - - -def test_a_list_of_links_answers_each_in_order() -> None: - links = [f"https://drive.google.com/drive/folders/{FOLDER}", "https://example.com/x"] - assert [bool(p.unreadable) for p in parse_links(links)] == [False, True] - - -# ---- the storage rule ------------------------------------------------------------ - - -def _src(**kw: Any) -> KnowledgeSource: - kw.setdefault("items", domain.items_from_config("gdrive", kw.get("config", {}))) - return KnowledgeSource( - org="o", namespace="n", name="d", kind="gdrive", source_id=str(uuid.uuid4()), **kw - ) - - -def _written(monkeypatch: pytest.MonkeyPatch, src: KnowledgeSource) -> dict[str, Any]: - ch = RecordingCH() - ch.install(monkeypatch) - asyncio.run(store.insert_source(src)) - [row] = ch.inserted("knowledge_sources") - return row - - -def test_a_source_id_list_config_holds_is_written_as_before( - monkeypatch: pytest.MonkeyPatch, -) -> None: - row = _written( - monkeypatch, - _src(config={"include": ["docs"]}, items=[_folder()], credential_enc="sealed"), - ) - assert row["kind"] == row["source_kind"] == "gdrive" - assert json.loads(row["config_json"]) == {"folder_ids": [FOLDER], "include": ["docs"]} - assert json.loads(row["items_json"]) == [_folder()] - assert (row["credential_enc"], row["secret_enc"]) == ("sealed", "") - - -def test_a_source_with_an_item_id_list_config_cannot_hold_is_written_without_a_kind( - monkeypatch: pytest.MonkeyPatch, -) -> None: - items = [_folder(recursive=True), {"type": "file", "id": FILE}] - row = _written(monkeypatch, _src(config={"include": ["docs"]}, items=items, secret_enc="s")) - assert (row["kind"], row["source_kind"]) == ("", "gdrive") - assert json.loads(row["config_json"]) == {"include": ["docs"]} - assert json.loads(row["items_json"]) == items - assert (row["credential_enc"], row["secret_enc"]) == ("", "s") - # Read back, it is the source N wrote. - back = store._source(row) - assert (back.kind, back.items, back.secret_enc) == ("gdrive", items, "s") - assert domain.include_in(back.config) == ["docs"] - - -# A build without items writes neither column, or rewrites a row with no items. -@pytest.mark.parametrize("items_json", ["", "[]"]) -def test_a_row_written_before_the_items_columns_reads_its_items_from_its_config( - items_json: str, -) -> None: - row = { - "org": "o", - "namespace": "n", - "name": "d", - "kind": "gdrive", - "source_id": "i", - "config_json": json.dumps({"folder_ids": [FOLDER], "include": ["docs"]}), - "credential_enc": "sealed", - "source_kind": "", - "items_json": items_json, - "secret_enc": "", - } - src = store._source(row) - assert (src.kind, src.items, src.credential_enc) == ("gdrive", [_folder()], "sealed") - assert domain.id_list_config(src) == {"folder_ids": [FOLDER], "include": ["docs"]} - - -def test_the_credential_is_read_from_the_column_its_source_was_written_to( - monkeypatch: pytest.MonkeyPatch, -) -> None: - from server.knowledge.app import sources as app - from server.settings import settings - - monkeypatch.setattr(settings, "jwt_secret", "unit-test-root-secret") - flat = app._with_credential(_src(config={"include": ["docs"]}, items=[_folder()]), "key") - assert flat.credential_enc and not flat.secret_enc - later = app._with_credential(_src(items=[_folder(recursive=True)]), "key") - assert later.secret_enc and not later.credential_enc - assert app.credential_of(flat) == app.credential_of(later) == "key" - # Each column has its own purpose: neither opens under the other's. - swapped = _src(items=[_folder(recursive=True)], secret_enc=flat.credential_enc) - assert app.credential_of(swapped) == "" - - -# ---- the shared-folder listing --------------------------------------------------- - - -class _Drive: - """A shared-folder store: subfolders by parent, files by parent and drive.""" - - def __init__(self) -> None: - self.children: dict[str, list[str]] = {} - self.files: list[dict[str, Any]] = [] - self.requests: list[httpx.Request] = [] - self.missing: set[str] = set() - # Merged into every folder query's answer: a next page, an unfinished search. - self.folder_extra: dict[str, Any] = {} - - def answer(self, request: httpx.Request) -> httpx.Response: - self.requests.append(request) - path = request.url.path - if path.startswith("/drive/v3/files/"): - file_id = path.rsplit("/", 1)[-1] - found = [f for f in self.files if f["id"] == file_id] - if file_id in self.missing or not found: - return httpx.Response(404) - return httpx.Response(200, json=found[0]) - if path.startswith("/drive/v3/drives/"): - return httpx.Response(404 if path.rsplit("/", 1)[-1] in self.missing else 200, json={}) - q = request.url.params["q"] - if "application/vnd.google-apps.folder" in q: - ids = [c for p, kids in self.children.items() if f"'{p}' in parents" in q for c in kids] - return httpx.Response( - 200, json={"files": [{"id": c} for c in ids], **self.folder_extra} - ) - drive = request.url.params.get("driveId", "") - if drive in self.missing: - return httpx.Response(404) - listed = [ - f - for f in self.files - if (drive and f.get("driveId") == drive) - or (not drive and any(f"'{p}' in parents" in q for p in f.get("parents", []))) - ] - return httpx.Response(200, json={"files": listed}) - - -@pytest.fixture -def drive(monkeypatch: pytest.MonkeyPatch) -> _Drive: - d = _Drive() - client = httpx.AsyncClient(transport=httpx.MockTransport(d.answer)) - monkeypatch.setattr(gdrive, "get_client", lambda: client) - return d - - -def _listings(d: _Drive) -> list[httpx.Request]: - return [r for r in d.requests if r.url.path == "/drive/v3/files"] - - -def test_a_filter_s_query_quotes_every_value() -> None: - query = gdrive.filter_query( - { - "type": "filter", - "name_contains": "it's a \\ test", - "modified_after": "2026-01-31", - "in": FOLDER, - }, - [DOCS], - ) - assert query == ( - f"trashed = false and (mimeType = '{DOCS}') and name contains 'it\\'s a \\\\ test' " - f"and modifiedTime > '2026-01-31T00:00:00' " - f"and '{FOLDER}' in parents" - ) - - -def test_a_listing_names_at_most_fifty_parents_per_query(drive: _Drive) -> None: - folders = [f"{FOLDER}{n:03d}" for n in range(120)] - asyncio.run(gdrive.list_all("tok", folders, [DOCS], pace_s=0)) - queries = [r.url.params["q"] for r in _listings(drive)] - assert [q.count(" in parents") for q in queries] == [50, 50, 20] - - -def test_a_recursive_folder_walks_its_subfolders(drive: _Drive) -> None: - drive.children = {FOLDER: ["sub1aaaaaaaaa"], "sub1aaaaaaaaa": ["sub2aaaaaaaaa"]} - drive.files = [ - {"id": "f1", "name": "a", "mimeType": DOCS, "parents": ["sub2aaaaaaaaa"]}, - {"id": "f2", "name": "b", "mimeType": DOCS, "parents": ["elsewhere"]}, - ] - listing = asyncio.run( - items_listing.list_items("tok", [_folder(recursive=True)], ["docs"], pace_s=0) - ) - assert [f["id"] for f in listing.files] == ["f1"] - assert listing.folders == {FOLDER, "sub1aaaaaaaaa", "sub2aaaaaaaaa"} and not listing.walk_cut - - -def test_a_walk_stops_at_its_folder_bound_and_says_so( - drive: _Drive, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(items_listing, "MAX_WALK_FOLDERS", 3) - drive.children = {FOLDER: [f"kid{n}aaaaaaaa" for n in range(5)]} - listing = asyncio.run( - items_listing.list_items("tok", [_folder(recursive=True)], ["docs"], pace_s=0) - ) - # The root and three subfolders: the bound counts subfolders. - assert len(listing.folders) == 4 and listing.walk_cut - - -def test_a_walk_reads_no_page_past_its_folder_bound(drive: _Drive) -> None: - # Every answer says another page follows: only the bound stops the reads. - drive.children = {FOLDER: ["kid0aaaaaaaaa", "kid1aaaaaaaaa"]} - drive.folder_extra = {"nextPageToken": "more"} - found, _ = asyncio.run(gdrive.subfolders("tok", [FOLDER], limit=3, pace_s=0)) - assert len(found) == 4 and len(_listings(drive)) == 2 - - -def _walk(**kw: Any) -> items_listing.Listing: - out = items_listing.Listing() - asyncio.run(items_listing.walk("tok", [FOLDER], out, pace_s=0, **kw)) - return out - - -def test_a_walk_stops_at_its_depth_bound_and_says_so(drive: _Drive) -> None: - chain = [FOLDER] + [f"level{n}aaaaaaa" for n in range(domain.MAX_DEPTH + 1)] - drive.children = {parent: [child] for parent, child in zip(chain, chain[1:], strict=False)} - walked = _walk() - assert len(walked.folders) == domain.MAX_DEPTH + 1 and walked.whole and walked.walk_cut - - -def test_a_shared_drive_is_listed_on_its_own_corpus(drive: _Drive) -> None: - drive.files = [{"id": "f1", "name": "a", "mimeType": DOCS, "driveId": DRIVE}] - item = {"type": "shared_drive", "id": DRIVE} - listing = asyncio.run(items_listing.list_items("tok", [item], ["docs"], pace_s=0)) - assert [f["id"] for f in listing.files] == ["f1"] - [request] = _listings(drive) - assert request.url.params["driveId"] == DRIVE and request.url.params["corpora"] == "drive" - - -def test_a_shared_drive_the_account_left_lists_nothing_and_says_nothing_is_absent( - drive: _Drive, -) -> None: - drive.missing = {DRIVE} - item = {"type": "shared_drive", "id": DRIVE} - listing = asyncio.run(items_listing.list_items("tok", [item], ["docs"], pace_s=0)) - assert listing.files == [] and listing.lost_item and listing.notes == ["item 0: http_404"] - - -def test_single_files_are_read_as_listed_and_a_missing_one_is_noted(drive: _Drive) -> None: - drive.files = [ - {"id": FILE, "name": "a", "mimeType": DOCS, "modifiedTime": "2026-01-02T00:00:00.000Z"}, - {"id": "sheet1aaaaaa", "name": "s", "mimeType": "application/vnd.google-apps.spreadsheet"}, - ] - items = [ - {"type": "file", "id": FILE}, - {"type": "file", "id": "gone1aaaaaaa"}, - {"type": "file", "id": "sheet1aaaaaa"}, - ] - listing = asyncio.run(items_listing.list_items("tok", items, ["docs"], pace_s=0)) - assert [f["id"] for f in listing.files] == [FILE] - assert listing.notes[0] == "item 1: http_404" and listing.notes[1].startswith("item 2:") - # An incremental turn lists a file only once it changed after the stamp. - later = asyncio.run( - items_listing.list_items( - "tok", items[:1], ["docs"], modified_after="2026-01-03T00:00:00.000Z", pace_s=0 - ) - ) - assert later.files == [] - - -def test_a_filter_lists_with_its_own_query(drive: _Drive) -> None: - item = {"type": "filter", "name_contains": "plan", "in": FOLDER, "kinds": ["docs", "pdf"]} - drive.files = [{"id": "f1", "name": "plan", "mimeType": DOCS, "parents": [FOLDER]}] - listing = asyncio.run(items_listing.list_items("tok", [item], ["docs", "slides"], pace_s=0)) - assert [f["id"] for f in listing.files] == ["f1"] - [request] = _listings(drive) - # The filter's kinds narrow the source's include: pdf is not in it, slides not asked. - assert f"mimeType = '{DOCS}'" in request.url.params["q"] - assert "pdf" not in request.url.params["q"] and "presentation" not in request.url.params["q"] - - -@pytest.mark.parametrize( - ("state", "reached"), - [ - ({"parents": [FOLDER], "mimeType": DOCS}, True), - ({"parents": ["elsewhere"], "mimeType": DOCS}, False), - ({"parents": ["elsewhere"], "driveId": DRIVE, "mimeType": DOCS}, True), - ({"parents": [FOLDER], "mimeType": "application/pdf"}, False), - ({"parents": ["x"], "name": "Q3 Plan", "mimeType": DOCS}, True), - ({"parents": ["x"], "name": "Budget", "mimeType": DOCS}, False), - ], -) -def test_what_the_items_reach(state: dict[str, Any], reached: bool) -> None: - listing = items_listing.Listing( - folders={FOLDER}, - drives={DRIVE}, - filters=[({"type": "filter", "name_contains": "plan"}, [DOCS])], - mime_types=[DOCS], - ) - assert listing.reaches("some-file", state) is reached - - -def test_a_file_item_is_reached_wherever_it_lives() -> None: - listing = items_listing.Listing(file_ids={FILE}, mime_types=[DOCS]) - assert listing.reaches(FILE, {"parents": ["elsewhere"], "mimeType": DOCS}) - - -# ---- the probe ------------------------------------------------------------------- - - -def test_a_probe_checks_the_twenty_items_added_last() -> None: - items = [{"type": "file", "id": f"{FILE}{n:02d}"} for n in range(25)] - assert source_probes.sample(items) == items[5:] - assert source_probes.sample(items[:3]) == items[:3] - - -def test_a_recursive_folder_that_is_a_shared_drive_s_root_comes_back_as_the_drive( - drive: _Drive, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _token(account: Any) -> str: - return "tok" - - monkeypatch.setattr(gdrive, "access_token", _token) - root = {"id": DRIVE, "mimeType": "application/vnd.google-apps.folder", "driveId": DRIVE} - drive.files = [root] - key = '{"type": "service_account", "client_email": "a@b", "private_key": "k"}' - - def probe(item: dict[str, Any]) -> list[dict[str, Any]]: - found = asyncio.run(source_probes.probe("gdrive", {"include": ["docs"]}, key, items=[item])) - return found.items - - assert probe(_folder(DRIVE, recursive=True)) == [{"type": "shared_drive", "id": DRIVE}] - # Not recursive, it reads the root's own files, as a folder: nothing widens. - assert probe(_folder(DRIVE)) == [_folder(DRIVE)] - - -def test_a_project_s_short_id_is_resolved_to_its_uuid(monkeypatch: pytest.MonkeyPatch) -> None: - asked: list[list[str]] = [] - - async def _ids(api_key: str, slugs: list[str]) -> dict[str, str]: - asked.append(slugs) - return {"1a2b3c4d5e6f": PROJECT} - - monkeypatch.setattr(linear, "project_ids", _ids) - items = [{"type": "project", "slug_id": "1a2b3c4d5e6f"}] - assert asyncio.run(source_probes.resolve("linear", items, "key")) == [ - {"type": "project", "id": PROJECT} - ] - with pytest.raises(source_probes.SourceUnreachable, match="ffffffffffff"): - asyncio.run( - source_probes.resolve("linear", [{"type": "project", "slug_id": "ffffffffffff"}], "k") - ) - - -def test_the_tracker_lookup_sends_short_ids_as_variables(monkeypatch: pytest.MonkeyPatch) -> None: - sent: list[dict[str, Any]] = [] - - def _answer(request: httpx.Request) -> httpx.Response: - sent.append(json.loads(request.content)) - nodes = [{"id": PROJECT, "slugId": "1a2b3c4d5e6f"}, {"id": "bad", "slugId": "x"}] - return httpx.Response(200, json={"data": {"projects": {"nodes": nodes}}}) - - client = httpx.AsyncClient(transport=httpx.MockTransport(_answer)) - monkeypatch.setattr(linear, "get_client", lambda: client) - found = asyncio.run(linear.project_ids("lin_api_key123", ["1a2b3c4d5e6f"])) - assert found == {"1a2b3c4d5e6f": PROJECT} - assert sent[0]["variables"]["slugs"] == ["1a2b3c4d5e6f"] - assert "1a2b3c4d5e6f" not in sent[0]["query"] - - -def test_a_walk_the_pass_ran_out_for_leaves_the_listing_incomplete(drive: _Drive) -> None: - drive.children = {FOLDER: ["sub1aaaaaaaaa"]} - listing = asyncio.run( - items_listing.list_items( - "tok", [_folder(recursive=True)], ["docs"], pace_s=0, out_of_time=lambda: True - ) - ) - # Only the folder itself is listed, and the turn keeps its stamp to list again. - assert listing.folders == {FOLDER} and listing.ran_out - - -def test_no_item_is_listed_once_the_pass_runs_out(drive: _Drive) -> None: - items = [{"type": "file", "id": FILE}, {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"}] - listing = asyncio.run( - items_listing.list_items("tok", items, ["docs"], pace_s=0, out_of_time=lambda: True) - ) - # Neither the file's metadata nor the drive is asked for. - assert not [r for r in drive.requests if FILE in r.url.path or "driveId" in r.url.params] - assert listing.files == [] and listing.ran_out - - -def test_recursive_folders_are_walked_together_under_one_bound( - drive: _Drive, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(items_listing, "MAX_WALK_FOLDERS", 3) - roots = [f"root{n}aaaaaaaaa" for n in range(4)] - drive.children = {r: [f"{r}kid"] for r in roots} - listing = asyncio.run( - items_listing.list_items( - "tok", [_folder(r, recursive=True) for r in roots], ["docs"], pace_s=0 - ) - ) - # One subfolder query for the four roots' first level, and the bound is the source's. - assert ( - sum( - "application/vnd.google-apps.folder" in r.url.params.get("q", "") - for r in _listings(drive) - ) - == 1 - ) - assert len(listing.folders) == 4 + 3 and listing.walk_cut - - -def test_a_tree_exactly_as_deep_as_the_bound_is_not_cut(drive: _Drive) -> None: - chain = [FOLDER] + [f"level{n}aaaaaaa" for n in range(domain.MAX_DEPTH)] - drive.children = {parent: [child] for parent, child in zip(chain, chain[1:], strict=False)} - walked = _walk() - # Every level is read and the last holds no folder: nothing was left unread. - assert len(walked.folders) == domain.MAX_DEPTH + 1 - assert walked.whole and not walked.ran_out - assert not walked.walk_cut - - -def test_a_walk_stops_between_levels_once_the_pass_runs_out(drive: _Drive) -> None: - drive.children = {FOLDER: ["sub1aaaaaaaaa"], "sub1aaaaaaaaa": ["sub2aaaaaaaaa"]} - asked: list[int] = [] - - def out_of_time() -> bool: - asked.append(1) - return len(asked) > 1 - - walked = _walk(out_of_time=out_of_time) - # The first level is read, the second is not, and the walk says it ran out. - assert walked.folders == {FOLDER, "sub1aaaaaaaaa"} and walked.ran_out and not walked.walk_cut - - -def test_a_walk_the_pass_runs_out_for_at_its_depth_bound_asks_no_more(drive: _Drive) -> None: - chain = [FOLDER] + [f"level{n}aaaaaaa" for n in range(domain.MAX_DEPTH + 1)] - drive.children = {parent: [child] for parent, child in zip(chain, chain[1:], strict=False)} - asked: list[int] = [] - - def out_of_time() -> bool: - asked.append(1) - return len(asked) > domain.MAX_DEPTH - - queries = len(_listings(drive)) - walked = _walk(out_of_time=out_of_time) - # Every level is read; the check below the last is not, and the walk says it ran out. - assert len(walked.folders) == domain.MAX_DEPTH + 1 and walked.ran_out - assert not walked.walk_cut - assert len(_listings(drive)) - queries == domain.MAX_DEPTH - - -@pytest.mark.parametrize("answer", [{"nextPageToken": "p2"}, {"incompleteSearch": True}]) -def test_any_subfolder_takes_an_unsure_answer_as_holding_one( - drive: _Drive, answer: dict[str, Any] -) -> None: - # The page holds no folder, but the store did not say the parent holds none. - assert asyncio.run(gdrive.any_subfolder("tok", [FOLDER], set())) is False - drive.folder_extra = answer - assert asyncio.run(gdrive.any_subfolder("tok", [FOLDER], set())) is True - - -def test_the_check_below_the_last_level_reads_one_page_per_batch(drive: _Drive) -> None: - level = [f"wide{n:03d}aaaaaaa" for n in range(120)] - drive.children = {level[60]: ["deeperaaaaaaa"]} - before = len(_listings(drive)) - # 50 parents per query: the second batch finds one and the third is never asked. - assert asyncio.run(gdrive.any_subfolder("tok", level, set(level))) is True - assert len(_listings(drive)) - before == 2 - - -def test_a_probe_names_a_file_of_a_kind_the_source_does_not_read( - drive: _Drive, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _token(account: Any) -> str: - return "tok" - - monkeypatch.setattr(gdrive, "access_token", _token) - drive.files = [{"id": FILE, "mimeType": "application/vnd.google-apps.spreadsheet"}] - key = '{"type": "service_account", "client_email": "a@b", "private_key": "k"}' - item = {"type": "file", "id": FILE} - found = asyncio.run(source_probes.probe("gdrive", {"include": ["docs"]}, key, items=[item])) - assert found.foreign == {FILE: "application/vnd.google-apps.spreadsheet"} - assert found.documents == 0 - - -def test_the_file_lookup_and_listings_ask_the_store_for_no_person(drive: _Drive) -> None: - drive.files = [{"id": FILE, "mimeType": DOCS, "parents": [FOLDER]}] - asyncio.run(gdrive.file_state("tok", FILE)) - # A namespace source keeps no person's address: no owner, sharing or user field is - # read by the retirement lookup, a listing or a probe's first page. Only a mirrored - # listing reads the permissions, and never the owners or a user's name. - for fields in (drive.requests[-1].url.params["fields"], gdrive.LISTED, gdrive._PAGE_FIELDS): - assert not any(word in fields.lower() for word in ("owner", "permission", "user")) - mirrored = gdrive.LISTED_WITH_PERMISSIONS.lower() - assert not any(word in mirrored for word in ("owners", "displayname", "lastmodifyinguser")) - - -def test_the_tracker_lookup_refuses_more_than_one_page_of_short_ids() -> None: - too_many = [f"{n:012x}" for n in range(linear.PAGE_SIZE + 1)] - with pytest.raises(ValueError, match="at most 50 short ids"): - asyncio.run(linear.project_ids("lin_api_key123", too_many)) - - -def test_one_update_s_short_ids_fit_one_tracker_page() -> None: - # An update looks up its added and its removed short ids together. - assert 2 * domain.max_items("linear") <= linear.PAGE_SIZE - - -def test_a_lookup_answer_without_the_projects_list_is_an_error( - monkeypatch: pytest.MonkeyPatch, -) -> None: - def _answer(request: httpx.Request) -> httpx.Response: - return httpx.Response(200, json={"data": {"projects": None}}) - - client = httpx.AsyncClient(transport=httpx.MockTransport(_answer)) - monkeypatch.setattr(linear, "get_client", lambda: client) - with pytest.raises(linear.LinearError): - asyncio.run(linear.project_ids("lin_api_key123", ["1a2b3c4d5e6f"])) - - -@pytest.mark.parametrize( - ("model", "field", "extra"), - [ - ( - models_sources.KnowledgeSourceAddInput, - "links", - {"name": "d", "kind": "gdrive", "credential": "k"}, - ), - (models_sources.KnowledgeSourceUpdateInput, "add_links", {"name": "d"}), - (models_sources.KnowledgeSourceUpdateInput, "remove_links", {"name": "d"}), - (models_sources.KnowledgeSourceParseLinksInput, "links", {}), - ], -) -def test_every_link_field_takes_links_up_to_the_wire_bound( - model: type[pydantic.BaseModel], field: str, extra: dict[str, Any] -) -> None: - longest = "https://" + "a" * (models_sources.MAX_LINK_CHARS - len("https://")) - model(org="o", namespace="n", **extra, **{field: [longest]}) - with pytest.raises(pydantic.ValidationError): - model(org="o", namespace="n", **extra, **{field: [longest + "a"]}) diff --git a/tests/unit/test_knowledge_source_mirror_pass.py b/tests/unit/test_knowledge_source_mirror_pass.py index 9711a57036..a59f4a5979 100644 --- a/tests/unit/test_knowledge_source_mirror_pass.py +++ b/tests/unit/test_knowledge_source_mirror_pass.py @@ -1,343 +1,91 @@ -"""The mirrored sources' share of a sync pass: they run first, apart from the namespace -sources' document bound, rotate, keep their state under the mirror, attribute their -model calls to the mirror, and read their lists on from a cursor -(docs/architecture/document-sources.md, Every complete listing reads the lists again).""" +"""Generic MCP turns keep private sync state under the source's immutable ID.""" -from __future__ import annotations - -import asyncio import json -from datetime import datetime -from typing import Any +from dataclasses import replace +from unittest.mock import AsyncMock import pytest -from server.clients import gdrive -from server.code.app.index.pass_budget import PassBudget -from server.knowledge.app import source_sync, source_sync_mirror -from server.knowledge.store import mirrors as mirror_store -from server.llm import customer -from server.settings import settings -from tests.unit.test_knowledge_source_sync import DOCS, _detail, _file, _source -from tests.unit.test_knowledge_source_sync import world as world # the fixture -from tests.unit.test_knowledge_source_sync_mirror import MIRROR, READERS, _mirrored, _own -from tests.unit.test_knowledge_source_sync_mirror import mirror as mirror # the fixture - - -def _pass(world: Any, *sources: Any) -> Any: - world.sources = list(sources) - return asyncio.run(source_sync.run_sync()) - - -def _files(n: int, **kw: Any) -> list[dict[str, Any]]: - return [_file(f"doc{i}", DOCS, f"2026-01-0{i}T00:00:00.000Z", **kw) for i in range(1, n + 1)] - - -def test_the_mirrored_sources_run_first_under_their_own_document_bound( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 3) - monkeypatch.setattr(settings, "knowledge_source_mirror_documents_per_pass", 1) - world.files = _files(3, permissions=READERS) - result = _pass(world, _source(name="notes"), _mirrored()) - homes = [written.namespace for written, _ in world.upserts] - # The mirror's one document first, then every namespace document: the mirror's size - # takes nothing from the namespace sources' bound. - assert homes == [MIRROR, *[_source().namespace] * 3] - assert result.sources == 2 and result.cut - - -def test_the_list_reads_leave_time_for_the_new_files( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = _files(1) - _pass(world, _mirrored()) # doc1 stored, its list read with its write - - class _Spent(PassBudget): - def exhausted(self) -> bool: - return True # the list reads' half of the leg is gone at once - - monkeypatch.setattr(source_sync_mirror, "PassBudget", _Spent) - world.files = [*_files(1), _file("doc9", DOCS, "2026-01-09T00:00:00.000Z")] - before = len(world.upserts) - _pass(world, _mirrored()) - assert [w.source_uri.split("/")[-2] for w, _ in world.upserts[before:]] == ["doc9"] - assert _own(world)["lists_cursor"].endswith("/doc1/edit#id-decks") - - -def test_the_mirrored_source_synced_longest_ago_goes_first_even_past_a_request( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - order: list[str] = [] - real = source_sync._sync_one - - async def _seen(src: Any, *a: Any) -> Any: - order.append(src.name) - return await real(src, *a) - - monkeypatch.setattr(source_sync, "_sync_one", _seen) - - def row(**detail: str) -> dict[str, str]: - return {"state_value": "", "detail": json.dumps(detail)} - - world.states = { - "a": row(last_synced_at="2026-01-03T00:00:00+00:00"), - "b": row(last_synced_at="2026-01-01T00:00:00+00:00"), - "c": row(last_synced_at="2026-01-05T00:00:00+00:00", requested_at="2026-01-06T00:00:00"), +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.app import source_sync as sync +from tests.unit.test_mcp_source_sync import MIRROR +from tests.unit.test_mcp_source_sync import harness as harness + +pytestmark = pytest.mark.asyncio + + +async def test_a_mirrored_source_s_namespace_row_holds_only_its_codes(harness, monkeypatch): + src = replace(harness.source, mirror=MIRROR) + read = { + "state_value": "", + "detail": json.dumps( + { + "requested_at": "request", + "full": True, + "file_waits": {"private-id": ["r", 1, "x"]}, + "error": "private detail", + } + ), } - _pass(world, *(_mirrored(name=n) for n in "abc")) - # A request waits its turn: a source cut every turn keeps its request, and going - # first on it would starve the others. - assert order == ["b", "a", "c"] - - -def test_a_mirrored_source_s_namespace_row_holds_only_its_codes( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _fails(token: str, file_id: str, **kw: Any) -> Any: - raise gdrive.VendorError("503") - - monkeypatch.setattr(gdrive, "file_permissions", _fails) - world.files = _files(2) # listed without lists: each needs a read, and each fails - # An N-1 turn left its whole state in the namespace row; this turn drops it. - left = {"requested_at": "t", "file_waits": {"doc1": ["r", 1, "x"]}, "error": "export"} - world.states["decks"] = {"state_value": "", "detail": json.dumps(left)} - _pass(world, _mirrored()) - shown = _detail(world) - assert set(shown) == {"last_synced_at", "status"} # the request was answered - own = _own(world) - assert own["changed"] == 2 and own["error"].startswith("permissions:") - - -def test_a_source_added_again_under_the_name_inherits_no_state(world: Any, mirror: Any) -> None: - world.files = _files(1, permissions=READERS) - revision = world.files[0]["modifiedTime"] - # The removed source gave the file up; its state is under its own id. - given_up = {"file_waits": {"doc1": [revision, 99, "export_failed"]}} - world.states["id-decks"] = {"state_value": "", "detail": json.dumps(given_up)} - _pass(world, _mirrored(source_id="id-again")) - assert [written.namespace for written, _ in world.upserts] == [MIRROR] - - -def test_a_mirrored_turn_attributes_model_calls_to_its_mirror( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - seen: list[str] = [] - named: list[tuple[str, str]] = [] - real = source_sync.sync_file - - async def _attributed(*a: Any, **kw: Any) -> Any: - seen.append(customer.attribution().namespace) - return await real(*a, **kw) - - def _identity(name: str, *, org: str = "", namespace: str = "", **kw: Any) -> None: - named.append((name, namespace)) - - monkeypatch.setattr(source_sync, "sync_file", _attributed) - monkeypatch.setattr(source_sync_mirror, "set_worker_identity", _identity) - world.files = _files(1, permissions=READERS) - _pass(world, _mirrored()) - assert seen == [MIRROR] and named == [(source_sync.WORKER, MIRROR)] - - -@pytest.fixture -def slow_lists(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: - """Each file's list read separately, and the deadline after `per_turn` of them.""" - reads: dict[str, Any] = {"per_turn": 0, "now": 0, "ids": [], "rows": []} - - async def _read(token: str, file_id: str, **kw: Any) -> Any: - reads["now"] += 1 - reads["ids"].append(file_id) - return READERS - - async def _listing(org: str, ns: str, source_id: str, name: str, started: Any) -> None: - reads["rows"].append(started) - - def _exhausted(self: PassBudget) -> bool: - return bool(reads["per_turn"]) and reads["now"] >= reads["per_turn"] - - monkeypatch.setattr(gdrive, "file_permissions", _read) - monkeypatch.setattr(mirror_store, "record_listing", _listing) - monkeypatch.setattr(PassBudget, "exhausted", _exhausted) - return reads - - -def _turn_with(world: Any, reads: dict[str, Any], per_turn: int) -> None: - reads.update(per_turn=per_turn, now=0) - reads["ids"].clear() - world.files = _files(4) # listed without lists every time - _pass(world, _mirrored()) - - -def test_the_lists_go_on_from_the_cursor_and_the_cycle_s_row_lands_past_the_wrap( - world: Any, mirror: Any, slow_lists: dict[str, Any] -) -> None: - _turn_with(world, slow_lists, 0) # every file written, each with its list read - assert len(slow_lists["rows"]) == 1 - first = slow_lists["rows"][-1] - _turn_with(world, slow_lists, 2) # doc1 and doc2 read; doc3 is where it stopped - assert slow_lists["ids"] == ["doc1", "doc2"] and len(slow_lists["rows"]) == 1 - began = datetime.fromisoformat(_own(world)["lists_since"]) - assert began > first and _own(world)["lists_cursor"].endswith("/doc3/edit#id-decks") - _turn_with(world, slow_lists, 3) # doc3, doc4, then doc1 past the wrap: the cycle is done - assert slow_lists["ids"] == ["doc3", "doc4", "doc1"] - assert slow_lists["rows"][-1] == began # the row carries the start of the cycle - assert _own(world)["lists_cursor"].endswith("/doc2/edit#id-decks") - - -def test_a_turn_that_vouches_for_nothing_keeps_the_cycle( - world: Any, mirror: Any, slow_lists: dict[str, Any], monkeypatch: pytest.MonkeyPatch -) -> None: - _turn_with(world, slow_lists, 0) - _turn_with(world, slow_lists, 2) - kept = (_own(world)["lists_cursor"], _own(world)["lists_since"]) - - async def _owed(org: str, namespace: str, uri_suffix: str) -> str: - return "owed" - - monkeypatch.setattr(source_sync.documents, "publications_owed", _owed) - rows = len(slow_lists["rows"]) - _turn_with(world, slow_lists, 0) # every list read, but a write was not in ClickHouse - assert len(slow_lists["rows"]) == rows - assert (_own(world)["lists_cursor"], _own(world)["lists_since"]) == kept - - -def test_the_namespace_sources_keep_the_pass_s_own_budget_after_the_mirrors( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - budgets: dict[str, PassBudget] = {} - deadlines: dict[str, float] = {} - real = source_sync._sync_one - - async def _seen(src: Any, state: Any, run: Any, result: Any) -> Any: - budgets[src.name] = run.budget - deadlines[src.name] = source_sync._read_deadline(run) - return await real(src, state, run, result) - - monkeypatch.setattr(source_sync, "_sync_one", _seen) - whole = source_sync._budget() - monkeypatch.setattr(source_sync, "_budget", lambda: whole) - world.files = _files(1, permissions=READERS) - _pass(world, _source(name="notes"), _mirrored()) - span = whole.stop_after - whole.started - assert budgets["decks"].stop_after <= budgets["decks"].started + span / 3 + 1e-6 - assert budgets["notes"] is whole # its start and end, whatever the mirrors used - pass_end = whole.started + float(settings.knowledge_source_sync_max_pass_seconds) - assert deadlines["notes"] == pass_end - source_sync._MINE_MARGIN_S - - -def test_a_cycle_begun_at_a_wrap_keeps_its_start_until_its_own_wrap( - world: Any, mirror: Any, slow_lists: dict[str, Any] -) -> None: - for per_turn in (0, 2, 3): # as above: the third turn wraps and begins a cycle at doc2 - _turn_with(world, slow_lists, per_turn) - began = _own(world)["lists_since"] - rows = len(slow_lists["rows"]) - _turn_with(world, slow_lists, 1) # doc2 read, doc3 left: before this cycle's wrap - assert slow_lists["ids"] == ["doc2"] and len(slow_lists["rows"]) == rows - assert _own(world)["lists_since"] == began - _turn_with(world, slow_lists, 3) # doc3, doc4, doc1, then doc2 past the wrap - assert slow_lists["ids"] == ["doc3", "doc4", "doc1"] - assert slow_lists["rows"][-1] == datetime.fromisoformat(began) - - -def test_a_turn_that_fails_before_it_knows_its_mirror_leaves_the_mirror_s_state( - world: Any, mirror: Any, slow_lists: dict[str, Any] -) -> None: - _turn_with(world, slow_lists, 0) - _turn_with(world, slow_lists, 2) - kept = _own(world) - slow_lists.update(per_turn=0, now=0) - world.fail_listing = 401 - world.sources = [_mirrored()] - asyncio.run(source_sync.run_sync()) - assert _own(world) == kept - assert _detail(world)["status"] == "credential_invalid" - - -def test_a_publication_owed_at_the_read_moves_no_cursor( - world: Any, mirror: Any, slow_lists: dict[str, Any], monkeypatch: pytest.MonkeyPatch -) -> None: - _turn_with(world, slow_lists, 0) - answers = iter(["owed", ""]) # owed when the copies are read, settled by the end - - async def _owed(org: str, namespace: str, uri_suffix: str) -> str: - return next(answers) - - monkeypatch.setattr(source_sync.documents, "publications_owed", _owed) - _turn_with(world, slow_lists, 2) # stops before the wrap: it would begin a cycle - assert _own(world).get("lists_cursor", "") == "" - - -def test_a_publication_parked_by_the_end_keeps_the_cycle( - world: Any, mirror: Any, slow_lists: dict[str, Any], monkeypatch: pytest.MonkeyPatch -) -> None: - _turn_with(world, slow_lists, 0) - _turn_with(world, slow_lists, 2) - kept = (_own(world)["lists_cursor"], _own(world)["lists_since"]) - answers = iter(["", "parked"]) # clear when the copies are read, parked by the end - - async def _owed(org: str, namespace: str, uri_suffix: str) -> str: - return next(answers) - - monkeypatch.setattr(source_sync.documents, "publications_owed", _owed) - rows = len(slow_lists["rows"]) - _turn_with(world, slow_lists, 1) # doc3 read, doc4 left: it would move the cursor on - assert len(slow_lists["rows"]) == rows - assert (_own(world)["lists_cursor"], _own(world)["lists_since"]) == kept - - -def test_a_turn_that_reads_every_list_mid_cycle_lands_its_own_start_and_ends_the_cycle( - world: Any, mirror: Any, slow_lists: dict[str, Any] -) -> None: - _turn_with(world, slow_lists, 0) - _turn_with(world, slow_lists, 2) - began = datetime.fromisoformat(_own(world)["lists_since"]) - _turn_with(world, slow_lists, 0) # time for every list - assert slow_lists["rows"][-1] > began - assert (_own(world)["lists_cursor"], _own(world)["lists_since"]) == ("", "") - - -def test_a_turn_whose_list_reads_stop_still_retires_a_gone_file_at_the_full_interval( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = _files(4) - _pass(world, _mirrored()) # each list read with its write - - class _Spent(PassBudget): - def exhausted(self) -> bool: - return True # the list reads' half of the leg is gone at once - - monkeypatch.setattr(source_sync_mirror, "PassBudget", _Spent) - # A full sync asked for, and doc4 gone from the store. - asked = {"requested_at": "t", "full": True} - world.states["decks"] = {"state_value": "", "detail": json.dumps(asked)} - world.files = _files(3) - result = _pass(world, _mirrored()) - assert result.removed == 0 and not any("/doc4/" in uri for uri in world.docs) - assert "full_listed_at" in _own(world) and _own(world)["lists_cursor"] - - -def test_the_list_reads_get_half_of_what_is_left_of_the_mirrors_share( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = _files(1) - _pass(world, _mirrored()) - legs: list[PassBudget] = [] - lists: list[PassBudget] = [] - real = source_sync._sync_one - - async def _seen(src: Any, state: Any, run: Any, result: Any) -> Any: - legs.append(run.budget) - return await real(src, state, run, result) - - class _Kept(PassBudget): - def __init__(self, started: float, stop_after: float) -> None: - super().__init__(started, stop_after) - lists.append(self) - - monkeypatch.setattr(source_sync, "_sync_one", _seen) - monkeypatch.setattr(source_sync_mirror, "PassBudget", _Kept) - _pass(world, _mirrored()) - [leg], [read] = legs, lists - assert read.stop_after - read.started == pytest.approx((leg.stop_after - read.started) / 2) + monkeypatch.setattr(sync.store, "read_states", AsyncMock(return_value={src.name: read})) + writes = AsyncMock() + monkeypatch.setattr(sync.store, "write_state", writes) + turn = sync.TurnResult(changed=2, mirror=MIRROR) + turn.error = "private permission failure" + async with accounts.account_lease(src.org, src.owner_subject, src.connection_slot): + await sync._write_state(src, read, turn) + assert writes.await_count == 2 + private, public = writes.await_args_list + assert private.args == (src.org, MIRROR, src.source_id) + assert public.args == (src.org, src.namespace, src.name) + assert private.kwargs["detail"]["changed"] == 2 + assert private.kwargs["detail"]["error"] == "private permission failure" + assert set(public.kwargs["detail"]) == {"last_synced_at", "status"} + assert not any( + secret in json.dumps(public.kwargs) + for secret in ("private-id", "private detail", "private permission failure") + ) + assert harness.locks == [] + + +async def test_a_source_added_again_under_the_name_inherits_no_state(harness, monkeypatch): + old = harness.source.source_id + src = replace(harness.source, source_id="22222222-2222-4222-8222-222222222222", mirror=MIRROR) + harness.source = src + monkeypatch.setattr(sync.store, "read_states", AsyncMock(return_value={})) + reads = AsyncMock(return_value={}) + monkeypatch.setattr(sync, "mirror_state", reads) + writes = AsyncMock() + monkeypatch.setattr(sync.store, "write_state", writes) + async with accounts.account_lease(src.org, src.owner_subject, src.connection_slot): + await sync._write_state(src, {}, sync.TurnResult(mirror=MIRROR)) + reads.assert_awaited_once_with(src, MIRROR) + assert writes.await_args_list[0].args == (src.org, MIRROR, src.source_id) + assert all(old not in call.args for call in writes.await_args_list) + assert all("file_waits" not in call.kwargs["detail"] for call in writes.await_args_list) + + +async def test_a_turn_that_fails_before_it_knows_its_mirror_leaves_the_mirror_s_state( + harness, monkeypatch +): + src = harness.source + read = {"state_value": "", "detail": json.dumps({"requested_at": "request", "full": True})} + monkeypatch.setattr(sync.store, "read_states", AsyncMock(return_value={src.name: read})) + reads = AsyncMock(side_effect=AssertionError("an unknown mirror must not be read")) + monkeypatch.setattr(sync, "mirror_state", reads) + writes = AsyncMock() + monkeypatch.setattr(sync.store, "write_state", writes) + turn = sync.TurnResult() + turn.fail("unavailable", "private transport error") + async with accounts.account_lease(src.org, src.owner_subject, src.connection_slot): + await sync._write_state(src, read, turn) + reads.assert_not_awaited() + writes.assert_awaited_once() + call = writes.await_args + assert call.args == (src.org, src.namespace, src.name) + assert call.kwargs["detail"]["status"] == "unavailable" + assert {k: call.kwargs["detail"][k] for k in ("requested_at", "full")} == { + "requested_at": "request", + "full": True, + } + assert "private transport error" not in json.dumps(call.kwargs) diff --git a/tests/unit/test_knowledge_source_recordings.py b/tests/unit/test_knowledge_source_recordings.py index 66ca76b846..3ce621072d 100644 --- a/tests/unit/test_knowledge_source_recordings.py +++ b/tests/unit/test_knowledge_source_recordings.py @@ -24,7 +24,8 @@ from server.knowledge.domain import sources as domain from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, KnowledgeSource from server.knowledge.domain.transcripts import Entry, parse_vtt, transcript_markdown -from tests.unit.test_knowledge_source_sync import NS, ORG, _detail, _World, world # noqa: F401 +from tests.unit.test_knowledge_source_sync import NS, ORG, _detail, _World +from tests.unit.test_knowledge_source_sync import source_world as source_world MEET_KEY = json.dumps( {"type": "authorized_user", "client_id": "c", "client_secret": "s", "refresh_token": "r"} @@ -124,7 +125,12 @@ def _zoom_recording(**file: Any) -> dict[str, Any]: @pytest.fixture -def stores(world: _World, monkeypatch: pytest.MonkeyPatch) -> _Stores: # noqa: F811 +def world(source_world: _World) -> _World: + return source_world + + +@pytest.fixture +def stores(world: _World, monkeypatch: pytest.MonkeyPatch) -> _Stores: s = _Stores() client = httpx.AsyncClient(transport=httpx.MockTransport(s.answer)) monkeypatch.setattr(recording, "get_client", lambda: client) @@ -295,7 +301,7 @@ def _quota(request: httpx.Request) -> httpx.Response: def test_zoom_transcripts_keep_import_metadata_and_a_recent_one_is_checked_again( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -354,15 +360,13 @@ def test_retired_or_unknown_provider_refuses_every_dispatch_before_transport( asyncio.run(source_sync_recording.transcript(session, {"id": "old-record"}, max_bytes=1000)) with pytest.raises(source_probes.SourceUnreachable, match=expected): asyncio.run( - source_probes.probe( - "recording", {"provider": provider, "ids": [SPACE]}, MEET_KEY, items=[] - ) + source_probes.probe("recording", {"provider": provider, "ids": [SPACE]}, MEET_KEY) ) assert stores.requests == [] def test_a_settled_recording_without_a_transcript_is_given_up_until_a_full_listing( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -381,7 +385,7 @@ def test_a_settled_recording_without_a_transcript_is_given_up_until_a_full_listi @pytest.mark.parametrize("hours", [3, 50]) def test_unrecorded_instances_ahead_of_a_recorded_one_do_not_hold_it_back( - world: _World, # noqa: F811 + world: _World, stores: _Stores, monkeypatch: pytest.MonkeyPatch, hours: float, @@ -400,7 +404,7 @@ def test_unrecorded_instances_ahead_of_a_recorded_one_do_not_hold_it_back( def test_a_recording_source_at_its_bound_holds_new_ones_and_unrecorded_take_no_room( - world: _World, # noqa: F811 + world: _World, stores: _Stores, monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -415,7 +419,7 @@ def test_a_recording_source_at_its_bound_holds_new_ones_and_unrecorded_take_no_r def test_a_recording_the_store_no_longer_lists_is_kept( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -430,7 +434,7 @@ def test_a_recording_the_store_no_longer_lists_is_kept( def test_a_meeting_the_account_lost_fails_the_turn_and_the_others_are_written( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: lost = "123456789" @@ -446,7 +450,7 @@ def test_a_meeting_the_account_lost_fails_the_turn_and_the_others_are_written( def test_zoom_instances_with_a_transcript_are_written_and_the_rest_given_up( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -481,7 +485,7 @@ def test_zoom_instances_with_a_transcript_are_written_and_the_rest_given_up( def test_a_refused_credential_a_wide_scope_or_a_rate_limit_is_the_turn_s( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -508,7 +512,7 @@ def test_the_probe_counts_recordings_and_refuses_an_unseen_id_or_a_wide_scope( {"uuid": "rec2", "start_time": second}, ] config = {"provider": "zoom", "ids": [MEETING]} - found = asyncio.run(source_probes.probe("recording", config, ZOOM_KEY, items=[])) + found = asyncio.run(source_probes.probe("recording", config, ZOOM_KEY)) assert (found.documents, found.sample) == ( 2, [ @@ -518,12 +522,12 @@ def test_the_probe_counts_recordings_and_refuses_an_unseen_id_or_a_wide_scope( ) stores.meeting_status = {MEETING: 404} with pytest.raises(source_probes.SourceUnreachable): - asyncio.run(source_probes.probe("recording", config, ZOOM_KEY, items=[])) + asyncio.run(source_probes.probe("recording", config, ZOOM_KEY)) with pytest.raises(source_probes.CredentialRefused): - asyncio.run(source_probes.probe("recording", config, "{}", items=[])) + asyncio.run(source_probes.probe("recording", config, "{}")) stores.scopes["zoom.us"] = "meeting:write:admin" with pytest.raises(source_probes.CredentialRefused): - asyncio.run(source_probes.probe("recording", config, ZOOM_KEY, items=[])) + asyncio.run(source_probes.probe("recording", config, ZOOM_KEY)) def test_a_session_never_shows_its_token() -> None: @@ -531,7 +535,7 @@ def test_a_session_never_shows_its_token() -> None: def test_a_zoom_full_listing_reads_the_last_thirty_days_and_keeps_older_documents( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -558,7 +562,7 @@ def test_a_vtt_speaker_name_reads_as_one_line(stores: _Stores) -> None: def test_a_meeting_the_account_may_not_read_is_lost_not_a_refused_credential( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: closed = "123456789" @@ -574,11 +578,11 @@ def test_a_meeting_the_account_may_not_read_is_lost_not_a_refused_credential( assert world.audits == [] config = {"provider": "zoom", "ids": [closed, MEETING]} with pytest.raises(source_probes.SourceUnreachable, match=f"meeting {closed}: http_403"): - asyncio.run(source_probes.probe("recording", config, ZOOM_KEY, items=[])) + asyncio.run(source_probes.probe("recording", config, ZOOM_KEY)) def test_a_401_on_a_meeting_after_the_token_exchange_is_the_turn_s_credential( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -595,7 +599,7 @@ def test_a_401_on_a_meeting_after_the_token_exchange_is_the_turn_s_credential( def test_a_401_on_recording_files_stops_the_turn( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -636,7 +640,7 @@ def _answer(request: httpx.Request) -> httpx.Response: def test_two_meeting_ids_listing_one_instance_write_it_once( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", ["123456789", MEETING], ZOOM_KEY)] @@ -649,7 +653,7 @@ def test_two_meeting_ids_listing_one_instance_write_it_once( def test_a_transcript_is_mined_for_decisions_by_the_same_leg( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] @@ -666,7 +670,7 @@ def test_a_transcript_is_mined_for_decisions_by_the_same_leg( def test_a_transcript_whose_address_is_taken_during_the_fetch_is_counted_skipped( - world: _World, # noqa: F811 + world: _World, stores: _Stores, ) -> None: world.sources = [_source("zoom", [MEETING], ZOOM_KEY)] diff --git a/tests/unit/test_knowledge_source_retirements.py b/tests/unit/test_knowledge_source_retirements.py index cdc601d15f..24b9b334ea 100644 --- a/tests/unit/test_knowledge_source_retirements.py +++ b/tests/unit/test_knowledge_source_retirements.py @@ -40,7 +40,7 @@ async def enqueue(src: Any) -> bool: async def forbidden(*args: Any, **kw: Any) -> int: raise AssertionError("a mirrored remove must not count documents") - monkeypatch.setattr(sources, "_queue_retirement", enqueue, raising=False) + monkeypatch.setattr(sources, "_queue_retirement", enqueue) monkeypatch.setattr(store, "count_documents", forbidden) out = asyncio.run( sources.handle_knowledge_source_remove( @@ -72,7 +72,7 @@ async def enqueue(src: Any) -> bool: queued.append(src.source_id) return True - monkeypatch.setattr(sources, "_queue_retirement", enqueue, raising=False) + monkeypatch.setattr(sources, "_queue_retirement", enqueue) assert asyncio.run(sources.deactivate_namespace_sources(ORG, NS)) == ["design-decks"] assert queued == [fake.rows[key].source_id] assert fake.rows[key].pending_delete diff --git a/tests/unit/test_knowledge_source_sync.py b/tests/unit/test_knowledge_source_sync.py index f5d6e3b40c..85f75a1b2b 100644 --- a/tests/unit/test_knowledge_source_sync.py +++ b/tests/unit/test_knowledge_source_sync.py @@ -1,8 +1,8 @@ -"""The document-source sync pass (server/knowledge/app/source_sync.py) over an -in-memory registry and document store and a shared-folder store answered by a -mock transport: what a first, an incremental and a full turn list, fetch, write -and retire, the stamp and status each leaves, and the bounds. Every response is -written here; none is a recording of real content.""" +"""Common source worker state, ownership and accounting over recording turns. + +Stores and recording inputs are local fixtures. The worker, recording turn, +write ownership checks, retirement and extraction bookkeeping run unchanged. +""" from __future__ import annotations @@ -12,85 +12,48 @@ import json import re from collections.abc import AsyncIterator -from datetime import datetime, timedelta from pathlib import Path from types import SimpleNamespace from typing import Any -import httpx import pytest -from server.clients import gdrive from server.code.app.index import repo_registry from server.core import leases from server.core.ch import sequential_reads_active -from server.core.errors import ValidationError from server.core.hashing import sha256_text from server.core.secrets_at_rest import seal -from server.knowledge.app import extractors, source_gdrive_items, source_sync, writes +from server.knowledge.app import source_sync, source_sync_recording, writes from server.knowledge.app import sources as source_ops -from server.knowledge.domain import access_list, convert -from server.knowledge.domain.extract.artifact import Artifact, Block, Coverage +from server.knowledge.domain import access_list from server.knowledge.domain.sources import ( MIRRORED_ACCESS, SYNC_WORKER_ACTOR, KnowledgeSource, - items_from_config, ) from server.knowledge.store import documents -from server.memory.domain.corpus_synthesis import ground_citations from server.memory.domain.provenance import pipeline_actor_var from server.observability import audit from server.settings import settings ORG, NS = "acme", "code-acme-app" -FOLDER = "1AbCdEfGhIjKlMnOp" -OTHER = "2QrStUvWxYzAbCdEf" -DOCS = "application/vnd.google-apps.document" -SLIDES = "application/vnd.google-apps.presentation" +DOCS = "text/plain" PDF = "application/pdf" -PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation" -DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -KEY = '{"type": "service_account", "client_email": "a@b", "private_key": "k"}' +KEY = "recording-fixture-credential" def _file(file_id: str, mime: str, modified: str, **kw: Any) -> dict[str, Any]: - kind = {DOCS: "document", SLIDES: "presentation"}.get(mime, "file") return { "id": file_id, "name": f"{file_id} title", - "mimeType": mime, "modifiedTime": modified, - "webViewLink": f"https://docs.example.com/{kind}/d/{file_id}/edit?usp=drivesdk", + "uri": f"https://docs.example.com/document/d/{file_id}/edit", **kw, } -DECK = { - "slides": [ - { - "pageElements": [ - { - "shape": { - "placeholder": {"type": "TITLE"}, - "text": { - "textElements": [{"textRun": {"content": "Why a planner pass\n"}}] - }, - } - }, - { - "shape": { - "text": {"textElements": [{"textRun": {"content": "The rewrite moves.\n"}}]} - } - }, - ] - } - ] -} - - class _World: - """The registry, sync state and documents, and what the folder store answers.""" + """The registry, sync state and stored document boundaries.""" def __init__(self) -> None: self.sources: list[KnowledgeSource] = [] @@ -99,23 +62,10 @@ def __init__(self) -> None: # Live documents by source_uri: {actor, tags, metadata}. self.docs: dict[str, dict[str, Any]] = {} self.files: list[dict[str, Any]] = [] - self.requests: list[httpx.Request] = [] + self.recording_lists: list[list[str]] = [] self.audits: list[dict[str, Any]] = [] self.upserts: list[Any] = [] - self.fail_listing: int = 0 - # Formats an extractor is configured for, and those its service declares. - self.routes: set[str] = {"pdf", "pptx", "docx"} - self.declared: set[str] = {"pdf", "pptx", "docx"} - self.extractor_down = False - self.extract_error: Exception | None = None - # Per-file extraction failures, by file id. - self.extract_errors: dict[str, Exception] = {} - self.capability_calls = 0 - self.incomplete_search = False - # Folders the account no longer sees; per-file answers that override the store's. - self.lost_folders: set[str] = set() - # A response, or a callable that answers (or raises) for that file. - self.file_answers: dict[str, Any] = {} + self.transcript_error: Exception | None = None # The extraction leg: each extract_document call (uri, actor, attribution), the # report it answers (or a callable that makes one, or an exception), the orgs # switched off (an exception: the switch unread), the namespaces over their cap @@ -192,42 +142,9 @@ async def source_documents(self, org: str, ns: str, tag: str) -> list[dict[str, async def count_documents(self, org: str, ns: str, tag: str) -> int: return len(await self.source_documents(org, ns, tag)) - # the folder store - def answer(self, request: httpx.Request) -> httpx.Response: - self.requests.append(request) - path = request.url.path - file_id = path.rstrip("/").split("/")[-1 if not path.endswith("/export") else -2] - if file_id in self.file_answers: - answer = self.file_answers[file_id] - return answer(request) if callable(answer) else answer - if path in (f"/drive/v3/files/{FOLDER}", f"/drive/v3/files/{OTHER}"): - if file_id in self.lost_folders: - return httpx.Response(404) - return httpx.Response(200, json={"mimeType": "application/vnd.google-apps.folder"}) - if path == "/drive/v3/files": - if self.fail_listing: - return httpx.Response(self.fail_listing, json={"error": {"status": "x"}}) - q = request.url.params["q"] - after = q.split("modifiedTime > '")[1].rstrip("'") if "modifiedTime >" in q else "" - files = [ - f - for f in self.files - if f["modifiedTime"] > after and f"mimeType = '{f['mimeType']}'" in q - ] - return httpx.Response( - 200, json={"files": files, "incompleteSearch": self.incomplete_search} - ) - if path.endswith("/export"): - return httpx.Response(200, text="# Design\n\nWe chose the planner.") - if request.url.host == "slides.googleapis.com": - return httpx.Response(200, json=DECK) - if request.url.params.get("alt") == "media": - return httpx.Response(200, content=b"%PDF-1.7 bytes") - return httpx.Response(404) - @pytest.fixture -def world(monkeypatch: pytest.MonkeyPatch) -> _World: +def source_world(monkeypatch: pytest.MonkeyPatch) -> _World: w = _World() monkeypatch.setattr(settings, "jwt_secret", "unit-test-root-secret") monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 40) @@ -266,13 +183,6 @@ async def _cluster(name: str, **kw: Any) -> AsyncIterator[Any]: monkeypatch.setattr(leases, "holding", _holding) monkeypatch.setattr(leases, "cluster_lease", _cluster) - async def _token(account: Any) -> str: - return "tok" - - monkeypatch.setattr(gdrive, "access_token", _token) - client = httpx.AsyncClient(transport=httpx.MockTransport(w.answer)) - monkeypatch.setattr(gdrive, "get_client", lambda: client) - async def _get_one(org: str, ns: str, uri: str, **kw: Any) -> Any: d = w.docs.get(uri) return ( @@ -319,41 +229,36 @@ async def _emit(event: str, **kw: Any) -> str: monkeypatch.setattr(audit, "emit", _emit) - def _endpoint(fmt: str, media_type: str = "") -> str: - return f"http://extractor-{fmt}" if fmt in w.routes else "" - - async def _capabilities(url: str) -> extractors.Capabilities: - w.capability_calls += 1 - if w.extractor_down: - raise extractors.ExtractorUnavailable("the extractor is unreachable") - return extractors.Capabilities(name="x", formats=frozenset(w.declared), max_bytes=10**9) - - async def _extract(data: bytes, **kw: Any) -> Artifact: - if w.extract_error is not None: - raise w.extract_error - downloaded = next(r for r in reversed(w.requests) if r.url.params.get("alt") == "media") - file_id = downloaded.url.path.rsplit("/", 1)[-1] - if file_id in w.extract_errors: - raise w.extract_errors[file_id] - return Artifact( - format=kw["declared_format"], - parser="test", - parser_version="1", - blocks=( - Block(id="b0", type="heading", text="Decision", depth=1), - Block(id="b1", type="paragraph", text="Keep the hash join."), - ), - coverage=Coverage(unit="pages", total=1, extracted=1), - ) - - monkeypatch.setattr(extractors, "endpoint_for", _endpoint) - monkeypatch.setattr(extractors, "capabilities", _capabilities) - monkeypatch.setattr(extractors, "extract", _extract) _mock_mining(monkeypatch, w) w.sources.append(_source()) return w +@pytest.fixture +def world(source_world, monkeypatch): + w = source_world + + async def session(provider, credential): + assert provider == "zoom" and credential == KEY + return source_sync_recording.Session("zoom", "fixture-token") + + async def listing(selected, ids, *, stamp): + assert selected.provider == "zoom" and ids == ["123456789"] + w.recording_lists.append(ids) + return [dict(item) for item in w.files], [] + + async def transcript(selected, item, *, max_bytes): + assert selected.provider == "zoom" and max_bytes > 0 + if w.transcript_error is not None: + raise w.transcript_error + return "# Decision\n\nKeep the hash join." + + monkeypatch.setattr(source_sync_recording, "open_session", session) + monkeypatch.setattr(source_sync_recording, "list_recordings", listing) + monkeypatch.setattr(source_sync_recording, "transcript", transcript) + return w + + def _mock_mining(monkeypatch: pytest.MonkeyPatch, w: _World) -> None: from server.llm import customer from server.memory.app import decision_extract @@ -407,17 +312,14 @@ def _cost(**kw: Any) -> None: def _source(name: str = "decks", **kw: Any) -> KnowledgeSource: - config = kw.pop( - "config", {"folder_ids": [FOLDER], "include": ["docs", "slides", "pdf", "pptx"]} - ) + config = kw.pop("config", {"provider": "zoom", "ids": ["123456789"]}) return KnowledgeSource( org=ORG, namespace=kw.pop("namespace", NS), name=name, - kind="gdrive", + kind="recording", source_id=kw.pop("source_id", f"id-{name}"), config=config, - items=kw.pop("items", None) or items_from_config("gdrive", config), credential_enc=kw.pop("credential_enc", seal("knowledge_sources.credential", KEY)), **kw, ) @@ -427,448 +329,9 @@ def _detail(world: _World, name: str = "decks") -> dict[str, Any]: return json.loads(world.states[name]["detail"]) -def _listings(world: _World) -> list[str]: - return [r.url.params["q"] for r in world.requests if r.url.path == "/drive/v3/files"] - - -def _run_out_after(monkeypatch: pytest.MonkeyPatch, name: str) -> None: - """The pass's time runs out once the turn's `gdrive.` call returns.""" - late = {"out": False} - real = getattr(source_sync.gdrive, name) - - async def _then_out(*a: Any, **kw: Any) -> Any: - found = await real(*a, **kw) - late["out"] = True - return found - - real_budget = source_sync._budget - - def _budget() -> Any: - budget = real_budget() - return SimpleNamespace( - started=budget.started, - stop_after=budget.stop_after, - exhausted=lambda: late["out"] or budget.exhausted(), - ) - - monkeypatch.setattr(source_sync.gdrive, name, _then_out) - monkeypatch.setattr(source_sync, "_budget", _budget) - - -def test_a_first_turn_lists_everything_and_writes_each_kind(world: _World) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("deck1", SLIDES, "2026-01-02T00:00:00.000Z"), - _file("pdf1", PDF, "2026-01-03T00:00:00.000Z", size="14"), - ] - result = asyncio.run(source_sync.run_sync()) - assert (result.synced, result.changed, result.failed) == (1, 3, 0) - assert "modifiedTime >" not in _listings(world)[0] - by_uri = {inp.source_uri: (inp, actor) for inp, actor in world.upserts} - deck, actor = by_uri["https://docs.example.com/presentation/d/deck1/edit"] - assert actor == SYNC_WORKER_ACTOR - assert deck.content.startswith("# Slide 1: Why a planner pass") - assert deck.tags == ["source-kind:design_doc", "repo:abc", "source:decks"] - assert deck.source_class == "imported" - assert deck.metadata["source_revision"] == "2026-01-02T00:00:00.000Z" - assert deck.original_bytes_b64 is None - pdf, _ = by_uri["https://docs.example.com/file/d/pdf1/edit"] - assert pdf.content == "# Decision\n\nKeep the hash join." - assert pdf.original_bytes_b64 and pdf.blob_content_type == PDF - assert world.states["decks"]["state_value"] == "2026-01-03T00:00:00.000Z" - detail = _detail(world) - assert (detail["status"], detail["documents_seen"], detail["changed"]) == ("ok", 3, 3) - assert detail["full_listed_at"] - - -def test_a_later_turn_lists_only_changes_and_skips_unchanged_files(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.files.append(_file("doc2", DOCS, "2026-01-05T00:00:00.000Z")) - world.upserts.clear() - asyncio.run(source_sync.run_sync()) - assert "modifiedTime > '2026-01-01T00:00:00.000Z'" in _listings(world)[-1] - assert [inp.source_uri for inp, _ in world.upserts] == [ - "https://docs.example.com/document/d/doc2/edit" - ] - # A full listing that returns a stored file at its stored revision fetches nothing. - world.upserts.clear() - world.requests.clear() - asyncio.run(source_sync.run_sync(full=True)) - assert world.upserts == [] - assert [r.url.path for r in world.requests] == ["/drive/v3/files", f"/drive/v3/files/{FOLDER}"] - - OLD_EXPORT = "# Design\n\n![][image1]\n\n[image1]: \n" -def _stored(world: _World, file_id: str, mime: str, content: str) -> str: - """A copy of `file_id` the sync stored at REV1.""" - uri = source_sync.source_uri_of(_file(file_id, mime, REV1)) - world.docs[uri] = { - "actor": SYNC_WORKER_ACTOR, - "tags": ["source-kind:design_doc", "source:decks"], - "metadata": {"ingested_from": file_id, "source_revision": REV1}, - "content": content, - } - return uri - - -def test_a_document_stored_with_its_pictures_bytes_is_converted_and_mined_again( - world: _World, -) -> None: - world.files = [_file("doc1", DOCS, REV1)] - uri = _stored(world, "doc1", DOCS, OLD_EXPORT) - world.states["decks"] = {"state_value": "", "detail": json.dumps({"mined": {uri: REV1}})} - asyncio.run(source_sync.run_sync()) - assert [inp.source_uri for inp, _ in world.upserts] == [uri] - assert "data:" not in world.docs[uri]["content"] - assert [u for u, _, _ in world.mined] == [uri] - world.upserts.clear() - asyncio.run(source_sync.run_sync(full=True)) - assert world.upserts == [] - - -def test_a_definition_shown_in_code_is_fetched_but_neither_written_nor_mined_again( - world: _World, -) -> None: - sample = "# Export\n\n```md\n[image1]: \n```\n" - world.files = [_file("doc1", DOCS, REV1)] - world.file_answers["doc1"] = httpx.Response(200, text=sample) - uri = _stored(world, "doc1", DOCS, sample) - world.states["decks"] = {"state_value": "", "detail": json.dumps({"mined": {uri: REV1}})} - for _ in range(2): - asyncio.run(source_sync.run_sync(full=True)) - assert world.upserts == [] and world.mined == [] - exports = [r for r in world.requests if r.url.path == "/drive/v3/files/doc1/export"] - assert len(exports) == 1 - assert _detail(world)["mined"] == {uri: REV1} - - -def test_a_given_up_flagged_copy_whose_address_moved_is_counted_unconverted( - world: _World, -) -> None: - _stored(world, "doc1", DOCS, OLD_EXPORT) - moved = _file("doc1", DOCS, REV1, webViewLink="https://docs.example.com/document/d/doc1/v2") - world.files = [moved] - waits = {"doc1": [REV1, 3, "http_500"]} - listed = "2026-01-02T00:00:00+00:00" - detail = {"file_waits": waits, "full_listed_at": listed, "retry_granted_for": listed} - world.states["decks"] = {"state_value": REV1, "detail": json.dumps(detail)} - asyncio.run(source_sync.run_sync()) - assert world.upserts == [] and _detail(world)["unconverted"] == 1 - - -def test_a_flagged_copy_whose_address_moved_is_written_at_the_new_one(world: _World) -> None: - old = _stored(world, "doc1", DOCS, OLD_EXPORT) - moved = _file("doc1", DOCS, REV1, webViewLink="https://docs.example.com/document/d/doc1/v2") - world.files = [moved] - asyncio.run(source_sync.run_sync(full=True)) - new = source_sync.source_uri_of(moved) - assert new != old and old not in world.docs - assert "data:" not in world.docs[new]["content"] - - -def test_unchanged_flagged_copies_do_not_hold_a_full_listing_at_the_pass_bound( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 2) - sample = "# Export\n\n```md\n[image1]: \n```\n" - world.files = [_file(f"doc{i}", DOCS, REV1) for i in (1, 2)] - world.files.append(_file("doc3", DOCS, "2026-01-02T00:00:00.000Z")) - for i in (1, 2): - world.file_answers[f"doc{i}"] = httpx.Response(200, text=sample) - _stored(world, f"doc{i}", DOCS, sample) - for _ in range(3): - asyncio.run(source_sync.run_sync(full=True)) - # The two were exported once each at their revision; the file after them was written. - exports = [r for r in world.requests if r.url.path.endswith("/export")] - assert sorted(r.url.path for r in exports if "doc3" not in r.url.path) == [ - "/drive/v3/files/doc1/export", - "/drive/v3/files/doc2/export", - ] - assert _uri("doc3") in world.docs and _detail(world)["status"] == "ok" - # Once a file is listed at another revision, its record goes. - world.files[0] = _file("doc1", DOCS, "2026-03-01T00:00:00.000Z") - asyncio.run(source_sync.run_sync(full=True)) - assert _detail(world)["pictures_checked"] == {"doc2": REV1} - # A file an incremental turn does not list keeps its record; a full listing without - # it drops the record. - world.files = [f for f in world.files if f["id"] != "doc2"] - asyncio.run(source_sync.run_sync()) - assert _detail(world)["pictures_checked"] == {"doc2": REV1} - asyncio.run(source_sync.run_sync(full=True)) - assert "doc2" not in _detail(world)["pictures_checked"] - - -def test_a_document_stored_without_pictures_bytes_is_not_fetched_again(world: _World) -> None: - world.files = [_file("doc1", DOCS, REV1)] - _stored(world, "doc1", DOCS, "# Design\n\nText only.\n") - asyncio.run(source_sync.run_sync(full=True)) - assert world.upserts == [] - - -def test_a_turn_cut_after_a_reconverting_write_still_mines_the_new_text( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, REV1)] - uri = _stored(world, "doc1", DOCS, OLD_EXPORT) - world.states["decks"] = {"state_value": "", "detail": json.dumps({"mined": {uri: REV1}})} - real = source_sync._write_state - - async def _cut(*a: Any, **kw: Any) -> None: - raise RuntimeError("cut before the turn's state") - - monkeypatch.setattr(source_sync, "_write_state", _cut) - asyncio.run(source_sync.run_sync()) - monkeypatch.setattr(source_sync, "_write_state", real) - asyncio.run(source_sync.run_sync()) - assert uri in [u for u, _, _ in world.mined] - - -def test_a_reconverting_write_cut_before_its_chunks_still_mines_the_new_text( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, REV1)] - uri = _stored(world, "doc1", DOCS, OLD_EXPORT) - world.states["decks"] = {"state_value": "", "detail": json.dumps({"mined": {uri: REV1}})} - real = writes.handle_knowledge_upsert - - async def _cut_before_chunks(inp: Any, **_: Any) -> Any: - await real(inp) - world.docs[inp.source_uri]["chunks"] = False # the document row, no live chunks - raise RuntimeError("cut before the chunks") - - monkeypatch.setattr(writes, "handle_knowledge_upsert", _cut_before_chunks) - asyncio.run(source_sync.run_sync()) - monkeypatch.setattr(writes, "handle_knowledge_upsert", real) - asyncio.run(source_sync.run_sync(full=True)) - assert "data:" not in world.docs[uri]["content"] - assert uri in [u for u, _, _ in world.mined] - - -def test_a_failed_reconverting_write_leaves_the_document_to_be_mined_again( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, REV1)] - uri = _stored(world, "doc1", DOCS, OLD_EXPORT) - world.states["decks"] = {"state_value": "", "detail": json.dumps({"mined": {uri: REV1}})} - real = writes.handle_knowledge_upsert - - async def _down(inp: Any, **_: Any) -> Any: - raise RuntimeError("store down") - - monkeypatch.setattr(writes, "handle_knowledge_upsert", _down) - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert detail["file_waits"]["doc1"][2] == "write_failed:RuntimeError" - assert "data:" in world.docs[uri]["content"] - monkeypatch.setattr(writes, "handle_knowledge_upsert", real) - asyncio.run(source_sync.run_sync(full=True)) - assert "data:" not in world.docs[uri]["content"] - # The failed write left the old copy and its mined key: only the new text is mined. - assert [u for u, _, _ in world.mined] == [uri] - - -def test_a_document_given_up_on_is_not_fetched_again_for_its_pictures(world: _World) -> None: - world.files = [_file("doc1", DOCS, REV1)] - _stored(world, "doc1", DOCS, OLD_EXPORT) - waits = {"doc1": [REV1, 3, "http_500"]} - # A periodic full listing whose one more try was already granted. - listed = "2026-01-02T00:00:00+00:00" - detail = {"file_waits": waits, "full_listed_at": listed, "retry_granted_for": listed} - world.states["decks"] = {"state_value": REV1, "detail": json.dumps(detail)} - asyncio.run(source_sync.run_sync()) - assert world.upserts == [] - detail = _detail(world) - assert (detail["file_waits"], detail["unconverted"]) == (waits, 0) - - -@pytest.mark.parametrize(("file_id", "mime"), [("deck1", SLIDES), ("pdf1", PDF)]) -def test_a_deck_or_uploaded_file_is_not_fetched_again_for_pictures_bytes( - world: _World, file_id: str, mime: str -) -> None: - world.files = [_file(file_id, mime, REV1, size="14")] - _stored(world, file_id, mime, OLD_EXPORT) - asyncio.run(source_sync.run_sync(full=True)) - assert world.upserts == [] - - -def test_a_document_export_keeps_its_text_and_marks_its_inlined_pictures() -> None: - data = "data:image/png;base64," + "iVBORw0KGgo" * 40 - exported = ( - "# Design\n\nThe planner runs first.\n\n![][image1]\n\n![][image2]\n\n" - "* ![][image3] the operator version shown\n* ![][image2]\n> ![Flow][image1]\n\n" - "![Flow][image4]*Figure 2: flow*\n\n```md\n![][image1]\n\n\n indented\n```\n\n" - "See [the spec][spec].\n\n" - f"[image1]: <{data}>\n\n[image2]: <{data}>\n\n[image3]: <{data}>\n\n" - f"[image4]: <{data}>\n\n[spec]: https://example.com/spec\n" - ) - assert convert.exported_markdown(exported) == ( - "# Design\n\nThe planner runs first.\n\n" - "> [image-only: 2 pictures, rationale not extracted]\n\n" - "* the operator version shown\n" - "* [image-only: 1 picture, rationale not extracted]\n" - "> [image-only: 1 picture, rationale not extracted] Flow\n\n" - "Flow *Figure 2: flow*\n\n```md\n![][image1]\n\n\n indented\n```\n\n" - "See [the spec][spec].\n\n[spec]: https://example.com/spec\n" - ) - nested = "1. Step\n\n ![][image1]\n\n2. Next\n\n[image1]: \n" - assert convert.exported_markdown(nested) == ( - "1. Step\n\n > [image-only: 1 picture, rationale not extracted]\n\n2. Next\n" - ) - heading = "# ![][image1]\n\nText.\n\n[image1]: \n" - assert convert.exported_markdown(heading) == ( - "# [image-only: 1 picture, rationale not extracted]\n\nText.\n" - ) - joined = "one![][image1]two\n\n[image1]: \n" - assert convert.exported_markdown(joined) == "one two\n" - inline = "![](data:image/png;base64,AAAA)\n\nA ![Graph](data:image/png;base64,AAAA) here.\n" - assert convert.exported_markdown(inline) == ( - "> [image-only: 1 picture, rationale not extracted]\n\nA Graph here.\n" - ) - tilde = "~~~\n![][image1]\n~~~\n``` x ` ```\n\n[image1]: \n" - assert convert.exported_markdown(tilde) == "~~~\n![][image1]\n~~~\n``` x ` ```\n" - listed = "- Step\n\n ```\n ![][image1]\n [image2]: \n ```\n" - assert convert.exported_markdown(listed) == listed - on_item = "- ```\n ![][image1]\n ```\n\nText ![][image2]\n\n[image1]: \n[image2]: \n" - assert convert.exported_markdown(on_item) == "- ```\n ![][image1]\n ```\n\nText\n" - quoted = "> ```\n> [image1]: \n> ```\n\n![][image2]\n\n[image2]: \n" - assert convert.exported_markdown(quoted) == ( - "> ```\n> [image1]: \n> ```\n\n> [image-only: 1 picture, rationale not extracted]\n" - ) - crlf = "Text.\r\n[image1]: \r\n" - assert convert.exported_markdown(crlf) == crlf - prose = "[Step 1]: data: the raw input\n\n[image1]: \n" - assert convert.exported_markdown(prose) == "[Step 1]: data: the raw input\n" - emphasis = "*![][image1]*\n\nx **![Flow][image1]** y\n\n[image1]: \n" - assert convert.exported_markdown(emphasis) == ( - "> [image-only: 1 picture, rationale not extracted]\n\nx **Flow** y\n" - ) - emptied = "x **![][image1]** y\n\n[image1]: \n" - assert convert.exported_markdown(emptied) == "x y\n" - bracketed = "see (![Fig][image1]) here\n\n[image1]: \n" - assert convert.exported_markdown(bracketed) == "see (Fig) here\n" - ended = "The flow is ![][image1]. Then ![Flow][image1], done.\n\n[image1]: \n" - assert convert.exported_markdown(ended) == "The flow is. Then Flow, done.\n" - spaced = "see![][image1] next\n\n[image1]: \n" - assert convert.exported_markdown(spaced) == "see next\n" - captioned = "see![Flow][image1] next\n\n[image1]: \n" - assert convert.exported_markdown(captioned) == "see Flow next\n" - plain = "# Plain\n\nNo pictures.\n\n\n```\n kept\n```" - assert convert.exported_markdown(plain) == plain - - -def test_a_full_listing_retires_what_the_folder_no_longer_has(world: _World) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - asyncio.run(source_sync.run_sync()) - world.files = world.files[1:] - # An incremental turn sees no absence: nothing is retired. - asyncio.run(source_sync.run_sync()) - assert len(world.docs) == 2 - result = asyncio.run(source_sync.run_sync(full=True)) - assert result.removed == 1 - assert list(world.docs) == ["https://docs.example.com/document/d/doc2/edit"] - assert world.audits == [ - { - "event": "knowledge.delete", - "org": ORG, - "namespace": NS, - "actor": SYNC_WORKER_ACTOR, - "subject": { - "source_uri": "https://docs.example.com/document/d/doc1/edit", - "source_name": "decks", - }, - } - ] - - -@pytest.mark.parametrize( - ("status", "body", "expected"), - [ - (429, {}, "rate_limited"), - (403, {"error": {"errors": [{"reason": "userRateLimitExceeded"}]}}, "rate_limited"), - (403, {}, "credential_invalid"), - (500, {}, "failed"), - ], -) -def test_a_failed_listing_keeps_the_stamp_and_retires_nothing( - world: _World, - monkeypatch: pytest.MonkeyPatch, - status: int, - body: dict[str, Any], - expected: str, -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.requests.clear() - - def _fail(request: httpx.Request) -> httpx.Response: - return httpx.Response(status, json=body) - - client = httpx.AsyncClient(transport=httpx.MockTransport(_fail)) - monkeypatch.setattr(gdrive, "get_client", lambda: client) - result = asyncio.run(source_sync.run_sync(full=True)) - assert result.failed == 1 - detail = _detail(world) - assert detail["status"] == expected - # The state names the status, never the store's answer. - assert "Exceeded" not in detail["error"] - assert world.states["decks"]["state_value"] == "2026-01-01T00:00:00.000Z" - assert len(world.docs) == 1 - - -def test_a_credential_that_no_longer_opens_fetches_nothing(world: _World) -> None: - world.sources = [_source(credential_enc="not-a-sealed-value")] - asyncio.run(source_sync.run_sync()) - assert world.requests == [] - assert _detail(world)["status"] == "credential_invalid" - - -def test_the_document_bound_cuts_the_turn_and_holds_the_stamp( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 2) - world.files = [_file(f"doc{i}", DOCS, f"2026-01-0{i}T00:00:00.000Z") for i in range(1, 6)] - world.states["decks"] = { - "state_value": "", - "detail": json.dumps({"requested_at": "2026-01-09T00:00:00+00:00", "full": True}), - } - first = asyncio.run(source_sync.run_sync()) - assert first.changed == 2 - assert world.states["decks"]["state_value"] == "" - # The request stays until a turn finishes it. - assert _detail(world)["requested_at"] - asyncio.run(source_sync.run_sync()) - asyncio.run(source_sync.run_sync()) - assert len(world.docs) == 5 - assert world.states["decks"]["state_value"] == "2026-01-05T00:00:00.000Z" - assert "requested_at" not in _detail(world) - - -def test_a_file_no_extractor_serves_is_unconverted(world: _World) -> None: - world.routes = set() - world.files = [_file("pdf1", PDF, "2026-01-03T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - assert world.docs == {} - assert _detail(world)["unconverted"] == 1 - assert not [r for r in world.requests if r.url.params.get("alt") == "media"] - - -def test_a_document_another_writer_holds_is_never_overwritten(world: _World) -> None: - uri = "https://docs.example.com/document/d/doc1/edit" - world.docs[uri] = {"actor": "human:ann", "tags": ["source:decks"], "metadata": {}} - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - assert world.upserts == [] - assert _detail(world)["skipped"] == 1 - # Nothing was fetched for it, and it cost none of the pass's bound. - assert not [r for r in world.requests if r.url.path.endswith("/export")] - - def test_sources_on_an_inactive_namespace_are_not_synced_and_requests_go_first( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -886,7 +349,7 @@ async def _turn(src: KnowledgeSource, *a: Any) -> Any: order.append(src.name) return source_sync.TurnResult() - monkeypatch.setattr(source_sync, "_turn", _turn) + monkeypatch.setattr(source_sync_recording, "turn", _turn) asyncio.run(source_sync.run_sync()) assert order == ["zzz", "aaa", "plain"] @@ -976,88 +439,6 @@ async def _upsert_then_remove(inp: Any, **_: Any) -> Any: assert "decks" not in world.states -def test_a_synced_document_s_address_grounds_as_a_citation() -> None: - uri = source_sync.source_uri_of(_file("deck1", SLIDES, "2026-01-01T00:00:00.000Z")) - assert uri == "https://docs.example.com/presentation/d/deck1/edit" - answer, kept, removed = ground_citations(f"The pass moves [{uri}#2].", {(uri, 2)}) - assert (answer, kept, removed) == (f"The pass moves [{uri}#2].", [f"{uri}#2"], []) - answer, kept, removed = ground_citations(f"The pass moves [{uri}#3].", {(uri, 2)}) - assert kept == [] and removed == [f"{uri}#3"] - - -def test_slides_become_one_section_each() -> None: - slide = { - "pageElements": [ - {"shape": {"placeholder": {"type": "TITLE"}, "text": _text("Join order\n")}}, - {"elementGroup": {"children": [{"shape": {"text": _text("Grouped text\n")}}]}}, - { - "table": { - "tableRows": [ - {"tableCells": [{"text": _text("a")}, {"text": _text("b")}]}, - ] - } - }, - {"shape": {"text": _text(" ".join(str(n) for n in range(10)) + " end\n")}}, - ], - "slideProperties": { - "notesPage": { - "notesProperties": {"speakerNotesObjectId": "n1"}, - "pageElements": [{"objectId": "n1", "shape": {"text": _text("Say why.\n")}}], - } - }, - } - assert convert.slide_markdown(2, slide) == ( - "# Slide 2: Join order\n\nGrouped text\n\na | b\n\nend\n\n> Notes: Say why." - ) - - -def test_a_slide_that_is_a_picture_says_so() -> None: - slide = {"pageElements": [{"image": {}}, {"image": {}}, {"shape": {"text": _text("Fig\n")}}]} - assert convert.slide_markdown(1, slide).endswith( - "> [image-only: 2 pictures, rationale not extracted]" - ) - - -def test_short_number_runs_stay() -> None: - assert convert.drop_number_runs(["1 2 3", "4 5 6 7 8 x"]) == ["x"] - assert convert.drop_number_runs(["v1 2 3 4"]) == ["v1 2 3 4"] - - -def _text(content: str) -> dict[str, Any]: - return {"textElements": [{"textRun": {"content": content}}, {"paragraphMarker": {}}]} - - -def test_the_listing_pages_through_and_refuses_a_stamp_it_did_not_issue( - monkeypatch: pytest.MonkeyPatch, -) -> None: - seen: list[httpx.Request] = [] - - def _answer(request: httpx.Request) -> httpx.Response: - seen.append(request) - if "pageToken" in request.url.params: - return httpx.Response(200, json={"files": [{"id": "b"}]}) - return httpx.Response(200, json={"files": [{"id": "a"}], "nextPageToken": "p2"}) - - client = httpx.AsyncClient(transport=httpx.MockTransport(_answer)) - monkeypatch.setattr(gdrive, "get_client", lambda: client) - files, whole = asyncio.run(gdrive.list_all("tok", [FOLDER], [DOCS], pace_s=0)) - assert [f["id"] for f in files] == ["a", "b"] and whole - assert all(r.headers["Authorization"] == "Bearer tok" for r in seen) - with pytest.raises(ValueError): - asyncio.run(gdrive.list_all("tok", [FOLDER], [DOCS], modified_after="x' or '1")) - - -def test_a_download_past_the_bound_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: - client = httpx.AsyncClient( - transport=httpx.MockTransport(lambda r: httpx.Response(200, content=b"x" * 5000)) - ) - monkeypatch.setattr(gdrive, "get_client", lambda: client) - with pytest.raises(gdrive.TooLarge): - asyncio.run(gdrive.download("tok", "abc", max_bytes=1000)) - with pytest.raises(ValueError): - asyncio.run(gdrive.download("tok", "../x", max_bytes=1000)) - - def test_the_worker_row_reads_its_settings(monkeypatch: pytest.MonkeyPatch) -> None: from server.workers import registry @@ -1070,261 +451,71 @@ def test_the_worker_row_reads_its_settings(monkeypatch: pytest.MonkeyPatch) -> N assert spec.deadline_seconds() == 300.0 -def test_a_turn_lists_everything_again_once_the_full_interval_passed( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - asyncio.run(source_sync.run_sync()) - assert "modifiedTime >" in _listings(world)[-1] - monkeypatch.setattr(settings, "knowledge_source_sync_full_interval_seconds", 0) - asyncio.run(source_sync.run_sync()) - assert "modifiedTime >" not in _listings(world)[-1] +def _uri(file_id: str, kind: str = "document") -> str: + return f"https://docs.example.com/{kind}/d/{file_id}/edit" -def test_a_file_over_the_size_bound_is_not_downloaded( +def test_a_source_another_copy_holds_is_skipped( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 10) - world.files = [_file("pdf1", PDF, "2026-01-03T00:00:00.000Z", size="11")] - asyncio.run(source_sync.run_sync()) - assert world.docs == {} - assert _detail(world)["unconverted"] == 1 - assert not [r for r in world.requests if r.url.params.get("alt") == "media"] + world.sources = [_source("aaa"), _source("bbb")] + world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] + @contextlib.asynccontextmanager + async def _cluster(name: str, **kw: Any) -> AsyncIterator[Any]: + if name.endswith("/aaa"): + raise leases.LeaseBusy(name) + yield world.lease -def _uri(file_id: str, kind: str = "document") -> str: - return f"https://docs.example.com/{kind}/d/{file_id}/edit" + monkeypatch.setattr(leases, "cluster_lease", _cluster) + result = asyncio.run(source_sync.run_sync()) + assert (result.synced, result.failed) == (1, 0) + assert "aaa" not in world.states and "bbb" in world.states -def test_a_file_the_store_refuses_is_unconverted_and_the_turn_goes_on(world: _World) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - _file("doc3", DOCS, "2026-01-03T00:00:00.000Z"), - ] - world.file_answers["doc2"] = httpx.Response(403, json={"error": {"status": "denied"}}) - asyncio.run(source_sync.run_sync()) - assert sorted(world.docs) == [_uri("doc1"), _uri("doc3")] - detail = _detail(world) - assert (detail["status"], detail["unconverted"]) == ("ok", 1) - assert detail["unconverted_reasons"] == {"http_403": 1} - assert world.states["decks"]["state_value"] == "2026-01-03T00:00:00.000Z" +def test_a_cut_pass_resumes_at_the_source_it_did_not_start( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + world.sources = [_source("aaa"), _source("bbb"), _source("ccc")] + cursor = {"at": ""} + monkeypatch.setattr(source_sync.pass_context, "resume_cursor", lambda: cursor["at"]) + monkeypatch.setattr( + source_sync.pass_context, "set_cursor", lambda value: cursor.update(at=value) + ) + order: list[str] = [] + async def _turn(src: KnowledgeSource, state: Any, run: Any) -> Any: + order.append(src.name) + run.left -= 1 + return source_sync.TurnResult() -def test_a_full_listing_of_a_folder_the_account_lost_retires_nothing(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] + monkeypatch.setattr(source_sync_recording, "turn", _turn) + monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 2) + first = asyncio.run(source_sync.run_sync()) + assert first.cut and order == ["aaa", "bbb"] + assert cursor["at"] == f"{ORG}/{NS}/ccc" asyncio.run(source_sync.run_sync()) - # Unshared: the store lists the folder empty, and the folder itself answers 404. - world.files = [] - world.lost_folders = {FOLDER} - asyncio.run(source_sync.run_sync(full=True)) - assert list(world.docs) == [_uri("doc1")] - assert world.audits == [] - assert _detail(world)["status"] == "failed" + assert order[2:] == ["ccc", "aaa"] -def test_a_write_cut_before_its_chunks_is_done_again( +def test_a_pass_past_its_time_budget_starts_no_source( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: + # The smallest pass the setting allows, with no share of it left to start a source. + monkeypatch.setattr(settings, "knowledge_source_sync_max_pass_seconds", 180) + monkeypatch.setattr(source_sync, "_BUDGET_FRACTION", 0.0) world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - real = writes.handle_knowledge_upsert + result = asyncio.run(source_sync.run_sync()) + assert result.cut and result.synced == 0 + assert world.recording_lists == [] - async def _cut(inp: Any, **_: Any) -> Any: - await real(inp) - world.docs[inp.source_uri]["chunks"] = False # the document row landed, no chunk - raise RuntimeError("cut") - monkeypatch.setattr(writes, "handle_knowledge_upsert", _cut) - asyncio.run(source_sync.run_sync()) - # The write failed in a way that may pass: the file waits and the turn ends - # failed, by the error's class only. - detail = _detail(world) - assert (detail["status"], detail["error"]) == ("failed", "RuntimeError") - monkeypatch.setattr(writes, "handle_knowledge_upsert", real) - world.upserts.clear() +def test_a_failed_retirement_of_a_removed_source_counts_as_a_failure( + world: _World, monkeypatch: pytest.MonkeyPatch +) -> None: + world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] asyncio.run(source_sync.run_sync()) - assert [inp.source_uri for inp, _ in world.upserts] == [_uri("doc1")] - assert world.docs[_uri("doc1")].get("chunks", True) - - -def test_an_extractor_whose_capabilities_cannot_be_read_holds_the_turn(world: _World) -> None: - world.extractor_down = True - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("pdf1", PDF, "2026-01-03T00:00:00.000Z", size="14"), - ] - for _ in range(4): - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert detail["status"] == "failed" and "extractor_unavailable" in detail["error"] - # The whole format is down, which is the turn's: no file is given up on. - assert world.states["decks"]["state_value"] == "" - assert detail["unconverted"] == 0 - assert list(world.docs) == [_uri("doc1")] - assert not [r for r in world.requests if r.url.params.get("alt") == "media"] - - -def test_one_file_s_extraction_outage_waits_for_that_file_alone(world: _World) -> None: - world.extract_errors["pdf1"] = extractors.ExtractorUnavailable("timed out") - world.files = [ - _file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="14"), - _file("pdf2", PDF, "2026-01-02T00:00:00.000Z", size="14"), - ] - asyncio.run(source_sync.run_sync()) - # The format's other file is served the same pass. - assert list(world.docs) == [_uri("pdf2", "file")] - assert _detail(world)["status"] == "failed" - assert world.states["decks"]["state_value"] == "" - asyncio.run(source_sync.run_sync()) - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert detail["status"] == "ok" - assert detail["unconverted_reasons"] == {"extractor_unavailable": 1} - assert world.states["decks"]["state_value"] == "2026-01-02T00:00:00.000Z" - # Given up on its revision: an incremental turn does not try it again... - del world.extract_errors["pdf1"] - world.upserts.clear() - asyncio.run(source_sync.run_sync()) - assert world.upserts == [] - # ...and a new revision is tried again. - world.files[0] = _file("pdf1", PDF, "2026-01-05T00:00:00.000Z", size="14") - asyncio.run(source_sync.run_sync()) - assert _uri("pdf1", "file") in world.docs - - -def test_a_file_the_extractor_refuses_is_unconverted(world: _World) -> None: - world.extract_error = extractors.ExtractionFailed("corrupt", "the file is damaged") - world.files = [_file("pdf1", PDF, "2026-01-03T00:00:00.000Z", size="14")] - asyncio.run(source_sync.run_sync()) - assert world.docs == {} - detail = _detail(world) - assert detail["unconverted_reasons"] == {"extraction_failed:corrupt": 1} - assert world.states["decks"]["state_value"] == "2026-01-03T00:00:00.000Z" - - -@pytest.mark.parametrize(("mime", "fmt"), [(PPTX, "pptx"), (DOCX, "docx")]) -def test_an_uploaded_deck_or_document_goes_to_the_extractor_with_its_bytes_kept( - world: _World, mime: str, fmt: str -) -> None: - world.sources = [_source(config={"folder_ids": [FOLDER], "include": [fmt]})] - world.files = [_file("file2", mime, "2026-01-03T00:00:00.000Z", size="14")] - asyncio.run(source_sync.run_sync()) - [(inp, _)] = world.upserts - assert inp.metadata["ingested_format"] == fmt - assert inp.metadata["extraction_coverage"]["complete"] is True - assert inp.blob_content_type == mime and inp.original_bytes_b64 - - -def test_a_changed_address_retires_the_old_one(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.files = [ - _file( - "doc1", - DOCS, - "2026-01-02T00:00:00.000Z", - webViewLink="https://docs.example.com/document/d/doc1/view", - ) - ] - result = asyncio.run(source_sync.run_sync()) - assert list(world.docs) == ["https://docs.example.com/document/d/doc1/view"] - assert result.removed == 1 - - -def test_two_sources_sharing_a_folder_do_not_take_each_other_s_documents( - world: _World, -) -> None: - world.sources = [_source("aaa"), _source("bbb")] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - asyncio.run(source_sync.run_sync(full=True)) - assert world.docs[_uri("doc1")]["tags"][-1] == "source:aaa" - assert len(world.upserts) == 1 - assert _detail(world, "bbb")["skipped"] == 1 - assert world.audits == [] - - -def test_a_second_source_with_only_docx_adds_a_folder_s_docx_files_and_nothing_else( - world: _World, -) -> None: - world.sources = [ - _source("aaa"), - _source("bbb", config={"folder_ids": [FOLDER], "include": ["docx"]}), - ] - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("docx1", DOCX, "2026-01-02T00:00:00.000Z", size="14"), - ] - asyncio.run(source_sync.run_sync()) - asyncio.run(source_sync.run_sync(full=True)) - tags = {uri: d["tags"][-1] for uri, d in world.docs.items()} - assert tags == {_uri("doc1"): "source:aaa", _uri("docx1", "file"): "source:bbb"} - assert len(world.upserts) == 2 - assert world.audits == [] - - -def test_a_source_another_copy_holds_is_skipped( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.sources = [_source("aaa"), _source("bbb")] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - - @contextlib.asynccontextmanager - async def _cluster(name: str, **kw: Any) -> AsyncIterator[Any]: - if name.endswith("/aaa"): - raise leases.LeaseBusy(name) - yield world.lease - - monkeypatch.setattr(leases, "cluster_lease", _cluster) - result = asyncio.run(source_sync.run_sync()) - assert (result.synced, result.failed) == (1, 0) - assert "aaa" not in world.states and "bbb" in world.states - - -def test_a_cut_pass_resumes_at_the_source_it_did_not_start( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.sources = [_source("aaa"), _source("bbb"), _source("ccc")] - cursor = {"at": ""} - monkeypatch.setattr(source_sync.pass_context, "resume_cursor", lambda: cursor["at"]) - monkeypatch.setattr( - source_sync.pass_context, "set_cursor", lambda value: cursor.update(at=value) - ) - order: list[str] = [] - - async def _turn(src: KnowledgeSource, state: Any, run: Any) -> Any: - order.append(src.name) - run.left -= 1 - return source_sync.TurnResult() - - monkeypatch.setattr(source_sync, "_turn", _turn) - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 2) - first = asyncio.run(source_sync.run_sync()) - assert first.cut and order == ["aaa", "bbb"] - assert cursor["at"] == f"{ORG}/{NS}/ccc" - asyncio.run(source_sync.run_sync()) - assert order[2:] == ["ccc", "aaa"] - - -def test_a_pass_past_its_time_budget_starts_no_source( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - # The smallest pass the setting allows, with no share of it left to start a source. - monkeypatch.setattr(settings, "knowledge_source_sync_max_pass_seconds", 180) - monkeypatch.setattr(source_sync, "_BUDGET_FRACTION", 0.0) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - result = asyncio.run(source_sync.run_sync()) - assert result.cut and result.synced == 0 - assert world.requests == [] - - -def test_a_failed_retirement_of_a_removed_source_counts_as_a_failure( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.sources = [_source(active=False, pending_delete=True, credential_enc="")] + world.sources = [_source(active=False, pending_delete=True, credential_enc="")] async def _fail(inp: Any) -> Any: raise RuntimeError("store down") @@ -1363,696 +554,72 @@ def test_a_committed_retirement_that_awaits_publication_counts_as_retired( world.sources = [_source(active=False, pending_delete=True, credential_enc="")] async def _pending(inp: Any, **_: Any) -> Any: - raise PublicationPending() - - monkeypatch.setattr(writes, "handle_knowledge_delete", _pending) - result = asyncio.run(source_sync.run_sync()) - assert result.failed == 0 and result.retired == 1 - - -def test_a_deck_over_the_size_bound_is_unconverted( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 10) - world.files = [_file("deck1", SLIDES, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - assert world.docs == {} - assert _detail(world)["unconverted_reasons"] == {"too_large": 1} - - -def test_an_artifact_fences_its_code_and_reports_its_coverage() -> None: - artifact = Artifact( - format="pdf", - parser="test", - parser_version="1", - blocks=( - Block(id="b0", type="heading", text="Query", depth=2), - Block(id="b1", type="sql_statement", text="SELECT 1"), - Block(id="b2", type="code", text="x = ```y```"), - ), - coverage=Coverage(unit="pages", total=4, extracted=3), - ) - assert convert.artifact_markdown(artifact) == ( - "## Query\n\n```sql\nSELECT 1\n```\n\n````\nx = ```y```\n````" - ) - assert convert.coverage_of(artifact) == { - "complete": False, - "unit": "pages", - "total": 4, - "extracted": 3, - "lost": [], - } - - -def _waits(world: _World) -> dict[str, Any]: - return dict(_detail(world).get("file_waits") or {}) - - -def test_two_files_that_start_waiting_on_different_passes_each_wait_their_own( - world: _World, -) -> None: - world.extract_errors["pdf1"] = extractors.ExtractorUnavailable("timed out") - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="14")] - asyncio.run(source_sync.run_sync()) - world.files.append(_file("pdf2", PDF, "2026-01-02T00:00:00.000Z", size="14")) - world.extract_errors["pdf2"] = extractors.ExtractorUnavailable("timed out") - asyncio.run(source_sync.run_sync()) - assert {k: v[1] for k, v in _waits(world).items()} == {"pdf1": 2, "pdf2": 1} - asyncio.run(source_sync.run_sync()) - # pdf1 gave up on its third pass; pdf2 still holds the turn. - detail = _detail(world) - assert detail["unconverted_reasons"] == {"extractor_unavailable": 1} - assert detail["status"] == "failed" - assert {k: v[1] for k, v in _waits(world).items()} == {"pdf1": 3, "pdf2": 2} - asyncio.run(source_sync.run_sync()) - assert _detail(world)["status"] == "ok" - assert world.states["decks"]["state_value"] == "2026-01-02T00:00:00.000Z" - - -@pytest.mark.parametrize("ending", ["rate_limited", "cut"]) -def test_a_turn_that_ends_early_keeps_the_stored_waits( - world: _World, monkeypatch: pytest.MonkeyPatch, ending: str -) -> None: - world.extract_errors["pdf1"] = extractors.ExtractorUnavailable("timed out") - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="14")] - asyncio.run(source_sync.run_sync()) - assert _waits(world)["pdf1"][1] == 1 - if ending == "rate_limited": - world.fail_listing = 429 - else: - # An older file, listed first, uses the whole bound. - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 1) - world.files.insert(0, _file("doc0", DOCS, "2025-12-01T00:00:00.000Z")) - asyncio.run(source_sync.run_sync()) - assert _waits(world)["pdf1"][1] == 1 - - -def test_an_address_another_writer_holds_reads_no_extractor(world: _World) -> None: - uri = _uri("pdf1", "file") - world.docs[uri] = {"actor": "human:ann", "tags": [], "metadata": {}} - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="14")] - asyncio.run(source_sync.run_sync()) - assert world.capability_calls == 0 - assert _detail(world)["skipped"] == 1 - - -def test_an_address_a_writer_takes_during_the_fetch_is_not_overwritten(world: _World) -> None: - """The address is free when the file is listed; a person writes there while it is - downloaded and converted. The write step reads the address again and leaves theirs.""" - uri = _uri("pdf1", "file") - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="14")] - - def _download(request: httpx.Request) -> httpx.Response: - world.docs[uri] = {"actor": "human:ann", "tags": [], "metadata": {}} - return httpx.Response(200, content=b"%PDF-1.7 bytes") - - world.file_answers["pdf1"] = _download - asyncio.run(source_sync.run_sync()) - assert world.upserts == [] - assert world.docs[uri]["actor"] == "human:ann" - assert _detail(world)["skipped"] == 1 - - -def test_the_write_time_owner_read_reads_with_sequential_consistency( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - """A replica that has not seen a person's write during the fetch would answer the - address is free, so the read just before the write waits for every insert.""" - uri = _uri("pdf1", "file") - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="14")] - fake = documents.get_one - sequential: list[bool] = [] - - async def _get_one(org: str, ns: str, at: str, **kw: Any) -> Any: - if at == uri: - sequential.append(sequential_reads_active()) - return await fake(org, ns, at, **kw) - - monkeypatch.setattr(documents, "get_one", _get_one) - asyncio.run(source_sync.run_sync()) - assert len(world.upserts) == 1 - assert sequential == [False, True] # the check before the fetch, then the write's - - -def test_the_retire_owner_read_reads_with_sequential_consistency( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - """A replica that has not seen a person's write at the address would answer the - document is still the source's, so the read before a retirement waits for every - insert.""" - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - (uri,) = world.docs - world.files = [] - fake = documents.get_one - sequential: list[bool] = [] - - async def _get_one(org: str, ns: str, at: str, **kw: Any) -> Any: - if at == uri: - sequential.append(sequential_reads_active()) - return await fake(org, ns, at, **kw) - - monkeypatch.setattr(documents, "get_one", _get_one) - result = asyncio.run(source_sync.run_sync(full=True)) - assert result.removed == 1 and world.docs == {} - assert sequential == [True] - - -def _timeout(request: httpx.Request) -> httpx.Response: - raise httpx.ReadTimeout("timed out", request=request) - - -@pytest.mark.parametrize( - ("mime", "answer", "reason"), - [ - (DOCS, httpx.Response(503), "http_503"), - (DOCS, _timeout, "unreachable"), - (SLIDES, httpx.Response(500), "http_500"), - (SLIDES, _timeout, "unreachable"), - ], -) -def test_one_file_s_store_failure_that_may_pass_waits_for_that_file( - world: _World, mime: str, answer: Any, reason: str -) -> None: - world.files = [ - _file("bad1", mime, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - world.file_answers["bad1"] = answer - asyncio.run(source_sync.run_sync()) - assert list(world.docs) == [_uri("doc2")] - assert _detail(world)["status"] == "failed" - assert world.states["decks"]["state_value"] == "" - asyncio.run(source_sync.run_sync()) - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert (detail["status"], detail["unconverted_reasons"]) == ("ok", {reason: 1}) - assert world.states["decks"]["state_value"] == "2026-01-02T00:00:00.000Z" - - -def test_a_401_on_one_file_is_the_turn_s_credential(world: _World) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - world.file_answers["doc1"] = httpx.Response(401) - asyncio.run(source_sync.run_sync()) - assert world.docs == {} - assert _detail(world)["status"] == "credential_invalid" - - -def test_the_stamp_never_passes_the_listing_s_start(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2999-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - stamp = world.states["decks"]["state_value"] - assert gdrive.valid_stamp(stamp) and stamp < "2999" - # So the file is listed again, and skipped by its revision. - world.upserts.clear() - asyncio.run(source_sync.run_sync()) - assert world.upserts == [] - - -def test_a_lost_folder_writes_the_visible_ones_and_retires_nothing(world: _World) -> None: - config = {"folder_ids": [FOLDER, OTHER], "include": ["docs"]} - world.sources = [_source(config=config)] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.lost_folders = {OTHER} - world.files = [_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")] - asyncio.run(source_sync.run_sync(full=True)) - assert sorted(world.docs) == [_uri("doc1"), _uri("doc2")] - assert world.audits == [] - assert _detail(world)["status"] == "failed" - - -def test_a_maintainer_s_delete_request_goes_before_the_changed_files( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.docs[_uri("old1")] = { - "actor": SYNC_WORKER_ACTOR, - "tags": ["source:gone"], - "metadata": {"ingested_from": "old1", "source_revision": "r"}, - } - world.sources.append(_source("gone", active=False, pending_delete=True, credential_enc="")) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 1) - result = asyncio.run(source_sync.run_sync()) - assert result.retired == 1 and result.changed == 0 - assert list(world.docs) == [] - - -def test_a_write_the_store_refuses_is_unconverted_at_once( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _refuse(inp: Any, **_: Any) -> Any: - raise ValidationError("the original is too large", code="TOO_LARGE") - - monkeypatch.setattr(writes, "handle_knowledge_upsert", _refuse) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert (detail["status"], detail["unconverted_reasons"]) == ( - "ok", - {"write_refused:TOO_LARGE": 1}, - ) - - -def test_a_full_sync_request_with_a_failing_file_completes_and_clears(world: _World) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("bad1", DOCS, "2026-01-02T00:00:00.000Z"), - ] - world.file_answers["bad1"] = httpx.Response(503) - asyncio.run(source_sync.run_sync()) - world.states["decks"]["detail"] = json.dumps( - {**_detail(world), "requested_at": "2026-11-01T00:00:00+00:00", "full": True} - ) - for _ in range(3): - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - # The request reset the waits once; the file then waited its passes and gave up. - assert "requested_at" not in detail and "full" not in detail - assert (detail["status"], detail["unconverted_reasons"]) == ("ok", {"http_503": 1}) - - -def test_a_periodic_full_listing_gives_a_given_up_file_one_more_try(world: _World) -> None: - world.files = [_file("bad1", DOCS, "2026-01-01T00:00:00.000Z")] - world.file_answers["bad1"] = httpx.Response(503) - for _ in range(3): - asyncio.run(source_sync.run_sync()) - assert _waits(world)["bad1"][1] == 3 - # One more failure on the next full listing gives it up again at once. - world.states["decks"]["detail"] = json.dumps(_listed_long_ago(world)) - asyncio.run(source_sync.run_sync()) - assert _detail(world)["status"] == "ok" and _waits(world)["bad1"][1] == 3 - # Once the store answers, the next full listing writes it. - del world.file_answers["bad1"] - world.states["decks"]["detail"] = json.dumps(_listed_long_ago(world, days=3)) - asyncio.run(source_sync.run_sync()) - assert _uri("bad1") in world.docs and "bad1" not in _waits(world) - - -def test_an_incomplete_listing_retires_nothing(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.files = [] - world.incomplete_search = True - world.files = [_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")] - asyncio.run(source_sync.run_sync(full=True)) - # What it listed is written; nothing is retired and the stamp stays. - assert sorted(world.docs) == [_uri("doc1"), _uri("doc2")] - detail = _detail(world) - assert (detail["status"], detail["error"]) == ("ok", "listing: incomplete search") - assert world.states["decks"]["state_value"] == "2026-01-01T00:00:00.000Z" - - -def test_a_file_missing_from_the_listing_but_still_in_the_folder_stays(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.files = [] - world.file_answers["doc1"] = httpx.Response(200, json={"trashed": False, "parents": [FOLDER]}) - asyncio.run(source_sync.run_sync(full=True)) - assert list(world.docs) == [_uri("doc1")] - world.file_answers["doc1"] = httpx.Response(200, json={"trashed": True, "parents": [FOLDER]}) - asyncio.run(source_sync.run_sync(full=True)) - assert world.docs == {} - - -def test_a_document_left_at_a_file_s_old_address_is_retired(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - moved = "https://docs.example.com/document/d/doc1/view" - # The new address is another writer's, so the file is not written there. - world.docs[moved] = {"actor": "human:ann", "tags": [], "metadata": {}} - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", webViewLink=moved)] - asyncio.run(source_sync.run_sync(full=True)) - assert list(world.docs) == [moved] - - -def test_a_401_on_the_folder_check_ends_the_turn(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - world.file_answers[FOLDER] = httpx.Response(401) - asyncio.run(source_sync.run_sync()) - assert world.docs == {} - assert _detail(world)["status"] == "credential_invalid" - - -def _folders(n: int) -> list[dict[str, Any]]: - return [{"type": "folder", "id": f"f{i}"} for i in range(n)] - - -def test_folder_checks_run_ten_at_a_time_each_folder_once( - monkeypatch: pytest.MonkeyPatch, -) -> None: - checked: list[str] = [] - flying, most = 0, 0 - - async def _require(token: str, folder: str) -> None: - nonlocal flying, most - checked.append(folder) - flying += 1 - most = max(most, flying) - await asyncio.sleep(0) - flying -= 1 - - monkeypatch.setattr(gdrive, "require_folder", _require) - items = [*_folders(25), {"type": "filter", "in": "f0"}] - turn = source_sync.TurnResult() - assert asyncio.run(source_sync._items_visible("t", items, turn, lambda: False)) - assert most == 10 and len(checked) == 25 and turn.complete - - -def test_folder_checks_stop_at_the_pass_bound(monkeypatch: pytest.MonkeyPatch) -> None: - checked: list[str] = [] - asked = 0 - - async def _require(token: str, folder: str) -> None: - checked.append(folder) - - def _out_of_time() -> bool: - nonlocal asked - asked += 1 - return asked > 1 # time for the first ten only - - monkeypatch.setattr(gdrive, "require_folder", _require) - turn = source_sync.TurnResult() - assert not asyncio.run(source_sync._items_visible("t", _folders(25), turn, _out_of_time)) - assert len(checked) == 10 and turn.cut - - -@pytest.mark.parametrize( - ("worst", "status"), - [(401, "credential_invalid"), (429, "rate_limited")], -) -def test_the_worst_folder_check_in_a_batch_decides_the_turn( - monkeypatch: pytest.MonkeyPatch, worst: int, status: str -) -> None: - async def _require(token: str, folder: str) -> None: - if folder == "f1": - raise gdrive.NotFound("folder f1: http_404", status=404) - if folder == "f2" and worst == 401: - raise gdrive.CredentialRefused("folder f2: http_401", status=401) - if folder == "f2": - raise gdrive.RateLimited("folder f2: rate_limited", status=429) - if folder == "f3": - raise gdrive.CredentialRefused("folder f3: http_401", status=401) - - monkeypatch.setattr(gdrive, "require_folder", _require) - turn = source_sync.TurnResult() - assert not asyncio.run(source_sync._items_visible("t", _folders(4), turn, lambda: False)) - assert turn.status == status - - -def test_a_folder_check_s_own_bug_is_raised(monkeypatch: pytest.MonkeyPatch) -> None: - async def _require(token: str, folder: str) -> None: - raise KeyError(folder) - - monkeypatch.setattr(gdrive, "require_folder", _require) - with pytest.raises(KeyError): - asyncio.run( - source_sync._items_visible("t", _folders(2), source_sync.TurnResult(), lambda: False) - ) - - -def test_any_other_conversion_failure_waits_for_that_file( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - def _broken(deck: Any) -> str: - raise KeyError("pageElements") - - monkeypatch.setattr(source_sync.convert, "presentation_markdown", _broken) - world.files = [ - _file("deck1", SLIDES, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - asyncio.run(source_sync.run_sync()) - assert list(world.docs) == [_uri("doc2")] - assert _waits(world)["deck1"][2] == "fetch_failed:KeyError" - - -def test_a_turn_that_raises_records_a_failed_state_and_keeps_the_waits( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("bad1", DOCS, "2026-01-01T00:00:00.000Z")] - world.file_answers["bad1"] = httpx.Response(503) - asyncio.run(source_sync.run_sync()) - - async def _down(*a: Any, **kw: Any) -> Any: - raise ConnectionError("store down") - - monkeypatch.setattr(source_sync.store, "source_revisions", _down) - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert (detail["status"], detail["error"]) == ("failed", "ConnectionError") - assert _waits(world)["bad1"][1] == 1 - - -def _requests_for(world: _World, file_id: str) -> int: - """Requests the store got about one file: its export, deck read, download or - lookup (every path that names the file's id).""" - return sum(1 for r in world.requests if f"/{file_id}" in r.url.path) - - -@pytest.mark.parametrize("held_by", ["waiting_file", "lost_folder", "cut"]) -def test_a_full_turn_that_stays_incomplete_retries_a_given_up_file_once( - world: _World, monkeypatch: pytest.MonkeyPatch, held_by: str -) -> None: - world.files = [_file("bad1", DOCS, "2026-01-01T00:00:00.000Z")] - world.file_answers["bad1"] = httpx.Response(503) - for _ in range(3): - asyncio.run(source_sync.run_sync()) - assert _waits(world)["bad1"][1] == 3 - if held_by == "waiting_file": - world.files.append(_file("bad2", DOCS, "2026-01-02T00:00:00.000Z")) - world.file_answers["bad2"] = httpx.Response(503) - elif held_by == "lost_folder": - world.lost_folders = {FOLDER} - else: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 1) - world.files.append(_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")) - world.files.append(_file("doc3", DOCS, "2026-01-03T00:00:00.000Z")) - world.states["decks"]["detail"] = json.dumps(_listed_long_ago(world)) - before = _requests_for(world, "bad1") - asyncio.run(source_sync.run_sync()) - assert _requests_for(world, "bad1") == before + 1 - # The full listing did not complete, so the next full turn grants no new retry. - asyncio.run(source_sync.run_sync()) - assert _requests_for(world, "bad1") == before + 1 - - -@pytest.mark.parametrize( - ("answer", "status"), - [(httpx.Response(401), "credential_invalid"), (httpx.Response(429), "rate_limited")], -) -def test_a_lookup_refused_for_the_credential_or_rate_limited_stops_retiring( - world: _World, answer: httpx.Response, status: str -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - asyncio.run(source_sync.run_sync()) - world.files = [] - world.file_answers["doc1"] = answer - world.file_answers["doc2"] = answer - asyncio.run(source_sync.run_sync(full=True)) - assert sorted(world.docs) == [_uri("doc1"), _uri("doc2")] - assert _detail(world)["status"] == status - lookups = [r for r in world.requests if r.url.params.get("fields", "").startswith("trashed,")] - assert len(lookups) == 1 - - -def _listed_long_ago(world: _World, days: int = 2) -> dict[str, Any]: - """The state as days past its last complete full listing: the next turn is full. - Each call in one test passes its own `days`, as each real full listing has its - own time.""" - detail = _detail(world) - stamp = datetime.fromisoformat(detail["full_listed_at"]) - timedelta(days=days) - return {**detail, "full_listed_at": stamp.isoformat()} - - -def test_a_listed_file_with_no_usable_address_keeps_its_document(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", webViewLink="")] - # The lookup finds the file still in the folder. - world.file_answers["doc1"] = httpx.Response(200, json={"trashed": False, "parents": [FOLDER]}) - asyncio.run(source_sync.run_sync(full=True)) - assert list(world.docs) == [_uri("doc1")] - assert world.audits == [] - assert _detail(world)["unconverted_reasons"] == {"no_address": 1} - - -@pytest.mark.parametrize("why", ["incomplete_search", "lost_folder"]) -def test_waits_survive_a_full_listing_that_is_not_whole(world: _World, why: str) -> None: - config = {"folder_ids": [FOLDER, OTHER], "include": ["docs"]} - world.sources = [_source(config=config)] - world.files = [_file("bad1", DOCS, "2026-01-01T00:00:00.000Z")] - world.file_answers["bad1"] = httpx.Response(503) - asyncio.run(source_sync.run_sync()) - assert _waits(world)["bad1"][1] == 1 - # The file is not listed this time, but the listing cannot say it is gone. - world.files = [] - if why == "incomplete_search": - world.incomplete_search = True - else: - world.lost_folders = {OTHER} - # A periodic full listing (an explicit full sync would reset the waits). - world.states["decks"]["detail"] = json.dumps( - {**_detail(world), "full_listed_at": "2026-01-01T00:00:00+00:00"} - ) - asyncio.run(source_sync.run_sync()) - assert _waits(world)["bad1"][1] == 1 - - -def test_a_folder_error_is_not_hidden_by_an_incomplete_listing(world: _World) -> None: - config = {"folder_ids": [FOLDER, OTHER], "include": ["docs"]} - world.sources = [_source(config=config)] - world.lost_folders = {OTHER} - world.incomplete_search = True - asyncio.run(source_sync.run_sync(full=True)) - detail = _detail(world) - assert detail["status"] == "failed" and OTHER in detail["error"] - - -def test_the_first_error_of_a_turn_is_the_one_it_reports(world: _World) -> None: - config = {"folder_ids": [FOLDER, OTHER], "include": ["docs"]} - world.sources = [_source(config=config)] - world.lost_folders = {OTHER} - world.files = [_file("bad1", DOCS, "2026-01-01T00:00:00.000Z")] - world.file_answers["bad1"] = httpx.Response(503) - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert detail["status"] == "failed" and OTHER in detail["error"] - - -def test_more_refused_files_than_the_bound_do_not_hold_the_stamp( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 2) - world.files = [_file(f"bad{i}", DOCS, f"2026-01-0{i}T00:00:00.000Z") for i in range(1, 6)] - for i in range(1, 6): - world.file_answers[f"bad{i}"] = httpx.Response(403) - asyncio.run(source_sync.run_sync()) - # Cut by the bound: not a failure, but it says so. - detail = _detail(world) - assert (detail["status"], detail["error"]) == ( - "ok", - "pass bound reached", - ) - for _ in range(2): - asyncio.run(source_sync.run_sync()) - assert world.states["decks"]["state_value"] == "2026-01-05T00:00:00.000Z" - # Each file was fetched once: a given-up file costs nothing on later passes. - assert all(_requests_for(world, f"bad{i}") == 1 for i in range(1, 6)) - assert _detail(world)["unconverted_reasons"] == {"http_403": 5} + raise PublicationPending() + + monkeypatch.setattr(writes, "handle_knowledge_delete", _pending) + result = asyncio.run(source_sync.run_sync()) + assert result.failed == 0 and result.retired == 1 -def test_a_file_over_the_listed_size_is_given_up_without_any_of_the_bound( +def test_the_write_time_owner_read_reads_with_sequential_consistency( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 1) - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 100) - world.files = [ - _file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="101"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - asyncio.run(source_sync.run_sync()) - assert list(world.docs) == [_uri("doc2")] - assert _waits(world)["pdf1"][2] == "too_large" + """A replica that has not seen a person's write during the fetch would answer the + address is free, so the read just before the write waits for every insert.""" + uri = _file("pdf1", PDF, REV1)["uri"] + world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="14")] + fake = documents.get_one + sequential: list[bool] = [] + async def _get_one(org: str, ns: str, at: str, **kw: Any) -> Any: + if at == uri: + sequential.append(sequential_reads_active()) + return await fake(org, ns, at, **kw) -def test_a_credential_refusal_after_a_waiting_file_is_the_turn_s_status(world: _World) -> None: - world.files = [ - _file("bad1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - world.file_answers["bad1"] = httpx.Response(503) - world.file_answers["doc2"] = httpx.Response(401) + monkeypatch.setattr(documents, "get_one", _get_one) asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert detail["status"] == "credential_invalid" and "http_401" in detail["error"] + assert len(world.upserts) == 1 + assert sequential == [False, True] # the check before the fetch, then the write's -def test_repeated_full_runs_get_past_more_refused_files_than_the_bound( +def test_the_retire_owner_read_reads_with_sequential_consistency( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 2) - world.files = [_file(f"bad{i}", DOCS, f"2026-01-0{i}T00:00:00.000Z") for i in range(1, 6)] - for i in range(1, 6): - world.file_answers[f"bad{i}"] = httpx.Response(403) - first = asyncio.run(source_sync.run_sync(full=True)) - assert first.cut - # Each run goes on with the request the first recorded, so the waits are reset once. - for _ in range(2): - asyncio.run(source_sync.run_sync(full=True)) - assert world.states["decks"]["state_value"] == "2026-01-05T00:00:00.000Z" - assert "requested_at" not in _detail(world) - assert all(_requests_for(world, f"bad{i}") == 1 for i in range(1, 6)) - - -@pytest.mark.parametrize("refusal", ["http_403", "extraction_failed", "write_refused"]) -def test_a_file_refused_at_once_is_tried_again_when_it_changes_and_on_a_full_listing( - world: _World, monkeypatch: pytest.MonkeyPatch, refusal: str -) -> None: - if refusal == "http_403": - world.files = [_file("f1", DOCS, "2026-01-01T00:00:00.000Z")] - world.file_answers["f1"] = httpx.Response(403) - elif refusal == "extraction_failed": - world.files = [_file("f1", PDF, "2026-01-01T00:00:00.000Z", size="14")] - world.extract_errors["f1"] = extractors.ExtractionFailed("corrupt", "damaged") - else: + """A replica that has not seen a person's write at the address would answer the + document is still the source's, so the read before a retirement waits for every + insert.""" + world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] + asyncio.run(source_sync.run_sync()) + (uri,) = world.docs + fake = documents.get_one + sequential: list[bool] = [] - async def _refuse(inp: Any, **_: Any) -> Any: - raise ValidationError("refused", code="TOO_LARGE") + async def _get_one(org: str, ns: str, at: str, **kw: Any) -> Any: + if at == uri: + sequential.append(sequential_reads_active()) + return await fake(org, ns, at, **kw) - monkeypatch.setattr(writes, "handle_knowledge_upsert", _refuse) - world.files = [_file("f1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - tried = _requests_for(world, "f1") - assert tried >= 1 - asyncio.run(source_sync.run_sync()) - # Given up on its revision (its entry exhausted), so the next turn does not fetch it. - assert _waits(world)["f1"][1] == 3 - assert _requests_for(world, "f1") == tried - # A periodic full listing tries it exactly once more... - world.states["decks"]["detail"] = json.dumps(_listed_long_ago(world)) - asyncio.run(source_sync.run_sync()) - assert _requests_for(world, "f1") == tried * 2 - assert _waits(world)["f1"][1] == 3 - # ...a full listing that grants no new retry skips it without a fetch... - detail = _detail(world) - world.states["decks"]["detail"] = json.dumps( - {**detail, "full_listed_at": detail["retry_granted_for"]} - ) - asyncio.run(source_sync.run_sync()) - assert "modifiedTime >" not in _listings(world)[-1] - assert _requests_for(world, "f1") == tried * 2 - # ...and a new revision is tried again. - world.files[0] = {**world.files[0], "modifiedTime": "2026-02-01T00:00:00.000Z"} - asyncio.run(source_sync.run_sync()) - assert _requests_for(world, "f1") == tried * 3 + monkeypatch.setattr(documents, "get_one", _get_one) + assert asyncio.run(source_sync.retire(world.sources[0], uri)) + assert world.docs == {} + assert sequential == [True] -def test_a_turn_cut_by_the_bound_marks_the_pass_cut( +def test_a_turn_that_raises_records_a_failed_state_and_keeps_the_waits( world: _World, monkeypatch: pytest.MonkeyPatch ) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 1) - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - result = asyncio.run(source_sync.run_sync()) - assert result.cut and result.changed == 1 - from server.knowledge.workers.source_sync import outcome - - assert outcome(result)["cut"] is True + world.files = [_file("bad1", DOCS, "2026-01-01T00:00:00.000Z")] + world.transcript_error = ConnectionError("transcript unavailable") + asyncio.run(source_sync.run_sync()) + async def _down(*a: Any, **kw: Any) -> Any: + raise ConnectionError("store down") -def test_a_size_that_is_not_a_number_is_left_to_the_download_bound(world: _World) -> None: - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="big")] + monkeypatch.setattr(source_sync.store, "source_revisions", _down) asyncio.run(source_sync.run_sync()) - assert _uri("pdf1", "file") in world.docs + detail = _detail(world) + assert (detail["status"], detail["error"]) == ("failed", "ConnectionError") + assert _detail(world)["file_waits"]["bad1"][1] == 1 def test_a_delete_request_cut_by_the_bound_marks_the_pass_cut( @@ -2089,18 +656,6 @@ def test_a_delete_request_past_the_bound_waits_and_marks_the_pass_cut( assert list(world.docs) == [_uri("bbb")] -def test_a_full_run_turns_a_waiting_plain_request_into_a_full_one(world: _World) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - asked = "2026-11-01T00:00:00+00:00" - world.states["decks"]["detail"] = json.dumps({**_detail(world), "requested_at": asked}) - asyncio.run(source_sync.source_ops.request_full_sync(world.sources[0])) - detail = _detail(world) - assert detail["full"] is True and detail["requested_at"] != asked - # The stamp is kept. - assert world.states["decks"]["state_value"] == "2026-01-01T00:00:00.000Z" - - # The extraction leg. DOC1 = "https://docs.example.com/document/d/doc1/edit" @@ -2779,421 +1334,6 @@ def entry(namespace: str, branch: str) -> SimpleNamespace: # ---- items ------------------------------------------------------------------- -def test_the_folder_turn_ends_a_source_stored_without_a_kind_before_any_request( - world: _World, -) -> None: - # What a build without items reads of such a row: kind '', no credential in - # `credential_enc`, a config with no folder. - assert source_sync._turn_of(dataclasses.replace(_source(), kind="")) is source_sync._turn - world.sources = [ - dataclasses.replace( - _source(), kind="", config={"include": ["docs"]}, items=[], credential_enc="" - ) - ] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - assert world.requests == [] - assert _detail(world)["status"] == "credential_invalid" - assert world.docs == {} - - -def test_a_source_s_items_are_listed_and_a_file_item_keeps_its_document(world: _World) -> None: - kept = _file("doc1", DOCS, "2026-01-01T00:00:00.000Z") - world.files = [kept, _file("doc2", DOCS, "2026-01-02T00:00:00.000Z")] - items = [ - {"type": "folder", "id": FOLDER, "recursive": False}, - {"type": "file", "id": "doc1"}, - ] - world.sources = [_source(items=items, secret_enc=seal("knowledge_sources.secret", KEY))] - world.sources[0] = dataclasses.replace(world.sources[0], credential_enc="") - world.file_answers["doc1"] = httpx.Response(200, json=kept) - asyncio.run(source_sync.run_sync()) - assert sorted(world.docs) == [_uri("doc1"), _uri("doc2")] - # The folder no longer lists either, and the store places both outside it: only the - # file the source names on its own stays. - world.files = [] - world.file_answers["doc2"] = httpx.Response( - 200, json={"trashed": False, "parents": ["elsewhere"], "mimeType": DOCS} - ) - asyncio.run(source_sync.run_sync(full=True)) - assert list(world.docs) == [_uri("doc1")] - - -def test_a_file_item_the_store_does_not_have_is_noted_and_the_rest_synced(world: _World) -> None: - items = [ - {"type": "folder", "id": FOLDER, "recursive": False}, - {"type": "file", "id": "missing1"}, - ] - world.sources = [_source(items=items)] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert list(world.docs) == [_uri("doc1")] - assert detail["status"] == "ok" and detail["error"] == "item 1: http_404" - - -def test_a_walk_cut_at_its_bound_retires_only_what_the_store_reports_gone( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-01T00:00:00.000Z"), - ] - world.sources = [_source(items=[{"type": "folder", "id": FOLDER, "recursive": True}])] - asyncio.run(source_sync.run_sync()) - assert sorted(world.docs) == [_uri("doc1"), _uri("doc2")] - - async def _cut(token: str, roots: list[str], out: Any, **_: Any) -> None: - out.folders.update(roots) - out.walk_cut = "more subfolders than a walk reads" - - monkeypatch.setattr(source_gdrive_items, "walk", _cut) - world.files = [] - # doc1 sits in a folder the walk did not reach; doc2 was trashed. - world.file_answers["doc1"] = httpx.Response(200, json={"trashed": False, "parents": ["deep"]}) - world.file_answers["doc2"] = httpx.Response(200, json={"trashed": True, "parents": ["deep"]}) - asyncio.run(source_sync.run_sync(full=True)) - assert list(world.docs) == [_uri("doc1")] - assert "more subfolders than a walk reads" in _detail(world)["error"] - - -def test_an_incomplete_listing_keeps_its_item_notes_behind_its_marker(world: _World) -> None: - items = [ - {"type": "folder", "id": FOLDER, "recursive": False}, - {"type": "file", "id": "missing1"}, - ] - world.sources = [_source(items=items)] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - world.incomplete_search = True - asyncio.run(source_sync.run_sync()) - # The marker first, so a long run of notes never cuts it off. - assert _detail(world)["error"] == "listing: incomplete search; item 1: http_404" - - -def test_a_turn_whose_pass_runs_out_before_the_walk_keeps_its_stamp( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - world.sources = [_source(items=[{"type": "folder", "id": FOLDER, "recursive": True}])] - asyncio.run(source_sync.run_sync()) - stamp = world.states["decks"]["state_value"] - # The pass's time runs out once the turn has its token, before the walk. - _run_out_after(monkeypatch, "access_token") - world.files.append(_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")) - asyncio.run(source_sync.run_sync()) - # Nothing is listed, so doc2 waits for the next pass and the stamp stays. - assert _uri("doc2") not in world.docs - assert world.states["decks"]["state_value"] == stamp - assert _detail(world)["error"] == "pass bound reached" - - -def _three_docs(world: _World) -> None: - world.files = [_file(f"doc{n}", DOCS, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2, 3)] - asyncio.run(source_sync.run_sync()) - assert len(world.docs) == 3 - - -def test_a_source_at_its_bound_writes_no_new_file_but_syncs_on( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - _three_docs(world) - # Exactly at the bound: the read is whole, the turn goes on, a new file waits. - monkeypatch.setattr(settings, "knowledge_source_max_documents", 3) - world.files.append(_file("doc4", DOCS, "2026-01-04T00:00:00.000Z")) - asyncio.run(source_sync.run_sync(full=True)) - detail = _detail(world) - assert _uri("doc4") not in world.docs and detail["status"] == "ok" - assert detail["error"].startswith("too_many_documents: 1 new files past 3") - - -def test_a_source_over_a_lowered_bound_still_retires_and_writes_nothing_new( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - _three_docs(world) - # More stored than the bound: every stored copy is still read and compared. - monkeypatch.setattr(settings, "knowledge_source_max_documents", 2) - world.files = [world.files[0], _file("doc4", DOCS, "2026-01-04T00:00:00.000Z")] - asyncio.run(source_sync.run_sync(full=True)) - detail = _detail(world) - assert sorted(world.docs) == [_uri("doc1")] and detail["status"] == "ok" - assert detail["error"].startswith("too_many_documents: 1 new files past 2") - - -def test_a_new_file_another_writer_holds_takes_no_room_under_the_bound( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_max_documents", 1) - world.docs[_uri("doc1")] = {"actor": "human:ann", "tags": [], "metadata": {}} - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - asyncio.run(source_sync.run_sync()) - assert _uri("doc2") in world.docs and _detail(world)["error"] == "" - - -def test_a_held_file_costs_no_read_of_its_address( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - monkeypatch.setattr(settings, "knowledge_source_max_documents", 1) - asked: list[str] = [] - may_write = source_sync._may_write - - async def _counted(src: Any, uri: str) -> bool: - asked.append(uri) - return await may_write(src, uri) - - monkeypatch.setattr(source_sync, "_may_write", _counted) - world.files.append(_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")) - asyncio.run(source_sync.run_sync(full=True)) - assert _uri("doc2") not in asked and _uri("doc2") not in world.docs - - -def test_a_new_file_the_store_refuses_takes_no_room_under_the_bound( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_max_documents", 1) - world.files = [ - _file("bad1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - world.file_answers["bad1"] = httpx.Response(403) - asyncio.run(source_sync.run_sync()) - assert list(world.docs) == [_uri("doc2")] and "too_many" not in _detail(world)["error"] - - -def test_a_new_file_past_the_room_is_counted_held_untried( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_max_documents", 1) - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("bad2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - # It would be refused, but past the room it is not tried, so it counts as held. - world.file_answers["bad2"] = httpx.Response(403) - asyncio.run(source_sync.run_sync()) - detail = _detail(world) - assert list(world.docs) == [_uri("doc1")] and detail["unconverted"] == 0 - assert detail["error"] == "too_many_documents: 1 new files past 1" - - -def test_a_moved_file_at_the_bound_takes_no_room( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - monkeypatch.setattr(settings, "knowledge_source_max_documents", 1) - moved = "https://docs.example.com/document/d/doc1/view" - world.files = [_file("doc1", DOCS, "2026-01-02T00:00:00.000Z", webViewLink=moved)] - asyncio.run(source_sync.run_sync(full=True)) - assert list(world.docs) == [moved] and _detail(world)["error"] == "" - - -def test_a_source_at_its_bound_still_retires_and_shrinks_back( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - _three_docs(world) - monkeypatch.setattr(settings, "knowledge_source_max_documents", 3) - # Two files leave the folder and one comes: the two are retired, the new one waits. - world.files = [world.files[0], _file("doc4", DOCS, "2026-01-04T00:00:00.000Z")] - asyncio.run(source_sync.run_sync(full=True)) - assert sorted(world.docs) == [_uri("doc1")] - # Under the bound again, the next full listing writes it. - asyncio.run(source_sync.run_sync(full=True)) - assert sorted(world.docs) == [_uri("doc1"), _uri("doc4")] - - -def test_the_bound_s_note_survives_a_long_run_of_item_notes( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [{"type": "folder", "id": FOLDER, "recursive": False}] - items += [{"type": "file", "id": f"missing{n:02d}"} for n in range(20)] - world.sources = [_source(items=items)] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - monkeypatch.setattr(settings, "knowledge_source_max_documents", 1) - world.files.append(_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")) - asyncio.run(source_sync.run_sync()) - assert _detail(world)["error"].startswith("too_many_documents: 1 new files past 1") - - -def test_a_full_listing_fails_on_a_shared_drive_the_account_left(world: _World) -> None: - items = [ - {"type": "folder", "id": FOLDER, "recursive": False}, - {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"}, - ] - world.sources = [_source(items=items)] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - # The drive answers 404: a full listing cannot say what is absent, so it fails. - asyncio.run(source_sync.run_sync(full=True)) - detail = _detail(world) - assert detail["status"] == "failed" and "http_404" in detail["error"] - - -def test_a_shared_drive_the_account_left_holds_the_stamp_of_a_partial_turn( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - from server.clients import gdrive - - list_query = gdrive.list_query - - async def _drive_left(token: str, query: str, **kw: Any) -> tuple[list[Any], bool]: - if kw.get("drive_id"): - raise gdrive.NotFound("drive") - return await list_query(token, query, **kw) - - folder = {"type": "folder", "id": FOLDER, "recursive": False} - world.sources = [_source(items=[folder])] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - monkeypatch.setattr(gdrive, "list_query", _drive_left) - world.sources = [_source(items=[folder, {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"}])] - world.files = [_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - # What the folder lists is written; nothing is retired and the stamp stays. - assert sorted(world.docs) == [_uri("doc1"), _uri("doc2")] - detail = _detail(world) - assert (detail["status"], detail["error"]) == ( - "ok", - "listing: an item listed nothing; item 1: http_404", - ) - assert world.states["decks"]["state_value"] == "2026-01-01T00:00:00.000Z" - - -def test_the_pass_bound_marker_leads_an_item_note( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 1) - items = [ - {"type": "folder", "id": FOLDER, "recursive": False}, - {"type": "file", "id": "missing1"}, - ] - world.sources = [_source(items=items)] - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - asyncio.run(source_sync.run_sync()) - assert _detail(world)["error"] == "pass bound reached; item 1: http_404" - - -def test_a_file_item_the_account_lost_is_retired_by_the_next_full_listing(world: _World) -> None: - meta = _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", trashed=False) - - def _seen(request: httpx.Request) -> httpx.Response: - if request.url.path.endswith("/export"): - return httpx.Response(200, text="# Design\n\nWe chose the planner.") - return httpx.Response(200, json=meta) - - world.sources = [_source(items=[{"type": "file", "id": "doc1"}])] - world.file_answers["doc1"] = _seen - asyncio.run(source_sync.run_sync()) - assert list(world.docs) == [_uri("doc1")] - world.file_answers["doc1"] = httpx.Response(404) - asyncio.run(source_sync.run_sync(full=True)) - assert world.docs == {} - assert _detail(world)["error"] == "item 0: http_404" - - -def test_a_full_turn_whose_pass_runs_out_after_the_listing_says_so( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - stamp = world.states["decks"]["state_value"] - # The pass's time runs out once the folder is listed, before its check. - _run_out_after(monkeypatch, "list_all") - # doc1 is gone from the folder and doc2 is new. - world.files = [_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")] - asyncio.run(source_sync.run_sync(full=True)) - # Unchecked, so nothing is written or retired, the stamp stays, and the turn says why. - assert list(world.docs) == [_uri("doc1")] - assert world.states["decks"]["state_value"] == stamp - assert _detail(world)["error"] == "pass bound reached" - - -def test_an_incomplete_search_the_pass_then_ran_out_on_names_both( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [ - {"type": "folder", "id": FOLDER, "recursive": False}, - {"type": "file", "id": "missing1"}, - ] - world.sources = [_source(items=items)] - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - world.incomplete_search = True - _run_out_after(monkeypatch, "list_all") - asyncio.run(source_sync.run_sync()) - assert _detail(world)["error"] == ("pass bound reached; listing: incomplete search") - - -@pytest.mark.parametrize( - ("mime", "note"), - [ - (DOCS, "item 0: not a kind the source's include names; name its kind in include"), - ("image/png", "item 0: 'image/png' is a type the sync does not read"), - ("application/vnd.google-apps.folder", "item 0: a folder; add it as a folder item"), - ], -) -def test_a_file_item_the_sync_does_not_read_is_noted_by_why( - world: _World, mime: str, note: str -) -> None: - world.sources = [_source(items=[{"type": "file", "id": "doc1"}], config={"include": ["pdf"]})] - world.file_answers["doc1"] = httpx.Response( - 200, json=_file("doc1", mime, "2026-01-01T00:00:00.000Z") - ) - asyncio.run(source_sync.run_sync()) - assert world.docs == {} and _detail(world)["error"] == note - - -def test_a_trashed_file_item_is_noted(world: _World) -> None: - world.sources = [_source(items=[{"type": "file", "id": "doc1"}])] - meta = _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", trashed=True) - world.file_answers["doc1"] = httpx.Response(200, json=meta) - asyncio.run(source_sync.run_sync()) - assert world.docs == {} and _detail(world)["error"] == "item 0: in the trash" - - -def test_a_cut_turn_s_marks_lead_the_held_back_files( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - asyncio.run(source_sync.run_sync()) - monkeypatch.setattr(settings, "knowledge_source_max_documents", 1) - world.incomplete_search = True - world.files.append(_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")) - asyncio.run(source_sync.run_sync()) - # The mark comes first, so the dashboard reads the turn as cut short. - assert _detail(world)["error"] == ( - "listing: incomplete search; too_many_documents: 1 new files past 1" - ) - - -def test_a_cut_walk_still_retires_a_kind_the_source_dropped( - world: _World, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - world.sources = [_source(items=[{"type": "folder", "id": FOLDER, "recursive": True}])] - asyncio.run(source_sync.run_sync()) - - async def _cut(token: str, roots: list[str], out: Any, **_: Any) -> None: - out.folders.update(roots) - out.walk_cut = "more subfolders than a walk reads" - - monkeypatch.setattr(source_gdrive_items, "walk", _cut) - folder = {"type": "folder", "id": FOLDER, "recursive": True} - world.sources = [_source(items=[folder], config={"include": ["pdf"]})] - world.files = [] - state = {"trashed": False, "parents": [FOLDER], "mimeType": DOCS} - world.file_answers["doc1"] = httpx.Response(200, json=state) - asyncio.run(source_sync.run_sync(full=True)) - # A kind the source no longer reads is not its own, cut walk or not. - assert world.docs == {} - - def test_every_stop_short_mark_reads_as_incomplete_on_the_dashboard() -> None: root = Path(__file__).resolve().parents[2] badge = (root / "frontend/src/lib/knowledgeSources.ts").read_text() @@ -3202,29 +1342,6 @@ def test_every_stop_short_mark_reads_as_incomplete_on_the_dashboard() -> None: # Out of time before the walk, or after the listing during the item check. -@pytest.mark.parametrize("after", ["access_token", "list_all"]) -def test_a_turn_out_of_pass_time_reads_no_stored_copies( - world: _World, monkeypatch: pytest.MonkeyPatch, after: str -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - world.sources = [_source(items=[{"type": "folder", "id": FOLDER, "recursive": True}])] - reads: list[str] = [] - real = world.source_revisions - - async def _counted(*a: Any, **kw: Any) -> list[dict[str, str]]: - # The turn's own read asks for the pictures on a full listing; the retirement - # and the extraction leg read without them. - if kw.get("pictures"): - reads.append("turn") - return await real(*a, **kw) - - monkeypatch.setattr(source_sync.store, "source_revisions", _counted) - asyncio.run(source_sync.run_sync(full=True)) - assert reads == ["turn"] # a full turn with time to spare reads them once - reads.clear() - _run_out_after(monkeypatch, after) - asyncio.run(source_sync.run_sync(full=True)) - assert reads == [] and _detail(world)["error"].startswith("pass bound reached") def test_the_pass_bound_mark_leads_an_earlier_mark() -> None: @@ -3253,7 +1370,7 @@ async def _turn(src: KnowledgeSource, state: Any, run: Any) -> Any: run.left = 0 return turn - monkeypatch.setattr(source_sync, "_turn", _turn) + monkeypatch.setattr(source_sync_recording, "turn", _turn) asyncio.run(source_sync.run_sync()) # On leftover time it goes first next; first and still starved, it moves on. assert cursor["at"] == f"{ORG}/{NS}/{resumes}" @@ -3283,7 +1400,7 @@ async def _turn(src: KnowledgeSource, state: Any, run: Any) -> Any: run.left = 0 return turn - monkeypatch.setattr(source_sync, "_turn", _turn) + monkeypatch.setattr(source_sync_recording, "turn", _turn) asyncio.run(source_sync.run_sync()) # bbb's request puts it first again; ccc, where the rest resumed, keeps its place. assert cursor["at"] == f"{ORG}/{NS}/ccc" @@ -3313,7 +1430,7 @@ async def _turn(src: KnowledgeSource, state: Any, run: Any) -> Any: run.left = 0 return turn - monkeypatch.setattr(source_sync, "_turn", _turn) + monkeypatch.setattr(source_sync_recording, "turn", _turn) asyncio.run(source_sync.run_sync()) asyncio.run(source_sync.run_sync()) # Pass 1: bbb led the rest and ran out, so pass 2 starts the rest at ccc; there bbb, @@ -3340,7 +1457,7 @@ def test_only_a_retired_meet_turn_is_not_a_pass_failure( status: str, expected_failures: int, ) -> None: - src = dataclasses.replace(_source(), kind=kind, config={"provider": provider}, items=[]) + src = dataclasses.replace(_source(), kind=kind, config={"provider": provider}) world.sources = [src] before = { "requested_at": "2026-01-01T00:00:00Z", @@ -3354,7 +1471,7 @@ async def _turn(source: Any, state: Any, run: Any) -> source_sync.TurnResult: return source_sync.TurnResult( status=status, complete=False, - error="Meet transcripts use a gdrive shared-folder source", + error="retired provider", ) monkeypatch.setattr(source_sync, "_turn_of", lambda source: _turn) @@ -3371,38 +1488,4 @@ async def _turn(source: Any, state: Any, run: Any) -> source_sync.TurnResult: detail = _detail(world, src.name) assert detail["status"] == status assert {key: detail[key] for key in before} == before - assert not world.requests and not world.upserts and not world.audits - - -@pytest.mark.parametrize( - ("body", "expected_format"), - [ - ( - "## **Planning**\n\n# **Attendees**\n\nSpeaker A, Speaker B\n\n" - "# **Transcript**\n\n### 00:05:00\n\nSpeaker A: Keep the proposal.\n\n" - "### 01:05:00\n\nSpeaker B: Check the revised figures.\n\n" - "### Meeting ended after 01:06:00 👋\n\n" - "*This editable transcript was computer generated and might contain errors. " - "People can also change the text after it was created.*\n", - "transcript", - ), - ("# Meeting notes\n\nKeep the proposal.\n", "markdown"), - ("# Transcript\n\nSpeaker A: No elapsed markers were supplied.\n", "markdown"), - ], -) -def test_drive_fetch_classifies_timed_transcripts_without_rewriting_the_export( - world: _World, monkeypatch: pytest.MonkeyPatch, body: str, expected_format: str -) -> None: - calls: list[tuple[Any, str]] = [] - - async def _export(token: Any, file_id: str, **kwargs: Any) -> str: - calls.append((token, file_id)) - return body - - monkeypatch.setattr(gdrive, "export_markdown", _export) - fetched = asyncio.run(source_sync._fetch("tok", {"id": "doc1", "mimeType": DOCS})) - assert fetched.content == body - assert fetched.ingested_format == expected_format - assert fetched.original == b"" and fetched.coverage == {} - assert calls == [("tok", "doc1")] - assert not world.requests and not world.upserts and not world.audits + assert not world.recording_lists and not world.upserts and not world.audits diff --git a/tests/unit/test_knowledge_source_sync_diagnostics.py b/tests/unit/test_knowledge_source_sync_diagnostics.py index a05d19409b..8e27d3601a 100644 --- a/tests/unit/test_knowledge_source_sync_diagnostics.py +++ b/tests/unit/test_knowledge_source_sync_diagnostics.py @@ -10,12 +10,10 @@ import pytest -from server.knowledge.app import extractors from server.knowledge.app import source_sync as sync -from server.knowledge.domain import access_list -from server.knowledge.domain.sources import MIRRORED_ACCESS from server.knowledge.workers.source_sync import outcome -from tests.unit.test_knowledge_source_sync import DOCS, _file, _source +from tests.unit.test_knowledge_source_sync import _source +from tests.unit.test_mcp_source_sync import harness as harness @pytest.fixture @@ -40,7 +38,7 @@ def failure(error: Exception, *args: Any) -> None: @pytest.mark.parametrize("mirrored", [False, True]) def test_document_figures_stay_in_private_turn( - boundary: dict[str, Any], monkeypatch: pytest.MonkeyPatch, mirrored: bool + boundary: dict[str, Any], monkeypatch: pytest.MonkeyPatch, harness, mirrored: bool ) -> None: answers = [] for count in (1, 10000): @@ -58,7 +56,7 @@ async def run(*args: Any, answer: Any = turn) -> Any: return answer monkeypatch.setattr(sync, "_turn_of", lambda src: run) - src = _source(access=MIRRORED_ACCESS) if mirrored else _source() + src = harness.source if mirrored else _source() result = sync.PassResult(sources=1) assert asyncio.run(sync._sync_one(src, {}, None, result)) is turn assert boundary["states"][-1] is turn @@ -75,6 +73,7 @@ def test_mirrored_failures_have_one_boundary_code( boundary: dict[str, Any], monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, + harness, where: str, ) -> None: answers = [] @@ -97,9 +96,9 @@ async def state(*args: Any, exc: Exception = error) -> None: monkeypatch.setattr(sync, "_write_state", state) result = sync.PassResult() with caplog.at_level(logging.INFO, logger=sync.log.name): - asyncio.run(sync._sync_one(_source(access=MIRRORED_ACCESS), {}, None, result)) + asyncio.run(sync._sync_one(harness.source, {}, None, result)) assert "private-file" not in caplog.text - assert result.errors == ["acme/code-acme-app/decks: SYNC_FAILED"] + assert result.errors == ["org/collection/selected: SYNC_FAILED"] assert result.failed == 0 assert boundary["failures"] == [("RuntimeError", "SYNC_FAILED")] answers.append((dataclasses.asdict(result), caplog.messages[:])) @@ -119,47 +118,3 @@ async def run(*args: Any) -> Any: assert result.errors == ["acme/code-acme-app/decks: failed ValueError"] assert "namespace diagnostic" in caplog.text assert boundary["failures"] == [("RuntimeError", "ValueError")] - - -@pytest.mark.parametrize("mirrored", [False, True]) -@pytest.mark.parametrize("stage", ["extract", "fetch", "write"]) -def test_per_file_failures_emit_no_mirrored_log( - monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, - mirrored: bool, - stage: str, -) -> None: - async def fetch(*args: Any) -> Any: - if stage == "extract": - raise extractors.ExtractionFailed("corrupt", "private extractor output") - if stage == "fetch": - raise ValueError("private fetch output") - return sync._Fetched("text", "markdown") - - async def write(*args: Any, **kw: Any) -> Any: - raise ValueError("private write output") - - async def current(*args: Any) -> None: - pass - - monkeypatch.setattr(sync, "_fetch", fetch) - monkeypatch.setattr(sync, "write_document", write) - monkeypatch.setattr(sync, "require_current", current) - src = _source(access=MIRRORED_ACCESS) if mirrored else _source() - turn = sync.TurnResult(kind_state={sync._PICTURES_CHECKED: {}}) - with caplog.at_level(logging.INFO, logger=sync.log.name): - for i in range(3): - file = _file(f"private-file-{i}", DOCS, "revision") - asyncio.run( - sync._fetch_and_write( - src, - "token", - file, - "uri", - turn, - stored_content_sha256="", - permissions=access_list.UNREAD, - ) - ) - assert len(turn.waits) == 3 - assert len(caplog.records) == (0 if mirrored else 3) diff --git a/tests/unit/test_knowledge_source_sync_linear.py b/tests/unit/test_knowledge_source_sync_linear.py deleted file mode 100644 index 279f83c12e..0000000000 --- a/tests/unit/test_knowledge_source_sync_linear.py +++ /dev/null @@ -1,583 +0,0 @@ -"""The sync turn of a tracker project's documents -(server/knowledge/app/source_sync_linear.py) over the in-memory registry and -document store of test_knowledge_source_sync and a GraphQL API answered by a mock -transport: what a turn lists, fetches, writes and retires, and how each failure is -told apart. Every response is written here; none is a recording of real content.""" - -from __future__ import annotations - -import asyncio -import dataclasses -import json -from typing import Any - -import httpx -import pytest - -from server.clients import linear -from server.core.secrets_at_rest import seal -from server.knowledge.app import source_sync -from server.knowledge.domain.sources import SYNC_WORKER_ACTOR, items_from_config -from server.settings import settings -from tests.unit.test_knowledge_source_sync import _detail, _source, _World -from tests.unit.test_knowledge_source_sync import world as world # the fixture - -PROJECT = "0b6d7a52-1c1e-4c2b-9a4e-5d0f3b1e2a01" -OTHER = "7e3f9c10-8a2b-4d5e-b6f7-0123456789ab" -KEY = "lin_api_unit-test-key" - - -def _doc_id(n: int) -> str: - return f"00000000-0000-4000-8000-{n:012d}" - - -def _node(n: int, updated: str, *, title: str = "") -> dict[str, Any]: - title = title or f"Design {n}" - slug = title.lower().replace(" ", "-") - return { - "id": _doc_id(n), - "title": title, - "updatedAt": updated, - "url": f"https://tracker.example.com/acme/document/{slug}-{n}?ref=x", - } - - -class _Tracker: - """A project's documents as the GraphQL API answers them, two to a page.""" - - page = 2 - - def __init__(self) -> None: - self.projects: dict[str, list[dict[str, Any]]] = {PROJECT: [], OTHER: []} - self.requests: list[dict[str, Any]] = [] - self.headers: list[str] = [] - # Answers that override the store's, by operation name or document id. - self.answers: dict[str, Any] = {} - # Document id -> its lookup answer (trashed, archivedAt, project). - self.states: dict[str, dict[str, Any]] = {} - - def fetches(self, document_id: str = "") -> int: - return sum( - 1 - for r in self.requests - if r["op"] == "Document" and (not document_id or r["variables"]["id"] == document_id) - ) - - def answer(self, request: httpx.Request) -> httpx.Response: - body = json.loads(request.content) - op = body["query"].split("query ", 1)[1].split("(", 1)[0] - variables = body["variables"] - self.requests.append({"op": op, "variables": variables}) - self.headers.append(request.headers["authorization"]) - for key in (op, variables.get("id")): - if key in self.answers: - answer = self.answers[key] - return answer(request) if callable(answer) else answer - if op == "ProjectDocuments": - nodes = self.projects.get(variables["id"]) - if nodes is None: - return _not_found("Project") - start = int(variables.get("after") or 0) - page = nodes[start : start + self.page] - more = start + self.page < len(nodes) - info = {"hasNextPage": more, "endCursor": str(start + self.page) if more else None} - data = {"id": variables["id"], "documents": {"nodes": page, "pageInfo": info}} - return httpx.Response(200, json={"data": {"project": data}}) - if op == "Document": - node = self._find(variables["id"]) - if node is None: - return _not_found("Document") - content = f"# {node['title']}\n\nWe keep the hash join.\n" - return httpx.Response(200, json={"data": {"document": {**node, "content": content}}}) - if op == "DocumentState": - if variables["id"] in self.states: - state = self.states[variables["id"]] - return httpx.Response(200, json={"data": {"document": state}}) - return _not_found("Document") - return httpx.Response(400) - - def _find(self, document_id: str) -> dict[str, Any] | None: - for nodes in self.projects.values(): - for node in nodes: - if node["id"] == document_id: - return node - return None - - -def _not_found(entity: str) -> httpx.Response: - error = { - "message": "Entity not found", - "extensions": { - "type": "invalid input", - "userPresentableMessage": f"Could not find referenced {entity}.", - }, - } - return httpx.Response(400, json={"errors": [error], "data": None}) - - -def _graphql_error(status: int, code: str, message: str = "x") -> httpx.Response: - error = {"message": message, "extensions": {"code": code}} - return httpx.Response(status, json={"errors": [error], "data": None}) - - -def _linear_source(**kw: Any) -> Any: - """The harness's source, of this kind.""" - config = kw.pop("config", {"project_ids": [PROJECT, OTHER]}) - fields = { - "kind": "linear", - "config": config, - "items": items_from_config("linear", config), - "credential_enc": seal("knowledge_sources.credential", KEY), - **kw, - } - return dataclasses.replace(_source(), **fields) - - -@pytest.fixture -def tracker(world: _World, monkeypatch: pytest.MonkeyPatch) -> _Tracker: - t = _Tracker() - client = httpx.AsyncClient(transport=httpx.MockTransport(t.answer)) - monkeypatch.setattr(linear, "get_client", lambda: client) - monkeypatch.setattr(linear, "PAGE_PACE_S", 0.0) - world.sources = [_linear_source()] - return t - - -def _sync(**kw: Any) -> source_sync.PassResult: - return asyncio.run(source_sync.run_sync(**kw)) - - -def test_a_turn_writes_every_project_s_documents_across_pages( - world: _World, tracker: _Tracker -) -> None: - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2, 3)] - tracker.projects[OTHER] = [_node(4, "2026-01-04T00:00:00.000Z")] - result = _sync() - assert result.changed == 4 and result.failed == 0 - listings = [r for r in tracker.requests if r["op"] == "ProjectDocuments"] - assert [r["variables"].get("after") for r in listings] == [None, "2", None] - # The key goes as it is, never as a bearer token. - assert set(tracker.headers) == {KEY} - inp, actor = world.upserts[0] - assert actor == SYNC_WORKER_ACTOR and inp.source_class == "imported" - assert inp.source_uri == "https://tracker.example.com/acme/document/design-1-1" - assert inp.title == "Design 1" and inp.description == "We keep the hash join." - assert inp.tags == ["source-kind:design_doc", "repo:abc", "source:decks"] - assert inp.metadata == { - "source_kind": "linear", - "source_name": "decks", - "source_revision": "2026-01-01T00:00:00.000Z", - "ingested_from": _doc_id(1), - "ingested_format": "markdown", - } - assert inp.original_bytes_b64 is None - detail = _detail(world) - assert detail["status"] == "ok" and detail["documents_seen"] == 4 - assert world.states["decks"]["state_value"] == "2026-01-04T00:00:00.000Z" - - -def test_an_unchanged_document_is_not_fetched_and_a_changed_one_is( - world: _World, tracker: _Tracker -) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - tracker.projects[OTHER] = [_node(2, "2026-01-02T00:00:00.000Z")] - _sync() - tracker.requests.clear() - tracker.projects[OTHER] = [_node(2, "2026-02-01T00:00:00.000Z")] - result = _sync() - assert result.changed == 1 - assert tracker.fetches(_doc_id(1)) == 0 and tracker.fetches(_doc_id(2)) == 1 - - -def test_a_renamed_document_moves_to_its_new_address(world: _World, tracker: _Tracker) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - _sync() - tracker.projects[PROJECT] = [_node(1, "2026-01-05T00:00:00.000Z", title="Planner")] - result = _sync() - assert result.changed == 1 and result.removed == 1 - assert list(world.docs) == ["https://tracker.example.com/acme/document/planner-1"] - - -@pytest.mark.parametrize( - "state, retired", - [ - (None, True), # the lookup finds nothing - ({"id": "x", "trashed": True, "project": {"id": PROJECT}}, True), - ({"id": "x", "archivedAt": "2026-01-09T00:00:00.000Z", "project": {"id": PROJECT}}, True), - ({"id": "x", "project": {"id": "11111111-2222-4333-8444-555555555555"}}, True), - ({"id": "x", "project": None}, True), - # Missed by the list, but the tracker still has it in the project. - ({"id": "x", "trashed": False, "project": {"id": OTHER}}, False), - ], -) -def test_a_document_missing_from_a_complete_list_is_retired_only_once_the_lookup_agrees( - world: _World, tracker: _Tracker, state: dict[str, Any] | None, retired: bool -) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - tracker.projects[OTHER] = [_node(2, "2026-01-02T00:00:00.000Z")] - _sync() - tracker.projects[OTHER] = [] - if state is not None: - tracker.states[_doc_id(2)] = state - result = _sync() - assert result.removed == (1 if retired else 0) - assert (len(world.docs) == 1) is retired - deletes = [a for a in world.audits if a["event"] == "knowledge.delete"] - assert len(deletes) == (1 if retired else 0) - if retired: - assert deletes[0]["actor"] == SYNC_WORKER_ACTOR - - -def test_a_project_the_key_cannot_see_retires_nothing(world: _World, tracker: _Tracker) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - tracker.projects[OTHER] = [_node(2, "2026-01-02T00:00:00.000Z")] - _sync() - stamp = world.states["decks"]["state_value"] - del tracker.projects[OTHER] # the key lost the project: its list is refused - tracker.projects[PROJECT].append(_node(3, "2026-01-03T00:00:00.000Z")) - result = _sync() - assert result.removed == 0 and result.changed == 1 and len(world.docs) == 3 - detail = _detail(world) - assert detail["status"] == "failed" and detail["error"] == f"project {OTHER}: not_found" - assert world.states["decks"]["state_value"] == stamp - assert not [r for r in tracker.requests if r["op"] == "DocumentState"] - - -@pytest.mark.parametrize( - "answer", - [ - _graphql_error(400, "RATELIMITED", "Rate limit exceeded"), - _graphql_error(200, "RATELIMITED"), - httpx.Response(429, text="slow down"), - ], -) -def test_a_rate_limit_in_any_shape_ends_the_turn( - world: _World, tracker: _Tracker, answer: httpx.Response -) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - _sync() - tracker.projects[PROJECT] = [] - tracker.answers["ProjectDocuments"] = answer - result = _sync() - assert result.removed == 0 and len(world.docs) == 1 - detail = _detail(world) - assert detail["status"] == "rate_limited" and detail["error"] == "rate_limited" - - -def test_a_rate_limit_on_a_fetch_stops_the_turn(world: _World, tracker: _Tracker) -> None: - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2)] - tracker.answers[_doc_id(1)] = _graphql_error(400, "RATELIMITED") - result = _sync() - assert result.changed == 0 and tracker.fetches(_doc_id(2)) == 0 - assert _detail(world)["status"] == "rate_limited" - assert world.states["decks"]["state_value"] == "" - - -def test_a_refused_key_is_the_turn_s_credential(world: _World, tracker: _Tracker) -> None: - tracker.answers["ProjectDocuments"] = _graphql_error(400, "AUTHENTICATION_ERROR") - _sync() - detail = _detail(world) - assert detail["status"] == "credential_invalid" - assert detail["error"] == f"project {PROJECT}: credential_refused" - - -def test_an_answer_with_any_error_is_no_list(world: _World, tracker: _Tracker) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - tracker.projects[OTHER] = [_node(2, "2026-01-02T00:00:00.000Z")] - _sync() - # Some data and an error: the list may be missing documents. - partial = { - "data": {"project": {"id": OTHER, "documents": {"nodes": [], "pageInfo": {}}}}, - "errors": [{"message": "x", "extensions": {"type": "internal error"}}], - } - tracker.answers["ProjectDocuments"] = httpx.Response(200, json=partial) - result = _sync() - assert result.removed == 0 and len(world.docs) == 2 - assert _detail(world)["error"] == f"project {PROJECT}: graphql_internal_error" - - -def test_a_next_page_without_a_cursor_is_no_list(world: _World, tracker: _Tracker) -> None: - info = {"hasNextPage": True, "endCursor": None} - page = {"data": {"project": {"id": PROJECT, "documents": {"nodes": [], "pageInfo": info}}}} - tracker.answers["ProjectDocuments"] = httpx.Response(200, json=page) - _sync() - assert _detail(world)["error"] == f"project {PROJECT}: no_cursor" - - -def test_a_next_page_with_the_same_cursor_is_no_list(world: _World, tracker: _Tracker) -> None: - info = {"hasNextPage": True, "endCursor": "c1"} - page = {"data": {"project": {"id": PROJECT, "documents": {"nodes": [], "pageInfo": info}}}} - tracker.answers["ProjectDocuments"] = httpx.Response(200, json=page) - _sync() - assert _detail(world)["error"] == f"project {PROJECT}: no_cursor" - listings = [r for r in tracker.requests if r["op"] == "ProjectDocuments"] - assert [r["variables"].get("after") for r in listings][:2] == [None, "c1"] - - -def test_a_page_without_page_info_is_no_list(world: _World, tracker: _Tracker) -> None: - page = {"data": {"project": {"id": PROJECT, "documents": {"nodes": []}}}} - tracker.answers["ProjectDocuments"] = httpx.Response(200, json=page) - _sync() - assert _detail(world)["error"] == f"project {PROJECT}: no_page_info" - - -def test_one_document_s_failure_waits_for_that_document_alone( - world: _World, tracker: _Tracker -) -> None: - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2)] - tracker.answers[_doc_id(1)] = httpx.Response(502) - first = _sync() - assert first.changed == 1 and len(world.docs) == 1 - detail = _detail(world) - assert detail["status"] == "failed" and detail["error"] == f"document {_doc_id(1)}: http_502" - assert world.states["decks"]["state_value"] == "" - _sync() - third = _sync() - # Three passes on the same revision: given up, and the stamp moves. - assert third.unconverted == 1 - assert _detail(world)["unconverted_reasons"] == {"http_502": 1} - assert world.states["decks"]["state_value"] == "2026-01-02T00:00:00.000Z" - tracker.requests.clear() - _sync() - assert tracker.fetches(_doc_id(1)) == 0 - - -def test_a_document_over_the_size_bound_is_given_up_at_once( - world: _World, tracker: _Tracker, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 64) - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - result = _sync() - assert result.unconverted == 1 and not world.docs - assert _detail(world)["unconverted_reasons"] == {"too_large": 1} - assert _detail(world)["status"] == "ok" - tracker.requests.clear() - _sync() - assert tracker.fetches() == 0 - # A new revision is tried again. - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 10**6) - tracker.projects[PROJECT] = [_node(1, "2026-01-02T00:00:00.000Z")] - assert _sync().changed == 1 - - -def test_a_document_another_writer_holds_is_not_fetched(world: _World, tracker: _Tracker) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - uri = "https://tracker.example.com/acme/document/design-1-1" - world.docs[uri] = {"actor": "alice", "tags": [], "metadata": {}} - result = _sync() - assert result.skipped == 1 and tracker.fetches() == 0 - assert world.docs[uri]["actor"] == "alice" - - -def test_the_document_bound_cuts_the_turn( - world: _World, tracker: _Tracker, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_documents_per_pass", 2) - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2, 3)] - first = _sync() - assert first.changed == 2 and first.cut - assert world.states["decks"]["state_value"] == "" - second = _sync() - assert second.changed == 1 and _detail(world)["error"] == "" - - -def test_a_project_source_at_its_bound_writes_no_new_document( - world: _World, tracker: _Tracker, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_max_documents", 2) - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2, 3)] - result = _sync() - assert result.changed == 2 and not result.cut - assert _detail(world)["error"] == "too_many_documents: 1 new files past 2" - - -def test_a_credential_that_no_longer_opens_calls_nothing(world: _World, tracker: _Tracker) -> None: - world.sources = [_linear_source(credential_enc="not-sealed")] - _sync() - assert _detail(world)["status"] == "credential_invalid" and not tracker.requests - - -def _two_synced(tracker: _Tracker) -> None: - """Documents 1 and 2 synced, then document 2 dropped from its project's list.""" - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - tracker.projects[OTHER] = [_node(2, "2026-01-02T00:00:00.000Z")] - _sync() - tracker.projects[OTHER] = [] - - -def _lookups(tracker: _Tracker) -> int: - return sum(1 for r in tracker.requests if r["op"] == "DocumentState") - - -@pytest.mark.parametrize( - "answer", - [ - httpx.Response(200, json={"data": {}}), - httpx.Response(200, json={"data": {"document": None}}), - httpx.Response(503), - _graphql_error(400, "FORBIDDEN"), - _graphql_error(200, "INTERNAL_ERROR"), - ], -) -def test_a_lookup_that_does_not_say_not_found_retires_nothing( - world: _World, tracker: _Tracker, answer: httpx.Response -) -> None: - _two_synced(tracker) - tracker.answers["DocumentState"] = answer - result = _sync() - assert _lookups(tracker) == 1 - assert result.removed == 0 and len(world.docs) == 2 - assert _detail(world)["status"] == "ok" - - -@pytest.mark.parametrize( - "answer, status", - [ - (_graphql_error(400, "RATELIMITED"), "rate_limited"), - (httpx.Response(429), "rate_limited"), - (_graphql_error(400, "AUTHENTICATION_ERROR"), "credential_invalid"), - (httpx.Response(401), "credential_invalid"), - ], -) -def test_a_rate_limit_or_a_refused_key_on_a_lookup_stops_the_retiring( - world: _World, tracker: _Tracker, answer: httpx.Response, status: str -) -> None: - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2, 3)] - _sync() - tracker.projects[PROJECT] = [] - tracker.answers["DocumentState"] = answer - result = _sync() - assert _lookups(tracker) == 1 # the first lookup stops the others - assert result.removed == 0 and len(world.docs) == 3 - assert _detail(world)["status"] == status - - -def test_a_stored_document_with_no_usable_id_is_never_looked_up_or_retired( - world: _World, tracker: _Tracker -) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - uri = "https://tracker.example.com/acme/document/kept-9" - world.docs[uri] = { - "actor": SYNC_WORKER_ACTOR, - "tags": ["source:decks"], - "metadata": {"ingested_from": "not-an-id", "source_revision": "x"}, - } - result = _sync() - assert result.removed == 0 and uri in world.docs and _lookups(tracker) == 0 - - -@pytest.mark.parametrize( - "answer", - [ - httpx.Response(200, json={"data": {}}), - httpx.Response(200, json={"data": {"document": None}}), - ], -) -def test_a_fetch_answered_without_the_document_waits( - world: _World, tracker: _Tracker, answer: httpx.Response -) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - tracker.answers["Document"] = answer - result = _sync() - assert result.changed == 0 and result.unconverted == 0 - detail = _detail(world) - assert detail["status"] == "failed" and detail["error"] == f"document {_doc_id(1)}: no_document" - assert detail["file_waits"][_doc_id(1)][1] == 1 - - -def test_a_refused_fetch_is_given_up_at_once_and_an_internal_error_waits( - world: _World, tracker: _Tracker -) -> None: - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2, 3, 4)] - tracker.answers[_doc_id(1)] = _graphql_error(200, "FORBIDDEN") - tracker.answers[_doc_id(4)] = _graphql_error(400, "FORBIDDEN") - tracker.answers[_doc_id(2)] = _graphql_error(200, "INTERNAL_ERROR") - # The tracker answers its internal errors with a 400 too: the type decides. - tracker.answers[_doc_id(3)] = _graphql_error(400, "INTERNAL_ERROR") - result = _sync() - assert result.unconverted == 2 - detail = _detail(world) - assert detail["unconverted_reasons"] == {"graphql_forbidden": 2} - assert detail["status"] == "failed" - assert detail["error"] == f"document {_doc_id(2)}: graphql_internal_error" - tracker.requests.clear() - _sync() - assert tracker.fetches(_doc_id(1)) == 0 and tracker.fetches(_doc_id(4)) == 0 - assert tracker.fetches(_doc_id(2)) == 1 and tracker.fetches(_doc_id(3)) == 1 - assert _detail(world)["file_waits"][_doc_id(3)][1:] == [2, "graphql_internal_error"] - - -def test_the_key_and_the_tracker_s_text_never_reach_the_state( - world: _World, tracker: _Tracker -) -> None: - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2)] - echo = f"bad key {KEY} for Roadmap" - tracker.answers[_doc_id(1)] = _graphql_error(200, "FORBIDDEN", echo) - tracker.answers[_doc_id(2)] = _graphql_error(502, "INTERNAL_ERROR", echo) - _sync() - assert tracker.fetches(_doc_id(1)) == 1 and tracker.fetches(_doc_id(2)) == 1 - state = json.dumps(world.states["decks"]) - assert KEY not in state and "Roadmap" not in state - # The list refused for the key, with the key in the tracker's text. - tracker.answers[OTHER] = _graphql_error(400, "AUTHENTICATION_ERROR", echo) - _sync() - assert _detail(world)["status"] == "credential_invalid" - state = json.dumps(world.states["decks"]) - assert KEY not in state and "Roadmap" not in state - - -def test_list_pages_are_paced( - world: _World, tracker: _Tracker, monkeypatch: pytest.MonkeyPatch -) -> None: - slept: list[float] = [] - - async def _sleep(seconds: float) -> None: - slept.append(seconds) - - monkeypatch.setattr(linear, "PAGE_PACE_S", 0.5) - monkeypatch.setattr(linear, "_sleep", _sleep) - tracker.projects[PROJECT] = [_node(n, f"2026-01-0{n}T00:00:00.000Z") for n in (1, 2, 3, 4, 5)] - _sync() - assert slept == [0.5, 0.5] # three pages of the first project, one of the other - - -def test_an_untyped_403_on_a_fetch_is_given_up_at_once(world: _World, tracker: _Tracker) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - tracker.answers[_doc_id(1)] = httpx.Response(403) - result = _sync() - assert result.unconverted == 1 and _detail(world)["status"] == "ok" - assert _detail(world)["unconverted_reasons"] == {"http_403": 1} - tracker.requests.clear() - _sync() - assert tracker.fetches(_doc_id(1)) == 0 - - -def test_a_project_s_documents_are_mined_by_the_same_leg(world: _World, tracker: _Tracker) -> None: - tracker.projects[PROJECT] = [_node(1, "2026-01-01T00:00:00.000Z")] - result = _sync() - uri = "https://tracker.example.com/acme/document/design-1-1" - assert [u for u, actor, _ in world.mined] == [uri] and result.extracted == 1 - assert _detail(world)["mined"] == {uri: "2026-01-01T00:00:00.000Z"} - _sync() - assert len(world.mined) == 1 - - -def test_an_address_taken_during_the_fetch_is_counted_skipped( - world: _World, tracker: _Tracker -) -> None: - """The address is free when the project is listed; a person writes there while the - document is fetched. The write step reads the address again and leaves theirs.""" - node = _node(1, "2026-01-01T00:00:00.000Z") - tracker.projects[PROJECT] = [node] - uri = "https://tracker.example.com/acme/document/design-1-1" - - def _fetch(request: httpx.Request) -> httpx.Response: - world.docs[uri] = {"actor": "human:ann", "tags": [], "metadata": {}} - document = {**node, "content": "# Design 1\n\nWe keep the hash join.\n"} - return httpx.Response(200, json={"data": {"document": document}}) - - tracker.answers[_doc_id(1)] = _fetch - result = _sync() - assert world.upserts == [] - assert world.docs[uri]["actor"] == "human:ann" - assert (result.skipped, result.changed) == (1, 0) diff --git a/tests/unit/test_knowledge_source_sync_mirror.py b/tests/unit/test_knowledge_source_sync_mirror.py index eb5f3e0dbf..40e472d6de 100644 --- a/tests/unit/test_knowledge_source_sync_mirror.py +++ b/tests/unit/test_knowledge_source_sync_mirror.py @@ -1,170 +1,28 @@ -"""A mirrored folder-store source's turn (server/knowledge/app/source_sync_mirror.py): its -files land in the namespace's mirror with the lists the store gives them, a changed list -is written without embedding again, an absent file reads `unread` before it is retired, -and the listing row lands last.""" - -from __future__ import annotations +"""Generic mirror allocation and namespace boundaries.""" import asyncio import contextlib -import dataclasses from collections.abc import AsyncIterator +from dataclasses import replace from typing import Any -import httpx import pytest -from server.clients import gdrive -from server.code.app.index.pass_budget import PassBudget -from server.core.secrets_at_rest import seal -from server.knowledge.app import mirrors, source_sync, source_sync_mirror -from server.knowledge.app import source_gdrive_items as gdrive_items -from server.knowledge.domain import access_list -from server.knowledge.domain.sources import MIRRORED_ACCESS, home, mirror_uri -from server.knowledge.store import documents -from server.knowledge.store import mirrors as mirror_store -from server.settings import settings -from tests.unit.test_knowledge_source_sync import DOCS, FOLDER, KEY, PDF, _detail, _file, _source -from tests.unit.test_knowledge_source_sync import world as world # the fixture +from server.knowledge.app import mirrors, source_sync +from server.knowledge.domain.sources import MIRRORED_ACCESS, home +from tests.unit.test_knowledge_source_sync import _source MIRROR = "acl-" + "a" * 24 -READERS = [{"type": "user", "role": "reader", "emailAddress": "Ann@example.com"}] - - -def _mirrored(**kw: Any) -> Any: - src = _source(access=MIRRORED_ACCESS, credential_enc="", **kw) - return dataclasses.replace(src, secret_enc=seal("knowledge_sources.secret", KEY)) - - -def _own(world: Any) -> dict[str, Any]: - """The turn's own state, under the mirror and the source's id.""" - return _detail(world, _mirrored().source_id) - - -@pytest.fixture -def mirror(world: Any, monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: - """The namespace's mirror, the listing rows recorded and the list-only rewrites.""" - seen: dict[str, Any] = {"listings": [], "rewrites": [], "permission_reads": []} - - async def _live(org: str, namespace: str) -> str: - return MIRROR - - async def _listing(org: str, namespace: str, source_id: str, name: str, started: Any) -> None: - seen["listings"].append((namespace, source_id, name)) - - async def _get_many(org: str, namespace: str, uris: list[str], **kw: Any) -> list[Any]: - found = [await documents.get_one(org, namespace, uri) for uri in uris] - return [d for d in found if d is not None] - async def _insert_many(rows: list[Any], *, over: Any, **kw: Any) -> int: - for row in rows: - seen["rewrites"].append(row) - world.docs[row["source_uri"]]["access_json"] = row["access_json"] - return len(rows) - async def _permissions(token: str, file_id: str, **kw: Any) -> Any: - seen["permission_reads"].append(file_id) - return None # the store will not say - - monkeypatch.setattr(mirrors, "live_mirror", _live) - monkeypatch.setattr(source_sync_mirror, "PERMISSIONS_PACE_S", 0) - monkeypatch.setattr(mirror_store, "record_listing", _listing) - monkeypatch.setattr(documents, "get_many_by_uris", _get_many) - monkeypatch.setattr(documents, "insert_many", _insert_many) - monkeypatch.setattr(gdrive, "file_permissions", _permissions) - return seen +def _mirrored(): + return replace(_source(), access=MIRRORED_ACCESS) async def _current() -> None: return None -def _turn(world: Any, src: Any) -> Any: - world.sources = [src] - return asyncio.run(source_sync.run_sync()) - - -def test_a_mirrored_file_lands_in_the_mirror_with_its_list( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(source_sync, "_repo_tag", lambda src: "repo:abc") # a trunk namespace - src = _mirrored() - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - result = _turn(world, src) - assert result.synced == 0 and result.changed == 0 - [(written, _)] = world.upserts - address = source_sync.source_uri_of(world.files[0]) - assert written.namespace == MIRROR - assert written.source_uri == mirror_uri(address, src.source_id) - # No repository tag: a repository's document reads must never reach a mirror. - assert written.tags == ["source-kind:design_doc", "source:decks", f"source-id:{src.source_id}"] - stored = access_list.from_json(world.docs[written.source_uri]["access_json"]) - assert stored.emails == ("ann@example.com",) - assert mirror["listings"] == [(MIRROR, src.source_id, src.name)] - - -def test_a_file_listed_without_permissions_is_read_and_unread_when_the_store_will_not_say( - world: Any, mirror: Any -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - _turn(world, _mirrored()) - assert mirror["permission_reads"] == ["doc1"] - [(written, _)] = world.upserts - assert world.docs[written.source_uri]["access_json"] == "" # unread - - -def test_a_narrowed_list_rewrites_the_row_and_the_same_list_writes_nothing( - world: Any, mirror: Any -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - for doc in world.docs.values(): - doc["revision"] = 4 # the stored row's revision, which its chunks record - assert len(world.upserts) == 1 - _turn(world, _mirrored()) # same revision, same list - assert len(world.upserts) == 1 and mirror["rewrites"] == [] - world.files[0]["permissions"] = [] # everyone removed, same revision - _turn(world, _mirrored()) - assert len(world.upserts) == 1 # no content fetched, nothing embedded - [row] = mirror["rewrites"] - assert access_list.from_json(row["access_json"]) == access_list.AccessList() - [(written, _)] = world.upserts - assert row["content"] == written.content and row["tags"] == written.tags - assert row["doc_id"] == "d" and row["version"] > 1 and row["superseded_at"] is None - # The revision is what keeps the rewritten row searchable over its old chunks. - assert row["revision"] == world.docs[row["source_uri"]]["revision"] == 4 - - -def test_an_absent_file_reads_unread_before_it_is_retired( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - [(written, _)] = world.upserts - monkeypatch.setattr(settings, "knowledge_source_sync_full_interval_seconds", 0) - world.files = [] - world.file_answers["doc1"] = httpx.Response(404) - audits = len(world.audits) - result = _turn(world, _mirrored()) - assert [r["access_json"] for r in mirror["rewrites"]] == [""] - assert result.removed == 0 and written.source_uri not in world.docs - assert len(world.audits) == audits # the audit log outlives an erasure: no address - - -def test_an_incomplete_listing_records_no_listing_row(world: Any, mirror: Any) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - world.incomplete_search = True - _turn(world, _mirrored()) - assert len(world.upserts) == 1 and mirror["listings"] == [] - - -def test_a_mirrored_source_is_never_mined(world: Any, mirror: Any) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - result = _turn(world, _mirrored()) - # Left out before its stored copies are read, not failed while reading them. - assert world.mined == [] and result.errors == [] and result.failed == 0 - - def test_a_mirror_never_takes_a_name_already_in_use(monkeypatch: pytest.MonkeyPatch) -> None: names = iter(["acl-" + "1" * 24, "acl-" + "2" * 24]) taken = {"acl-" + "1" * 24} @@ -197,252 +55,12 @@ async def _holding(name: str, **kw: Any) -> AsyncIterator[bool]: assert added == ["acl-" + "2" * 24] -def test_permissions_are_read_page_by_page_and_a_refusal_reads_none( - monkeypatch: pytest.MonkeyPatch, -) -> None: - pages = { - "": {"permissions": [READERS[0]], "nextPageToken": "p2"}, - "p2": {"permissions": [{"type": "anyone", "role": "reader"}]}, - } - - def answer(request: httpx.Request) -> httpx.Response: - if "/files/locked/" in request.url.path: - return httpx.Response(403, json={"error": {"code": 403}}) - return httpx.Response(200, json=pages[request.url.params.get("pageToken", "")]) - - client = httpx.AsyncClient(transport=httpx.MockTransport(answer)) - monkeypatch.setattr(gdrive, "get_client", lambda: client) - got = asyncio.run(gdrive.file_permissions("tok", "doc1", pace_s=0)) - assert got == [READERS[0], {"type": "anyone", "role": "reader"}] - assert asyncio.run(gdrive.file_permissions("tok", "locked", pace_s=0)) is None - - -def test_a_new_revision_left_unwritten_still_takes_the_store_s_list( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 100) - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="10", permissions=READERS)] - _turn(world, _mirrored()) - # The owner shares it with nobody and uploads a revision past the size bound. - world.files = [_file("pdf1", PDF, "2026-01-02T00:00:00.000Z", size="101", permissions=[])] - _turn(world, _mirrored()) - assert len(world.upserts) == 1 - [row] = mirror["rewrites"] - assert access_list.from_json(row["access_json"]) == access_list.AccessList() - - -def test_a_given_up_file_is_tried_again_once_per_full_interval( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("bad1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - world.file_answers["bad1"] = httpx.Response(503) - for _ in range(8): - _turn(world, _mirrored()) - fetches = [r for r in world.requests if r.url.path.endswith("/bad1/export")] - # One fetch a pass until it is given up, then none until the full interval. - assert len(fetches) == source_sync._WAIT_PASSES - assert list(_own(world)["file_waits"]) == ["bad1"] - monkeypatch.setattr(settings, "knowledge_source_sync_full_interval_seconds", 0) - _turn(world, _mirrored()) - fetches = [r for r in world.requests if r.url.path.endswith("/bad1/export")] - assert len(fetches) == source_sync._WAIT_PASSES + 1 # one more try at the interval - world.files = [] - _turn(world, _mirrored()) - assert "bad1" not in _own(world)["file_waits"] - - -def test_lists_read_before_the_pass_runs_out_are_written_and_no_listing_row_lands( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - _turn(world, _mirrored()) - out = {"of_time": False} - - async def _permissions(token: str, file_id: str, **kw: Any) -> Any: - out["of_time"] = True - return [] # everyone removed - - monkeypatch.setattr(gdrive, "file_permissions", _permissions) - monkeypatch.setattr(PassBudget, "exhausted", lambda self: out["of_time"]) - for f in world.files: - del f["permissions"] # a shared drive's files: read one at a time - listings = len(mirror["listings"]) - _turn(world, _mirrored()) - [row] = mirror["rewrites"] # the one list read before the deadline - assert access_list.from_json(row["access_json"]) == access_list.AccessList() - assert _own(world)["lists_cursor"] and len(world.upserts) == 2 - assert len(mirror["listings"]) == listings - - -def test_a_rate_limit_on_a_stored_copy_s_list_stops_the_turn_before_any_fetch( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - - async def _limited(token: str, file_id: str, **kw: Any) -> Any: - raise gdrive.RateLimited("rate_limited") - - monkeypatch.setattr(gdrive, "file_permissions", _limited) - world.files = [ - _file("doc1", DOCS, "2026-01-03T00:00:00.000Z", permissions=READERS), # new - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), # stored, its list unread - ] - _turn(world, _mirrored()) - assert len(world.upserts) == 1 and _own(world)["status"] == "rate_limited" - - def test_a_new_mirror_name_has_the_form_no_token_may_name() -> None: from server.core.naming import is_mirror_name, new_mirror_name assert is_mirror_name(new_mirror_name()) -def test_a_failed_permission_read_reads_unread_and_the_turn_goes_on( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _failing(token: str, file_id: str, **kw: Any) -> Any: - if file_id == "doc1": - raise gdrive.VendorError("permissions of doc1: http 500", status=500) - return READERS - - monkeypatch.setattr(gdrive, "file_permissions", _failing) - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - _turn(world, _mirrored()) - lists = { - u.source_uri.split("/")[-2]: world.docs[u.source_uri]["access_json"] - for u, _ in world.upserts - } - assert lists["doc1"] == "" - assert access_list.from_json(lists["doc2"]).emails == ("ann@example.com",) - # `unread` admits nobody, so the listing still vouches. - assert len(mirror["listings"]) == 1 and _own(world)["status"] == "ok" - # A note, not a mark: the dashboard shows a `listing:` note as a turn cut short. - assert _own(world)["error"] == "permissions: a file's list could not be read" - - -def test_a_copy_without_live_chunks_still_takes_the_store_s_list( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 100) - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="10", permissions=READERS)] - _turn(world, _mirrored()) - [uri] = world.docs - world.docs[uri]["chunks"] = False # a write cut before its chunks - world.files = [_file("pdf1", PDF, "2026-01-02T00:00:00.000Z", size="101", permissions=[])] - _turn(world, _mirrored()) - assert access_list.from_json(world.docs[uri]["access_json"]) == access_list.AccessList() - assert len(mirror["listings"]) == 2 - - -def test_list_rewrites_go_on_past_the_pass_s_document_bound( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - _turn(world, _mirrored()) - monkeypatch.setattr(settings, "knowledge_source_mirror_documents_per_pass", 1) - for f in world.files: # both changed: the bound fetches one and defers the other - f["modifiedTime"] = f["modifiedTime"].replace("2026-01-0", "2026-02-0") - f["permissions"] = [] - result = _turn(world, _mirrored()) - assert not result.cut and len(world.upserts) == 3 - assert all( - d["access_json"] == access_list.to_json(access_list.AccessList()) - for d in world.docs.values() - ) - assert len(mirror["listings"]) == 2 - - -def test_a_walk_cut_at_its_bounds_reads_unread_where_it_did_not_reach( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - [uri] = world.docs - real = gdrive_items.list_items - - async def _cut(*a: Any, **kw: Any) -> Any: - listing = await real(*a, **kw) - return dataclasses.replace(listing, files=[], walk_cut="walk: depth bound reached") - - monkeypatch.setattr(gdrive_items, "list_items", _cut) - world.file_answers["doc1"] = httpx.Response( - 200, json={"id": "doc1", "mimeType": DOCS, "parents": [FOLDER], "trashed": False} - ) - _turn(world, _mirrored()) - # The document is kept (the store says it is there), its list unread. - assert world.docs[uri]["access_json"] == "" - assert len(mirror["listings"]) == 2 - - -def test_a_rate_limit_on_a_new_file_s_permissions_writes_no_document( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _limited(token: str, file_id: str, **kw: Any) -> Any: - raise gdrive.RateLimited("rate_limited") - - monkeypatch.setattr(gdrive, "file_permissions", _limited) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - _turn(world, _mirrored()) - assert world.upserts == [] and _own(world)["status"] == "rate_limited" - # No stored copy's list was left unread, so the listing still vouches. - assert len(mirror["listings"]) == 1 - - -def test_a_file_whose_fetch_fails_leaves_the_listing_row_to_land(world: Any, mirror: Any) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("bad1", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - world.file_answers["bad1"] = httpx.Response(503) - _turn(world, _mirrored()) - assert len(world.upserts) == 1 and _own(world)["status"] == "failed" - assert len(mirror["listings"]) == 1 - - -def test_a_list_is_compared_with_the_one_the_committed_head_holds( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - [uri] = world.docs - widened = READERS + [{"type": "user", "role": "reader", "emailAddress": "bob@example.com"}] - - async def _heads(org: str, namespace: str, uris: list[str]) -> dict[str, str]: - # A widening committed and not yet published: ClickHouse still holds Ann alone. - return {uri: access_list.to_json(access_list.from_drive_permissions(widened))} - - monkeypatch.setattr(documents, "committed_lists", _heads) - _turn(world, _mirrored()) # the store names Ann alone again - [row] = mirror["rewrites"] - assert access_list.from_json(row["access_json"]).emails == ("ann@example.com",) - - -def test_a_moved_file_keeps_its_list_at_its_new_address_and_none_at_its_old( - world: Any, mirror: Any -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - [(old, _)] = world.upserts - world.files[0]["webViewLink"] = "https://docs.example.com/document/d/doc1b/edit" - world.files[0]["modifiedTime"] = "2026-01-02T00:00:00.000Z" - _turn(world, _mirrored()) - [moved] = world.docs - assert old.source_uri not in world.docs and moved.endswith( - "/doc1b/edit#" + _mirrored().source_id - ) - assert access_list.from_json(world.docs[moved]["access_json"]).emails == ("ann@example.com",) - - def test_a_namespace_s_live_mirror_is_kept_and_none_is_registered( monkeypatch: pytest.MonkeyPatch, ) -> None: @@ -488,27 +106,6 @@ async def _gone() -> None: assert added == [] -def test_a_publication_still_owed_in_the_mirror_records_no_listing_row( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _owed(org: str, namespace: str, uri_suffix: str) -> str: - return "owed" if namespace == MIRROR else "" # a head ClickHouse has no row for yet - - monkeypatch.setattr(documents, "publications_owed", _owed) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - assert len(world.upserts) == 1 and mirror["listings"] == [] - - -def test_a_mirrored_source_is_not_synced_while_auth_is_off( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(type(settings), "auth_actually_required", lambda self: False) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - result = _turn(world, _mirrored()) - assert (result.sources, world.upserts, mirror["listings"]) == (0, [], []) - - def test_two_turns_at_once_make_one_mirror(monkeypatch: pytest.MonkeyPatch) -> None: from server.core import leases @@ -547,409 +144,6 @@ async def _both() -> list[str]: assert made[0] == made[1] and len(registry) == 1 -def test_a_publication_owed_when_the_copies_were_read_records_no_listing_row( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - answers = iter(["owed", ""]) # owed at the read, settled by the turn's end - - async def _owed(org: str, namespace: str, uri_suffix: str) -> str: - return next(answers) - - monkeypatch.setattr(documents, "publications_owed", _owed) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - assert len(world.upserts) == 1 and mirror["listings"] == [] - assert _own(world)["error"] == "publication: a write is not in ClickHouse yet" - - -def test_a_failed_permission_read_does_not_hold_back_retirement( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - _turn(world, _mirrored()) - - async def _failing(token: str, file_id: str, **kw: Any) -> Any: - raise gdrive.VendorError("permissions of doc1: http 500", status=500) - - monkeypatch.setattr(gdrive, "file_permissions", _failing) - del world.files[0]["permissions"] - gone = world.files.pop() # doc2 deleted in the store - world.file_answers[gone["id"]] = httpx.Response(404) - monkeypatch.setattr(settings, "knowledge_source_sync_full_interval_seconds", 0) - result = _turn(world, _mirrored()) - assert result.removed == 0 and len(world.docs) == 1 - - -def test_an_incomplete_search_leaves_an_unlisted_copy_s_list_as_it_was( - world: Any, mirror: Any -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - world.files, world.incomplete_search = [], True - _turn(world, _mirrored()) - assert mirror["rewrites"] == [] - - -def test_lists_read_before_a_rate_limit_in_the_same_batch_are_written( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - _turn(world, _mirrored()) - - async def _limited_after_one(token: str, file_id: str, **kw: Any) -> Any: - if file_id == "doc2": - raise gdrive.RateLimited("rate_limited") - return [] # doc1 shared with nobody now - - monkeypatch.setattr(gdrive, "file_permissions", _limited_after_one) - for f in world.files: - del f["permissions"] - _turn(world, _mirrored()) - [row] = mirror["rewrites"] - assert row["source_uri"].split("/")[-2] == "doc1" - assert access_list.from_json(row["access_json"]) == access_list.AccessList() - assert _own(world)["status"] == "rate_limited" - - -def test_a_cut_in_a_later_batch_keeps_the_earlier_batches_writes( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file(f"doc{n}", DOCS, f"2026-01-0{n}T00:00:00.000Z", permissions=READERS) - for n in (1, 2, 3) - ] - _turn(world, _mirrored()) - out = {"reads": 0} - - async def _permissions(token: str, file_id: str, **kw: Any) -> Any: - out["reads"] += 1 - return [] - - monkeypatch.setattr(source_sync_mirror, "_REWRITE_BATCH", 1) - monkeypatch.setattr(gdrive, "file_permissions", _permissions) - monkeypatch.setattr(PassBudget, "exhausted", lambda self: out["reads"] >= 2) - for f in world.files: - del f["permissions"] - listings = len(mirror["listings"]) - _turn(world, _mirrored()) - narrowed = sorted(r["source_uri"] for r in mirror["rewrites"]) - assert _own(world)["lists_cursor"] and narrowed == sorted(world.docs)[:2] # batches 1, 2 - assert len(mirror["listings"]) == listings - - -def test_past_the_deadline_a_list_the_listing_carried_is_still_written( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - _turn(world, _mirrored()) - out = {"read": False} - real = source_sync_mirror.store.every_copy - - async def _then_out_of_time(*a: Any, **kw: Any) -> Any: - copies = await real(*a, **kw) - out["read"] = True - return copies - - monkeypatch.setattr(source_sync_mirror.store, "every_copy", _then_out_of_time) - monkeypatch.setattr(PassBudget, "exhausted", lambda self: out["read"]) - del world.files[0]["permissions"] # doc1's list needs a read, which the deadline stops - world.files[1]["permissions"] = [] # doc2's, narrowed, came with the listing - listings = len(mirror["listings"]) - _turn(world, _mirrored()) - [row] = mirror["rewrites"] - assert row["source_uri"].split("/")[-2] == "doc2" - assert access_list.from_json(row["access_json"]) == access_list.AccessList() - assert _own(world)["lists_cursor"] and len(mirror["listings"]) == listings - - -def test_a_mirrored_source_without_a_mirror_turn_is_refused_a_turn() -> None: - src = dataclasses.replace(_mirrored(), kind="notion") - with pytest.raises(ValueError, match="does not sync"): - source_sync._turn_of(src) - - -def test_a_rate_limit_on_a_new_file_after_the_lists_keeps_the_listing_row( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - - async def _limited(token: str, file_id: str, **kw: Any) -> Any: - raise gdrive.RateLimited("rate_limited") - - monkeypatch.setattr(gdrive, "file_permissions", _limited) - world.files[0]["permissions"] = [] # the stored copy's list, narrowed - world.files.append(_file("doc2", DOCS, "2026-01-02T00:00:00.000Z")) # new, unlisted perms - _turn(world, _mirrored()) - [row] = mirror["rewrites"] - assert access_list.from_json(row["access_json"]) == access_list.AccessList() - assert len(world.upserts) == 1 and len(mirror["listings"]) == 2 - - -def test_no_mirror_is_made_for_a_source_that_cannot_list( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - made: list[str] = [] - - async def _ensure(org: str, namespace: str, **kw: Any) -> str: - made.append(namespace) - return MIRROR - - monkeypatch.setattr(mirrors, "ensure_mirror", _ensure) - world.fail_listing = 403 - _turn(world, _mirrored()) - assert made == [] and world.upserts == [] - - -def test_files_past_the_deadline_that_need_no_read_do_not_cut_the_turn( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - _turn(world, _mirrored()) - copies_read = {"done": False} - real = source_sync_mirror._refresh_lists - - async def _then_out_of_time(*a: Any, **kw: Any) -> bool: - ok = await real(*a, **kw) - copies_read["done"] = True - return ok - - monkeypatch.setattr(source_sync_mirror, "_refresh_lists", _then_out_of_time) - monkeypatch.setattr(PassBudget, "exhausted", lambda self: copies_read["done"]) - result = _turn(world, _mirrored()) # both unchanged: nothing to fetch or read - assert not result.cut and len(mirror["listings"]) == 2 - - -def test_a_turn_between_full_intervals_looks_up_no_absent_file(world: Any, mirror: Any) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - world.files = [] - before = len(world.requests) - result = _turn(world, _mirrored()) - lookups = [r for r in world.requests[before:] if r.url.path.endswith("/files/doc1")] - assert lookups == [] and result.removed == 0 - [(written, _)] = world.upserts - assert world.docs[written.source_uri]["access_json"] == "" # it admits nobody meanwhile - - -def test_a_deadline_with_every_list_already_listed_still_records_the_listing( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file(f"doc{n}", DOCS, f"2026-01-0{n}T00:00:00.000Z", permissions=READERS) - for n in (1, 2, 3) - ] - _turn(world, _mirrored()) - out = {"read": False} - real = source_sync_mirror.store.every_copy - - async def _then_out_of_time(*a: Any, **kw: Any) -> Any: - copies = await real(*a, **kw) - out["read"] = True # the deadline passes once the stored copies are read - return copies - - monkeypatch.setattr(source_sync_mirror, "_REWRITE_BATCH", 1) - monkeypatch.setattr(source_sync_mirror.store, "every_copy", _then_out_of_time) - monkeypatch.setattr(PassBudget, "exhausted", lambda self: out["read"]) - for f in world.files: - f["permissions"] = [] # every list narrowed, each carried by the listing - result = _turn(world, _mirrored()) - assert not result.cut and len(mirror["rewrites"]) == 3 and len(mirror["listings"]) == 2 - - -def test_a_viewer_account_s_unread_lists_are_noted( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _will_not_say(token: str, file_id: str, **kw: Any) -> Any: - return None # a 403: the account may not see who the file is shared with - - monkeypatch.setattr(gdrive, "file_permissions", _will_not_say) - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z"), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z"), - ] - _turn(world, _mirrored()) - assert all(d["access_json"] == "" for d in world.docs.values()) and len(world.docs) == 2 - assert _own(world)["error"] == "permissions: the store gave no list for a file" - - -def test_a_copy_behind_its_file_is_never_widened_by_the_store_s_new_list( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 100) - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="10", permissions=READERS)] - _turn(world, _mirrored()) - [uri] = world.docs - # A paragraph is cut in a new revision past the size bound, then Bob is added. - bob = {"type": "user", "role": "reader", "emailAddress": "bob@example.com"} - world.files = [ - _file("pdf1", PDF, "2026-01-02T00:00:00.000Z", size="101", permissions=[*READERS, bob]) - ] - _turn(world, _mirrored()) - assert access_list.from_json(world.docs[uri]["access_json"]).emails == ("ann@example.com",) - - -def test_a_behind_copy_that_read_unread_stays_unread_until_its_content_write( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(settings, "knowledge_source_sync_max_file_bytes", 100) - world.files = [_file("pdf1", PDF, "2026-01-01T00:00:00.000Z", size="10", permissions=READERS)] - _turn(world, _mirrored()) - [uri] = world.docs - # A revision past the size bound whose list could not be read, then one that can. - world.files = [_file("pdf1", PDF, "2026-01-02T00:00:00.000Z", size="101")] - - async def _failed(token: str, file_id: str, **kw: Any) -> Any: - raise gdrive.VendorError("503") - - monkeypatch.setattr(gdrive, "file_permissions", _failed) - _turn(world, _mirrored()) - assert world.docs[uri]["access_json"] == "" - world.files[0]["permissions"] = READERS - _turn(world, _mirrored()) - assert world.docs[uri]["access_json"] == "" # narrowing only: unread admits nobody - world.files = [_file("pdf1", PDF, "2026-01-03T00:00:00.000Z", size="10", permissions=READERS)] - _turn(world, _mirrored()) # the content write carries the list read with it - assert access_list.from_json(world.docs[uri]["access_json"]).emails == ("ann@example.com",) - - -def test_a_copy_another_writer_holds_keeps_its_list_and_no_listing_row_lands( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - held = documents.get_many_by_uris - - async def _taken(org: str, namespace: str, uris: list[str], **kw: Any) -> list[Any]: - return [ - d.model_copy(update={"actor": "user:someone"}) for d in await held(org, namespace, uris) - ] - - monkeypatch.setattr(documents, "get_many_by_uris", _taken) - world.files[0]["permissions"] = [] - listings = len(mirror["listings"]) - _turn(world, _mirrored()) - assert mirror["rewrites"] == [] and len(mirror["listings"]) == listings - assert _own(world)["error"] == "permissions: a stored copy is not this source's to write" - - -def test_a_source_removed_since_its_last_write_lands_no_listing_row( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - listings = len(mirror["listings"]) - - async def _gone(src: Any) -> None: - raise source_sync.SourceGone("acme/team/decks") # a namespace erasure ran meanwhile - - monkeypatch.setattr(source_sync, "require_current", _gone) - _turn(world, _mirrored()) # nothing changed: the listing row is the turn's one write - assert len(mirror["listings"]) == listings - - -def test_a_copy_another_writer_holds_does_not_stop_later_narrowings( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("doc2", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - _turn(world, _mirrored()) - held = documents.get_many_by_uris - - async def _first_taken(org: str, namespace: str, uris: list[str], **kw: Any) -> list[Any]: - docs = await held(org, namespace, uris) - return [ - d.model_copy(update={"actor": "user:someone"}) if "/doc1/" in d.source_uri else d - for d in docs - ] - - monkeypatch.setattr(source_sync_mirror, "_REWRITE_BATCH", 1) - monkeypatch.setattr(documents, "get_many_by_uris", _first_taken) - for f in world.files: - f["permissions"] = [] - listings = len(mirror["listings"]) - _turn(world, _mirrored()) - [row] = mirror["rewrites"] - assert "/doc2/" in row["source_uri"] and len(mirror["listings"]) == listings - - -def test_a_parked_publication_is_noted_as_needing_an_operator( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _parked(org: str, namespace: str, uri_suffix: str) -> str: - return "parked" - - monkeypatch.setattr(documents, "publications_owed", _parked) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - _turn(world, _mirrored()) - assert mirror["listings"] == [] - assert "parked; see the knowledge delivery backlog" in _own(world)["error"] - - -def test_a_delivery_owed_at_the_read_and_parked_by_the_end_is_noted_parked_first( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - answers = iter(["owed", "parked"]) - - async def _owed(org: str, namespace: str, uri_suffix: str) -> str: - return next(answers) - - async def _will_not_say(token: str, file_id: str, **kw: Any) -> Any: - return None - - monkeypatch.setattr(documents, "publications_owed", _owed) - monkeypatch.setattr(gdrive, "file_permissions", _will_not_say) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z")] - _turn(world, _mirrored()) - assert mirror["listings"] == [] - assert _own(world)["error"].startswith("publication: a write is parked") - - -def test_a_parked_publication_is_shown_beside_a_failed_fetch( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _parked(org: str, namespace: str, uri_suffix: str) -> str: - return "parked" - - monkeypatch.setattr(documents, "publications_owed", _parked) - world.files = [ - _file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS), - _file("bad1", DOCS, "2026-01-02T00:00:00.000Z", permissions=READERS), - ] - world.file_answers["bad1"] = httpx.Response(503) - _turn(world, _mirrored()) - error = _own(world)["error"] - assert error.startswith("publication: a write is parked") and "503" in error - - -def test_a_parked_publication_stays_out_of_worker_logs( - world: Any, mirror: Any, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture -) -> None: - async def _parked(org: str, namespace: str, uri_suffix: str) -> str: - return "parked" - - monkeypatch.setattr(documents, "publications_owed", _parked) - world.files = [_file("doc1", DOCS, "2026-01-01T00:00:00.000Z", permissions=READERS)] - with caplog.at_level("WARNING", logger="loom.knowledge.source_sync"): - _turn(world, _mirrored()) - assert "publication: a write is parked" in _own(world)["error"] - assert caplog.records == [] - - def test_home_refuses_an_access_this_build_does_not_know() -> None: assert home(_source()) == ("code-acme-app", "source:decks") with pytest.raises(ValueError, match="access"): diff --git a/tests/unit/test_knowledge_sources.py b/tests/unit/test_knowledge_sources.py index 95577f2123..05fa9a7942 100644 --- a/tests/unit/test_knowledge_sources.py +++ b/tests/unit/test_knowledge_sources.py @@ -9,7 +9,6 @@ import json import uuid from collections.abc import AsyncIterator -from pathlib import Path from types import SimpleNamespace from typing import Any @@ -21,7 +20,6 @@ from server.core import leases from server.core.ch import sequential_reads_active from server.core.errors import ( - BadConfigError, ErasureRunningError, NotFoundError, OverloadedError, @@ -35,11 +33,9 @@ KnowledgeSourceCheckInput, KnowledgeSourceInspectInput, KnowledgeSourceListInput, - KnowledgeSourceParseLinksInput, KnowledgeSourceRemoveInput, KnowledgeSourceRotateInput, KnowledgeSourceSyncNowInput, - KnowledgeSourceUpdateInput, ) from server.knowledge.app import source_probes from server.knowledge.app import sources as app @@ -53,8 +49,7 @@ from tests.unit.schema_ddl import column_names ORG, NS = "acme", "code-acme-app" -FOLDER = "1AbCdEfGhIjKlMnOp" -SECRET = '{"type": "service_account", "client_email": "a@b", "private_key": "k"}' +SECRET = "recording-test-credential" class _Store: @@ -91,9 +86,11 @@ async def sources_in(self, org: str, names: list[str]) -> list[tuple[str, str]]: found = [(n, name) for (o, n, name) in self.rows if o == org] return sorted(f for f in found if f[0] in names) - async def list_sources(self, org: str, ns: str) -> list[KnowledgeSource]: + async def list_sources( + self, org: str, ns: str, *, include_mcp: bool = True + ) -> list[KnowledgeSource]: found = [s for (o, n, _), s in self.rows.items() if (o, n) == (org, ns) and s.active] - return sorted(found, key=lambda s: s.name) + return sorted((s for s in found if include_mcp or s.kind != "mcp"), key=lambda s: s.name) async def get_source(self, org: str, ns: str, name: str) -> KnowledgeSource | None: src = self.rows.get((org, ns, name)) @@ -149,7 +146,7 @@ async def _probe( ) -> source_probes.Probe: fake.probes.append((kind, config, credential)) fake.probed_items.append(items) - return source_probes.Probe(documents=3, sample=["Deck"], items=items or []) + return source_probes.Probe(documents=3, sample=["Deck"]) monkeypatch.setattr(source_probes, "probe", _probe) @@ -179,8 +176,8 @@ def _add(**kw: Any) -> KnowledgeSourceAddInput: "org": ORG, "namespace": NS, "name": "design-decks", - "kind": "gdrive", - "config": {"folder_ids": [FOLDER]}, + "kind": "recording", + "config": {"provider": "zoom", "ids": ["123456789"]}, "credential": SECRET, } body.update(kw) @@ -210,26 +207,14 @@ def test_add_probes_then_stores_the_credential_sealed(fake: _Store) -> None: out = asyncio.run(app.handle_knowledge_source_add(_add(name=" Design-Decks "))) assert not out.dry_run and out.name == "design-decks" assert out.probe.documents == 3 and out.probe.sample == ["Deck"] - assert out.config == {"folder_ids": [FOLDER], "include": ["docs", "slides", "pdf", "pptx"]} + assert out.config == {"provider": "zoom", "ids": ["123456789"]} src = fake.rows[(ORG, NS, "design-decks")] - assert src.kind == "gdrive" and src.active and domain.id_list_config(src) == out.config + assert src.kind == "recording" and src.active and src.config == out.config assert SECRET not in src.credential_enc assert unseal("knowledge_sources.credential", src.credential_enc) == SECRET assert SECRET not in out.model_dump_json() -def test_a_page_store_source_stores_its_ids_in_one_form(fake: _Store) -> None: - page = "0123456789abcdef0123456789ABCDEF" - dashed = "01234567-89ab-cdef-0123-456789abcdef" - config = {"page_ids": [page, dashed], "database_ids": ["fedcba98-7654-3210-fedc-ba9876543210"]} - out = asyncio.run(app.handle_knowledge_source_add(_add(kind="notion", config=config))) - assert out.config == { - "page_ids": [dashed], - "database_ids": ["fedcba98-7654-3210-fedc-ba9876543210"], - } - assert fake.probes[-1][0] == "notion" - - def test_a_dry_run_probes_and_writes_nothing(fake: _Store) -> None: out = asyncio.run(app.handle_knowledge_source_add(_add(dry_run=True))) assert out.dry_run @@ -240,25 +225,12 @@ def test_a_dry_run_probes_and_writes_nothing(fake: _Store) -> None: ("kw", "code"), [ ({"name": "x"}, "BAD_NAME"), - ({"kind": "ftp"}, "BAD_KIND"), - ({"kind": "notion"}, "BAD_CONFIG"), # a folder config is not a page store's - ({"kind": "notion", "config": {"page_ids": []}}, "BAD_CONFIG"), - ({"kind": "notion", "config": {"page_ids": ["not-an-id"]}}, "BAD_CONFIG"), - ({"kind": "notion", "config": {"page_ids": "a" * 32}}, "BAD_CONFIG"), - ( - {"kind": "notion", "config": {"page_ids": [f"{n:032x}" for n in range(21)]}}, - "BAD_CONFIG", - ), - ({"kind": "notion", "config": {"database_ids": [{"id": 1}]}}, "BAD_CONFIG"), - ({"config": {"folder_ids": ["bad id'"]}}, "BAD_CONFIG"), - ({"config": {"folder_ids": [FOLDER + "\n"]}}, "BAD_CONFIG"), - ({"config": {"folder_ids": [FOLDER], "include": ["xls"]}}, "BAD_CONFIG"), - ({"config": {"folder_ids": [FOLDER], "include": [["docs"]]}}, "BAD_CONFIG"), - ({"config": {"folder_ids": [FOLDER], "include": [{"k": 1}]}}, "BAD_CONFIG"), - ({"config": {"folder_ids": [["x"]]}}, "BAD_CONFIG"), - ({"config": {"folder_ids": FOLDER}}, "BAD_CONFIG"), - ({"config": {"folder_ids": []}}, "BAD_CONFIG"), - ({"config": {"folder_ids": [FOLDER], "host": "h"}}, "BAD_CONFIG"), + ({"config": {"provider": "unknown", "ids": ["123"]}}, "BAD_CONFIG"), + ({"config": {"provider": "zoom", "ids": []}}, "BAD_CONFIG"), + ({"config": {"provider": "zoom", "ids": "123"}}, "BAD_CONFIG"), + ({"config": {"provider": "zoom", "ids": ["bad id"]}}, "BAD_CONFIG"), + ({"config": {"provider": "zoom", "ids": [["123"]]}}, "BAD_CONFIG"), + ({"config": {"provider": "zoom", "ids": ["123"], "host": "h"}}, "BAD_CONFIG"), ({"credential": " "}, "CREDENTIAL_REFUSED"), ], ) @@ -300,16 +272,6 @@ async def _fail(*_: Any, **__: Any) -> source_probes.Probe: assert fake.rows == {} -def test_a_folder_config_naming_docx_is_stored_in_the_table_s_order_and_probed( - fake: _Store, -) -> None: - config = {"folder_ids": [FOLDER], "include": ["docx", "pdf"]} - out = asyncio.run(app.handle_knowledge_source_add(_add(config=config))) - assert out.config["include"] == ["pdf", "docx"] - assert fake.rows[(ORG, NS, "design-decks")].config == {"include": ["pdf", "docx"]} - assert fake.probes[-1][1]["include"] == ["pdf", "docx"] - - def test_list_and_inspect_return_config_and_sync_never_the_credential( fake: _Store, monkeypatch: pytest.MonkeyPatch ) -> None: @@ -397,7 +359,7 @@ def test_unknown_sources_are_not_found(fake: _Store) -> None: def test_rotate_replaces_only_the_credential(fake: _Store) -> None: asyncio.run(app.handle_knowledge_source_add(_add())) before = fake.rows[(ORG, NS, "design-decks")] - new = SECRET.replace("a@b", "c@d") + new = SECRET + "-rotated" body = KnowledgeSourceRotateInput(org=ORG, namespace=NS, name="design-decks", credential=new) out = asyncio.run(app.handle_knowledge_source_rotate(body)) after = fake.rows[(ORG, NS, "design-decks")] @@ -466,9 +428,6 @@ def test_remove_needs_the_name_and_keeps_documents_by_default(fake: _Store) -> N lambda: app.handle_knowledge_source_sync_now( KnowledgeSourceSyncNowInput(org=ORG, namespace=NS, name="design-decks") ), - lambda: app.handle_knowledge_source_update( - KnowledgeSourceUpdateInput(org=ORG, namespace=NS, name="design-decks", include=["pdf"]) - ), ], ) def test_a_mirrored_source_is_refused(fake: _Store, call: Any) -> None: @@ -641,23 +600,17 @@ def test_sync_now_refuses_a_source_of_an_inactive_namespace(fake: _Store) -> Non def test_audit_subjects_carry_no_credential() -> None: add = OPERATIONS_BY_NAME["knowledge.source.add"] - items = [{"type": "folder", "id": FOLDER, "recursive": False}] response = { "name": "design-decks", - "kind": "gdrive", - "items": items, - "include": ["docs"], - "config": {"folder_ids": [FOLDER]}, + "kind": "recording", + "config": {"provider": "zoom", "ids": ["123456789"]}, } subject = add.audit_subject(_add(), response) # type: ignore[misc] assert subject == { "org": ORG, "namespace": NS, "name": "design-decks", - "kind": "gdrive", - "items": items, - "include": ["docs"], - "config": {"folder_ids": [FOLDER]}, + "kind": "recording", "dry_run": False, } rotate = OPERATIONS_BY_NAME["knowledge.source.rotate"] @@ -669,7 +622,6 @@ def test_audit_subjects_carry_no_credential() -> None: ADMIN_OPS = ( "knowledge.source.add", - "knowledge.source.update", "knowledge.source.check", "knowledge.source.rotate", "knowledge.source.remove", @@ -685,6 +637,9 @@ async def _none(*_: Any) -> None: async def _false(*_: Any) -> bool: return False + from types import SimpleNamespace + + monkeypatch.setattr(authz, "directory", lambda: SimpleNamespace(code_entry=lambda *a: None)) monkeypatch.setattr(authz, "_lookup_grant", _none) monkeypatch.setattr(authz, "claim_cap", _none) monkeypatch.setattr(authz, "may_be_restricted", _false) @@ -720,9 +675,7 @@ def test_source_entry_role_keeps_connected_writers_and_shared_admins( asyncio.run(check_authorized(refused, op.required_role, ORG, NS)) -@pytest.mark.parametrize( - "name", ["knowledge.source.list", "knowledge.source.inspect", "knowledge.source.parse_links"] -) +@pytest.mark.parametrize("name", ["knowledge.source.list", "knowledge.source.inspect"]) def test_reads_are_open_to_the_namespace_reader(no_grant_reads: None, name: str) -> None: op = OPERATIONS_BY_NAME[name] assert op.required_role == Role.VIEWER and op.read_only @@ -761,10 +714,10 @@ def test_statements_read_final_on_the_key_prefix(monkeypatch: pytest.MonkeyPatch def test_a_registry_write_is_a_full_row(monkeypatch: pytest.MonkeyPatch) -> None: ch = RecordingCH() ch.install(monkeypatch) - config = {"folder_ids": [FOLDER], "include": ["docs"]} + config = {"provider": "zoom", "ids": ["123456789"]} src = KnowledgeSource( - org=ORG, namespace=NS, name="d", kind="gdrive", source_id=str(uuid.uuid4()), - config=config, items=domain.items_from_config("gdrive", config), + org=ORG, namespace=NS, name="d", kind="recording", source_id=str(uuid.uuid4()), + config=config, ) # fmt: skip asyncio.run(store.insert_source(src)) [row] = ch.inserted("knowledge_sources") @@ -775,17 +728,17 @@ def test_a_registry_write_is_a_full_row(monkeypatch: pytest.MonkeyPatch) -> None assert json.loads(row["config_json"]) == config and row["active"] is True -def test_a_mirrored_source_is_stored_where_a_build_without_items_finds_nothing( +def test_a_retained_mirrored_source_keeps_private_columns_on_write( monkeypatch: pytest.MonkeyPatch, ) -> None: ch = RecordingCH() ch.install(monkeypatch) - config = {"folder_ids": [FOLDER]} + config = {"provider": "zoom", "ids": ["123456789"]} src = KnowledgeSource( org=ORG, namespace=NS, name="d", kind="gdrive", source_id=str(uuid.uuid4()), - config=config, items=domain.items_from_config("gdrive", config), access=domain.MIRRORED_ACCESS, + config=config, access=domain.MIRRORED_ACCESS, secret_enc="retained-sealed", ) # fmt: skip - asyncio.run(store.insert_source(app._with_credential(src, SECRET))) + asyncio.run(store.insert_source(src)) [row] = ch.inserted("knowledge_sources") assert row["kind"] == "" and row["source_kind"] == "gdrive" assert ( @@ -793,7 +746,7 @@ def test_a_mirrored_source_is_stored_where_a_build_without_items_finds_nothing( and row["secret_enc"] and row["access"] == domain.MIRRORED_ACCESS ) - # Read back, it is still mirrored; an empty value reads `namespace`. + # Retained access metadata survives a raw row round trip. assert store._source(row).access == domain.MIRRORED_ACCESS assert store._source({**row, "access": ""}).access == "namespace" @@ -846,7 +799,7 @@ async def _probe_while_added(*_: Any, **__: Any) -> source_probes.Probe: org=ORG, namespace=NS, name="design-decks", - kind="gdrive", + kind="recording", source_id=str(uuid.uuid4()), ) ) @@ -1427,796 +1380,7 @@ async def _held_elsewhere(name: str, *, wait_s: float, **_kw: Any) -> AsyncItera assert clock.t == 130.0 -# ---- items, links and update ------------------------------------------------- - -LINK = f"https://drive.google.com/drive/folders/{FOLDER}" -FILE = "1FiLeIdOfADocument_x" - - -@pytest.fixture -def fleet(monkeypatch: pytest.MonkeyPatch) -> dict[str, bool]: - """Whether every live process runs the items migration; each read is counted.""" - from server.auth import machines - - state = {"ready": True, "reads": 0} - - async def _fleet_at(ch: Any, migration: int) -> bool: - assert migration == app._ITEMS_MIGRATION - state["reads"] += 1 - return bool(state["ready"]) - - monkeypatch.setattr(machines, "fleet_at", _fleet_at) - monkeypatch.setattr("server.core.ch.get_client", lambda: None) - return state # type: ignore[return-value] - - -def _folder(folder_id: str = FOLDER, recursive: bool = False) -> dict[str, Any]: - return {"type": "folder", "id": folder_id, "recursive": recursive} - - -def _stored(fake: _Store, name: str = "design-decks") -> KnowledgeSource: - return fake.rows[(ORG, NS, name)] - - -def test_add_takes_links_and_stores_them_as_id_list_config(fake: _Store, fleet: Any) -> None: - out = asyncio.run(app.handle_knowledge_source_add(_add(config=None, links=[LINK]))) - assert out.items == [_folder()] and out.config["folder_ids"] == [FOLDER] - src = _stored(fake) - assert domain.id_list_config(src) is not None and src.credential_enc and not src.secret_enc - assert app.credential_of(src) == SECRET - # The id-list config needs no gate. - assert fleet["reads"] == 0 - - -def test_add_takes_items_id_list_config_cannot_hold(fake: _Store, fleet: Any) -> None: - items = [_folder(recursive=True), {"type": "file", "id": FILE}] - out = asyncio.run( - app.handle_knowledge_source_add(_add(config=None, items=items, include=["docs"])) - ) - assert out.items == items and out.config == {} and out.include == ["docs"] - src = _stored(fake) - assert src.secret_enc and not src.credential_enc and app.credential_of(src) == SECRET - assert out.probe.checked == 2 and not out.probe.sampled - assert fleet["reads"] == 1 - - -def test_add_takes_items_and_links_together(fake: _Store, fleet: Any) -> None: - drive = {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"} - out = asyncio.run( - app.handle_knowledge_source_add(_add(config=None, items=[drive], links=[LINK])) - ) - # The given items come first, the links' after them. - assert out.items == [drive, _folder()] - - -def test_add_turns_a_config_into_items(fake: _Store) -> None: - out = asyncio.run(app.handle_knowledge_source_add(_add())) - assert out.items == [_folder()] - assert fake.probed_items == [[_folder()]] - - -@pytest.mark.parametrize( - ("kw", "code"), - [ - ({"config": None}, "BAD_CONFIG"), - ({"links": [LINK]}, "BAD_CONFIG"), - ({"links": [LINK], "items": [_folder()]}, "BAD_CONFIG"), - ({"config": None, "links": []}, "BAD_CONFIG"), - ({"include": ["docs"]}, "BAD_CONFIG"), - ({"kind": "recording", "config": None, "items": [_folder()]}, "BAD_CONFIG"), - ({"config": None, "items": [{"type": "folder", "id": "x' or '1"}]}, "BAD_CONFIG"), - ({"config": None, "links": [LINK, "https://example.com/a", "nope"]}, "BAD_LINK"), - ( - {"config": None, "links": [f"https://www.notion.so/{'a' * 32}"]}, - "BAD_LINK", - ), - ], -) -def test_add_refuses_what_it_cannot_read_before_any_probe( - fake: _Store, kw: dict[str, Any], code: str -) -> None: - assert _code(app.handle_knowledge_source_add(_add(**kw))) == code - assert fake.probes == [] - - -def test_bad_link_names_each_unreadable_link_of_a_few(fake: _Store) -> None: - body = _add(config=None, links=[LINK, "https://example.com/a", "https://example.com/b"]) - with pytest.raises(ValidationError) as e: - asyncio.run(app.handle_knowledge_source_add(body)) - message = str(e.value) - assert "example.com/a" in message and "example.com/b" in message and FOLDER not in message - - -def test_add_of_a_source_without_a_kind_waits_for_the_fleet(fake: _Store, fleet: Any) -> None: - fleet["ready"] = False - body = _add(config=None, items=[_folder(recursive=True)]) - fake.probes.clear() - with pytest.raises(OverloadedError) as e: - asyncio.run(app.handle_knowledge_source_add(body)) - assert e.value.extra["retry_after_s"] == 30 - # Refused before any probe. - assert fake.rows == {} and fake.probes == [] - # A source the id-list config holds is not held back. - asyncio.run(app.handle_knowledge_source_add(_add(config=None, links=[LINK]))) - assert _stored(fake).kind == "gdrive" - - -def test_a_probe_checks_a_sample_of_many_items(fake: _Store, fleet: Any) -> None: - items = [{"type": "file", "id": f"{FILE}{n:02d}"} for n in range(30)] - out = asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - assert out.probe.checked == 20 and out.probe.sampled - assert fake.probed_items == [items[10:]] - - -def _update(**kw: Any) -> KnowledgeSourceUpdateInput: - return KnowledgeSourceUpdateInput(org=ORG, namespace=NS, name="design-decks", **kw) - - -def test_an_item_added_in_another_form_reports_the_held_form_removed( - fake: _Store, fleet: Any -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - out = asyncio.run( - app.handle_knowledge_source_update(_update(add_items=[_folder(recursive=True)])) - ) - assert out.items == out.added == [_folder(recursive=True)] - assert out.removed == [_folder()] - - -def test_an_add_of_a_folder_and_the_drive_of_its_id_keeps_the_drive( - fake: _Store, fleet: Any -) -> None: - drive = {"type": "shared_drive", "id": FOLDER} - out = asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=[_folder(), drive]))) - assert out.items == [drive] - - -def test_update_adds_and_removes_items(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - before = _stored(fake) - fake.probed_items.clear() - out = asyncio.run( - app.handle_knowledge_source_update( - _update( - add_items=[{"type": "file", "id": FILE}], - add_links=[LINK.replace(FOLDER, "2QrStUvWxYzAbCdEf")], - ) - ) - ) - assert out.items == [_folder(), {"type": "file", "id": FILE}, _folder("2QrStUvWxYzAbCdEf")] - assert out.added == out.items[1:] and out.removed == [] and out.config == {} - # Only the added items are probed. - assert fake.probed_items == [out.items[1:]] - after = _stored(fake) - assert after.source_id == before.source_id - # The source no longer fits the id-list config: its credential moved to the other column. - assert after.secret_enc and not after.credential_enc and app.credential_of(after) == SECRET - out = asyncio.run( - app.handle_knowledge_source_update(_update(remove_items=[{"type": "file", "id": FILE}])) - ) - assert out.items == [_folder(), _folder("2QrStUvWxYzAbCdEf")] and out.config["folder_ids"] - assert _stored(fake).credential_enc and not _stored(fake).secret_enc - - -def test_update_changes_include_of_a_source_without_file_items(fake: _Store) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - fake.probes.clear() - out = asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - assert out.include == ["pdf"] and out.config["include"] == ["pdf"] - assert fake.probes == [] and out.probe.checked == 0 - - -@pytest.mark.parametrize( - ("kw", "code"), - [ - ({}, "BAD_CONFIG"), - ({"remove_items": [_folder()]}, "BAD_CONFIG"), - ({"remove_links": [LINK]}, "BAD_CONFIG"), - ({"remove_items": [{"type": "file", "id": FILE}]}, "BAD_CONFIG"), - ({"add_links": ["https://example.com/x"]}, "BAD_LINK"), - ], -) -def test_update_refuses_what_it_cannot_do_before_any_probe( - fake: _Store, kw: dict[str, Any], code: str -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - fake.probes.clear() - stored = _stored(fake) - assert _code(app.handle_knowledge_source_update(_update(**kw))) == code - assert fake.probes == [] and _stored(fake) == stored - - -def test_meet_recording_registration_refuses_before_probe( - fake: _Store, monkeypatch: pytest.MonkeyPatch -) -> None: - before = dict(fake.rows) - - async def _must_not_probe(*args: Any, **kwargs: Any) -> Any: - raise AssertionError("rejected Meet registration reached a provider probe") - - monkeypatch.setattr(source_probes, "probe", _must_not_probe) - config = {"provider": "meet", "ids": ["spaces/old-space"]} - assert ( - _code(app.handle_knowledge_source_add(_add(kind="recording", config=config))) - == "BAD_CONFIG" - ) - assert fake.rows == before - - -def test_update_of_a_recording_source_is_refused(fake: _Store) -> None: - config = {"provider": "zoom", "ids": ["123456789"]} - asyncio.run(app.handle_knowledge_source_add(_add(kind="recording", config=config))) - assert _code(app.handle_knowledge_source_update(_update(include=["pdf"]))) == "BAD_KIND" - - -def test_update_refuses_a_source_replaced_during_its_probe( - fake: _Store, monkeypatch: pytest.MonkeyPatch, fleet: Any -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - readded = dataclasses.replace(_stored(fake), source_id=str(uuid.uuid4())) - - async def _probe_while_replaced(*_: Any, **__: Any) -> source_probes.Probe: - fake.rows[(ORG, NS, "design-decks")] = readded - return source_probes.Probe(documents=1) - - monkeypatch.setattr(source_probes, "probe", _probe_while_replaced) - with pytest.raises(SourceReplacedError): - asyncio.run( - app.handle_knowledge_source_update(_update(add_items=[{"type": "file", "id": FILE}])) - ) - assert _stored(fake) is readded - - -def test_update_retries_when_the_source_changed_during_its_probe( - fake: _Store, monkeypatch: pytest.MonkeyPatch, fleet: Any -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - other = "2QrStUvWxYzAbCdEf" - added_meanwhile = dataclasses.replace(_stored(fake), items=[_folder(), _folder(other)]) - - async def _probe_while_updated(*_: Any, **__: Any) -> source_probes.Probe: - fake.rows[(ORG, NS, "design-decks")] = added_meanwhile - return source_probes.Probe(documents=1) - - monkeypatch.setattr(source_probes, "probe", _probe_while_updated) - # What the probe checked holds for the source as it was read: the caller retries. - with pytest.raises(OverloadedError): - asyncio.run( - app.handle_knowledge_source_update(_update(add_items=[{"type": "file", "id": FILE}])) - ) - assert _stored(fake) == added_meanwhile - - -def test_update_of_a_source_without_a_kind_waits_for_the_fleet(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - stored = _stored(fake) - fleet["ready"] = False - fake.probes.clear() - with pytest.raises(OverloadedError): - asyncio.run( - app.handle_knowledge_source_update(_update(add_items=[_folder(recursive=True)])) - ) - # Refused before any probe: a rollout answer spends no store call. - assert _stored(fake) == stored and fake.probes == [] - - -def test_update_records_the_items_it_added_and_removed() -> None: - op = OPERATIONS_BY_NAME["knowledge.source.update"] - body = _update(add_items=[{"type": "file", "id": FILE}]) - response = {"name": "design-decks", "added": [{"type": "file", "id": FILE}], "removed": []} - assert op.audit_subject(body, response) == { # type: ignore[misc] - "org": ORG, - "namespace": NS, - "name": "design-decks", - "added": [{"type": "file", "id": FILE}], - "removed": [], - "include": None, - } - - -def test_parse_links_answers_each_link_and_reads_no_store(fake: _Store) -> None: - body = KnowledgeSourceParseLinksInput(org=ORG, namespace=NS, links=[LINK, "nope"]) - out = asyncio.run(app.handle_knowledge_source_parse_links(body)) - assert [(p.kind, p.item, bool(p.unreadable)) for p in out.links] == [ - ("gdrive", _folder(), False), - ("", {}, True), - ] - assert fake.rows == {} and fake.probes == [] - - -def test_list_and_inspect_answer_items_and_id_list_config(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - items = [_folder(recursive=True)] - asyncio.run(app.handle_knowledge_source_add(_add(name="walked", config=None, items=items))) - listed = asyncio.run( - app.handle_knowledge_source_list(KnowledgeSourceListInput(org=ORG, namespace=NS)) - ) - by_name = {s.name: s for s in listed.sources} - assert by_name["design-decks"].config["folder_ids"] == [FOLDER] - assert by_name["walked"].items == items and by_name["walked"].config == {} - assert by_name["walked"].include == ["docs", "slides", "pdf", "pptx"] - inspected = asyncio.run( - app.handle_knowledge_source_inspect( - KnowledgeSourceInspectInput(org=ORG, namespace=NS, name="walked") - ) - ) - assert inspected.items == items and inspected.config == {} - - -def test_update_is_refused_on_a_gone_namespace_and_during_an_erasure(fake: _Store) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - fake.probes.clear() - stored = _stored(fake) - fake.erasures.append({"scope_type": "namespace", "scope_value": NS}) - body = _update(add_items=[{"type": "file", "id": FILE}]) - with pytest.raises(ErasureRunningError): - asyncio.run(app.handle_knowledge_source_update(body)) - fake.erasures.clear() - fake.inactive.add((ORG, NS)) - assert _code(app.handle_knowledge_source_update(body)) == "NAMESPACE_INACTIVE" - # Refused before the probe, and nothing stored. - assert fake.probes == [] and _stored(fake) == stored - - -def test_an_update_asks_the_next_turn_for_a_full_listing(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - assert not json.loads(fake.states["design-decks"]["detail"]).get("full") - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - detail = json.loads(fake.states["design-decks"]["detail"]) - # An incremental turn would skip an added item's older files. - assert detail["full"] is True and detail["requested_at"] - - -def test_a_filter_names_no_person() -> None: - # An owner email would stay in the registry after the person's erasure. - with pytest.raises(BadConfigError, match="unknown"): - domain.parse_items("gdrive", [{"type": "filter", "owner": "a.person@example.com"}]) - - -def test_a_folder_link_removes_the_shared_drive_it_names(fake: _Store, fleet: Any) -> None: - drive_id = "0AbCdEfGhIjKlMnOpQr" - items = [{"type": "shared_drive", "id": drive_id}, _folder()] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - link = f"https://drive.google.com/drive/folders/{drive_id}" - out = asyncio.run(app.handle_knowledge_source_update(_update(remove_links=[link]))) - assert out.items == [_folder()] and out.removed == [{"type": "shared_drive", "id": drive_id}] - - -def test_a_dry_run_is_answered_during_a_rollout(fake: _Store, fleet: Any) -> None: - fleet["ready"] = False - body = _add(config=None, items=[_folder(recursive=True)], dry_run=True) - assert asyncio.run(app.handle_knowledge_source_add(body)).dry_run - assert fake.rows == {} and fleet["reads"] == 0 - - -def test_update_refuses_an_erasure_that_starts_during_its_probe( - fake: _Store, monkeypatch: pytest.MonkeyPatch, fleet: Any -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - stored = _stored(fake) - erasures = fake.erasures - - async def _probe(*_: Any, **__: Any) -> source_probes.Probe: - erasures.append({"scope_type": "namespace", "scope_value": NS}) - return source_probes.Probe(documents=1) - - monkeypatch.setattr(source_probes, "probe", _probe) - with pytest.raises(ErasureRunningError): - asyncio.run( - app.handle_knowledge_source_update(_update(add_items=[{"type": "file", "id": FILE}])) - ) - assert _stored(fake) == stored - - -def test_update_refuses_a_person_s_own_place(fake: _Store) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - fake.claimed.add(NS) - assert _code(app.handle_knowledge_source_update(_update(include=["pdf"]))) == ( - "PERSONAL_NAMESPACE" - ) - - -def test_an_update_asks_again_over_a_full_request_already_waiting(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - waiting = "2026-01-01T00:00:00+00:00" - fake.states["design-decks"] = { - "state_value": "", - "detail": json.dumps({"full": True, "requested_at": waiting}), - } - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - # A turn already running over the old items clears only the request it read. - detail = json.loads(fake.states["design-decks"]["detail"]) - assert detail["full"] is True and detail["requested_at"] != waiting - - -def test_an_update_s_request_differs_from_one_made_in_the_same_second( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - same_second = app._now_iso() - fake.states["design-decks"] = { - "state_value": "", - "detail": json.dumps({"full": True, "requested_at": same_second}), - } - monkeypatch.setattr(app, "_now_iso", lambda: same_second) - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - assert json.loads(fake.states["design-decks"]["detail"])["requested_at"] != same_second - - -@pytest.mark.parametrize(("kind", "most"), [("linear", 20), ("notion", 20), ("gdrive", 300)]) -def test_a_source_holds_as_many_items_as_its_kind_reads(kind: str, most: int) -> None: - item = { - "linear": lambda n: {"type": "project", "id": f"{n:08d}-0000-4000-8000-000000000000"}, - "notion": lambda n: {"type": "page", "id": f"{n:032x}"}, - "gdrive": lambda n: {"type": "file", "id": f"{FILE}{n:03d}"}, - }[kind] - app._require_count(kind, [item(n) for n in range(most)], ["items"]) - with pytest.raises(BadConfigError, match=f"^items: at most {most} items"): - app._require_count(kind, [item(n) for n in range(most + 1)], ["items"]) - - -P1 = "11111111-1111-4111-8111-111111111111" -P2 = "22222222-2222-4222-8222-222222222222" -P3 = "33333333-3333-4333-8333-333333333333" - - -def _linear(monkeypatch: pytest.MonkeyPatch, slugs: dict[str, str]) -> list[list[str]]: - """A tracker whose short ids name `slugs`; each lookup's short ids, in order.""" - from server.clients import linear - - asked: list[list[str]] = [] - - async def _ids(credential: str, wanted: list[str]) -> dict[str, str]: - asked.append(list(wanted)) - return {s: slugs[s] for s in wanted if s in slugs} - - monkeypatch.setattr(linear, "project_ids", _ids) - return asked - - -def test_update_resolves_added_and_removed_short_ids_in_one_lookup( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - config = {"project_ids": [P1, P2]} - asyncio.run(app.handle_knowledge_source_add(_add(kind="linear", config=config))) - asked = _linear(monkeypatch, {"aaaaaaaaaaaa": P3, "bbbbbbbbbbbb": P2}) - out = asyncio.run( - app.handle_knowledge_source_update( - _update( - add_items=[{"type": "project", "slug_id": "aaaaaaaaaaaa"}], - remove_items=[{"type": "project", "slug_id": "bbbbbbbbbbbb"}], - ) - ) - ) - assert asked == [["aaaaaaaaaaaa", "bbbbbbbbbbbb"]] - assert out.added == [{"type": "project", "id": P3}] - assert out.removed == [{"type": "project", "id": P2}] - assert _stored(fake).items == [{"type": "project", "id": P1}, {"type": "project", "id": P3}] - - -def test_a_project_named_by_id_and_by_short_id_is_stored_once( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - _linear(monkeypatch, {"aaaaaaaaaaaa": P1}) - items = [{"type": "project", "id": P1}, {"type": "project", "slug_id": "aaaaaaaaaaaa"}] - out = asyncio.run( - app.handle_knowledge_source_add(_add(kind="linear", config=None, items=items)) - ) - assert out.items == [{"type": "project", "id": P1}] - # Probed once, its duplicate dropped before the probe. - assert fake.probed_items[-1] == [{"type": "project", "id": P1}] - assert out.probe.checked == 1 - - -def test_update_refuses_a_tracker_source_grown_past_its_twenty(fake: _Store, fleet: Any) -> None: - held = [f"{n:08d}-0000-4000-8000-000000000000" for n in range(15)] - asyncio.run(app.handle_knowledge_source_add(_add(kind="linear", config={"project_ids": held}))) - more = [ - {"type": "project", "id": f"{n:08d}-0000-4000-8000-000000000000"} for n in range(15, 21) - ] - with pytest.raises(BadConfigError, match="at most 20 items"): - asyncio.run(app.handle_knowledge_source_update(_update(add_items=more))) - - -def test_update_refuses_an_item_both_added_and_removed(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - stored = _stored(fake) - probes = len(fake.probes) - body = _update(add_items=[_folder()], remove_items=[_folder()]) - assert _code(app.handle_knowledge_source_update(body)) == "BAD_CONFIG" - # Refused before any probe. - assert _stored(fake) == stored and len(fake.probes) == probes - - -def test_update_refuses_a_held_drive_both_added_and_removed_by_its_folder_link( - fake: _Store, fleet: Any -) -> None: - drive_id = "0AbCdEfGhIjKlMnOpQr" - items = [{"type": "shared_drive", "id": drive_id}, _folder()] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - probes = len(fake.probes) - link = f"https://drive.google.com/drive/folders/{drive_id}" - body = _update(add_links=[link], remove_links=[link]) - assert _code(app.handle_knowledge_source_update(body)) == "BAD_CONFIG" - assert len(fake.probes) == probes - - -def test_update_adds_and_removes_a_filter_item(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - item = {"type": "filter", "name_contains": "plan", "in": FOLDER} - out = asyncio.run(app.handle_knowledge_source_update(_update(add_items=[item]))) - assert item in out.items - out = asyncio.run(app.handle_knowledge_source_update(_update(remove_items=[item]))) - assert out.items == [_folder()] and out.removed == [item] - - -def test_update_answers_a_removed_item_as_the_source_held_it(fake: _Store, fleet: Any) -> None: - items = [_folder(recursive=True), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - # The link reads `recursive: false`; the answer names the folder as it was stored. - out = asyncio.run(app.handle_knowledge_source_update(_update(remove_links=[LINK]))) - assert out.removed == [_folder(recursive=True)] - - -def _foreign_probe(monkeypatch: pytest.MonkeyPatch, foreign: list[str]) -> list[Any]: - """A probe that names `foreign` as files of a kind the source does not read.""" - calls: list[Any] = [] - - async def _probe( - kind: str, config: dict[str, Any], credential: str, **kw: Any - ) -> source_probes.Probe: - calls.append(kw.get("items")) - named = {f: domain.GDRIVE_MIME_TYPES["docs"] for f in foreign} - return source_probes.Probe(documents=0, items=kw.get("items") or [], foreign=named) - - monkeypatch.setattr(source_probes, "probe", _probe) - return calls - - -def test_add_refuses_a_file_of_a_kind_its_include_does_not_name( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - _foreign_probe(monkeypatch, [FILE]) - body = _add(config=None, items=[{"type": "file", "id": FILE}]) - assert _code(app.handle_knowledge_source_add(body)) == "BAD_CONFIG" - assert fake.rows == {} - - -def test_an_include_update_probes_the_stored_files_and_rotate_is_not_refused( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - stored = _stored(fake) - calls = _foreign_probe(monkeypatch, [FILE]) - # A narrower include that no longer names the stored file's kind is refused. - assert _code(app.handle_knowledge_source_update(_update(include=["pdf"]))) == "BAD_CONFIG" - assert calls == [[{"type": "file", "id": FILE}]] and _stored(fake) == stored - # The shared probe names the file but refuses nothing, so rotate still works. - body = KnowledgeSourceRotateInput(org=ORG, namespace=NS, name="design-decks", credential=SECRET) - assert asyncio.run(app.handle_knowledge_source_rotate(body)).name == "design-decks" - - -def test_a_folder_added_beside_the_drive_of_its_id_adds_nothing(fake: _Store, fleet: Any) -> None: - drive = {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"} - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=[drive]))) - out = asyncio.run(app.handle_knowledge_source_update(_update(add_items=[_folder(drive["id"])]))) - assert out.items == [drive] and out.added == [] - - -def test_an_update_swapping_a_drive_for_its_root_folder_adds_the_folder( - fake: _Store, fleet: Any -) -> None: - drive = {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"} - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=[drive, _folder()]))) - out = asyncio.run( - app.handle_knowledge_source_update( - _update(remove_items=[drive], add_items=[_folder(drive["id"])]) - ) - ) - assert out.items == [_folder(), _folder(drive["id"])] - assert out.added == [_folder(drive["id"])] and out.removed == [drive] - - -def test_an_add_of_a_drive_and_a_link_to_its_root_folder_keeps_the_drive( - fake: _Store, fleet: Any -) -> None: - drive = {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"} - link = f"https://drive.google.com/drive/folders/{drive['id']}" - body = _add(config=None, items=[drive], links=[link]) - assert asyncio.run(app.handle_knowledge_source_add(body)).items == [drive] - - -def test_a_filter_whose_kinds_include_does_not_name_is_refused(fake: _Store, fleet: Any) -> None: - item = {"type": "filter", "kinds": ["docx"]} - body = _add(config=None, items=[item], include=["docs"]) - assert _code(app.handle_knowledge_source_add(body)) == "BAD_CONFIG" - asyncio.run(app.handle_knowledge_source_add(_add())) - # Nor can an update narrow include below a stored filter's kinds. - asyncio.run( - app.handle_knowledge_source_update( - _update(add_items=[{"type": "filter", "kinds": ["pdf"]}]) - ) - ) - assert _code(app.handle_knowledge_source_update(_update(include=["docs"]))) == "BAD_CONFIG" - - -def test_an_include_update_that_removes_the_file_it_would_refuse_succeeds( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - calls = _foreign_probe(monkeypatch, [FILE]) - body = _update(include=["pdf"], remove_items=[{"type": "file", "id": FILE}]) - out = asyncio.run(app.handle_knowledge_source_update(body)) - # The file goes with this call, so it is not probed against the new include. - assert out.items == [_folder()] and calls == [] - - -def test_an_include_restated_unchanged_is_no_change( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - calls = _foreign_probe(monkeypatch, []) - include = list(_stored(fake).config["include"]) - stored = _stored(fake) - # A retried call restates what landed: it answers the source, probing and writing none. - out = asyncio.run(app.handle_knowledge_source_update(_update(include=include))) - assert out.include == include and out.added == [] and calls == [] - assert _stored(fake) == stored - # Restated beside an added item, only the added item is probed. - asyncio.run( - app.handle_knowledge_source_update( - _update(add_items=[_folder("2QrStUvWxYzAbCdEf")], include=include) - ) - ) - assert calls == [[_folder("2QrStUvWxYzAbCdEf")]] - - -def test_an_include_only_update_answers_the_stored_files_probe( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - _foreign_probe(monkeypatch, []) - out = asyncio.run(app.handle_knowledge_source_update(_update(include=["docs"]))) - assert out.probe.checked == 1 - - -def test_an_include_update_retries_when_another_update_adds_a_file_during_its_probe( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - other = {"type": "file", "id": f"{FILE}2"} - - async def _probe_while_added(*_: Any, **kw: Any) -> source_probes.Probe: - row = _stored(fake) - fake.rows[(ORG, NS, "design-decks")] = dataclasses.replace(row, items=[*row.items, other]) - return source_probes.Probe(documents=1, items=kw.get("items") or []) - - monkeypatch.setattr(source_probes, "probe", _probe_while_added) - with pytest.raises(OverloadedError): - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - - -def test_a_file_add_retries_when_another_update_changes_include_during_its_probe( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - - async def _probe_while_narrowed(*_: Any, **kw: Any) -> source_probes.Probe: - row = _stored(fake) - fake.rows[(ORG, NS, "design-decks")] = dataclasses.replace(row, config={"include": ["pdf"]}) - return source_probes.Probe(documents=1, items=kw.get("items") or []) - - monkeypatch.setattr(source_probes, "probe", _probe_while_narrowed) - body = _update(add_items=[{"type": "file", "id": FILE}]) - with pytest.raises(OverloadedError): - asyncio.run(app.handle_knowledge_source_update(body)) - - -def test_an_update_with_its_own_include_also_retries_when_another_changed_it( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - - async def _probe_while_narrowed(*_: Any, **kw: Any) -> source_probes.Probe: - row = _stored(fake) - fake.rows[(ORG, NS, "design-decks")] = dataclasses.replace(row, config={"include": ["pdf"]}) - return source_probes.Probe(documents=1, items=kw.get("items") or []) - - monkeypatch.setattr(source_probes, "probe", _probe_while_narrowed) - body = _update(add_items=[{"type": "file", "id": FILE}], include=["docs", "pdf"]) - # Any change during the probe is retried: the caller sees the other change first. - with pytest.raises(OverloadedError): - asyncio.run(app.handle_knowledge_source_update(body)) - - -def test_a_plain_sync_now_leaves_an_update_s_full_request_as_it_is( - fake: _Store, fleet: Any -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - before = fake.states["design-decks"]["detail"] - body = KnowledgeSourceSyncNowInput(org=ORG, namespace=NS, name="design-decks") - asyncio.run(app.handle_knowledge_source_sync_now(body)) - # Neither narrowed nor started over: the request's file waits are reset only once. - assert fake.states["design-decks"]["detail"] == before - - -def test_an_update_retries_when_a_rotate_landed_during_its_probe( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - - async def _probe_while_rotated(*_: Any, **kw: Any) -> source_probes.Probe: - row = _stored(fake) - fake.rows[(ORG, NS, "design-decks")] = dataclasses.replace(row, credential_enc="other") - return source_probes.Probe(documents=1, items=kw.get("items") or []) - - monkeypatch.setattr(source_probes, "probe", _probe_while_rotated) - # The added folder was probed with the old credential only. - with pytest.raises(OverloadedError): - asyncio.run( - app.handle_knowledge_source_update(_update(add_items=[_folder("2QrStUvWxYzAbCdEf")])) - ) - - -def test_a_rotate_retries_when_an_update_landed_during_its_probe( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - - async def _probe_while_updated(*_: Any, **kw: Any) -> source_probes.Probe: - row = _stored(fake) - fake.rows[(ORG, NS, "design-decks")] = dataclasses.replace( - row, items=[*row.items, _folder("2QrStUvWxYzAbCdEf")] - ) - return source_probes.Probe(documents=1, items=kw.get("items") or []) - - monkeypatch.setattr(source_probes, "probe", _probe_while_updated) - body = KnowledgeSourceRotateInput(org=ORG, namespace=NS, name="design-decks", credential=SECRET) - # The new credential never saw the folder the update added. - with pytest.raises(OverloadedError): - asyncio.run(app.handle_knowledge_source_rotate(body)) - - -def test_bad_link_message_stays_bounded_for_overlong_links(fake: _Store) -> None: - long = "https://drive.google.com/drive/folders/" + "a" * 2000 - with pytest.raises(ValidationError) as e: - asyncio.run(app.handle_knowledge_source_add(_add(config=None, links=[long] * 3))) - # Each link and its reason are cut, so the message never grows with the input, and - # the reason still says why. - assert e.value.to_detail()["code"] == "BAD_LINK" and len(str(e.value)) < 3 * 250 - assert "is not an id" in str(e.value) - - -@pytest.mark.parametrize( - ("kw", "code"), - [ - ({"config": None, "items": [{"type": "folder", "id": "a" * 100_000}]}, "BAD_CONFIG"), - ({"config": {"folder_ids": ["a" * 100_000]}}, "BAD_CONFIG"), - ({"config": None, "items": [_folder()], "include": ["x" * 100_000]}, "BAD_CONFIG"), - ({"config": None, "items": [{**_folder(), "k" * 100_000: 1}]}, "BAD_CONFIG"), - ({"config": {"folder_ids": [FOLDER], "k" * 100_000: 1}}, "BAD_CONFIG"), - ({"kind": "k" * 100_000}, "BAD_KIND"), - ], -) -def test_a_refused_value_is_quoted_in_part(fake: _Store, kw: dict[str, Any], code: str) -> None: - with pytest.raises(ValidationError) as e: - asyncio.run(app.handle_knowledge_source_add(_add(**kw))) - # At most 40 characters of it, quoted, the cut marked. - assert e.value.to_detail()["code"] == code and len(str(e.value)) < 200 - assert "…" in str(e.value) - - -def test_unknown_keys_name_the_first_and_count_the_rest(fake: _Store) -> None: - item = {**_folder(), "aa": 1, "bb": 2} - with pytest.raises(ValidationError) as e: - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=[item]))) - assert "unknown key 'aa' and 1 more" in str(e.value) +# ---- bounded diagnostics and source quotas ---------------------------------- def test_a_value_that_fits_is_quoted_whole() -> None: @@ -2225,9 +1389,9 @@ def test_a_value_that_fits_is_quoted_whole() -> None: def test_an_unknown_source_name_is_quoted_in_part(fake: _Store) -> None: - body = KnowledgeSourceUpdateInput(org=ORG, namespace=NS, name="n" * 100_000, include=["pdf"]) + body = KnowledgeSourceCheckInput(org=ORG, namespace=NS, name="n" * 100_000) with pytest.raises(NotFoundError) as e: - asyncio.run(app.handle_knowledge_source_update(body)) + asyncio.run(app.handle_knowledge_source_check(body)) assert e.value.to_detail()["code"] == "SOURCE_NOT_FOUND" and len(str(e.value)) < 200 assert "…" in str(e.value) @@ -2243,425 +1407,6 @@ def test_remove_quotes_a_long_name_in_part(fake: _Store, confirm: str, code: str assert "…" in str(e.value) -def test_update_names_the_field_a_bad_item_came_in(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - with pytest.raises(ValidationError, match=r"add_items\[0\]\.id"): - asyncio.run( - app.handle_knowledge_source_update(_update(add_items=[{"type": "folder", "id": "x y"}])) - ) - with pytest.raises(ValidationError, match=r"remove_items\[0\]\.id"): - asyncio.run( - app.handle_knowledge_source_update( - _update(remove_items=[{"type": "folder", "id": "x y"}]) - ) - ) - - -def test_bad_link_names_the_first_ten_and_counts_the_rest(fake: _Store) -> None: - links = [f"https://example.com/{n}" for n in range(25)] - with pytest.raises(ValidationError) as e: - asyncio.run(app.handle_knowledge_source_add(_add(config=None, links=links))) - message = str(e.value) - assert "example.com/9" in message and "example.com/10" not in message - assert message.endswith("and 15 more") - - -def test_update_counts_added_items_and_links_together(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - items = [{"type": "file", "id": f"{FILE}{n:03d}"} for n in range(200)] - links = [f"https://drive.google.com/file/d/{FILE}{n:03d}x/view" for n in range(200)] - with pytest.raises(ValidationError, match="add_items and add_links: at most 300"): - asyncio.run(app.handle_knowledge_source_update(_update(add_items=items, add_links=links))) - - -def test_a_count_refusal_names_only_the_fields_sent(fake: _Store, fleet: Any) -> None: - # A page store keeps 20 items, so 21 links pass the wire's bound and reach the count. - links = [f"https://www.notion.so/Page-{n:032x}" for n in range(21)] - body = _add(kind="notion", config=None, links=links) - with pytest.raises(ValidationError, match=r"^links: at most 20"): - asyncio.run(app.handle_knowledge_source_add(body)) - - -def test_a_drive_added_for_a_held_folder_of_its_id_replaces_it( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - drive_id = "0AbCdEfGhIjKlMnOpQr" - asyncio.run( - app.handle_knowledge_source_add(_add(config=None, items=[_folder(drive_id), _folder()])) - ) - - async def _as_drive(*_: Any, **kw: Any) -> source_probes.Probe: - # The probe finds the recursive folder is the drive's root. - return source_probes.Probe(documents=1, items=[{"type": "shared_drive", "id": drive_id}]) - - monkeypatch.setattr(source_probes, "probe", _as_drive) - body = _update(add_items=[_folder(drive_id, recursive=True)]) - out = asyncio.run(app.handle_knowledge_source_update(body)) - assert out.items == [_folder(), {"type": "shared_drive", "id": drive_id}] - # The folder the drive replaced is named as removed. - assert out.removed == [_folder(drive_id)] - - -def test_a_drive_removed_and_added_back_as_its_root_folder_is_refused( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - drive = {"type": "shared_drive", "id": "0AbCdEfGhIjKlMnOpQr"} - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=[drive, _folder()]))) - stored = _stored(fake) - - async def _as_drive(*_: Any, **kw: Any) -> source_probes.Probe: - return source_probes.Probe(documents=1, items=[drive]) - - monkeypatch.setattr(source_probes, "probe", _as_drive) - # The probe names the folder as the drive, so the source re-read under its lease - # refuses the change. - body = _update(remove_items=[drive], add_items=[_folder(drive["id"], recursive=True)]) - assert _code(app.handle_knowledge_source_update(body)) == "BAD_CONFIG" - assert _stored(fake) == stored - - -def test_the_fleet_gate_names_the_items_migration() -> None: - migrations = Path(__file__).resolve().parents[2] / "schemas" / "migrations" - found = migrations.glob(f"{app._ITEMS_MIGRATION:03d}_*.sql") - assert [p.name for p in found] == [f"{app._ITEMS_MIGRATION:03d}_knowledge_source_items.sql"] - - -def test_an_include_update_over_an_unshared_kept_file_says_it_can_be_removed( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - - async def _unshared(*_: Any, **__: Any) -> source_probes.Probe: - message = f"file {FILE}: not found; share it with the service account" - raise source_probes.SourceUnreachable(message, FILE) - - monkeypatch.setattr(source_probes, "probe", _unshared) - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - assert raised.value.to_detail()["code"] == "SOURCE_UNREACHABLE" - assert raised.value.message.endswith( - "share it with the service account, or remove it with remove_items" - ) - - -def test_an_include_update_the_store_does_not_answer_gives_no_remove_hint( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - - async def _slow(*_: Any, **__: Any) -> source_probes.Probe: - raise source_probes.SourceUnreachable("the source did not answer within 20 s") - - monkeypatch.setattr(source_probes, "probe", _slow) - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - assert "remove_items" not in raised.value.message - - -def test_only_an_unseen_removed_short_id_says_to_remove_by_id( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - config = {"project_ids": [P1, P2]} - asyncio.run(app.handle_knowledge_source_add(_add(kind="linear", config=config))) - _linear(monkeypatch, {}) - gone = [{"type": "project", "slug_id": "bbbbbbbbbbbb"}] - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_update(_update(remove_items=gone))) - assert raised.value.message.endswith("; remove a source's own project by its id") - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_update(_update(add_items=gone))) - assert raised.value.message.endswith("the key's account must see it") - - -def test_a_kept_file_of_a_dropped_kind_names_both_ways_out( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - _foreign_probe(monkeypatch, [FILE]) - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - assert raised.value.message == ( - f"file {FILE}: not a kind the source's include names; name its kind in include, " - "or remove it with remove_items" - ) - - -def test_a_file_of_a_type_the_sync_does_not_read_is_named_as_such( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - async def _probe(kind: str, config: dict[str, Any], credential: str, **kw: Any) -> Any: - return source_probes.Probe(documents=0, items=kw["items"], foreign={FILE: "image/png"}) - - monkeypatch.setattr(source_probes, "probe", _probe) - body = _add(config=None, items=[{"type": "file", "id": FILE}]) - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_add(body)) - assert raised.value.message == f"file {FILE}: 'image/png' is a type the sync does not read" - - -def test_a_folder_given_as_a_file_item_says_to_add_it_as_a_folder( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - folder = "application/vnd.google-apps.folder" - - async def _probe(kind: str, config: dict[str, Any], credential: str, **kw: Any) -> Any: - return source_probes.Probe(documents=0, items=kw["items"], foreign={FILE: folder}) - - monkeypatch.setattr(source_probes, "probe", _probe) - body = _add(config=None, items=[{"type": "file", "id": FILE}]) - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_add(body)) - assert raised.value.message == f"file {FILE}: a folder; add it as a folder item" - - -def _trashed_probe(monkeypatch: pytest.MonkeyPatch) -> None: - async def _probe(kind: str, config: dict[str, Any], credential: str, **kw: Any) -> Any: - return source_probes.Probe(documents=0, items=kw["items"], trashed=[FILE]) - - monkeypatch.setattr(source_probes, "probe", _probe) - - -def test_add_refuses_a_trashed_file( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - _trashed_probe(monkeypatch) - items = [_folder(), {"type": "file", "id": FILE}] - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - assert raised.value.to_detail()["code"] == "SOURCE_UNREACHABLE" - assert raised.value.message.endswith(f"file {FILE}: in the trash; restore it first") - - -def test_rotate_is_not_refused_over_a_trashed_file( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - _trashed_probe(monkeypatch) - body = KnowledgeSourceRotateInput(org=ORG, namespace=NS, name="design-decks", credential=SECRET) - assert asyncio.run(app.handle_knowledge_source_rotate(body)).name == "design-decks" - - -def test_an_include_update_over_a_trashed_kept_file_says_it_can_be_removed( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - items = [_folder(), {"type": "file", "id": FILE}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - _trashed_probe(monkeypatch) - with pytest.raises(ValidationError) as raised: - asyncio.run(app.handle_knowledge_source_update(_update(include=["pdf"]))) - assert raised.value.message.endswith( - "in the trash; restore it first, or remove it with remove_items" - ) - - -def test_update_adding_a_trashed_file_is_refused_and_check_is_not( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - _trashed_probe(monkeypatch) - added = [{"type": "file", "id": FILE}] - assert _code(app.handle_knowledge_source_update(_update(add_items=added))) == ( - "SOURCE_UNREACHABLE" - ) - body = KnowledgeSourceCheckInput(org=ORG, namespace=NS, name="design-decks") - assert asyncio.run(app.handle_knowledge_source_check(body)).reachable - - -def test_a_folder_link_to_a_held_drive_changes_nothing(fake: _Store, fleet: Any) -> None: - drive_id = "0AbCdEfGhIjKlMnOpQr" - items = [{"type": "shared_drive", "id": drive_id}, _folder()] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - stored = _stored(fake) - fake.probes.clear() - link = f"https://drive.google.com/drive/folders/{drive_id}" - out = asyncio.run(app.handle_knowledge_source_update(_update(add_links=[link]))) - assert out.items == items and out.added == [] and out.removed == [] - assert _stored(fake) == stored and fake.probes == [] - - -def test_an_update_adding_held_items_again_writes_and_probes_nothing( - fake: _Store, fleet: Any -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - stored, states = _stored(fake), dict(fake.states) - fake.probes.clear() - out = asyncio.run(app.handle_knowledge_source_update(_update(add_items=[_folder()]))) - assert out.items == [_folder()] and out.added == [] - assert _stored(fake) == stored and fake.probes == [] - # No full listing is asked for either. - assert fake.states == states - - -def test_a_folder_link_over_a_held_recursive_folder_changes_nothing( - fake: _Store, fleet: Any -) -> None: - items = [_folder(recursive=True)] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - stored, states = _stored(fake), dict(fake.states) - out = asyncio.run(app.handle_knowledge_source_update(_update(add_links=[LINK]))) - # The link names the folder the source walks; only an item given narrows it. - assert out.items == items and out.added == [] - assert _stored(fake) == stored and fake.states == states - out = asyncio.run(app.handle_knowledge_source_update(_update(add_items=[_folder()]))) - assert out.items == [_folder()] - - -def test_an_item_given_wins_over_a_link_to_the_same_folder(fake: _Store, fleet: Any) -> None: - out = asyncio.run( - app.handle_knowledge_source_add( - _add(config=None, items=[_folder(recursive=True)], links=[LINK]) - ) - ) - assert out.items == [_folder(recursive=True)] - other = "2QrStUvWxYzAbCdEf" - link = f"https://drive.google.com/drive/folders/{other}" - body = _update(add_items=[_folder(other, recursive=True)], add_links=[link]) - out = asyncio.run(app.handle_knowledge_source_update(body)) - assert out.items == [_folder(recursive=True), _folder(other, recursive=True)] - # A held recursive folder: the item given narrows it, the link beside it does not undo that. - body = _update(add_items=[_folder()], add_links=[LINK]) - out = asyncio.run(app.handle_knowledge_source_update(body)) - assert _folder() in out.items and _folder(recursive=True) not in out.items - - -def test_a_folder_the_probe_names_as_a_held_drive_changes_nothing( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - drive_id = "0AbCdEfGhIjKlMnOpQr" - items = [{"type": "shared_drive", "id": drive_id}, _folder()] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - stored, states = _stored(fake), dict(fake.states) - - async def _as_drive(*_: Any, **kw: Any) -> source_probes.Probe: - return source_probes.Probe(documents=1, items=[{"type": "shared_drive", "id": drive_id}]) - - monkeypatch.setattr(source_probes, "probe", _as_drive) - body = _update(add_items=[_folder(drive_id, recursive=True)]) - out = asyncio.run(app.handle_knowledge_source_update(body)) - assert out.items == items and out.added == [] - assert _stored(fake) == stored and fake.states == states - - -def test_a_project_named_by_id_and_by_link_counts_once( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - ids = [f"{n:08x}-1111-4111-8111-111111111111" for n in range(20)] - _linear(monkeypatch, {"aaaaaaaaaaaa": ids[0]}) - items = [{"type": "project", "id": i} for i in ids] - link = "https://linear.app/acme/project/q3-planning-aaaaaaaaaaaa" - body = _add(kind="linear", config=None, items=items, links=[link]) - # 21 entries, 20 projects: the bound counts the projects. - assert len(asyncio.run(app.handle_knowledge_source_add(body)).items) == 20 - - -def test_a_folder_entry_removes_the_shared_drive_of_its_id(fake: _Store, fleet: Any) -> None: - drive_id = "0AbCdEfGhIjKlMnOpQr" - items = [{"type": "shared_drive", "id": drive_id}, _folder()] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=items))) - out = asyncio.run(app.handle_knowledge_source_update(_update(remove_items=[_folder(drive_id)]))) - assert out.items == [_folder()] and out.removed == [{"type": "shared_drive", "id": drive_id}] - - -def test_a_project_named_by_id_and_by_short_id_in_items_counts_once( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - ids = [f"{n:08x}-1111-4111-8111-111111111111" for n in range(20)] - _linear(monkeypatch, {"aaaaaaaaaaaa": ids[0]}) - items = [{"type": "project", "id": i} for i in ids] - items.append({"type": "project", "slug_id": "aaaaaaaaaaaa"}) - body = _add(kind="linear", config=None, items=items) - assert len(asyncio.run(app.handle_knowledge_source_add(body)).items) == 20 - - -def test_an_update_counts_a_project_named_by_id_and_by_link_once( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - held = [f"{n:08x}-1111-4111-8111-111111111111" for n in range(19)] - asyncio.run(app.handle_knowledge_source_add(_add(kind="linear", config={"project_ids": held}))) - _linear(monkeypatch, {"bbbbbbbbbbbb": P3}) - link = "https://linear.app/acme/project/q3-planning-bbbbbbbbbbbb" - body = _update(add_items=[{"type": "project", "id": P3}], add_links=[link]) - assert len(asyncio.run(app.handle_knowledge_source_update(body)).items) == 20 - - -def test_a_call_too_large_is_refused_before_the_short_id_lookup( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asked = _linear(monkeypatch, {}) - links = [f"https://linear.app/acme/project/p-{n:012x}" for n in range(21)] - with pytest.raises(BadConfigError, match="^links: at most 20"): - asyncio.run(app.handle_knowledge_source_add(_add(kind="linear", config=None, links=links))) - assert asked == [] - - -def test_an_update_too_large_is_refused_before_the_short_id_lookup( - fake: _Store, fleet: Any, monkeypatch: pytest.MonkeyPatch -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add(kind="linear", config={"project_ids": [P1]}))) - asked = _linear(monkeypatch, {}) - links = [f"https://linear.app/acme/project/p-{n:012x}" for n in range(21)] - with pytest.raises(BadConfigError, match="^add_links: at most 20"): - asyncio.run(app.handle_knowledge_source_update(_update(add_links=links))) - # Removals past what the source holds are refused before the lookup too. - with pytest.raises( - BadConfigError, match="^remove_links: names more items than the source holds" - ): - asyncio.run(app.handle_knowledge_source_update(_update(remove_links=links[:2]))) - assert asked == [] - - -def test_an_unreadable_link_is_named_with_its_field(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - body = _update(remove_links=["https://example.com/a"]) - with pytest.raises(ValidationError, match=r"^unreadable remove_links: "): - asyncio.run(app.handle_knowledge_source_update(body)) - - -@pytest.mark.parametrize( - "body", [{"include": ["docs", "slides", "pdf", "pptx"]}, {"add_items": [_folder()]}] -) -def test_an_update_that_changes_nothing_is_still_refused_during_an_erasure( - fake: _Store, fleet: Any, body: dict[str, Any] -) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - fake.erasures.append({"scope_type": "namespace", "scope_value": NS}) - # However a no-op is phrased, it answers as every update does. - with pytest.raises(ErasureRunningError): - asyncio.run(app.handle_knowledge_source_update(_update(**body))) - - -def test_a_folder_entry_and_a_drive_entry_of_one_id_remove_the_drive_once( - fake: _Store, fleet: Any -) -> None: - drive_id = "0AbCdEfGhIjKlMnOpQr" - drive = {"type": "shared_drive", "id": drive_id} - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=[drive, _folder()]))) - body = _update(remove_items=[_folder(drive_id), drive]) - out = asyncio.run(app.handle_knowledge_source_update(body)) - assert out.items == [_folder()] and out.removed == [drive] - - -def test_an_update_naming_nothing_says_what_to_name(fake: _Store, fleet: Any) -> None: - asyncio.run(app.handle_knowledge_source_add(_add())) - with pytest.raises(BadConfigError, match="^name an item, a link or include to change"): - asyncio.run(app.handle_knowledge_source_update(_update())) - - -def test_redundant_folder_and_drive_entries_count_as_the_items_they_name( - fake: _Store, fleet: Any -) -> None: - x, y = "0AbCdEfGhIjKlMnOpQr", "0BbCdEfGhIjKlMnOpQr" - drives = [{"type": "shared_drive", "id": x}, {"type": "shared_drive", "id": y}] - asyncio.run(app.handle_knowledge_source_add(_add(config=None, items=[*drives, _folder()]))) - body = _update(remove_items=[_folder(x), drives[0], _folder(y), drives[1]]) - out = asyncio.run(app.handle_knowledge_source_update(body)) - assert out.items == [_folder()] and out.removed == drives - - @pytest.mark.parametrize("axis", ["namespace", "person"]) def test_connected_source_quota_uses_its_own_namespace_and_owner_bounds( fake: _Store, monkeypatch: pytest.MonkeyPatch, axis: str @@ -2698,3 +1443,14 @@ def test_shared_source_writer_is_refused_before_probe_or_registry_write( with acting_as(_auth(Role.WRITER)), pytest.raises(AuthInsufficientError): asyncio.run(app.handle_knowledge_source_add(_add())) assert fake.rows == {} and fake.probes == [] + + +@pytest.mark.parametrize("kind", ["ftp", "gdrive", "notion", "linear"]) +def test_native_kinds_refuse_at_the_wire_without_echoing_input(fake, kind): + from pydantic import ValidationError as InputValidationError + + with pytest.raises(InputValidationError) as caught: + _add(kind=kind) + assert "PRIVATE_SOURCE_INPUT_INVALID" in str(caught.value) + assert kind not in str(caught.value) and SECRET not in str(caught.value) + assert fake.rows == {} and fake.probes == [] diff --git a/tests/unit/test_live_provider_search.py b/tests/unit/test_live_provider_search.py deleted file mode 100644 index 4af8cc55a5..0000000000 --- a/tests/unit/test_live_provider_search.py +++ /dev/null @@ -1,267 +0,0 @@ -"""Live hits retain native corpus membership and bounded checked transport.""" - -from __future__ import annotations - -import asyncio -import json -from collections.abc import AsyncIterator -from types import SimpleNamespace -from typing import Any, Literal - -import httpx -import pytest - -from server.clients import _vendor, notion -from server.clients._checked_access import CheckedAccess -from server.knowledge.app import live_provider_search as live -from server.knowledge.domain.sources import KnowledgeSource -from tests.unit.clock_fake import ManualClock - -_PAGE = "12345678-1234-1234-1234-123456789abc" -_DATABASE = "22345678-1234-1234-1234-123456789abc" -_OTHER_DATABASE = "32345678-1234-1234-1234-123456789abc" - - -def _source(kind: str, items: list[dict[str, Any]]) -> KnowledgeSource: - return KnowledgeSource( - org="org", - namespace="ns", - name="docs", - kind=kind, - source_id="selected-source", - credential_mode="connected", - access="mirrored", - owner_subject="asker", - connection_id="selected-generation", - config={"include": ["docs"]} if kind == "gdrive" else {}, - items=items, - ) - - -def _access(kind: Literal["gdrive", "notion", "linear"]) -> CheckedAccess: - async def validate() -> None: - pass - - return CheckedAccess( - "checked-token", - kind=kind, - deadline=asyncio.get_running_loop().time() + 60, - validate=validate, - ) - - -async def test_drive_search_quotes_query_and_refuses_a_hit_moved_out_of_its_filter( - monkeypatch: pytest.MonkeyPatch, -) -> None: - source = _source("gdrive", [{"type": "filter", "in": "folder123456", "name_contains": "Plan"}]) - access = _access("gdrive") - calls: list[httpx.Request] = [] - file = { - "id": "file12345678", - "name": "Plan", - "trashed": False, - "mimeType": "application/vnd.google-apps.document", - "parents": ["folder123456"], - "webViewLink": "https://docs.google.com/document/d/file12345678/edit?private=1#heading", - } - - def handle(request: httpx.Request) -> httpx.Response: - calls.append(request) - assert request.headers["Authorization"] == "Bearer checked-token" - if request.url.path.endswith("/files"): - assert request.url.params["pageSize"] == "3" - query = request.url.params["q"] - assert "'folder123456' in parents" in query - assert "name contains 'Plan'" in query - assert query.endswith("fullText contains 'a\\' or trashed = true'") - return httpx.Response( - 200, json={"files": [file, {**file, "id": "outside12345", "parents": []}]} - ) - # A rename that still contains the fragment is outside Drive's prefix filter. - return httpx.Response(200, json={**file, "name": "Old Plan"}) - - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: - monkeypatch.setattr(live, "get_client", lambda: client) - hits = await live.search( - source, access, "a' or trashed = true", top_k=3, deadline=access.deadline - ) - assert hits == [ - live.LiveProviderHit( - "file12345678", - "Plan", - "https://docs.google.com/document/d/file12345678/edit", - "gdrive", - ) - ] - assert not await live.revalidate(source, access, hits[0], deadline=access.deadline) - assert len(calls) == 2 - - -@pytest.mark.parametrize( - ("modified", "expected"), - [ - ("2026-11-01T00:00:00Z", False), - ("2026-11-01T00:00:00.000Z", False), - ("2026-10-31T23:59:59.999999Z", False), - ("2026-11-01T00:00:00.000001Z", True), - ("2026-11-02T00:00:00Z", True), - ("not-a-date", False), - ("2026-13-99T00:00:00Z", False), - ("2026-11-01T00:00:00", False), - ], -) -async def test_drive_revalidation_excludes_the_strict_modification_cutoff( - monkeypatch: pytest.MonkeyPatch, modified: str, expected: bool -) -> None: - source = _source("gdrive", [{"type": "filter", "modified_after": "2026-11-01"}]) - access = _access("gdrive") - hit = live.LiveProviderHit( - "file12345678", "Plan", "https://docs.google.com/document/d/file12345678/edit", "gdrive" - ) - calls = [] - - def handle(request: httpx.Request) -> httpx.Response: - calls.append(request) - assert request.url.path.endswith("/files/" + hit.id) - return httpx.Response( - 200, - json={ - "id": hit.id, - "name": hit.title, - "mimeType": "application/vnd.google-apps.document", - "trashed": False, - "parents": [], - "modifiedTime": modified, - }, - ) - - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: - monkeypatch.setattr(live, "get_client", lambda: client) - assert await live.revalidate(source, access, hit, deadline=access.deadline) is expected - assert len(calls) == 1 - - -async def test_notion_search_filters_native_pages_and_rechecks_database_membership( - monkeypatch: pytest.MonkeyPatch, -) -> None: - source = _source("notion", [{"type": "database", "id": _DATABASE}]) - access = _access("notion") - calls: list[httpx.Request] = [] - - async def no_pacing(token: Any) -> None: - pass - - page = { - "object": "page", - "id": _PAGE, - "in_trash": False, - "parent": {"type": "data_source_id", "database_id": _DATABASE}, - "properties": {"Name": {"type": "title", "title": [{"plain_text": "Private title"}]}}, - "url": f"https://www.notion.so/{_PAGE}", - } - - def handle(request: httpx.Request) -> httpx.Response: - calls.append(request) - assert request.headers["Notion-Version"] == notion.API_VERSION - if request.method == "POST": - body = json.loads(request.content) - assert body == { - "query": "title", - "page_size": 2, - "filter": {"property": "object", "value": "page"}, - } - return httpx.Response( - 200, - json={"results": [page, {**page, "url": "https://notion.so.evil.example/private"}]}, - ) - return httpx.Response( - 200, - json={**page, "parent": {"type": "data_source_id", "database_id": _OTHER_DATABASE}}, - ) - - async with httpx.AsyncClient(transport=httpx.MockTransport(handle)) as client: - monkeypatch.setattr(live, "get_client", lambda: client) - monkeypatch.setattr(notion, "_pace", no_pacing) - hits = await live.search(source, access, "title", top_k=2, deadline=access.deadline) - assert len(hits) == 1 and hits[0].id == _PAGE and hits[0].title == "Private title" - assert not await live.revalidate(source, access, hits[0], deadline=access.deadline) - assert len(calls) == 2 - - -async def test_an_expired_deadline_or_wrong_provider_never_dispatches( - monkeypatch: pytest.MonkeyPatch, -) -> None: - access = _access("gdrive") - source = _source("gdrive", [{"type": "folder", "id": "folder123456"}]) - clock = ManualClock(t=asyncio.get_running_loop().time()) - monkeypatch.setattr(live, "time", SimpleNamespace(monotonic=clock.monotonic)) - - def no_client() -> Any: - pytest.fail("a refused search must not acquire an HTTP client") - - monkeypatch.setattr(live, "get_client", no_client) - with pytest.raises(live.SearchUnavailable): - await live.search(_source("notion", []), access, "query", top_k=1, deadline=access.deadline) - stop = clock.monotonic() + 1 - clock.advance(2) - with pytest.raises(live.SearchUnavailable): - await live.search(source, access, "query", top_k=1, deadline=stop) - - -class _Oversize(httpx.AsyncByteStream): - def __init__(self) -> None: - self.closed = False - self.reads = 0 - - async def __aiter__(self) -> AsyncIterator[bytes]: - for piece in (b"x" * 65, b"must not be read"): - self.reads += 1 - yield piece - - async def aclose(self) -> None: - self.closed = True - - -async def test_live_response_cap_is_clamped_and_redirects_do_not_forward_credentials( - monkeypatch: pytest.MonkeyPatch, -) -> None: - source = _source("gdrive", [{"type": "folder", "id": "folder123456"}]) - access = _access("gdrive") - stream = _Oversize() - calls: list[httpx.Request] = [] - monkeypatch.setattr(_vendor.settings, "knowledge_source_sync_max_file_bytes", 64) - - def handle(request: httpx.Request) -> httpx.Response: - calls.append(request) - if len(calls) == 1: - return httpx.Response(200, stream=stream) - return httpx.Response( - 302, - headers={"Location": "https://untrusted.example/collect"}, - json={ - "files": [ - { - "id": "file12345678", - "name": "Redirect body must not answer", - "trashed": False, - "mimeType": "application/vnd.google-apps.document", - "parents": ["folder123456"], - "webViewLink": "https://docs.google.com/document/d/file12345678/edit", - } - ] - }, - ) - - async with httpx.AsyncClient( - transport=httpx.MockTransport(handle), follow_redirects=True - ) as client: - monkeypatch.setattr(live, "get_client", lambda: client) - with pytest.raises(_vendor.TooLarge): - await live.search(source, access, "query", top_k=1, deadline=access.deadline) - assert stream.closed and stream.reads == 1 - monkeypatch.setattr(_vendor.settings, "knowledge_source_sync_max_file_bytes", 1024) - with pytest.raises(_vendor.VendorError) as refused: - await live.search(source, access, "query", top_k=1, deadline=access.deadline) - assert refused.value.status == 302 - assert len(calls) == 2 - assert all(request.url.host == "www.googleapis.com" for request in calls) diff --git a/tests/unit/test_live_source_search.py b/tests/unit/test_live_source_search.py index 0170936dea..c7bf72e91f 100644 --- a/tests/unit/test_live_source_search.py +++ b/tests/unit/test_live_source_search.py @@ -6,6 +6,7 @@ import json from contextlib import AsyncExitStack, asynccontextmanager from copy import deepcopy +from dataclasses import replace from types import SimpleNamespace import pytest @@ -14,9 +15,15 @@ from server.core import request_tail, request_work from server.core.diagnostics import codes_only from server.knowledge.app import live_search -from server.knowledge.domain.sources import MIRRORED_ACCESS +from server.knowledge.domain.mcp_identity import resource_uri from server.memory.api.models_loom_search import SearchInput -from tests.unit.principals import acting_as, principal +from tests.unit.principals import acting_as +from tests.unit.test_mcp_source_live import live_setup as live_setup +from tests.unit.test_mcp_source_live import live_tools as live_tools +from tests.unit.test_mcp_source_read_policy import reader as reader +from tests.unit.test_mcp_source_sync import RESOURCE +from tests.unit.test_mcp_source_sync import harness as harness +from tests.unit.test_mcp_source_sync import upstream as upstream @asynccontextmanager @@ -35,23 +42,12 @@ async def _request(auth, *, bag=True, tail=True, protected=True): @pytest.fixture -def native(monkeypatch): - from server.knowledge.store import mirror_latch +def generic(live_tools, monkeypatch): from server.settings import settings monkeypatch.setattr(settings, "auth_required", True) monkeypatch.setattr(settings, "knowledge_mirrored_sources_enabled", True) - auth = principal("viewer", org="org", namespaces=("allowed",), service_account=False) - source = SimpleNamespace( - namespace="allowed", - name="personal", - source_id="original-source", - active=True, - credential_mode="connected", - owner_subject="canonical@example.test", - access=MIRRORED_ACCESS, - kind="gdrive", - ) + source, auth = live_tools.h.source, live_tools.auth state = SimpleNamespace( auth=auth, source=source, @@ -59,20 +55,12 @@ def native(monkeypatch): events=[], resolutions=[], authorities=[], - access=object(), - deadline=None, revoked=False, revocation_seen=False, block=False, started=asyncio.Event(), closed=asyncio.Event(), - ) - hit = live_search.live_provider_search.LiveProviderHit( - "private-id", - "Private title", - "https://drive.google.com/file/d/private-id", - "gdrive", - "private excerpt", + harness=live_tools.h, ) def private(stage): @@ -87,81 +75,73 @@ def private(stage): async def own_subject(actual): private("subject") assert actual is auth - return "org", "canonical@example.test" + return "org", "owner" async def connected_sources(org, subject): private("sources") - assert (org, subject) == ("org", "canonical@example.test") + assert (org, subject) == ("org", "owner") return state.sources - async def ensure(): + async def ensure(actual): private("latch") + assert actual is auth - class Authority: - def __init__(self, selected): - self.source = selected - - async def run(self, callback): - private("authority") - if state.revoked: - state.revocation_seen = True - raise RuntimeError("authority revoked") - return await callback(state.access) + actual_search = live_search.mcp_live.search + actual_check = live_search.mcp_live.Contribution.check - async def resolve(org, namespace, name, *, deadline, expected_source_id): + async def search(selected, actual, query, *, limit): private("resolve") - assert (org, namespace, name) == ("org", "allowed", "personal") - assert expected_source_id == source.source_id - state.resolutions.append((namespace, name, expected_source_id, deadline)) - state.deadline = deadline - authority = Authority(source) - state.authorities.append(authority) - return authority - - async def search(selected, access, query, *, top_k, deadline): + assert selected is source and actual is auth + assert query == "selected" and limit == 2 + state.resolutions.append((selected.namespace, selected.name, selected.source_id)) + private("authority") private("provider") - assert selected is source and access is state.access - assert query == "question" and top_k == 2 - assert deadline == state.deadline state.started.set() try: if state.block: await asyncio.Event().wait() - return [hit] + contribution = await actual_search(selected, actual, query, limit=limit) + assert contribution is not None + state.authorities.append(contribution) + return contribution finally: state.closed.set() - async def revalidate(selected, access, actual_hit, *, deadline): + async def check(contribution): + private("authority") + if state.revoked: + state.revocation_seen = True + raise RuntimeError("authority revoked") private("membership") - assert selected is source and access is state.access and actual_hit is hit - assert deadline == state.deadline - return True + await actual_check(contribution) monkeypatch.setattr(live_search.connected_accounts, "own_subject", own_subject) monkeypatch.setattr(live_search.source_store, "connected_sources", connected_sources) - monkeypatch.setattr(live_search.connected_accounts, "resolve", resolve) - monkeypatch.setattr(mirror_latch, "ensure", ensure) - monkeypatch.setattr(live_search.live_provider_search, "search", search) - monkeypatch.setattr(live_search.live_provider_search, "revalidate", revalidate) + monkeypatch.setattr(live_search.session_admission, "require", ensure) + monkeypatch.setattr(live_search.mcp_live, "search", search) + monkeypatch.setattr(live_search.mcp_live.Contribution, "check", check) return state @pytest.mark.parametrize("missing", ["bag", "tail", "protection"]) -async def test_live_search_requires_real_request_privacy_ownership(native, missing): +async def test_live_search_requires_real_request_privacy_ownership(generic, missing): async with _request( - native.auth, bag=missing != "bag", tail=missing != "tail", protected=missing != "protection" + generic.auth, + bag=missing != "bag", + tail=missing != "tail", + protected=missing != "protection", ): - assert await live_search.search("org", ["allowed"], "question", top_k=2) is None - assert native.events == [] - assert not native.started.is_set() + assert await live_search.search("org", ["collection"], "selected", top_k=2) is None + assert generic.events == [] + assert not generic.started.is_set() async def test_live_search_keeps_only_asker_connected_authorized_sources_and_original_authority( - native, + generic, ): - base = vars(native.source) - native.sources = [ - SimpleNamespace(**{**base, **change}) + base = generic.source + generic.sources = [ + replace(base, **change) for change in ( {"namespace": "foreign"}, {"credential_mode": "shared"}, @@ -169,38 +149,42 @@ async def test_live_search_keeps_only_asker_connected_authorized_sources_and_ori {"active": False}, {"access": "shared"}, ) - ] + [native.source] - async with _request(native.auth): - result = await live_search.search("org", ["allowed"], "question", top_k=2) + ] + [generic.source] + async with _request(generic.auth): + result = await live_search.search("org", ["collection"], "selected", top_k=2) assert result is not None - assert len(native.resolutions) == len(result.contributions) == 1 - assert result.contributions[0].authority is native.authorities[0] - assert result.deadline == native.deadline + assert len(generic.resolutions) == len(result.contributions) == 1 + assert result.contributions[0] is generic.authorities[0] + assert result.contributions[0].source is generic.source + assert result.contributions[0].auth is generic.auth + assert generic.harness.reads == [RESOURCE] + assert not generic.harness.doc_rows and not generic.harness.originals assert await live_search.publish(result) is result assert result.fresh() - assert native.events[:4] == ["subject", "sources", "latch", "resolve"] - assert native.events.count("provider") == native.events.count("membership") == 1 + assert generic.harness.reads == [RESOURCE, RESOURCE] + assert generic.events[:4] == ["subject", "sources", "latch", "resolve"] + assert generic.events.count("provider") == generic.events.count("membership") == 1 -async def test_live_search_expiry_joins_the_started_native_call(native, monkeypatch): - native.block = True +async def test_live_search_expiry_joins_the_started_generic_call(generic, monkeypatch): + generic.block = True monkeypatch.setattr(live_search.settings, "knowledge_live_search_timeout_s", 0) - async with _request(native.auth) as bag: - task = asyncio.create_task(live_search.search("org", ["allowed"], "question", top_k=2)) + async with _request(generic.auth) as bag: + task = asyncio.create_task(live_search.search("org", ["collection"], "selected", top_k=2)) assert await task is None assert task.done() - assert native.started.is_set() and native.closed.is_set() + assert generic.started.is_set() and generic.closed.is_set() assert bag.mirror_marked -async def test_final_response_publication_refuses_revoked_live_authority(native): +async def test_final_response_publication_refuses_revoked_live_authority(generic): sent = [] async def app(scope, receive, send): - result = await live_search.search("org", ["allowed"], "question", top_k=2) + result = await live_search.search("org", ["collection"], "selected", top_k=2) assert result is not None assert await live_search.publish(result) is result - native.revoked = True + generic.revoked = True await send({"type": "http.response.start", "status": 200, "headers": []}) await send({"type": "http.response.body", "body": b"private bytes"}) @@ -210,11 +194,11 @@ async def receive(): async def send(message): sent.append(message) - async with _request(native.auth, tail=False): + async with _request(generic.auth, tail=False): with pytest.raises(request_tail.RequiredTailError): await request_tail.RequestTailMiddleware(app)({"type": "http"}, receive, send) - assert native.events.count("authority") == 3 - assert native.revocation_seen + assert generic.events.count("authority") == 3 + assert generic.revocation_seen assert sent == [] @@ -237,7 +221,7 @@ def indexed(monkeypatch): monkeypatch.setattr(settings, "knowledge_gaps_enabled", False) async def namespaces(*args): - return ["allowed"], [] + return ["collection"], [] async def nothing(*args, **kwargs): return None @@ -254,7 +238,7 @@ async def sections(**kwargs): async def test_delivered_live_answer_prevents_an_otherwise_recorded_gap( - native, indexed, monkeypatch + generic, indexed, monkeypatch ): from server.knowledge.app import gaps from server.settings import settings @@ -263,18 +247,20 @@ async def test_delivered_live_answer_prevents_an_otherwise_recorded_gap( monkeypatch.setattr(settings, "knowledge_gaps_enabled", True) monkeypatch.setattr(gaps, "reads_whole_namespace", lambda: True) monkeypatch.setattr(gaps, "record_miss", lambda **kwargs: misses.append(kwargs)) - request = SearchInput(org="org", namespace="allowed", query="question", top_k=2, live=True) + request = SearchInput(org="org", namespace="collection", query="selected", top_k=2, live=True) indexed._record_gap_miss(request, _indexed(), "") assert len(misses) == 1 - async with _request(native.auth): + async with _request(generic.auth): output = await indexed.handle_search(request) - assert output.live is not None and output.live.results[0].id == "private-id" + assert output.live is not None and output.live.results[0].id == resource_uri( + generic.source.source_id, RESOURCE + ) assert output.memory == _indexed()["memory"] assert len(misses) == 1 async def test_live_mcp_output_protects_the_sdk_before_automatic_capture( - native, indexed, tmp_path, monkeypatch + generic, indexed, tmp_path, monkeypatch ): import httpx from loom.session_protection import AutomaticCaptureSuppressed, SessionProtection @@ -283,13 +269,13 @@ async def test_live_mcp_output_protects_the_sdk_before_automatic_capture( from server.memory.app.served_reads import search_query_keys from server.transport.mcp_outcome import _search_answer - request = SearchInput(org="org", namespace="allowed", query="question", top_k=2, live=True) + request = SearchInput(org="org", namespace="collection", query="selected", top_k=2, live=True) call = SimpleNamespace( - arguments={"query": "question", "top_k": 2}, rl_ns="allowed", mcp_session_id="" + arguments={"query": "selected", "top_k": 2}, rl_ns="collection", mcp_session_id="" ) family = SessionProtection.create(base=tmp_path / "protection") assert not family.protected - async with _request(native.auth): + async with _request(generic.auth): output = await indexed.handle_search(request) answer = _search_answer(call, output) assert output.live is not None @@ -333,20 +319,20 @@ def respond(actual): @pytest.mark.parametrize("outcome", ["indexed_failure", "caller_cancel"]) -async def test_handler_cancels_and_joins_started_live_work(native, indexed, monkeypatch, outcome): - native.block = True +async def test_handler_cancels_and_joins_started_live_work(generic, indexed, monkeypatch, outcome): + generic.block = True async def sections(**kwargs): - await native.started.wait() + await generic.started.wait() if outcome == "indexed_failure": raise ValueError("indexed failed") await asyncio.Event().wait() monkeypatch.setattr(indexed, "search_sections", sections) - request = SearchInput(org="org", namespace="allowed", query="question", top_k=2, live=True) - async with _request(native.auth): + request = SearchInput(org="org", namespace="collection", query="selected", top_k=2, live=True) + async with _request(generic.auth): task = asyncio.create_task(indexed.handle_search(request)) - await asyncio.wait_for(native.started.wait(), 1) + await asyncio.wait_for(generic.started.wait(), 1) if outcome == "caller_cancel": task.cancel() with pytest.raises(asyncio.CancelledError): @@ -354,16 +340,16 @@ async def sections(**kwargs): else: with pytest.raises(ValueError, match="indexed failed"): await task - assert task.done() and native.closed.is_set() + assert task.done() and generic.closed.is_set() @pytest.mark.parametrize( "options", [{}, {"live": True, "tags": ["tag"]}, {"live": True, "page": "page"}] ) -async def test_default_filtered_and_page_calls_do_not_start_live_work(native, indexed, options): - request = SearchInput(org="org", namespace="allowed", query="question", top_k=2, **options) - async with _request(native.auth): +async def test_default_filtered_and_page_calls_do_not_start_live_work(generic, indexed, options): + request = SearchInput(org="org", namespace="collection", query="selected", top_k=2, **options) + async with _request(generic.auth): output = await indexed.handle_search(request) assert output.live is None - assert native.events == [] - assert not native.started.is_set() + assert generic.events == [] + assert not generic.started.is_set() diff --git a/tests/unit/test_mcp_connection_lifecycle.py b/tests/unit/test_mcp_connection_lifecycle.py index 9fcf4b0450..dfa0270d65 100644 --- a/tests/unit/test_mcp_connection_lifecycle.py +++ b/tests/unit/test_mcp_connection_lifecycle.py @@ -21,6 +21,11 @@ OWNER = ("org-one", "owner-one", SLOT) +class _OpaqueCredential(str): + def __bool__(self) -> bool: + raise AssertionError("cleanup must not inspect credentials") + + def test_restore_keeps_owner_and_slot_identity_separate() -> None: groups: dict[Any, set[str]] = defaultdict(set) prefixes: dict[str, Any] = {} @@ -246,32 +251,25 @@ async def test_restore_reuses_durable_inactive_fence_without_same_value_cas( @pytest.mark.asyncio -@pytest.mark.parametrize("kind", [SLOT, "mcp", "unknown-source"]) -async def test_generic_credential_never_enters_native_revocation_factory( - monkeypatch: pytest.MonkeyPatch, kind: str +@pytest.mark.parametrize("kind", [SLOT, "gdrive", "notion", "linear"]) +async def test_owner_erasure_uses_stored_keys_without_credential_execution( + owner_history: SimpleNamespace, kind: str ) -> None: - factory = Mock( - side_effect=AssertionError("native revocation factory must not receive this kind") + state = owner_history + owner = (*OWNER[:2], kind) + state.rows[owner] = restore.ConnectedAccount( + *owner, CONNECTION, active=True, credential_enc=_OpaqueCredential("retained-envelope") ) - monkeypatch.setattr(restore.accounts, "client", factory) - account = restore.ConnectedAccount("org-one", "owner-one", kind, CONNECTION) - await restore.accounts._revoke(account, credential="nonempty-generic-envelope") - factory.assert_not_called() - - -@pytest.mark.asyncio -async def test_native_revocation_control_still_uses_its_existing_client( - monkeypatch: pytest.MonkeyPatch, -) -> None: - revoke = AsyncMock() - factory = Mock(return_value=SimpleNamespace(revoke=revoke)) - monkeypatch.setattr(restore.accounts, "client", factory) - account = restore.ConnectedAccount("org-one", "owner-one", "gdrive", CONNECTION) - await restore.accounts._revoke(account, credential="fixture-native-credential") - factory.assert_called_once_with("gdrive") - revoke.assert_awaited_once() - assert revoke.await_args.args == ("fixture-native-credential",) - assert revoke.await_args.kwargs["refresh"] is True + source = _owner_source(owner, "c") + if kind != SLOT: + source = replace(source, kind=kind, credential_mode="connected", connection_slot="") + state.history[owner] = [source] + await restore.accounts.stop_subjects([owner[1]], erase_owner=True) + assert not state.rows and not state.history and not state.held + assert state.fences[restore.accounts._fence_key(CONNECTION)].split("/")[1][0] == "0" + assert state.events == [(event, owner) for event in ("fence", "marker", "retire", "erase")] + state.unseal.assert_not_called() + state.http.assert_not_called() @pytest.fixture @@ -331,13 +329,69 @@ async def keys(*, owner: Any = None, **kwargs: Any) -> list[Any]: monkeypatch.setattr( accounts.revocation, "cutoffs", AsyncMock(side_effect=lambda *a, **k: state.cutoffs) ) - monkeypatch.setattr(accounts, "unseal", Mock(side_effect=AssertionError("unseal not required"))) - monkeypatch.setattr(restore, "unseal", Mock(side_effect=AssertionError("unseal not required"))) - monkeypatch.setattr(accounts, "_revoke", AsyncMock()) + state.unseal = Mock(side_effect=AssertionError("credential decryption forbidden")) + state.http = AsyncMock(side_effect=AssertionError("legacy HTTP execution forbidden")) + monkeypatch.setattr("server.core.secrets_at_rest.unseal", state.unseal) + monkeypatch.setattr("httpx.AsyncClient.send", state.http) _wire_owner_history_writes(monkeypatch, state) return state +@pytest.mark.asyncio +async def test_offline_restore_erases_legacy_history_without_remote_revocation( + owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + state = owner_history + owner = (*OWNER[:2], "gdrive") + state.rows[owner] = restore.ConnectedAccount( + *owner, CONNECTION, active=True, credential_enc=_OpaqueCredential("retained-envelope") + ) + state.history[owner] = [ + replace( + _owner_source(owner, "c"), + kind="gdrive", + credential_mode="connected", + connection_slot="", + ) + ] + metadata = restore._metadata + + async def inventory(ch: Any, selected: Any = None) -> Any: + return await metadata(ch, owner if selected is None else selected) + + async def check_census(*, ch: Any) -> None: + assert ch is state + assert not state.rows and not state.history and not state.held + + census = AsyncMock(side_effect=check_census) + monkeypatch.setattr(restore, "_metadata", inventory) + monkeypatch.setattr(restore.ch_module, "get_client", lambda: state) + monkeypatch.setattr(restore, "offline_refusal", AsyncMock(return_value="")) + monkeypatch.setattr(restore, "require_restore_erased", census) + await restore.restore_all(apply=True, ch=state) + assert not state.rows and not state.history and not state.held + census.assert_awaited_once_with(ch=state) + state.http.assert_not_called() + state.unseal.assert_not_called() + + +@pytest.mark.asyncio +async def test_server_installs_generic_owner_erasure_lifecycle( + owner_history: SimpleNamespace, +) -> None: + from server import main + from server.auth import account_lifecycle + + assert main.app is not None + assert account_lifecycle._stopper is restore.accounts.stop_subjects + owner_history.history[OWNER] = [_owner_source(OWNER, "c")] + await account_lifecycle.stop_connections([OWNER[1]], erase_owner=True) + assert not owner_history.history and not owner_history.rows + assert ("erase", OWNER) in owner_history.events + owner_history.http.assert_not_called() + owner_history.unseal.assert_not_called() + + def _wire_owner_history_writes(monkeypatch: pytest.MonkeyPatch, state: SimpleNamespace) -> None: async def fence_get(ch: Any, key: str) -> str | None: assert ch is state @@ -419,8 +473,8 @@ async def test_owner_erasure_discovers_source_only_history_without_accounts( selected = set(owners) - set(retained) assert {owner for event, owner in state.events if event == "erase"} == selected assert not state.rows and len(state.fences) == len(selected) - restore.unseal.assert_not_called() - restore.accounts.unseal.assert_not_called() + state.unseal.assert_not_called() + state.http.assert_not_called() @pytest.mark.asyncio @@ -522,8 +576,8 @@ async def interrupted(account: Any, *, keep_marker: bool) -> None: @pytest.mark.asyncio -async def test_owner_erasure_revokes_only_after_all_local_history_is_retired( - owner_history: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +async def test_owner_erasure_finishes_all_local_history_without_remote_revocation( + owner_history: SimpleNamespace, ) -> None: state = owner_history native = (OWNER[0], OWNER[1], "gdrive") @@ -540,15 +594,11 @@ async def test_owner_erasure_revokes_only_after_all_local_history_is_retired( ) ], } - revoked = [] - - async def revoke(account: Any, **kwargs: Any) -> None: - assert not state.history and not state.rows and not state.held - revoked.append((account.org, account.subject, account.kind)) - - monkeypatch.setattr(restore.accounts, "_revoke", revoke) await restore.accounts.stop_subjects([OWNER[1]], erase_owner=True, respect_cutoff=True) - assert set(revoked) == {OWNER, native} + assert not state.history and not state.rows and not state.held + assert {owner for event, owner in state.events if event == "erase"} == {OWNER, native} + state.http.assert_not_called() + state.unseal.assert_not_called() assert all( event != "erase" or ("retire", owner) in state.events for event, owner in state.events ) @@ -821,4 +871,6 @@ async def test_retry_budget_retains_admitted_registration_workset( assert ( state.fences[restore.accounts._fence_key(marker.connection_id)] == proof.connection_id ) - assert not await restore.accounts.available(marker) + assert not await restore.accounts._fence_current(marker) + with pytest.raises(restore.accounts.OwnerUnavailable): + await restore.accounts._require_source_fence(marker) diff --git a/tests/unit/test_mcp_connections.py b/tests/unit/test_mcp_connections.py index a9fdc46be5..235b72556b 100644 --- a/tests/unit/test_mcp_connections.py +++ b/tests/unit/test_mcp_connections.py @@ -185,7 +185,7 @@ async def claim_swap( return self.fences.get(key) async def ready(self, ch: Any, migration: int) -> bool: - assert ch is self.ch and migration == 116 + assert ch is self.ch and migration == 117 return self.fleet async def canonical(self, org: str, owner: str) -> str: diff --git a/tests/unit/test_mcp_profile_api.py b/tests/unit/test_mcp_profile_api.py index af9df28681..798823e8b8 100644 --- a/tests/unit/test_mcp_profile_api.py +++ b/tests/unit/test_mcp_profile_api.py @@ -65,12 +65,10 @@ def auth(subject: str = "person-a", org: str = "org-a", **changes: Any) -> AuthI @pytest.fixture def world(monkeypatch: pytest.MonkeyPatch) -> Iterator[SimpleNamespace]: - fake = SimpleNamespace( - knowledge_source_mcp_profiles_json="", - knowledge_source_self_service_enabled=True, - jwt_secret="unit-profile-cursor-key", - auth_actually_required=lambda: True, - ) + fake = SimpleNamespace(**KnowledgeSettings().model_dump()) + fake.knowledge_source_self_service_enabled = True + fake.jwt_secret = "unit-profile-cursor-key" + fake.auth_actually_required = lambda: True state = SimpleNamespace(settings=fake, active=True, managed_denial=False, revoked={}, seen=[]) def refuse(*args: Any, **kwargs: Any) -> Any: diff --git a/tests/unit/test_mcp_source_browse.py b/tests/unit/test_mcp_source_browse.py new file mode 100644 index 0000000000..3c97801fed --- /dev/null +++ b/tests/unit/test_mcp_source_browse.py @@ -0,0 +1,237 @@ +"""Owner-bound metadata uses real SDK sessions without importing or reading bodies.""" + +import asyncio +import json +from dataclasses import replace +from unittest.mock import AsyncMock + +import pytest +from mcp import types +from pydantic import ValidationError as ModelError + +from server.auth.context import current_auth_var +from server.core import request_tail +from server.core.diagnostics import codes_only, public_diagnostics +from server.core.errors import ValidationError +from server.knowledge.api.models_mcp_connections import MCPBrowseInput +from server.knowledge.app import mcp_browse as browse +from server.knowledge.app import mcp_connections, mcp_profiles +from server.knowledge.app import mcp_source_authority as authority +from tests.unit.test_mcp_source_live import live_setup as live_setup +from tests.unit.test_mcp_source_live import live_tools as live_tools +from tests.unit.test_mcp_source_live_read import protected as protected +from tests.unit.test_mcp_source_read_policy import reader as reader +from tests.unit.test_mcp_source_sync import RESOURCE, SECOND +from tests.unit.test_mcp_source_sync import harness as harness +from tests.unit.test_mcp_source_sync import upstream as upstream + + +@pytest.fixture +def browse_remote(protected, upstream, monkeypatch): + # Keep the approved profile builder and official SDK; replace only its network transport. + monkeypatch.setattr( + mcp_connections, "build_mcp_source_client", authority.build_mcp_source_client + ) + return protected + + +def browse_input(h, **changes): + values = {"org": "org", "slot": h.account.kind, "mode": "resources"} + return MCPBrowseInput(**(values | changes)) + + +@pytest.mark.asyncio +async def test_resources_browse_returns_only_metadata_and_stable_hints(browse_remote): + h = browse_remote.h + result = await browse_remote.request.call(browse.handle_mcp_browse, browse_input(h)) + again = await browse_remote.request.call(browse.handle_mcp_browse, browse_input(h)) + assert result.supported and result.resources and result.complete and not result.truncated + assert len(result.items) == 4 + assert [(r.id, r.uri) for r in result.items] == [(r.id, r.uri) for r in again.items] + assert all(item.uri.startswith("mcp-resource-hint:") for item in result.items) + assert all(set(item.model_dump()) == {"id", "title", "uri"} for item in result.items) + assert not h.reads and not h.originals and not h.doc_rows + assert browse_remote.request.marked + browse_remote.imports.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_remote_next_cursor_is_never_returned_or_reused(browse_remote, upstream): + seen = [] + + @upstream._mcp_server.list_resources() + async def listed(request: types.ListResourcesRequest): + assert codes_only() and not public_diagnostics() + seen.append(request.params.cursor if request.params else None) + return types.ListResourcesResult( + resources=[types.Resource(uri=RESOURCE, name="private title")], + nextCursor="private-session-token", + ) + + for _ in range(2): + result = await browse_remote.request.call( + browse.handle_mcp_browse, browse_input(browse_remote.h) + ) + assert not result.complete and result.truncated and result.reason == "first_window_only" + assert "private-session-token" not in result.model_dump_json() + assert "cursor" not in result.model_dump() + assert seen == [None, None] and not browse_remote.h.reads + + +@pytest.mark.asyncio +async def test_each_browse_restarts_without_reusing_a_changed_page(browse_remote, upstream): + identities = iter((RESOURCE, SECOND)) + + @upstream._mcp_server.list_resources() + async def listed(): + return types.ListResourcesResult( + resources=[types.Resource(uri=next(identities), name="private title")], + nextCursor="session cursor", + ) + + results = [ + await browse_remote.request.call(browse.handle_mcp_browse, browse_input(browse_remote.h)) + for _ in range(2) + ] + assert [result.items[0].id for result in results] == [RESOURCE, SECOND] + assert all(not result.complete and result.reason == "first_window_only" for result in results) + + +@pytest.mark.asyncio +async def test_oversized_remote_page_cannot_publish_partial_metadata(browse_remote, upstream): + @upstream._mcp_server.list_resources() + async def listed(): + return [types.Resource(uri=f"selected://document/{i}", name="title") for i in range(101)] + + with pytest.raises(ValidationError): + await browse_remote.request.call(browse.handle_mcp_browse, browse_input(browse_remote.h)) + assert not browse_remote.request.messages and not browse_remote.h.reads + + +@pytest.mark.asyncio +async def test_local_limit_marks_the_window_truncated(browse_remote): + result = await browse_remote.request.call( + browse.handle_mcp_browse, browse_input(browse_remote.h, limit=1) + ) + assert len(result.items) == 1 and result.truncated and not result.complete + assert result.reason == "result_limit" and result.manual_resource_ids_supported + + +@pytest.mark.asyncio +async def test_unmapped_search_is_truthfully_unsupported(browse_remote): + result = await browse_remote.request.call( + browse.handle_mcp_browse, + browse_input(browse_remote.h, mode="search", query="selected"), + ) + assert not result.supported and not result.complete and not result.items + assert result.resources is None and not result.capabilities_checked + assert result.reason == "unsupported_mode" + assert not browse_remote.h.reads + + +@pytest.mark.asyncio +async def test_explicit_mapped_search_drops_remote_body_and_uri(browse_remote, live_tools): + result = await browse_remote.request.call( + browse.handle_mcp_browse, + browse_input(browse_remote.h, mode="search", query="selected"), + ) + assert result.supported and result.mapped_search + assert {item.id for item in result.items} == {RESOURCE, SECOND} + assert not result.complete and result.truncated + assert result.reason == "search_completeness_unavailable" + assert "Search is not a read" not in result.model_dump_json() + assert "https://untrusted.example" not in result.model_dump_json() + assert not browse_remote.h.reads and not browse_remote.h.doc_rows + + +@pytest.mark.asyncio +async def test_schema_drift_refuses_mapped_search(browse_remote, live_tools): + live_tools.schema = {**live_tools.schema, "description": "schema drift"} + with pytest.raises(ValidationError): + await browse_remote.request.call( + browse.handle_mcp_browse, + browse_input(browse_remote.h, mode="search", query="selected"), + ) + assert not browse_remote.request.messages and not browse_remote.h.reads + assert not browse_remote.h.account.active + + +@pytest.mark.asyncio +@pytest.mark.parametrize("changed", ["owner", "generation", "profile", "fence", "protected"]) +async def test_foreign_or_stale_connection_never_publishes(browse_remote, monkeypatch, changed): + h = browse_remote.h + if changed == "owner": + current_auth_var.set(replace(browse_remote.auth, subject="other")) + elif changed == "generation": + h.account = replace(h.account, connection_id="a" * 32 + "/1" + "c" * 31) + elif changed == "profile": + monkeypatch.setattr( + mcp_connections, "load_mcp_profile_catalog", lambda: mcp_profiles.MCPProfileCatalog() + ) + elif changed == "fence": + monkeypatch.setattr(authority.accounts, "_fence_current", AsyncMock(return_value=False)) + with pytest.raises(ValidationError): + await browse_remote.request.call( + browse.handle_mcp_browse, browse_input(h), protected=changed != "protected" + ) + assert not browse_remote.request.messages and not h.reads + + +@pytest.mark.asyncio +async def test_revocation_after_listing_blocks_actual_publication(browse_remote): + async def revoke(): + browse_remote.h.account = replace(browse_remote.h.account, active=False) + + with pytest.raises(request_tail.RequiredTailError): + await browse_remote.request.call( + browse.handle_mcp_browse, browse_input(browse_remote.h), before_send=revoke + ) + assert not browse_remote.request.messages + + +@pytest.mark.asyncio +async def test_cancelled_listing_drains_the_owned_server_task(browse_remote, upstream): + started, stopped = asyncio.Event(), asyncio.Event() + + @upstream._mcp_server.list_resources() + async def blocked(): + started.set() + try: + await asyncio.Event().wait() + finally: + stopped.set() + return [] + + task = asyncio.create_task( + browse_remote.request.call(browse.handle_mcp_browse, browse_input(browse_remote.h)) + ) + try: + async with asyncio.timeout(5): + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await stopped.wait() + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert not browse_remote.request.messages and not browse_remote.h.reads + + +@pytest.mark.parametrize("extra", ["cursor", "namespace", "endpoint", "tool", "fixed_arguments"]) +def test_browse_cannot_accept_continuations_or_authority_overrides(extra): + private = "private cursor or query" + with pytest.raises(ModelError) as error: + MCPBrowseInput(org="org", slot="mcp:" + "a" * 32, mode="resources", **{extra: private}) + assert private not in json.dumps(error.value.errors(), default=str) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode,query", [("resources", "private query"), ("search", " ")]) +async def test_mode_must_match_the_explicit_query(browse_remote, mode, query): + with pytest.raises(ValidationError, match="MCP_BROWSE_QUERY_INVALID"): + await browse_remote.request.call( + browse.handle_mcp_browse, browse_input(browse_remote.h, mode=mode, query=query) + ) + assert not browse_remote.request.messages and not browse_remote.h.reads diff --git a/tests/unit/test_mcp_source_live.py b/tests/unit/test_mcp_source_live.py index 849ae1f029..34e60b8879 100644 --- a/tests/unit/test_mcp_source_live.py +++ b/tests/unit/test_mcp_source_live.py @@ -141,6 +141,7 @@ async def test_live_result_loses_publication_when_the_resource_changes(live_tool live_tools.h.text = "Changed after retrieval" with pytest.raises(MCPSourceError): await result.check() + assert live_tools.h.account.active @pytest.mark.asyncio @@ -149,6 +150,7 @@ async def test_live_revalidation_detects_schema_drift(live_tools): live_tools.schema = {**SEARCH_OUTPUT, "description": "Changed contract"} with pytest.raises(MCPSourceError): await result.check() + assert not live_tools.h.account.active @pytest.mark.asyncio diff --git a/tests/unit/test_mcp_source_live_read.py b/tests/unit/test_mcp_source_live_read.py new file mode 100644 index 0000000000..ad084d5937 --- /dev/null +++ b/tests/unit/test_mcp_source_live_read.py @@ -0,0 +1,266 @@ +"""Official SDK reads and real publication tails; storage and identity are unit seams.""" + +import asyncio +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass, field, replace +from types import SimpleNamespace +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from server.auth.context import current_auth_var +from server.auth.session_protection import request_declaration +from server.clients import mcp_source as client_module +from server.clients.mcp_source import MCPSourceError +from server.core import request_tail, request_work +from server.core.ch_names import qualify +from server.core.errors import ValidationError +from server.knowledge.api.models_mcp_reads import MCPReadInput +from server.knowledge.app import mcp_browse as browse +from server.knowledge.app import mcp_connections, session_admission, writes +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.store import mirror_latch +from tests.unit.test_mcp_source_read_policy import reader as reader +from tests.unit.test_mcp_source_sync import JSON_TEXT, RESOURCE, SECOND +from tests.unit.test_mcp_source_sync import harness as harness +from tests.unit.test_mcp_source_sync import upstream as upstream + + +class LatchStore: + """Only fake DB responses; session admission and latch verification execute.""" + + @asynccontextmanager + async def coordination_session(self) -> AsyncIterator[None]: + yield + + async def execute(self, *args: Any) -> None: + pass + + async def query_one(self, *args: Any) -> dict[str, Any]: + return { + "server_id": "00000000-0000-4000-8000-000000000001", + "enabled": 1, + "engines": [ + ( + "knowledge_mirror_latch", + qualify("KeeperMap('/loom/knowledge_mirror_latch') PRIMARY KEY id"), + ), + ("_migration_lock", qualify("KeeperMap('/loom/migration_lock') PRIMARY KEY name")), + ], + } + + +@dataclass +class Request: + messages: list[dict[str, Any]] = field(default_factory=list) + marked: bool = False + + async def call(self, handler, input, *, protected=True, before_send=None): + scope = { + "type": "http", + "headers": [(b"x-loom-session-protection", b"v1")] if protected else [], + } + result = None + + async def app(scope, receive, send): + nonlocal result + with request_declaration(scope), request_work.bind(request_work.RequestWork()): + result = await handler(input) + self.marked = request_work.http_mirror_marked(scope) + if before_send is not None: + await before_send() + await send({"type": "http.response.start", "status": 200, "headers": []}) + await send( + {"type": "http.response.body", "body": result.model_dump_json().encode()} + ) + + async def receive(): + return {"type": "http.disconnect"} + + async def send(message): + self.messages.append(message) + + with request_work.http_owner(scope): + try: + await request_tail.RequestTailMiddleware(app)(scope, receive, send) + except ValidationError as error: + if isinstance(error.__context__, MCPSourceError): + error.add_note("Fixed client refusal: " + error.__context__.code) + raise + return result + + +@pytest.fixture +def protected(reader, harness, monkeypatch): + enabled = SimpleNamespace( + auth_actually_required=lambda: True, + knowledge_mirrored_sources_enabled=True, + knowledge_live_search_timeout_s=10, + ) + monkeypatch.setattr(browse, "settings", enabled) + monkeypatch.setattr(session_admission, "settings", enabled) + monkeypatch.setattr(mirror_latch, "get_client", LatchStore) + monkeypatch.setattr( + mcp_connections.accounts, + "resolve_reader", + AsyncMock( + side_effect=lambda org, subject: SimpleNamespace(subject=subject, emails=frozenset()) + ), + ) + forbidden = AsyncMock(side_effect=AssertionError("live reads cannot import")) + monkeypatch.setattr(writes, "handle_knowledge_upsert", forbidden) + harness.select(mode="live") + return SimpleNamespace(h=harness, auth=reader.auth, request=Request(), imports=forbidden) + + +def read_input(**changes): + values = dict(org="org", namespace="collection", name="selected", resource_id=RESOURCE) + return MCPReadInput(**(values | changes)) + + +@pytest.mark.asyncio +async def test_resource_only_read_is_full_selected_and_protected(protected, upstream): + h = protected.h + h.text = "Full selected content. " * 50 + result = await protected.request.call(browse.handle_mcp_read, read_input()) + assert result.text == h.text and len(result.text) > 200 + assert result.source_id == h.source.source_id + assert result.uri == resource_uri(h.source.source_id, RESOURCE) + assert result.resource_identity_verified and result.mime_type == "text/plain" + assert not result.remote_identity_verified and not result.upstream_acl_verified + assert protected.request.marked and len(protected.request.messages) == 2 + assert len(h.reads) >= 4 and set(h.reads) == {RESOURCE} + assert not h.doc_rows and not h.chunk_rows and not h.originals + protected.imports.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("harness", ["tool", "text"], indirect=True) +async def test_explicit_mapped_reads_keep_receipt_identity_truthful(protected, upstream, harness): + result = await protected.request.call(browse.handle_mcp_read, read_input()) + plain = harness.reads[0] == "tool:" + RESOURCE and result.text.startswith("Plain") + assert result.resource_identity_verified is not plain + assert result.uri == resource_uri(harness.source.source_id, RESOURCE) + assert set(harness.reads) == {"tool:" + RESOURCE} + protected.imports.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_unprotected_read_refuses_before_any_remote_read(protected, upstream): + with pytest.raises(ValidationError, match="MCP_PROTECTED_SESSION_REQUIRED"): + await protected.request.call(browse.handle_mcp_read, read_input(), protected=False) + assert not protected.h.reads and not protected.request.messages + client_module.pinned_target.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_live_read_keeps_declared_text_mime(protected, upstream): + protected.h.select(mode="live", resources=(JSON_TEXT,)) + result = await protected.request.call(browse.handle_mcp_read, read_input(resource_id=JSON_TEXT)) + assert result.mime_type == "application/json" + assert result.text == '{"selected": "text"}' + assert result.uri == resource_uri(protected.h.source.source_id, JSON_TEXT) + + +@pytest.mark.asyncio +async def test_missing_durable_session_protection_refuses_before_network( + protected, upstream, monkeypatch +): + original = LatchStore.query_one + + async def unlatched(self, *args): + return {**await original(self, *args), "enabled": 0} + + monkeypatch.setattr(LatchStore, "query_one", unlatched) + with pytest.raises(ValidationError): + await protected.request.call(browse.handle_mcp_read, read_input()) + client_module.pinned_target.assert_not_awaited() + assert not protected.h.reads and not protected.request.messages + + +@pytest.mark.asyncio +@pytest.mark.parametrize("changed", ["owner", "namespace", "unselected", "snapshot", "revoked"]) +async def test_wrong_reader_or_scope_refuses_before_read(protected, upstream, monkeypatch, changed): + values = read_input().model_dump() + if changed == "owner": + current_auth_var.set(replace(protected.auth, subject="other")) + elif changed == "namespace": + values["namespace"] = "other" + elif changed == "unselected": + values["resource_id"] = SECOND + elif changed == "snapshot": + protected.h.select(mode="snapshot") + else: + monkeypatch.setattr(authority.accounts, "_fence_current", AsyncMock(return_value=False)) + with pytest.raises(ValidationError): + await protected.request.call(browse.handle_mcp_read, MCPReadInput(**values)) + assert not protected.h.reads and not protected.request.messages + + +@pytest.mark.asyncio +@pytest.mark.parametrize("changed", ["body", "source", "grant", "connection"]) +async def test_publication_rechecks_current_body_and_authority( + protected, upstream, monkeypatch, changed +): + async def change(): + if changed == "body": + protected.h.text = "changed after handler" + elif changed == "source": + protected.h.source = replace(protected.h.source, active=False) + elif changed == "grant": + monkeypatch.setattr(authority.authz, "row_in_scope", AsyncMock(return_value=False)) + else: + protected.h.account = replace(protected.h.account, active=False) + + with pytest.raises(request_tail.RequiredTailError): + await protected.request.call(browse.handle_mcp_read, read_input(), before_send=change) + assert not protected.request.messages + protected.imports.assert_not_awaited() + + +@pytest.mark.asyncio +async def test_cancelled_read_drains_owned_asgi_work(protected, upstream): + started, stopped = asyncio.Event(), asyncio.Event() + + @upstream._mcp_server.read_resource() + async def blocked(uri): + started.set() + try: + await asyncio.Event().wait() + finally: + stopped.set() + return [] + + task = asyncio.create_task(protected.request.call(browse.handle_mcp_read, read_input())) + try: + async with asyncio.timeout(5): + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await stopped.wait() + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + assert not protected.request.messages and not protected.h.doc_rows + + +@pytest.mark.parametrize("extra", ["endpoint", "source_id", "slot", "uri", "tool"]) +def test_read_validation_does_not_echo_private_inputs(extra): + from pydantic import ValidationError as ModelError + + secret = "private selected identity" + with pytest.raises(ModelError) as error: + MCPReadInput( + org="org", + namespace="collection", + name="selected", + resource_id=secret, + **{extra: "private override"}, + ) + assert secret not in json.dumps(error.value.errors(), default=str) diff --git a/tests/unit/test_mcp_source_profiles.py b/tests/unit/test_mcp_source_profiles.py index cc1f9c903d..d10d3059a5 100644 --- a/tests/unit/test_mcp_source_profiles.py +++ b/tests/unit/test_mcp_source_profiles.py @@ -15,7 +15,6 @@ from server.clients.mcp_source import MCPLimits, MCPSourceClient, MCPToolMapping from server.knowledge.app import mcp_profiles from server.knowledge.app.mcp_profiles import ( - MAX_CATALOG_BYTES, MCPProfileCatalog, MCPProfileError, build_mcp_source_client, @@ -201,7 +200,7 @@ def test_page_arguments_are_bounded(changes: dict[str, Any]) -> None: '{"version":1,"profiles":[],"x":NaN}', '{"version":1,"profiles":[{"id":"secret","id":"other"}]}', b"\xff", - b" " * (MAX_CATALOG_BYTES + 1), + b" " * (mcp_profiles.settings.knowledge_source_mcp_catalog_max_bytes + 1), ], ) def test_invalid_catalog_errors_never_echo_payload(payload: str | bytes) -> None: @@ -585,3 +584,40 @@ def test_oversized_selection_refuses_through_real_client_limits() -> None: ) with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): client(profile, contract=two) + + +@pytest.mark.parametrize( + ("field", "limit"), + [ + ("knowledge_source_mcp_catalog_max_bytes", 1024), + ("knowledge_source_mcp_catalog_max_profiles", 1), + ("knowledge_source_mcp_profile_max_bytes", 1024), + ("knowledge_source_mcp_schema_max_bytes", 128), + ("knowledge_source_mcp_profile_max_nodes", 16), + ("knowledge_source_mcp_profile_max_depth", 3), + ], +) +def test_actual_operator_bound_refuses_an_otherwise_valid_catalog( + monkeypatch: pytest.MonkeyPatch, field: str, limit: int +) -> None: + mapping = tool_mapping() + mapping["input_schema"]["description"] = "x" * 1024 + configured = row( + config={"endpoint": ENDPOINT, "approved_tools": ["read_document"], "read": mapping} + ) + payload = json.dumps({"version": 1, "profiles": [configured, row("second")]}) + assert MCPProfileCatalog.parse(payload).get("org-a", "approved") + monkeypatch.setattr(mcp_profiles.settings, field, limit) + with pytest.raises(MCPProfileError, match="^MCP_PROFILE_INVALID$"): + MCPProfileCatalog.parse(payload) + + +def test_cached_approval_cannot_ignore_changed_operator_bounds( + monkeypatch: pytest.MonkeyPatch, +) -> None: + payload = json.dumps({"version": 1, "profiles": [row("first"), row("second")]}) + monkeypatch.setattr(mcp_profiles.settings, "knowledge_source_mcp_profiles_json", payload) + assert mcp_profiles.load_mcp_profile_catalog().get("org-a", "second") + monkeypatch.setattr(mcp_profiles.settings, "knowledge_source_mcp_catalog_max_profiles", 1) + with pytest.raises(MCPProfileError): + mcp_profiles.load_mcp_profile_catalog() diff --git a/tests/unit/test_mcp_source_schedule.py b/tests/unit/test_mcp_source_schedule.py new file mode 100644 index 0000000000..a157475e03 --- /dev/null +++ b/tests/unit/test_mcp_source_schedule.py @@ -0,0 +1,402 @@ +"""Finite scheduler tests without stores, clients or source-engine substitution claims.""" + +from __future__ import annotations + +import asyncio +import time +from collections import Counter +from dataclasses import dataclass, replace + +import pytest + +from server.knowledge.app import mcp_source_schedule as schedule +from server.knowledge.store.mcp_source_schedule import Header, QueryLimits, candidate_page + + +@dataclass +class Budget: + left: int + + +LIMITS = schedule.Limits(4, 20, 8, 4, 2, 1, 2, 1) + + +def header(index: int, org: str = "org") -> Header: + return Header( + org, "ns", str(index), "random-" + str(index), "profile", "a" * 64, f"{index:064X}" + ) + + +@pytest.fixture +def cursors(monkeypatch: pytest.MonkeyPatch) -> list[str]: + values: list[str] = [] + monkeypatch.setattr(schedule.pass_context, "resume_cursor", lambda: "") + monkeypatch.setattr(schedule.pass_context, "set_cursor", values.append) + monkeypatch.setattr(schedule.pass_context, "check_stop", lambda: None) + return values + + +def page_of(rows: list[Header]): + async def page(after: str, size: int) -> list[Header]: + return [row for row in rows if row.schedule_key > after][:size] + + return page + + +async def run(rows: list[Header], execute, *, parent: Budget | None = None, limits=LIMITS): + return await schedule.dispatch( + limits=limits, + parent=parent or Budget(100), + make_pass=Budget, + execute=execute, + endpoint_key=lambda row: row.name, + deadline=time.monotonic() + 5, + page=page_of(rows), + resume_cursor=schedule.pass_context.resume_cursor(), + checkpoint=schedule.pass_context.set_cursor, + ) + + +@pytest.mark.asyncio +async def test_reserves_before_task_start_and_refunds_unused(cursors): + parent = Budget(5) + current = peak = consumed = 0 + + async def execute(row, budget): + nonlocal current, peak, consumed + current += budget.left + peak = max(peak, current) + assert current + parent.left <= 5 + reserved = budget.left + await asyncio.sleep(0) + budget.left -= 1 + consumed += 1 + current -= reserved + + metrics = await run([header(i, str(i % 3)) for i in range(1, 10)], execute, parent=parent) + assert peak <= 5 + assert consumed == 5 and parent.left == 0 + assert metrics.started == 5 + assert metrics.deferred > 0 + + +@pytest.mark.asyncio +async def test_round_robin_and_endpoint_caps(cursors): + starts: list[str] = [] + active: Counter[str] = Counter() + endpoints: Counter[str] = Counter() + gate = asyncio.Event() + + async def execute(row, budget): + endpoint = "shared" if int(row.name) <= 6 else row.name + starts.append(row.org) + active[row.org] += 1 + endpoints[endpoint] += 1 + assert active[row.org] <= 2 and endpoints[endpoint] <= 1 + if len(starts) >= 3: + gate.set() + await gate.wait() + budget.left -= 1 + active[row.org] -= 1 + endpoints[endpoint] -= 1 + + rows = [header(i, "faulty") for i in range(1, 7)] + [header(7, "healthy"), header(8, "third")] + metrics = await schedule.dispatch( + limits=replace(LIMITS, page_size=8), + parent=Budget(100), + make_pass=Budget, + execute=execute, + endpoint_key=lambda row: "shared" if int(row.name) <= 6 else row.name, + deadline=time.monotonic() + 5, + page=page_of(rows), + resume_cursor=schedule.pass_context.resume_cursor(), + checkpoint=schedule.pass_context.set_cursor, + ) + assert starts[:3] == ["faulty", "healthy", "third"] + assert metrics.completed == 8 + assert metrics.queue_highwater <= 8 and metrics.inflight_highwater <= 4 + assert metrics.endpoint_highwater == 1 + + +@pytest.mark.asyncio +async def test_failed_busy_sources_do_not_pin_scan_cursor(cursors): + seen: list[str] = [] + + async def execute(row, budget): + seen.append(row.org) + if row.org == "faulty": + raise ValueError("private detail must not escape") + budget.left -= 1 + + metrics = await run([header(1, "faulty"), header(2, "healthy")], execute) + assert metrics.failed == 1 and metrics.completed == 1 + assert seen == ["faulty", "healthy"] + assert cursors[-1] == "mcp1:" + "0" * 64 + assert all("faulty" not in value and "healthy" not in value for value in cursors) + assert "private" not in repr(metrics) + + +@pytest.mark.asyncio +async def test_cancellation_joins_and_returns_remaining_credits(cursors): + parent, started, closed = Budget(4), asyncio.Event(), asyncio.Event() + + async def execute(row, budget): + budget.left -= 1 + started.set() + try: + await asyncio.Event().wait() + finally: + closed.set() + + task = asyncio.create_task(run([header(1)], execute, parent=parent)) + await started.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert task.done() and closed.is_set() + assert parent.left == 3 + + +@pytest.mark.asyncio +async def test_counter_inflation_fails_closed(cursors): + parent = Budget(4) + + async def execute(row, budget): + budget.left += 1 + + with pytest.raises(ValueError, match="mcp_schedule_budget"): + await run([header(1)], execute, parent=parent) + assert parent.left == 2 + + +@pytest.mark.asyncio +async def test_store_page_has_no_body_and_has_physical_query_bounds(): + class Store: + async def query_all(self, sql, params, *, settings): + assert ( + "items_json" not in sql and "credential_enc" not in sql and "secret_enc" not in sql + ) + assert "source_kind = 'mcp'" in sql and "source_contract_version = 1" in sql + assert "'snapshot', 'selected_refresh'" in sql and "'paused'" in sql + assert "LIMIT {limit:UInt64}" in sql + assert params["org"] == "tenant" and params["ns"] == "collection" + assert settings == { + "max_rows_to_read": 1000, + "max_bytes_to_read": 100000, + "max_execution_time": 1, + "read_overflow_mode": "throw", + } + return [vars(header(1, "tenant"))] + + rows = await candidate_page( + "", + 2, + query_limits=QueryLimits(1000, 100000, 1), + org="tenant", + namespace="collection", + ch=Store(), + ) + assert rows == [header(1, "tenant")] + + +@pytest.mark.asyncio +async def test_page_and_scope_validation(): + class Store: + async def query_all(self, sql, params, *, settings): + return [vars(header(2)), vars(header(1))] + + for kwargs in ( + {"limit": 0}, + {"limit": 1, "after": "raw tenant"}, + {"limit": 1, "namespace": "foreign"}, + {"limit": 1, "only": "name"}, + ): + with pytest.raises(ValueError): + await candidate_page( + **{"after": "", **kwargs}, query_limits=QueryLimits(10, 100, 1), ch=Store() + ) + with pytest.raises(ValueError, match="page_order"): + await candidate_page("", 2, query_limits=QueryLimits(10, 100, 1), ch=Store()) + + +@pytest.mark.asyncio +async def test_scan_window_and_restart_use_supervisor_cursor(cursors, monkeypatch): + monkeypatch.setattr(schedule.pass_context, "resume_cursor", lambda: "mcp1:" + f"{2:064X}") + seen = [] + + async def execute(row, budget): + seen.append(row.name) + budget.left -= 1 + + metrics = await run( + [header(i) for i in range(1, 20)], + execute, + limits=replace(LIMITS, page_size=2, scan_pages=1), + ) + assert seen == ["3", "4"] and metrics.pages == 1 and metrics.scanned == 2 + assert cursors[-1] == "mcp1:" + f"{4:064X}" + + +def test_limits_have_no_implicit_unbounded_mode(): + for field in ( + "page_size", + "scan_pages", + "ready", + "global_inflight", + "per_org", + "per_endpoint", + "documents", + "source_seconds", + ): + with pytest.raises(ValueError): + replace(LIMITS, **{field: 0}) + + +@pytest.mark.asyncio +async def test_small_pass_budget_does_not_skip_ready_tails(cursors, monkeypatch): + rows = [header(i, str(i % 3)) for i in range(1, 13)] + seen: set[str] = set() + + async def execute(row, budget): + seen.add(row.name) + budget.left -= 1 + + for _ in range(12): + resume = cursors[-1] if cursors else "" + monkeypatch.setattr(schedule.pass_context, "resume_cursor", lambda value=resume: value) + await run(rows, execute, parent=Budget(1)) + assert seen == {str(i) for i in range(1, 13)} + + +@pytest.mark.asyncio +async def test_task_context_keeps_private_namespace_out_of_global_status(cursors): + owner = schedule.pass_context.begin("knowledge_source_sync") + + async def execute(row, budget): + child = schedule.pass_context.current() + assert child is not owner and child.stopped is owner.stopped + schedule.pass_context.set_namespace("private-namespace") + budget.left -= 1 + + try: + await run([header(1)], execute) + assert owner.namespace == "" + assert schedule.pass_context.current() is owner + finally: + schedule.pass_context.clear() + + +@pytest.mark.asyncio +async def test_durable_wrapper_preserves_recording_cursor(cursors, monkeypatch): + persisted = {} + seen = [] + + async def resume(worker, *, timeout_s): + assert worker == schedule.PROGRESS_WORKER and timeout_s == 0.25 + return persisted.get(worker, "") + + async def record(worker, **fields): + assert fields["namespace"] == "" + persisted[worker] = fields["resume_cursor"] + return {"resume_cursor": fields["resume_cursor"]} + + async def execute(row, budget): + seen.append(row.name) + budget.left -= 1 + + monkeypatch.setattr(schedule.status_store, "resume_cursor", resume) + monkeypatch.setattr(schedule.status_store, "record_manual_pass", record) + owner = schedule.pass_context.begin("knowledge_source_sync") + owner.cursor = "recording-original" + try: + for _ in range(2): + await schedule.run_pass( + limits=LIMITS, + parent=Budget(1), + make_pass=Budget, + execute=execute, + endpoint_key=lambda row: row.name, + deadline=time.monotonic() + 5, + page=page_of([header(i) for i in range(1, 5)]), + progress_timeout=0.25, + ) + assert seen == ["1", "2"] + assert owner.cursor == "recording-original" + assert persisted[schedule.PROGRESS_WORKER] == "mcp1:" + f"{2:064X}" + finally: + schedule.pass_context.clear() + + +@pytest.mark.asyncio +async def test_shared_child_counter_is_rejected_before_parallel_use(cursors): + shared, parent = Budget(2), Budget(10) + + async def execute(row, budget): + pytest.fail("aliased budgets must never execute") + + with pytest.raises(ValueError, match="mcp_schedule_budget"): + await schedule.dispatch( + limits=LIMITS, + parent=parent, + make_pass=lambda credits: shared, + execute=execute, + endpoint_key=lambda row: row.name, + deadline=time.monotonic() + 5, + page=page_of([header(1), header(2)]), + resume_cursor="", + checkpoint=cursors.append, + ) + assert parent.left == 10 + + +@pytest.mark.asyncio +async def test_source_timeout_frees_capacity_for_healthy_work(cursors): + closed = asyncio.Event() + + async def execute(row, budget): + if row.name == "1": + try: + await asyncio.Event().wait() + finally: + closed.set() + else: + budget.left -= 1 + + metrics = await run( + [header(1), header(2, "healthy")], + execute, + limits=replace(LIMITS, global_inflight=1, source_seconds=0.001), + ) + assert closed.is_set() + assert metrics.timed_out == 1 and metrics.completed == 1 + + +@pytest.mark.asyncio +async def test_metadata_page_cannot_outlive_the_parent_pass(cursors): + cancelled = False + parent = Budget(4) + + async def page(after, size): + nonlocal cancelled + try: + await asyncio.Event().wait() + finally: + cancelled = True + + async def execute(row, budget): + pytest.fail("a hanging metadata page cannot admit a source") + + async with asyncio.timeout(0.3): + measured = await schedule.dispatch( + limits=LIMITS, + parent=parent, + make_pass=Budget, + execute=execute, + endpoint_key=lambda row: row.name, + deadline=time.monotonic() + 0.02, + page=page, + resume_cursor="", + checkpoint=cursors.append, + ) + assert measured.deadline_cut == 1 and measured.started == 0 + assert cancelled and parent.left == 4 diff --git a/tests/unit/test_mcp_source_schema_quarantine.py b/tests/unit/test_mcp_source_schema_quarantine.py new file mode 100644 index 0000000000..3ffdd8a025 --- /dev/null +++ b/tests/unit/test_mcp_source_schema_quarantine.py @@ -0,0 +1,94 @@ +"""Observed read-mapping drift cannot leave a connection's old copy proofs usable.""" + +from dataclasses import replace +from unittest.mock import AsyncMock + +import pytest +from mcp import types + +from server.core.errors import ValidationError +from server.knowledge.api.models_mcp_connections import MCPSlotInput +from server.knowledge.app import mcp_connections +from server.knowledge.app import mcp_source_authority as authority +from server.knowledge.app import mcp_source_sessions as sessions +from tests.unit.test_mcp_source_sync import RESOURCE, TOOL_INPUT, TOOL_OUTPUT, execute +from tests.unit.test_mcp_source_sync import harness as harness +from tests.unit.test_mcp_source_sync import storage as storage +from tests.unit.test_mcp_source_sync import upstream as upstream + + +@pytest.mark.asyncio +@pytest.mark.parametrize("harness", ["tool"], indirect=True) +async def test_observed_mapping_drift_quarantines_without_erasing_credentials_or_copies( + storage, upstream, monkeypatch +): + h = storage + h.select(mode="selected_refresh") + assert (await execute(h)).complete + before = h.account + written = [] + + async def put(account): + written.append(account) + h.account = account + + monkeypatch.setattr(authority.account_store, "put", put) + + @upstream._mcp_server.list_tools() + async def drifted(): + schema = {**TOOL_INPUT, "description": "Unapproved mapping revision"} + return [types.Tool(name="read_selected", inputSchema=schema, outputSchema=TOOL_OUTPUT)] + + result = await execute(h) + assert not result.complete and result.status != "ok" + assert len(written) == 1 and h.account == replace(before, active=False) + assert h.account.credential_enc == before.credential_enc + assert h.source.active and len(h.doc_rows) == len(h.originals) == 1 + assert h.reads == ["tool:" + RESOURCE] + with pytest.raises(authority.MCPAuthorityError): + await authority.validate_connection(h.source.org, h.source.owner_subject, h.contract) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "change", + [ + {"connection_id": "a" * 32 + "/0" + "d" * 31}, + {"active": False}, + {"org": "other"}, + {"subject": "other"}, + {"kind": "mcp:" + "f" * 32}, + ], +) +async def test_schema_quarantine_cannot_rewrite_a_changed_or_foreign_connection( + harness, monkeypatch, change +): + h = harness + bound = await authority.validate_source(h.source) + h.account = replace(h.account, **change) + put = AsyncMock() + monkeypatch.setattr(authority.account_store, "put", put) + await sessions.quarantine_mapping(bound.connection.account) + put.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("harness", ["tool"], indirect=True) +async def test_owner_discovery_schema_refusal_stops_the_exact_connection( + harness, upstream, monkeypatch +): + before = harness.account + monkeypatch.setattr(mcp_connections, "_owner", AsyncMock(return_value="owner")) + monkeypatch.setattr(mcp_connections, "_validate", AsyncMock()) + monkeypatch.setattr( + mcp_connections, "build_mcp_source_client", authority.build_mcp_source_client + ) + + @upstream._mcp_server.list_tools() + async def drifted(): + return [types.Tool(name="read_selected", inputSchema={"type": "object"})] + + with pytest.raises(ValidationError): + await mcp_connections.handle_mcp_discover(MCPSlotInput(org="org", slot=before.kind)) + assert harness.account == replace(before, active=False) + assert not harness.reads and not harness.doc_rows and not harness.originals diff --git a/tests/unit/test_mcp_source_sync.py b/tests/unit/test_mcp_source_sync.py index d712956d0e..bb0779a8de 100644 --- a/tests/unit/test_mcp_source_sync.py +++ b/tests/unit/test_mcp_source_sync.py @@ -227,6 +227,12 @@ def harness(monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest) -> monkeypatch.setattr(mcp_connections, "load_mcp_profile_catalog", lambda: catalog) monkeypatch.setattr(mcp_connections, "_ready", AsyncMock()) monkeypatch.setattr(authority.account_store, "get", AsyncMock(side_effect=lambda *a: h.account)) + + async def put_account(changed: ConnectedAccount) -> None: + assert changed == replace(h.account, active=False) + h.account = changed + + monkeypatch.setattr(authority.account_store, "put", put_account) monkeypatch.setattr( authority.source_store, "get_source", AsyncMock(side_effect=lambda *a: h.source) ) diff --git a/tests/unit/test_mcp_source_worker.py b/tests/unit/test_mcp_source_worker.py index 0453812267..c6896c67f8 100644 --- a/tests/unit/test_mcp_source_worker.py +++ b/tests/unit/test_mcp_source_worker.py @@ -10,16 +10,79 @@ import pytest from server.code.app.index.pass_budget import PassBudget +from server.knowledge.app import mcp_connections +from server.knowledge.app import mcp_source_worker as worker from server.knowledge.app import source_sync as sync from server.knowledge.app import source_sync_mcp as engine from server.knowledge.app.mcp_contracts import encode_source +from server.knowledge.app.mcp_profiles import MCPProfileCatalog from server.knowledge.domain.sources import mirror_synced, served +from server.knowledge.store.mcp_source_schedule import Header from tests.unit.test_mcp_source_sync import MIRROR, RESOURCE from tests.unit.test_mcp_source_sync import harness as harness from tests.unit.test_mcp_source_sync import storage as storage from tests.unit.test_mcp_source_sync import upstream as upstream +@pytest.mark.asyncio +@pytest.mark.parametrize("changed", [False, True]) +async def test_bounded_worker_lazily_runs_the_leased_engine_and_rejects_stale_profiles( + storage, upstream, monkeypatch, changed +): + h = storage + header = Header( + h.source.org, + h.source.namespace, + h.source.name, + h.source.source_id, + h.contract.profile_id, + "0" * 64 if changed else h.contract.profile_sha256, + "A" * 64, + ) + pages = [] + progress = {} + + async def page(after, limit, *, query_limits): + assert limit <= sync.settings.knowledge_source_mcp_schedule_page_size + assert query_limits == worker.query_limits() + pages.append(after) + return [] if after else [header] + + async def resume(name, **kwargs): + assert name == worker.scheduler.PROGRESS_WORKER + return progress.get("cursor", "") + + async def record(name, **kwargs): + assert name == worker.scheduler.PROGRESS_WORKER and kwargs["namespace"] == "" + progress["cursor"] = kwargs["resume_cursor"] + return SimpleNamespace() + + @asynccontextmanager + async def lease(name, **kwargs): + assert name == sync.turn_lease_name(h.source.org, h.source.namespace, h.source.name) + yield SimpleNamespace() + + monkeypatch.setattr(type(sync.settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr( + worker, "load_mcp_profile_catalog", mcp_connections.load_mcp_profile_catalog + ) + monkeypatch.setattr(worker.headers, "candidate_page", page) + monkeypatch.setattr(worker.scheduler.status_store, "resume_cursor", resume) + monkeypatch.setattr(worker.scheduler.status_store, "record_manual_pass", record) + monkeypatch.setattr(sync.store, "inactive_namespaces", AsyncMock(return_value=set())) + monkeypatch.setattr(sync.store, "read_states", AsyncMock(return_value={})) + monkeypatch.setattr(sync, "require_source_registry", AsyncMock()) + monkeypatch.setattr(sync.leases, "cluster_lease", lease) + monkeypatch.setattr(sync, "_write_state", AsyncMock()) + started = time.monotonic() + result = sync.PassResult() + await worker.run(PassBudget(started, started + 15), result) + assert pages == [""] and progress["cursor"].startswith("mcp1:") + assert result.sources == int(not changed) + assert bool(h.reads) == bool(h.doc_rows) == bool(h.originals) == (not changed) + assert result.private_work == (not changed) + + @pytest.mark.asyncio async def test_shared_worker_runs_actual_mcp_engine_as_private_work(storage, upstream, monkeypatch): h = storage @@ -103,3 +166,47 @@ async def write(org, namespace, key, *, state_value, detail): assert public[4]["mcp_selection"] == "scope" assert public[4]["requested_at"] == "request" assert set(public[4]) == {"mcp_selection", "requested_at", "full", "last_synced_at", "status"} + + +@pytest.mark.asyncio +async def test_failed_mcp_catalog_keeps_the_ordinary_recording_lane(harness, monkeypatch): + recording = replace( + harness.source, + kind="recording", + credential_mode="shared", + access="namespace", + source_contract_version=0, + generic_config_json="", + generic_items_json="", + config={"provider": "zoom", "ids": ["123456789"]}, + ) + monkeypatch.setattr(type(sync.settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr(sync.settings, "knowledge_mirrored_sources_enabled", True) + monkeypatch.setattr(worker, "run", AsyncMock(side_effect=ValueError("private config"))) + monkeypatch.setattr(sync.store, "all_active_sources", AsyncMock(return_value=[recording])) + monkeypatch.setattr(sync, "_retire_removed_sources", AsyncMock()) + monkeypatch.setattr(sync, "require_source_registry", AsyncMock()) + monkeypatch.setattr(sync, "_usable", AsyncMock(return_value=[recording])) + monkeypatch.setattr(sync, "_states", AsyncMock(return_value={})) + turn = AsyncMock(return_value=sync.TurnResult()) + monkeypatch.setattr(sync, "_sync_one", turn) + monkeypatch.setattr(sync, "_extract_pending", AsyncMock()) + monkeypatch.setattr(sync.pass_context, "resume_cursor", lambda: "") + monkeypatch.setattr(sync.pass_context, "set_cursor", lambda value: None) + monkeypatch.setattr(sync.pass_context, "note_failure", lambda *args: None) + result = await sync.run_sync() + assert turn.await_count == 1 and turn.await_args.args[0] == recording + assert result.private_work and result.failed == 1 and result.sources == 1 + assert result.errors == ["MCP_SCHEDULER_UNAVAILABLE"] + + +@pytest.mark.asyncio +async def test_unconfigured_mcp_lane_opens_no_scheduler_or_store(monkeypatch): + monkeypatch.setattr(worker, "load_mcp_profile_catalog", lambda: MCPProfileCatalog()) + dispatch = AsyncMock(side_effect=AssertionError("unconfigured lane opened storage")) + monkeypatch.setattr(worker.scheduler, "run_pass", dispatch) + started = time.monotonic() + result = sync.PassResult() + await worker.run(PassBudget(started, started + 1), result) + assert result == sync.PassResult() + dispatch.assert_not_awaited() diff --git a/tests/unit/test_native_source_retirement.py b/tests/unit/test_native_source_retirement.py new file mode 100644 index 0000000000..4161aa990e --- /dev/null +++ b/tests/unit/test_native_source_retirement.py @@ -0,0 +1,168 @@ +"""Legacy connection metadata can be fenced and erased without native execution.""" + +from contextlib import asynccontextmanager +from dataclasses import replace +from datetime import UTC, datetime +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import httpx +import pytest + +from server.auth.jwt import AuthInfo +from server.core.errors import AuthInsufficientError +from server.knowledge.app import connected_accounts as accounts +from server.knowledge.domain.connected_accounts import ConnectedAccount +from server.operations.base import Role + + +@pytest.fixture +def no_native_execution(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + httpx.AsyncClient, "send", AsyncMock(side_effect=AssertionError("provider HTTP forbidden")) + ) + monkeypatch.setattr( + accounts, "unseal", Mock(side_effect=AssertionError("credential decryption forbidden")) + ) + + +@pytest.mark.asyncio +async def test_personal_owner_is_canonical_and_checks_every_token_cutoff( + monkeypatch: pytest.MonkeyPatch, +) -> None: + auth = AuthInfo( + subject="verified-alias", + org="org-one", + namespaces=("selected",), + roles=(Role.WRITER,), + is_service_account=False, + session_id="session-one", + token_id="token-one", + issued_at=200, + parent_iats=(100,), + parents=("parent-one",), + ) + canonical = AsyncMock(return_value="canonical-owner") + standing = AsyncMock() + monkeypatch.setattr(accounts.aliases, "canonical_subject", canonical) + monkeypatch.setattr(accounts, "_standing", standing) + assert await accounts.own_subject(auth) == ("org-one", "canonical-owner") + canonical.assert_awaited_once_with("org-one", "verified-alias") + standing.assert_awaited_once_with( + "org-one", + "canonical-owner", + 100, + ("verified-alias", "token-one", "session-one", "parent-one"), + ) + for changed in ({"is_service_account": True}, {"reads_as_creator": True}, {"org": "*"}): + with pytest.raises(AuthInsufficientError): + await accounts.own_subject(replace(auth, **changed)) + assert canonical.await_count == standing.await_count == 1 + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["identity", "inactive", "scim", "cutoff"]) +async def test_owner_standing_refuses_offboarding_without_native_execution( + monkeypatch: pytest.MonkeyPatch, no_native_execution: None, failure: str +) -> None: + identity = SimpleNamespace(subject="owner-one", emails={"owner@example.test"}) + monkeypatch.setattr(type(accounts.settings), "auth_actually_required", lambda self: True) + monkeypatch.setattr( + accounts, + "resolve_reader", + AsyncMock(return_value=None if failure == "identity" else identity), + ) + monkeypatch.setattr( + accounts.aliases, "verified_spellings", AsyncMock(return_value=["owner-one", "old-alias"]) + ) + monkeypatch.setattr( + accounts.store, "account_active", AsyncMock(return_value=failure != "inactive") + ) + monkeypatch.setattr(accounts.scim, "refuses_subject", AsyncMock(return_value=failure == "scim")) + monkeypatch.setattr( + accounts.revocation, + "cutoffs", + AsyncMock(return_value={"old-alias": None} if failure == "cutoff" else {}), + ) + with pytest.raises(accounts.OwnerUnavailable): + await accounts._standing("org-one", "owner-one", 200, ("session-one",)) + if failure == "cutoff": + accounts.revocation.cutoffs.assert_awaited_once_with( + ["owner-one", "old-alias", "session-one"] + ) + + +@pytest.mark.asyncio +async def test_owner_standing_refuses_unconfigured_auth_before_directory_reads( + monkeypatch: pytest.MonkeyPatch, +) -> None: + identity = AsyncMock() + monkeypatch.setattr(type(accounts.settings), "auth_actually_required", lambda self: False) + monkeypatch.setattr(accounts, "resolve_reader", identity) + with pytest.raises(accounts.ValidationError, match="the connected account is unavailable"): + await accounts._standing("org-one", "owner-one", 200) + identity.assert_not_awaited() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["gdrive", "notion", "linear", "mcp:" + "a" * 32, "retired-kind"]) +async def test_local_erasure_uses_exact_stored_key_without_opening_credentials( + monkeypatch: pytest.MonkeyPatch, no_native_execution: None, kind: str +) -> None: + from server.erasure.app import connected_accounts as erasure + from server.knowledge.app import sources + + account = ConnectedAccount( + "org-one", + "canonical-owner", + kind, + "b" * 32 + "/0" + "c" * 31, + disconnected_at=datetime.now(UTC), + ) + held: list[tuple[str, str]] = [] + + @asynccontextmanager + async def lease(org: str, namespace: str): + held.append((org, namespace)) + try: + yield + finally: + held.pop() + + async def erase_source(*key: str) -> None: + assert held == [("org-one", "selected")] + assert key == ("org-one", "selected", "canonical-owner", kind) + + namespaces = AsyncMock(return_value=["selected"]) + erase = AsyncMock() + source_census, account_census = AsyncMock(), AsyncMock() + monkeypatch.setattr(accounts, "get_client", object) + monkeypatch.setattr(accounts.claims, "get", AsyncMock(return_value=account.connection_id)) + monkeypatch.setattr(accounts.source_store, "connected_owner_namespaces", namespaces) + monkeypatch.setattr(accounts.source_store, "erase_connected_owner", erase_source) + monkeypatch.setattr(accounts.store, "erase", erase) + monkeypatch.setattr(sources, "sources_lease", lease) + monkeypatch.setattr(erasure, "require_sources_erased", source_census) + monkeypatch.setattr(erasure, "require_erased", account_census) + await accounts._erase_locked(account, keep_marker=False) + namespaces.assert_awaited_once_with("org-one", "canonical-owner", kind) + erase.assert_awaited_once_with("org-one", ["canonical-owner"], kind=kind) + source_census.assert_awaited_once_with("org-one", "selected", "canonical-owner", kind) + account_census.assert_awaited_once_with( + "org-one", "canonical-owner", kind, keep_connection=None + ) + assert not held + + +@pytest.mark.asyncio +async def test_erasure_refuses_unknown_fence_before_removing_any_raw_version( + monkeypatch: pytest.MonkeyPatch, no_native_execution: None +) -> None: + account = ConnectedAccount("org-one", "owner-one", "retired-kind", "b" * 32 + "/0" + "c" * 31) + erase = AsyncMock() + monkeypatch.setattr(accounts, "get_client", object) + monkeypatch.setattr(accounts.claims, "get", AsyncMock(return_value=None)) + monkeypatch.setattr(accounts.store, "erase", erase) + with pytest.raises(accounts.ValidationError, match="the connected account is unavailable"): + await accounts._erase_locked(account, keep_marker=False) + erase.assert_not_awaited() diff --git a/tests/unit/test_schema_baseline.py b/tests/unit/test_schema_baseline.py index 3e8adcf911..72eb779ad9 100644 --- a/tests/unit/test_schema_baseline.py +++ b/tests/unit/test_schema_baseline.py @@ -172,6 +172,7 @@ def test_the_journal_files() -> None: "114_memory_proposal_review.sql", "115_memory_refusals.sql", "116_mcp_source_lifecycle.sql", + "117_mcp_source_admission.sql", ] diff --git a/tests/unit/test_source_push.py b/tests/unit/test_source_push.py index d58b3a9b0d..85d0e05c1e 100644 --- a/tests/unit/test_source_push.py +++ b/tests/unit/test_source_push.py @@ -1,564 +1,95 @@ -"""Setup activation and sync hints stay bound across source lifecycle changes.""" - -from __future__ import annotations +"""Retained notification registrations keep their exact namespace and secret.""" import dataclasses -import hashlib -import hmac -import json -import time from contextlib import asynccontextmanager from types import SimpleNamespace from unittest.mock import AsyncMock import pytest -from server.knowledge.api.models_source_push import ( - PushConfigureInput, - PushConfirmInput, - PushStatusInput, -) from server.knowledge.app import source_push as app -from server.knowledge.domain.source_push import DeliveryRefused, PushRegistration -from server.knowledge.domain.sources import KnowledgeSource +from server.knowledge.domain.source_push import PushRegistration @pytest.fixture -def env(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: +def env(monkeypatch): state = SimpleNamespace( - src=KnowledgeSource( - org="org", namespace="docs", name="source", kind="notion", source_id="source-id" + reg=PushRegistration( + org="org", + namespace="docs", + name="retired", + source_id="retained-id", + provider="notion", + generation="retained-generation", + fingerprint="retained-fingerprint", + status="active", + secret_enc="retained-secret", ), - reg=None, - sync={}, writes=[], - requests=[], - ready=True, ) - monkeypatch.setattr(app.settings, "public_base_url", "https://loom.example") - monkeypatch.setattr(app.settings, "knowledge_source_push_enabled", True) - monkeypatch.setattr(app.settings, "jwt_secret", "source-push-test-root-" * 4) - monkeypatch.setattr(app.sources, "credential_of", lambda src: "credential") @asynccontextmanager - async def lease(*args: object, **kwargs: object): + async def lease(*args, **kwargs): yield - @asynccontextmanager - async def renewal_lease(*args: object, **kwargs: object): - yield True - - @asynccontextmanager - async def fence(*args: object, **kwargs: object): - yield lambda uncertain: None - - async def get_source(*args: object, **kwargs: object): - return state.src + async def get(org, namespace, source_id, **kwargs): + assert (org, namespace, source_id) == ("org", "docs", "retained-id") + return state.reg - async def get_reg(org: str, namespace: str, source_id: str, *, ch=None): - if ( - state.reg - and state.reg.org == org - and state.reg.namespace == namespace - and state.reg.source_id == source_id - ): - return state.reg - return None - - async def put(reg: PushRegistration, *, ch=None): - state.reg = reg - state.writes.append(reg) - - async def read_state(src: KnowledgeSource): - return state.sync - - async def update_state( - src: KnowledgeSource, previous: dict[str, str], changes: dict[str, object] - ): - state.requests.append((src, changes)) - detail = json.loads(state.sync.get("detail") or "{}") - state.sync = {"detail": json.dumps({**detail, **changes})} + async def put(row, **kwargs): + state.reg = row + state.writes.append(row) monkeypatch.setattr(app.sources, "sources_lease", lease) - monkeypatch.setattr(app.leases, "holding", renewal_lease) - monkeypatch.setattr(app, "fenced", fence) - monkeypatch.setattr(app.sources, "_source_or_404", get_source) - monkeypatch.setattr(app.source_store, "get_source", get_source) - monkeypatch.setattr(app.sources, "_require_served", lambda src: None) - monkeypatch.setattr(app.sources, "_require_source_namespace", AsyncMock()) monkeypatch.setattr(app.sources, "_require_no_erasure", AsyncMock()) - monkeypatch.setattr(app.sources, "_read_state", read_state) - monkeypatch.setattr(app.sources, "_update_state", update_state) - monkeypatch.setattr(app.store, "get", get_reg) - monkeypatch.setattr(app.store, "put", put) - monkeypatch.setattr(app.machines, "fleet_at", AsyncMock(side_effect=lambda *args: state.ready)) - monkeypatch.setattr(app.notion, "workspace_id", AsyncMock(return_value="workspace")) - monkeypatch.setattr(app.linear, "organization_id", AsyncMock(return_value="organization")) + monkeypatch.setattr(app.store, "get", get) + monkeypatch.setattr(app, "_put", put) + monkeypatch.setattr(app, "resealed", lambda purpose, value: "resealed:" + value) return state -async def setup_notion(env: SimpleNamespace) -> None: - await app.handle_configure(PushConfigureInput(org="org", namespace="docs", name="source")) - - -async def capture(env: SimpleNamespace, token: str = "verification-challenge") -> None: - await app.receive( - "org", - "docs", - "source-id", - env.reg.generation, - json.dumps({"verification_token": token}).encode(), - {}, - ) - - -async def activate(env: SimpleNamespace) -> None: - await capture(env) - await app.handle_confirm( - PushConfirmInput( - org="org", - namespace="docs", - name="source", - generation=env.reg.generation, - challenge_fingerprint=app.domain.challenge_fingerprint("verification-challenge"), - ) - ) - - @pytest.mark.asyncio -async def test_notion_challenge_does_not_sync_or_activate_and_only_explicitly_reveals( - env: SimpleNamespace, -) -> None: - await setup_notion(env) - await capture(env) - normal = await app.handle_status(PushStatusInput(org="org", namespace="docs", name="source")) - assert normal.status == "pending" and normal.verification_token == "" - reveal = await app.handle_status( - PushStatusInput(org="org", namespace="docs", name="source", reveal_challenge=True) - ) - assert reveal.verification_token == "verification-challenge" - assert env.requests == [] - assert "verification-challenge" not in env.reg.secret_enc - with pytest.raises(DeliveryRefused, match="already captured"): - await capture(env, "attacker-replacement") - await activate(env) - assert env.reg.status == "active" - assert ( - await app.handle_status( - PushStatusInput(org="org", namespace="docs", name="source", reveal_challenge=True) - ) - ).verification_token == "" - - -@pytest.mark.asyncio -async def test_confirmation_requires_exact_generation_and_fingerprint(env: SimpleNamespace) -> None: - await setup_notion(env) - await capture(env) - for generation, fingerprint in ( - ("old", app.domain.challenge_fingerprint("verification-challenge")), - (env.reg.generation, "wrong"), - ): - with pytest.raises(app.ValidationError): - await app.handle_confirm( - PushConfirmInput( - org="org", - namespace="docs", - name="source", - generation=generation, - challenge_fingerprint=fingerprint, - ) - ) - assert env.reg.status == "pending" and not env.requests - - -@pytest.mark.asyncio -async def test_active_notion_only_records_one_hint_and_preserves_full_request( - env: SimpleNamespace, -) -> None: - await setup_notion(env) - await activate(env) - raw = json.dumps({"workspace_id": "workspace", "type": "page.content_updated"}).encode() - signature = "sha256=" + hmac.new(b"verification-challenge", raw, hashlib.sha256).hexdigest() - for _ in range(2): - await app.receive( - "org", "docs", "source-id", env.reg.generation, raw, {"x-notion-signature": signature} - ) - assert len(env.requests) == 1 - env.sync = {"detail": json.dumps({"requested_at": "earlier", "full": True, "cursor": "keep"})} - await app.receive( - "org", "docs", "source-id", env.reg.generation, raw, {"x-notion-signature": signature} - ) - assert json.loads(env.sync["detail"]) == { - "requested_at": "earlier", - "full": True, - "cursor": "keep", - } - with pytest.raises(DeliveryRefused): - await app.receive("org", "docs", "source-id", env.reg.generation, raw, {}) - - -@pytest.mark.asyncio -@pytest.mark.parametrize( - "change", ["removed", "replaced", "items", "retired", "other-org", "other-namespace"] -) -async def test_late_delivery_cannot_reach_changed_registration( - env: SimpleNamespace, change: str -) -> None: - await setup_notion(env) - generation = env.reg.generation - if change == "removed": - env.src = None - elif change == "replaced": - env.src = dataclasses.replace(env.src, source_id="replacement") - elif change == "items": - env.src = dataclasses.replace(env.src, items=[{"type": "page", "id": "new"}]) - elif change == "retired": - await app.retire(env.src) - before = len(env.writes) - with pytest.raises(DeliveryRefused): - await app.receive( - "other-org" if change == "other-org" else "org", - "other-docs" if change == "other-namespace" else "docs", - "source-id", - generation, - b'{"verification_token":"verification-challenge"}', - {}, - ) - assert not env.requests and len(env.writes) == before - - -@pytest.mark.asyncio -async def test_fleet_downgrade_refuses_unsigned_challenge_write(env: SimpleNamespace) -> None: - await setup_notion(env) - env.ready = False - with pytest.raises(app.BadConfigError): - await capture(env) - assert "challenge" not in app._secrets(env.reg) - - -@pytest.mark.asyncio -async def test_setup_requires_explicit_https_origin( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - for url in ( - "", - "http://loom.example", - "https://user:secret@loom.example", - "https://loom.example/path", - "https://[broken", - ): - monkeypatch.setattr(app.settings, "public_base_url", url) - with pytest.raises(app.BadConfigError): - await setup_notion(env) - assert not env.writes - - -@pytest.mark.asyncio -async def test_removal_during_drive_watch_cannot_reactivate( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - env.src = dataclasses.replace(env.src, kind="gdrive") - monkeypatch.setattr(app.gdrive, "parse_service_account", lambda key: object()) - monkeypatch.setattr(app.gdrive, "access_token", AsyncMock(return_value="token")) - monkeypatch.setattr(app.gdrive_push, "member_drives", AsyncMock(return_value=set())) - stopped = AsyncMock() - monkeypatch.setattr(app.gdrive_push, "stop", stopped) - - async def watch(*args: object, **kwargs: object): - await app.retire(env.src) - env.src = None - return { - "id": kwargs["channel_id"], - "token": kwargs["channel_token"], - "resource_id": "resource", - "expiration": time.time() + 3600, - "drive_id": "", - } - - monkeypatch.setattr(app.gdrive_push, "watch", watch) - with pytest.raises(DeliveryRefused): - await app.handle_configure(PushConfigureInput(org="org", namespace="docs", name="source")) - assert env.reg.status == "retired" and env.reg.secret_enc == "" - stopped.assert_awaited_once() - - -def test_pending_secret_read_cannot_enter_idempotency_replay_storage() -> None: - from server.knowledge.api.ops_source_push import OPERATIONS - - status = next(op for op in OPERATIONS if op.name.endswith(".push_status")) - assert not status.idempotent - - -def test_setup_audit_accepts_response_and_omits_secrets() -> None: - body = PushConfirmInput( - org="org", namespace="docs", name="source", generation="generation", signing_secret="secret" - ) - assert app.audit_subject(body, {"verification_token": "secret"}) == { - "org": "org", - "namespace": "docs", - "name": "source", - } - - -@pytest.mark.asyncio -async def test_reseal_rechecks_row_after_scanning_before_erasure( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - await setup_notion(env) +async def test_reseal_rechecks_row_after_scanning_before_erasure(env, monkeypatch): scanned = env.reg - pages = AsyncMock(side_effect=[[scanned], []]) - monkeypatch.setattr(app.store, "sealed_page", pages) + monkeypatch.setattr(app.store, "sealed_page", AsyncMock(side_effect=[[scanned], []])) @asynccontextmanager - async def erase_before_claim(*args: object, **kwargs: object): + async def erase_before_claim(*args, **kwargs): env.reg = None yield monkeypatch.setattr(app.sources, "sources_lease", erase_before_claim) - before = len(env.writes) assert await app.reseal_registry(dry_run=False) == (0, []) - assert env.reg is None and len(env.writes) == before + assert env.reg is None and env.writes == [] @pytest.mark.asyncio -async def test_reseal_uses_current_generation_and_fleet_gate( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - await setup_notion(env) +async def test_reseal_uses_current_generation_and_preserves_retained_metadata(env, monkeypatch): scanned = env.reg - await setup_notion(env) - generation = env.reg.generation + current = dataclasses.replace( + scanned, generation="replacement", secret_enc="replacement-secret" + ) + env.reg = current monkeypatch.setattr(app.store, "sealed_page", AsyncMock(side_effect=[[scanned], []])) - monkeypatch.setattr(app, "resealed", lambda purpose, value: value) assert await app.reseal_registry(dry_run=False) == (1, []) - assert env.reg.generation == generation - env.ready = False - monkeypatch.setattr(app.store, "sealed_page", AsyncMock(side_effect=[[env.reg], []])) - with pytest.raises(app.BadConfigError): - await app.reseal_registry(dry_run=False) - - -@pytest.mark.asyncio -async def test_lost_publication_ack_does_not_stop_current_drive_channels( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - env.src = dataclasses.replace(env.src, kind="gdrive") - monkeypatch.setattr(app.gdrive, "parse_service_account", lambda key: object()) - monkeypatch.setattr(app.gdrive, "access_token", AsyncMock(return_value="token")) - monkeypatch.setattr(app.gdrive_push, "member_drives", AsyncMock(return_value=set())) - stopped = AsyncMock() - monkeypatch.setattr(app.gdrive_push, "stop", stopped) - original_put = app.store.put - - async def uncertain_put(reg: PushRegistration, *, ch=None): - await original_put(reg, ch=ch) - if reg.status == "active": - raise ConnectionError("ack lost after commit") - - async def watch(*args: object, **kwargs: object): - return { - "id": kwargs["channel_id"], - "token": kwargs["channel_token"], - "resource_id": "resource", - "expiration": time.time() + 3600, - "drive_id": "", - } - - monkeypatch.setattr(app.store, "put", uncertain_put) - monkeypatch.setattr(app.gdrive_push, "watch", watch) - with pytest.raises(ConnectionError, match="ack lost"): - await app.handle_configure(PushConfigureInput(org="org", namespace="docs", name="source")) - assert env.reg.status == "active" and app._secrets(env.reg)["channels"] - stopped.assert_not_awaited() - - -@pytest.mark.asyncio -async def test_linear_prepares_stable_address_then_requires_exact_confirmation( - env: SimpleNamespace, -) -> None: - env.src = dataclasses.replace(env.src, kind="linear") - pending = await app.handle_configure( - PushConfigureInput(org="org", namespace="docs", name="source") - ) - assert pending.status == "pending" - assert pending.callback_url == ( - f"https://loom.example/hooks/knowledge/docs/source-id/{pending.generation}?org=org" - ) - generation = pending.generation - raw = json.dumps( - {"organizationId": "organization", "webhookTimestamp": int(time.time() * 1000)} - ).encode() - signature = hmac.new(b"signing-secret", raw, hashlib.sha256).hexdigest() - with pytest.raises(DeliveryRefused): - await app.receive( - "org", "docs", "source-id", generation, raw, {"linear-signature": signature} - ) - with pytest.raises(app.ValidationError): - await app.handle_confirm( - PushConfirmInput( - org="org", - namespace="docs", - name="source", - generation="old", - signing_secret="signing-secret", - ) - ) - active = await app.handle_confirm( - PushConfirmInput( - org="org", - namespace="docs", - name="source", - generation=generation, - signing_secret="signing-secret", - ) - ) - assert active.status == "active" and active.callback_url == pending.callback_url - await app.receive("org", "docs", "source-id", generation, raw, {"linear-signature": signature}) - assert len(env.requests) == 1 - - -@pytest.mark.asyncio -async def test_deployment_opt_out_refuses_setup( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.setattr(app.settings, "knowledge_source_push_enabled", False) - with pytest.raises(app.BadConfigError): - await setup_notion(env) - assert not env.writes - - -@pytest.mark.asyncio -async def test_deployment_opt_out_refuses_existing_delivery( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - await setup_notion(env) - await activate(env) - monkeypatch.setattr(app.settings, "knowledge_source_push_enabled", False) - raw = json.dumps({"workspace_id": "workspace"}).encode() - signature = "sha256=" + hmac.new(b"verification-challenge", raw, hashlib.sha256).hexdigest() - with pytest.raises(DeliveryRefused): - await app.receive( - "org", "docs", "source-id", env.reg.generation, raw, {"x-notion-signature": signature} - ) - assert not env.requests - - -@pytest.mark.asyncio -@pytest.mark.parametrize("origin", ["", "https://[broken"]) -async def test_paused_setup_can_be_inspected_and_disabled_without_public_origin( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, origin: str -) -> None: - await setup_notion(env) - monkeypatch.setattr(app.settings, "knowledge_source_push_enabled", False) - monkeypatch.setattr(app.settings, "public_base_url", origin) - status = await app.handle_status(PushStatusInput(org="org", namespace="docs", name="source")) - assert not status.enabled and status.callback_url == "" and status.status == "pending" - disabled = await app.handle_configure( - PushConfigureInput(org="org", namespace="docs", name="source", enabled=False) - ) - assert disabled.status == "disabled" and env.reg.secret_enc == "" + assert env.writes == [dataclasses.replace(current, secret_enc="resealed:replacement-secret")] + assert dataclasses.asdict(env.reg) == { + **dataclasses.asdict(current), + "secret_enc": "resealed:replacement-secret", + } @pytest.mark.asyncio -async def test_provider_and_channel_cleanup_read_configured_timeouts( - env: SimpleNamespace, monkeypatch: pytest.MonkeyPatch -) -> None: - waits = [] - - @asynccontextmanager - async def timeout(seconds: float): - waits.append(seconds) - yield - - monkeypatch.setattr(app.asyncio, "timeout", timeout) - monkeypatch.setattr(app.settings, "knowledge_source_push_provider_timeout_s", 17.0) - monkeypatch.setattr(app.settings, "knowledge_source_push_stop_timeout_s", 1.25) - monkeypatch.setattr(app.settings, "knowledge_source_push_cleanup_timeout_s", 3.0) - await setup_notion(env) - assert waits == [17.0] - env.src = dataclasses.replace(env.src, kind="gdrive") - env.reg = dataclasses.replace(env.reg, provider="gdrive") - monkeypatch.setattr(app.gdrive, "parse_service_account", lambda key: object()) - monkeypatch.setattr(app.gdrive, "access_token", AsyncMock(return_value="token")) - monkeypatch.setattr(app.gdrive_push, "member_drives", AsyncMock(return_value=set())) - monkeypatch.setattr( - app.gdrive_push, - "watch", - AsyncMock( - return_value={ - "id": "created", - "token": "channel-token", - "resource_id": "resource", - "expiration": time.time() + 3600, - "drive_id": "", - } - ), - ) - stopped = AsyncMock() - monkeypatch.setattr(app.gdrive_push, "stop", stopped) - await app._renew_drive(env.reg, initial=True) - assert waits == [17.0, 17.0, 3.0] - await app._stop_channels("token", [{"id": "superseded"}]) - assert waits == [17.0, 17.0, 3.0, 1.25] - stopped.assert_awaited_once_with("token", {"id": "superseded"}) - - -@pytest.mark.parametrize( - "overrides,error", - [ - ({"knowledge_source_push_stop_timeout_s": 6.0}, "STOP_TIMEOUT_S"), - ({"knowledge_source_push_provider_timeout_s": 60.0}, "renewal work window"), - ({"knowledge_source_push_max_pass_seconds": 50.0}, "MAX_PASS_SECONDS"), - ], -) -def test_push_budgets_refuse_cleanup_or_attempt_outside_deadline( - overrides: dict[str, float], error: str -) -> None: - from pydantic import ValidationError - - from server.settings.catalog import KnowledgeSettings - - with pytest.raises(ValidationError, match=error): - KnowledgeSettings(**overrides) - - -def test_push_budgets_accept_configured_deadlines() -> None: - from server.settings.catalog import KnowledgeSettings - - configured = KnowledgeSettings( - knowledge_source_push_provider_timeout_s=36.0, - knowledge_source_push_stop_timeout_s=3.0, - knowledge_source_push_cleanup_timeout_s=6.0, - knowledge_source_push_max_pass_seconds=180.0, - ) - assert configured.knowledge_source_push_provider_timeout_s == 36.0 - assert configured.knowledge_source_push_stop_timeout_s == 3.0 - assert configured.knowledge_source_push_cleanup_timeout_s == 6.0 - assert configured.knowledge_source_push_max_pass_seconds == 180.0 - - -def test_push_budget_boundary_matches_the_actual_renewal_lease_window( - monkeypatch: pytest.MonkeyPatch, -) -> None: - from pydantic import ValidationError - - from server.settings.catalog import KnowledgeSettings - - monkeypatch.setattr(app.leases, "time", SimpleNamespace(monotonic=lambda: 100.0)) - lease = app.leases.Lease("push-budget", ttl_s=120, ch=object(), holder="budget-test") - lease._renewed = 100.0 - work_window = app.leases.work_left(lease, 120) - assert work_window == 48.0 - with pytest.raises(ValidationError, match="renewal work window"): - KnowledgeSettings( - knowledge_source_push_provider_timeout_s=40.0, - knowledge_source_push_cleanup_timeout_s=work_window - 40.0, - ) - configured = KnowledgeSettings( - knowledge_source_push_provider_timeout_s=40.0, - knowledge_source_push_cleanup_timeout_s=work_window - 41.0, - ) - assert configured.knowledge_source_push_cleanup_timeout_s == 7.0 +@pytest.mark.parametrize("dry_run,changed", [(True, "replacement"), (False, None)]) +async def test_reseal_dry_run_or_unreadable_secret_never_deletes_a_registration( + env, monkeypatch, dry_run, changed +): + retained = env.reg + monkeypatch.setattr(app.store, "sealed_page", AsyncMock(side_effect=[[retained], []])) + monkeypatch.setattr(app, "resealed", lambda purpose, value: changed) + expected_bad = [] if changed is not None else ["org/docs/retained-id"] + assert await app.reseal_registry(dry_run=dry_run) == (int(changed is not None), expected_bad) + assert env.reg is retained and env.writes == [] @pytest.mark.asyncio diff --git a/tests/unit/test_source_push_proofs.py b/tests/unit/test_source_push_proofs.py deleted file mode 100644 index b03fce4772..0000000000 --- a/tests/unit/test_source_push_proofs.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Provider proof is checked over raw bytes and the signed provider scope.""" - -from __future__ import annotations - -import hashlib -import hmac -import json - -import pytest - -from server.knowledge.domain import source_push as push - - -def signed(body: dict[str, object], *, prefix: str = "") -> tuple[bytes, str]: - raw = json.dumps(body, indent=2).encode() - return raw, prefix + hmac.new(b"secret", raw, hashlib.sha256).hexdigest() - - -def test_linear_requires_signed_timestamp_and_organization() -> None: - raw, signature = signed({"organizationId": "org", "webhookTimestamp": 1_000_000}) - push.verify_linear(raw, signature, "secret", "org", now=1000) - for kwargs in ( - {"now": 1061, "organization_id": "org"}, - {"now": 1000, "organization_id": "other"}, - ): - with pytest.raises(push.DeliveryRefused): - push.verify_linear(raw, signature, "secret", **kwargs) - with pytest.raises(push.DeliveryRefused): - push.verify_linear(raw + b" ", signature, "secret", "org", now=1000) - - -@pytest.mark.parametrize("stamp", [True, "1000000", None, float("nan"), float("inf"), 10**1000]) -def test_linear_refuses_invalid_signed_clock(stamp: object) -> None: - raw, signature = signed({"organizationId": "org", "webhookTimestamp": stamp}) - with pytest.raises(push.DeliveryRefused): - push.verify_linear(raw, signature, "secret", "org", now=1000) - - -def test_notion_checks_raw_body_workspace_and_prefix() -> None: - raw, signature = signed({"workspace_id": "space"}, prefix="sha256=") - push.verify_notion(raw, signature, "secret", "space") - for body, proof, workspace in ( - (raw + b" ", signature, "space"), - (raw, signature[7:], "space"), - (raw, signature, "other"), - ): - with pytest.raises(push.DeliveryRefused): - push.verify_notion(body, proof, "secret", workspace) - - -def test_drive_requires_whole_active_channel_binding() -> None: - channel = {"id": "id", "token": "secret", "resource_id": "resource", "expiration": 1100} - headers = { - "x-goog-channel-id": "id", - "x-goog-channel-token": "secret", - "x-goog-resource-id": "resource", - "x-goog-resource-state": "change", - } - assert push.verify_drive(headers, [channel], now=1000) - assert not push.verify_drive({**headers, "x-goog-resource-state": "sync"}, [channel], now=1000) - for key in headers: - with pytest.raises(push.DeliveryRefused): - push.verify_drive({**headers, key: "wrong"}, [channel], now=1000) - with pytest.raises(push.DeliveryRefused): - push.verify_drive(headers, [channel], now=1100) - - -def test_fingerprint_ignores_mapping_order_but_binds_credentials_and_items() -> None: - kwargs = {"credential": "key", "items": [{"id": "one", "type": "file"}], "config": {}} - first = push.fingerprint(**kwargs) - assert first == push.fingerprint(**{**kwargs, "items": [{"type": "file", "id": "one"}]}) - assert first != push.fingerprint(**{**kwargs, "credential": "other"}) - assert first != push.fingerprint(**{**kwargs, "items": []}) diff --git a/tests/unit/test_source_push_routes.py b/tests/unit/test_source_push_routes.py deleted file mode 100644 index 4d06a23600..0000000000 --- a/tests/unit/test_source_push_routes.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Provider ingress bounds its bytes and acknowledges with the required status.""" - -from __future__ import annotations - -from unittest.mock import AsyncMock -from urllib.parse import urlsplit, urlunsplit - -import pytest -from fastapi import FastAPI -from fastapi.testclient import TestClient - -from server.knowledge.app import source_push as push -from server.knowledge.app import source_push_routes as routes -from server.knowledge.domain.source_push import MAX_BODY_BYTES, DeliveryRefused, PushRegistration - -URL = "/hooks/knowledge/docs/12345678-1234-1234-1234-123456789abc/22345678-1234-1234-1234-123456789abc?org=org" - - -def client() -> TestClient: - app = FastAPI() - routes.attach(app) - return TestClient(app) - - -def test_verified_delivery_acknowledges_200_inside_provider_deadline( - monkeypatch: pytest.MonkeyPatch, -) -> None: - receive = AsyncMock() - monkeypatch.setattr(routes, "receive", receive) - assert client().post(URL, content=b"signal").status_code == 200 - assert routes.CALLBACK_TIMEOUT_S < 5 - assert receive.call_args.args[:5] == ( - "org", - "docs", - "12345678-1234-1234-1234-123456789abc", - "22345678-1234-1234-1234-123456789abc", - b"signal", - ) - - -def test_oversized_delivery_never_reaches_store(monkeypatch: pytest.MonkeyPatch) -> None: - receive = AsyncMock() - monkeypatch.setattr(routes, "receive", receive) - assert client().post(URL, content=b"x" * (MAX_BODY_BYTES + 1)).status_code == 413 - receive.assert_not_awaited() - - -def test_unverifiable_delivery_refuses(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr( - routes, "receive", AsyncMock(side_effect=DeliveryRefused("unverifiable delivery")) - ) - assert client().post(URL, content=b"signal").status_code == 403 - - -def test_callback_without_namespace_is_not_a_route(monkeypatch: pytest.MonkeyPatch) -> None: - receive = AsyncMock() - monkeypatch.setattr(routes, "receive", receive) - assert client().post(URL.replace("/docs/", "/"), content=b"signal").status_code == 404 - receive.assert_not_awaited() - - -@pytest.fixture -def callback_env(monkeypatch: pytest.MonkeyPatch) -> AsyncMock: - held = AsyncMock(return_value=True) - monkeypatch.setattr(routes.tenancy, "is_held", held) - monkeypatch.setattr(push.settings, "public_base_url", "https://loom.example") - return held - - -def registration(org: str) -> PushRegistration: - return PushRegistration( - org=org, - namespace="docs", - name="source", - source_id="12345678-1234-1234-1234-123456789abc", - generation="22345678-1234-1234-1234-123456789abc", - provider="notion", - fingerprint="fingerprint", - ) - - -@pytest.mark.parametrize( - "org", - ["org", "team/acme", "team?x=1&org=other#group", "team%2Facme+ ops", "研究/チーム &é"], -) -def test_generated_callback_round_trips_the_exact_organization_through_asgi( - monkeypatch: pytest.MonkeyPatch, callback_env: AsyncMock, org: str -) -> None: - receive = AsyncMock() - monkeypatch.setattr(routes, "receive", receive) - reg = registration(org) - response = client().post(push.callback_url(reg), content=b"signal") - assert response.status_code == 200 - callback_env.assert_awaited_once_with(org) - assert receive.await_args.args[:5] == ( - org, - reg.namespace, - reg.source_id, - reg.generation, - b"signal", - ) - - -def test_callback_requires_organization_before_tenancy_or_delivery( - monkeypatch: pytest.MonkeyPatch, callback_env: AsyncMock -) -> None: - receive = AsyncMock() - monkeypatch.setattr(routes, "receive", receive) - address = urlsplit(push.callback_url(registration("org"))) - missing_org = urlunsplit(address._replace(query="")) - assert client().post(missing_org, content=b"signal").status_code == 422 - callback_env.assert_not_awaited() - receive.assert_not_awaited() diff --git a/tests/unit/test_source_push_worker.py b/tests/unit/test_source_push_worker.py deleted file mode 100644 index 5ed1439633..0000000000 --- a/tests/unit/test_source_push_worker.py +++ /dev/null @@ -1,100 +0,0 @@ -"""Renewal pages advance past failed sources and reset exhausted scans durably.""" - -from __future__ import annotations - -import json -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import pytest - -from server.knowledge.domain.source_push import PushRegistration -from server.knowledge.workers import source_push as worker -from server.workers import pass_context, registry - - -def registration(source_id: str) -> PushRegistration: - return PushRegistration( - org="org", - namespace="docs", - name="source", - source_id=source_id, - provider="gdrive", - generation="gen", - fingerprint="fp", - ) - - -@pytest.mark.asyncio -async def test_failed_source_does_not_starve_following_row(monkeypatch: pytest.MonkeyPatch) -> None: - context = pass_context.begin("knowledge_source_push", resume_cursor='["before", "docs", "id"]') - page = AsyncMock(return_value=[registration("one"), registration("two")]) - renew = AsyncMock(side_effect=[ConnectionError("temporary"), None]) - monkeypatch.setattr(worker, "require_ready", AsyncMock()) - monkeypatch.setattr(worker, "drive_page", page) - monkeypatch.setattr(worker, "renew_drive", renew) - result = await worker.run_pass() - page.assert_awaited_once_with(("before", "docs", "id")) - assert result == {"items_planned": 2, "items_done": 1, "failed": 1} - assert context.count == 1 and json.loads(context.cursor) == ["", "", ""] - - -@pytest.mark.asyncio -@pytest.mark.parametrize("max_pass,expected", [(120.0, 1), (180.0, 2)]) -async def test_page_cut_persists_last_attempted_row( - monkeypatch: pytest.MonkeyPatch, max_pass: float, expected: int -) -> None: - context = pass_context.begin("knowledge_source_push") - monkeypatch.setattr(worker, "require_ready", AsyncMock()) - monkeypatch.setattr( - worker, "drive_page", AsyncMock(return_value=[registration("one"), registration("two")]) - ) - renew = AsyncMock() - monkeypatch.setattr(worker, "renew_drive", renew) - monkeypatch.setattr(worker.settings, "knowledge_source_push_max_pass_seconds", max_pass) - clock = iter([0.0, 0.0, 80.0]) - monkeypatch.setattr(worker, "time", SimpleNamespace(monotonic=lambda: next(clock, 80.0))) - result = await worker.run_pass() - assert result["items_done"] == expected - assert json.loads(context.cursor) == (["org", "docs", "one"] if expected == 1 else ["", "", ""]) - assert renew.await_count == expected - - -def test_registry_reads_configured_push_cadence_and_deadline( - monkeypatch: pytest.MonkeyPatch, -) -> None: - monkeypatch.setattr(worker.settings, "knowledge_source_push_enabled", True) - monkeypatch.setattr(worker.settings, "knowledge_source_push_interval_seconds", 733) - monkeypatch.setattr(worker.settings, "knowledge_source_push_max_pass_seconds", 180.0) - spec = next(spec for spec in registry.enabled_workers() if spec.name == "knowledge_source_push") - assert spec.interval_seconds == 733 - assert spec.deadline_seconds() == 180.0 - - -@pytest.mark.asyncio -async def test_page_cursor_advances_between_namespaces(monkeypatch: pytest.MonkeyPatch) -> None: - import dataclasses - - context = pass_context.begin("knowledge_source_push", resume_cursor='["org", "docs", "before"]') - rows = [ - registration("same-id"), - dataclasses.replace(registration("same-id"), namespace="other-docs"), - ] - page = AsyncMock(return_value=rows) - renew = AsyncMock() - cursors: list[list[str]] = [] - set_cursor = pass_context.set_cursor - - def capture_cursor(cursor: str) -> None: - cursors.append(json.loads(cursor)) - set_cursor(cursor) - - monkeypatch.setattr(worker, "require_ready", AsyncMock()) - monkeypatch.setattr(worker, "drive_page", page) - monkeypatch.setattr(worker, "renew_drive", renew) - monkeypatch.setattr(pass_context, "set_cursor", capture_cursor) - assert await worker.run_pass() == {"items_planned": 2, "items_done": 2, "failed": 0} - page.assert_awaited_once_with(("org", "docs", "before")) - assert [call.args[0] for call in renew.await_args_list] == rows - assert cursors == [["org", "docs", "same-id"], ["org", "other-docs", "same-id"], ["", "", ""]] - assert json.loads(context.cursor) == ["", "", ""] From 401db50f3e018898dea0ecbf6c366f9bf25a19f9 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 06:19:14 +0000 Subject: [PATCH 25/30] Protect source retrieval across clients and setup controls Observe protected responses before release and retain publication guards across later requests. Expose source setup through the SDKs, CLI and dashboard, with owned synthetic qualification workflows. Signed-off-by: zlareb1 --- .github/workflows/ci.yml | 64 + .../workflows/mcp-source-qualification.yml | 286 ++ .github/workflows/mcp-source-scale.yml | 271 + docs/architecture/source-cli.md | 83 + docs/guides/mcp-source-cli.md | 211 + docs/reference/cli.md | 37 +- docs/reference/errors.md | 10 +- docs/reference/operations.md | 41 +- docs/reference/operations/connection.md | 40 - docs/reference/operations/knowledge.md | 417 +- docs/reference/status.md | 9 +- docs/reference/workers.md | 1 - frontend/e2e/connected-accounts.spec.ts | 61 - .../e2e/dashboard-session-protection.spec.ts | 310 ++ frontend/e2e/fixtures.ts | 17 +- frontend/e2e/repositories.spec.ts | 8 +- frontend/e2e/sessionProtectionHarness.ts | 29 + frontend/src/App.tsx | 7 +- frontend/src/api.ts | 106 +- frontend/src/api/admin.ts | 46 +- frontend/src/api/adminReadRoutes.ts | 5 + frontend/src/api/assistantChat.ts | 2 + frontend/src/api/briefs.ts | 3 +- frontend/src/api/code.ts | 24 +- frontend/src/api/collections.ts | 10 +- frontend/src/api/connections.test.ts | 61 - frontend/src/api/connections.ts | 29 - frontend/src/api/conversations.ts | 12 +- frontend/src/api/guardrails.ts | 15 +- frontend/src/api/knowledge.ts | 34 +- frontend/src/api/knowledgeGaps.ts | 3 +- frontend/src/api/knowledgeSources.ts | 15 +- frontend/src/api/maintenance.ts | 29 +- frontend/src/api/mcpSources.test.ts | 83 + frontend/src/api/mcpSources.ts | 207 + frontend/src/api/memoryLifecycle.ts | 23 +- frontend/src/api/models.ts | 14 +- frontend/src/api/profile.ts | 7 +- frontend/src/api/queryHistory.ts | 8 +- frontend/src/api/review.ts | 22 +- frontend/src/api/runs.ts | 3 +- frontend/src/api/sourcePush.ts | 32 - frontend/src/api/structure.ts | 20 +- frontend/src/api/tasks.ts | 55 +- frontend/src/api/tracker.ts | 12 +- frontend/src/api/webhooks.ts | 7 +- frontend/src/components/HeaderSearch.tsx | 2 +- .../MemoryInspector.lifecycle.test.tsx | 19 +- .../components/MemoryInspector.pin.test.tsx | 3 +- .../MemoryInspector.rename.test.tsx | 2 + .../MemoryInspector.restore.test.tsx | 4 +- frontend/src/components/MemoryInspector.tsx | 28 +- .../components/NamespacePicker.seen.test.tsx | 2 +- frontend/src/components/NamespacePicker.tsx | 2 +- .../src/components/NamespacePickerList.tsx | 2 +- .../src/components/PendingRequestBanner.tsx | 2 +- .../components/SessionBriefsSection.test.tsx | 2 +- .../src/components/SessionBriefsSection.tsx | 2 +- frontend/src/flows/AddDocumentDialog.test.tsx | 2 +- frontend/src/flows/AddDocumentDialog.tsx | 6 +- frontend/src/flows/AddMemoryDialog.tsx | 2 +- frontend/src/flows/BatchUpload.tsx | 3 +- frontend/src/flows/CodeReindexDialog.test.tsx | 2 +- frontend/src/flows/CodeReindexDialog.tsx | 2 +- frontend/src/flows/CopyToNamespaceDialog.tsx | 2 +- frontend/src/flows/CreateCollectionDialog.tsx | 4 +- frontend/src/flows/CreateNamespaceDialog.tsx | 1 + frontend/src/flows/DatasetsDialog.test.tsx | 4 +- frontend/src/flows/DatasetsDialog.tsx | 2 +- frontend/src/flows/DialogStaleLoad.test.tsx | 2 +- .../src/flows/EditDocumentMetadataDialog.tsx | 2 +- frontend/src/flows/ForgetMemoriesDialog.tsx | 2 +- frontend/src/flows/GuideDialog.test.tsx | 2 +- frontend/src/flows/GuideDialog.tsx | 2 +- frontend/src/flows/InboxSettingsDialog.tsx | 6 +- .../src/flows/KnowledgeSourceDialog.test.tsx | 206 +- frontend/src/flows/KnowledgeSourceDialog.tsx | 123 +- frontend/src/flows/MCPConnectionStep.test.tsx | 114 + frontend/src/flows/MCPConnectionStep.tsx | 198 + frontend/src/flows/MCPLiveRead.test.tsx | 78 + frontend/src/flows/MCPLiveRead.tsx | 44 + .../src/flows/MCPResourceBrowser.test.tsx | 68 + frontend/src/flows/MCPResourceBrowser.tsx | 55 + .../flows/MCPSourceSetup.protection.test.tsx | 88 + frontend/src/flows/MCPSourceSetup.test.tsx | 254 + frontend/src/flows/MCPSourceSetup.tsx | 187 + frontend/src/flows/MembersDialog.tsx | 10 +- frontend/src/flows/MemoryReasonDialogs.tsx | 4 +- .../src/flows/MoveCollectionDialog.test.tsx | 2 +- frontend/src/flows/MoveCollectionDialog.tsx | 2 +- .../src/flows/MoveDocumentsDialog.test.tsx | 4 + frontend/src/flows/MoveDocumentsDialog.tsx | 1 + .../NamespaceSettingsDialog.costCap.test.tsx | 4 +- .../src/flows/NamespaceSettingsDialog.tsx | 4 +- frontend/src/flows/RepoDocDialogs.tsx | 3 +- frontend/src/flows/RunGrade.test.tsx | 4 +- frontend/src/flows/RunGrade.tsx | 2 +- frontend/src/flows/SourcePushDialog.test.tsx | 147 - frontend/src/flows/SourcePushDialog.tsx | 219 - frontend/src/flows/TaskActionDialog.tsx | 20 +- frontend/src/flows/TaskEditDialog.tsx | 4 +- frontend/src/flows/ThreadActions.test.tsx | 14 +- frontend/src/flows/ThreadActions.tsx | 13 +- .../src/flows/TrackerSourceDialogs.test.tsx | 2 +- frontend/src/flows/TrackerSourceDialogs.tsx | 8 +- frontend/src/flows/mcpSourceCopy.ts | 34 + frontend/src/flows/useMCPRequest.ts | 33 + frontend/src/layout/MobileMore.tsx | 2 +- frontend/src/layout/Sidebar.tsx | 2 +- frontend/src/lib/batchIngest.ts | 7 +- .../src/lib/dashboardSessionProtection.ts | 175 + frontend/src/lib/dashboardSourceReads.test.ts | 84 + frontend/src/lib/dashboardTransport.test.ts | 218 + frontend/src/lib/dashboardTransport.ts | 51 + frontend/src/lib/fileIngest.ts | 5 +- frontend/src/lib/folderUpload.ts | 3 +- frontend/src/lib/joinActions.ts | 12 +- frontend/src/lib/knowledgeSources.test.ts | 171 +- frontend/src/lib/knowledgeSources.ts | 212 +- frontend/src/lib/state.ts | 4 - frontend/src/lib/vitals.protection.test.ts | 22 + frontend/src/lib/vitals.test.ts | 5 + frontend/src/lib/vitals.ts | 3 +- frontend/src/test/mcpSources.ts | 36 + frontend/src/views/Browse.rows.test.tsx | 6 +- frontend/src/views/Browse.tsx | 8 +- frontend/src/views/Code.tsx | 40 +- frontend/src/views/CollectionSharing.test.tsx | 4 +- frontend/src/views/ConnectedAccounts.test.tsx | 269 - frontend/src/views/ConnectedAccounts.tsx | 217 - frontend/src/views/Conversations.tsx | 2 +- frontend/src/views/Documents.all.test.tsx | 5 +- .../src/views/Documents.download.test.tsx | 2 +- frontend/src/views/Documents.drag.test.tsx | 1 + frontend/src/views/Documents.restore.test.tsx | 2 +- frontend/src/views/Documents.tsx | 6 +- frontend/src/views/KnowledgeGaps.test.tsx | 2 +- frontend/src/views/KnowledgeGaps.tsx | 2 +- .../src/views/LibraryCollections.test.tsx | 1 + frontend/src/views/LibraryCollections.tsx | 2 +- frontend/src/views/LibraryTree.tsx | 2 +- frontend/src/views/MCPSources.test.tsx | 145 + frontend/src/views/MCPSources.tsx | 197 + frontend/src/views/ModelsSettings.tsx | 8 +- frontend/src/views/Profile.tsx | 6 +- frontend/src/views/QueryHistorySources.tsx | 3 +- frontend/src/views/Recent.lists.test.tsx | 1 + frontend/src/views/Recent.tsx | 6 +- frontend/src/views/RepoDocs.test.tsx | 2 + frontend/src/views/RepoDocs.tsx | 2 +- frontend/src/views/Setup.title.test.tsx | 6 +- frontend/src/views/Setup.tsx | 6 +- frontend/src/views/SourcesList.test.tsx | 30 + frontend/src/views/SourcesList.tsx | 93 +- frontend/src/views/StructureTab.tsx | 13 +- frontend/src/views/Tasks.tsx | 8 +- frontend/src/views/Tokens.tsx | 5 +- frontend/src/views/TrackerSources.tsx | 8 +- frontend/src/views/WebhooksSection.tsx | 3 +- frontend/src/views/admin/Blacklist.tsx | 6 +- .../src/views/admin/DeploymentSettings.tsx | 4 +- frontend/src/views/admin/Duplicates.tsx | 14 +- frontend/src/views/admin/Erasures.tsx | 2 +- frontend/src/views/admin/OrgGuardrails.tsx | 6 +- frontend/src/views/admin/Policies.tsx | 4 +- .../src/views/admin/ProjectionFailures.tsx | 4 +- frontend/src/views/admin/Proposals.tsx | 2 +- frontend/src/views/admin/Repairs.tsx | 16 +- frontend/src/views/admin/ReviewQueue.tsx | 8 +- frontend/src/views/admin/Spending.tsx | 2 +- frontend/src/views/admin/Users.tsx | 2 +- frontend/src/views/assistant/Chat.tsx | 6 +- frontend/src/views/assistant/Dock.tsx | 2 +- frontend/src/views/assistant/SearchAnswer.tsx | 4 +- frontend/src/views/assistant/cards/Card.tsx | 1 + .../src/views/assistant/cards/Starters.tsx | 2 +- .../src/views/assistant/cards/TuneBody.tsx | 2 +- .../src/views/assistant/cards/cardStore.ts | 3 +- frontend/src/views/assistant/chatStore.ts | 9 +- frontend/src/views/registry.ts | 1 - frontend/vite.config.ts | 3 + llms.txt | 5 + scripts/ops/qualify_mcp_source_scale.py | 305 ++ scripts/ops/qualify_mcp_sources.py | 319 ++ sdk/python/README.md | 6 + sdk/python/SESSION_PROTECTION.md | 54 + sdk/python/loom/cli.py | 37 +- sdk/python/loom/cli_context.py | 283 ++ sdk/python/loom/client.py | 139 +- sdk/python/loom/ops.py | 629 ++- sdk/python/loom/session_protection.py | 13 + sdk/python/loom/source_cli.py | 513 ++ sdk/python/loom/transport.py | 109 +- .../tests/qualify_cli_source_context.py | 171 + sdk/python/tests/test_cli_context.py | 304 ++ sdk/python/tests/test_source_cli.py | 558 +++ sdk/ruby/README.md | 4 + sdk/ruby/SESSION_PROTECTION.md | 33 + sdk/ruby/lib/clickhouse/loom/client.rb | 76 +- .../lib/clickhouse/loom/generated/errors.rb | 12 +- sdk/ruby/lib/clickhouse/loom/generated/ops.rb | 126 +- .../lib/clickhouse/loom/session_protection.rb | 246 + sdk/ruby/test/session_protection_http_test.rb | 257 + sdk/ruby/test/session_protection_test.rb | 188 + sdk/rust/README.md | 4 + sdk/rust/SESSION_PROTECTION.md | 41 + sdk/rust/src/client.rs | 56 +- sdk/rust/src/lib.rs | 2 + sdk/rust/src/session_protection.rs | 528 ++ sdk/rust/tests/client.rs | 3 + .../network_cases/session_protection_http.rs | 497 ++ sdk/typescript/README.md | 29 +- sdk/typescript/src/browser-download.test.ts | 123 + sdk/typescript/src/browser-protection.ts | 182 + sdk/typescript/src/index.ts | 2 + sdk/typescript/src/session-protection.ts | 30 +- .../src/source-client-readiness.test.ts | 356 ++ sdk/typescript/src/transport.ts | 21 +- server/cli/_client.py | 4 + server/cli/_session_context.py | 201 + server/cli/app.py | 21 +- server/cli/import_recall.py | 11 +- server/cli/knowledge_source.py | 257 +- server/cli/login.py | 8 + server/cli/okf.py | 20 +- server/cli/shell.py | 34 +- .../mcp_source_qualification_fixtures.py | 361 ++ .../mcp_source_qualification_servers.py | 269 + .../mcp_source_scale_acceptance.py | 233 + .../integration/mcp_source_scale_fixtures.py | 269 + tests/integration/mcp_source_scale_metrics.py | 139 + tests/integration/mcp_source_scale_servers.py | 103 + .../test_mcp_source_qualification.py | 542 ++ tests/unit/snapshots/cli_help.json | 144 +- tests/unit/snapshots/cli_tree.json | 4437 ++++++++++++++++- tests/unit/test_cli_knowledge_source.py | 240 +- .../test_cli_knowledge_source_installed.py | 114 + tests/unit/test_cli_source_context.py | 173 + .../unit/test_sdk_source_client_readiness.py | 313 ++ tests/unit/test_sdk_source_download.py | 164 + 240 files changed, 18102 insertions(+), 3298 deletions(-) create mode 100644 .github/workflows/mcp-source-qualification.yml create mode 100644 .github/workflows/mcp-source-scale.yml create mode 100644 docs/architecture/source-cli.md create mode 100644 docs/guides/mcp-source-cli.md delete mode 100644 docs/reference/operations/connection.md delete mode 100644 frontend/e2e/connected-accounts.spec.ts create mode 100644 frontend/e2e/dashboard-session-protection.spec.ts create mode 100644 frontend/e2e/sessionProtectionHarness.ts create mode 100644 frontend/src/api/adminReadRoutes.ts delete mode 100644 frontend/src/api/connections.test.ts delete mode 100644 frontend/src/api/connections.ts create mode 100644 frontend/src/api/mcpSources.test.ts create mode 100644 frontend/src/api/mcpSources.ts delete mode 100644 frontend/src/api/sourcePush.ts create mode 100644 frontend/src/flows/MCPConnectionStep.test.tsx create mode 100644 frontend/src/flows/MCPConnectionStep.tsx create mode 100644 frontend/src/flows/MCPLiveRead.test.tsx create mode 100644 frontend/src/flows/MCPLiveRead.tsx create mode 100644 frontend/src/flows/MCPResourceBrowser.test.tsx create mode 100644 frontend/src/flows/MCPResourceBrowser.tsx create mode 100644 frontend/src/flows/MCPSourceSetup.protection.test.tsx create mode 100644 frontend/src/flows/MCPSourceSetup.test.tsx create mode 100644 frontend/src/flows/MCPSourceSetup.tsx delete mode 100644 frontend/src/flows/SourcePushDialog.test.tsx delete mode 100644 frontend/src/flows/SourcePushDialog.tsx create mode 100644 frontend/src/flows/mcpSourceCopy.ts create mode 100644 frontend/src/flows/useMCPRequest.ts create mode 100644 frontend/src/lib/dashboardSessionProtection.ts create mode 100644 frontend/src/lib/dashboardSourceReads.test.ts create mode 100644 frontend/src/lib/dashboardTransport.test.ts create mode 100644 frontend/src/lib/dashboardTransport.ts create mode 100644 frontend/src/lib/vitals.protection.test.ts create mode 100644 frontend/src/test/mcpSources.ts delete mode 100644 frontend/src/views/ConnectedAccounts.test.tsx delete mode 100644 frontend/src/views/ConnectedAccounts.tsx create mode 100644 frontend/src/views/MCPSources.test.tsx create mode 100644 frontend/src/views/MCPSources.tsx create mode 100644 scripts/ops/qualify_mcp_source_scale.py create mode 100644 scripts/ops/qualify_mcp_sources.py create mode 100644 sdk/python/SESSION_PROTECTION.md create mode 100644 sdk/python/loom/cli_context.py create mode 100644 sdk/python/loom/source_cli.py create mode 100644 sdk/python/tests/qualify_cli_source_context.py create mode 100644 sdk/python/tests/test_cli_context.py create mode 100644 sdk/python/tests/test_source_cli.py create mode 100644 sdk/ruby/SESSION_PROTECTION.md create mode 100644 sdk/ruby/lib/clickhouse/loom/session_protection.rb create mode 100644 sdk/ruby/test/session_protection_http_test.rb create mode 100644 sdk/ruby/test/session_protection_test.rb create mode 100644 sdk/rust/SESSION_PROTECTION.md create mode 100644 sdk/rust/src/session_protection.rs create mode 100644 sdk/rust/tests/network_cases/session_protection_http.rs create mode 100644 sdk/typescript/src/browser-download.test.ts create mode 100644 sdk/typescript/src/browser-protection.ts create mode 100644 sdk/typescript/src/source-client-readiness.test.ts create mode 100644 server/cli/_session_context.py create mode 100644 tests/integration/mcp_source_qualification_fixtures.py create mode 100644 tests/integration/mcp_source_qualification_servers.py create mode 100644 tests/integration/mcp_source_scale_acceptance.py create mode 100644 tests/integration/mcp_source_scale_fixtures.py create mode 100644 tests/integration/mcp_source_scale_metrics.py create mode 100644 tests/integration/mcp_source_scale_servers.py create mode 100644 tests/integration/test_mcp_source_qualification.py create mode 100644 tests/unit/test_cli_knowledge_source_installed.py create mode 100644 tests/unit/test_cli_source_context.py create mode 100644 tests/unit/test_sdk_source_client_readiness.py create mode 100644 tests/unit/test_sdk_source_download.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1258482052..d36f3bda4d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -186,6 +186,8 @@ jobs: run: | uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + - name: Install the maintained Python SDK for its unit request contracts + run: uv pip install --no-deps -e sdk/python - name: Fetch origin/main for the migration-number check run: git fetch --no-tags --depth=1 origin +refs/heads/main:refs/remotes/origin/main # The clickhouse binary (as clickhouse-local and clickhouse-format) for the @@ -439,6 +441,7 @@ jobs: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + fetch-depth: 2 - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ env.NODE_VERSION }} @@ -458,6 +461,43 @@ jobs: run: npx --yes @taplo/cli@0.7.0 format --check - name: shfmt run: git ls-files '*.sh' ':!tests/fixtures' | xargs shfmt -d + - name: Render changed-source formatting candidate after failure + if: failure() + run: | + python3 - <<'PY' + import os + import subprocess + from pathlib import Path + + changed = subprocess.check_output([ + "git", "diff", "-z", "--name-only", "--diff-filter=ACMR", "HEAD^1", "HEAD" + ], text=True).split("\0") + selected = [p for p in changed if p.endswith((".ts", ".tsx", ".md", ".yml", ".yaml"))] + if len(selected) > 512 or any(Path(p).is_symlink() for p in selected): + raise SystemExit("Formatting candidate scope refused") + for suffixes, command in ( + ((".ts", ".tsx"), ["npx", "--yes", "@biomejs/biome@2.5.14", "format", "--write"]), + ((".md", ".yml", ".yaml"), ["npx", "--yes", "prettier@3.9.9", "--write", "--log-level", "warn"]), + ): + files = [p for p in selected if p.endswith(suffixes)] + for offset in range(0, len(files), 32): + subprocess.run([ + *command, *[str(Path(p).resolve()) for p in files[offset:offset + 32]] + ], check=True) + patch = subprocess.check_output([ + "git", "diff", "--no-ext-diff", "--unified=3", "--", *selected + ]) if selected else b"" + if len(patch) > 32 * 1024 * 1024: + raise SystemExit("Formatting candidate size refused") + Path(os.environ["RUNNER_TEMP"], "format-candidate.patch").write_bytes(patch) + PY + - name: Upload formatting candidate + if: failure() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: changed-source-format-candidate + path: ${{ runner.temp }}/format-candidate.patch + if-no-files-found: error helm: needs: validate-ref @@ -1315,7 +1355,20 @@ jobs: - name: Resolve dependencies for this toolchain run: cargo generate-lockfile - name: Rust formatting + id: rust-format run: cargo fmt --check + - name: Render Rust formatting candidate after failure + if: failure() && steps.rust-format.outcome == 'failure' + run: | + cargo fmt + git diff --no-ext-diff --unified=3 -- '*.rs' > "$RUNNER_TEMP/rust-format-candidate.patch" + - name: Upload Rust formatting candidate + if: failure() && steps.rust-format.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: rust-format-${{ matrix.rust }} + path: ${{ runner.temp }}/rust-format-candidate.patch + if-no-files-found: error - name: Unit, HTTP contract and documentation tests run: cargo test --locked - name: Lint the library, tests and examples @@ -1358,7 +1411,18 @@ jobs: # server's registry; a server change that alters a # request or response shape must regenerate them in the same PR. - name: generated ops.ts is current + id: generated-ts run: python scripts/codegen/sdk_ts_gen.py --check + - name: Render TypeScript contract candidate after failure + if: failure() && steps.generated-ts.outcome == 'failure' + run: python scripts/codegen/sdk_ts_gen.py + - name: Upload TypeScript contract candidate + if: failure() && steps.generated-ts.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: generated-typescript-contract + path: sdk/typescript/src/generated/ops.ts + if-no-files-found: error - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: node-version: ${{ env.NODE_VERSION }} diff --git a/.github/workflows/mcp-source-qualification.yml b/.github/workflows/mcp-source-qualification.yml new file mode 100644 index 0000000000..04a452721d --- /dev/null +++ b/.github/workflows/mcp-source-qualification.yml @@ -0,0 +1,286 @@ +name: MCP source functional qualification + +on: + pull_request: + paths: + - .github/workflows/mcp-source-qualification.yml + - .github/workflows/mcp-source-lifecycle.yml + - scripts/ops/qualify_mcp_sources.py + - tests/integration/test_mcp_source_qualification.py + - tests/integration/mcp_source_qualification*.py + - server/knowledge/** + - server/clients/mcp_source.py + - server/auth/** + - server/core/** + - server/identity/** + - server/memory/** + - server/embedding/** + - server/settings/** + - server/operations/** + - server/transport/** + - server/workers/** + - server/storage/** + - server/main.py + - sdk/python/** + - sdk/ruby/** + - schemas/** + - dev/ci_start_clickhouse.sh + - dev/ci_start_postgres.sh + - dev/clickhouse_release.sh + - pyproject.toml + - uv.lock + workflow_dispatch: + inputs: + sha: + description: Exact commit SHA to qualify + required: true + type: string + +permissions: + contents: read + +env: + PYTHON_VERSION: "3.12" + UV_VERSION: "0.12.19" + +jobs: + ruby-client: + name: Ruby protected source client + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Validate a dispatched commit + if: github.event_name == 'workflow_dispatch' + env: + REQUESTED_SHA: ${{ inputs.sha }} + run: '[[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout: /sdk/ruby/ + sparse-checkout-cone-mode: false + - name: Install the SDK test dependencies + working-directory: sdk/ruby + run: | + ruby --version + bundle config set --local path "$RUNNER_TEMP/mcp-ruby-bundle" + bundle install --jobs 4 --retry 2 + - name: Run the SDK tests including protected request admission + working-directory: sdk/ruby + run: bundle exec rake test + + clickhouse: + name: Resolve the ClickHouse release + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + image: ${{ steps.resolve.outputs.image }} + steps: + - name: Validate a dispatched commit + if: github.event_name == 'workflow_dispatch' + env: + REQUESTED_SHA: ${{ inputs.sha }} + run: '[[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout: /dev/clickhouse_release.sh + sparse-checkout-cone-mode: false + - id: resolve + run: | + image=$(bash dev/clickhouse_release.sh) + echo "image=$image" >> "$GITHUB_OUTPUT" + + qualification: + name: Functional and privacy (${{ matrix.authority }}) + needs: clickhouse + runs-on: ubuntu-latest + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + authority: [clickhouse, postgres] + env: + LOOM_CLICKHOUSE_IMAGE: ${{ needs.clickhouse.outputs.image }} + LOOM_CH_HOST: 127.0.0.1 + LOOM_CH_PORT: "8123" + LOOM_CH_USER: loom + LOOM_CH_READER_USER: loom_reader + LOOM_CH_PASSWORD: loomdev + LOOM_CH_DATABASE: loom + LOOM_CH_SECURE: "false" + LOOM_PG_IMAGE: postgres:16 + LOOM_PG_STANDBY: "1" + LOOM_STORAGE_AUTHORITY: ${{ matrix.authority }} + LOOM_AUTH_REQUIRED: "true" + LOOM_BIND_HOST: 127.0.0.1 + LOOM_LLM_PROVIDER: fake + LOOM_LLM_FALLBACK_MODEL: "" + LOOM_EMBEDDING_MODEL: fake-ngram-1024 + LOOM_BACKGROUND_WORKERS: "off" + LOOM_BOOT_MIGRATE: "true" + LOOM_ENV_FILE: "" + LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED: "true" + LOOM_DOCUMENT_OBJECT_STORE: s3 + LOOM_DOCUMENT_S3_ENDPOINT_URL: http://127.0.0.1:9000 + LOOM_DOCUMENT_S3_REGION: us-east-1 + AWS_DEFAULT_REGION: us-east-1 + AWS_EC2_METADATA_DISABLED: "true" + LOOM_MCP_SOURCE_QUALIFICATION: github-owned + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/*/ + /server/ + /scripts/ + /schemas/ + /dev/ + /deploy/ + /sdk/ + /extractor/ + /tests/__init__.py + /tests/conftest.py + /tests/integration/__init__.py + /tests/integration/conftest.py + /tests/integration/_resources.py + /tests/integration/_redact.py + /tests/integration/test_mcp_source_qualification.py + /tests/integration/mcp_source_qualification*.py + !/tests/unit/test_term_leg.py + !/tests/integration/test_term_leg.py + !/integrations/librechat/qualification/cases.json + !/integrations/librechat/qualification/fixture.json + !/integrations/librechat/qualification/qualify.py + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + id: python + with: + python-version: ${{ env.PYTHON_VERSION }} + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: ${{ env.UV_VERSION }} + enable-cache: false + - name: Install the locked dependencies + run: | + uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code >/dev/null 2>&1 + uv pip install --no-deps -e sdk/python >/dev/null 2>&1 + echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + - name: Initialize fresh synthetic secrets and exact ownership + id: ownership + env: + AUTHORITY: ${{ matrix.authority }} + run: | + python - <<'PY' + import os + import secrets + import subprocess + + values = { + "QUALIFICATION_SHA": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + "LOOM_JWT_SECRET": secrets.token_hex(32), + "AWS_ACCESS_KEY_ID": secrets.token_hex(16), + "AWS_SECRET_ACCESS_KEY": secrets.token_hex(32), + "LOOM_DOCUMENT_S3_BUCKET": "mcp-qualification-" + secrets.token_hex(12), + "LOOM_INSTANCE_LABEL": "mcp-source-qualification", + "LOOM_CH_CONTAINER": "mcp-source-qualification-ch", + "LOOM_PG_CONTAINER": "mcp-source-qualification-pg", + "LOOM_PG_DSN": "postgres://loom:loomdev@127.0.0.1:5432/loom" if os.environ["AUTHORITY"] == "postgres" else "", + } + values["LOOM_BUILD_COMMIT"] = values["QUALIFICATION_SHA"] + with open(os.environ["GITHUB_ENV"], "a") as output: + for key, value in values.items(): + output.write(key + "=" + value + "\n") + PY + - name: Refuse preexisting fixture containers + id: fresh + run: | + for container in "$LOOM_CH_CONTAINER" "$LOOM_PG_CONTAINER" "$LOOM_PG_CONTAINER-standby" mcp-source-qualification-objects; do + if docker container inspect "$container" >/dev/null 2>&1; then + echo "MCP source qualification: status=refused" + exit 1 + fi + done + if docker network inspect "$LOOM_PG_CONTAINER-net" >/dev/null 2>&1; then + echo "MCP source qualification: status=refused" + exit 1 + fi + - name: Start the owned ClickHouse with Keeper + id: ch + run: bash dev/ci_start_clickhouse.sh >/dev/null 2>&1 + - name: Start the owned Postgres 16 authority and synchronous standby + id: pg + if: matrix.authority == 'postgres' + run: bash dev/ci_start_postgres.sh >/dev/null 2>&1 + - name: Start the owned originals store + id: objects + run: | + docker run -d --name mcp-source-qualification-objects -p 127.0.0.1:9000:9000 \ + -e MINIO_ROOT_USER="$AWS_ACCESS_KEY_ID" -e MINIO_ROOT_PASSWORD="$AWS_SECRET_ACCESS_KEY" \ + minio/minio:RELEASE.2025-04-22T22-12-26Z server /data >/dev/null 2>&1 + ready=0 + for attempt in $(seq 1 60); do + if curl --silent --fail http://127.0.0.1:9000/minio/health/ready >/dev/null 2>&1; then + ready=1 + break + fi + sleep 1 + done + test "$ready" = 1 + - name: Apply the normal schema journal + run: python -m server.core.schema.migrate >/dev/null 2>&1 + - name: Qualify the actual source pipeline and privacy cases + run: python -m scripts.ops.qualify_mcp_sources --result "$RUNNER_TEMP/qualification-report.json" + - name: Stop only this job's stores + id: cleanup + if: always() && steps.fresh.outcome == 'success' + env: + CH_STARTED: ${{ steps.ch.outcome }} + PG_STARTED: ${{ steps.pg.outcome }} + OBJECTS_STARTED: ${{ steps.objects.outcome }} + run: | + cleanup_status=0 + stop_owned() { + if docker container inspect "$1" >/dev/null 2>&1; then + docker rm -f -v "$1" >/dev/null 2>&1 || cleanup_status=1 + fi + } + if [ "$CH_STARTED" != '' ] && [ "$CH_STARTED" != 'skipped' ]; then + stop_owned "$LOOM_CH_CONTAINER" + fi + if [ "$PG_STARTED" != '' ] && [ "$PG_STARTED" != 'skipped' ]; then + stop_owned "$LOOM_PG_CONTAINER-standby" + stop_owned "$LOOM_PG_CONTAINER" + if docker network inspect "$LOOM_PG_CONTAINER-net" >/dev/null 2>&1; then + docker network rm "$LOOM_PG_CONTAINER-net" >/dev/null 2>&1 || cleanup_status=1 + fi + fi + if [ "$OBJECTS_STARTED" != '' ] && [ "$OBJECTS_STARTED" != 'skipped' ]; then + stop_owned mcp-source-qualification-objects + fi + echo "MCP source qualification: cleanup_status=$cleanup_status" + echo "status=$cleanup_status" >> "$GITHUB_OUTPUT" + exit "$cleanup_status" + - name: Finalize the result after store cleanup + if: always() + env: + CLEANUP_STATUS: ${{ steps.cleanup.outputs.status || '1' }} + run: >- + python -m scripts.ops.qualify_mcp_sources + --result "$RUNNER_TEMP/qualification-report.json" + --cleanup-status "$CLEANUP_STATUS" + - name: Upload only the bounded qualification report + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mcp-source-qualification-${{ matrix.authority }} + path: ${{ runner.temp }}/qualification-report.json + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/mcp-source-scale.yml b/.github/workflows/mcp-source-scale.yml new file mode 100644 index 0000000000..15f5a702c4 --- /dev/null +++ b/.github/workflows/mcp-source-scale.yml @@ -0,0 +1,271 @@ +name: MCP source scale qualification + +on: + pull_request: + paths: + - .github/workflows/mcp-source-scale.yml + - .github/workflows/mcp-source-lifecycle.yml + - scripts/ops/qualify_mcp_source_scale.py + - tests/integration/mcp_source_scale*.py + - tests/integration/mcp_source_qualification*.py + - server/knowledge/** + - server/clients/mcp_source.py + - server/auth/** + - server/core/** + - server/identity/** + - server/memory/** + - server/embedding/** + - server/settings/** + - server/operations/** + - server/transport/** + - server/workers/** + - server/storage/** + - server/main.py + - sdk/python/** + - schemas/** + - dev/ci_start_clickhouse.sh + - dev/ci_start_postgres.sh + - dev/clickhouse_release.sh + - pyproject.toml + - uv.lock + workflow_dispatch: + inputs: + sha: + description: Exact commit SHA to qualify + required: true + type: string + +permissions: + contents: read + +env: + PYTHON_VERSION: "3.12" + UV_VERSION: "0.12.19" + +jobs: + clickhouse: + name: Resolve the ClickHouse release + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + image: ${{ steps.resolve.outputs.image }} + steps: + - name: Validate a dispatched commit + if: github.event_name == 'workflow_dispatch' + env: + REQUESTED_SHA: ${{ inputs.sha }} + run: '[[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout: /dev/clickhouse_release.sh + sparse-checkout-cone-mode: false + - id: resolve + run: | + image=$(bash dev/clickhouse_release.sh) + echo "image=$image" >> "$GITHUB_OUTPUT" + + qualification: + name: Capacity and scheduling (${{ matrix.authority }}) + needs: clickhouse + runs-on: ubuntu-latest + timeout-minutes: 45 + strategy: + fail-fast: false + matrix: + authority: [clickhouse, postgres] + env: + LOOM_CLICKHOUSE_IMAGE: ${{ needs.clickhouse.outputs.image }} + LOOM_CH_HOST: 127.0.0.1 + LOOM_CH_PORT: "8123" + LOOM_CH_USER: loom + LOOM_CH_READER_USER: loom_reader + LOOM_CH_PASSWORD: loomdev + LOOM_CH_DATABASE: loom + LOOM_CH_SECURE: "false" + LOOM_PG_IMAGE: postgres:16 + LOOM_PG_STANDBY: "1" + LOOM_STORAGE_AUTHORITY: ${{ matrix.authority }} + LOOM_AUTH_REQUIRED: "true" + LOOM_BIND_HOST: 127.0.0.1 + LOOM_LLM_PROVIDER: fake + LOOM_LLM_FALLBACK_MODEL: "" + LOOM_EMBEDDING_MODEL: fake-ngram-1024 + LOOM_BACKGROUND_WORKERS: "off" + LOOM_BOOT_MIGRATE: "true" + LOOM_ENV_FILE: "" + LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED: "true" + LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED: "true" + LOOM_DOCUMENT_OBJECT_STORE: s3 + LOOM_DOCUMENT_S3_ENDPOINT_URL: http://127.0.0.1:9000 + LOOM_DOCUMENT_S3_REGION: us-east-1 + AWS_DEFAULT_REGION: us-east-1 + AWS_EC2_METADATA_DISABLED: "true" + LOOM_MCP_SOURCE_QUALIFICATION: github-owned + LOOM_MCP_SOURCE_SCALE: github-owned + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_PAGE_SIZE: "100" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_SCAN_PAGES: "16" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_READY: "256" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_GLOBAL: "16" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_PER_ORG: "4" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_PER_ENDPOINT: "2" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_DOCUMENTS: "1" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_SOURCE_SECONDS: "5" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_QUERY_ROWS: "1000000" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_QUERY_BYTES: "67108864" + LOOM_KNOWLEDGE_SOURCE_MCP_SCHEDULE_QUERY_SECONDS: "5" + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/*/ + /server/ + /scripts/ + /schemas/ + /dev/ + /deploy/ + /sdk/ + /extractor/ + /tests/__init__.py + /tests/conftest.py + /tests/integration/__init__.py + /tests/integration/conftest.py + /tests/integration/_resources.py + /tests/integration/_redact.py + /tests/integration/mcp_source_scale*.py + /tests/integration/mcp_source_qualification*.py + !/tests/unit/test_term_leg.py + !/tests/integration/test_term_leg.py + !/integrations/librechat/qualification/cases.json + !/integrations/librechat/qualification/fixture.json + !/integrations/librechat/qualification/qualify.py + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + id: python + with: + python-version: ${{ env.PYTHON_VERSION }} + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: ${{ env.UV_VERSION }} + enable-cache: false + - name: Install the locked dependencies + run: | + uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code >/dev/null 2>&1 + uv pip install --no-deps -e sdk/python >/dev/null 2>&1 + echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + - name: Initialize fresh synthetic secrets and exact ownership + id: ownership + env: + AUTHORITY: ${{ matrix.authority }} + run: | + python - <<'PY' + import os + import secrets + import subprocess + + values = { + "QUALIFICATION_SHA": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(), + "LOOM_JWT_SECRET": secrets.token_hex(32), + "AWS_ACCESS_KEY_ID": secrets.token_hex(16), + "AWS_SECRET_ACCESS_KEY": secrets.token_hex(32), + "LOOM_DOCUMENT_S3_BUCKET": "mcp-qualification-" + secrets.token_hex(12), + "LOOM_INSTANCE_LABEL": "mcp-source-scale", + "LOOM_CH_CONTAINER": "mcp-source-scale-ch", + "LOOM_PG_CONTAINER": "mcp-source-scale-pg", + "LOOM_PG_DSN": "postgres://loom:loomdev@127.0.0.1:5432/loom" if os.environ["AUTHORITY"] == "postgres" else "", + } + values["LOOM_BUILD_COMMIT"] = values["QUALIFICATION_SHA"] + with open(os.environ["GITHUB_ENV"], "a") as output: + for key, value in values.items(): + output.write(key + "=" + value + "\n") + PY + - name: Refuse preexisting fixture containers + id: fresh + run: | + for container in "$LOOM_CH_CONTAINER" "$LOOM_PG_CONTAINER" "$LOOM_PG_CONTAINER-standby" mcp-source-scale-objects; do + if docker container inspect "$container" >/dev/null 2>&1; then + echo "MCP source qualification: status=refused" + exit 1 + fi + done + if docker network inspect "$LOOM_PG_CONTAINER-net" >/dev/null 2>&1; then + echo "MCP source qualification: status=refused" + exit 1 + fi + - name: Start the owned ClickHouse with Keeper + id: ch + run: bash dev/ci_start_clickhouse.sh >/dev/null 2>&1 + - name: Start the owned Postgres 16 authority and synchronous standby + id: pg + if: matrix.authority == 'postgres' + run: bash dev/ci_start_postgres.sh >/dev/null 2>&1 + - name: Start the owned originals store + id: objects + run: | + docker run -d --name mcp-source-scale-objects -p 127.0.0.1:9000:9000 \ + -e MINIO_ROOT_USER="$AWS_ACCESS_KEY_ID" -e MINIO_ROOT_PASSWORD="$AWS_SECRET_ACCESS_KEY" \ + minio/minio:RELEASE.2025-04-22T22-12-26Z server /data >/dev/null 2>&1 + ready=0 + for attempt in $(seq 1 60); do + if curl --silent --fail http://127.0.0.1:9000/minio/health/ready >/dev/null 2>&1; then + ready=1 + break + fi + sleep 1 + done + test "$ready" = 1 + - name: Apply the normal schema journal + run: python -m server.core.schema.migrate >/dev/null 2>&1 + - name: Qualify the frozen scale contract + run: python -m scripts.ops.qualify_mcp_source_scale --result "$RUNNER_TEMP/scale-report.json" + - name: Stop only this job's stores + id: cleanup + if: always() && steps.fresh.outcome == 'success' + env: + CH_STARTED: ${{ steps.ch.outcome }} + PG_STARTED: ${{ steps.pg.outcome }} + OBJECTS_STARTED: ${{ steps.objects.outcome }} + run: | + cleanup_status=0 + stop_owned() { + if docker container inspect "$1" >/dev/null 2>&1; then + docker rm -f -v "$1" >/dev/null 2>&1 || cleanup_status=1 + fi + } + if [ "$CH_STARTED" != '' ] && [ "$CH_STARTED" != 'skipped' ]; then + stop_owned "$LOOM_CH_CONTAINER" + fi + if [ "$PG_STARTED" != '' ] && [ "$PG_STARTED" != 'skipped' ]; then + stop_owned "$LOOM_PG_CONTAINER-standby" + stop_owned "$LOOM_PG_CONTAINER" + if docker network inspect "$LOOM_PG_CONTAINER-net" >/dev/null 2>&1; then + docker network rm "$LOOM_PG_CONTAINER-net" >/dev/null 2>&1 || cleanup_status=1 + fi + fi + if [ "$OBJECTS_STARTED" != '' ] && [ "$OBJECTS_STARTED" != 'skipped' ]; then + stop_owned mcp-source-scale-objects + fi + echo "MCP source qualification: cleanup_status=$cleanup_status" + echo "status=$cleanup_status" >> "$GITHUB_OUTPUT" + exit "$cleanup_status" + - name: Finalize the result after store cleanup + if: always() + env: + CLEANUP_STATUS: ${{ steps.cleanup.outputs.status || '1' }} + run: >- + python -m scripts.ops.qualify_mcp_source_scale + --result "$RUNNER_TEMP/scale-report.json" + --cleanup-status "$CLEANUP_STATUS" + - name: Upload only the bounded qualification report + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mcp-source-scale-${{ matrix.authority }} + path: ${{ runner.temp }}/scale-report.json + if-no-files-found: error + retention-days: 7 diff --git a/docs/architecture/source-cli.md b/docs/architecture/source-cli.md new file mode 100644 index 0000000000..614ab61f34 --- /dev/null +++ b/docs/architecture/source-cli.md @@ -0,0 +1,83 @@ +# Source CLI execution + +Source controls execute in the installed Python SDK so browse and read use the +maintained session-protection transport. The server and SDK remain separate +Python distributions. The server parser is available without loading the SDK; +execution requires a matching SDK installation. + +## Distribution boundary + +`server/cli/knowledge_source.py` owns the server command paths and common flags. +It imports `loom.source_cli` only when executing a command, checks +`SOURCE_CLI_API`, and calls `run_server_entry(args)`. An absent or incompatible +SDK produces an actionable error. There is no source-checkout path discovery or +bare HTTP fallback. + +`sdk/python/loom/source_cli.py` owns exact operation fields, request-file parsing, +credential input, the standalone module parser and execution. The SDK wheel's +existing package includes the helper. Hosted contract tests compare both parser +trees and compare the helper's field sets with the server wire models. This +keeps server-only help and CLI snapshot generation independent of SDK imports. + +## Retained authority + +The trusted application provisions `SessionProtection` before private output and +persists its content-free pointer with `save_session_pointer`. Pointer persistence +is exclusive, mode 0600 and fsynced in an owned mode-0700 directory. Execution only +reopens existing authority with `open_session`; unknown or missing proof refuses. +The pointer and SDK authority must remain trusted application state across restore. + +`loom.cli_context.session_environment` creates a content-free environment capsule +that pins the pointer file and its expected SDK pointer. The trusted launcher retains +it unchanged across subprocesses, tasks and resumes. Automatic source commands require +the capsule to match `--session-file`; replacing the pointer with another family +refuses. A configured context is never repaired or replaced after failure. + +`call_source` binds that family to `Transport`. Writes and unknown routes enter the +same family's `automatic` context before constructing the transport. Only generated +SDK metadata classifies a known read-only operation. The maintained +transport performs final admission and response observation, including error +responses, before CLI output. Every dispatch disables transport retries and +rate-limit replay, supplies the original request UUID where present, and closes +the transport. Save reconciliation is an explicit inspection using that UUID. + +The server's `_client` JSON/raw-file boundary, async OKF/Recall writers and shell +search/transcript requests lazily restore the same capsule through `loom.cli_context`. +The delegated SDK CLI binds its maintained clients through the SDK observation and +automatic scopes. Unbound HTTP calls retain their ordinary behavior. A configured +context requires the matching installed SDK and refuses before an unobserved request +when that dependency is missing. Raw uploads use `Transport.request(content=...)`; +streaming uses the maintained `Transport.stream` through consumption and cleanup. + +Root `--request-intent explicit` binds one direct human dispatch. Its revocable +scope expires on return, including contexts copied by retained callbacks. SDK parser +arguments consume this intent once; no Agent, Transport or returned writer callback +stores it. A synchronous helper called from an active event loop creates and closes +its async client in a joined thread with copied context, without nesting event loops. + +## Invariants + +- One complete application session retains the same authority across tasks, + namespaces, credentials and server origins. Source content cannot choose it. +- CLI execution never creates a fresh family to recover from missing or protected + state. Direct user intent is a trusted application decision. +- Automatic guards apply to writes and unknown routes, including collection grants + and recording writes. A namespace change cannot clear protection. Generated + read-only operations remain available with the same response observation. +- Credentials come from explicit environment or private file/stdin inputs and + are excluded from request-file fields and diagnostics. +- Direct database administration and nonparticipating external clients are outside + this HTTP client qualification. Each application must retain contributing authority. + +## Source entry points + +- `server/cli/knowledge_source.py`: `register_knowledge_source_cli`, `_dispatch`. +- `sdk/python/loom/source_cli.py`: `run_server_entry`, `open_session`, `call_source`. +- `sdk/python/loom/cli_context.py`: `session_environment`, `request`, `stream`, `run_sync`. +- `server/cli/_session_context.py`: `invocation`, `send`, `post`. +- `tests/unit/test_cli_knowledge_source_installed.py`: installed parser and wire contracts. +- `sdk/python/tests/test_source_cli.py`: restored authority and actual SDK dispatch cases. + +The [source CLI guide](../guides/mcp-source-cli.md) describes fields, collection +destinations and reconciliation. Release qualification must exercise both +installed artifacts and actual protected browse/read before activation. diff --git a/docs/guides/mcp-source-cli.md b/docs/guides/mcp-source-cli.md new file mode 100644 index 0000000000..e799f62f26 --- /dev/null +++ b/docs/guides/mcp-source-cli.md @@ -0,0 +1,211 @@ +# Manage MCP sources from the CLI + +The Python SDK supplies source controls through `python -m loom.source_cli source`. +The server CLI exposes the same controls under `loom knowledge source` when the +matching-release `clickhouse-loom` SDK is installed alongside it. A server-only +installation can show command help but refuses execution with a dependency message. + +## Application-owned session authority + +Every command requires `--session-file`, an absolute path to an existing private +application-owned session pointer. The CLI reopens the maintained SDK's +`SessionProtection` and sends requests through its `Transport`. It does not create, +reset or repair session families. Missing pointers or proof refuse before dispatch. + +The trusted application provisions the pointer once, before a session receives +private output: + +```python +from pathlib import Path + +from loom.cli_context import session_environment +from loom.session_protection import SessionProtection +from loom.source_cli import save_session_pointer + +application = Path("application-state").absolute() +application.mkdir(mode=0o700) +family = SessionProtection.create(base=application / "families") +save_session_pointer(application / "session.json", family) +session_env = session_environment(str(application / "session.json")) +``` + +`save_session_pointer` creates an owned mode-0600 file exclusively and syncs it to +disk. Its directory must already be owned and mode 0700. Keep both the pointer and +its SDK authority. Replacing either with a clean family or restoring older state +breaks the application contract. Source responses must never select these paths. + +The trusted launcher merges `session_env` into every contributing command's inherited +environment and persists it unchanged for resume. Its `LOOM_SOURCE_SESSION_CONTEXT` +capsule names the pointer file and pins the expected SDK pointer. It contains no +credentials and grants no additional server authority. Replacing the file with a +different valid family refuses. The application must retain this same capsule across +namespaces, servers, credentials, subprocesses and automatic tasks. Source output +cannot select or replace it. + +`--intent automatic` is the default and requires that inherited capsule to match +`--session-file`. It enters the SDK's automatic guard for writes and operations +without generated read-only metadata, including grants and recording writes. After +private output protects the family, those automatic commands refuse; known read-only +operations remain available. A direct user action +may pass `--intent explicit`; its response is still observed before output. Explicit +intent must come from the application's user interaction, never from source content +or an automatic callback. + +The server CLI's common JSON/file helpers, shell search/transcript ingestion, Recall +HTTP imports, OKF requests and delegated SDK `call` requests restore the same inherited +context. Configured context without the matching installed SDK refuses. Unbound +ordinary commands retain their normal behavior. For a direct human write, the root +CLI accepts `loom --request-intent explicit ...`; SDK `call` also accepts that flag +after `call`. Intent ends with that dispatch and is never stored on a client. Later +automatic commands still use the protected capsule. Explicit source invocation may +use its own `--session-file` without an inherited capsule, but does not establish a +qualified automatic application session by itself. + +Direct database administration and nonparticipating external clients are outside +this HTTP client qualification. An application must retain every contributing +context and use participating request paths before claiming protection. See the SDK's +[session protection contract](../../sdk/python/SESSION_PROTECTION.md). +The [execution design](../architecture/source-cli.md) describes the distribution boundary. + +## Request and credential inputs + +Every operation accepts `--server-url`, `--org`, `--session-file`, +`--request-file` and `--token-file`. Request files contain one UTF-8 JSON object of +at most 1 MiB. Duplicate keys and unknown fields refuse without echoing their +values. `org` comes from `--org`. Where a namespace is accepted, `--namespace` may +supply it; a conflicting JSON `namespace` refuses. + +Credentials never travel in argv. `--token-file` reads an owned mode-0600 regular +file; otherwise the command uses `LOOM_API_KEY`. It does not borrow a saved human +token. Connection setup accepts `--bearer-file`; recording setup requires +`--credential-file`. Each secret is at most 64 KiB. A file argument of `-` reads +stdin, and only one input may consume stdin. Secret files and session pointers +cannot be symlinks or have multiple hard links. + +The examples below use application-supplied `LOOM_URL`, `LOOM_ORG`, +`APP_SESSION_FILE` and `APP_TOKEN_FILE`. For a direct user action: + +```bash +python -m loom.source_cli source connection profiles \ + --server-url "$LOOM_URL" --org "$LOOM_ORG" \ + --session-file "$APP_SESSION_FILE" --token-file "$APP_TOKEN_FILE" \ + --intent explicit +``` + +All commands return JSON. Paginated lists return their server continuation; pass +that exact `next_cursor` as `cursor` in another request with the same filters. +Browse returns only its declared first window. Inspect `complete`, `truncated`, +`limitations` and manual resource-ID support; a browse response is not proof of +complete enumeration or upstream permissions. + +## Connections and selected sources + +The request fields below exclude `org` and the separate secret input. Required +fields and bounds come from the [operations reference](../reference/operations.md). + +| Command after `source` | Operation | JSON request fields | +| --- | --- | --- | +| `connection profiles` | `knowledge.source.mcp_profiles` | `query`, `cursor`, `limit` | +| `connection connect` | `knowledge.connection.mcp_connect` | `profile_id`, `request_id`, `label` | +| `connection list` | `knowledge.connection.mcp_list` | `cursor`, `limit` | +| `connection inspect` | `knowledge.connection.mcp_inspect` | `slot`, `request_id` | +| `connection discover` | `knowledge.connection.mcp_discover` | `slot` | +| `connection browse` | `knowledge.connection.mcp_browse` | `slot`, `mode`, `query`, `limit` | +| `connection disconnect` | `knowledge.connection.mcp_disconnect` | `slot` | +| `preview`, `destination preview` | `knowledge.source.mcp_preview` | `namespace`, `slot`, `mode`, `reader_policy`, `resource_ids` | +| `add` | `knowledge.source.mcp_add` | Preview fields plus `request_id`, `label`, `confirm_copy_authority` | +| `update` | `knowledge.source.mcp_update` | `namespace`, `name`, `if_scope_revision`, `resource_ids`, `mode`, `label`, `confirm_copy_authority` | +| `list` | `knowledge.source.mcp_list` | `namespace`, `cursor`, `limit`, `include_retired` | +| `inspect` | `knowledge.source.mcp_inspect` | `namespace`, `name`, `slot`, `request_id` | +| `pause`, `resume`, `refresh` | `knowledge.source.mcp_pause`, `knowledge.source.mcp_resume`, `knowledge.source.mcp_refresh` | `namespace`, `name` | +| `read` | `knowledge.source.mcp_read` | `namespace`, `name`, `resource_id` | +| `remove` | `knowledge.source.mcp_remove` | `namespace`, `name`, `confirm`, `delete_documents` | + +Select an approved profile, connect with a client-generated canonical UUID, and +keep that UUID. Discover capabilities before browsing. Browse resources with +`mode: "resources"`, or an approved mapped search with `mode: "search"` and `query`. +An approved endpoint and supported capability do not verify remote identity. + +Preview an exact selection before adding it. A preview request file contains: + +```json +{ + "namespace": "col-research", + "slot": "20000000-0000-4000-8000-000000000002", + "mode": "snapshot", + "reader_policy": "owner_only", + "resource_ids": ["resource:one", "resource:two"] +} +``` + +Run `source preview` with `--request-file selection.json`. Its access rule explains +stored copies, collection grants, freshness and publication confirmation. Preview +grants no authority. Source modes are `live`, `snapshot` and `selected_refresh`. +Reader policies are `owner_only` and `collection_copy`. A collection copy requires +the server's operator approval, destination grants and explicit publication consent. +Future items are not included, and upstream ACL or deletion tracking is not implied. + +For `source add`, include `request_id` in the same file. Set +`confirm_copy_authority` only when authorized to publish that exact selection. +For `source update`, `resource_ids` is the complete replacement selection, and +`if_scope_revision` can reject concurrent changes. An audience change requires a +separate source registration and its access checks. + +`pause` and `connection disconnect` stop reads while retaining copies. Disconnect +does not revoke the upstream credential; follow the response's upstream action. +`remove` requires `confirm` to repeat the opaque source name. Its +`delete_documents` field explicitly requests asynchronous copy erasure; otherwise +copies remain. No command infers erasure from a failed read or missing resource. + +## Ordinary collection destinations + +| Command after `source destination` | Operation | JSON request fields | +| --- | --- | --- | +| `list` | `collection.list` | `limit`, `include_document_counts`, `cursor` | +| `create` | `collection.create` | `namespace`, `title`, `derive_name`, `parent`, `description` | +| `grants` | `grants.list` | `namespace`, `limit`, `cursor`, `fields` | +| `grant` | `grants.create` | `namespace`, `subject`, `role`, `granted_by`, `replace` | +| `preview` | `knowledge.source.mcp_preview` | The exact preview fields above | + +List collections and choose the returned namespace with the required destination +role. Create an ordinary top-level collection for a private destination, or set +`parent` to a team collection whose grants it should inherit. Explicit grants may +share a top-level collection. No source command creates a personal namespace or +replaces grants automatically. + +For example, `destination create` accepts +`{"namespace":"col-research","title":"Research"}`. Adding +`"parent":"col-team"` requests the inherited team destination. Inspect grants +and run the source access preview for the selected namespace and reader policy. +A grant listing is not a complete upstream reader list, and an `owner_only` source +still requires destination access. The server decides each grant and publication +request independently. + +## Uncertain outcomes and reconciliation + +The CLI disables transport retries and rate-limit replay for every command. It +never regenerates a request UUID or follows a failed save with another save. + +After an uncertain connect, run `connection inspect` with +`{"request_id":"10000000-0000-4000-8000-000000000001"}`. Preserve the original +UUID; inspect reports `absent`, `present` or `incomplete` reconciliation. An +incomplete result does not authorize another registration. + +After an uncertain source add, run `inspect` with the original `namespace`, `slot` +and `request_id`. A confirmed saved source can then be inspected by its opaque +`name`. A failed inspection is not evidence that the save was absent. Keep the +original request file and session proof after cancellation or interruption. + +## Recordings and retained sources + +`recording add` calls `knowledge.source.add` with `namespace`, `name`, +`kind: "recording"`, `config` and optional `dry_run`, plus the separate +`--credential-file`. `config` contains the recording provider and explicitly +selected recording IDs. `recording list` calls `knowledge.source.list` with +`namespace`; `recording sync-now` accepts `namespace`, `name` and optional `full`. + +`retained list`, `retained inspect` and `retained remove` expose ordinary source +listing, inspection and retirement. Inspection takes `namespace` and `name`; +removal also requires `confirm` and accepts `delete_documents`. Retained native +document sources remain unavailable for execution. Document setup and updates use +the MCP controls above. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 2bd191143d..268b686bf1 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -257,10 +257,39 @@ python scripts/codegen/docs_reference.py | `loom decisions extract` | Mine one knowledge document into decision records: the model reads the document whole (or in windows of whole sections past LOOM_MEMORY_DECISION_EXTRACT_WINDOW_CHARS; a heading over only an image and… | `--org`, `--namespace`, `--source-uri`, `--repo`, `--into`, `--max-per-section`, `--window-chars`, `--apply`, `--dry-run` | | `loom knowledge` | Knowledge documents and their sources. | | | `loom knowledge sync` | Run one sync pass over a repository namespace's document sources now: list each source's changed files (every file with --full), write the changed ones as documents and retire those a full listing no… | `--org`, `--namespace`, `--source`, `--full` | -| `loom knowledge source` | A namespace's document sources, over a running server. | | -| `loom knowledge source list` | List the namespace's sources, items and sync state. | `--namespace`, `--org`, `--server-url`, `--token` | -| `loom knowledge source add` | Register a source from links or items, probed with the credential before anything is stored (knowledge.source.add). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--kind`, `--link`, `--item-json`, `--include`, `--credential-file`, `--dry-run` | -| `loom knowledge source update` | Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update). | `--namespace`, `--org`, `--server-url`, `--token`, `--name`, `--link`, `--item-json`, `--include`, `--remove-link`, `--remove-item-json` | +| `loom knowledge source` | MCP sources, connections, collection destinations and recordings. | | +| `loom knowledge source preview` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source add` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source update` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source list` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source inspect` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source pause` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source resume` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source refresh` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source read` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source remove` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source connection` | | | +| `loom knowledge source connection profiles` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source connection connect` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent`, `--bearer-file` | +| `loom knowledge source connection list` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source connection inspect` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source connection discover` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source connection browse` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source connection disconnect` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source destination` | | | +| `loom knowledge source destination list` | | `--server-url`, `--org`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source destination create` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source destination grants` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source destination grant` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source destination preview` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source recording` | | | +| `loom knowledge source recording add` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent`, `--credential-file` | +| `loom knowledge source recording list` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source recording sync-now` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source retained` | | | +| `loom knowledge source retained list` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source retained inspect` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | +| `loom knowledge source retained remove` | | `--server-url`, `--org`, `--namespace`, `--request-file`, `--token-file`, `--session-file`, `--intent` | | `loom knowledge migrate-originals` | Move the document originals still held in ClickHouse, that a document, upload or ingestion needs, to LOOM_DOCUMENT_S3_BUCKET: each is copied to its own object, hash-verified and switched, fenced by… | `--org`, `--namespace`, `--dry-run` | | `loom export-okf` | Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. | `--server-url`, `--token`, `--org`, `--namespace`, `--out`, `--title`, `--include-tombstoned`, `--limit`, `--dry-run`, `--no-evidence`, `--no-links`, `--include-high` | | `loom import-okf` | Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. | ``, `--server-url`, `--token`, `--org`, `--namespace`, `--agent`, `--user-id`, `--session-id`, `--keep-sessions`, `--verify`, `--dry-run`, `--no-evidence`, `--no-lint`, `--force-import`, `--no-links`, `--prune` | diff --git a/docs/reference/errors.md b/docs/reference/errors.md index 003aff192d..56c8d30acc 100644 --- a/docs/reference/errors.md +++ b/docs/reference/errors.md @@ -316,10 +316,6 @@ Raised in `server/code/app/repo_admin.py`. Raised in `server/knowledge/app/sources.py`. -#### `BAD_LINK` - -Raised in `server/knowledge/app/sources.py`. - #### `BAD_MAPPING` Raised in `server/tracker/app/sources.py`. @@ -450,7 +446,7 @@ Raised in `server/tracker/app/sources.py`. #### `CREDENTIAL_REFUSED` -Raised in `server/knowledge/app/connected_sources.py`, `server/knowledge/app/sources.py`. +Raised in `server/knowledge/app/sources.py`. #### `CROSS_SITE_REQUEST` @@ -600,6 +596,10 @@ Raised in `server/memory/domain/lock.py`. What to do: [common errors](#common-er Raised in `server/tracker/app/sources.py`. +#### `MCP_SOURCE_UNAVAILABLE` + +Raised in `server/knowledge/app/mcp_source_ops.py`. + #### `MISDIRECTED_REQUEST` Raised in `server/main.py`. diff --git a/docs/reference/operations.md b/docs/reference/operations.md index 74ca4e675c..a4f23674f0 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -123,11 +123,11 @@ python scripts/codegen/docs_reference.py --check # exit 1 when a region is stal -376 operations in 43 groups. Every op is served at `POST /v1/` and as the MCP tool `loom_` (dots become underscores). +386 operations in 42 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. -Groups: [`admin`](#admin) · [`agents`](#agents) · [`assistant`](#assistant) · [`audit`](#audit) · [`blacklist`](#blacklist) · [`calibration`](#calibration) · [`code`](#code) · [`collection`](#collection) · [`conflicts`](#conflicts) · [`connection`](#connection) · [`consolidations`](#consolidations) · [`context`](#context) · [`conversation`](#conversation) · [`cost`](#cost) · [`decision`](#decision) · [`erasure`](#erasure) · [`extraction_policy`](#extraction_policy) · [`facts`](#facts) · [`grants`](#grants) · [`help`](#help) · [`inbox`](#inbox) · [`insights`](#insights) · [`knowledge`](#knowledge) · [`learnings`](#learnings) · [`memory`](#memory) · [`memory_schema`](#memory_schema) · [`mentor`](#mentor) · [`namespace`](#namespace) · [`observe`](#observe) · [`ops`](#ops) · [`org`](#org) · [`policy`](#policy) · [`procedure`](#procedure) · [`profile`](#profile) · [`profile_schema`](#profile_schema) · [`run`](#run) · [`search`](#search) · [`session`](#session) · [`task`](#task) · [`tracker`](#tracker) · [`ui`](#ui) · [`webhook`](#webhook) · [`working_memory`](#working_memory) +Groups: [`admin`](#admin) · [`agents`](#agents) · [`assistant`](#assistant) · [`audit`](#audit) · [`blacklist`](#blacklist) · [`calibration`](#calibration) · [`code`](#code) · [`collection`](#collection) · [`conflicts`](#conflicts) · [`consolidations`](#consolidations) · [`context`](#context) · [`conversation`](#conversation) · [`cost`](#cost) · [`decision`](#decision) · [`erasure`](#erasure) · [`extraction_policy`](#extraction_policy) · [`facts`](#facts) · [`grants`](#grants) · [`help`](#help) · [`inbox`](#inbox) · [`insights`](#insights) · [`knowledge`](#knowledge) · [`learnings`](#learnings) · [`memory`](#memory) · [`memory_schema`](#memory_schema) · [`mentor`](#mentor) · [`namespace`](#namespace) · [`observe`](#observe) · [`ops`](#ops) · [`org`](#org) · [`policy`](#policy) · [`procedure`](#procedure) · [`profile`](#profile) · [`profile_schema`](#profile_schema) · [`run`](#run) · [`search`](#search) · [`session`](#session) · [`task`](#task) · [`tracker`](#tracker) · [`ui`](#ui) · [`webhook`](#webhook) · [`working_memory`](#working_memory) ### admin @@ -262,15 +262,6 @@ Fields for every `conflicts` op: [operations/conflicts.md](operations/conflicts. | [`conflicts.propose_revision`](operations/conflicts.md#conflictspropose_revision) | Return non-destructive revise/contract/allow suggestions. | viewer | read | no | | | [`conflicts.resolve`](operations/conflicts.md#conflictsresolve) | Pick the winner of a conflict (keep A, keep B, keep both, merge). | admin | idempotent | no | yes | -### connection - -Fields for every `connection` op: [operations/connection.md](operations/connection.md). - -| Operation | Summary | Role | Kind | Listed under `all` | Audit | -| --- | --- | --- | --- | --- | --- | -| [`connection.disconnect`](operations/connection.md#connectiondisconnect) | Disconnect the caller's own provider account and stop its connected sources. | viewer | idempotent | no | | -| [`connection.list`](operations/connection.md#connectionlist) | List the signed-in caller's own connected provider accounts. | viewer | read | no | | - ### consolidations Fields for every `consolidations` op: [operations/consolidations.md](operations/consolidations.md). @@ -419,6 +410,12 @@ Fields for every `knowledge` op: [operations/knowledge.md](operations/knowledge. | [`knowledge.add`](operations/knowledge.md#knowledgeadd) | WHAT: Ingest a document into the knowledge base for later retrieval via loom_search. | writer | idempotent | yes | | | [`knowledge.bulk_add`](operations/knowledge.md#knowledgebulk_add) | Batched ingestion: many documents in one CH round-trip. | writer | idempotent | yes | | | [`knowledge.bulk_delete`](operations/knowledge.md#knowledgebulk_delete) | Soft-delete multiple documents by source_uri, in one commit. | writer | idempotent | no | yes | +| [`knowledge.connection.mcp_browse`](operations/knowledge.md#knowledgeconnectionmcp_browse) | | viewer | read | no | | +| [`knowledge.connection.mcp_connect`](operations/knowledge.md#knowledgeconnectionmcp_connect) | | viewer | write | no | yes | +| [`knowledge.connection.mcp_disconnect`](operations/knowledge.md#knowledgeconnectionmcp_disconnect) | | viewer | write | no | yes | +| [`knowledge.connection.mcp_discover`](operations/knowledge.md#knowledgeconnectionmcp_discover) | | viewer | read | no | | +| [`knowledge.connection.mcp_inspect`](operations/knowledge.md#knowledgeconnectionmcp_inspect) | | viewer | read | no | | +| [`knowledge.connection.mcp_list`](operations/knowledge.md#knowledgeconnectionmcp_list) | | viewer | read | no | | | [`knowledge.dataset_approve`](operations/knowledge.md#knowledgedataset_approve) | Approve a dataset's schema, retyping the columns named: its rows are typed again from the stored extraction under a new snapshot. | writer | write | no | yes | | [`knowledge.dataset_get`](operations/knowledge.md#knowledgedataset_get) | The typed datasets an ingested file's tables became: their schemas, what needs a person's answer, the rows rejected and, on request, the first rows. | viewer | read | no | | | [`knowledge.dedup_list`](operations/knowledge.md#knowledgededup_list) | List cross-URI doc duplicates and (optionally) chunk-overlap clusters. | admin | idempotent | no | | @@ -442,18 +439,24 @@ Fields for every `knowledge` op: [operations/knowledge.md](operations/knowledge. | [`knowledge.reads`](operations/knowledge.md#knowledgereads) | How often agents opened each document over the last `days` (`knowledge.get` ledger rows; dashboard, assistant and bench traffic left out). | viewer | read | no | | | [`knowledge.restore`](operations/knowledge.md#knowledgerestore) | Undo a `knowledge.delete` or `knowledge.bulk_delete` of one document. | writer | idempotent | no | yes | | [`knowledge.search`](operations/knowledge.md#knowledgesearch) | Search the user's uploaded document library — bills, contracts, receipts, resumes, policies, manuals, technical docs. | viewer | read | no | | -| [`knowledge.source.add`](operations/knowledge.md#knowledgesourceadd) | Register a document source on a namespace: a kind, what it reads (items and links, or a config) and a read-only credential. | writer | write | no | yes | -| [`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.add`](operations/knowledge.md#knowledgesourceadd) | Register a shared recording source after checking its read-only credential. | writer | write | no | yes | +| [`knowledge.source.check`](operations/knowledge.md#knowledgesourcecheck) | Probe a shared recording with its stored credential without writing. | writer | idempotent | no | | +| [`knowledge.source.inspect`](operations/knowledge.md#knowledgesourceinspect) | One registered document source: its config, 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.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 | -| [`knowledge.source.push_status`](operations/knowledge.md#knowledgesourcepush_status) | Read push setup as a namespace admin. | admin | write | no | | +| [`knowledge.source.mcp_add`](operations/knowledge.md#knowledgesourcemcp_add) | | writer | write | no | yes | +| [`knowledge.source.mcp_inspect`](operations/knowledge.md#knowledgesourcemcp_inspect) | | writer | idempotent | no | | +| [`knowledge.source.mcp_list`](operations/knowledge.md#knowledgesourcemcp_list) | | writer | idempotent | no | | +| [`knowledge.source.mcp_pause`](operations/knowledge.md#knowledgesourcemcp_pause) | | writer | write | no | yes | +| [`knowledge.source.mcp_preview`](operations/knowledge.md#knowledgesourcemcp_preview) | | writer | idempotent | no | | +| [`knowledge.source.mcp_profiles`](operations/knowledge.md#knowledgesourcemcp_profiles) | List approved profile declarations for the signed-in caller's organization. | viewer | read | no | | +| [`knowledge.source.mcp_read`](operations/knowledge.md#knowledgesourcemcp_read) | | viewer | read | no | | +| [`knowledge.source.mcp_refresh`](operations/knowledge.md#knowledgesourcemcp_refresh) | | writer | write | no | yes | +| [`knowledge.source.mcp_remove`](operations/knowledge.md#knowledgesourcemcp_remove) | | writer | write | no | yes | +| [`knowledge.source.mcp_resume`](operations/knowledge.md#knowledgesourcemcp_resume) | | writer | write | no | yes | +| [`knowledge.source.mcp_update`](operations/knowledge.md#knowledgesourcemcp_update) | | writer | write | no | yes | | [`knowledge.source.remove`](operations/knowledge.md#knowledgesourceremove) | Retire a registered document source: its registry row goes inactive and its credential is cleared. | writer | write | no | yes | | [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate) | Replace a registered document source's credential. | admin | write | no | yes | | [`knowledge.source.sync_now`](operations/knowledge.md#knowledgesourcesync_now) | Record a request to sync one document source in its sync state: the sync worker starts its next pass with it. | writer | idempotent | no | yes | -| [`knowledge.source.update`](operations/knowledge.md#knowledgesourceupdate) | Add items to a registered document source or remove them, or change a gdrive source's file kinds. | writer | write | no | yes | | [`knowledge.synthesize`](operations/knowledge.md#knowledgesynthesize) | Complete a task over WHOLE documents, not a search slice: every active chunk of the named documents is read in order, in windows that respect section boundaries, each window is noted once, and the… | viewer | idempotent | no | yes | | [`knowledge.update_metadata`](operations/knowledge.md#knowledgeupdate_metadata) | Edit doc-level metadata (title, description, tags). | writer | idempotent | no | yes | | [`knowledge.upsert`](operations/knowledge.md#knowledgeupsert) | Same fields as knowledge.add. | writer | idempotent | no | | diff --git a/docs/reference/operations/connection.md b/docs/reference/operations/connection.md deleted file mode 100644 index d962ba9317..0000000000 --- a/docs/reference/operations/connection.md +++ /dev/null @@ -1,40 +0,0 @@ -# `connection` operations - -The exact fields each `connection.*` operation takes and returns. - - - -Every op is `POST /v1/` over HTTP and the MCP tool `loom_`. The identity fields (`org`, `namespace`, `agent`, `user_id`, `session_id`) are filled from the token and the MCP session when a transport can; for an HTTP call with no token on a single-user server, the install's org on every op but `code.*` and `tracker.*` (which keep their plane's), and on [some ops](../http-api.md#request) its namespace and agent; see [identities and namespaces](../../concepts/identities-and-namespaces.md). The [operations index](../operations.md) explains role, kind and the MCP `all` listing. Unknown input fields are served and named in `ignored_args`. - - - -## `connection.disconnect` - -Disconnect the caller's own provider account and stop its connected sources. - -`POST /v1/connection.disconnect` · MCP `loom_connection_disconnect` · role `viewer` · idempotent · not listed under the MCP `all` toolset - -| Input field | Type | Default | Meaning | -| --- | --- | --- | --- | -| `org` | `str` | required | The caller's organization. | -| `kind` | `Literal['gdrive', 'notion', 'linear']` | required | The connected provider to disconnect. | - -| Output field | Type | Meaning | -| --- | --- | --- | -| `disconnected` | `bool` | | - -## `connection.list` - -List the signed-in caller's own connected provider accounts. - -`POST /v1/connection.list` · MCP `loom_connection_list` · role `viewer` · read · not listed under the MCP `all` toolset - -| Input field | Type | Default | Meaning | -| --- | --- | --- | --- | -| `org` | `str` | required | The caller's organization. | - -| Output field | Type | Meaning | -| --- | --- | --- | -| `connections` | `list[ConnectionEntry]` | | - - diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index ce11319251..7fbc20e3d4 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -78,6 +78,119 @@ Soft-delete multiple documents by source_uri, in one commit. | `deleted` | `list[_KnowledgeBulkDeleteResult]` | One result per input URI, in input order, with its tombstoned chunk count (0 if none). | | `total_chunks_tombstoned` | `int` | Sum of each source's count, a source named twice counted once (`deleted` repeats it). | +## `knowledge.connection.mcp_browse` + +`POST /v1/knowledge.connection.mcp_browse` · MCP `loom_knowledge_connection_mcp_browse` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `slot` | `str` | required | The exact owned MCP connection slot. | +| `mode` | `Literal['resources', 'search']` | required | The explicit metadata operation. | +| `query` | `str` | `''` | The approved mapped-search query; empty for resources, default empty. | +| `limit` | `int` | `100` | Maximum metadata items in the first window, from 1 to 100; default 100. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `slot` | `str` | | +| `generation` | `str` | | +| `mode` | `Literal['resources', 'search']` | | +| `supported` | `bool` | | +| `resources` | `bool \| None` | | +| `mapped_read` | `bool` | | +| `mapped_search` | `bool` | | +| `capabilities_checked` | `bool` | | +| `items` | `list[MCPBrowseItem]` | | +| `complete` | `bool` | The declared page fits this response window. | +| `truncated` | `bool` | | +| `reason` | `str \| None` | | +| `limitations` | `list[str]` | | +| `manual_resource_ids_supported` | `Literal[True]` | | +| `remote_identity_verified` | `Literal[False]` | | + +## `knowledge.connection.mcp_connect` + +`POST /v1/knowledge.connection.mcp_connect` · MCP `loom_knowledge_connection_mcp_connect` · role `viewer` · write · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `profile_id` | `str` | required | The operator-approved profile ID. | +| `request_id` | `str` | required | A client-generated UUID retained across uncertain-save retries. | +| `label` | `str \| None` | `None` | An optional display label; it verifies no remote identity. | +| `bearer` | `SecretStr \| None` | `None` | The preissued upstream bearer for a bearer profile; default none. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `connection` | `MCPConnectionEntry` | | + +## `knowledge.connection.mcp_disconnect` + +`POST /v1/knowledge.connection.mcp_disconnect` · MCP `loom_knowledge_connection_mcp_disconnect` · role `viewer` · write · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `slot` | `str` | required | The exact owned MCP connection slot. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `disconnected` | `bool` | | +| `upstream_revoked` | `Literal[False]` | | +| `upstream_action` | `Literal['revoke_credential_upstream']` | | + +## `knowledge.connection.mcp_discover` + +`POST /v1/knowledge.connection.mcp_discover` · MCP `loom_knowledge_connection_mcp_discover` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `slot` | `str` | required | The exact owned MCP connection slot. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `slot` | `str` | | +| `generation` | `str` | | +| `resources` | `bool` | | +| `mapped_read` | `bool` | | +| `mapped_search` | `bool` | | +| `supported_reads` | `bool` | | +| `limitations` | `list[str]` | | +| `remote_identity_verified` | `Literal[False]` | | + +## `knowledge.connection.mcp_inspect` + +`POST /v1/knowledge.connection.mcp_inspect` · MCP `loom_knowledge_connection_mcp_inspect` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `slot` | `str` | `''` | An exact owned MCP slot, or empty when reconciling a request ID. | +| `request_id` | `str` | `''` | The original connect UUID for save reconciliation; default empty. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `found` | `bool` | | +| `slot` | `str` | | +| `connection` | `MCPConnectionEntry \| None` | | +| `reconciliation` | `Literal['absent', 'present', 'incomplete']` | | + +## `knowledge.connection.mcp_list` + +`POST /v1/knowledge.connection.mcp_list` · MCP `loom_knowledge_connection_mcp_list` · role `viewer` · read · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `cursor` | `str \| None` | `None` | The signed continuation for the same listing arguments; default none. | +| `limit` | `int` | `100` | Maximum connections per page, from 1 to 100; default 100. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `connections` | `list[MCPConnectionEntry]` | | +| `next_cursor` | `str \| None` | | + ## `knowledge.dataset_approve` Approve a dataset's schema, retyping the columns named: its rows are typed again from the stored extraction under a new snapshot. @@ -610,38 +723,32 @@ Search the user's uploaded document library — bills, contracts, receipts, resu ## `knowledge.source.add` -Register a document source on a namespace: a kind, what it reads (items and links, or a config) and a read-only credential. +Register a shared recording source after checking its read-only credential. `POST /v1/knowledge.source.add` · MCP `loom_knowledge_source_add` · role `writer` · write · audited · not listed under the MCP `all` toolset | Input field | Type | Default | Meaning | | --- | --- | --- | --- | -| `org` | `str` | required | The org. | -| `namespace` | `str` | required | The namespace or collection the documents live in; a person's own (personal-…, single sign-on u--, col-me-…, or one claimed at sign-up) is refused. | -| `name` | `str` | required | Source name: 2-32 lower-case letters, digits, - or _, starting with a letter; trimmed and lower-cased. | -| `kind` | `str` | required | The source kind: `gdrive` (a shared-folder store), `linear` (a project tracker's project documents), `notion` (a page store's pages and databases) or `recording` (Zoom recording transcripts). | -| `items` | `list[dict[str, Any]] \| None` | `None` | The things the source reads, each an object with a `type`: 1-300 for gdrive, 1-20 for linear and 1-20 for notion; gdrive: {type: folder, id, recursive (default false; subfolders to a depth of 8, at most 500 subfolders per source)}, {type… | -| `links` | `list[str] \| None` | `None` | Links to folders, files, documents, slides, pages, databases or projects, read as items (`knowledge.source.parse_links`); an unreadable link refuses the call (BAD_LINK). | -| `config` | `dict[str, Any] \| None` | `None` | What the source reads in the form that names ids per kind, instead of items or links; gdrive: {folder_ids: [1-20 folder ids], include: [docs, slides, pdf, pptx, docx] (default all but docx)}; linear: {project_ids: [1-20 project ids… | -| `include` | `list[str] \| None` | `None` | gdrive with items or links: the file kinds read, of docs, slides, pdf, pptx, docx (default all but docx). | -| `credential_mode` | `Literal['shared', 'connected']` | `'shared'` | Use the supplied shared credential, or your own mirrored connected account. | -| `credential` | `str` | `''` | The source's read-only credential (gdrive: a service account's JSON key, with the folders shared to the account read-only; linear: a read-only API key of an account that sees the projects; notion: an integration token with read content… | -| `dry_run` | `bool` | `False` | Probe and write nothing. | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | An ordinary destination namespace or collection. | +| `name` | `str` | required | Source name: 2-32 lower-case letters, digits, - or _, starting with a letter. | +| `kind` | `Literal['recording']` | `'recording'` | | +| `config` | `dict[str, Any]` | required | Recording provider and explicitly selected recording IDs. | +| `credential` | `str` | required | Read-only recording credential; sealed and never returned. | +| `dry_run` | `bool` | `False` | Check the credential and selection without saving. | | Output field | Type | Meaning | | --- | --- | --- | | `name` | `str` | The registered source's name, normalised. | | `kind` | `str` | The source kind, normalised. | | `namespace` | `str` | The namespace the source was registered on. | -| `items` | `list[dict[str, Any]]` | The items as stored; [] for a recording source. | -| `include` | `list[str]` | The file kinds a gdrive source reads; [] for another kind. | -| `config` | `dict[str, Any]` | The config in the form that names ids per kind, or {} when an item has no place in it. | +| `config` | `dict[str, Any]` | Recording provider and selected IDs; {} for an unavailable retained source. | | `probe` | `KnowledgeSourceProbe` | What the probe with the credential found. | | `dry_run` | `bool` | True when the call only probed. | ## `knowledge.source.check` -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. +Probe a shared recording with its stored credential without writing. `POST /v1/knowledge.source.check` · MCP `loom_knowledge_source_check` · role `writer` · idempotent · not listed under the MCP `all` toolset @@ -655,17 +762,15 @@ Probe a registered document source with its stored credential now (a check of ev | --- | --- | --- | | `name` | `str` | The source checked. | | `reachable` | `bool` | False when the probe failed; `summary` says why. | -| `documents` | `int` | Documents the source lists now: the first page, 1000 at most, of the folders, of each shared drive and of each filter, and each file item (gdrive); at most 1000 (recording); each project's first page (linear); the listed pages and the… | +| `documents` | `int` | Selected recordings found, at most 1000; `more` marks a lower bound. | | `more` | `bool` | True when more documents match than were listed, so `documents` is a lower bound. | | `sample` | `list[str]` | Up to five document titles, most recently changed first. | -| `checked` | `int` | Items the probe checked: every item while there are at most 20, else the 20 added last. | -| `sampled` | `bool` | True when the source holds more items than were checked. | | `summary` | `str` | One line: what was found, or why it failed. | | `checked_at` | `str` | When the probe ran, ISO UTC. | ## `knowledge.source.inspect` -One registered document source: its items, its sync state and the documents it wrote (the 200 most recently ingested). +One registered document source: its config, its sync state and the documents it wrote (the 200 most recently ingested). `POST /v1/knowledge.source.inspect` · MCP `loom_knowledge_source_inspect` · role `viewer` · read · not listed under the MCP `all` toolset @@ -682,9 +787,7 @@ One registered document source: its items, its sync state and the documents it w | `credential_mode` | `str` | The registration's credential class; never the credential or account identity. | | `access` | `str` | Namespace-wide or checked mirrored document access. | | `owner_subject` | `str` | Canonical connected owner, only in the owner's permitted detail projection. | -| `items` | `list[dict[str, Any]]` | The things the source reads; [] for a recording source. | -| `include` | `list[str]` | The file kinds a gdrive source reads; [] for another kind. | -| `config` | `dict[str, Any]` | The source's config in the form that names ids per kind, or {} when an item has no place in it; never a credential. | +| `config` | `dict[str, Any]` | Recording provider and selected IDs; {} for an unavailable retained source. | | `created_by` | `str` | Token subject of the admin who added it; '' with auth off. | | `created_at` | `str` | When it was added, ISO UTC. | | `sync` | `KnowledgeSourceSync` | The source's sync state: a waiting request and the last pass. | @@ -707,104 +810,219 @@ The document sources registered on a namespace, with each one's sync state. | `enabled` | `bool` | Whether this deployment runs the sync worker (LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED); false: sources are stored and probed, but nothing pulls from them. | | `accepts_sources` | `bool` | False where add would refuse the namespace (PERSONAL_NAMESPACE, NAMESPACE_INACTIVE). | -## `knowledge.source.parse_links` +## `knowledge.source.mcp_add` + +`POST /v1/knowledge.source.mcp_add` · MCP `loom_knowledge_source_mcp_add` · role `writer` · write · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `slot` | `str` | required | The signed-in owner's MCP connection slot. | +| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | required | Live lookup, a selected snapshot, or periodic refresh of the fixed selection. | +| `reader_policy` | `Literal['owner_only', 'collection_copy']` | `'owner_only'` | Requested copy audience; default owner-only. | +| `resource_ids` | `list[str]` | required | Between 1 and 1000 explicit resource identities, without recursion. | +| `request_id` | `str` | required | A client UUID retained across uncertain registration retries. | +| `label` | `str \| None` | `None` | Optional source display label; default none; conveys no remote identity. | +| `confirm_copy_authority` | `bool` | `False` | Confirm authority to publish this selection through current and future collection grants; default false. | -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. +| Output field | Type | Meaning | +| --- | --- | --- | +| `source` | `MCPSourceEntry` | | +| `copies` | `Literal['retained', 'erasure_requested']` | Disposition of any copies, including earlier source modes. | +| `refresh_requested` | `bool` | | -`POST /v1/knowledge.source.parse_links` · MCP `loom_knowledge_source_parse_links` · role `viewer` · read · not listed under the MCP `all` toolset +## `knowledge.source.mcp_inspect` + +`POST /v1/knowledge.source.mcp_inspect` · MCP `loom_knowledge_source_mcp_inspect` · role `writer` · idempotent · not listed under the MCP `all` toolset | Input field | Type | Default | Meaning | | --- | --- | --- | --- | -| `org` | `str` | required | The org. | -| `namespace` | `str` | required | The namespace the source would live in. | -| `links` | `list[str]` | required | 1-300 links. | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `name` | `str` | `''` | The exact source name, or empty for request reconciliation. | +| `slot` | `str` | `''` | The original owned connection slot for request reconciliation. | +| `request_id` | `str` | `''` | The original add UUID, with slot instead of name. | | Output field | Type | Meaning | | --- | --- | --- | -| `links` | `list[KnowledgeSourceParsedLink]` | Each link, in the order given. | +| `found` | `bool` | | +| `source` | `MCPSourceEntry \| None` | | -## `knowledge.source.push_configure` +## `knowledge.source.mcp_list` -Enable provider sync hints for an existing source, or disable its setup. +`POST /v1/knowledge.source.mcp_list` · MCP `loom_knowledge_source_mcp_list` · role `writer` · idempotent · not listed under the MCP `all` toolset -`POST /v1/knowledge.source.push_configure` · MCP `loom_knowledge_source_push_configure` · role `admin` · write · audited · not listed under the MCP `all` toolset +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `cursor` | `str \| None` | `None` | Continuation for this exact listing; default none. | +| `limit` | `int` | `20` | Source summaries per page, from 1 to 20; default 20. | +| `include_retired` | `bool` | `False` | Include this owner's retired registrations; default false. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `sources` | `list[MCPSourceSummary]` | | +| `next_cursor` | `str \| None` | | + +## `knowledge.source.mcp_pause` + +`POST /v1/knowledge.source.mcp_pause` · MCP `loom_knowledge_source_mcp_pause` · role `writer` · write · audited · not listed under the MCP `all` toolset | Input field | Type | Default | Meaning | | --- | --- | --- | --- | -| `org` | `str` | required | The org. | -| `namespace` | `str` | required | The source's namespace. | -| `name` | `str` | required | The registered source name. | -| `enabled` | `bool` | `True` | Enable a fresh setup; false disables push. | -| `agent` | `str` | `'-'` | The configuring agent, default '-'. | -| `user_id` | `str` | `'-'` | The configuring user, default '-'. | -| `session_id` | `str` | `'-'` | The configuring session, default '-'. | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `name` | `str` | required | The opaque source registry name returned by add. | | Output field | Type | Meaning | | --- | --- | --- | -| `enabled` | `bool` | | -| `status` | `str` | | -| `provider` | `str` | | -| `generation` | `str` | | -| `callback_url` | `str` | | -| `provider_id` | `str` | | -| `challenge_fingerprint` | `str` | | -| `verification_token` | `str` | | -| `channels` | `int` | | -| `expires_at` | `float` | | +| `source` | `MCPSourceEntry` | | +| `copies` | `Literal['retained', 'erasure_requested']` | Disposition of any copies, including earlier source modes. | +| `refresh_requested` | `bool` | | + +## `knowledge.source.mcp_preview` + +`POST /v1/knowledge.source.mcp_preview` · MCP `loom_knowledge_source_mcp_preview` · role `writer` · idempotent · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `slot` | `str` | required | The signed-in owner's MCP connection slot. | +| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | required | Live lookup, a selected snapshot, or periodic refresh of the fixed selection. | +| `reader_policy` | `Literal['owner_only', 'collection_copy']` | `'owner_only'` | Requested copy audience; default owner-only. | +| `resource_ids` | `list[str]` | required | Between 1 and 1000 explicit resource identities, without recursion. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `namespace` | `str` | The namespace the op reads or writes. | +| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | | +| `rule` | `MCPAccessRule` | | +| `connection_state` | `Literal['configured', 'stopped', 'unavailable', 'approval_drift']` | | +| `compatibility` | `Literal['unchecked']` | | +| `permission_evidence` | `Literal['unsupported']` | | +| `refresh_state` | `Literal['not_applicable', 'enabled', 'disabled']` | | +| `selected_count` | `int` | | +| `checked_at` | `str` | | +| `read_evidence_stale_seconds` | `int` | | +| `preview_grants_authority` | `Literal[False]` | | +| `limitations` | `list[str]` | | -## `knowledge.source.push_confirm` +## `knowledge.source.mcp_profiles` -Activate the exact pending setup. +List approved profile declarations for the signed-in caller's organization. -`POST /v1/knowledge.source.push_confirm` · MCP `loom_knowledge_source_push_confirm` · role `admin` · write · audited · not listed under the MCP `all` toolset +`POST /v1/knowledge.source.mcp_profiles` · MCP `loom_knowledge_source_mcp_profiles` · role `viewer` · read · not listed under the MCP `all` toolset | Input field | Type | Default | Meaning | | --- | --- | --- | --- | -| `org` | `str` | required | The org. | -| `namespace` | `str` | required | The source's namespace. | -| `name` | `str` | required | The registered source name. | -| `generation` | `str` | required | The pending setup generation. | -| `challenge_fingerprint` | `str` | `''` | The inspected Notion challenge's SHA-256 fingerprint; empty for Linear. | -| `signing_secret` | `str` | `''` | The Linear webhook signing secret; empty for Notion. | +| `org` | `str` | required | The caller's authenticated organization. | +| `query` | `str` | `''` | Case-insensitive ID or label filter, at most 256 UTF-8 bytes; default empty. | +| `cursor` | `str \| None` | `None` | Continuation from this listing with the same arguments; default none. | +| `limit` | `int` | `100` | Maximum profile declarations per page, from 1 to 100; default 100. | | Output field | Type | Meaning | | --- | --- | --- | -| `enabled` | `bool` | | -| `status` | `str` | | -| `provider` | `str` | | -| `generation` | `str` | | -| `callback_url` | `str` | | -| `provider_id` | `str` | | -| `challenge_fingerprint` | `str` | | -| `verification_token` | `str` | | -| `channels` | `int` | | -| `expires_at` | `float` | | +| `profiles` | `list[MCPProfileEntry]` | | +| `next_cursor` | `str \| None` | | +| `self_service_enabled` | `bool` | Whether the operator permits self-service source and credential registration. | -## `knowledge.source.push_status` +## `knowledge.source.mcp_read` -Read push setup as a namespace admin. +`POST /v1/knowledge.source.mcp_read` · MCP `loom_knowledge_source_mcp_read` · role `viewer` · read · not listed under the MCP `all` toolset -`POST /v1/knowledge.source.push_status` · MCP `loom_knowledge_source_push_status` · role `admin` · write · not listed under the MCP `all` toolset +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The source collection. | +| `name` | `str` | required | The opaque saved source name. | +| `resource_id` | `str` | required | An exact resource ID explicitly selected in the saved live source. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `source_id` | `str` | | +| `resource_id` | `str` | | +| `uri` | `str` | | +| `title` | `str` | | +| `text` | `str` | | +| `mime_type` | `str` | | +| `resource_identity_verified` | `bool` | | +| `remote_identity_verified` | `Literal[False]` | | +| `upstream_acl_verified` | `Literal[False]` | | +| `limitations` | `list[str]` | | + +## `knowledge.source.mcp_refresh` + +`POST /v1/knowledge.source.mcp_refresh` · MCP `loom_knowledge_source_mcp_refresh` · role `writer` · write · audited · not listed under the MCP `all` toolset | Input field | Type | Default | Meaning | | --- | --- | --- | --- | -| `org` | `str` | required | The org. | -| `namespace` | `str` | required | The source's namespace. | -| `name` | `str` | required | The registered source name. | -| `reveal_challenge` | `bool` | `False` | Reveal a pending Notion challenge, default false. | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `name` | `str` | required | The opaque source registry name returned by add. | | Output field | Type | Meaning | | --- | --- | --- | -| `enabled` | `bool` | | -| `status` | `str` | | -| `provider` | `str` | | -| `generation` | `str` | | -| `callback_url` | `str` | | -| `provider_id` | `str` | | -| `challenge_fingerprint` | `str` | | -| `verification_token` | `str` | | -| `channels` | `int` | | -| `expires_at` | `float` | | +| `source` | `MCPSourceEntry` | | +| `copies` | `Literal['retained', 'erasure_requested']` | Disposition of any copies, including earlier source modes. | +| `refresh_requested` | `bool` | | + +## `knowledge.source.mcp_remove` + +`POST /v1/knowledge.source.mcp_remove` · MCP `loom_knowledge_source_mcp_remove` · role `writer` · write · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `name` | `str` | required | The opaque source registry name returned by add. | +| `confirm` | `str` | required | Repeat the exact opaque source name to retire. | +| `delete_documents` | `bool` | `False` | Request asynchronous erasure of stored copies; default false retains them. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `source` | `MCPSourceEntry` | | +| `copies` | `Literal['retained', 'erasure_requested']` | Disposition of any copies, including earlier source modes. | +| `refresh_requested` | `bool` | | + +## `knowledge.source.mcp_resume` + +`POST /v1/knowledge.source.mcp_resume` · MCP `loom_knowledge_source_mcp_resume` · role `writer` · write · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `name` | `str` | required | The opaque source registry name returned by add. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `source` | `MCPSourceEntry` | | +| `copies` | `Literal['retained', 'erasure_requested']` | Disposition of any copies, including earlier source modes. | +| `refresh_requested` | `bool` | | + +## `knowledge.source.mcp_update` + +`POST /v1/knowledge.source.mcp_update` · MCP `loom_knowledge_source_mcp_update` · role `writer` · write · audited · not listed under the MCP `all` toolset + +| Input field | Type | Default | Meaning | +| --- | --- | --- | --- | +| `org` | `str` | required | The authenticated caller's organization. | +| `namespace` | `str` | required | The ordinary destination collection or namespace. | +| `name` | `str` | required | The opaque source registry name returned by add. | +| `if_scope_revision` | `int \| None` | `None` | Require this current scope revision before changing selection; default unconditional. | +| `resource_ids` | `list[str]` | required | The complete ordered fixed selection replacing the current selected IDs. | +| `mode` | `Literal['live', 'snapshot', 'selected_refresh']` | required | Live lookup, a selected snapshot, or periodic refresh of this fixed selection. | +| `label` | `str \| None` | `None` | Replacement display label, or none to clear it; default none. | +| `confirm_copy_authority` | `bool` | `False` | Confirm publication authority for this replacement selection; default false. | + +| Output field | Type | Meaning | +| --- | --- | --- | +| `source` | `MCPSourceEntry` | | +| `copies` | `Literal['retained', 'erasure_requested']` | Disposition of any copies, including earlier source modes. | +| `refresh_requested` | `bool` | | ## `knowledge.source.remove` @@ -862,33 +1080,6 @@ Record a request to sync one document source in its sync state: the sync worker | `name` | `str` | The source the request was recorded for. | | `enabled` | `bool` | Whether this deployment runs the sync worker; false: the request waits until it does. | -## `knowledge.source.update` - -Add items to a registered document source or remove them, or change a gdrive source's file kinds. - -`POST /v1/knowledge.source.update` · MCP `loom_knowledge_source_update` · role `writer` · write · audited · not listed under the MCP `all` toolset - -| Input field | Type | Default | Meaning | -| --- | --- | --- | --- | -| `org` | `str` | required | The org. | -| `namespace` | `str` | required | The namespace the source's documents live in. | -| `name` | `str` | required | The source name. | -| `add_items` | `list[dict[str, Any]]` | *(computed)* | Items to add, of the forms add takes; one of the same type and id replaces the stored one, and a folder of the id of a shared drive the source keeps or is given adds nothing. | -| `add_links` | `list[str]` | *(computed)* | Links to add, read as items; a link to something the source holds names it as held (a recursive folder, a drive at its root), and an add_items entry for the same thing wins. | -| `remove_items` | `list[dict[str, Any]]` | *(computed)* | Items to remove, matched by type and id (a filter by its fields); a folder entry also removes a shared drive of the same id the source holds. | -| `remove_links` | `list[str]` | *(computed)* | Links to remove, read as items; a folder link also removes a shared drive of the same id the source holds. | -| `include` | `list[str] \| None` | `None` | gdrive only: the new file kinds read, of docs, slides, pdf, pptx, docx; default unchanged. | - -| Output field | Type | Meaning | -| --- | --- | --- | -| `name` | `str` | The source updated. | -| `items` | `list[dict[str, Any]]` | The source's items as now stored. | -| `include` | `list[str]` | The file kinds a gdrive source reads; [] for another kind. | -| `config` | `dict[str, Any]` | The config in the form that names ids per kind, or {} when an item has no place in it. | -| `added` | `list[dict[str, Any]]` | The items this call added. | -| `removed` | `list[dict[str, Any]]` | The items this call removed, as the source held them. | -| `probe` | `KnowledgeSourceProbe` | What the probe of the added items found, or with none added, of the kept file items a changed `include` probes; nothing checked when neither ran. | - ## `knowledge.synthesize` Complete a task over WHOLE documents, not a search slice: every active chunk of the named documents is read in order, in windows that respect section boundaries, each window is noted once, and the… diff --git a/docs/reference/status.md b/docs/reference/status.md index fc832313ad..2d22f1d143 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -25,7 +25,7 @@ serves is in the [MCP reference](./mcp.md#toolsets). -376 operations, 262 of them experimental. +386 operations, 272 of them experimental. | Group | Stable | Experimental | | --- | --- | --- | @@ -38,7 +38,6 @@ serves is in the [MCP reference](./mcp.md#toolsets). | `code` | 28 | [`code.backport_gap`](operations/code.md#codebackport_gap), [`code.backport_gaps`](operations/code.md#codebackport_gaps), [`code.bisect_candidates`](operations/code.md#codebisect_candidates), [`code.blame_range`](operations/code.md#codeblame_range), [`code.callees`](operations/code.md#codecallees), [`code.conventions`](operations/code.md#codeconventions), [`code.coverage_claim`](operations/code.md#codecoverage_claim), [`code.examples`](operations/code.md#codeexamples), [`code.files`](operations/code.md#codefiles), [`code.first_build`](operations/code.md#codefirst_build), [`code.map`](operations/code.md#codemap), [`code.outline`](operations/code.md#codeoutline), [`code.path_guards`](operations/code.md#codepath_guards), [`code.pr_check`](operations/code.md#codepr_check), [`code.reindex`](operations/code.md#codereindex), [`code.repo.set_access`](operations/code.md#codereposet_access), [`code.repo.set_source`](operations/code.md#codereposet_source), [`code.review_brief`](operations/code.md#codereview_brief), [`code.setting_facts`](operations/code.md#codesetting_facts), [`code.symbol_history`](operations/code.md#codesymbol_history), [`code.test_gate`](operations/code.md#codetest_gate), [`code.test_home`](operations/code.md#codetest_home), [`code.tests_for`](operations/code.md#codetests_for), [`code.verify_citations`](operations/code.md#codeverify_citations) | | `collection` | 0 | [`collection.create`](operations/collection.md#collectioncreate), [`collection.delete`](operations/collection.md#collectiondelete), [`collection.list`](operations/collection.md#collectionlist), [`collection.move`](operations/collection.md#collectionmove) | | `conflicts` | 2 | [`conflicts.allowlist_list`](operations/conflicts.md#conflictsallowlist_list), [`conflicts.allowlist_remove`](operations/conflicts.md#conflictsallowlist_remove), [`conflicts.propose_revision`](operations/conflicts.md#conflictspropose_revision) | -| `connection` | 0 | [`connection.disconnect`](operations/connection.md#connectiondisconnect), [`connection.list`](operations/connection.md#connectionlist) | | `consolidations` | 0 | [`consolidations.list`](operations/consolidations.md#consolidationslist) | | `context` | 1 | [`context.fetch`](operations/context.md#contextfetch), [`context.offload`](operations/context.md#contextoffload) | | `conversation` | 2 | [`conversation.compact`](operations/conversation.md#conversationcompact), [`conversation.create`](operations/conversation.md#conversationcreate), [`conversation.delete`](operations/conversation.md#conversationdelete), [`conversation.get`](operations/conversation.md#conversationget), [`conversation.list`](operations/conversation.md#conversationlist), [`conversation.list_saved_messages`](operations/conversation.md#conversationlist_saved_messages), [`conversation.save_message`](operations/conversation.md#conversationsave_message), [`conversation.saved_status`](operations/conversation.md#conversationsaved_status), [`conversation.search`](operations/conversation.md#conversationsearch), [`conversation.search_saved_messages`](operations/conversation.md#conversationsearch_saved_messages), [`conversation.set_logging`](operations/conversation.md#conversationset_logging), [`conversation.unsave_message`](operations/conversation.md#conversationunsave_message), [`conversation.update`](operations/conversation.md#conversationupdate) | @@ -51,7 +50,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.connection.mcp_browse`](operations/knowledge.md#knowledgeconnectionmcp_browse), [`knowledge.connection.mcp_connect`](operations/knowledge.md#knowledgeconnectionmcp_connect), [`knowledge.connection.mcp_disconnect`](operations/knowledge.md#knowledgeconnectionmcp_disconnect), [`knowledge.connection.mcp_discover`](operations/knowledge.md#knowledgeconnectionmcp_discover), [`knowledge.connection.mcp_inspect`](operations/knowledge.md#knowledgeconnectionmcp_inspect), [`knowledge.connection.mcp_list`](operations/knowledge.md#knowledgeconnectionmcp_list), [`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.mcp_add`](operations/knowledge.md#knowledgesourcemcp_add), [`knowledge.source.mcp_inspect`](operations/knowledge.md#knowledgesourcemcp_inspect), [`knowledge.source.mcp_list`](operations/knowledge.md#knowledgesourcemcp_list), [`knowledge.source.mcp_pause`](operations/knowledge.md#knowledgesourcemcp_pause), [`knowledge.source.mcp_preview`](operations/knowledge.md#knowledgesourcemcp_preview), [`knowledge.source.mcp_profiles`](operations/knowledge.md#knowledgesourcemcp_profiles), [`knowledge.source.mcp_read`](operations/knowledge.md#knowledgesourcemcp_read), [`knowledge.source.mcp_refresh`](operations/knowledge.md#knowledgesourcemcp_refresh), [`knowledge.source.mcp_remove`](operations/knowledge.md#knowledgesourcemcp_remove), [`knowledge.source.mcp_resume`](operations/knowledge.md#knowledgesourcemcp_resume), [`knowledge.source.mcp_update`](operations/knowledge.md#knowledgesourcemcp_update), [`knowledge.source.remove`](operations/knowledge.md#knowledgesourceremove), [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate), [`knowledge.source.sync_now`](operations/knowledge.md#knowledgesourcesync_now), [`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) | @@ -89,7 +88,7 @@ default is `off`) are not listed here. -53 boolean settings load false. +51 boolean settings load false. | Setting | Meaning | | --- | --- | @@ -114,7 +113,6 @@ default is `off`) are not listed here. | `LOOM_CODE_SQL_COLUMN_LINEAGE` | Column-level SQL lineage: `.` symbols, `column_read` / `column_write` facets and statement → column edges, for `.sql` and Python SQL islands. | | `LOOM_CODE_SQL_STATEMENT_RECORDS` | SQL tests as statement records: one `statement` symbol per record, chunks packed by whole statements, facet rows in loom.code_test_facets. | | `LOOM_CODE_SUMMARY_ENABLED` | Weekly LLM file/module summary cards (inputs_hash-gated). | -| `LOOM_CONNECT_NOTION_READ_CONTENT_ONLY` | The operator has restricted the public integration to read-content capability. | | `LOOM_DEPLOYMENT` | True marks this process as the deployment itself: its compose files set LOOM_DEPLOYMENT=1, and every other process sets LOOM_INSTANCE_LABEL instead (e.g. `iso::`, `ci:integration`). | | `LOOM_EMBEDDING_SEND_DIMENSIONS` | Send the optional dimensions request parameter to a compatible endpoint. | | `LOOM_ENTITY_COMMUNITIES_ENABLED` | Label-propagation communities over the entity co-occurrence graph, per namespace, into loom.entity_communities (read by namespace.taxonomy and graph-mode expansion). | @@ -123,7 +121,6 @@ default is `off`) are not listed here. | `LOOM_KNOWLEDGE_GAPS_ENABLED` | Record searches that found nothing and group them daily into knowledge.gaps.list (docs/architecture/knowledge-gaps.md). | | `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED` | Require protected automatic session capture and persist deployment privacy state. | | `LOOM_KNOWLEDGE_QUERY_HISTORY_ENABLED` | Permit opt-in ClickHouse query-history sources to queue definition drafts. | -| `LOOM_KNOWLEDGE_SOURCE_PUSH_ENABLED` | Enable optional source push setup, callbacks and Drive renewal; false keeps polling only. | | `LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED` | The knowledge_source_sync worker: pulls each registered document source's changed files into its namespace's documents. | | `LOOM_MCP_CODE_TOOLS` | List code.* tools on the MCP surface (core toolset union). | | `LOOM_MCP_CODE_UPLOAD_TOOLS` | Serve the compiler-tier upload ops (code.scip_ingest, code.scip_status) over MCP, which hides both when off. | diff --git a/docs/reference/workers.md b/docs/reference/workers.md index f87e42a2c2..956c222611 100644 --- a/docs/reference/workers.md +++ b/docs/reference/workers.md @@ -233,7 +233,6 @@ adding its row. | `knowledge_gaps` | Once a day, group each namespace's recent misses into the gaps `knowledge.gaps.list` serves. | `LOOM_KNOWLEDGE_GAPS_ENABLED` | False | `LOOM_KNOWLEDGE_GAPS_INTERVAL_SECONDS` | 86400 | | `knowledge_ingest` | Runs ingestion jobs (`server/knowledge/app/ingest_run.py`). | `LOOM_KNOWLEDGE_INGEST_ENABLED` | True | `LOOM_KNOWLEDGE_INGEST_INTERVAL_SECONDS` | 0 | | `knowledge_pg_delivery` | Knowledge delivery worker: publishes the knowledge documents a request committed to the Postgres authority but did not publish to ClickHouse (`server.knowledge.app.pg_delivery`), and sweeps expired… | `LOOM_PG_DELIVERY_ENABLED` | True | `LOOM_PG_DELIVERY_INTERVAL_SECONDS` | 2 | -| `knowledge_source_push` | Renew bounded Drive channel sets; ordinary source polling remains independent. | `LOOM_KNOWLEDGE_SOURCE_PUSH_ENABLED` | False | `LOOM_KNOWLEDGE_SOURCE_PUSH_INTERVAL_SECONDS` | 300 | | `knowledge_source_retire` | Finish queued source deletions even when source syncing or authentication is off. | always on | | `LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS` | 900 | | `knowledge_source_sync` | Pulls each registered document source's changed files into its namespace's documents (`server.knowledge.app.source_sync`). | `LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED` | False | `LOOM_KNOWLEDGE_SOURCE_SYNC_INTERVAL_SECONDS` | 900 | | `mcp_session_run_sweep` | MCP session run sweeper. | always on | | `LOOM_MCP_SESSION_RUN_SWEEP_INTERVAL_SECONDS` | 60 | diff --git a/frontend/e2e/connected-accounts.spec.ts b/frontend/e2e/connected-accounts.spec.ts deleted file mode 100644 index b2177db74c..0000000000 --- a/frontend/e2e/connected-accounts.spec.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { boxOf, installApi, MIN_TARGET_PX } from "./fixtures"; -import { violations } from "./axe"; - -for (const width of [1400, 375]) { - test.describe(`${width} px connected accounts`, () => { - test.use({ viewport: { width, height: 900 }, hasTouch: width === 375 }); - - test("a viewer can review and disconnect their own account", async ({ page }) => { - await installApi(page, { viewer: true }); - let connected = true; - let disconnects = 0; - await page.route("**/v1/connection.list", (route) => - route.fulfill({ - status: 200, - contentType: "application/json", - body: JSON.stringify({ - connections: ["gdrive", "notion", "linear"].map((kind) => ({ - kind, - connected: kind === "gdrive" && connected, - account_email: kind === "gdrive" && connected ? "reader@example.com" : null, - scopes: ["scope-not-for-display"], - connect_url: `/settings/connected-accounts?kind=${kind}`, - })), - }), - }), - ); - await page.route("**/v1/connection.disconnect", (route) => { - disconnects++; - connected = false; - return route.fulfill({ status: 200, contentType: "application/json", body: '{"disconnected":true}' }); - }); - await page.goto("/settings/connected-accounts?kind=linear"); - await expect(page.getByText("reader@example.com")).toBeVisible(); - await expect(page.getByRole("heading", { name: "Linear", exact: true })).toBeFocused(); - await expect(page.getByText("scope-not-for-display")).toHaveCount(0); - expect(await violations(page)).toEqual([]); - const main = page.locator("main"); - expect(await main.evaluate((el) => el.scrollWidth <= el.clientWidth)).toBe(true); - if (width === 375) { - for (const button of await main.getByRole("button").all()) { - const box = await boxOf(button); - expect(box.width).toBeGreaterThanOrEqual(MIN_TARGET_PX); - expect(box.height).toBeGreaterThanOrEqual(MIN_TARGET_PX); - } - } - await page.getByRole("button", { name: "Disconnect Google Drive" }).click(); - const confirm = page.getByRole("dialog", { name: "Disconnect Google Drive?", exact: true }); - await expect(confirm.getByText("This stops your document sources that use this connection.")).toBeVisible(); - await expect(confirm.getByRole("button", { name: "Cancel", exact: true })).toBeFocused(); - await confirm.getByRole("button", { name: "Cancel", exact: true }).click(); - expect(disconnects).toBe(0); - await page.getByRole("button", { name: "Disconnect Google Drive" }).click(); - await confirm.getByRole("button", { name: "Disconnect", exact: true }).click(); - await expect(page.getByRole("button", { name: "Connect Google Drive", exact: true })).toBeVisible(); - await expect(page.getByText("reader@example.com")).toHaveCount(0); - await expect(page.getByRole("heading", { name: "Google Drive", exact: true })).toBeFocused(); - expect(disconnects).toBe(1); - }); - }); -} diff --git a/frontend/e2e/dashboard-session-protection.spec.ts b/frontend/e2e/dashboard-session-protection.spec.ts new file mode 100644 index 0000000000..d1d84186d5 --- /dev/null +++ b/frontend/e2e/dashboard-session-protection.spec.ts @@ -0,0 +1,310 @@ +import { expect, test, type BrowserContext, type Page } from "@playwright/test"; +import { fileURLToPath } from "node:url"; +import { build } from "vite"; +import { mcpConnection, mcpDiscovery, mcpPreviewValue, mcpProfile, mcpResult, mcpSource } from "../src/test/mcpSources"; + +type HarnessWindow = Window & { + DashboardProtection: typeof import("./sessionProtectionHarness"); +}; + +const DATABASE = "loom-dashboard-session-protection"; +const WITNESS = "loom-dashboard-session-protection-v1"; +let bundle: string; + +// Compile the production modules, then execute them against real browser storage. +// This suite runs only in the hosted frontend environment with its normal dependencies. +test.beforeAll(async () => { + const result = await build({ + configFile: false, + logLevel: "error", + define: { "process.env.NODE_ENV": JSON.stringify("production") }, + build: { + rollupOptions: { output: { inlineDynamicImports: true } }, + write: false, + minify: false, + target: "esnext", + lib: { + entry: fileURLToPath(new URL("./sessionProtectionHarness.ts", import.meta.url)), + name: "DashboardProtection", + formats: ["iife"], + }, + }, + }); + const outputs = Array.isArray(result) ? result : [result]; + const chunks = outputs.flatMap((output) => "output" in output + ? output.output.filter((chunk) => chunk.type === "chunk") : []); + expect(chunks).toHaveLength(1); + const chunk = chunks[0]; + if (!chunk || chunk.type !== "chunk") throw new Error("protection harness did not compile to one script"); + bundle = chunk.code; +}); + +async function installPage(context: BrowserContext, page: Page) { + await context.route("**/protection-test", (route) => route.fulfill({ + contentType: "text/html", body: "Session protection", + })); + await page.goto("/protection-test"); + await page.addScriptTag({ content: bundle }); +} + +test("actual POST observes private responses, keeps explicit intent local and persists across tabs/reload", async ({ context, page }) => { + const requests: { path: string; declaration: string | undefined }[] = []; + await context.route("**/v1/**", async (route) => { + requests.push({ path: new URL(route.request().url()).pathname, + declaration: route.request().headers()["x-loom-session-protection"] }); + await route.fulfill({ contentType: "application/json", body: JSON.stringify({ mirrored: true, text: "private" }) }); + }); + await installPage(context, page); + const first = await page.evaluate(async (witness) => { + const { post, mcpRead, DashboardSessionProtectionStore } = (window as HarnessWindow).DashboardProtection; + const response = await mcpRead({ org: "one", namespace: "one", name: "source", resource_id: "private" }); + const store = await DashboardSessionProtectionStore.open(); + let automatic: string | undefined; + try { await post("/v1/memory.set", { namespace: "two", session_id: "new", value: "private" }); } + catch (error) { automatic = (error as Error).name; } + return { response, automatic, state: await store.read(), family: localStorage.getItem(witness), + storage: Object.values(localStorage) }; + }, WITNESS); + expect(first.response).toEqual({ mirrored: true, text: "private" }); + expect(first.automatic).toBe("AutomaticCaptureSuppressed"); + expect(first.state).toBe("protected"); + expect(first.family).toBeTruthy(); + expect(first.storage).toEqual([first.family]); + expect(requests).toEqual([{ path: "/v1/knowledge.source.mcp_read", declaration: "v1" }]); + + const second = await context.newPage(); + await second.goto("/protection-test"); + await second.addScriptTag({ content: bundle }); + const restored = async (target: Page) => target.evaluate(async (witness) => { + const { post, DashboardSessionProtectionStore } = (window as HarnessWindow).DashboardProtection; + const state = await (await DashboardSessionProtectionStore.open()).read(); + try { await post("/v1/conversation.create", { namespace: "another", thread_id: "new" }); } + catch (error) { return { state, family: localStorage.getItem(witness), error: (error as Error).name }; } + throw new Error("automatic write escaped"); + }, WITNESS); + expect(await restored(second)).toEqual({ state: "protected", family: first.family, error: "AutomaticCaptureSuppressed" }); + await page.reload(); + await page.addScriptTag({ content: bundle }); + expect(await restored(page)).toEqual({ state: "protected", family: first.family, error: "AutomaticCaptureSuppressed" }); + expect(requests).toHaveLength(1); +}); + +test("real source controls and ordinary manual submit dispatch through one durable protected family", async ({ context, page }) => { + const sent: { op: string; body: Record; declaration: string | undefined }[] = []; + await context.route("**/v1/**", async (route) => { + const request = route.request(); + const op = new URL(request.url()).pathname.slice(4); + sent.push({ op, body: request.postDataJSON(), declaration: request.headers()["x-loom-session-protection"] }); + const responses: Record = { + "knowledge.source.mcp_profiles": { profiles: [mcpProfile], next_cursor: null, self_service_enabled: true }, + "knowledge.connection.mcp_list": { connections: [], next_cursor: null }, + "knowledge.connection.mcp_connect": { connection: mcpConnection }, + "knowledge.connection.mcp_inspect": { found: true, connection: mcpConnection, reconciliation: "present" }, + "knowledge.connection.mcp_discover": mcpDiscovery, + "knowledge.source.mcp_preview": mcpPreviewValue, + "knowledge.source.mcp_add": mcpResult, + "collection.list": { collections: [{ namespace: "col-team", title: "Team", parent: "", personal: false, role: "admin" }], next_cursor: null }, + "knowledge.connection.mcp_browse": { items: [], limitations: [], supported: true, complete: false, truncated: false }, + "namespace.taxonomy": { tags: [], entities: [], communities: [] }, + "memory.list": { rows: [], total: 0 }, + "memory.set": { version: 1, pinned: false }, + }; + expect(Object.hasOwn(responses, op)).toBe(true); + await route.fulfill({ contentType: "application/json", body: JSON.stringify({ ...responses[op], mirrored: true }) }); + }); + await installPage(context, page); + await page.evaluate(() => { + const unmount = (window as HarnessWindow).DashboardProtection.mountSourceSetup(); + Object.assign(window, { unmountSource: unmount }); + }); + await page.getByRole("radio", { name: "Approved remote server" }).click(); + await page.getByLabel("Preissued upstream bearer").fill("selected-secret"); + await page.getByRole("button", { name: "Connect a new account" }).click(); + await page.getByRole("button", { name: "Discover capabilities" }).click(); + await page.getByLabel("Explicit resource IDs (one per line)").fill(mcpSource.resource_ids[0] ?? ""); + await page.getByRole("radio", { name: "Selected snapshot" }).click(); + await page.getByRole("radio", { name: "Team (col-team)" }).click(); + await page.getByRole("button", { name: "Review effective access" }).click(); + await expect(page.getByRole("region", { name: "Effective access preview" })).toBeVisible(); + await page.getByRole("button", { name: "Register source" }).click(); + await expect(page.getByText(/Server registration state: registered/)).toBeVisible(); + expect(sent.filter((r) => r.op === "knowledge.source.mcp_add")).toEqual([{ + op: "knowledge.source.mcp_add", declaration: "v1", body: expect.objectContaining({ + namespace: "col-team", reader_policy: "owner_only", confirm_copy_authority: false, resource_ids: mcpSource.resource_ids, + }), + }]); + const family = await page.evaluate((key) => localStorage.getItem(key), WITNESS); + await page.evaluate(async () => { + const api = (window as HarnessWindow).DashboardProtection; + await api.post("/v1/memory.list", { namespace: "another" }); + (window as Window & { unmountSource: () => void }).unmountSource(); + api.mountMemory(); + }); + await page.getByLabel("Key (lower_snake_case)").fill("manual_value"); + await page.getByLabel("Value", { exact: true }).fill("human supplied value"); + await page.getByRole("button", { name: "Add memory" }).click(); + await expect.poll(() => sent.filter((r) => r.op === "memory.set").length).toBe(1); + expect(sent.find((r) => r.op === "memory.set")).toEqual({ op: "memory.set", declaration: "v1", + body: expect.objectContaining({ memory_key: "manual_value", value: "human supplied value" }) }); + const count = sent.length; + expect(await page.evaluate(async () => { + try { await (window as HarnessWindow).DashboardProtection.post("/v1/memory.set", { namespace: "other", session_id: "new" }); } + catch (error) { return (error as Error).name; } + throw new Error("automatic write escaped"); + })).toBe("AutomaticCaptureSuppressed"); + expect(sent).toHaveLength(count); + expect(sent.every((r) => r.declaration === "v1")).toBe(true); + expect(await page.evaluate((key) => localStorage.getItem(key), WITNESS)).toBe(family); +}); + +test("actual GET JSON and opaque historical downloads remain observed", async ({ context, page }) => { + await context.route("**/v1/**", async (route) => { + expect(route.request().headers()["x-loom-session-protection"]).toBe("v1"); + await route.fulfill(route.request().url().includes("knowledge.download") + ? { contentType: "text/plain", body: "historical original bytes" } + : { contentType: "application/json", body: '{"mirrored":true,"found":true}' }); + }); + await installPage(context, page); + expect(await page.evaluate(async () => { + const api = (window as HarnessWindow).DashboardProtection; + const original = await api.getResponse("/v1/knowledge.download?revision=1&original=true"); + const bytes = await original.text(); + const json = await api.getJson("/v1/me/sharing-summary"); + return { bytes, json, state: await (await api.DashboardSessionProtectionStore.open()).read() }; + })).toEqual({ bytes: "historical original bytes", json: { mirrored: true, found: true }, state: "protected" }); +}); + +test("missing durable row refuses explicit POST before and after restore", async ({ context, page }) => { + let requests = 0; + await context.route("**/v1/**", async (route) => { + requests++; + await route.fulfill({ contentType: "application/json", body: "{}" }); + }); + await installPage(context, page); + const failure = await page.evaluate(async (database) => { + const { post } = (window as HarnessWindow).DashboardProtection; + await post("/v1/memory.get", {}, undefined, "explicit"); + await new Promise((resolve, reject) => { + const opening = indexedDB.open(database, 1); + opening.onerror = () => reject(opening.error); + opening.onsuccess = () => { + const transaction = opening.result.transaction("authority", "readwrite", { durability: "strict" }); + transaction.objectStore("authority").delete("dashboard"); + transaction.oncomplete = () => { opening.result.close(); resolve(); }; + transaction.onabort = () => reject(transaction.error); + }; + }); + try { await post("/v1/memory.set", {}, undefined, "explicit"); } + catch (error) { return (error as Error).name; } + throw new Error("lost proof accepted"); + }, DATABASE); + expect(failure).toBe("SessionProtectionUnavailable"); + await page.reload(); + await page.addScriptTag({ content: bundle }); + const restored = await page.evaluate(async () => { + try { await (window as HarnessWindow).DashboardProtection.post("/v1/memory.set", {}, undefined, "explicit"); } + catch (error) { return (error as Error).name; } + throw new Error("lost proof was reinitialized"); + }); + expect(restored).toBe("SessionProtectionUnavailable"); + expect(requests).toBe(1); +}); + +test("missing witness refuses restore instead of creating another family", async ({ context, page }) => { + await installPage(context, page); + await page.evaluate(async (witness) => { + await (window as HarnessWindow).DashboardProtection.DashboardSessionProtectionStore.open(); + localStorage.removeItem(witness); + }, WITNESS); + await page.reload(); + await page.addScriptTag({ content: bundle }); + expect(await page.evaluate(async () => { + try { await (window as HarnessWindow).DashboardProtection.DashboardSessionProtectionStore.open(); } + catch (error) { return (error as Error).name; } + throw new Error("missing witness accepted"); + })).toBe("SessionProtectionUnavailable"); +}); + +test("complete browser storage loss never provisions automatic-write permission", async ({ context, page }) => { + await installPage(context, page); + await page.evaluate(async () => { + await (window as HarnessWindow).DashboardProtection.DashboardSessionProtectionStore.open(); + }); + // Leave this document so its database handles close before browser-owned deletion. + await page.goto("about:blank"); + await page.goto("/protection-test"); + await page.evaluate(async (database) => { + localStorage.clear(); + await new Promise((resolve, reject) => { + const deletion = indexedDB.deleteDatabase(database); + deletion.onsuccess = () => resolve(); + deletion.onerror = () => reject(deletion.error); + deletion.onblocked = () => reject(new Error("browser still owns an open handle")); + }); + }, DATABASE); + await page.addScriptTag({ content: bundle }); + expect(await page.evaluate(async () => { + try { await (window as HarnessWindow).DashboardProtection.post("/v1/memory.set", {}); } + catch (error) { return (error as Error).name; } + throw new Error("storage loss created clean permission"); + })).toBe("AutomaticCaptureSuppressed"); +}); + +for (const damage of [{ state: "clean" }, { version: 2 }, { family: "other" }, { text: "private" }]) { + test(`damaged durable authority refuses dispatch: ${JSON.stringify(damage)}`, async ({ context, page }) => { + let requests = 0; + await context.route("**/v1/**", async (route) => { + requests++; + await route.fulfill({ contentType: "application/json", body: "{}" }); + }); + await installPage(context, page); + const failure = await page.evaluate(async ({ database, damage }) => { + const { post } = (window as HarnessWindow).DashboardProtection; + await post("/v1/memory.get", {}, undefined, "explicit"); + await new Promise((resolve, reject) => { + const opening = indexedDB.open(database, 1); + opening.onerror = () => reject(opening.error); + opening.onsuccess = () => { + const transaction = opening.result.transaction("authority", "readwrite", { durability: "strict" }); + const store = transaction.objectStore("authority"); + const read = store.get("dashboard"); + read.onsuccess = () => store.put({ ...read.result, ...damage }, "dashboard"); + transaction.oncomplete = () => { opening.result.close(); resolve(); }; + transaction.onabort = () => reject(transaction.error); + }; + }); + try { await post("/v1/memory.set", {}, undefined, "explicit"); } + catch (error) { return (error as Error).name; } + throw new Error("damaged proof accepted"); + }, { database: DATABASE, damage }); + expect(failure).toBe("SessionProtectionUnavailable"); + expect(requests).toBe(1); + }); +} + +test("actual error/status and stream paths are observed; file writes remain guarded", async ({ context, page }) => { + await context.route("**/v1/**", async (route) => { + if (route.request().url().endsWith("/assistant.chat")) { + await route.fulfill({ contentType: "text/event-stream", body: 'data: {"mirrored":true,"delta":"private"}\n\n' }); + } else { + await route.fulfill({ status: 503, contentType: "application/json", body: '{"mirrored":true,' }); + } + }); + await installPage(context, page); + const result = await page.evaluate(async () => { + const { post, postStreaming, postFile } = (window as HarnessWindow).DashboardProtection; + let error: string | undefined; + try { await post("/v1/knowledge.source.mcp_read", {}, undefined, "explicit"); } + catch (failure) { error = (failure as Error).name; } + const stream = await postStreaming("/v1/assistant.chat", {}, {}, new AbortController().signal, "explicit"); + const text = await stream.text(); + const unread = await postStreaming("/v1/assistant.chat", {}, {}, new AbortController().signal, "explicit"); + await unread.body?.cancel(); + let file: string | undefined; + try { await postFile("/v1/knowledge.upload", new Blob(["private"])); } + catch (failure) { file = (failure as Error).name; } + return { error, text, file }; + }); + expect(result).toEqual({ error: "SessionProtectionUnavailable", + text: 'data: {"mirrored":true,"delta":"private"}\n\n', file: "AutomaticCaptureSuppressed" }); +}); diff --git a/frontend/e2e/fixtures.ts b/frontend/e2e/fixtures.ts index 8b1fbfa0ef..04dfd160dc 100644 --- a/frontend/e2e/fixtures.ts +++ b/frontend/e2e/fixtures.ts @@ -455,8 +455,8 @@ export function knowledgeSourcesFixture(): Record[] { return [ { name: "design-docs", - kind: "gdrive", - config: { folder_ids: ["1AbCdEfGhIjKlMnOp"], include: ["docs", "slides", "pdf", "pptx"] }, + kind: "recording", + config: { provider: "zoom", ids: ["81234567890"] }, created_by: "maintainer@example.com", created_at: "2026-10-01T00:00:00Z", sync: { @@ -1001,16 +1001,8 @@ export async function installApi(page: Page, options: InstallOptions = {}): Prom switch (url.pathname) { case "/v1/whoami": return json(who); - case "/v1/connection.list": - return json({ - connections: ["gdrive", "notion", "linear"].map((kind) => ({ - kind, - connected: false, - account_email: null, - scopes: [], - connect_url: `/settings/connected-accounts?kind=${kind}`, - })), - }); + case "/v1/knowledge.source.mcp_list": + return json({ sources: [], next_cursor: null }); // Well-shaped empties for the two summaries the Sharing and Usage views read fields // of; the default answer's bare rows/entries would make them throw. case "/v1/me/sharing-summary": @@ -1775,7 +1767,6 @@ export const ROUTES = [ "/memories", "/recall", "/settings", - "/settings/connected-accounts", "/repositories", "/flow", "/library", diff --git a/frontend/e2e/repositories.spec.ts b/frontend/e2e/repositories.spec.ts index 14348a87cc..3ea50dfcb2 100644 --- a/frontend/e2e/repositories.spec.ts +++ b/frontend/e2e/repositories.spec.ts @@ -317,16 +317,18 @@ test.describe("document sources", () => { await expect(page.getByRole("alert")).toHaveCount(0); }); - test("the namespace's admin gets Add a source, off until a check, and each verb's dialog", async ({ page }) => { + test("the namespace's admin gets recording setup, off until a check, and recording management", async ({ page }) => { const errors = collectErrors(page); await installApi(page, { codeRepos: reposWith("admin"), knowledgeSources: knowledgeSourcesFixture() }); await page.goto("/repositories"); await unfold(card(page), CODE_REPO); const sources = card(page).getByRole("group", { name: "Sources" }); - await sources.getByRole("button", { name: "Add a source" }).click(); + await sources.getByRole("button", { name: "Add recording source" }).click(); const dialog = page.getByRole("dialog"); await expect(dialog.getByRole("button", { name: "Add source" })).toBeDisabled(); - await expect(dialog.getByLabel(/^Service account key/)).toHaveAttribute("type", "password"); + await expect(dialog.getByLabel(/^Read-only credential/)).toHaveAttribute("type", "password"); + await expect(dialog.getByLabel(/^Meetings/)).toBeVisible(); + await expect(dialog.getByLabel(/^Folders/)).toHaveCount(0); await dialog.getByRole("button", { name: "Cancel" }).click(); for (const verb of ["Check", "Sync now", "Rotate credential", "Retire"]) { await sources.getByRole("button", { name: "Actions for design-docs" }).click(); diff --git a/frontend/e2e/sessionProtectionHarness.ts b/frontend/e2e/sessionProtectionHarness.ts new file mode 100644 index 0000000000..c047846332 --- /dev/null +++ b/frontend/e2e/sessionProtectionHarness.ts @@ -0,0 +1,29 @@ +export { post, postFile, postStreaming, getJson, getResponse } from "../src/api"; +export { DashboardSessionProtectionStore } from "../src/lib/dashboardSessionProtection"; +export { createDashboardTransport } from "../src/lib/dashboardTransport"; +export { mcpRead } from "../src/api/mcpSources"; +import { createElement } from "react"; +import { createRoot } from "react-dom/client"; +import { MCPSourceSetup } from "../src/flows/MCPSourceSetup"; +import { AddMemoryDialog } from "../src/flows/AddMemoryDialog"; + +export function mountSourceSetup() { + const target = document.createElement("div"); + document.body.append(target); + const root = createRoot(target); + root.render(createElement(MCPSourceSetup, { + org: "acme", callerKey: "owner", collectionVersion: "grants", + onSaved: () => {}, onClose: () => {}, + })); + return () => { root.unmount(); target.remove(); }; +} + +export function mountMemory() { + const target = document.createElement("div"); + document.body.append(target); + const root = createRoot(target); + root.render(createElement(AddMemoryDialog, { + open: true, identity: { org: "acme", namespace: "col-team", agent: "loom-ui" }, + onAdded: () => {}, onOpenChange: () => {}, + })); +} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index f72cb6ce7c..2b90384916 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -90,9 +90,6 @@ const Sharing = lazy(() => import("./views/Sharing").then((m) => ({ default: m.S const Browse = lazy(() => import("./views/Browse").then((m) => ({ default: m.Browse }))); const CodeView = lazy(() => import("./views/Code").then((m) => ({ default: m.CodeView }))); const Setup = lazy(() => import("./views/Setup").then((m) => ({ default: m.Setup }))); -const ConnectedAccounts = lazy(() => - import("./views/ConnectedAccounts").then((m) => ({ default: m.ConnectedAccounts })), -); const Tasks = lazy(() => import("./views/Tasks").then((m) => ({ default: m.Tasks }))); const ReviewQueue = lazy(() => import("./views/admin/ReviewQueue").then((m) => ({ default: m.ReviewQueue }))); const Health = lazy(() => import("./views/admin/Health").then((m) => ({ default: m.Health }))); @@ -710,7 +707,7 @@ function ViewSwitch({ view }: { view: ReturnType["view const denied = useStore((s) => s.deniedNamespace); // A link to a namespace the account cannot read shows that, never the view: on the // namespace under it the view would read data the link did not ask for. - if (denied && view !== "connected-accounts") return ; + if (denied) return ; // A view that reads the memory plane never mounts on a code or tracker namespace, or on // no namespace — it would fire memory.* reads the token cannot make against a namespace // that holds no memories. One empty state, one place, says what the namespace is and @@ -742,8 +739,6 @@ function ViewSwitch({ view }: { view: ReturnType["view return ; case "setup": return ; - case "connected-accounts": - return ; case "tasks": return ; // task inbox board case "admin:review_queue": diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 7ad71ac76a..8b66a7b633 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -5,6 +5,7 @@ import { noteCallEnd, noteCallStart } from "./lib/vitalsCounter"; import { claimsFromToken } from "./lib/boot"; import { ApiError, apiErrorFromResponse } from "./lib/errors"; +import { dashboardFetch, type DashboardRequestIntent } from "./lib/dashboardTransport"; export { ApiError } from "./lib/errors"; // The two code-plane shapes the shell reads; the plane itself lives in api/code.ts and rides with the Repositories view. import type { CodeIndexStatus, CodeRepoSummary } from "./api/code"; @@ -321,11 +322,13 @@ async function request( body?: unknown, signal?: AbortSignal, headers: Record = {}, + intent: DashboardRequestIntent = "automatic", + download = false, ): Promise { _bump(+1); noteCallStart(); // the view's call count and span try { - return await send(method, path, body, signal, false, headers); + return await send(method, path, body, signal, false, headers, intent, download); } finally { _bump(-1); noteCallEnd(); @@ -339,6 +342,8 @@ async function send( signal: AbortSignal | undefined, retried: boolean, headers: Record, + intent: DashboardRequestIntent, + download: boolean, ): Promise { const sent = token(); // Another tab may have stored another person's token a moment ago, before this one heard @@ -351,7 +356,7 @@ async function send( } // A file goes as its bytes (`knowledge.upload`); any other body is the op's JSON. const raw = body instanceof Blob; - const r = await fetch( + const r = await dashboardFetch( path, method === "POST" ? { @@ -365,6 +370,8 @@ async function send( signal: boundedSignal(signal), } : { method, headers: { ...headers, ...authHeader() }, signal: boundedSignal(signal) }, + intent, + download, ); if (r.status === 401 && sent) { // The first refusal of the stored token ends the session, before any await, so @@ -373,7 +380,7 @@ async function send( if (ending) signInRejected?.(); // A single-user install has no sign-in: the stale token is gone (this refusal or a // concurrent one dropped it), so the call goes again without it. - if (isAuthDisabled() && !retried) return send(method, path, body, signal, true, headers); + if (isAuthDisabled() && !retried) return send(method, path, body, signal, true, headers, intent, download); // A call raced by another tab's sign-in is not sent again under a token this tab has // not checked: Retry sends it, and the error says so instead of "sign in again". if (!ending && token() && ownsToken(token())) throw new ApiError({ status: 401, code: "SIGNED_IN_ELSEWHERE" }); @@ -400,8 +407,14 @@ async function readJson(r: Response): Promise { } } -export async function post(path: string, body: unknown, signal?: AbortSignal): Promise { - return readJson(await request("POST", path, body, signal)); +/** Unclassified POSTs are automatic. A user write passes explicit intent for this call. */ +export async function post( + path: string, + body: unknown, + signal?: AbortSignal, + intent: DashboardRequestIntent = "automatic", +): Promise { + return readJson(await request("POST", path, body, signal, {}, intent)); } /** POST JSON and answer the ok Response unread, for a body that streams (the assistant's @@ -413,14 +426,20 @@ export async function postStreaming( body: unknown, headers: Record, signal: AbortSignal, + intent: DashboardRequestIntent = "automatic", ): Promise { - return request("POST", path, body, signal, headers); + return request("POST", path, body, signal, headers, intent); } /** POST a file's bytes as the body (`/v1/knowledge.upload?...`), parsed as JSON. Pass a * `signal` for a large file: without one the call is bounded like any other. */ -export async function postFile(path: string, file: Blob, signal?: AbortSignal): Promise { - return readJson(await request("POST", path, file, signal)); +export async function postFile( + path: string, + file: Blob, + signal?: AbortSignal, + intent: DashboardRequestIntent = "automatic", +): Promise { + return readJson(await request("POST", path, file, signal, {}, intent)); } /** A GET read on the shared request path, parsed as JSON. */ @@ -430,7 +449,7 @@ export async function getJson(path: string, opts: RequestOpts = {}): Promise< /** A GET whose body is not JSON (a download): the ok Response, for the caller to read. */ export async function getResponse(path: string, opts: RequestOpts = {}): Promise { - return request("GET", path, undefined, opts.signal); + return request("GET", path, undefined, opts.signal, {}, "automatic", true); } /** The namespace's memory total, and nothing else: `memory.list` with `count_only`, two @@ -517,6 +536,7 @@ export async function restoreMemory( /** Restore only a row still retired, whatever it retired behind; never undo a delete. */ only_if_superseded?: boolean; } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ restored: boolean; memory_id?: string | null; @@ -531,7 +551,7 @@ export async function restoreMemory( memory_key: key, ...(opts.if_superseded_by ? { if_superseded_by: opts.if_superseded_by } : {}), ...(opts.only_if_superseded ? { only_if_superseded: true } : {}), - }); + }, undefined, intent); } /** Wire shape returned by /v1/memory.get. `found=false` means the row @@ -685,6 +705,7 @@ export async function setMemory( * overflow. */ charLimit?: number | null; } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ version: number; pinned: boolean }> { const body: Record = { ...id, @@ -705,7 +726,7 @@ export async function setMemory( if (opts.charLimit != null) { body.char_limit = opts.charLimit; } - return post<{ version: number; pinned: boolean }>("/v1/memory.set", body); + return post<{ version: number; pinned: boolean }>("/v1/memory.set", body, undefined, intent); } /** The source classes a write may declare (`server.memory.domain.provenance`); the @@ -731,6 +752,7 @@ export async function pinMemory( id: Identity, key: string, row: MemoryDetail, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ version: number; pinned: boolean }> { const body: Record = { ...rowIdentity(id, row), @@ -752,15 +774,16 @@ export async function pinMemory( if (row.char_limit != null) body.char_limit = row.char_limit; // A change to the value since the read answers 409 instead of being reverted. if (row.content_sha256) body.if_match_sha256 = row.content_sha256; - return post<{ version: number; pinned: boolean }>("/v1/memory.pin", body); + return post<{ version: number; pinned: boolean }>("/v1/memory.pin", body, undefined, intent); } /** `id` may name the row's user and session (`rowIdentity`); they default to '-'. */ export async function unpinMemory( id: Identity, key: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ unpinned: boolean; reason: string; memory_id: string; version: number | null }> { - return post("/v1/memory.unpin", { ...id, memory_key: key }); + return post("/v1/memory.unpin", { ...id, memory_key: key }, undefined, intent); } export interface VerifyResult { @@ -779,6 +802,7 @@ export async function verifyMemory( id: Identity, key: string, opts: { revoke?: boolean; userId?: string; sessionId?: string } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/memory.verify", { org: id.org, @@ -788,7 +812,7 @@ export async function verifyMemory( session_id: opts.sessionId || "-", memory_key: key, revoke: !!opts.revoke, - }); + }, undefined, intent); } /** Tombstone one memory. @@ -797,11 +821,11 @@ export async function verifyMemory( * idempotent: deleting a row that does not match the full identity tuple is a * 200 with `tombstoned: false`, not an error: a caller that only catches * exceptions reports "Deleted" for a delete that did nothing. Check `tombstoned`. */ -export async function deleteMemory(id: Identity, key: string): Promise<{ tombstoned: boolean; version: number }> { +export async function deleteMemory(id: Identity, key: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ tombstoned: boolean; version: number }> { return post<{ tombstoned: boolean; version: number }>("/v1/memory.delete", { ...id, memory_key: key, - }); + }, undefined, intent); } /** POST /v1/memory.move: rename `fromKey` to `toKey`. The destination is written through @@ -831,6 +855,7 @@ export async function moveMemory( fromKey: string, toKey: string, opts: { keepRedirect?: boolean; dryRun?: boolean; user_id?: string; session_id?: string } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/memory.move", { ...id, @@ -840,7 +865,7 @@ export async function moveMemory( to_key: toKey, keep_redirect: opts.keepRedirect ?? true, dry_run: opts.dryRun ?? false, - }); + }, undefined, intent); } // ===== Datapacks / Grants ===== @@ -916,6 +941,7 @@ export async function createGrant( * control passes it; "add member" never does, so re-adding an existing admin as writer * cannot demote them. */ opts: { replace?: boolean } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/grants.create", { org: id.org, @@ -924,18 +950,19 @@ export async function createGrant( role, granted_by: "dashboard", ...(opts.replace ? { replace: true } : {}), - }); + }, undefined, intent); } export async function revokeGrant( id: Pick, subject: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ revoked: boolean }> { return post<{ revoked: boolean }>("/v1/grants.revoke", { org: id.org, namespace: id.namespace, subject, - }); + }, undefined, intent); } export async function approveGrant( @@ -944,10 +971,11 @@ export async function approveGrant( decision: "approve" | "reject" = "approve", /** Approve with a different role than was asked for (a maintainer request answered as reader). Omit = as asked. */ role?: GrantRole, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ decision: string; role: GrantRole | null }> { const body: Record = { org: id.org, namespace: id.namespace, subject, decision }; if (role) body.role = role; - return post("/v1/grants.approve", body); + return post("/v1/grants.approve", body, undefined, intent); } // ===== Connected agents ===== @@ -1078,6 +1106,7 @@ export async function removeAllowlist( memory_key_a: string, memory_key_b: string, opts: { reason?: string; removed_by?: string } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ removed: boolean }> { return post("/v1/conflicts.allowlist_remove", { org: id.org, @@ -1086,7 +1115,7 @@ export async function removeAllowlist( memory_key_b, reason: opts.reason ?? "", removed_by: opts.removed_by ?? "", - }); + }, undefined, intent); } export async function resolveConflict( @@ -1094,6 +1123,7 @@ export async function resolveConflict( memory_id: string, decision: ResolveDecision, opts: { peer_id?: string; reason?: string; resolved_by?: string } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ resolved: boolean; affected_memory_ids: string[]; @@ -1110,7 +1140,7 @@ export async function resolveConflict( resolved_by: opts.resolved_by ?? "", }; if (opts.peer_id) body["peer_id"] = opts.peer_id; - return post("/v1/conflicts.resolve", body); + return post("/v1/conflicts.resolve", body, undefined, intent); } // ===== cost.budget_status ===== @@ -1188,8 +1218,8 @@ export interface ClaimReleaseResponse { grants_revoked: number; } -export async function claimRelease(org: string, namespace: string, reason: string = ""): Promise { - return post("/v1/admin/claim_release", { org, namespace, reason }); +export async function claimRelease(org: string, namespace: string, reason: string = "", intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/admin/claim_release", { org, namespace, reason }, undefined, intent); } /** Mint a JWT for a chosen namespace. Returns 404 if LOOM_SELF_SIGNUP=off. */ @@ -1238,8 +1268,8 @@ export interface MyNamespaceEntry { /** POST /v1/namespace.mark_seen: the caller picked `namespace` in the picker, so list_mine * stops calling it new. */ -export async function markNamespaceSeen(org: string, namespace: string): Promise { - return post("/v1/namespace.mark_seen", { org, namespace }); +export async function markNamespaceSeen(org: string, namespace: string, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/namespace.mark_seen", { org, namespace }, undefined, intent); } export async function listMine(org: string, opts: RequestOpts = {}): Promise { @@ -1290,6 +1320,7 @@ export async function copyMemoryTo( memoryKey: string, toNamespace: string, opts: { targetKey?: string; rationale?: string } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/memory.copy_to", { from_org: source.org, @@ -1303,7 +1334,7 @@ export async function copyMemoryTo( to_namespace: toNamespace, target_key: opts.targetKey ?? null, rationale: opts.rationale ?? "", - }); + }, undefined, intent); } export interface SharingAgentRow { @@ -1407,10 +1438,12 @@ export async function createToken(opts: { ttl_days: number | null; /** A list's save target, one of its memory namespaces it writes; not sent with `*`. */ saves_to?: string; -}): Promise { +}, intent: "automatic" | "explicit" = "automatic"): Promise { const r = await post & Pick>( "/v1/me/service_accounts.create", opts, + undefined, + intent, ); // A replica of the previous build answers a list mint without the fields it added // (docs/architecture/rolling-upgrades.md, rule 35): the token is still shown. @@ -1428,8 +1461,8 @@ export async function createToken(opts: { }; } -export async function revokeToken(name: string): Promise { - await post("/v1/me/service_accounts.revoke", { name }); +export async function revokeToken(name: string, intent: "automatic" | "explicit" = "automatic"): Promise { + await post("/v1/me/service_accounts.revoke", { name }, undefined, intent); } export interface BrowseEntry { @@ -1521,8 +1554,9 @@ export async function saveNamespaceGuide( org: string, namespace: string, edit: { content: string; summary?: string; note: string; expected_revision: number }, + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/namespace.guide_set", { org, namespace, ...edit }); + return post("/v1/namespace.guide_set", { org, namespace, ...edit }, undefined, intent); } export interface JoinResponse { @@ -1541,10 +1575,11 @@ export async function joinNamespace( org: string, namespace: string, opts: { role?: "viewer" | "writer" | "admin" } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { const body: Record = { org, namespace }; if (opts.role) body.role = opts.role; - return post("/v1/namespace.join", body); + return post("/v1/namespace.join", body, undefined, intent); } /** Withdraw the caller's own pending elevation request. Keeps their @@ -1552,14 +1587,15 @@ export async function joinNamespace( export async function cancelNamespaceRequest( org: string, namespace: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ cancelled: boolean; namespace: string; cleared_role: string | null; cancelled_at: string | null }> { - return post("/v1/namespace.cancel_request", { org, namespace }); + return post("/v1/namespace.cancel_request", { org, namespace }, undefined, intent); } /** Give up the caller's own membership of a namespace (their grant is * revoked; nothing else changes). Used by the Code view's Leave. */ -export async function leaveNamespace(org: string, namespace: string): Promise<{ left: boolean; namespace: string }> { - return post("/v1/namespace.leave", { org, namespace }); +export async function leaveNamespace(org: string, namespace: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ left: boolean; namespace: string }> { + return post("/v1/namespace.leave", { org, namespace }, undefined, intent); } export type CodeId = { org: string; namespace: string }; diff --git a/frontend/src/api/admin.ts b/frontend/src/api/admin.ts index df6b542e39..536dfb3ca2 100644 --- a/frontend/src/api/admin.ts +++ b/frontend/src/api/admin.ts @@ -1,3 +1,4 @@ +import { ADMIN_SETTINGS_READ_ROUTES } from "./adminReadRoutes"; // The API client is split by plane behind the `api.ts` barrel, so a view's client rides // in that view's chunk and the shell evaluates only the functions it calls. Importers // still import from `api.ts`. @@ -293,12 +294,13 @@ export async function getNamespace( export async function setConversationLogging( id: Pick, enabled: boolean, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ namespace: string; enabled: boolean }> { return post("/v1/conversation.set_logging", { org: id.org, namespace: id.namespace, enabled, - }); + }, undefined, intent); } /** The fields namespace.register writes. */ @@ -326,6 +328,7 @@ type RegisterResult = { registered: boolean; namespace: string; updated_at: stri export async function registerNamespace( id: Pick, opts: NamespaceRegisterFields, + intent: "automatic" | "explicit" = "automatic", ): Promise { const body: Record = { org: id.org, @@ -353,7 +356,7 @@ export async function registerNamespace( if (opts.capture_generation_io !== undefined) { body["capture_generation_io"] = opts.capture_generation_io; } - return post("/v1/namespace.register", body); + return post("/v1/namespace.register", body, undefined, intent); } /** Rewrite an existing namespace's row with `patch` applied. The fields the settings @@ -363,6 +366,7 @@ export async function reregisterNamespace( id: Pick, ns: NamespaceInfo, patch: Partial, + intent: "automatic" | "explicit" = "automatic", ): Promise { return registerNamespace(id, { owner_email: ns.owner_email, @@ -376,7 +380,7 @@ export async function reregisterNamespace( requires_approval: ns.requires_approval ?? false, capture_generation_io: ns.capture_generation_io, ...patch, - }); + }, intent); } /** Soft-delete a namespace (sets active=false); existing memories + @@ -384,8 +388,9 @@ export async function reregisterNamespace( * data must go too. */ export async function deleteNamespace( id: Pick, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ deleted: boolean; namespace: string; updated_at: string }> { - return post("/v1/namespace.delete", { org: id.org, namespace: id.namespace }); + return post("/v1/namespace.delete", { org: id.org, namespace: id.namespace }, undefined, intent); } // ===== Consolidations ===== @@ -555,8 +560,9 @@ export async function requestErasure( requester: string, purge: boolean, signal?: AbortSignal, + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/erasure.request", { org, ...scope, requester, purge }, signal); + return post("/v1/erasure.request", { org, ...scope, requester, purge }, signal, intent); } /** Mirrors `server/erasure/api/erasure.py::ErasureStatusOutput` (the parts shown). */ @@ -594,8 +600,9 @@ export async function clearAgentMemories( id: Pick, agent: string, signal?: AbortSignal, + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/memory.clear", { org: id.org, namespace: id.namespace, agent, confirm_subject: agent }, signal); + return post("/v1/memory.clear", { org: id.org, namespace: id.namespace, agent, confirm_subject: agent }, signal, intent); } /** One (token, agent) that read the namespace: `server/memory/api/models_exposure.py`. */ @@ -752,6 +759,7 @@ export async function addBlacklist( reason?: string; created_by?: string; } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ pattern_id: string; created_at: string }> { return post("/v1/blacklist.add", { org: id.org, @@ -761,20 +769,21 @@ export async function addBlacklist( scope: opts.scope ?? "namespace", reason: opts.reason ?? "", created_by: opts.created_by ?? "", - }); + }, undefined, intent); } export async function removeBlacklist( id: Pick, pattern_id: string, opts: { removed_by?: string; reason?: string } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ removed: boolean; removed_at: string | null }> { return post("/v1/blacklist.remove", { org: id.org, pattern_id, removed_by: opts.removed_by ?? "", reason: opts.reason ?? "", - }); + }, undefined, intent); } // ===== History policy ===== @@ -834,6 +843,7 @@ export async function setPolicy( description?: string; enabled?: boolean; }, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ rule: PolicyRule; leaf_count: number }> { return post("/v1/policy.set", { org: id.org, @@ -844,14 +854,15 @@ export async function setPolicy( condition: rule.condition, description: rule.description ?? "", enabled: rule.enabled ?? true, - }); + }, undefined, intent); } export async function deletePolicy( id: Pick, policy_id: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ removed: boolean }> { - return post("/v1/policy.delete", { org: id.org, namespace: id.namespace, policy_id }); + return post("/v1/policy.delete", { org: id.org, namespace: id.namespace, policy_id }, undefined, intent); } export interface PolicyLeafResult { @@ -896,6 +907,7 @@ export async function checkPolicy( at?: string; rules?: PolicyCondition[]; }, + intent: "automatic" | "explicit" = "automatic", ): Promise { const body: Record = { org: id.org, @@ -908,7 +920,7 @@ export async function checkPolicy( }; if (req.at) body["at"] = req.at; if (req.rules) body["rules"] = req.rules; - return post("/v1/policy.check", body); + return post("/v1/policy.check", body, undefined, intent); } export interface PolicyDecisionRow { @@ -1087,25 +1099,25 @@ export interface SettingChange { /** POST /v1/admin/settings.list — every setting's value in force on the replica that answers. */ export async function adminSettingsList(opts: RequestOpts = {}): Promise { - const out = await post<{ settings: SettingRow[] }>("/v1/admin/settings.list", {}, opts.signal); + const out = await post<{ settings: SettingRow[] }>(ADMIN_SETTINGS_READ_ROUTES.list, {}, opts.signal); return out.settings; } /** POST /v1/admin/settings.set — override a live setting, refused (409) unless `expected` * is still the value in force. */ -export async function adminSettingSet(name: string, value: unknown, expected: unknown): Promise { - const out = await post<{ setting: SettingRow }>("/v1/admin/settings.set", { name, value, expected }); +export async function adminSettingSet(name: string, value: unknown, expected: unknown, intent: "automatic" | "explicit" = "automatic"): Promise { + const out = await post<{ setting: SettingRow }>("/v1/admin/settings.set", { name, value, expected }, undefined, intent); return out.setting; } /** POST /v1/admin/settings.set with `clear` — back to the environment's value or the default. */ -export async function adminSettingReset(name: string, expected: unknown): Promise { - const out = await post<{ setting: SettingRow }>("/v1/admin/settings.set", { name, clear: true, expected }); +export async function adminSettingReset(name: string, expected: unknown, intent: "automatic" | "explicit" = "automatic"): Promise { + const out = await post<{ setting: SettingRow }>("/v1/admin/settings.set", { name, clear: true, expected }, undefined, intent); return out.setting; } /** POST /v1/admin/settings.history — recorded changes, newest first. */ export async function adminSettingsHistory(name = "", limit = 50, opts: RequestOpts = {}): Promise { - const out = await post<{ changes: SettingChange[] }>("/v1/admin/settings.history", { name, limit }, opts.signal); + const out = await post<{ changes: SettingChange[] }>(ADMIN_SETTINGS_READ_ROUTES.history, { name, limit }, opts.signal); return out.changes; } diff --git a/frontend/src/api/adminReadRoutes.ts b/frontend/src/api/adminReadRoutes.ts new file mode 100644 index 0000000000..98eb1ca5b0 --- /dev/null +++ b/frontend/src/api/adminReadRoutes.ts @@ -0,0 +1,5 @@ +// These operator reads have dedicated HTTP handlers outside the operation registry. +export const ADMIN_SETTINGS_READ_ROUTES = Object.freeze({ + list: "/v1/admin/settings.list", + history: "/v1/admin/settings.history", +}); diff --git a/frontend/src/api/assistantChat.ts b/frontend/src/api/assistantChat.ts index d68449aad6..9524c3b76f 100644 --- a/frontend/src/api/assistantChat.ts +++ b/frontend/src/api/assistantChat.ts @@ -146,12 +146,14 @@ export async function streamAssistantChat( messages: ChatMessage[], on: ChatHandlers, signal: AbortSignal, + intent: "automatic" | "explicit" = "automatic", ): Promise { const r = await postStreaming( CHAT_PATH, { stream: true, messages }, { "X-Loom-Namespace": namespace, Accept: "text/event-stream" }, signal, + intent, ); if (!r.body) throw new ApiError({ status: r.status, message: "the answer carried no body" }); const requestId = r.headers.get("X-Request-Id") ?? ""; diff --git a/frontend/src/api/briefs.ts b/frontend/src/api/briefs.ts index 7f00066cbe..59c1cf926b 100644 --- a/frontend/src/api/briefs.ts +++ b/frontend/src/api/briefs.ts @@ -75,11 +75,12 @@ export async function listBriefs( export async function deleteBrief( id: Pick, briefKey: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ deleted: boolean }> { return post("/v1/session.brief_delete", { org: id.org, namespace: id.namespace, agent: "loom-ui", brief_key: briefKey, - }); + }, undefined, intent); } diff --git a/frontend/src/api/code.ts b/frontend/src/api/code.ts index abfcd30908..a924320173 100644 --- a/frontend/src/api/code.ts +++ b/frontend/src/api/code.ts @@ -110,8 +110,9 @@ export async function addCodeRepo( /** More branches chosen at add time, each its own index. */ branches?: string[]; }, + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/code.repo.add", { org, ...body }); + return post("/v1/code.repo.add", { org, ...body }, undefined, intent); } /** What a Git remote shows before anything is written — every branch, the @@ -159,8 +160,8 @@ export interface CodeRepoRemoveResult { erasure_id: string; mirror_removed: boolean; } -export async function removeCodeRepo(org: string, namespace: string): Promise { - return post("/v1/code.repo.remove", { org, namespace, confirm: namespace }); +export async function removeCodeRepo(org: string, namespace: string, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/code.repo.remove", { org, namespace, confirm: namespace }, undefined, intent); } /** A maintainer sets a repository's access — classification and join policy. Opening a @@ -183,6 +184,7 @@ export async function setCodeRepoAccess( classification: "standard" | "restricted", join_policy: "open" | "approval" | "closed", confirm = "", + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/code.repo.set_access", { org, @@ -190,7 +192,7 @@ export async function setCodeRepoAccess( classification, join_policy, confirm, - }); + }, undefined, intent); } /** A maintainer binds the tracker record (issues, PRs, tests, incidents) a repository's @@ -211,13 +213,14 @@ export async function setCodeRepoSource( org: string, namespace: string, tracker_namespaces: string[], + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/code.repo.set_source", { org, namespace, tracker_namespaces }); + return post("/v1/code.repo.set_source", { org, namespace, tracker_namespaces }, undefined, intent); } /** A maintainer indexes another branch of a repository they maintain. */ -export async function addCodeBranch(org: string, namespace: string, branch: string): Promise { - return post("/v1/code.repo.add_branch", { org, namespace, branch }); +export async function addCodeBranch(org: string, namespace: string, branch: string, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/code.repo.add_branch", { org, namespace, branch }, undefined, intent); } export interface CodeWorkerStatus { @@ -263,14 +266,15 @@ export interface CodeIndexStatus extends Omit { export async function codeRefresh( id: CodeId, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ triggered: boolean; already_running: boolean; head_before: string; head_after: string }> { - return post("/v1/code.refresh", { ...id, agent: "loom-ui", wait: false }); + return post("/v1/code.refresh", { ...id, agent: "loom-ui", wait: false }, undefined, intent); } /** POST /v1/code.reindex (ADMIN): move the index's git watermark to `gitHead`; the ingest * worker indexes the commits after it again. */ -export async function codeReindex(id: CodeId, gitHead: string): Promise<{ previous_head: string; new_head: string }> { - return post("/v1/code.reindex", { ...id, agent: "loom-ui", git_head: gitHead }); +export async function codeReindex(id: CodeId, gitHead: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ previous_head: string; new_head: string }> { + return post("/v1/code.reindex", { ...id, agent: "loom-ui", git_head: gitHead }, undefined, intent); } export interface CodeUnit { diff --git a/frontend/src/api/collections.ts b/frontend/src/api/collections.ts index 025e51741f..709539b1d8 100644 --- a/frontend/src/api/collections.ts +++ b/frontend/src/api/collections.ts @@ -57,6 +57,7 @@ export async function createCollection( org: string, namespace: string, opts: { parent?: string; description?: string; title?: string; deriveName?: boolean } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/collection.create", { org, @@ -65,7 +66,7 @@ export async function createCollection( description: opts.description ?? "", title: opts.title ?? "", derive_name: opts.deriveName ?? false, - }); + }, undefined, intent); } export interface CollectionDeleteResult { @@ -80,8 +81,8 @@ export interface CollectionDeleteResult { /** Delete a collection with what it holds: a purging erasure of its namespace, then it * leaves the directory and the tree, and its children become top-level. */ -export async function deleteCollection(org: string, namespace: string): Promise { - return post("/v1/collection.delete", { org, namespace }); +export async function deleteCollection(org: string, namespace: string, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/collection.delete", { org, namespace }, undefined, intent); } /** POST /v1/collection.move (ADMIN): put a collection under `parent`, or "" to make it @@ -90,6 +91,7 @@ export async function moveCollection( org: string, namespace: string, parent: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ namespace: string; parent: string; moved: boolean }> { - return post("/v1/collection.move", { org, namespace, parent }); + return post("/v1/collection.move", { org, namespace, parent }, undefined, intent); } diff --git a/frontend/src/api/connections.test.ts b/frontend/src/api/connections.test.ts deleted file mode 100644 index e155bb0a43..0000000000 --- a/frontend/src/api/connections.test.ts +++ /dev/null @@ -1,61 +0,0 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; -import { clearToken, setPageOwner, setToken } from "../api"; -import { ApiError } from "../lib/errors"; -import { disconnectConnection, listConnections, startConnection } from "./connections"; - -afterEach(() => { - clearToken(); - setPageOwner(null); - vi.unstubAllGlobals(); -}); - -describe("connected account API", () => { - it("uses the own-account ops and authenticated start route with abort signals", async () => { - setPageOwner(null); - setToken("personal-test-bearer"); - const fetch = vi.fn(async (_url: string, _init?: RequestInit) => new Response("{}")); - vi.stubGlobal("fetch", fetch); - const controller = new AbortController(); - await listConnections("acme", { signal: controller.signal }); - await disconnectConnection("acme", "notion", { signal: controller.signal }); - await startConnection("linear", { signal: controller.signal }); - expect(fetch.mock.calls.map(([path]) => path)).toEqual([ - "/v1/connection.list", - "/v1/connection.disconnect", - "/v1/connect/linear/start", - ]); - const bodies = fetch.mock.calls.map(([, init]) => JSON.parse(String(init?.body))); - expect(bodies[0]).toMatchObject({ org: "acme" }); - expect(bodies[1]).toMatchObject({ org: "acme", kind: "notion" }); - for (const body of bodies) { - expect(body).not.toHaveProperty("namespace"); - expect(body).not.toHaveProperty("subject"); - expect(body).not.toHaveProperty("credential"); - } - for (const [, init] of fetch.mock.calls) { - expect(init?.method).toBe("POST"); - expect(init?.headers).toMatchObject({ Authorization: "Bearer personal-test-bearer" }); - expect(init?.signal).toBe(controller.signal); - } - controller.abort(); - expect(fetch.mock.calls.every(([, init]) => init?.signal?.aborted)).toBe(true); - }); - - it("keeps the shared transport's structured refusal and request id", async () => { - vi.stubGlobal( - "fetch", - vi.fn( - async () => - new Response( - JSON.stringify({ detail: { code: "AUTH_INSUFFICIENT", message: "a primary sign-in session is required" } }), - { status: 403, headers: { "X-Request-Id": "connect-refusal" } }, - ), - ), - ); - await expect(startConnection("gdrive")).rejects.toMatchObject({ - status: 403, - code: "AUTH_INSUFFICIENT", - requestId: "connect-refusal", - } satisfies Partial); - }); -}); diff --git a/frontend/src/api/connections.ts b/frontend/src/api/connections.ts deleted file mode 100644 index 9a596491bd..0000000000 --- a/frontend/src/api/connections.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { post, type RequestOpts } from "../api"; - -export const CONNECTION_KINDS = ["gdrive", "notion", "linear"] as const; -export type ConnectionKind = (typeof CONNECTION_KINDS)[number]; - -/** The public connection.list entry; credentials never cross this boundary. */ -export interface ConnectionEntry { - kind: ConnectionKind; - connected: boolean; - account_email: string | null; - scopes: string[]; - connect_url: string; -} - -export function listConnections(org: string, opts: RequestOpts = {}): Promise<{ connections: ConnectionEntry[] }> { - return post("/v1/connection.list", { org }, opts.signal); -} - -export function disconnectConnection( - org: string, - kind: ConnectionKind, - opts: RequestOpts = {}, -): Promise<{ disconnected: boolean }> { - return post("/v1/connection.disconnect", { org, kind }, opts.signal); -} - -export function startConnection(kind: ConnectionKind, opts: RequestOpts = {}): Promise<{ authorization_url: string }> { - return post(`/v1/connect/${kind}/start`, {}, opts.signal); -} diff --git a/frontend/src/api/conversations.ts b/frontend/src/api/conversations.ts index f400f00ff1..18b5fa40ce 100644 --- a/frontend/src/api/conversations.ts +++ b/frontend/src/api/conversations.ts @@ -206,6 +206,7 @@ export async function reviewLearning( candidate_id: string, decision: ReviewDecision, reason: string = "", + intent: "automatic" | "explicit" = "automatic", ): Promise<{ candidate_id: string; new_status: LearningStatus; @@ -218,7 +219,7 @@ export async function reviewLearning( candidate_id, decision, reason, - }); + }, undefined, intent); } /** POST /v1/conversation.create: a thread row for a thread built by appends only, which @@ -228,8 +229,9 @@ export async function createThreadRow( agent: string, threadId: string, title: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ thread_id: string }> { - return post("/v1/conversation.create", { org: id.org, namespace: id.namespace, agent, thread_id: threadId, title }); + return post("/v1/conversation.create", { org: id.org, namespace: id.namespace, agent, thread_id: threadId, title }, undefined, intent); } /** POST /v1/conversation.update: a thread's new title. */ @@ -238,8 +240,9 @@ export async function renameThread( agent: string, threadId: string, title: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ updated: boolean }> { - return post("/v1/conversation.update", { org: id.org, namespace: id.namespace, agent, thread_id: threadId, title }); + return post("/v1/conversation.update", { org: id.org, namespace: id.namespace, agent, thread_id: threadId, title }, undefined, intent); } /** POST /v1/conversation.delete (ADMIN): tombstones the thread and its messages; the @@ -248,6 +251,7 @@ export async function deleteThread( id: Pick, agent: string, threadId: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ total: number }> { return post("/v1/conversation.delete", { org: id.org, @@ -255,5 +259,5 @@ export async function deleteThread( agent, thread_id: threadId, confirm_thread_id: threadId, - }); + }, undefined, intent); } diff --git a/frontend/src/api/guardrails.ts b/frontend/src/api/guardrails.ts index 1d6f412f69..97d5bcce3f 100644 --- a/frontend/src/api/guardrails.ts +++ b/frontend/src/api/guardrails.ts @@ -9,8 +9,9 @@ type Scope = Pick; export async function sweepBlacklistPattern( id: Scope, patternId: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ matched: number; tombstoned: number; truncated: boolean; error: string }> { - return post("/v1/blacklist.sweep", { org: id.org, namespace: id.namespace, pattern_id: patternId }); + return post("/v1/blacklist.sweep", { org: id.org, namespace: id.namespace, pattern_id: patternId }, undefined, intent); } // ===== Extraction policy (org admin) ===== @@ -37,12 +38,12 @@ export async function getExtractionPolicy( return post("/v1/extraction_policy.get", policyBody(id, scope), opts.signal); } -export async function setExtractionPolicy(id: Scope, scope: PolicyScope, policy: string): Promise { - return post("/v1/extraction_policy.set", { ...policyBody(id, scope), policy }); +export async function setExtractionPolicy(id: Scope, scope: PolicyScope, policy: string, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/extraction_policy.set", { ...policyBody(id, scope), policy }, undefined, intent); } -export async function clearExtractionPolicy(id: Scope, scope: PolicyScope): Promise { - return post("/v1/extraction_policy.clear", policyBody(id, scope)); +export async function clearExtractionPolicy(id: Scope, scope: PolicyScope, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/extraction_policy.clear", policyBody(id, scope), undefined, intent); } // ===== The org's model calls (org admin) ===== @@ -62,6 +63,6 @@ export async function getOrgModelCalls(org: string, opts: RequestOpts = {}): Pro return post("/v1/org.model_calls", { org }, opts.signal); } -export async function setOrgModelCalls(org: string, enabled: boolean, reason: string): Promise { - return post("/v1/org.set_model_calls", { org, enabled, reason }); +export async function setOrgModelCalls(org: string, enabled: boolean, reason: string, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/org.set_model_calls", { org, enabled, reason }, undefined, intent); } diff --git a/frontend/src/api/knowledge.ts b/frontend/src/api/knowledge.ts index 5e9614d5f7..d220be343b 100644 --- a/frontend/src/api/knowledge.ts +++ b/frontend/src/api/knowledge.ts @@ -85,6 +85,7 @@ export async function updateKnowledgeMetadata( * content re-upload would, without re-uploading the file. */ reindex?: boolean; }, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ updated: boolean; title: string; description: string; tags: string[]; chunks_reindexed: number }> { return post("/v1/knowledge.update_metadata", { org: id.org, @@ -94,15 +95,15 @@ export async function updateKnowledgeMetadata( ...(patch.description !== undefined ? { description: patch.description } : {}), ...(patch.tags !== undefined ? { tags: patch.tags } : {}), ...(patch.reindex ? { reindex: true } : {}), - }); + }, undefined, intent); } -export async function deleteKnowledge(id: Pick, sourceUri: string): Promise { +export async function deleteKnowledge(id: Pick, sourceUri: string, intent: "automatic" | "explicit" = "automatic"): Promise { await post("/v1/knowledge.delete", { org: id.org, namespace: id.namespace, source_uri: sourceUri, - }); + }, undefined, intent); } export type RestoreRefusal = "not_found" | "live" | "revision_mismatch" | "not_restorable" | "expired"; @@ -119,8 +120,9 @@ export type KnowledgeRestoreResult = { export async function restoreKnowledge( id: Pick, sourceUri: string, + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/knowledge.restore", { org: id.org, namespace: id.namespace, source_uri: sourceUri }); + return post("/v1/knowledge.restore", { org: id.org, namespace: id.namespace, source_uri: sourceUri }, undefined, intent); } /** Why a document did not move (`knowledge.move`'s `reason`). */ @@ -155,6 +157,7 @@ export async function moveKnowledge( sourceUris: string[], signal?: AbortSignal, onCall?: (results: KnowledgeMoveResult[]) => void, + intent: "automatic" | "explicit" = "automatic", ): Promise { const results: KnowledgeMoveResult[] = []; for (let i = 0; i < sourceUris.length && !signal?.aborted; i += MOVE_MAX) { @@ -165,7 +168,7 @@ export async function moveKnowledge( namespace: id.namespace, to_namespace: to, source_uris: sourceUris.slice(i, i + MOVE_MAX), - }); + }, undefined, intent); } catch (error) { onCall?.([]); return { found: true, results, error }; @@ -187,12 +190,13 @@ export interface KnowledgeBulkDeleteResult { export async function bulkDeleteKnowledge( id: Pick, sourceUris: string[], + intent: "automatic" | "explicit" = "automatic", ): Promise<{ results: KnowledgeBulkDeleteResult[]; total_tombstoned: number }> { return post("/v1/knowledge.bulk_delete", { org: id.org, namespace: id.namespace, source_uris: sourceUris, - }); + }, undefined, intent); } export interface KnowledgeDocument { @@ -263,6 +267,7 @@ export async function addKnowledge( tags?: string[]; upsert?: boolean; }, + intent: "automatic" | "explicit" = "automatic", ): Promise { const body: Record = { org: id.org, @@ -276,7 +281,7 @@ export async function addKnowledge( // knowledge.upsert replaces existing chunks for the same source_uri; // knowledge.add is add-only and 409s on duplicates. Default to upsert. const path = opts.upsert === false ? "/v1/knowledge.add" : "/v1/knowledge.upsert"; - return post(path, body); + return post(path, body, undefined, intent); } /** A passage `knowledge.search` found: its document, where it sits (`locator`, read for @@ -365,6 +370,7 @@ export async function uploadKnowledgeFile( id: Pick, file: File, signal?: AbortSignal, + intent: "automatic" | "explicit" = "automatic", ): Promise { const q = new URLSearchParams({ org: id.org, @@ -372,7 +378,7 @@ export async function uploadKnowledgeFile( filename: file.name, content_type: file.type, }); - return postFile(`/v1/knowledge.upload?${q}`, file, signal); + return postFile(`/v1/knowledge.upload?${q}`, file, signal, intent); } export interface KnowledgeIngestJob { @@ -397,6 +403,7 @@ export interface KnowledgeIngestFields { export async function ingestKnowledge( id: Pick, opts: KnowledgeIngestFields & { upload_id: string }, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/knowledge.ingest", { org: id.org, @@ -408,7 +415,7 @@ export async function ingestKnowledge( tags: opts.tags || [], allow_partial: !!opts.allow_partial, ...(opts.expected_revision === undefined ? {} : { expected_revision: opts.expected_revision }), - }); + }, undefined, intent); } export interface KnowledgeIngestStatus { @@ -479,6 +486,7 @@ export async function approveDataset( sourceUri: string, dataset: Pick, columns: Record, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ found: boolean; retyped: boolean }> { return post("/v1/knowledge.dataset_approve", { org: id.org, @@ -487,7 +495,7 @@ export async function approveDataset( dataset_id: dataset.dataset_id, snapshot_id: dataset.snapshot_id, columns, - }); + }, undefined, intent); } export interface IngestCancelResult { @@ -501,8 +509,9 @@ export interface IngestCancelResult { export async function cancelIngestion( id: Pick, ingestionId: string, + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/knowledge.ingest_cancel", { org: id.org, namespace: id.namespace, ingestion_id: ingestionId }); + return post("/v1/knowledge.ingest_cancel", { org: id.org, namespace: id.namespace, ingestion_id: ingestionId }, undefined, intent); } /** How the Library shows an original file. An uploaded file is @@ -650,6 +659,7 @@ export async function importCuratedDoc( heading_level?: number; extra_tags?: string[]; }, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/memory.import_curated", { org: id.org, @@ -658,5 +668,5 @@ export async function importCuratedDoc( source_uri: opts.source_uri || "", heading_level: opts.heading_level ?? 2, extra_tags: opts.extra_tags || [], - }); + }, undefined, intent); } diff --git a/frontend/src/api/knowledgeGaps.ts b/frontend/src/api/knowledgeGaps.ts index b256318d7b..9c85201b1b 100644 --- a/frontend/src/api/knowledgeGaps.ts +++ b/frontend/src/api/knowledgeGaps.ts @@ -39,6 +39,7 @@ export async function listKnowledgeGaps( export async function draftKnowledgeGap( id: Pick, gapId: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ candidate_id: string }> { - return post("/v1/knowledge.gaps.draft", { ...id, gap_id: gapId }); + return post("/v1/knowledge.gaps.draft", { ...id, gap_id: gapId }, undefined, intent); } diff --git a/frontend/src/api/knowledgeSources.ts b/frontend/src/api/knowledgeSources.ts index 9000ac7014..332d618a7f 100644 --- a/frontend/src/api/knowledgeSources.ts +++ b/frontend/src/api/knowledgeSources.ts @@ -33,8 +33,8 @@ export async function inspectKnowledgeSource( } /** `dryRun` probes the credential and stores nothing. */ -export async function addKnowledgeSource(id: Ns, form: SourceForm, dryRun: boolean): Promise { - return post("/v1/knowledge.source.add", sourceAddBody(id.org, id.namespace, form, dryRun)); +export async function addKnowledgeSource(id: Ns, form: SourceForm, dryRun: boolean, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/knowledge.source.add", sourceAddBody(id.org, id.namespace, form, dryRun), undefined, intent); } /** Closing the Check dialog aborts the probe through `opts.signal`. */ @@ -42,11 +42,13 @@ export async function checkKnowledgeSource( id: Ns, name: string, opts: RequestOpts = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post( "/v1/knowledge.source.check", { org: id.org, namespace: id.namespace, name }, opts.signal, + intent, ); } @@ -54,13 +56,14 @@ export async function rotateKnowledgeSource( id: Ns, name: string, credential: string, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/knowledge.source.rotate", { org: id.org, namespace: id.namespace, name, credential, - }); + }, undefined, intent); } export async function removeKnowledgeSource( @@ -68,6 +71,7 @@ export async function removeKnowledgeSource( name: string, confirm: string, deleteDocuments: boolean, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/knowledge.source.remove", { org: id.org, @@ -75,18 +79,19 @@ export async function removeKnowledgeSource( name, confirm, delete_documents: deleteDocuments, - }); + }, undefined, intent); } export async function syncKnowledgeSourceNow( id: Ns, name: string, full: boolean, + intent: "automatic" | "explicit" = "automatic", ): Promise { return post("/v1/knowledge.source.sync_now", { org: id.org, namespace: id.namespace, name, full, - }); + }, undefined, intent); } diff --git a/frontend/src/api/maintenance.ts b/frontend/src/api/maintenance.ts index dbd28a60ca..2b0ce172af 100644 --- a/frontend/src/api/maintenance.ts +++ b/frontend/src/api/maintenance.ts @@ -79,28 +79,29 @@ export interface ExpirySweep { export const SWEEP_LIMIT = 500; /** POST /v1/memory.sweep_expired: the expiry worker's pass, now, for this namespace. */ -export async function sweepExpired(id: Scope, dryRun: boolean): Promise { +export async function sweepExpired(id: Scope, dryRun: boolean, intent: "automatic" | "explicit" = "automatic"): Promise { return post("/v1/memory.sweep_expired", { org: id.org, namespace: id.namespace, dry_run: dryRun, limit: SWEEP_LIMIT, - }); + }, undefined, intent); } export const REEMBED_LIMIT = 200; /** POST /v1/memory.reindex: re-embed up to REEMBED_LIMIT memories another embedding model made. */ -export async function reembedMemories(id: Scope): Promise<{ processed: number; target_model: string }> { - return post("/v1/memory.reindex", { org: id.org, namespace: id.namespace, limit: REEMBED_LIMIT }); +export async function reembedMemories(id: Scope, intent: "automatic" | "explicit" = "automatic"): Promise<{ processed: number; target_model: string }> { + return post("/v1/memory.reindex", { org: id.org, namespace: id.namespace, limit: REEMBED_LIMIT }, undefined, intent); } /** POST /v1/facts.expire_by_adapter: tombstone the graph facts one extractor emitted. */ export async function expireAdapterFacts( id: Scope, adapter: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ expired_triples: number; expired_triple_memories: number }> { - return post("/v1/facts.expire_by_adapter", { org: id.org, namespace: id.namespace, adapter_name: adapter }); + return post("/v1/facts.expire_by_adapter", { org: id.org, namespace: id.namespace, adapter_name: adapter }, undefined, intent); } /** Mirrors `server/identity/api/models.py::NamespaceRollbackOutput` (the counts). */ @@ -111,13 +112,13 @@ export interface Rollback { } /** POST /v1/namespace.rollback: every memory head back to its version at `asOf` (ISO). */ -export async function rollbackNamespace(id: Scope, asOf: string, dryRun: boolean): Promise { - return post("/v1/namespace.rollback", { org: id.org, namespace: id.namespace, as_of: asOf, dry_run: dryRun }); +export async function rollbackNamespace(id: Scope, asOf: string, dryRun: boolean, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/namespace.rollback", { org: id.org, namespace: id.namespace, as_of: asOf, dry_run: dryRun }, undefined, intent); } /** POST /v1/namespace.snapshot: the namespace's curated state as one JSON payload. */ -export async function snapshotNamespace(id: Scope): Promise> { - return post("/v1/namespace.snapshot", { org: id.org, namespace: id.namespace }); +export async function snapshotNamespace(id: Scope, intent: "automatic" | "explicit" = "automatic"): Promise> { + return post("/v1/namespace.snapshot", { org: id.org, namespace: id.namespace }, undefined, intent); } /** POST /v1/namespace.restore: a snapshot payload into `target`. A snapshot already @@ -126,8 +127,9 @@ export async function restoreNamespace( org: string, target: string, payload: unknown, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ restored: boolean; counts: { memories: number; erased_skipped: number } }> { - return post("/v1/namespace.restore", { org, target_namespace: target, payload }); + return post("/v1/namespace.restore", { org, target_namespace: target, payload }, undefined, intent); } // ===== Projection failures (org admin) ===== @@ -175,10 +177,11 @@ export const RETRY_LIMIT = 50; export async function retryProjectionFailures( id: Scope, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ results: ProjectionRetry[]; retried: number; resolved: number; abandoned: number }> { - return post("/v1/ops.projection_failures.retry", { org: id.org, namespace: id.namespace, limit: RETRY_LIMIT }); + return post("/v1/ops.projection_failures.retry", { org: id.org, namespace: id.namespace, limit: RETRY_LIMIT }, undefined, intent); } -export async function resolveProjectionFailures(org: string, ids: string[]): Promise<{ resolved: number }> { - return post("/v1/ops.projection_failures.resolve", { org, failure_ids: ids }); +export async function resolveProjectionFailures(org: string, ids: string[], intent: "automatic" | "explicit" = "automatic"): Promise<{ resolved: number }> { + return post("/v1/ops.projection_failures.resolve", { org, failure_ids: ids }, undefined, intent); } diff --git a/frontend/src/api/mcpSources.test.ts b/frontend/src/api/mcpSources.test.ts new file mode 100644 index 0000000000..e15da49be7 --- /dev/null +++ b/frontend/src/api/mcpSources.test.ts @@ -0,0 +1,83 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +vi.mock("../api", () => ({ post: vi.fn() })); +import { post } from "../api"; +import { + mcpAdd, mcpConnect, mcpConnections, mcpControl, mcpDiscover, mcpDisconnect, mcpInspect, + mcpInspectConnection, mcpList, mcpPreview, mcpProfiles, mcpRemove, mcpUpdate, mcpBrowse, mcpRead, +} from "./mcpSources"; + +const send = vi.mocked(post); +const selected = { org: "acme", namespace: "col-team", slot: "slot", resource_ids: ["opaque://A?x=%2F", " ID with spaces "], mode: "snapshot", reader_policy: "owner_only" } as const; + +describe("MCP source operation boundary", () => { + beforeEach(() => { vi.clearAllMocks(); send.mockResolvedValue({}); }); + it("uses the shared transport and sends only the connection contract, never invented authority", async () => { + const signal = new AbortController().signal; + const input = { org: "acme", profile_id: "approved", request_id: "nonce", bearer: "secret", owner: "other", endpoint: "https://other.example", tool: "hidden", headers: { protection: "pretend" } }; + await mcpConnect(input, signal); + expect(send).toHaveBeenCalledTimes(1); + expect(send).toHaveBeenCalledWith("/v1/knowledge.connection.mcp_connect", { + org: "acme", profile_id: "approved", request_id: "nonce", bearer: "secret", + }, signal, "automatic"); + }); + it("does not retry a protected-client or session refusal", async () => { + const failure = new Error("SESSION_PROTECTION_REQUIRED"); + send.mockRejectedValue(failure); + await expect(mcpConnect({ org: "acme", profile_id: "p", request_id: "n" })).rejects.toBe(failure); + expect(send).toHaveBeenCalledTimes(1); + }); + it("preserves opaque IDs and has no hidden endpoint, owner, tool or scope fields", async () => { + const input = { ...selected, resource_ids: [...selected.resource_ids], owner: "other", scope: "all", endpoint: "https://other.example" }; + await mcpPreview(input); + expect(send).toHaveBeenLastCalledWith("/v1/knowledge.source.mcp_preview", { ...selected, resource_ids: [...selected.resource_ids] }, undefined, "automatic"); + await mcpAdd({ ...input, request_id: "same-nonce", label: null, confirm_copy_authority: false }); + expect(send).toHaveBeenLastCalledWith("/v1/knowledge.source.mcp_add", { + ...selected, resource_ids: [...selected.resource_ids], request_id: "same-nonce", label: null, confirm_copy_authority: false, + }, undefined, "automatic"); + }); + it("reconciles additions with the original UUID and slot and strips extra authority", async () => { + const request_id = "4a8dbf51-c184-4e4d-8e45-83139cdfc1ba"; + const input = { org: "acme", namespace: "col-team", slot: "original-slot", request_id, owner: "other", endpoint: "https://other.example", source_id: "override" }; + await mcpInspect(input); + expect(send).toHaveBeenLastCalledWith("/v1/knowledge.source.mcp_inspect", { org: "acme", namespace: "col-team", slot: "original-slot", request_id }, undefined, "automatic"); + }); + it("browses one bounded metadata window with no cursor or arbitrary tool", async () => { + const input = { org: "acme", slot: "slot", mode: "search" as const, query: "private query", limit: 37, cursor: "hidden", tool: "execute", endpoint: "https://other.example", owner: "other" }; + await mcpBrowse(input); + expect(send).toHaveBeenLastCalledWith("/v1/knowledge.connection.mcp_browse", { org: "acme", slot: "slot", mode: "search", query: "private query", limit: 37 }, undefined, "automatic"); + await mcpBrowse({ ...input, mode: "resources" }); + expect(send).toHaveBeenLastCalledWith("/v1/knowledge.connection.mcp_browse", { org: "acme", slot: "slot", mode: "resources", query: "", limit: 37 }, undefined, "automatic"); + }); + it("reads only a saved source and exact resource ID without any authority overrides", async () => { + const input = { org: "acme", namespace: "col-team", name: "opaque-registration", resource_id: " opaque://A?x=%2F ", endpoint: "https://other.example", tool: "hidden", slot: "override", source_id: "override", owner: "other", headers: { protection: "pretend" } }; + await mcpRead(input); + expect(send).toHaveBeenLastCalledWith("/v1/knowledge.source.mcp_read", { org: input.org, namespace: input.namespace, name: input.name, resource_id: input.resource_id }, undefined, "automatic"); + send.mockRejectedValueOnce(new Error("MCP_PROTECTED_SESSION_REQUIRED")); + await expect(mcpRead(input)).rejects.toThrow("MCP_PROTECTED_SESSION_REQUIRED"); + expect(send).toHaveBeenCalledTimes(2); + }); + it("exposes every management operation, bounds owner-list pages and omits mutable audience on update", async () => { + const signal = new AbortController().signal; + const key = { org: "acme", namespace: "col-team", name: "registration" }; + await mcpProfiles("acme", "profiles-next", signal); + await mcpConnections("acme", "accounts-next", signal); + await mcpInspectConnection("acme", { request_id: "connect-nonce" }, signal); + await mcpDiscover("acme", "slot", signal); + await mcpDisconnect("acme", "slot", signal); + await mcpList("acme", "col-team", "next", signal); + await mcpInspect(key, signal); + await mcpUpdate({ ...key, if_scope_revision: 4, resource_ids: ["opaque"], mode: "live", label: "new", confirm_copy_authority: false, reader_policy: "collection_copy" } as Parameters[0], signal); + await mcpControl(key, "pause", signal); await mcpControl(key, "resume", signal); await mcpControl(key, "refresh", signal); + await mcpRemove({ ...key, confirm: "registration", delete_documents: false }, signal); + expect(send.mock.calls.map(([path]) => path)).toEqual([ + "/v1/knowledge.source.mcp_profiles", "/v1/knowledge.connection.mcp_list", "/v1/knowledge.connection.mcp_inspect", + "/v1/knowledge.connection.mcp_discover", "/v1/knowledge.connection.mcp_disconnect", "/v1/knowledge.source.mcp_list", + "/v1/knowledge.source.mcp_inspect", "/v1/knowledge.source.mcp_update", "/v1/knowledge.source.mcp_pause", + "/v1/knowledge.source.mcp_resume", "/v1/knowledge.source.mcp_refresh", "/v1/knowledge.source.mcp_remove", + ]); + expect(send.mock.calls[5]?.[1]).toEqual({ org: "acme", namespace: "col-team", cursor: "next", limit: 20, include_retired: true }); + expect(send.mock.calls[7]?.[1]).toEqual({ ...key, if_scope_revision: 4, resource_ids: ["opaque"], mode: "live", label: "new", confirm_copy_authority: false }); + for (const call of send.mock.calls) expect(call[2]).toBe(signal); + for (const call of send.mock.calls) expect(call[3]).toBe("automatic"); + }); +}); diff --git a/frontend/src/api/mcpSources.ts b/frontend/src/api/mcpSources.ts new file mode 100644 index 0000000000..eda6706d64 --- /dev/null +++ b/frontend/src/api/mcpSources.ts @@ -0,0 +1,207 @@ +import { post } from "../api"; +import type { DashboardRequestIntent } from "../lib/dashboardTransport"; + +export type MCPMode = "live" | "snapshot" | "selected_refresh"; +export type MCPAudience = "owner_only" | "collection_copy"; +export interface MCPProfile { + id: string; + label: string; + auth: "none" | "bearer"; + endpoint_origin: string; + profile_sha256: string; + approved_tools: string[]; + allow_collection_copy: boolean; +} +export interface MCPConnection { + slot: string; + generation: string; + state: "configured" | "stopped" | "unavailable" | "approval_drift"; + profile_id: string | null; + profile_sha256: string | null; + label: string | null; + compatibility: "unchecked"; + remote_identity_verified: false; +} +export interface MCPDiscovery { + slot: string; + generation: string; + resources: boolean; + mapped_read: boolean; + mapped_search: boolean; + supported_reads: boolean; + limitations: string[]; + remote_identity_verified: false; +} +export interface MCPBrowse { + slot: string; + generation: string; + mode: "resources" | "search"; + supported: boolean; + resources: boolean | null; + mapped_read: boolean; + mapped_search: boolean; + capabilities_checked: boolean; + items: { id: string; title: string; uri: string }[]; + complete: boolean; + truncated: boolean; + reason: string | null; + limitations: string[]; + manual_resource_ids_supported: true; + remote_identity_verified: false; +} +export interface MCPLiveRead { + source_id: string; + resource_id: string; + uri: string; + title: string; + text: string; + mime_type: string; + resource_identity_verified: boolean; + remote_identity_verified: false; + upstream_acl_verified: false; + limitations: string[]; +} +export interface MCPAccessRule { + access: "owner_only" | "collection_wide" | "unavailable"; + reason: string; + stores_copy: boolean; + future_items_included: false; + upstream_permissions: "unsupported"; + reader_list_complete: false; + collection_readers_receive_copy: boolean; + inherited_grants_apply: true; + membership_changes_affect_copy: boolean; + publication_confirmation_required: boolean; + explanation: string; +} +export interface MCPPreview { + namespace: string; + mode: MCPMode; + rule: MCPAccessRule; + connection_state: MCPConnection["state"]; + compatibility: "unchecked"; + permission_evidence: "unsupported"; + refresh_state: "not_applicable" | "enabled" | "disabled"; + selected_count: number; + checked_at: string; + read_evidence_stale_seconds: number; + preview_grants_authority: false; + limitations: string[]; +} +export interface MCPSourceSummary { + name: string; + source_id: string; + slot: string; + namespace: string; + state: "registered" | "paused" | "retired" | "unsupported"; + mode: MCPMode | null; + reader_policy: MCPAudience | null; + scope_revision: number | null; + label: string | null; + selected_count: number | null; + sync_enabled: boolean; + read_evidence_stale_seconds: number; + refresh_state: string; + compatibility: "unchecked"; + upstream_permissions: "unsupported"; + complete_enumeration: false; + upstream_deletion_tracking: false; + future_items_included: false; + current_access_attested: false; + local_authority: "current" | "unavailable" | "unchecked"; + pending_erasure: boolean; + rule: MCPAccessRule | null; +} +export interface MCPSource extends MCPSourceSummary { resource_ids: string[] } +export interface MCPSourceResult { + source: MCPSource; + copies: "retained" | "erasure_requested"; + refresh_requested: boolean; +} +export interface MCPSelection { + org: string; + namespace: string; + slot: string; + resource_ids: string[]; + mode: MCPMode; + reader_policy: MCPAudience; +} +export interface MCPSourceKey { org: string; namespace: string; name: string } + +// Use the dashboard transport unchanged. Protected-result/session refusals remain refusals. +function call(op: string, body: object, signal?: AbortSignal, intent: DashboardRequestIntent = "automatic"): Promise { + return post(`/v1/knowledge.${op}`, body, signal, intent); +} +export function mcpProfiles(org: string, cursor: string | null, signal?: AbortSignal) { + return call<{ profiles: MCPProfile[]; next_cursor: string | null; self_service_enabled: boolean }>( + "source.mcp_profiles", { org, cursor, limit: 100 }, signal, + ); +} +export function mcpConnections(org: string, cursor: string | null, signal?: AbortSignal) { + return call<{ connections: MCPConnection[]; next_cursor: string | null }>( + "connection.mcp_list", { org, cursor, limit: 100 }, signal, + ); +} +export function mcpConnect(input: { org: string; profile_id: string; request_id: string; label?: string; bearer?: string }, signal?: AbortSignal, intent: DashboardRequestIntent = "automatic") { + return call<{ connection: MCPConnection }>("connection.mcp_connect", { + org: input.org, profile_id: input.profile_id, request_id: input.request_id, + ...(input.label === undefined ? {} : { label: input.label }), + ...(input.bearer === undefined ? {} : { bearer: input.bearer }), + }, signal, intent); +} +export function mcpInspectConnection(org: string, key: { slot?: string; request_id?: string }, signal?: AbortSignal) { + return call<{ found: boolean; slot: string; connection: MCPConnection | null; reconciliation: "absent" | "present" | "incomplete" }>( + "connection.mcp_inspect", { org, slot: key.slot ?? "", request_id: key.request_id ?? "" }, signal, + ); +} +export function mcpDiscover(org: string, slot: string, signal?: AbortSignal, intent: DashboardRequestIntent = "automatic") { + return call("connection.mcp_discover", { org, slot }, signal, intent); +} +export function mcpBrowse(input: { org: string; slot: string; mode: "resources" | "search"; query: string; limit: number }, signal?: AbortSignal) { + return call("connection.mcp_browse", { org: input.org, slot: input.slot, + mode: input.mode, query: input.mode === "search" ? input.query : "", limit: input.limit }, signal); +} +export function mcpRead(input: MCPSourceKey & { resource_id: string }, signal?: AbortSignal) { + return call("source.mcp_read", { ...sourceKey(input), resource_id: input.resource_id }, signal); +} +export function mcpDisconnect(org: string, slot: string, signal?: AbortSignal, intent: DashboardRequestIntent = "automatic") { + return call<{ disconnected: boolean; upstream_revoked: false; upstream_action: "revoke_credential_upstream" }>( + "connection.mcp_disconnect", { org, slot }, signal, intent, + ); +} +function selection(input: MCPSelection): MCPSelection { + return { org: input.org, namespace: input.namespace, slot: input.slot, resource_ids: input.resource_ids, + mode: input.mode, reader_policy: input.reader_policy }; +} +export function mcpPreview(input: MCPSelection, signal?: AbortSignal) { + return call("source.mcp_preview", selection(input), signal); +} +export function mcpAdd(input: MCPSelection & { request_id: string; label: string | null; confirm_copy_authority: boolean }, signal?: AbortSignal, intent: DashboardRequestIntent = "automatic") { + return call("source.mcp_add", { ...selection(input), request_id: input.request_id, + label: input.label, confirm_copy_authority: input.confirm_copy_authority }, signal, intent); +} +function sourceKey(input: MCPSourceKey): MCPSourceKey { + return { org: input.org, namespace: input.namespace, name: input.name }; +} +export function mcpList(org: string, namespace: string, cursor: string | null, signal?: AbortSignal) { + return call<{ sources: MCPSourceSummary[]; next_cursor: string | null }>( + "source.mcp_list", { org, namespace, cursor, limit: 20, include_retired: true }, signal, + ); +} +export function mcpInspect(input: { org: string; namespace: string } & ({ name: string } | { slot: string; request_id: string }), signal?: AbortSignal) { + return call<{ found: boolean; source: MCPSource | null }>("source.mcp_inspect", { + org: input.org, namespace: input.namespace, + ...("name" in input ? { name: input.name } : { slot: input.slot, request_id: input.request_id }), + }, signal); +} +export function mcpUpdate(input: MCPSourceKey & { if_scope_revision: number; resource_ids: string[]; mode: MCPMode; label: string | null; confirm_copy_authority: boolean }, signal?: AbortSignal, intent: DashboardRequestIntent = "automatic") { + return call("source.mcp_update", { ...sourceKey(input), if_scope_revision: input.if_scope_revision, + resource_ids: input.resource_ids, mode: input.mode, label: input.label, confirm_copy_authority: input.confirm_copy_authority }, signal, intent); +} +export function mcpControl(input: MCPSourceKey, action: "pause" | "resume" | "refresh", signal?: AbortSignal, intent: DashboardRequestIntent = "automatic") { + return call(`source.mcp_${action}`, sourceKey(input), signal, intent); +} +export function mcpRemove(input: MCPSourceKey & { confirm: string; delete_documents: boolean }, signal?: AbortSignal, intent: DashboardRequestIntent = "automatic") { + return call("source.mcp_remove", { ...sourceKey(input), confirm: input.confirm, + delete_documents: input.delete_documents }, signal, intent); +} diff --git a/frontend/src/api/memoryLifecycle.ts b/frontend/src/api/memoryLifecycle.ts index f02c0dedf7..abf9525513 100644 --- a/frontend/src/api/memoryLifecycle.ts +++ b/frontend/src/api/memoryLifecycle.ts @@ -11,18 +11,19 @@ export async function lockMemory( memoryKey: string, mode: LockMode, reason: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ locked: boolean; reason?: string }> { - return post("/v1/memory.lock", { ...id, memory_key: memoryKey, mode, reason }); + return post("/v1/memory.lock", { ...id, memory_key: memoryKey, mode, reason }, undefined, intent); } /** POST /v1/memory.unlock (ADMIN). */ -export async function unlockMemory(id: Identity, memoryKey: string): Promise<{ unlocked: boolean; reason: string }> { - return post("/v1/memory.unlock", { ...id, memory_key: memoryKey }); +export async function unlockMemory(id: Identity, memoryKey: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ unlocked: boolean; reason: string }> { + return post("/v1/memory.unlock", { ...id, memory_key: memoryKey }, undefined, intent); } /** POST /v1/memory.reject: the fact is wrong; it is retired and not extracted again. */ -export async function rejectMemory(id: Identity, memoryKey: string, reason: string): Promise<{ rejected: boolean }> { - return post("/v1/memory.reject", { ...id, memory_key: memoryKey, rejection_reason: reason }); +export async function rejectMemory(id: Identity, memoryKey: string, reason: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ rejected: boolean }> { + return post("/v1/memory.reject", { ...id, memory_key: memoryKey, rejection_reason: reason }, undefined, intent); } /** POST /v1/memory.promote (ADMIN): a copy in the namespace's shared layer, read by every agent. @@ -32,16 +33,18 @@ export async function shareMemory( id: Identity, memoryKey: string, approvedSha256?: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ shared_memory_key: string }> { - return post("/v1/memory.promote", { ...id, memory_key: memoryKey, approved_sha256: approvedSha256 }); + return post("/v1/memory.promote", { ...id, memory_key: memoryKey, approved_sha256: approvedSha256 }, undefined, intent); } /** POST /v1/memory.demote (ADMIN): the shared copy goes; the agent's own row stays. */ export async function unshareMemory( id: Pick, memoryKey: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ demoted: boolean }> { - return post("/v1/memory.demote", { org: id.org, namespace: id.namespace, memory_key: memoryKey }); + return post("/v1/memory.demote", { org: id.org, namespace: id.namespace, memory_key: memoryKey }, undefined, intent); } /** One source turn a memory was extracted from: `server/memory/api/models_lifecycle.py`. */ @@ -87,8 +90,9 @@ export async function recordMemoryOutcome( id: Identity, memoryId: string, outcome: "positive" | "negative", + intent: "automatic" | "explicit" = "automatic", ): Promise<{ recorded: boolean; quarantined: boolean }> { - return post("/v1/memory.outcome", { ...id, memory_id: memoryId, outcome, source: "dashboard" }); + return post("/v1/memory.outcome", { ...id, memory_id: memoryId, outcome, source: "dashboard" }, undefined, intent); } /** POST /v1/memory.redact (ADMIN): scrub one past version's value, keeping its row and @@ -99,6 +103,7 @@ export async function redactMemoryVersion( memoryId: string, versionText: string, reason: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ redacted: boolean; refused_head: boolean }> { - return post("/v1/memory.redact", { org, memory_id: memoryId, version: versionText, reason }); + return post("/v1/memory.redact", { org, memory_id: memoryId, version: versionText, reason }, undefined, intent); } diff --git a/frontend/src/api/models.ts b/frontend/src/api/models.ts index bc2d683a67..0809fa3b70 100644 --- a/frontend/src/api/models.ts +++ b/frontend/src/api/models.ts @@ -78,10 +78,10 @@ export interface ModelSaveResult { } export const getModelStatus = (signal?: AbortSignal) => getJson("/v1/admin/models", { signal }); -export const validateModelConfiguration = (body: ModelConfiguration) => - post("/v1/admin/models/validate", body); -export const saveModelConfiguration = (body: ModelConfiguration) => post("/v1/admin/models", body); -export const resetModelConfiguration = (expected_version: string) => - post("/v1/admin/models/reset", { expected_version }); -export const retryModelConfiguration = (config_id: string) => - post("/v1/admin/models/retry", { config_id }); +export const validateModelConfiguration = (body: ModelConfiguration, intent: "automatic" | "explicit" = "automatic") => + post("/v1/admin/models/validate", body, undefined, intent); +export const saveModelConfiguration = (body: ModelConfiguration, intent: "automatic" | "explicit" = "automatic") => post("/v1/admin/models", body, undefined, intent); +export const resetModelConfiguration = (expected_version: string, intent: "automatic" | "explicit" = "automatic") => + post("/v1/admin/models/reset", { expected_version }, undefined, intent); +export const retryModelConfiguration = (config_id: string, intent: "automatic" | "explicit" = "automatic") => + post("/v1/admin/models/retry", { config_id }, undefined, intent); diff --git a/frontend/src/api/profile.ts b/frontend/src/api/profile.ts index 6bddace4e5..43e9e68488 100644 --- a/frontend/src/api/profile.ts +++ b/frontend/src/api/profile.ts @@ -100,19 +100,20 @@ export async function setProfileSection( label: string, value: string, charLimit: number, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ version: string; content_sha256: string; value_length: number }> { return post<{ version: string; content_sha256: string; value_length: number }>("/v1/profile.set", { ...id, label, value, char_limit: charLimit, - }); + }, undefined, intent); } /** Tombstone a profile section (14-day grace, restorable). Sections * live in loom.memory so memory.delete is the right primitive. */ -export async function deleteProfileSection(id: Identity, label: string): Promise { - await post("/v1/memory.delete", { ...id, memory_key: label }); +export async function deleteProfileSection(id: Identity, label: string, intent: "automatic" | "explicit" = "automatic"): Promise { + await post("/v1/memory.delete", { ...id, memory_key: label }, undefined, intent); } export interface ProfileActivityEntry { diff --git a/frontend/src/api/queryHistory.ts b/frontend/src/api/queryHistory.ts index d9f66f2a7d..d059201232 100644 --- a/frontend/src/api/queryHistory.ts +++ b/frontend/src/api/queryHistory.ts @@ -23,9 +23,9 @@ export interface QueryHistorySources { export function listQueryHistory(id: Scope, opts: RequestOpts = {}): Promise { return post("/v1/knowledge.query_history.list", { ...id, limit: 1000 }, opts.signal); } -export function addQueryHistory(id: Scope, source: QueryHistoryRegistration): Promise { - return post("/v1/knowledge.query_history.add", { ...id, ...source }); +export function addQueryHistory(id: Scope, source: QueryHistoryRegistration, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/knowledge.query_history.add", { ...id, ...source }, undefined, intent); } -export function removeQueryHistory(id: Scope, name: string): Promise<{ removed: boolean }> { - return post("/v1/knowledge.query_history.remove", { ...id, name }); +export function removeQueryHistory(id: Scope, name: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ removed: boolean }> { + return post("/v1/knowledge.query_history.remove", { ...id, name }, undefined, intent); } diff --git a/frontend/src/api/review.ts b/frontend/src/api/review.ts index 274bc73fb7..13f3640bb0 100644 --- a/frontend/src/api/review.ts +++ b/frontend/src/api/review.ts @@ -38,6 +38,7 @@ export async function resolveMemoryDuplicate( cluster: MemoryDuplicateCluster, duplicateId: string, decision: MemoryDuplicateDecision, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ canonical_tombstoned: boolean; duplicate_tombstoned: boolean }> { return post("/v1/memory.dedup_resolve", { org: id.org, @@ -46,7 +47,7 @@ export async function resolveMemoryDuplicate( duplicate_id: duplicateId, decision, confirm_canonical_key: cluster.canonical_key, - }); + }, undefined, intent); } /** The fields of `server/memory/api/models_graph.py::MemoryDedupCollapseOutput` the tab reads. */ @@ -63,21 +64,22 @@ export const COLLAPSE_PAIRS = 5000; /** POST /v1/memory.dedup_collapse: marks the search rows of duplicates `duplicate`, so search * skips them; no model call, and no value, key or memory changes. `dryRun` counts them. */ -export async function collapseMemoryDuplicates(id: Scope, dryRun: boolean): Promise { +export async function collapseMemoryDuplicates(id: Scope, dryRun: boolean, intent: "automatic" | "explicit" = "automatic"): Promise { return post("/v1/memory.dedup_collapse", { org: id.org, namespace: id.namespace, dry_run: dryRun, limit: COLLAPSE_PAIRS, - }); + }, undefined, intent); } /** POST /v1/memory.resolve_orphan_duplicates: duplicates whose canonical is gone come back. */ export async function repairOrphanDuplicates( id: Scope, dryRun: boolean, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ candidates: number; reactivated: number }> { - return post("/v1/memory.resolve_orphan_duplicates", { org: id.org, namespace: id.namespace, dry_run: dryRun }); + return post("/v1/memory.resolve_orphan_duplicates", { org: id.org, namespace: id.namespace, dry_run: dryRun }, undefined, intent); } /** How many of the agent's newest eligible memories a merge reads, and how old one must be. */ @@ -90,6 +92,7 @@ export const CONSOLIDATE_MIN_AGE_SECONDS = 3600; export async function consolidateMemories( id: Scope, agent: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ /** One entry per cluster merged. */ consolidated: unknown[]; @@ -110,6 +113,7 @@ export async function consolidateMemories( min_age_seconds: CONSOLIDATE_MIN_AGE_SECONDS, }, AbortSignal.timeout(LONG_CALL_MS), + intent, ); } @@ -143,7 +147,7 @@ export async function listDocumentDuplicates( } /** POST /v1/knowledge.dedup_resolve: `duplicateUri` is superseded by `canonicalUri`. */ -export async function retireDocumentDuplicate(id: Scope, canonicalUri: string, duplicateUri: string): Promise { +export async function retireDocumentDuplicate(id: Scope, canonicalUri: string, duplicateUri: string, intent: "automatic" | "explicit" = "automatic"): Promise { return post("/v1/knowledge.dedup_resolve", { org: id.org, namespace: id.namespace, @@ -151,7 +155,7 @@ export async function retireDocumentDuplicate(id: Scope, canonicalUri: string, d duplicate_uri: duplicateUri, decision: "keep_canonical", confirm_duplicate_uri: duplicateUri, - }); + }, undefined, intent); } // ===== Proposals (facts on trial) ===== @@ -191,6 +195,7 @@ export async function decideProposals( keys: string[], decision: "accept" | "reject", approvedSha256: Record = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ decided: number; results: { memory_key: string; decided: boolean; status: string; reason: string }[] }> { return post("/v1/memory.proposal_decide", { org: id.org, @@ -198,7 +203,7 @@ export async function decideProposals( memory_keys: keys, decision, ...(decision === "accept" ? { approved_sha256: approvedSha256 } : {}), - }); + }, undefined, intent); } // ===== Revision suggestions for a conflict ===== @@ -213,6 +218,7 @@ export interface RevisionSuggestion { export async function proposeRevision( id: Scope, memoryId: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ found: boolean; suggestions: RevisionSuggestion[] }> { - return post("/v1/conflicts.propose_revision", { org: id.org, namespace: id.namespace, memory_id: memoryId }); + return post("/v1/conflicts.propose_revision", { org: id.org, namespace: id.namespace, memory_id: memoryId }, undefined, intent); } diff --git a/frontend/src/api/runs.ts b/frontend/src/api/runs.ts index ba8f894c62..27b847f4e3 100644 --- a/frontend/src/api/runs.ts +++ b/frontend/src/api/runs.ts @@ -145,6 +145,7 @@ export async function gradeRun( grade: "pass" | "fail", reason: string, source: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ graded: number; skipped_active: number; unchanged: number; proposals_decided: RunGradeProposal[] }> { - return post("/v1/run.grade", { org: id.org, namespace: id.namespace, run_id: runId, grade, reason, source }); + return post("/v1/run.grade", { org: id.org, namespace: id.namespace, run_id: runId, grade, reason, source }, undefined, intent); } diff --git a/frontend/src/api/sourcePush.ts b/frontend/src/api/sourcePush.ts deleted file mode 100644 index dfedd8a8ac..0000000000 --- a/frontend/src/api/sourcePush.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { post } from "../api"; - -type Source = { org: string; namespace: string; name: string }; - -export type PushStatus = { - enabled: boolean; - status: string; - provider: string; - generation: string; - callback_url: string; - challenge_fingerprint: string; - verification_token: string; - channels: number; - expires_at: number; -}; - -export function sourcePushStatus(source: Source, reveal = false, signal?: AbortSignal): Promise { - return post("/v1/knowledge.source.push_status", { ...source, reveal_challenge: reveal }, signal); -} - -export function configureSourcePush(source: Source, enabled: boolean): Promise { - return post("/v1/knowledge.source.push_configure", { ...source, enabled }); -} - -export function confirmSourcePush(source: Source, status: PushStatus, secret = ""): Promise { - return post("/v1/knowledge.source.push_confirm", { - ...source, - generation: status.generation, - challenge_fingerprint: status.challenge_fingerprint, - signing_secret: secret, - }); -} diff --git a/frontend/src/api/structure.ts b/frontend/src/api/structure.ts index 3179403e8a..5d48ba438a 100644 --- a/frontend/src/api/structure.ts +++ b/frontend/src/api/structure.ts @@ -38,16 +38,18 @@ export async function registerRecordSchema( name: string, description: string, fields: SchemaField[], + intent: "automatic" | "explicit" = "automatic", ): Promise<{ name: string; status: string }> { - return post("/v1/memory_schema.register", { ...scope(id), name, description, fields }); + return post("/v1/memory_schema.register", { ...scope(id), name, description, fields }, undefined, intent); } export async function decideRecordSchema( id: Scope, name: string, decision: "approve" | "reject", + intent: "automatic" | "explicit" = "automatic", ): Promise<{ status: string; updated: boolean }> { - return post("/v1/memory_schema.approve", { ...scope(id), name, decision }); + return post("/v1/memory_schema.approve", { ...scope(id), name, decision }, undefined, intent); } // ===== Typed records ===== @@ -117,12 +119,12 @@ export async function getProfileSchema(id: Scope, opts: RequestOpts = {}): Promi return post("/v1/profile_schema.get", scope(id), opts.signal); } -export async function setProfileSchema(id: Scope, jsonSchema: Record): Promise { - return post("/v1/profile_schema.set", { ...scope(id), json_schema: jsonSchema }); +export async function setProfileSchema(id: Scope, jsonSchema: Record, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/profile_schema.set", { ...scope(id), json_schema: jsonSchema }, undefined, intent); } -export async function clearProfileSchema(id: Scope): Promise { - return post("/v1/profile_schema.clear", scope(id)); +export async function clearProfileSchema(id: Scope, intent: "automatic" | "explicit" = "automatic"): Promise { + return post("/v1/profile_schema.clear", scope(id), undefined, intent); } // ===== Ontology ===== @@ -158,6 +160,7 @@ export async function listOntology(id: Scope, opts: RequestOpts = {}): Promise, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ registered: boolean }> { const { kind, name, description, cardinality } = term; return post("/v1/namespace.register_ontology", { @@ -167,7 +170,7 @@ export async function registerOntologyTerm( description, cardinality, status: "accepted", - }); + }, undefined, intent); } // ===== Categories ===== @@ -190,6 +193,7 @@ export async function registerCategory( id: Scope, name: string, description: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ category_id: string; embedded: boolean }> { - return post("/v1/namespace.register_category", { ...scope(id), name, description }); + return post("/v1/namespace.register_category", { ...scope(id), name, description }, undefined, intent); } diff --git a/frontend/src/api/tasks.ts b/frontend/src/api/tasks.ts index 01cd5664e1..ad4887c36d 100644 --- a/frontend/src/api/tasks.ts +++ b/frontend/src/api/tasks.ts @@ -202,8 +202,9 @@ export interface InboxRegisterInput { export async function registerInbox( id: Caller, input: InboxRegisterInput, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ inbox: Inbox; created: boolean }> { - return post("/v1/inbox.register", body(id, input)); + return post("/v1/inbox.register", body(id, input), undefined, intent); } /** One identity loom already knows in the org — the poster picker's row. @@ -258,8 +259,9 @@ export interface PolicySetInput { export async function setPolicy( id: Caller, input: PolicySetInput, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ policy: PosterPolicy | null; removed: boolean }> { - return post("/v1/inbox.policy_set", body(id, input)); + return post("/v1/inbox.policy_set", body(id, input), undefined, intent); } // ---------------------------------------------------------------- reads @@ -334,8 +336,9 @@ export interface TaskCreateInput { export async function createTask( id: Caller, input: TaskCreateInput, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ task: TaskRow; created: boolean; seq: number }> { - return post("/v1/task.create", body(id, input)); + return post("/v1/task.create", body(id, input), undefined, intent); } export interface TaskUpdateInput { @@ -354,16 +357,17 @@ export interface TaskUpdateInput { /** Edit the brief under optimistic concurrency. A stale `if_match_version` * is a 409 PRECONDITION_FAILED whose `detail` carries `current_version` and * `current` (the row as it is now) — see `conflictOf`. */ -export async function updateTask(id: Caller, input: TaskUpdateInput): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.update", body(id, input)); +export async function updateTask(id: Caller, input: TaskUpdateInput, intent: "automatic" | "explicit" = "automatic"): Promise<{ task: TaskRow; seq: number }> { + return post("/v1/task.update", body(id, input), undefined, intent); } export async function acceptTask( id: Caller, taskId: string, opts: { priority?: number; constraints?: string; note?: string } = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.accept", body(id, { task_id: taskId, ...opts })); + return post("/v1/task.accept", body(id, { task_id: taskId, ...opts }), undefined, intent); } export async function deferTask( @@ -372,8 +376,9 @@ export async function deferTask( reason: string, resumeAt: string | null, fence = 0, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.defer", (fence ? fenced : body)(id, { task_id: taskId, fence, reason, resume_at: resumeAt })); + return post("/v1/task.defer", (fence ? fenced : body)(id, { task_id: taskId, fence, reason, resume_at: resumeAt }), undefined, intent); } export async function blockTask( @@ -382,14 +387,15 @@ export async function blockTask( reason: string, blockedOn: BlockedOn, fence = 0, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.block", (fence ? fenced : body)(id, { task_id: taskId, fence, reason, blocked_on: blockedOn })); + return post("/v1/task.block", (fence ? fenced : body)(id, { task_id: taskId, fence, reason, blocked_on: blockedOn }), undefined, intent); } /** To do → in progress, held by the dashboard (owner `loom-ui`); 409 TASK_NOT_YET while * `not_before` is ahead, TASK_ALREADY_CLAIMED when an agent won the lease first. */ -export async function claimTask(id: Caller, taskId: string): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.claim", body(id, { task_id: taskId, lease_seconds: PERSON_LEASE_SECONDS })); +export async function claimTask(id: Caller, taskId: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ task: TaskRow; seq: number }> { + return post("/v1/task.claim", body(id, { task_id: taskId, lease_seconds: PERSON_LEASE_SECONDS }), undefined, intent); } export async function completeTask( @@ -397,8 +403,9 @@ export async function completeTask( taskId: string, fence: number, note = "", + intent: "automatic" | "explicit" = "automatic", ): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.complete", fenced(id, { task_id: taskId, fence, note })); + return post("/v1/task.complete", fenced(id, { task_id: taskId, fence, note }), undefined, intent); } export async function failTask( @@ -406,30 +413,31 @@ export async function failTask( taskId: string, fence: number, reason: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.fail", fenced(id, { task_id: taskId, fence, reason })); + return post("/v1/task.fail", fenced(id, { task_id: taskId, fence, reason }), undefined, intent); } -export async function unblockTask(id: Caller, taskId: string, note = ""): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.unblock", body(id, { task_id: taskId, note })); +export async function unblockTask(id: Caller, taskId: string, note = "", intent: "automatic" | "explicit" = "automatic"): Promise<{ task: TaskRow; seq: number }> { + return post("/v1/task.unblock", body(id, { task_id: taskId, note }), undefined, intent); } /** A deferred task back to the queue now, ahead of its `resume_at` * (409 TASK_NOT_DEFERRED for any other status). */ -export async function resumeTask(id: Caller, taskId: string, note = ""): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.resume", body(id, { task_id: taskId, note })); +export async function resumeTask(id: Caller, taskId: string, note = "", intent: "automatic" | "explicit" = "automatic"): Promise<{ task: TaskRow; seq: number }> { + return post("/v1/task.resume", body(id, { task_id: taskId, note }), undefined, intent); } -export async function wontDoTask(id: Caller, taskId: string, reason: string): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.wont_do", body(id, { task_id: taskId, reason })); +export async function wontDoTask(id: Caller, taskId: string, reason: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ task: TaskRow; seq: number }> { + return post("/v1/task.wont_do", body(id, { task_id: taskId, reason }), undefined, intent); } -export async function cancelTask(id: Caller, taskId: string, reason: string): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.cancel", body(id, { task_id: taskId, reason })); +export async function cancelTask(id: Caller, taskId: string, reason: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ task: TaskRow; seq: number }> { + return post("/v1/task.cancel", body(id, { task_id: taskId, reason }), undefined, intent); } -export async function reopenTask(id: Caller, taskId: string, reason: string): Promise<{ task: TaskRow; seq: number }> { - return post("/v1/task.reopen", body(id, { task_id: taskId, reason })); +export async function reopenTask(id: Caller, taskId: string, reason: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ task: TaskRow; seq: number }> { + return post("/v1/task.reopen", body(id, { task_id: taskId, reason }), undefined, intent); } export async function reassignTask( @@ -437,6 +445,7 @@ export async function reassignTask( taskId: string, toInbox: string, reason: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ task: TaskRow; replacement: TaskRow }> { - return post("/v1/task.reassign", body(id, { task_id: taskId, to_inbox: toInbox, reason })); + return post("/v1/task.reassign", body(id, { task_id: taskId, to_inbox: toInbox, reason }), undefined, intent); } diff --git a/frontend/src/api/tracker.ts b/frontend/src/api/tracker.ts index c91b80b093..2a7f87cd8d 100644 --- a/frontend/src/api/tracker.ts +++ b/frontend/src/api/tracker.ts @@ -161,8 +161,9 @@ export async function listTrackerSources( export async function addTrackerSource( body: Record, opts: RequestOpts = {}, + intent: "automatic" | "explicit" = "automatic", ): Promise { - return post("/v1/tracker.source.add", body, opts.signal); + return post("/v1/tracker.source.add", body, opts.signal, intent); } export async function checkTrackerSource( @@ -178,16 +179,18 @@ export async function rotateTrackerSource( name: string, user: string, password: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ name: string; contract: TrackerSourceCheckResult["contract"]; rotated_at: string }> { - return post("/v1/tracker.source.rotate", { org, name, user, password }); + return post("/v1/tracker.source.rotate", { org, name, user, password }, undefined, intent); } export async function removeTrackerSource( org: string, name: string, confirm: string, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ name: string; deactivated: boolean; namespaces_retired: string[] }> { - return post("/v1/tracker.source.remove", { org, name, confirm }); + return post("/v1/tracker.source.remove", { org, name, confirm }, undefined, intent); } /** The contract before a connection — every table and column Loom reads, what each holds, and a blank view per table (no I/O). */ @@ -223,6 +226,7 @@ export async function setTrackerMapping( name: string, mapping: SourceMapping | null, dryRun = false, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ name: string; contract: TrackerSourceCheckResult["contract"]; dry_run: boolean; written: boolean }> { - return post("/v1/tracker.source.set_mapping", { org, name, mapping, dry_run: dryRun }); + return post("/v1/tracker.source.set_mapping", { org, name, mapping, dry_run: dryRun }, undefined, intent); } diff --git a/frontend/src/api/webhooks.ts b/frontend/src/api/webhooks.ts index 23ecd027f6..6c2ea608de 100644 --- a/frontend/src/api/webhooks.ts +++ b/frontend/src/api/webhooks.ts @@ -47,12 +47,13 @@ export async function registerWebhook( url: string, secretRef: string, events: WebhookEvent[], + intent: "automatic" | "explicit" = "automatic", ): Promise<{ webhook: Webhook }> { - return post("/v1/webhook.register", { org: id.org, namespace: id.namespace, url, secret_ref: secretRef, events }); + return post("/v1/webhook.register", { org: id.org, namespace: id.namespace, url, secret_ref: secretRef, events }, undefined, intent); } -export async function removeWebhook(id: Scope, webhookId: string): Promise<{ removed: boolean }> { - return post("/v1/webhook.remove", { org: id.org, namespace: id.namespace, webhook_id: webhookId }); +export async function removeWebhook(id: Scope, webhookId: string, intent: "automatic" | "explicit" = "automatic"): Promise<{ removed: boolean }> { + return post("/v1/webhook.remove", { org: id.org, namespace: id.namespace, webhook_id: webhookId }, undefined, intent); } /** The fields of `server/memory/api/models_webhook.py::WebhookDelivery` the dialog reads. */ diff --git a/frontend/src/components/HeaderSearch.tsx b/frontend/src/components/HeaderSearch.tsx index ccf4c20631..c053eda089 100644 --- a/frontend/src/components/HeaderSearch.tsx +++ b/frontend/src/components/HeaderSearch.tsx @@ -464,7 +464,7 @@ export function HeaderSearch({ const sent = m.askFromSearch(question, (turnId) => { shown = turnId; setAsked((a) => (a && a.question === question ? { ...a, turnId } : a)); - }); + }, "explicit"); setAsked({ question, turnId: shown, busy: !sent }); // The card's Continue in chat is the first option now. setActiveIdx(0); diff --git a/frontend/src/components/MemoryInspector.lifecycle.test.tsx b/frontend/src/components/MemoryInspector.lifecycle.test.tsx index a21cadbfb8..452c06887d 100644 --- a/frontend/src/components/MemoryInspector.lifecycle.test.tsx +++ b/frontend/src/components/MemoryInspector.lifecycle.test.tsx @@ -254,6 +254,7 @@ describe("MemoryInspector lifecycle actions", () => { "coffee_pref", LIVE.value, expect.objectContaining({ ttlSeconds: 3600 }), + "explicit", ), ); await userEvent.click(screen.getByRole("button", { name: "Edit" })); @@ -265,7 +266,7 @@ describe("MemoryInspector lifecycle actions", () => { it("deletes the row it shows, and says so when nothing was deleted", async () => { await open("writer"); await userEvent.click(screen.getByRole("button", { name: "Delete" })); - await waitFor(() => expect(api.deleteMemory).toHaveBeenCalledWith(row, "coffee_pref")); + await waitFor(() => expect(api.deleteMemory).toHaveBeenCalledWith(row, "coffee_pref", "explicit")); cleanup(); vi.mocked(api.deleteMemory).mockResolvedValueOnce({ tombstoned: false, version: 0 }); @@ -288,6 +289,7 @@ describe("MemoryInspector lifecycle actions", () => { "coffee_pref", LIVE.value, expect.objectContaining({ tags: ["coffee", "ops"] }), + "explicit", ), ); const items = within(await menu()) @@ -382,7 +384,7 @@ describe("MemoryInspector lifecycle actions", () => { await userEvent.click(within(dialog).getByRole("radio", { name: "No delete" })); await userEvent.type(within(dialog).getByLabelText("Reason"), "legal hold"); await userEvent.click(within(dialog).getByRole("button", { name: "Lock" })); - await waitFor(() => expect(lc.lockMemory).toHaveBeenCalledWith(row, "coffee_pref", "no_delete", "legal hold")); + await waitFor(() => expect(lc.lockMemory).toHaveBeenCalledWith(row, "coffee_pref", "no_delete", "legal hold", "explicit")); }); it("closes an open edit when a read only lock lands, and says so", async () => { @@ -552,7 +554,7 @@ describe("MemoryInspector lifecycle actions", () => { await open("admin", locked); await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Unlock" })); - await waitFor(() => expect(lc.unlockMemory).toHaveBeenCalledWith(row, "coffee_pref")); + await waitFor(() => expect(lc.unlockMemory).toHaveBeenCalledWith(row, "coffee_pref", "explicit")); }); it("marks a memory as wrong with the reason", async () => { @@ -561,7 +563,7 @@ describe("MemoryInspector lifecycle actions", () => { const dialog = await screen.findByRole("dialog", { name: "Mark as wrong" }); await userEvent.type(within(dialog).getByLabelText("Reason"), "she switched to soy"); await userEvent.click(within(dialog).getByRole("button", { name: "Mark as wrong" })); - await waitFor(() => expect(lc.rejectMemory).toHaveBeenCalledWith(row, "coffee_pref", "she switched to soy")); + await waitFor(() => expect(lc.rejectMemory).toHaveBeenCalledWith(row, "coffee_pref", "she switched to soy", "explicit")); }); it.each([ @@ -594,6 +596,7 @@ describe("MemoryInspector lifecycle actions", () => { expect.objectContaining({ agent: "-", user_id: "-", session_id: "-" }), "definition/arr", "abc123", + "explicit", ), ); }); @@ -602,9 +605,9 @@ describe("MemoryInspector lifecycle actions", () => { await open("admin"); await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Share with every agent" })); // Only a definition names the text it approves. - await waitFor(() => expect(lc.shareMemory).toHaveBeenCalledWith(row, "coffee_pref", undefined)); + await waitFor(() => expect(lc.shareMemory).toHaveBeenCalledWith(row, "coffee_pref", undefined, "explicit")); await userEvent.click(within(await menu()).getByRole("menuitem", { name: "Stop sharing" })); - await waitFor(() => expect(lc.unshareMemory).toHaveBeenCalledWith(identity, "coffee_pref")); + await waitFor(() => expect(lc.unshareMemory).toHaveBeenCalledWith(identity, "coffee_pref", "explicit")); expect(confirmAction).toHaveBeenCalledTimes(2); expect(vi.mocked(confirmAction).mock.calls[1][0]).toMatchObject({ title: "Stop sharing coffee_pref in team?" }); }); @@ -670,7 +673,7 @@ describe("MemoryInspector lifecycle actions", () => { await userEvent.type(within(dialog).getByLabelText("Reason"), "card number"); await userEvent.click(within(dialog).getByRole("button", { name: "Redact" })); await waitFor(() => - expect(lc.redactMemoryVersion).toHaveBeenCalledWith("dev", "m1", "1790000000000000001", "card number"), + expect(lc.redactMemoryVersion).toHaveBeenCalledWith("dev", "m1", "1790000000000000001", "card number", "explicit"), ); await waitFor(() => expect(screen.queryByRole("dialog", { name: "Redact v1" })).toBeNull()); }); @@ -715,7 +718,7 @@ describe("MemoryInspector lifecycle actions", () => { await open("writer"); await userEvent.click(within(await menu()).getByRole("menuitem", { name: "This misled" })); // By id: the op resolves a key in the `-` session only, and this row has its own. - await waitFor(() => expect(lc.recordMemoryOutcome).toHaveBeenCalledWith(identity, "m-live", "negative")); + await waitFor(() => expect(lc.recordMemoryOutcome).toHaveBeenCalledWith(identity, "m-live", "negative", "explicit")); }); it("reads the memory again when a bad outcome rejects it", async () => { diff --git a/frontend/src/components/MemoryInspector.pin.test.tsx b/frontend/src/components/MemoryInspector.pin.test.tsx index 6cf6faaab7..8a2d2c6bcc 100644 --- a/frontend/src/components/MemoryInspector.pin.test.tsx +++ b/frontend/src/components/MemoryInspector.pin.test.tsx @@ -97,7 +97,7 @@ describe("MemoryInspector pin", () => { await userEvent.click(await screen.findByRole("menuitem", { name: "Pin" })); await waitFor(() => expect(pinMemory).toHaveBeenCalledTimes(1)); - expect(vi.mocked(pinMemory).mock.calls[0]).toEqual([identity, "coffee_pref", LIVE]); + expect(vi.mocked(pinMemory).mock.calls[0]).toEqual([identity, "coffee_pref", LIVE, "explicit"]); }); it("stays pinned when memory.pin committed with only search behind, and rolls back a failure", async () => { @@ -141,6 +141,7 @@ describe("MemoryInspector pin", () => { expect(vi.mocked(unpinMemory).mock.calls[0]).toEqual([ { ...identity, agent: "claude-desktop", user_id: "alice", session_id: "s1" }, "coffee_pref", + "explicit", ]); }); }); diff --git a/frontend/src/components/MemoryInspector.rename.test.tsx b/frontend/src/components/MemoryInspector.rename.test.tsx index 0134fe03aa..d9ce0cc098 100644 --- a/frontend/src/components/MemoryInspector.rename.test.tsx +++ b/frontend/src/components/MemoryInspector.rename.test.tsx @@ -180,6 +180,7 @@ describe("MemoryInspector rename with redirect", () => { "coffee_pref", "prefs/coffee", { keepRedirect: true, dryRun: true }, + "explicit", ]); const preview = await screen.findByTestId("rename-preview"); expect(preview).toHaveTextContent( @@ -194,6 +195,7 @@ describe("MemoryInspector rename with redirect", () => { "coffee_pref", "prefs/coffee", { keepRedirect: true, dryRun: false }, + "explicit", ]); // The form closes, the list is told, the row is re-read and now wears the badge. await waitFor(() => expect(screen.queryByTestId("rename-form")).toBeNull()); diff --git a/frontend/src/components/MemoryInspector.restore.test.tsx b/frontend/src/components/MemoryInspector.restore.test.tsx index b6d6c3f3c1..3876eb3a70 100644 --- a/frontend/src/components/MemoryInspector.restore.test.tsx +++ b/frontend/src/components/MemoryInspector.restore.test.tsx @@ -104,7 +104,7 @@ describe("MemoryInspector restore of a superseded row", () => { // Only the retirement on screen: a delete since is left as it is. if_superseded_by: "m-city-4", only_if_superseded: true, - }), + }, "explicit"), ); await waitFor(() => expect(toast).toHaveBeenCalledWith("Restored", "ok")); expect(onChanged).toHaveBeenCalled(); @@ -122,7 +122,7 @@ describe("MemoryInspector restore of a superseded row", () => { session_id: "s1", if_superseded_by: "", only_if_superseded: true, - }), + }, "explicit"), ); }); diff --git a/frontend/src/components/MemoryInspector.tsx b/frontend/src/components/MemoryInspector.tsx index 093b677e67..e5a261eccb 100644 --- a/frontend/src/components/MemoryInspector.tsx +++ b/frontend/src/components/MemoryInspector.tsx @@ -547,12 +547,12 @@ export function MemoryInspector({ try { if (wasPinned) { // The row pinMemory writes to. - const result = await unpinMemory(rowIdentity(identity, detail), memoryKey); + const result = await unpinMemory(rowIdentity(identity, detail), memoryKey, "explicit"); if (!result.unpinned && result.reason !== "not_pinned") { throw new Error(result.reason || "memory was not unpinned"); } } else { - await pinMemory(identity, memoryKey, detail); + await pinMemory(identity, memoryKey, detail, "explicit"); } toast(wasPinned ? "Unpinned" : "Pinned", "ok"); } catch (e) { @@ -575,7 +575,7 @@ export function MemoryInspector({ revoke: live, userId: detail.user_id || undefined, sessionId: detail.session_id || undefined, - }); + }, "explicit"); setDetail({ ...detail, verified_by: r.verified_by, verified_at: r.verified_at, verification: r.verification }); toast(live ? "Verification removed" : `Verified as ${r.verified_by}`, "ok"); onChanged(); @@ -589,7 +589,7 @@ export function MemoryInspector({ if (!detail?.memory_id) return; try { // By id: the op resolves a key in the `-` session only, and an extracted row has its own. - const r = await recordMemoryOutcome(identity, detail.memory_id, outcome); + const r = await recordMemoryOutcome(identity, detail.memory_id, outcome, "explicit"); if (!r.recorded) { toast("Couldn't record that", "error"); return; @@ -610,7 +610,7 @@ export function MemoryInspector({ // personal data): `memory.redact`, through RedactVersionDialog. const redact = async (h: MemoryHistoryEntry, label: string, reason: string) => { if (!h.memory_id || !h.version_text) throw new Error(`${label} has no exact version to redact.`); - const r = await redactMemoryVersion(identity.org, h.memory_id, h.version_text, reason); + const r = await redactMemoryVersion(identity.org, h.memory_id, h.version_text, reason, "explicit"); if (r.refused_head) throw new Error(`${label} is a live version; edit or delete the memory instead.`); if (!r.redacted) throw new Error(`${label} is no longer recorded.`); toast(`Redacted ${label}`, "ok"); @@ -645,7 +645,7 @@ export function MemoryInspector({ const onUnlock = async () => { if (!detail) return; try { - const r = await unlockMemory(rowIdentity(identity, detail), memoryKey); + const r = await unlockMemory(rowIdentity(identity, detail), memoryKey, "explicit"); if (!r.unlocked) { toast(r.reason === "not_found" ? "This memory is no longer live" : "This memory carried no lock", "info"); return; @@ -671,7 +671,7 @@ export function MemoryInspector({ try { // A definition's promotion names the text it approves: the one shown. const approved = detail.memory_type === "definition" ? detail.content_sha256 : undefined; - const r = await shareMemory(rowIdentity(identity, detail), memoryKey, approved); + const r = await shareMemory(rowIdentity(identity, detail), memoryKey, approved, "explicit"); toast(`Shared as ${r.shared_memory_key}`, "ok"); onChanged(); } catch (e) { @@ -688,7 +688,7 @@ export function MemoryInspector({ }); if (!ok) return; try { - const r = await unshareMemory(identity, memoryKey); + const r = await unshareMemory(identity, memoryKey, "explicit"); toast(r.demoted ? "No longer shared" : "This memory was not shared", "ok"); onChanged(); } catch (e) { @@ -739,7 +739,7 @@ export function MemoryInspector({ memoryType: detail.memory_type || "semantic", tags: nextTags, charLimit: detail.char_limit ?? undefined, - }); + }, "explicit"); } catch (e) { if (!committedAnyway("Tag update failed", e)) { setDetail((d) => (d ? { ...d, tags: prev } : d)); @@ -774,7 +774,7 @@ export function MemoryInspector({ ttlSeconds: ttlSeconds ?? undefined, clearExpiry: ttlSeconds === null, charLimit: detail.char_limit ?? undefined, - }); + }, "explicit"); toast(ttlSeconds === null ? "Expiry cleared — never expires" : "Expiry updated", "ok"); } catch (e) { if (!committedAnyway("Expiry update failed", e)) return; @@ -800,7 +800,7 @@ export function MemoryInspector({ memoryType: detail.memory_type || "semantic", tags: detail.tags, charLimit: detail.char_limit ?? undefined, - }); + }, "explicit"); toast("Saved", "ok"); } catch (e) { if (!committedAnyway("Save failed", e)) return; @@ -846,7 +846,7 @@ export function MemoryInspector({ // outside the reader's scope shows no successor, so it is guarded by status. if_superseded_by: detail.superseded_by, only_if_superseded: true, - }); + }, "explicit"); // Either way the row changed, so the list behind the drawer is stale too, // even if the drawer has moved on to another memory. onChanged(); @@ -895,7 +895,7 @@ export function MemoryInspector({ ) return; try { - const r = await deleteMemory(rowIdentity(identity, detail), memoryKey); + const r = await deleteMemory(rowIdentity(identity, detail), memoryKey, "explicit"); if (!r.tombstoned) { toast("This memory is no longer live", "info"); return; @@ -2151,7 +2151,7 @@ function RenameForm({ const call = async (dryRun: boolean) => { setBusy(dryRun ? "preview" : "rename"); try { - const r = await moveMemory(identity, fromKey, target, { keepRedirect: redirect, dryRun }); + const r = await moveMemory(identity, fromKey, target, { keepRedirect: redirect, dryRun }, "explicit"); if (dryRun) setPreview(r); else onRenamed(r); } catch (e) { diff --git a/frontend/src/components/NamespacePicker.seen.test.tsx b/frontend/src/components/NamespacePicker.seen.test.tsx index 63a5985fdd..9a8a93f1a0 100644 --- a/frontend/src/components/NamespacePicker.seen.test.tsx +++ b/frontend/src/components/NamespacePicker.seen.test.tsx @@ -65,7 +65,7 @@ describe("NamespacePicker's New badge", () => { const billing = await rowButton("billing"); expect(within(billing).getByText("New")).toBeInTheDocument(); fireEvent.click(billing); - await waitFor(() => expect(markNamespaceSeen).toHaveBeenCalledWith("dev", "billing")); + await waitFor(() => expect(markNamespaceSeen).toHaveBeenCalledWith("dev", "billing", "explicit")); expect(useStore.getState().myNamespaces?.find((r) => r.namespace === "billing")?.is_new).toBe(false); }); diff --git a/frontend/src/components/NamespacePicker.tsx b/frontend/src/components/NamespacePicker.tsx index 13a6050bca..4342e79592 100644 --- a/frontend/src/components/NamespacePicker.tsx +++ b/frontend/src/components/NamespacePicker.tsx @@ -101,7 +101,7 @@ function NamespacePickerMenu() { const { myNamespaces, setMyNamespaces } = useStore.getState(); if (myNamespaces?.find((r) => r.namespace === ns)?.is_new) { setMyNamespaces(myNamespaces.map((r) => (r.namespace === ns ? { ...r, is_new: false } : r))); - markNamespaceSeen(identity.org, ns) + markNamespaceSeen(identity.org, ns, "explicit") .then(() => invalidateShared("mine:")) // The badge is a convenience: after a failed mark it comes back on the next list read. .catch(() => {}); diff --git a/frontend/src/components/NamespacePickerList.tsx b/frontend/src/components/NamespacePickerList.tsx index b3b74d3034..a0e43ada94 100644 --- a/frontend/src/components/NamespacePickerList.tsx +++ b/frontend/src/components/NamespacePickerList.tsx @@ -241,7 +241,7 @@ export function NamespacePickerList({ ) return; try { - await cancelNamespaceRequest(identity.org, ns); + await cancelNamespaceRequest(identity.org, ns, "explicit"); toast(`Withdrew ${role} request`, "ok"); invalidateShared("mine:"); listMine(identity.org) diff --git a/frontend/src/components/PendingRequestBanner.tsx b/frontend/src/components/PendingRequestBanner.tsx index caa2dba4ba..38394f63d7 100644 --- a/frontend/src/components/PendingRequestBanner.tsx +++ b/frontend/src/components/PendingRequestBanner.tsx @@ -61,7 +61,7 @@ export function PendingRequestBanner() { return; setCancelling(true); try { - await cancelNamespaceRequest(identity.org, entry.namespace); + await cancelNamespaceRequest(identity.org, entry.namespace, "explicit"); toast(`Withdrew ${requested} request on ${entry.namespace}`, "ok"); setEntry(null); } catch (e) { diff --git a/frontend/src/components/SessionBriefsSection.test.tsx b/frontend/src/components/SessionBriefsSection.test.tsx index d2e600d6e7..6fbd19faa9 100644 --- a/frontend/src/components/SessionBriefsSection.test.tsx +++ b/frontend/src/components/SessionBriefsSection.test.tsx @@ -85,7 +85,7 @@ describe("SessionBriefsSection", () => { deleteBrief.mockResolvedValue({ deleted: true }); render(); fireEvent.click(await screen.findByRole("button", { name: "Forget brief Billing handoff" })); - await waitFor(() => expect(deleteBrief).toHaveBeenCalledWith({ org: "o", namespace: "ns" }, "handoff/billing")); + await waitFor(() => expect(deleteBrief).toHaveBeenCalledWith({ org: "o", namespace: "ns" }, "handoff/billing", "explicit")); await waitFor(() => expect(screen.queryByRole("button", { name: "Forget brief Billing handoff" })).toBeNull()); }); diff --git a/frontend/src/components/SessionBriefsSection.tsx b/frontend/src/components/SessionBriefsSection.tsx index 0ff076b7f6..7c153b9e26 100644 --- a/frontend/src/components/SessionBriefsSection.tsx +++ b/frontend/src/components/SessionBriefsSection.tsx @@ -33,7 +33,7 @@ export function SessionBriefsSection({ org, namespace }: { org: string; namespac }); if (!ok) return; try { - await deleteBrief({ org, namespace }, b.brief_key); + await deleteBrief({ org, namespace }, b.brief_key, "explicit"); setBriefs((all) => all.filter((x) => x.brief_key !== b.brief_key)); } catch (e) { toastError("Couldn't forget the brief", e); diff --git a/frontend/src/flows/AddDocumentDialog.test.tsx b/frontend/src/flows/AddDocumentDialog.test.tsx index 0310fd31f1..7f62917d01 100644 --- a/frontend/src/flows/AddDocumentDialog.test.tsx +++ b/frontend/src/flows/AddDocumentDialog.test.tsx @@ -224,7 +224,7 @@ describe("AddDocumentDialog", () => { const user = await pick("spec.pdf"); await user.click(within(dialog).getByRole("button", { name: "Upload" })); await user.click(await within(dialog).findByRole("button", { name: "Stop ingestion" })); - await waitFor(() => expect(cancelIngestion).toHaveBeenCalledWith(identity, "job-1")); + await waitFor(() => expect(cancelIngestion).toHaveBeenCalledWith(identity, "job-1", "explicit")); expect(onOpenChange).toHaveBeenCalledWith(false); expect(vi.mocked(toast).mock.calls.at(-1)?.[0]).toBe("Stopped spec.pdf"); }); diff --git a/frontend/src/flows/AddDocumentDialog.tsx b/frontend/src/flows/AddDocumentDialog.tsx index 9092b393a2..25b31ac23e 100644 --- a/frontend/src/flows/AddDocumentDialog.tsx +++ b/frontend/src/flows/AddDocumentDialog.tsx @@ -322,7 +322,7 @@ export function AddDocumentDialog({ setStep(line); setBusy(phase); }, - { signal: ctrl.signal, onQueued: setJobId }, + { signal: ctrl.signal, onQueued: setJobId, intent: "explicit" }, ); if (status.state === "ready" || status.state === "partial") { const what = `${replaceMode ? "Replaced" : "Added"} ${sourceUri.trim()}: revision ${status.revision}`; @@ -359,7 +359,7 @@ export function AddDocumentDialog({ description: description.trim(), content, tags: tags(), - }); + }, "explicit"); // Heads-up when this text duplicates an existing doc under a different source_uri. if (r.duplicate_of_uri && r.duplicate_of_uri !== sourceUri.trim()) { toast(`Same content already in your library as "${r.duplicate_of_uri}" — keeping both`, "info"); @@ -404,7 +404,7 @@ export function AddDocumentDialog({ following.current?.abort(); setStopping(true); try { - const r = await cancelIngestion(identity, jobId); + const r = await cancelIngestion(identity, jobId, "explicit"); if (published(r)) onAdded(); toast(stopped(sourceUri.trim(), r), "info"); } catch (e) { diff --git a/frontend/src/flows/AddMemoryDialog.tsx b/frontend/src/flows/AddMemoryDialog.tsx index 06242a2485..2a10235cc5 100644 --- a/frontend/src/flows/AddMemoryDialog.tsx +++ b/frontend/src/flows/AddMemoryDialog.tsx @@ -87,7 +87,7 @@ export function AddMemoryDialog({ open, onOpenChange, identity, onAdded, reason memoryType: "semantic", tags, ttlSeconds: EXPIRY_OPTIONS[expiryIdx].ttlSeconds, - }); + }, "explicit"); toast("Memory added", "ok"); } catch (e) { // Added, with only lists and search behind: the dialog closes as after a success, so diff --git a/frontend/src/flows/BatchUpload.tsx b/frontend/src/flows/BatchUpload.tsx index 5e06734be7..15f2b03360 100644 --- a/frontend/src/flows/BatchUpload.tsx +++ b/frontend/src/flows/BatchUpload.tsx @@ -514,7 +514,7 @@ export function BatchUpload({ if (asCollections && start.some((r) => r.state === "waiting" && r.folder)) { foldersSent.current = true; setRows(start.map((r) => (r.state === "waiting" && r.folder ? { ...r, line: MAKING } : r))); - const folders = new FolderCollections(org, byFolder, root, quietRetry(c.signal), madeHere.current); + const folders = new FolderCollections(org, byFolder, root, quietRetry(c.signal), madeHere.current, "explicit"); const placed = await placeFolders(start, folders, sourcesOf, wentTo, c.signal); madeHere.current.push(...folders.created); // Collections were made or titled: other views read again, waiting for the first made. @@ -548,6 +548,7 @@ export function BatchUpload({ // Each row as the run left it, kept here: the rendered rows may lag the last update. const final = new Map(begin.map((r) => [r.id, r])); await runBatch(begin, { + intent: "explicit", fields: { tags, allow_partial: allowPartial }, signal: c.signal, cancelling: () => cancelling.current, diff --git a/frontend/src/flows/CodeReindexDialog.test.tsx b/frontend/src/flows/CodeReindexDialog.test.tsx index 30f47d2d55..ba63de1063 100644 --- a/frontend/src/flows/CodeReindexDialog.test.tsx +++ b/frontend/src/flows/CodeReindexDialog.test.tsx @@ -52,7 +52,7 @@ describe("CodeReindexDialog", () => { expect(screen.getByRole("button", { name: "Re-index" })).toBeDisabled(); await pick(); await userEvent.click(screen.getByRole("button", { name: "Re-index" })); - await waitFor(() => expect(api.codeReindex).toHaveBeenCalledWith({ org: "acme", namespace: "code-x" }, sha)); + await waitFor(() => expect(api.codeReindex).toHaveBeenCalledWith({ org: "acme", namespace: "code-x" }, sha, "explicit")); expect(api.codeRecentCommits).toHaveBeenCalledWith({ org: "acme", namespace: "code-x" }, 100, expect.anything()); expect(onDone).toHaveBeenCalled(); expect(onClose).toHaveBeenCalled(); diff --git a/frontend/src/flows/CodeReindexDialog.tsx b/frontend/src/flows/CodeReindexDialog.tsx index 96c8716743..55ffbd67ea 100644 --- a/frontend/src/flows/CodeReindexDialog.tsx +++ b/frontend/src/flows/CodeReindexDialog.tsx @@ -44,7 +44,7 @@ export function CodeReindexDialog({ setBusy(true); setError(null); try { - const r = await codeReindex(id, sha); + const r = await codeReindex(id, sha, "explicit"); toast(`${branch.repo} @ ${branch.branch} indexes the commits after ${r.new_head.slice(0, 12)} again`, "ok"); onDone(); onClose(); diff --git a/frontend/src/flows/CopyToNamespaceDialog.tsx b/frontend/src/flows/CopyToNamespaceDialog.tsx index c97207f368..c496e362a1 100644 --- a/frontend/src/flows/CopyToNamespaceDialog.tsx +++ b/frontend/src/flows/CopyToNamespaceDialog.tsx @@ -77,7 +77,7 @@ export function CopyToNamespaceDialog({ open, onOpenChange, source, memoryKey }: const res = await copyMemoryTo(source, memoryKey, target, { targetKey: newKey.trim() || undefined, rationale: rationale.trim() || undefined, - }); + }, "explicit"); toast(`Copied to ${res.target_namespace} as ${res.target_key}`, "ok"); reset(); onOpenChange(false); diff --git a/frontend/src/flows/CreateCollectionDialog.tsx b/frontend/src/flows/CreateCollectionDialog.tsx index 25fbfec41a..af15f6a531 100644 --- a/frontend/src/flows/CreateCollectionDialog.tsx +++ b/frontend/src/flows/CreateCollectionDialog.tsx @@ -129,14 +129,14 @@ export function CreateCollectionDialog({ const into = parent === TOP_LEVEL ? "" : parent; try { const r = ownAddress - ? await createCollection(org, trimmed, { parent: into, description: description.trim(), title: trimmedTitle }) + ? await createCollection(org, trimmed, { parent: into, description: description.trim(), title: trimmedTitle }, "explicit") : // The plain name rides along for a server a release behind, which creates it. await createCollection(org, derived || placeholderName(trimmedTitle), { parent: into, description: description.trim(), title: trimmedTitle, deriveName: true, - }); + }, "explicit"); announceCreated(r, trimmedTitle, org); if (!mounted.current) return; onCreated(r.namespace, version); diff --git a/frontend/src/flows/CreateNamespaceDialog.tsx b/frontend/src/flows/CreateNamespaceDialog.tsx index 34c6876210..7c2c76748b 100644 --- a/frontend/src/flows/CreateNamespaceDialog.tsx +++ b/frontend/src/flows/CreateNamespaceDialog.tsx @@ -71,6 +71,7 @@ export function CreateNamespaceDialog({ open, onOpenChange, onCreated }: Props) visibility, requires_approval: visibility === "public" ? requiresApproval : false, }, + "explicit", ); toast(`Created ${trimmed}`, "ok"); // Switch to the freshly-created namespace. diff --git a/frontend/src/flows/DatasetsDialog.test.tsx b/frontend/src/flows/DatasetsDialog.test.tsx index fd9fd38792..260aacbea1 100644 --- a/frontend/src/flows/DatasetsDialog.test.tsx +++ b/frontend/src/flows/DatasetsDialog.test.tsx @@ -45,7 +45,7 @@ describe("DatasetsDialog", () => { expect(within(dialog).getByText(/could be a date/)).toBeInTheDocument(); expect(within(dialog).getByText("needs a decision")).toBeInTheDocument(); await userEvent.click(within(dialog).getByRole("button", { name: "Approve schema" })); - await waitFor(() => expect(api.approveDataset).toHaveBeenCalledWith(identity, "q3.xlsx", SET, {})); + await waitFor(() => expect(api.approveDataset).toHaveBeenCalledWith(identity, "q3.xlsx", SET, {}, "explicit")); }); it("shows a reader the types, and Approve unavailable with the role it needs", async () => { @@ -76,7 +76,7 @@ describe("DatasetsDialog", () => { fireEvent.click(within(options).getByText("string")); await userEvent.click(screen.getByRole("button", { name: "Retype and approve" })); await waitFor(() => - expect(api.approveDataset).toHaveBeenCalledWith(identity, "q3.xlsx", SET, { amount: "string" }), + expect(api.approveDataset).toHaveBeenCalledWith(identity, "q3.xlsx", SET, { amount: "string" }, "explicit"), ); }); diff --git a/frontend/src/flows/DatasetsDialog.tsx b/frontend/src/flows/DatasetsDialog.tsx index e4b4fce9a0..4b76ccb846 100644 --- a/frontend/src/flows/DatasetsDialog.tsx +++ b/frontend/src/flows/DatasetsDialog.tsx @@ -95,7 +95,7 @@ function DatasetCard({ const approve = async () => { setBusy(true); try { - const r = await approveDataset(identity, sourceUri, d, retyped); + const r = await approveDataset(identity, sourceUri, d, retyped, "explicit"); toast(r.found ? `Approved ${d.name}` : `${d.name} is no longer in this document`, r.found ? "ok" : "info"); onChanged(); } catch (e) { diff --git a/frontend/src/flows/DialogStaleLoad.test.tsx b/frontend/src/flows/DialogStaleLoad.test.tsx index ad1fa6f7ca..b2ba578a6d 100644 --- a/frontend/src/flows/DialogStaleLoad.test.tsx +++ b/frontend/src/flows/DialogStaleLoad.test.tsx @@ -198,7 +198,7 @@ describe("a stale namespace load is dropped", () => { await act(async () => fireEvent.click(screen.getByRole("button", { name: "Save" }))); expect(api.reregisterNamespace).toHaveBeenCalledWith({ org: "dev", namespace: "old-ns" }, nsRow("old-ns"), { description: "edited", - }); + }, "explicit"); rerender(); await act(async () => undefined); diff --git a/frontend/src/flows/EditDocumentMetadataDialog.tsx b/frontend/src/flows/EditDocumentMetadataDialog.tsx index fb1bda2fa7..1b595e7146 100644 --- a/frontend/src/flows/EditDocumentMetadataDialog.tsx +++ b/frontend/src/flows/EditDocumentMetadataDialog.tsx @@ -58,7 +58,7 @@ export function EditDocumentMetadataDialog({ open, onOpenChange, identity, entry description: description.trim(), tags, reindex, - }); + }, "explicit"); if (reindex && r.chunks_reindexed > 0) { toast(`Saved · re-embedded ${r.chunks_reindexed} chunks`, "ok"); } else { diff --git a/frontend/src/flows/ForgetMemoriesDialog.tsx b/frontend/src/flows/ForgetMemoriesDialog.tsx index baec8f566e..96eb9ebbd0 100644 --- a/frontend/src/flows/ForgetMemoriesDialog.tsx +++ b/frontend/src/flows/ForgetMemoriesDialog.tsx @@ -22,7 +22,7 @@ export function ForgetMemoriesDialog({ agent, onClose }: { agent: string; onClos setBusy(true); setError(null); try { - const r = await clearAgentMemories(identity, agent, AbortSignal.timeout(LONG_CALL_MS)); + const r = await clearAgentMemories(identity, agent, AbortSignal.timeout(LONG_CALL_MS), "explicit"); const locked = r.locked_skipped > 0 ? `; ${r.locked_skipped} locked kept` : ""; const n = r.rows_affected["loom.memory"] ?? 0; toast(`Forgot ${n} memor${n === 1 ? "y" : "ies"} of ${agent}${locked}`, "ok"); diff --git a/frontend/src/flows/GuideDialog.test.tsx b/frontend/src/flows/GuideDialog.test.tsx index c0f00e1492..1585a17b29 100644 --- a/frontend/src/flows/GuideDialog.test.tsx +++ b/frontend/src/flows/GuideDialog.test.tsx @@ -57,7 +57,7 @@ describe("GuideDialog", () => { content: "Keys: acct//plan\nTag stale", note: "", expected_revision: 3, - }); + }, "explicit"); }); it("closes an open editor when a reason appears, and saves nothing", async () => { diff --git a/frontend/src/flows/GuideDialog.tsx b/frontend/src/flows/GuideDialog.tsx index 89cbf64538..0547a55143 100644 --- a/frontend/src/flows/GuideDialog.tsx +++ b/frontend/src/flows/GuideDialog.tsx @@ -134,7 +134,7 @@ export function GuideDialog({ ...(summary !== base.summary ? { summary } : {}), note, expected_revision: base.revision, - }); + }, "explicit"); if (r.conflict && r.current) { if (summary === base.summary) setSummary(r.current.summary); setBase(r.current); diff --git a/frontend/src/flows/InboxSettingsDialog.tsx b/frontend/src/flows/InboxSettingsDialog.tsx index b2a1a482e9..1c6c358863 100644 --- a/frontend/src/flows/InboxSettingsDialog.tsx +++ b/frontend/src/flows/InboxSettingsDialog.tsx @@ -117,7 +117,7 @@ export function InboxSettingsDialog({ open, onOpenChange, identity, inbox, onSav triage_escalate_after_seconds: escalate, webhook_url: webhook.trim(), ...(version != null ? { if_match_version: version } : {}), - }); + }, "explicit"); toast(r.created ? "Inbox registered" : "Inbox settings saved", "ok"); setVersion(r.inbox.version); onSaved(r.inbox); @@ -527,7 +527,7 @@ function TrustTable({ identity, inbox, open }: { identity: Caller; inbox: string kind: draft.kind.trim() || "*", mode: draft.mode, require_evidence: splitList(draft.require_evidence), - }); + }, "explicit"); toast("Trust rule saved", "ok"); setDraft(null); load(); @@ -542,7 +542,7 @@ function TrustTable({ identity, inbox, open }: { identity: Caller; inbox: string setBusy(true); setError(null); try { - await setPolicy(identity, { inbox, poster: p.poster, kind: p.kind, mode: p.mode, remove: true }); + await setPolicy(identity, { inbox, poster: p.poster, kind: p.kind, mode: p.mode, remove: true }, "explicit"); toast("Trust rule removed", "ok"); load(); } catch (e) { diff --git a/frontend/src/flows/KnowledgeSourceDialog.test.tsx b/frontend/src/flows/KnowledgeSourceDialog.test.tsx index 3024fc2902..814b91d5c6 100644 --- a/frontend/src/flows/KnowledgeSourceDialog.test.tsx +++ b/frontend/src/flows/KnowledgeSourceDialog.test.tsx @@ -1,10 +1,3 @@ -/** - * Adding a document source checks first — `knowledge.source.add(dry_run)`, nothing - * stored — and Add sends exactly the form that passed, each kind with its own config. - * A key is typed into a password field, and no toast, error or text on the page ever - * carries it. Check probes on open and stops when the dialog closes; Sync now records a - * request; Retire needs the typed name and keeps the documents unless asked. - */ import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; import userEvent from "@testing-library/user-event"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -20,7 +13,7 @@ import { ApiError } from "../lib/errors"; import { sourceAddBody, type SourceForm } from "../lib/knowledgeSources"; import { axeViolations, unlabeledControls } from "../test/axe"; import { - AddSourceDialog, + AddRecordingSourceDialog, CheckSourceDialog, RetireSourceDialog, RotateSourceDialog, @@ -44,9 +37,7 @@ vi.mock("../components/Toast", async (importOriginal) => { }); const SECRET = "secret-value-7f3a"; -const KEY = `{"type": "service_account", "private_key": "${SECRET}"}`; const ZOOM_KEY = JSON.stringify({ account_id: "account", client_id: "client", client_secret: SECRET }); -const FOLDER = "1AbCdEfGhIjKlMnOp"; const NS = { org: "o", namespace: "code-x" }; afterEach(() => { @@ -70,14 +61,14 @@ function expectKeyNowhere() { async function fill() { const user = userEvent.setup(); fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: "design-docs" } }); - await user.click(screen.getByLabelText(/^Folders/)); - await user.paste(FOLDER); - fireEvent.change(screen.getByLabelText(/^Service account key/), { target: { value: KEY } }); + await user.click(screen.getByLabelText(/^Meetings/)); + await user.paste("81234567890"); + fireEvent.change(screen.getByLabelText(/^Read-only credential/), { target: { value: ZOOM_KEY } }); } const addResult = (dryRun: boolean) => ({ name: "design-docs", - kind: "gdrive", + kind: "recording", namespace: "code-x", config: {}, probe: { documents: 12, more: false, sample: ["Storage design"] }, @@ -85,11 +76,11 @@ const addResult = (dryRun: boolean) => ({ }); function renderAdd(onAdded = vi.fn()) { - render( {}} {...NS} label="Acme/x" onAdded={onAdded} />); + render( {}} {...NS} label="Acme/x" onAdded={onAdded} />); return onAdded; } -describe("AddSourceDialog", () => { +describe("AddRecordingSourceDialog", () => { it("checks before it adds, and adds only the form that passed", async () => { vi.mocked(addKnowledgeSource).mockImplementation(async (_id, _f, dryRun) => addResult(dryRun)); const onAdded = renderAdd(); @@ -97,7 +88,7 @@ describe("AddSourceDialog", () => { expect(add).toBeDisabled(); expect(screen.getByRole("button", { name: "Check" })).toBeDisabled(); await fill(); - expect(screen.getByLabelText(/^Service account key/)).toHaveAttribute("type", "password"); + expect(screen.getByLabelText(/^Read-only credential/)).toHaveAttribute("type", "password"); fireEvent.click(screen.getByRole("button", { name: "Check" })); expect(await screen.findByText(/lists 12 documents/)).toBeInTheDocument(); expect(screen.getByText("Storage design")).toBeInTheDocument(); @@ -117,20 +108,6 @@ describe("AddSourceDialog", () => { expect(await axeViolations(document.body)).toEqual([]); }); - it("unticking and ticking a file kind again leaves the checked form, so Add stays on", async () => { - vi.mocked(addKnowledgeSource).mockImplementation(async (_id, _f, dryRun) => addResult(dryRun)); - renderAdd(); - await fill(); - fireEvent.click(screen.getByRole("button", { name: "Check" })); - await screen.findByText(/lists 12 documents/); - const add = screen.getByRole("button", { name: "Add source" }); - const docs = screen.getByRole("checkbox", { name: "Documents" }); - fireEvent.click(docs); - expect(add).toBeDisabled(); - fireEvent.click(docs); - expect(add).toBeEnabled(); - }); - it("shows a refused check, keeps Add off, and the key appears nowhere", async () => { vi.mocked(addKnowledgeSource).mockRejectedValue(refused()); renderAdd(); @@ -166,11 +143,7 @@ function sentBody(n: number) { return sourceAddBody(call[0].org, call[0].namespace, call[1] as SourceForm, call[2]); } -const PROJECT = "0f8b2c4e-1a2b-4c3d-8e9f-0123456789ab"; -const PAGE = "1a2b3c4d5e6f708192a3b4c5d6e7f809"; -const DATABASE = "abcdefabcdefabcdefabcdefabcdef01"; - -describe("AddSourceDialog's kinds", () => { +describe("recording source setup", () => { async function typeInto(name: RegExp, text: string) { const user = userEvent.setup(); await user.click(screen.getByRole("textbox", { name })); @@ -186,60 +159,8 @@ describe("AddSourceDialog's kinds", () => { expect(sentBody(1)).toEqual({ ...sentBody(0), dry_run: false }); } - it("offers each kind, the shared folder first", () => { - renderAdd(); - const kinds = screen.getAllByRole("radio").map((r) => r.getAttribute("aria-label")); - expect(kinds).toEqual(["Shared folder", "Project documents", "Pages", "Zoom transcripts"]); - expect(screen.getByRole("radio", { name: "Shared folder" })).toHaveAttribute("aria-checked", "true"); - }); - - it("adds a project tracker's projects with a read-only API key", async () => { - renderAdd(); - fireEvent.click(screen.getByRole("radio", { name: "Project documents" })); - expect(screen.queryByLabelText(/^Folders/)).toBeNull(); - fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: "roadmap" } }); - await typeInto(/^Projects/, PROJECT); - const key = screen.getByLabelText(/^Read-only API key/); - expect(key).toHaveAttribute("type", "password"); - fireEvent.change(key, { target: { value: SECRET } }); - await checkAndAdd(/The key reads the projects: roadmap lists 12 documents/); - expect(sentBody(0)).toEqual({ - org: "o", - namespace: "code-x", - name: "roadmap", - kind: "linear", - config: { project_ids: [PROJECT] }, - credential: SECRET, - dry_run: true, - }); - expectKeyNowhere(); - expect(unlabeledControls(document.body)).toEqual([]); - expect(await axeViolations(document.body)).toEqual([]); - }); - - it("adds a page store's pages and databases with an integration token", async () => { - renderAdd(); - fireEvent.click(screen.getByRole("radio", { name: "Pages" })); - fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: "wiki" } }); - await typeInto(/^Pages/, `https://pages.example/team/Home-${PAGE}`); - await typeInto(/^Databases/, DATABASE); - const token = screen.getByLabelText(/^Integration token/); - expect(token).toHaveAttribute("type", "password"); - fireEvent.change(token, { target: { value: SECRET } }); - await checkAndAdd(/The token reads the pages and databases: wiki lists 12 documents/); - expect(sentBody(0)).toMatchObject({ - kind: "notion", - config: { page_ids: [PAGE], database_ids: [DATABASE] }, - credential: SECRET, - }); - expectKeyNowhere(); - expect(unlabeledControls(document.body)).toEqual([]); - expect(await axeViolations(document.body)).toEqual([]); - }); - it("adds Zoom meetings without a provider choice", async () => { renderAdd(); - fireEvent.click(screen.getByRole("radio", { name: "Zoom transcripts" })); expect(screen.queryByRole("radio", { name: "meet" })).toBeNull(); expect(screen.queryByRole("radio", { name: "zoom" })).toBeNull(); expect(screen.queryByLabelText(/^Meeting spaces/)).toBeNull(); @@ -264,93 +185,12 @@ describe("AddSourceDialog's kinds", () => { expect(await axeViolations(document.body)).toEqual([]); }); - it("routes Meet notes and transcripts through the shared folder form", async () => { - renderAdd(); - fireEvent.click(screen.getByRole("radio", { name: "Zoom transcripts" })); - expect(screen.getByText(/For Meet notes and transcripts, choose Shared folder/)).toBeInTheDocument(); - fireEvent.change(screen.getByLabelText(/^Read-only credential/), { target: { value: ZOOM_KEY } }); - fireEvent.click(screen.getByRole("radio", { name: "Shared folder" })); - expect(screen.getByText(/including Meet notes and transcripts saved as documents/)).toBeInTheDocument(); - expect(screen.getByLabelText(/^Service account key/)).toHaveValue(""); - expect(screen.getByRole("checkbox", { name: "Documents" })).toBeChecked(); - await fill(); - await checkAndAdd(/The key reads the folders: design-docs lists 12 documents/); - expect(sentBody(0)).toMatchObject({ - kind: "gdrive", - config: { folder_ids: [FOLDER], include: ["docs", "slides", "pdf", "pptx"] }, - credential: KEY, - }); - expectKeyNowhere(); - }); - - it("a check of one kind does not pass the form once the kind changes", async () => { - vi.mocked(addKnowledgeSource).mockImplementation(async (_id, _f, dryRun) => addResult(dryRun)); - renderAdd(); - await fill(); - fireEvent.click(screen.getByRole("button", { name: "Check" })); - await screen.findByText(/lists 12 documents/); - const add = screen.getByRole("button", { name: "Add source" }); - expect(add).toBeEnabled(); - fireEvent.click(screen.getByRole("radio", { name: "Project documents" })); - expect(add).toBeDisabled(); - // The key was typed for the shared folder: another kind never sends it. - expect(screen.getByLabelText(/^Read-only API key/)).toHaveValue(""); - // Back to the shared folder: the folders typed are still there; the key is asked - // for again, and the same key gives the form that passed. - fireEvent.click(screen.getByRole("radio", { name: "Shared folder" })); - expect(screen.getByLabelText(/^Folders/)).toHaveValue(FOLDER); - expect(screen.getByLabelText(/^Service account key/)).toHaveValue(""); - fireEvent.change(screen.getByLabelText(/^Service account key/), { target: { value: KEY } }); - expect(add).toBeEnabled(); - }); - - it("locks the kind while a Zoom check runs", async () => { - let answer: (v: ReturnType) => void = () => {}; - vi.mocked(addKnowledgeSource).mockImplementation(() => new Promise((resolve) => (answer = resolve))); - renderAdd(); - fireEvent.click(screen.getByRole("radio", { name: "Zoom transcripts" })); - fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: "standups" } }); - await typeInto(/^Meetings/, "81234567890"); - fireEvent.change(screen.getByLabelText(/^Read-only credential/), { target: { value: ZOOM_KEY } }); - fireEvent.click(screen.getByRole("button", { name: "Check" })); - expect(screen.getByRole("radio", { name: "Pages" })).toBeDisabled(); - expect(screen.queryByRole("radio", { name: "meet" })).toBeNull(); - await act(async () => answer(addResult(true))); - expect(screen.getByRole("radio", { name: "Pages" })).toBeEnabled(); - expect(screen.queryByRole("radio", { name: "zoom" })).toBeNull(); - }); - - it("shows the server's refusal of a config as it comes back", async () => { - const message = "config.project_ids: at most 20 projects"; - vi.mocked(addKnowledgeSource).mockRejectedValue(new ApiError({ status: 400, code: "BAD_CONFIG", message })); - renderAdd(); - fireEvent.click(screen.getByRole("radio", { name: "Project documents" })); - fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: "roadmap" } }); - await typeInto(/^Projects/, PROJECT); - fireEvent.change(screen.getByLabelText(/^Read-only API key/), { target: { value: SECRET } }); - fireEvent.click(screen.getByRole("button", { name: "Check" })); - expect(await screen.findByRole("alert")).toHaveTextContent(message); - expect(screen.getByRole("button", { name: "Add source" })).toBeDisabled(); - expectKeyNowhere(); - }); - - it("shows the server's refusal as it comes back", async () => { - // What the server answers when the account cannot see the meeting. - const message = - "the source could not be listed: meeting 81234567890: http_404; check the id and that the account can see it"; - vi.mocked(addKnowledgeSource).mockRejectedValue(new ApiError({ status: 400, code: "SOURCE_UNREACHABLE", message })); + it("offers only recording fields", () => { renderAdd(); - fireEvent.click(screen.getByRole("radio", { name: "Zoom transcripts" })); - fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: "standups" } }); - await typeInto(/^Meetings/, "81234567890"); - fireEvent.change(screen.getByLabelText(/^Read-only credential/), { target: { value: ZOOM_KEY } }); - fireEvent.click(screen.getByRole("button", { name: "Check" })); - expect(await screen.findByRole("alert")).toHaveTextContent(message); - // The error was the meeting store's: another kind does not show it. - fireEvent.click(screen.getByRole("radio", { name: "Pages" })); - expect(screen.queryByRole("alert")).toBeNull(); - expect(screen.getByRole("button", { name: "Add source" })).toBeDisabled(); - expectKeyNowhere(); + expect(screen.queryAllByRole("radio")).toEqual([]); + expect(screen.queryByLabelText(/^Folders/)).toBeNull(); + expect(screen.queryByLabelText(/^Pages/)).toBeNull(); + expect(screen.getByLabelText(/^Meetings/)).toBeInTheDocument(); }); }); @@ -368,28 +208,28 @@ describe("RotateSourceDialog", () => { onOpenChange={() => {}} {...NS} name="design-docs" - kind="gdrive" + kind="recording" onRotated={onRotated} />, ); const rotate = screen.getByRole("button", { name: "Rotate" }); expect(rotate).toBeDisabled(); - const field = screen.getByLabelText(/^Service account key/); + const field = screen.getByLabelText(/^Read-only credential/); expect(field).toHaveAttribute("type", "password"); - fireEvent.change(field, { target: { value: KEY } }); + fireEvent.change(field, { target: { value: ZOOM_KEY } }); fireEvent.click(rotate); await waitFor(() => expect(onRotated).toHaveBeenCalled()); expect(rotateKnowledgeSource).toHaveBeenCalledTimes(1); - expect(rotateKnowledgeSource).toHaveBeenCalledWith(NS, "design-docs", KEY); + expect(rotateKnowledgeSource).toHaveBeenCalledWith(NS, "design-docs", ZOOM_KEY, "explicit"); expectKeyNowhere(); }); it("shows a refused key without echoing it", async () => { vi.mocked(rotateKnowledgeSource).mockRejectedValue(refused()); render( - {}} {...NS} name="design-docs" kind="gdrive" onRotated={() => {}} />, + {}} {...NS} name="design-docs" kind="recording" onRotated={() => {}} />, ); - fireEvent.change(screen.getByLabelText(/^Service account key/), { target: { value: KEY } }); + fireEvent.change(screen.getByLabelText(/^Read-only credential/), { target: { value: ZOOM_KEY } }); fireEvent.click(screen.getByRole("button", { name: "Rotate" })); expect(await screen.findByRole("alert")).toHaveTextContent("refused the credential"); expectKeyNowhere(); @@ -449,7 +289,7 @@ describe("SyncNowDialog", () => { fireEvent.click(screen.getByRole("checkbox", { name: /List every document/ })); fireEvent.click(screen.getByRole("button", { name: "Request sync" })); await waitFor(() => expect(onRequested).toHaveBeenCalled()); - expect(syncKnowledgeSourceNow).toHaveBeenCalledWith(NS, "design-docs", true); + expect(syncKnowledgeSourceNow).toHaveBeenCalledWith(NS, "design-docs", true, "explicit"); expect(String(vi.mocked(toast).mock.calls[0]?.[0])).toContain("sync is off"); }); }); @@ -477,7 +317,7 @@ describe("RetireSourceDialog", () => { fireEvent.change(screen.getByLabelText(/to confirm/), { target: { value: "design-docs" } }); fireEvent.click(retire); await waitFor(() => expect(onRetired).toHaveBeenCalled()); - expect(removeKnowledgeSource).toHaveBeenCalledWith(NS, "design-docs", "design-docs", false); + expect(removeKnowledgeSource).toHaveBeenCalledWith(NS, "design-docs", "design-docs", false, "explicit"); expect(vi.mocked(toast).mock.calls[0]?.[0]).toBe("Retired design-docs; its documents stay"); }); @@ -488,7 +328,7 @@ describe("RetireSourceDialog", () => { fireEvent.change(screen.getByLabelText(/to confirm/), { target: { value: "design-docs" } }); fireEvent.click(screen.getByRole("button", { name: "Retire source" })); await waitFor(() => expect(onRetired).toHaveBeenCalled()); - expect(removeKnowledgeSource).toHaveBeenCalledWith(NS, "design-docs", "design-docs", true); + expect(removeKnowledgeSource).toHaveBeenCalledWith(NS, "design-docs", "design-docs", true, "explicit"); expect(vi.mocked(toast).mock.calls[0]?.[0]).toBe( "Retired design-docs; its 1 document is retired once sync is on for this deployment", ); diff --git a/frontend/src/flows/KnowledgeSourceDialog.tsx b/frontend/src/flows/KnowledgeSourceDialog.tsx index 6b6b7a540a..57aa6cc0bf 100644 --- a/frontend/src/flows/KnowledgeSourceDialog.tsx +++ b/frontend/src/flows/KnowledgeSourceDialog.tsx @@ -1,15 +1,3 @@ -/** - * Adding, checking, syncing, rotating and retiring a namespace's document source. - * Loaded on first use, behind `lazy()`, by the Sources list (a repository card's, or the - * Library's). - * - * Add probes first: the form takes a kind and that kind's ids, Check sends - * `knowledge.source.add` with `dry_run` (the credential is tried, nothing is stored) and - * shows what the source holds; Add stays off until the form it would send is the one - * that passed. A credential is typed into a password field, held in the dialog's state - * only, sent once and never shown back. Changing the kind clears it, so - * a credential is only ever sent to the store it was typed for. - */ import { useState } from "react"; import { Button } from "@clickhouse/click-ui/Button"; import { Checkbox } from "@clickhouse/click-ui/Checkbox"; @@ -28,22 +16,18 @@ import { useAbortableEffect } from "../lib/hooks"; import { credentialLabel, emptySourceForm, - INCLUDE_OPTIONS, KIND_FORM, - KIND_OPTIONS, normalisedName, probeCount, retiredMessage, sourceFormFingerprint, sourceFormProblems, sourceFormTouched, - toggleInclude, type KnowledgeSourceCheckResult, type KnowledgeSourceProbe, type SourceForm, } from "../lib/knowledgeSources"; import { toast } from "../components/Toast"; -import { ChoiceGroup } from "../components/ui/ChoiceGroup"; import { Alert } from "../components/ui/Alert"; import { Loading } from "../components/ui/Loading"; import { CancelButton, DialogFrame, ErrorNote } from "./TaskDialogFrame"; @@ -78,82 +62,7 @@ function ProbeResult({ probe, lead }: { probe: KnowledgeSourceProbe; lead: strin type SetField = (key: K, value: SourceForm[K]) => void; -/** The chosen kind's ids and filters, as the server's config for that kind takes them. */ -function SourceFields({ form, set }: { form: SourceForm; set: SetField }) { - switch (form.kind) { - case "gdrive": - return ( - <> - set("folders", v)} - /> -
- File kinds to pull -
- {INCLUDE_OPTIONS.map((o) => ( - set("include", toggleInclude(form.include, o.value))} - /> - ))} -
-
- - ); - case "linear": - return ( - set("projects", v)} - /> - ); - case "notion": - return ( - <> - set("pages", v)} - /> - set("databases", v)} - /> - - ); - case "recording": - return ( - set("meetings", v)} - /> - ); - } -} - -export function AddSourceDialog({ +export function AddRecordingSourceDialog({ open, onOpenChange, org, @@ -166,14 +75,7 @@ export function AddSourceDialog({ const [busy, setBusy] = useState<"check" | "add" | null>(null); const [error, setError] = useState(null); const set: SetField = (key, value) => { - // The credential and last error belong to the kind they were entered for. - const switched = key === "kind" && value !== form.kind; - if (switched) setError(null); - setForm((f) => ({ - ...f, - [key]: value, - ...(switched ? { credential: "" } : {}), - })); + setForm((f) => ({ ...f, [key]: value })); }; const problems = sourceFormProblems(form); const fingerprint = sourceFormFingerprint(form); @@ -183,7 +85,7 @@ export function AddSourceDialog({ setBusy(dryRun ? "check" : "add"); setError(null); try { - const out = await addKnowledgeSource({ org, namespace }, form, dryRun); + const out = await addKnowledgeSource({ org, namespace }, form, dryRun, "explicit"); if (dryRun) setChecked({ fingerprint, probe: out.probe }); else { onAdded(out.name); @@ -203,7 +105,7 @@ export function AddSourceDialog({ open={open} onOpenChange={onOpenChange} width={560} - title={`Add a document source · ${label}`} + title={`Add a recording source · ${label}`} description={KIND_FORM[form.kind].about} footer={ <> @@ -237,16 +139,7 @@ export function AddSourceDialog({ onChange={(v) => set("name", v)} autoFocus /> - {/* Locked while a call runs, so its answer lands on the form it was sent for. */} - set("kind", v)} - options={KIND_OPTIONS} - /> - + set("meetings", v)} /> ({ + ...(await original()), mcpProfiles: vi.fn(), mcpConnections: vi.fn(), + mcpConnect: vi.fn(), mcpInspectConnection: vi.fn(), mcpDiscover: vi.fn(), mcpDisconnect: vi.fn(), +})); +import * as api from "../api/mcpSources"; +import { MCPConnectionStep } from "./MCPConnectionStep"; + +async function chooseProfile() { fireEvent.click(await screen.findByRole("radio", { name: "Approved remote server" })); } +async function chooseAccount() { await chooseProfile(); fireEvent.click(screen.getByRole("radio", { name: "My connection (configured)" })); } + +describe("MCP connection setup", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(api.mcpProfiles).mockResolvedValue({ profiles: [mcpProfile], next_cursor: null, self_service_enabled: true }); + vi.mocked(api.mcpConnections).mockResolvedValue({ connections: [mcpConnection, { ...mcpConnection, slot: "second-slot", label: "Other connection", generation: "generation-b" }], next_cursor: null }); + vi.mocked(api.mcpInspectConnection).mockResolvedValue({ found: true, slot: mcpConnection.slot, connection: mcpConnection, reconciliation: "present" }); + vi.mocked(api.mcpDiscover).mockResolvedValue(mcpDiscovery); + vi.mocked(api.mcpConnect).mockResolvedValue({ connection: mcpConnection }); + vi.mocked(api.mcpDisconnect).mockResolvedValue({ disconnected: true, upstream_revoked: false, upstream_action: "revoke_credential_upstream" }); + }); + afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + + it("discloses trusted origin/auth and clears credentials before connecting without storage, URL or log writes", async () => { + render(); await chooseProfile(); + expect(screen.getByText(/Endpoint origin: https:\/\/source.example/)).toBeInTheDocument(); + expect(screen.getByText(/Preissued bearer sent to this approved server/)).toBeInTheDocument(); + const storage = vi.spyOn(Storage.prototype, "setItem"); + const history = vi.spyOn(window.history, "replaceState"); + const push = vi.spyOn(window.history, "pushState"); + const log = vi.spyOn(console, "log"); const warn = vi.spyOn(console, "warn"); const error = vi.spyOn(console, "error"); + const secret = "input-only-upstream-secret"; + await userEvent.type(screen.getByLabelText("Preissued upstream bearer"), secret); + await userEvent.click(screen.getByRole("button", { name: "Connect a new account" })); + await waitFor(() => expect(api.mcpConnect).toHaveBeenCalledTimes(1)); + expect(vi.mocked(api.mcpConnect).mock.calls[0]?.[0]).toEqual({ org: "acme", profile_id: mcpProfile.id, request_id: expect.any(String), bearer: secret }); + expect(screen.getByLabelText("Preissued upstream bearer")).toHaveValue(""); + expect(storage).not.toHaveBeenCalled(); expect(history).not.toHaveBeenCalled(); expect(push).not.toHaveBeenCalled(); + for (const spy of [log, warn, error]) expect(JSON.stringify(spy.mock.calls)).not.toContain(secret); + expect(document.body.textContent).not.toContain(secret); + expect(window.location.href).not.toContain(secret); + }); + it("requires a disclosed HTTPS origin before credential entry or discovery", async () => { + vi.mocked(api.mcpProfiles).mockResolvedValue({ profiles: [{ ...mcpProfile, endpoint_origin: "" }], next_cursor: null, self_service_enabled: true }); + render(); await chooseAccount(); + expect(screen.queryByLabelText("Preissued upstream bearer")).toBeNull(); + expect(screen.getByRole("button", { name: "Connect a new account" })).toBeDisabled(); + expect(screen.getByRole("button", { name: "Discover capabilities" })).toBeDisabled(); + expect(api.mcpConnect).not.toHaveBeenCalled(); expect(api.mcpDiscover).not.toHaveBeenCalled(); + }); + it("supports anonymous profiles without a bearer", async () => { + vi.mocked(api.mcpProfiles).mockResolvedValue({ profiles: [{ ...mcpProfile, auth: "none" }], next_cursor: null, self_service_enabled: true }); + render(); await chooseProfile(); + await userEvent.click(screen.getByRole("button", { name: "Connect a new account" })); + expect(vi.mocked(api.mcpConnect).mock.calls[0]?.[0]).not.toHaveProperty("bearer"); + }); + it("reconciles an uncertain connect by its original nonce without resubmitting credentials", async () => { + vi.mocked(api.mcpConnect).mockRejectedValue(new Error("cut response")); + render(); await chooseProfile(); + await userEvent.type(screen.getByLabelText("Preissued upstream bearer"), "secret"); + await userEvent.click(screen.getByRole("button", { name: "Connect a new account" })); + await screen.findByRole("button", { name: "Inspect connection result" }); + const nonce = vi.mocked(api.mcpConnect).mock.calls[0]?.[0].request_id; + await waitFor(() => expect(screen.getByRole("button", { name: "Inspect connection result" })).toBeEnabled()); + await userEvent.click(screen.getByRole("button", { name: "Inspect connection result" })); + expect(api.mcpInspectConnection).toHaveBeenCalledWith("acme", { request_id: nonce }, expect.any(AbortSignal)); + expect(api.mcpConnect).toHaveBeenCalledTimes(1); + expect(screen.getByLabelText("Preissued upstream bearer")).toHaveValue(""); + }); + it("drops a late discovery after the selected connection changes", async () => { + let release!: (result: MCPDiscovery) => void; + const held = new Promise((resolve) => { release = resolve; }); + vi.mocked(api.mcpDiscover).mockReturnValueOnce(held); + const changed = vi.fn(); render(); await chooseAccount(); + await userEvent.click(screen.getByRole("button", { name: "Discover capabilities" })); + // Simulate a native focus refresh, which remains possible during the read. + fireEvent(window, new Event("focus")); + await act(async () => { release(mcpDiscovery); await held; }); + expect(changed.mock.calls.some(([value]) => value?.discovery)).toBe(false); + }); + it("requires separate disconnect confirmation and reports no upstream revocation", async () => { + const changed = vi.fn(); render(); await chooseAccount(); + expect(screen.getByRole("button", { name: "Disconnect connection" })).toBeDisabled(); + fireEvent.click(screen.getByRole("checkbox", { name: /Disconnect this connection and stop all registrations/ })); + await userEvent.click(screen.getByRole("button", { name: "Disconnect connection" })); + expect(api.mcpDisconnect).toHaveBeenCalledWith("acme", mcpConnection.slot, expect.any(AbortSignal), "explicit"); + expect(await screen.findByText(/Upstream credential revoked: no/)).toHaveTextContent("Revoke it with the upstream service yourself"); + expect(changed).toHaveBeenLastCalledWith(null); + }); + it("retains the exact uncertain disconnect target through auth-context invalidation", async () => { + vi.mocked(api.mcpDisconnect).mockRejectedValue(new Error("cut disconnect response")); + const changed = vi.fn(); + const view = render(); await chooseAccount(); + fireEvent.click(screen.getByRole("checkbox", { name: /Disconnect this connection and stop all registrations/ })); + await userEvent.click(screen.getByRole("button", { name: "Disconnect connection" })); + await waitFor(() => expect(screen.getByRole("button", { name: "Inspect connection result" })).toBeEnabled()); + view.rerender(); + await userEvent.click(screen.getByRole("button", { name: "Inspect connection result" })); + expect(api.mcpInspectConnection).toHaveBeenLastCalledWith("acme", { slot: mcpConnection.slot }, expect.any(AbortSignal)); + expect(api.mcpDisconnect).toHaveBeenCalledTimes(1); + expect(screen.getByText(/The mutation result is uncertain/)).toBeInTheDocument(); + }); + it("rejects generation drift before running capability discovery", async () => { + vi.mocked(api.mcpInspectConnection).mockResolvedValue({ found: true, slot: mcpConnection.slot, connection: { ...mcpConnection, generation: "new-generation" }, reconciliation: "present" }); + const changed = vi.fn(); render(); await chooseAccount(); + await userEvent.click(screen.getByRole("button", { name: "Discover capabilities" })); + await screen.findByRole("alert"); expect(api.mcpDiscover).not.toHaveBeenCalled(); + expect(changed.mock.calls.some(([value]) => value?.discovery)).toBe(false); + }); +}); diff --git a/frontend/src/flows/MCPConnectionStep.tsx b/frontend/src/flows/MCPConnectionStep.tsx new file mode 100644 index 0000000000..a7cef67432 --- /dev/null +++ b/frontend/src/flows/MCPConnectionStep.tsx @@ -0,0 +1,198 @@ +import { Button } from "@clickhouse/click-ui/Button"; +import { Checkbox } from "@clickhouse/click-ui/Checkbox"; +import { PasswordField } from "@clickhouse/click-ui/PasswordField"; +import { TextField } from "@clickhouse/click-ui/TextField"; +import { useEffect, useRef, useState } from "react"; +import { + type MCPConnection, type MCPDiscovery, type MCPProfile, mcpConnect, mcpConnections, + mcpDiscover, mcpDisconnect, mcpInspectConnection, mcpProfiles, +} from "../api/mcpSources"; +import { Alert } from "../components/ui/Alert"; +import { ChoiceGroup } from "../components/ui/ChoiceGroup"; +import { ListState } from "../components/ui/ListState"; +import { Loading } from "../components/ui/Loading"; +import { useAbortableEffect } from "../lib/hooks"; +import type { DashboardRequestIntent } from "../lib/dashboardTransport"; +import { mcpSourceCopy as copy } from "./mcpSourceCopy"; +import { DialogFrame } from "./TaskDialogFrame"; +import { useMCPRequest } from "./useMCPRequest"; + +export interface MCPChosenConnection { connection: MCPConnection; discovery: MCPDiscovery } + +export function MCPConnectionsDialog({ org, callerKey, contextKey, onClose }: { org: string; callerKey: string; contextKey: string; onClose: () => void }) { + const [uncertain, setUncertain] = useState(false); + return { if (!open && !uncertain) onClose(); }} footer={}> + {}} onUncertainChange={setUncertain} /> +

{copy.privacy}

+
; +} + +/** Endpoint disclosure precedes credential entry. Discovery proves capabilities, never remote identity. */ +export function MCPConnectionStep({ org, callerKey, contextKey = "", onChange, onUncertainChange, disabled = false }: { + org: string; callerKey: string; onChange: (value: MCPChosenConnection | null) => void; + contextKey?: string; onUncertainChange?: (value: boolean) => void; disabled?: boolean; +}) { + const [profileCursor, setProfileCursor] = useState(null); + const [connectionCursor, setConnectionCursor] = useState(null); + const [revision, setRevision] = useState(0); + const [catalog, setCatalog] = useState> | null>(null); + const [accounts, setAccounts] = useState> | null>(null); + const [loadError, setLoadError] = useState(null); + const [loading, setLoading] = useState(true); + const [profile, setProfile] = useState(null); + const [slot, setSlot] = useState(""); + const [bearer, setBearer] = useState(""); + const [connectionLabel, setConnectionLabel] = useState(""); + const [pending, setPending] = useState<{ request_id: string; profile_id: string } | null>(null); + const [disconnectConfirmed, setDisconnectConfirmed] = useState(false); + const [disconnectUncertain, setDisconnectUncertain] = useState(false); + const [disconnectSlot, setDisconnectSlot] = useState(""); + const [notice, setNotice] = useState(""); + const [discovered, setDiscovered] = useState<{ key: string; value: MCPDiscovery } | null>(null); + useEffect(() => { onUncertainChange?.(pending !== null || disconnectUncertain); }, [pending, disconnectUncertain, onUncertainChange]); + const scope = JSON.stringify([org, callerKey, contextKey, profile?.profile_sha256, slot, revision]); + const request = useMCPRequest(scope); + const refresh = () => { + onChange(null); setBearer(""); setProfile(null); setSlot(""); setCatalog(null); setAccounts(null); + setLoading(true); setProfileCursor(null); setConnectionCursor(null); setRevision((r) => r + 1); + }; + const refreshRef = useRef(refresh); + refreshRef.current = refresh; + const previousContext = useRef(contextKey); + useEffect(() => { + if (previousContext.current !== contextKey) { + previousContext.current = contextKey; + refreshRef.current(); + } + }, [contextKey]); + useEffect(() => { + const focus = () => refreshRef.current(); + window.addEventListener("focus", focus); + return () => window.removeEventListener("focus", focus); + }, []); + useAbortableEffect(async (signal, live) => { + setLoading(true); setLoadError(null); + try { + const [profiles, connections] = await Promise.all([ + mcpProfiles(org, profileCursor, signal), mcpConnections(org, connectionCursor, signal), + ]); + if (!live()) return; + setCatalog(profiles); setAccounts(connections); setLoading(false); + } catch (error) { if (live()) { setLoadError(error); setLoading(false); } } + }, [org, callerKey, contextKey, profileCursor, connectionCursor, revision]); + + const useConnection = async (connection: MCPConnection, intent: DashboardRequestIntent) => { + if (connection.state !== "configured" || !profile || !origin || + connection.profile_sha256 !== profile.profile_sha256) return; + const result = await request.run(async (signal) => { + const inspected = await mcpInspectConnection(org, { slot: connection.slot }, signal); + const current = inspected.connection; + if (!inspected.found || !current || current.state !== "configured" || + current.slot !== connection.slot || current.profile_id !== profile.id || + current.generation !== connection.generation || current.profile_sha256 !== profile.profile_sha256) + throw new Error("Connection changed. Refresh the connection list."); + const discovery = await mcpDiscover(org, current.slot, signal, intent); + if (discovery.generation !== current.generation || discovery.slot !== current.slot || !discovery.supported_reads) + throw new Error("This connection has no supported reads. Refresh or choose another connection."); + return { connection: current, discovery }; + }); + if (result) { + setDiscovered({ key: scope, value: result.discovery }); + onChange(result); setNotice("Capability discovery returned supported reads. Remote identity and ACLs remain unverified."); + } + }; + const connect = async (intent: DashboardRequestIntent) => { + if (!profile || !origin || pending || !catalog?.self_service_enabled || request.busy || disabled || connectionLabel.length > 256) return; + const receipt = { request_id: crypto.randomUUID(), profile_id: profile.id }; + setPending(receipt); + const secret = profile.auth === "bearer" ? bearer : undefined; + setBearer(""); onChange(null); + const result = await request.run((signal) => mcpConnect({ org, ...receipt, ...(connectionLabel ? { label: connectionLabel } : {}), ...(secret === undefined ? {} : { bearer: secret }) }, signal, intent)); + if (result) { + setPending(null); setSlot(result.connection.slot); + setAccounts((a) => a ? { ...a, connections: [result.connection, ...a.connections.filter((c) => c.slot !== result.connection.slot)] } : a); + setNotice(`Server connection state: ${result.connection.state}. Discover capabilities before selecting content.`); + } + }; + const reconcile = async () => { + const inspectSlot = disconnectUncertain ? disconnectSlot : slot; + if (!pending && !inspectSlot) return; + const result = await request.run((signal) => mcpInspectConnection(org, pending ? { request_id: pending.request_id } : { slot: inspectSlot }, signal)); + if (!result) return; + setNotice(`Server reconciliation: ${result.reconciliation}. ${result.connection ? `Connection state: ${result.connection.state}.` : "No confirmed connection was returned. Do not resubmit."}`); + if (result.found && result.connection && result.reconciliation === "present") { + const connection = result.connection; + setPending(null); + if (connection.state === "stopped") { setDisconnectUncertain(false); setDisconnectSlot(""); } + setSlot(connection.slot); + setAccounts((a) => a ? { ...a, connections: [connection, ...a.connections.filter((c) => c.slot !== connection.slot)] } : a); + } + }; + const disconnect = async (intent: DashboardRequestIntent) => { + if (!slot || !disconnectConfirmed || disconnectUncertain || request.busy || disabled) return; + onChange(null); setDisconnectSlot(slot); setDisconnectUncertain(true); + const result = await request.run((signal) => mcpDisconnect(org, slot, signal, intent)); + if (result) { + setDisconnectUncertain(false); setDisconnectSlot(""); setDisconnectConfirmed(false); + setNotice(`Server disconnected: ${result.disconnected ? "yes" : "no"}. Upstream credential revoked: no. Revoke it with the upstream service yourself.`); + setAccounts((a) => a ? { ...a, connections: a.connections.map((c) => c.slot === slot && result.disconnected ? { ...c, state: "stopped" } : c) } : a); + } + }; + // A missing origin is a catalog integration gap, never permission to guess a host. + const origin = disclosedOrigin(profile?.endpoint_origin); + const choices = (accounts?.connections ?? []).filter((c) => c.profile_id === profile?.id); + const selected = choices.find((c) => c.slot === slot); + const locked = disabled || request.busy || pending !== null || disconnectUncertain; + return ( +
+

{copy.transport}

+ {loading && } + {!!loadError && } +
+ ({ value: p.id, label: p.label || p.id }))} + onChange={(id) => { onChange(null); setProfile(catalog?.profiles.find((p) => p.id === id) ?? null); setSlot(""); setBearer(""); setNotice(""); }} /> + {profile &&
+

Endpoint origin: {origin ?? "Not disclosed. Connection setup is unavailable until the operator discloses the trusted HTTPS origin."} This is operator-approved metadata; it does not verify remote identity.

+

Authentication: {profile.auth === "bearer" ? "Preissued bearer sent to this approved server" : "Anonymous"}.

+

Approved tools: {profile.approved_tools.join(", ") || "None declared"}. Operator collection-copy approval: {profile.allow_collection_copy ? "yes" : "no"}.

+
} + {profile && ({ value: c.slot, label: `${c.label || c.slot} (${c.state})` }))} + onChange={(value) => { onChange(null); setSlot(value); setBearer(""); setDisconnectConfirmed(false); setNotice(""); }} />} + {selected && } + {profile?.auth === "bearer" && origin && { onChange(null); setBearer(value); }} />} + {profile && } + {profile && } + {catalog && !catalog.self_service_enabled &&

New connection registration is disabled by the operator.

} +
+
+ + {catalog?.next_cursor && } + {accounts?.next_cursor && } +
+ {(pending || disconnectUncertain) && <>} + {selected &&
+ setDisconnectConfirmed(v === true)} /> + +
} + {!!request.error && } + {discovered?.key === scope &&
+

Server discovery: resources {discovered.value.resources ? "yes" : "no"}; approved read mapping {discovered.value.mapped_read ? "yes" : "no"}; approved search mapping {discovered.value.mapped_search ? "yes" : "no"}. These capabilities do not define or enumerate your selection.

+
    {discovered.value.limitations.map((line, index) =>
  • {line}
  • )}
+
} + {notice &&

{notice}

} +
+ ); +} + +function disclosedOrigin(value: string | undefined): string | null { + if (!value || /[^\x21-\x7e]/.test(value)) return null; + try { + const url = new URL(value); + return url.protocol === "https:" && !url.username && !url.password && url.origin === value ? value : null; + } catch { return null; } +} diff --git a/frontend/src/flows/MCPLiveRead.test.tsx b/frontend/src/flows/MCPLiveRead.test.tsx new file mode 100644 index 0000000000..264dfebbab --- /dev/null +++ b/frontend/src/flows/MCPLiveRead.test.tsx @@ -0,0 +1,78 @@ +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { type MCPLiveRead as LiveRead, mcpRead } from "../api/mcpSources"; +import { mcpSource } from "../test/mcpSources"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; +import { MCPLiveRead } from "./MCPLiveRead"; + +vi.mock("../api/mcpSources", () => ({ mcpRead: vi.fn() })); +const id = mcpSource.resource_ids[0] ?? ""; +const read: LiveRead = { source_id: mcpSource.source_id, resource_id: id, uri: "mcp-resource:stable", title: "Private resource", + text: "", mime_type: "text/plain", resource_identity_verified: false, + remote_identity_verified: false, upstream_acl_verified: false, limitations: ["no_acl_or_permission_sync_proof"] }; +const props = () => ({ org: "acme", source: { ...mcpSource, mode: "live" as const }, contextKey: "owner-authority", disabled: false }); +async function requestRead() { + fireEvent.click(screen.getByRole("radio", { name: id })); + await userEvent.click(screen.getByRole("button", { name: "Read selected live resource" })); +} +describe("explicit saved live reads", () => { + beforeEach(() => { vi.clearAllMocks(); vi.mocked(mcpRead).mockResolvedValue(read); }); + afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + it("loads one exact saved ID only on request, renders text and never stores or logs the body", async () => { + const storage = vi.spyOn(Storage.prototype, "setItem"); + const log = vi.spyOn(console, "log").mockImplementation(() => {}); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const info = vi.spyOn(console, "info").mockImplementation(() => {}); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const push = vi.spyOn(history, "pushState"); + const replace = vi.spyOn(history, "replaceState"); + render(); + expect(mcpRead).not.toHaveBeenCalled(); + await requestRead(); + expect(await screen.findByLabelText("Live resource text")).toHaveTextContent(read.text); + expect(screen.getByLabelText("Live resource text").querySelector("script")).toBeNull(); + expect(screen.getByText(/Stable citation:/)).toHaveTextContent(read.uri); + expect(screen.getByText(/Resource identity verified: no/)).toHaveTextContent("Upstream ACL verified: no"); + expect(screen.getByText("no_acl_or_permission_sync_proof")).toBeInTheDocument(); + expect(mcpRead).toHaveBeenCalledWith({ org: "acme", namespace: mcpSource.namespace, name: mcpSource.name, resource_id: id }, expect.any(AbortSignal)); + for (const spy of [storage, log, error, info, warn, push, replace]) expect(spy).not.toHaveBeenCalled(); + await userEvent.click(screen.getByRole("button", { name: "Clear live content" })); + expect(screen.queryByLabelText("Live resource text")).toBeNull(); + expect(mcpRead).toHaveBeenCalledTimes(1); + }); + it("drops late bodies after clear or an authority change", async () => { + let release!: (value: LiveRead) => void; + const held = new Promise((resolve) => { release = resolve; }); + vi.mocked(mcpRead).mockReturnValueOnce(held); + const p = props(); const view = render(); + await requestRead(); + await waitFor(() => expect(mcpRead).toHaveBeenCalledTimes(1)); + const signal = vi.mocked(mcpRead).mock.calls[0]?.[1]; + await userEvent.click(screen.getByRole("button", { name: "Clear live content" })); + view.rerender(); + expect(signal?.aborted).toBe(true); + await act(async () => { release(read); await held; }); + expect(screen.queryByLabelText("Live resource text")).toBeNull(); + expect(document.body.textContent).not.toContain(read.text); + }); + it("clears displayed content when authority changes and never auto-refreshes it", async () => { + const p = props(); const view = render(); await requestRead(); + await screen.findByLabelText("Live resource text"); + view.rerender(); + expect(screen.queryByLabelText("Live resource text")).toBeNull(); + view.rerender(); + expect(screen.queryByLabelText("Live resource text")).toBeNull(); + expect(mcpRead).toHaveBeenCalledTimes(1); + }); + it("refuses mismatched source IDs and protected transport failures without retry or error-body display", async () => { + vi.mocked(mcpRead).mockResolvedValueOnce({ ...read, source_id: "other" }); + render(); await requestRead(); + await screen.findByRole("alert"); + expect(screen.queryByLabelText("Live resource text")).toBeNull(); + vi.mocked(mcpRead).mockRejectedValueOnce(new Error(`MCP_PROTECTED_SESSION_REQUIRED ${read.text}`)); + await userEvent.click(screen.getByRole("button", { name: "Read selected live resource" })); + expect(await screen.findByRole("alert")).toHaveTextContent("refusals remain failures"); + expect(document.body.textContent).not.toContain(read.text); + expect(mcpRead).toHaveBeenCalledTimes(2); + }); +}); diff --git a/frontend/src/flows/MCPLiveRead.tsx b/frontend/src/flows/MCPLiveRead.tsx new file mode 100644 index 0000000000..7b58608a19 --- /dev/null +++ b/frontend/src/flows/MCPLiveRead.tsx @@ -0,0 +1,44 @@ +import { Button } from "@clickhouse/click-ui/Button"; +import { useEffect, useState } from "react"; +import { type MCPLiveRead as LiveRead, type MCPSource, mcpRead } from "../api/mcpSources"; +import { Alert } from "../components/ui/Alert"; +import { BusyButton } from "../components/ui/BusyButton"; +import { ChoiceGroup } from "../components/ui/ChoiceGroup"; +import { Loading } from "../components/ui/Loading"; +import { useMCPRequest } from "./useMCPRequest"; + +export function MCPLiveRead({ org, source, contextKey, disabled }: { + org: string; source: MCPSource; contextKey: string; disabled: boolean; +}) { + const [id, setId] = useState(""); + const [epoch, setEpoch] = useState(0); + const [answer, setAnswer] = useState<{ key: string; value: LiveRead } | null>(null); + const authority = JSON.stringify([org, source, contextKey, disabled]); + useEffect(() => { setAnswer(null); }, [authority]); + const scope = JSON.stringify([org, source, contextKey, id, epoch, disabled]); + const request = useMCPRequest(scope); + const result = answer?.key === scope ? answer.value : null; + const read = async () => { + if (disabled || request.busy || !source.resource_ids.includes(id) || source.mode !== "live" || source.state !== "registered") return; + setAnswer(null); + const value = await request.run(async (signal) => { + const out = await mcpRead({ org, namespace: source.namespace, name: source.name, resource_id: id }, signal); + if (out.source_id !== source.source_id || out.resource_id !== id) throw new Error("Read identity mismatch."); + return out; + }); + if (value) setAnswer({ key: scope, value }); + }; + return
+

Explicit owner live read of one saved ID. This reads the bounded text without importing it. Current server authorization is required; remote identity and upstream ACLs remain unverified. Closing or clearing this view discards the displayed body.

+ { setAnswer(null); setId(value); }} disabled={disabled} options={source.resource_ids.map((value) => ({ value, label: value }))} /> + void read()}>Read selected live resource + + {request.busy && } + {!!request.error && } + {result &&
+

{result.title}

Stable citation: {result.uri}

MIME: {result.mime_type}. Resource identity verified: {result.resource_identity_verified ? "yes" : "no"}. Remote identity verified: no. Upstream ACL verified: no.

+
{result.text}
+
    {result.limitations.map((line, index) =>
  • {line}
  • )}
+
} +
; +} diff --git a/frontend/src/flows/MCPResourceBrowser.test.tsx b/frontend/src/flows/MCPResourceBrowser.test.tsx new file mode 100644 index 0000000000..4ff8b2b5a1 --- /dev/null +++ b/frontend/src/flows/MCPResourceBrowser.test.tsx @@ -0,0 +1,68 @@ +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { type MCPBrowse, mcpBrowse } from "../api/mcpSources"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; +import { MCPResourceBrowser } from "./MCPResourceBrowser"; + +vi.mock("../api/mcpSources", () => ({ mcpBrowse: vi.fn() })); +const window: MCPBrowse = { + slot: "slot", generation: "generation", mode: "resources", supported: true, + resources: true, mapped_read: false, mapped_search: false, capabilities_checked: true, + items: [{ id: " opaque://A?x=%2F ", title: "Private title", uri: "mcp-resource-hint:opaque" }], + complete: false, truncated: true, reason: "first_window_only", limitations: ["no_acl_or_permission_sync_proof"], + manual_resource_ids_supported: true, remote_identity_verified: false, +}; +const props = () => ({ org: "acme", slot: "slot", generation: "generation", contextKey: "authority-1", disabled: false, selected: [], onSelect: vi.fn() }); +describe("bounded MCP metadata selection", () => { + beforeEach(() => { vi.clearAllMocks(); vi.mocked(mcpBrowse).mockResolvedValue(window); }); + afterEach(cleanup); + it("requires a click, displays truncation and selects an exact ID without importing", async () => { + const p = props(); render(); + expect(mcpBrowse).not.toHaveBeenCalled(); + await userEvent.click(screen.getByRole("button", { name: "Read first metadata window" })); + expect(mcpBrowse).toHaveBeenCalledWith({ org: "acme", slot: "slot", mode: "resources", query: "", limit: 100 }, expect.any(AbortSignal)); + expect(await screen.findByText(/Truncated: yes/)).toHaveTextContent("first_window_only"); + expect(screen.getByText(/Manual IDs remain possible/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: /next|more|import/i })).toBeNull(); + expect(screen.queryByRole("link")).toBeNull(); + await userEvent.click(screen.getByRole("button", { name: /Select ID/ })); + expect(p.onSelect).toHaveBeenCalledWith(window.items[0]?.id); + expect(mcpBrowse).toHaveBeenCalledTimes(1); + }); + it("shows unsupported mapped search as unchecked and retains manual entry guidance", async () => { + vi.mocked(mcpBrowse).mockResolvedValue({ ...window, mode: "search", supported: false, resources: null, capabilities_checked: false, items: [], reason: "unsupported_mode" }); + render(); + fireEvent.click(screen.getByRole("radio", { name: "Mapped search" })); + expect(screen.getByRole("button", { name: "Read first metadata window" })).toBeDisabled(); + fireEvent.change(screen.getByLabelText("Mapped search query"), { target: { value: "private query" } }); + await userEvent.click(screen.getByRole("button", { name: "Read first metadata window" })); + expect(await screen.findByText(/Resources: unchecked/)).toHaveTextContent("Capabilities checked: no"); + expect(screen.getByText(/Reason: unsupported_mode/)).toBeInTheDocument(); + expect(mcpBrowse).toHaveBeenCalledWith(expect.objectContaining({ mode: "search", query: "private query" }), expect.any(AbortSignal)); + }); + it("drops an abort-ignoring metadata answer after authority changes", async () => { + let release!: (value: MCPBrowse) => void; + const held = new Promise((resolve) => { release = resolve; }); + vi.mocked(mcpBrowse).mockReturnValueOnce(held); + const p = props(); const view = render(); + await userEvent.click(screen.getByRole("button", { name: "Read first metadata window" })); + await waitFor(() => expect(mcpBrowse).toHaveBeenCalledTimes(1)); + const signal = vi.mocked(mcpBrowse).mock.calls[0]?.[1]; + view.rerender(); + expect(signal?.aborted).toBe(true); + await act(async () => { release(window); await held; }); + expect(screen.queryByText("Private title")).toBeNull(); + expect(p.onSelect).not.toHaveBeenCalled(); + }); + it("fails on generation drift or protected transport refusal without retry", async () => { + vi.mocked(mcpBrowse).mockResolvedValueOnce({ ...window, generation: "other" }); + render(); + await userEvent.click(screen.getByRole("button", { name: "Read first metadata window" })); + await screen.findByRole("alert"); + expect(screen.queryByText("Private title")).toBeNull(); + vi.mocked(mcpBrowse).mockRejectedValueOnce(new Error("MCP_PROTECTED_SESSION_REQUIRED")); + await userEvent.click(screen.getByRole("button", { name: "Read first metadata window" })); + expect(await screen.findByRole("alert")).toHaveTextContent("Protected transport refusals remain failures"); + expect(mcpBrowse).toHaveBeenCalledTimes(2); + }); +}); diff --git a/frontend/src/flows/MCPResourceBrowser.tsx b/frontend/src/flows/MCPResourceBrowser.tsx new file mode 100644 index 0000000000..feb44eda3c --- /dev/null +++ b/frontend/src/flows/MCPResourceBrowser.tsx @@ -0,0 +1,55 @@ +import { Button } from "@clickhouse/click-ui/Button"; +import { TextField } from "@clickhouse/click-ui/TextField"; +import { useEffect, useState } from "react"; +import { type MCPBrowse, mcpBrowse } from "../api/mcpSources"; +import { Alert } from "../components/ui/Alert"; +import { BusyButton } from "../components/ui/BusyButton"; +import { ChoiceGroup } from "../components/ui/ChoiceGroup"; +import { Loading } from "../components/ui/Loading"; +import { useMCPRequest } from "./useMCPRequest"; + +export function MCPResourceBrowser({ org, slot, generation, contextKey, disabled, selected, onSelect }: { + org: string; slot: string; generation: string; contextKey: string; disabled: boolean; + selected: string[]; onSelect: (id: string) => void; +}) { + const [mode, setMode] = useState<"resources" | "search">("resources"); + const [query, setQuery] = useState(""); + const [window, setWindow] = useState<{ key: string; value: MCPBrowse } | null>(null); + const authority = JSON.stringify([org, slot, generation, contextKey]); + useEffect(() => { setWindow(null); setQuery(""); }, [authority]); + const scope = JSON.stringify([org, slot, generation, contextKey, mode, query]); + const request = useMCPRequest(scope); + const result = window?.key === scope ? window.value : null; + const valid = mode === "resources" || (query.trim().length > 0 && query.length <= 1000 && new TextEncoder().encode(query).length <= 4096); + const browse = async () => { + if (disabled || request.busy || !valid) return; + setWindow(null); + const answer = await request.run(async (signal) => { + const value = await mcpBrowse({ org, slot, mode, query, limit: 100 }, signal); + if (value.slot !== slot || value.generation !== generation || value.mode !== mode) + throw new Error("Connection changed. Discover capabilities again."); + return value; + }); + if (answer) setWindow({ key: scope, value: answer }); + }; + return
+

Optional metadata window. Choose standard resource listing or an operator-mapped search. Capabilities come from the approved profile and server discovery. Enter manual resource IDs below at any time.

+ + {mode === "search" && } + void browse()}>Read first metadata window + {request.busy && } + {!!request.error && } + {result &&
+

Supported: {result.supported ? "yes" : "no"}. Capabilities checked: {result.capabilities_checked ? "yes" : "no"}. Resources: {result.resources === null ? "unchecked" : result.resources ? "yes" : "no"}. Approved read mapping: {result.mapped_read ? "yes" : "no"}. Approved search mapping: {result.mapped_search ? "yes" : "no"}.

+

First window only. Declared page fits this window: {result.complete ? "yes" : "no"}. Truncated: {result.truncated ? "yes" : "no"}. Reason: {result.reason ?? "none returned"}. This does not prove a complete tree, corpus, deletion or ACL access. No continuation is available. Manual IDs remain possible.

+
    {result.items.map((item) =>
  • +

    {item.title}

    {item.id}

    Display hint only: {item.uri}

    + +
  • )}
+
    {result.limitations.map((line, index) =>
  • {line}
  • )}
+ +
} +
; +} diff --git a/frontend/src/flows/MCPSourceSetup.protection.test.tsx b/frontend/src/flows/MCPSourceSetup.protection.test.tsx new file mode 100644 index 0000000000..1252add5e7 --- /dev/null +++ b/frontend/src/flows/MCPSourceSetup.protection.test.tsx @@ -0,0 +1,88 @@ +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { AutomaticCaptureSuppressed } from "../../../sdk/typescript/src/session-protection.js"; +import { post } from "../api"; +import { cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; +import { mcpConnection, mcpDiscovery, mcpPreviewValue, mcpProfile, mcpResult, mcpSource } from "../test/mcpSources"; +import { MCPSourceSetup } from "./MCPSourceSetup"; +import { AddMemoryDialog } from "./AddMemoryDialog"; + +// Only durable storage is replaced: controls, API methods and response observation are real. +vi.mock("../lib/dashboardSessionProtection", async () => { + const { SessionProtection } = await import("../../../sdk/typescript/src/session-protection.js"); + const family = new SessionProtection({ read: async () => "protected", mark: async () => {} }); + return { dashboardSessionProtection: async () => family }; +}); + +describe("source setup through the protected dashboard sender", () => { + const sent: { op: string; body: Record; declaration: string | null }[] = []; + beforeEach(() => { + sent.length = 0; + vi.stubGlobal("fetch", vi.fn(async (input: string, init: RequestInit) => { + const op = new URL(input).pathname.slice(4); + const body = JSON.parse(String(init.body)); + sent.push({ op, body, declaration: new Headers(init.headers).get("x-loom-session-protection") }); + const responses: Record = { + "knowledge.source.mcp_profiles": { profiles: [mcpProfile], next_cursor: null, self_service_enabled: true }, + "knowledge.connection.mcp_list": { connections: [], next_cursor: null }, + "knowledge.connection.mcp_connect": { connection: mcpConnection }, + "knowledge.connection.mcp_inspect": { found: true, connection: mcpConnection, reconciliation: "present" }, + "knowledge.connection.mcp_discover": mcpDiscovery, + "knowledge.source.mcp_preview": mcpPreviewValue, + "knowledge.source.mcp_add": mcpResult, + "collection.list": { collections: [{ namespace: "col-team", title: "Team", parent: "", personal: false, role: "admin" }], next_cursor: null }, + "knowledge.connection.mcp_browse": { slot: mcpConnection.slot, generation: mcpConnection.generation, + mode: "resources", supported: true, items: [], complete: false, truncated: false, + limitations: [], manual_resource_ids_supported: true, remote_identity_verified: false }, + "memory.set": { version: 1, pinned: false }, + "namespace.taxonomy": { tags: [], entities: [], communities: [] }, + }; + if (!(op in responses)) throw new Error(`Unexpected dispatch: ${op}`); + return new Response(JSON.stringify({ ...(responses[op] as object), mirrored: true }), { + headers: { "Content-Type": "application/json" }, + }); + })); + }); + afterEach(() => { cleanup(); vi.unstubAllGlobals(); }); + + it("connects, discovers, reviews a private selection in a team collection and submits with human intent", async () => { + const onSaved = vi.fn(); + render( {}} />); + fireEvent.click(await screen.findByRole("radio", { name: "Approved remote server" })); + await userEvent.type(screen.getByLabelText("Preissued upstream bearer"), "selected-secret"); + await userEvent.click(screen.getByRole("button", { name: "Connect a new account" })); + await userEvent.click(await screen.findByRole("button", { name: "Discover capabilities" })); + fireEvent.change(await screen.findByLabelText("Explicit resource IDs (one per line)"), { target: { value: mcpSource.resource_ids[0] } }); + fireEvent.click(screen.getByRole("radio", { name: "Selected snapshot" })); + fireEvent.click(await screen.findByRole("radio", { name: "Team (col-team)" })); + await userEvent.click(screen.getByRole("button", { name: "Review effective access" })); + await screen.findByRole("region", { name: "Effective access preview" }); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + await screen.findByText(/Server registration state: registered/); + expect(onSaved).toHaveBeenCalledWith(mcpSource); + expect(sent.filter((r) => r.op === "knowledge.source.mcp_add")).toEqual([{ + op: "knowledge.source.mcp_add", declaration: "v1", + body: expect.objectContaining({ namespace: "col-team", reader_policy: "owner_only", resource_ids: mcpSource.resource_ids, confirm_copy_authority: false }), + }]); + expect(sent.every((r) => r.declaration === "v1")).toBe(true); + expect(sent.filter((r) => r.op !== "knowledge.connection.mcp_connect").some((r) => JSON.stringify(r.body).includes("selected-secret"))).toBe(false); + const count = sent.length; + await expect(post("/v1/memory.set", { namespace: "other", session_id: "new", value: "private" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(sent).toHaveLength(count); + }); + + it("dispatches an ordinary human memory submit and refuses the next automatic write in the same family", async () => { + const onAdded = vi.fn(); + render( {}} />); + await userEvent.type(screen.getByLabelText("Key (lower_snake_case)"), "manual_value"); + await userEvent.type(screen.getByLabelText("Value"), "human supplied value"); + await userEvent.click(screen.getByRole("button", { name: "Add memory" })); + await waitFor(() => expect(onAdded).toHaveBeenCalledOnce()); + expect(sent.filter((r) => r.op === "memory.set")).toEqual([{ + op: "memory.set", declaration: "v1", body: expect.objectContaining({ memory_key: "manual_value", value: "human supplied value" }), + }]); + const count = sent.length; + await expect(post("/v1/memory.set", { namespace: "elsewhere", value: "private" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(sent).toHaveLength(count); + }); +}); diff --git a/frontend/src/flows/MCPSourceSetup.test.tsx b/frontend/src/flows/MCPSourceSetup.test.tsx new file mode 100644 index 0000000000..c1b8fb563d --- /dev/null +++ b/frontend/src/flows/MCPSourceSetup.test.tsx @@ -0,0 +1,254 @@ +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; +import { axeViolations } from "../test/axe"; +import { mcpConnection, mcpDiscovery, mcpPreviewValue, mcpProfile, mcpResult, mcpSource } from "../test/mcpSources"; +import type { MCPPreview } from "../api/mcpSources"; + +vi.mock("../api/mcpSources", async (original) => ({ + ...(await original()), + mcpProfiles: vi.fn(), mcpConnections: vi.fn(), mcpConnect: vi.fn(), mcpInspectConnection: vi.fn(), + mcpDiscover: vi.fn(), mcpDisconnect: vi.fn(), mcpPreview: vi.fn(), mcpAdd: vi.fn(), mcpInspect: vi.fn(), mcpUpdate: vi.fn(), +})); +vi.mock("../api", async (original) => ({ + ...(await original()), listCollections: vi.fn(), createCollection: vi.fn(), +})); +import * as api from "../api/mcpSources"; +import { createCollection, listCollections } from "../api"; +import { MCPSourceSetup, resourceIDs } from "./MCPSourceSetup"; + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((done) => { resolve = done; }); + return { promise, resolve }; +} +const props = () => ({ org: "acme", callerKey: "owner:auth-1", collectionVersion: "grants-1", onSaved: vi.fn(), onClose: vi.fn() }); +async function chooseConnection() { + fireEvent.click(await screen.findByRole("radio", { name: "Approved remote server" })); + fireEvent.click(await screen.findByRole("radio", { name: "My connection (configured)" })); + await userEvent.click(screen.getByRole("button", { name: "Discover capabilities" })); + await screen.findByLabelText("Explicit resource IDs (one per line)"); +} +async function selection() { + await chooseConnection(); + fireEvent.change(screen.getByLabelText("Explicit resource IDs (one per line)"), { target: { value: mcpSource.resource_ids[0] } }); + fireEvent.click(screen.getByRole("radio", { name: "Selected snapshot" })); + fireEvent.click(await screen.findByRole("radio", { name: "Team (col-team)" })); +} +async function review() { + await userEvent.click(screen.getByRole("button", { name: "Review effective access" })); + await screen.findByRole("region", { name: "Effective access preview" }); +} + +describe("generic MCP source setup", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(api.mcpProfiles).mockResolvedValue({ profiles: [mcpProfile], next_cursor: null, self_service_enabled: true }); + vi.mocked(api.mcpConnections).mockResolvedValue({ connections: [mcpConnection], next_cursor: null }); + vi.mocked(api.mcpInspectConnection).mockResolvedValue({ found: true, slot: mcpConnection.slot, connection: mcpConnection, reconciliation: "present" }); + vi.mocked(api.mcpDiscover).mockResolvedValue(mcpDiscovery); + vi.mocked(api.mcpConnect).mockResolvedValue({ connection: mcpConnection }); + vi.mocked(api.mcpPreview).mockResolvedValue(mcpPreviewValue); + vi.mocked(api.mcpAdd).mockResolvedValue(mcpResult); + vi.mocked(api.mcpInspect).mockResolvedValue({ found: true, source: mcpSource }); + vi.mocked(api.mcpUpdate).mockResolvedValue(mcpResult); + vi.mocked(listCollections).mockResolvedValue({ collections: [{ namespace: "col-team", title: "Team", parent: "", personal: false, role: "admin" }], next_cursor: null }); + }); + afterEach(() => { cleanup(); vi.restoreAllMocks(); }); + + it("selects an existing owner connection, discovers, chooses opaque content/mode/destination, previews and saves", async () => { + const p = props(); render(); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + await selection(); + expect(screen.getByText(/complete enumeration are not supported/)).toBeInTheDocument(); + await review(); + expect(screen.getByText(/Server access rule: owner_only/)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Register source" })).toBeEnabled(); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + expect(api.mcpAdd).toHaveBeenCalledTimes(1); + expect(api.mcpAdd).toHaveBeenCalledWith(expect.objectContaining({ + org: "acme", namespace: "col-team", slot: mcpConnection.slot, resource_ids: mcpSource.resource_ids, + mode: "snapshot", reader_policy: "owner_only", confirm_copy_authority: false, request_id: expect.any(String), + }), expect.any(AbortSignal), "explicit"); + expect(p.onSaved).toHaveBeenCalledWith(mcpSource); + expect(await screen.findByText(/Server registration state: registered/)).toHaveTextContent("does not attest upstream access"); + }); + it("connects a new account and requires discovery before the complete source flow", async () => { + vi.mocked(api.mcpConnections).mockResolvedValue({ connections: [], next_cursor: null }); + render(); + fireEvent.click(await screen.findByRole("radio", { name: "Approved remote server" })); + await userEvent.type(screen.getByLabelText("Preissued upstream bearer"), "input-only-secret"); + await userEvent.click(screen.getByRole("button", { name: "Connect a new account" })); + expect(screen.queryByLabelText("Explicit resource IDs (one per line)")).toBeNull(); + await userEvent.click(await screen.findByRole("button", { name: "Discover capabilities" })); + fireEvent.change(await screen.findByLabelText("Explicit resource IDs (one per line)"), { target: { value: mcpSource.resource_ids[0] } }); + fireEvent.click(screen.getByRole("radio", { name: "Selected snapshot" })); + fireEvent.click(await screen.findByRole("radio", { name: "Team (col-team)" })); await review(); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + expect(api.mcpConnect).toHaveBeenCalledTimes(1); expect(api.mcpAdd).toHaveBeenCalledTimes(1); + expect(JSON.stringify(vi.mocked(api.mcpAdd).mock.calls)).not.toContain("input-only-secret"); + }); + it("requires explicit publication consent and rechecks it after content or grant changes", async () => { + vi.mocked(api.mcpPreview).mockResolvedValue({ ...mcpPreviewValue, rule: { ...mcpPreviewValue.rule, access: "collection_wide", publication_confirmation_required: true, collection_readers_receive_copy: true } }); + const p = props(); const view = render(); + await selection(); fireEvent.click(screen.getByRole("radio", { name: "Copy to collection readers" })); + fireEvent.click(await screen.findByRole("radio", { name: "Team (col-team)" })); await review(); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + fireEvent.click(screen.getByRole("checkbox", { name: /I have authority to publish/ })); + expect(screen.getByRole("button", { name: "Register source" })).toBeEnabled(); + view.rerender(); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + expect(screen.queryByRole("region", { name: "Effective access preview" })).toBeNull(); + }); + it("sends publication authority only after intentional collection copy consent", async () => { + vi.mocked(api.mcpPreview).mockResolvedValue({ ...mcpPreviewValue, rule: { ...mcpPreviewValue.rule, access: "collection_wide", publication_confirmation_required: true } }); + render(); await selection(); + fireEvent.click(screen.getByRole("radio", { name: "Copy to collection readers" })); + fireEvent.click(await screen.findByRole("radio", { name: "Team (col-team)" })); await review(); + fireEvent.click(screen.getByRole("checkbox", { name: /I have authority to publish/ })); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + expect(api.mcpAdd).toHaveBeenCalledWith(expect.objectContaining({ reader_policy: "collection_copy", confirm_copy_authority: true }), expect.any(AbortSignal), "explicit"); + }); + it("drops an abort-ignoring late preview after selection changes", async () => { + const held = deferred(); vi.mocked(api.mcpPreview).mockReturnValueOnce(held.promise); + render(); await selection(); + await userEvent.click(screen.getByRole("button", { name: "Review effective access" })); + // A collection/grant invalidation remains possible while a request is in flight. + fireEvent(window, new Event("focus")); + await act(async () => { held.resolve(mcpPreviewValue); await held.promise; }); + expect(screen.queryByRole("region", { name: "Effective access preview" })).toBeNull(); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + expect(api.mcpAdd).not.toHaveBeenCalled(); + }); + it("aborts a pending preview when grants change and rejects its late answer", async () => { + const held = deferred(); vi.mocked(api.mcpPreview).mockReturnValueOnce(held.promise); + const p = props(); const view = render(); await selection(); + await userEvent.click(screen.getByRole("button", { name: "Review effective access" })); + await waitFor(() => expect(api.mcpPreview).toHaveBeenCalledTimes(1)); + const signal = vi.mocked(api.mcpPreview).mock.calls[0]?.[1]; + view.rerender(); + expect(signal?.aborted).toBe(true); + await act(async () => { held.resolve(mcpPreviewValue); await held.promise; }); + expect(screen.queryByRole("region", { name: "Effective access preview" })).toBeNull(); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + }); + it("drops caller-owned state and late discovery when the authenticated caller changes", async () => { + const held = deferred(); vi.mocked(api.mcpDiscover).mockReturnValueOnce(held.promise); + const p = props(); const view = render(); + fireEvent.click(await screen.findByRole("radio", { name: "Approved remote server" })); + fireEvent.click(screen.getByRole("radio", { name: "My connection (configured)" })); + await userEvent.type(screen.getByLabelText("Preissued upstream bearer"), "old-caller-secret"); + await userEvent.click(screen.getByRole("button", { name: "Discover capabilities" })); + await waitFor(() => expect(api.mcpDiscover).toHaveBeenCalledTimes(1)); + view.rerender(); + await act(async () => { held.resolve(mcpDiscovery); await held.promise; }); + expect(screen.queryByLabelText("Explicit resource IDs (one per line)")).toBeNull(); + expect(screen.queryByDisplayValue("old-caller-secret")).toBeNull(); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + }); + it("invalidates preview synchronously on mode/label changes and never accepts unavailable access", async () => { + render(); await selection(); await review(); + fireEvent.change(screen.getByLabelText("Source label (optional)"), { target: { value: "new label" } }); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + vi.mocked(api.mcpPreview).mockResolvedValue({ ...mcpPreviewValue, rule: { ...mcpPreviewValue.rule, access: "unavailable", reason: "operator_refused" } }); + await review(); expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + fireEvent.click(screen.getByRole("radio", { name: "Live lookup" })); + expect(screen.queryByRole("region", { name: "Effective access preview" })).toBeNull(); + }); + it("keeps the draft, nonce and confirmed collection after uncertain add and never resends", async () => { + vi.mocked(api.mcpAdd).mockRejectedValue(new Error("unreadable result")); + vi.mocked(createCollection).mockResolvedValue({ namespace: "col-new", parent: "", created: true }); + vi.mocked(listCollections).mockResolvedValue({ collections: [ + { namespace: "col-team", title: "Team", parent: "", personal: false, role: "admin" }, + { namespace: "col-new", title: "New library", parent: "", personal: false, role: "admin" }, + ], next_cursor: null }); + render(); await selection(); + await userEvent.click(screen.getByRole("button", { name: "New collection" })); + await userEvent.type(screen.getByLabelText("Title"), "New library"); + await userEvent.click(screen.getByRole("button", { name: "Create", exact: true })); + await screen.findByText(/Confirmed collections retained: col-new/); + fireEvent.click(await screen.findByRole("radio", { name: "Team (col-team)" })); await review(); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + await screen.findByText(/The mutation result is uncertain/); + const nonce = vi.mocked(api.mcpAdd).mock.calls[0]?.[0].request_id; + expect(screen.getByText(/Retained request ID:/)).toHaveTextContent(nonce ?? "missing"); + expect(screen.getByLabelText("Explicit resource IDs (one per line)")).toHaveValue(mcpSource.resource_ids[0]); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + fireEvent(window, new Event("focus")); + expect(screen.getByText(/Retained request ID:/)).toHaveTextContent(nonce ?? "missing"); + await userEvent.click(screen.getByRole("button", { name: "Inspect source result" })); + expect(api.mcpInspect).toHaveBeenCalledWith({ org: "acme", namespace: "col-team", slot: mcpConnection.slot, request_id: nonce }, expect.any(AbortSignal)); + expect(nonce).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i); + expect(screen.queryByLabelText("Registration name returned by the server")).toBeNull(); + expect(api.mcpAdd).toHaveBeenCalledTimes(1); + expect(screen.getByText(/Confirmed collections retained: col-new/)).toBeInTheDocument(); + }); + it("edits using the inspected scope revision without an audience or connection mutation", async () => { + render(); + fireEvent.change(screen.getByLabelText("Explicit resource IDs (one per line)"), { target: { value: "replacement" } }); + await review(); await userEvent.click(screen.getByRole("button", { name: "Save source changes" })); + expect(api.mcpUpdate).toHaveBeenCalledWith({ org: "acme", namespace: "col-team", name: mcpSource.name, + if_scope_revision: 4, resource_ids: ["replacement"], mode: "snapshot", label: "Private documents", confirm_copy_authority: false }, expect.any(AbortSignal), "explicit"); + expect(screen.queryByRole("radiogroup", { name: "Publication audience" })).toBeNull(); + }); + it("accepts only the server-reconciled original binding after an unreadable add", async () => { + vi.mocked(api.mcpAdd).mockRejectedValue(new Error("unreadable result")); + const p = props(); render(); await selection(); await review(); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + await userEvent.click(await screen.findByRole("button", { name: "Inspect source result" })); + const submitted = vi.mocked(api.mcpAdd).mock.calls[0]?.[0]; + expect(api.mcpInspect).toHaveBeenCalledWith({ org: "acme", namespace: "col-team", slot: submitted?.slot, request_id: submitted?.request_id }, expect.any(AbortSignal)); + expect(await screen.findByText(/server reconciled the original request/)).toBeInTheDocument(); + expect(p.onSaved).not.toHaveBeenCalled(); + await userEvent.click(screen.getByRole("button", { name: "Accept inspected server state" })); + expect(p.onSaved).toHaveBeenCalledWith(mcpSource); + expect(api.mcpAdd).toHaveBeenCalledTimes(1); + }); + it.each([ + { found: false, source: null }, + { found: true, source: { ...mcpSource, namespace: "other-destination" } }, + { found: true, source: { ...mcpSource, slot: "other-slot" } }, + ])("keeps absent or mismatched reconciliation blocked without a guessed name or retry: %j", async (answer) => { + vi.mocked(api.mcpAdd).mockRejectedValue(new Error("unreadable result")); + vi.mocked(api.mcpInspect).mockResolvedValue(answer); + render(); await selection(); await review(); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + await userEvent.click(await screen.findByRole("button", { name: "Inspect source result" })); + await screen.findByText(/No matching owned registration/); + expect(screen.queryByRole("button", { name: "Accept inspected server state" })).toBeNull(); + expect(screen.getByRole("button", { name: "Register source" })).toBeDisabled(); + expect(api.mcpAdd).toHaveBeenCalledTimes(1); + }); + it("drops late reconciliation after caller changes while retaining the original request in the sent read", async () => { + vi.mocked(api.mcpAdd).mockRejectedValue(new Error("unreadable result")); + const held = deferred>>(); + vi.mocked(api.mcpInspect).mockReturnValueOnce(held.promise); + const p = props(); const view = render(); await selection(); await review(); + await userEvent.click(screen.getByRole("button", { name: "Register source" })); + await userEvent.click(await screen.findByRole("button", { name: "Inspect source result" })); + await waitFor(() => expect(api.mcpInspect).toHaveBeenCalledTimes(1)); + const signal = vi.mocked(api.mcpInspect).mock.calls[0]?.[1]; + view.rerender(); + expect(signal?.aborted).toBe(true); + await act(async () => { held.resolve({ found: true, source: mcpSource }); await held.promise; }); + expect(screen.queryByRole("button", { name: "Accept inspected server state" })).toBeNull(); + expect(screen.queryByText(/Retained request ID:/)).toBeNull(); + expect(p.onSaved).not.toHaveBeenCalled(); + expect(api.mcpAdd).toHaveBeenCalledTimes(1); + }); + it("refuses an edit if the server revision changed", async () => { + vi.mocked(api.mcpInspect).mockResolvedValue({ found: true, source: { ...mcpSource, scope_revision: 5 } }); + render(); await review(); + await userEvent.click(screen.getByRole("button", { name: "Save source changes" })); + await screen.findByText(/The mutation result is uncertain/); + expect(api.mcpUpdate).not.toHaveBeenCalled(); + }); + it("has named accessible controls and no axe violations", async () => { + render(); await selection(); await review(); + expect(await axeViolations(screen.getByRole("dialog"))).toEqual([]); + }); + it("splits only on newline and preserves opaque identity bytes", () => { + expect(resourceIDs(" opaque://A?x=%2F \nhttps://source.example/a//b?x=1#part")).toEqual([" opaque://A?x=%2F ", "https://source.example/a//b?x=1#part"]); + expect(resourceIDs("")).toEqual([]); + }); +}); diff --git a/frontend/src/flows/MCPSourceSetup.tsx b/frontend/src/flows/MCPSourceSetup.tsx new file mode 100644 index 0000000000..db77fdc034 --- /dev/null +++ b/frontend/src/flows/MCPSourceSetup.tsx @@ -0,0 +1,187 @@ +import { Button } from "@clickhouse/click-ui/Button"; +import { Checkbox } from "@clickhouse/click-ui/Checkbox"; +import { TextAreaField } from "@clickhouse/click-ui/TextAreaField"; +import { TextField } from "@clickhouse/click-ui/TextField"; +import { useRef, useState } from "react"; +import type { CollectionEntry } from "../api"; +import { + type MCPAudience, type MCPMode, type MCPPreview, type MCPSelection, type MCPSource, + mcpAdd, mcpInspect, mcpInspectConnection, mcpPreview, mcpUpdate, +} from "../api/mcpSources"; +import { Alert } from "../components/ui/Alert"; +import { ChoiceGroup } from "../components/ui/ChoiceGroup"; +import { Loading } from "../components/ui/Loading"; +import { humanizeError } from "../lib/errorWords"; +import type { DashboardRequestIntent } from "../lib/dashboardTransport"; +import { MCPConnectionStep, type MCPChosenConnection } from "./MCPConnectionStep"; +import { mcpDestinationCopy, mcpSourceCopy as copy } from "./mcpSourceCopy"; +import { SourceDestinationStep } from "./SourceDestinationStep"; +import { DialogFrame } from "./TaskDialogFrame"; +import { useMCPRequest } from "./useMCPRequest"; +import { MCPResourceBrowser } from "./MCPResourceBrowser"; + +export interface MCPSourceSetupProps { + org: string; + callerKey: string; + collectionVersion: string; + source?: MCPSource; + onSaved: (source: MCPSource) => void; + onClose: () => void; +} + +/** A source nonce and confirmed collection identity remain in memory across uncertain saves. */ +export function MCPSourceSetup(props: MCPSourceSetupProps) { + return ; +} + +function SourceDraft({ org, callerKey, collectionVersion, source, onSaved, onClose }: MCPSourceSetupProps) { + const [chosen, setChosen] = useState(null); + const [connectionUncertain, setConnectionUncertain] = useState(false); + const [resources, setResources] = useState(source?.resource_ids.join("\n") ?? ""); + const [mode, setMode] = useState(source?.mode ?? "live"); + const [audience, setAudience] = useState(source?.reader_policy ?? "owner_only"); + const [label, setLabel] = useState(source?.label ?? ""); + const [destination, setDestination] = useState(null); + const [created, setCreated] = useState([]); + const [preview, setPreview] = useState<{ key: string; value: MCPPreview } | null>(null); + const [consent, setConsent] = useState(false); + const [invalidation, setInvalidation] = useState(0); + const [requestId] = useState(() => crypto.randomUUID()); + const [uncertain, setUncertain] = useState(false); + const [binding, setBinding] = useState<{ org: string; callerKey: string; namespace: string; slot: string; request_id: string } | null>(null); + const [inspection, setInspected] = useState<{ key: string; source: MCPSource } | null>(null); + const [saved, setSaved] = useState(null); + const [notice, setNotice] = useState(""); + const ids = resourceIDs(resources); + const namespace = source?.namespace ?? destination?.namespace ?? ""; + const slot = source?.slot ?? chosen?.connection.slot ?? ""; + const contentContext = JSON.stringify([slot, chosen?.connection.generation, resources, mode, audience]); + const key = JSON.stringify([org, callerKey, collectionVersion, contentContext, namespace, label, invalidation]); + const currentKey = useRef(key); + currentKey.current = key; + const request = useMCPRequest(key); + const invalidate = () => { setPreview(null); setConsent(false); setInvalidation((v) => v + 1); }; + const result = preview?.key === key ? preview.value : null; + const inspected = inspection?.key === key ? inspection.source : null; + const selection: MCPSelection = { org, namespace, slot, resource_ids: ids, mode, reader_policy: audience }; + const valid = !!slot && !!namespace && ids.length > 0 && ids.length <= 1000 && new Set(ids).size === ids.length && + ids.every((id) => !/[\r\u0000]/.test(id)) && label.length <= 256; + const canSave = valid && !!result && result.rule.access === (audience === "collection_copy" ? "collection_wide" : "owner_only") && result.connection_state === "configured" && + (!result.rule.publication_confirmation_required || consent) && (audience !== "collection_copy" || consent); + const locked = request.busy || uncertain || saved !== null; + + const check = async () => { + if (!valid || locked) return; + setPreview(null); setConsent(false); + const stamp = key; + const answer = await request.run(async (signal) => { + const connection = await mcpInspectConnection(org, { slot }, signal); + if (!connection.found || !connection.connection || connection.connection.slot !== slot || connection.connection.state !== "configured" || + (chosen && connection.connection.generation !== chosen.connection.generation)) + throw new Error("Connection changed. Select and discover it again."); + const value = await mcpPreview(selection, signal); + if (value.namespace !== namespace || value.mode !== mode || value.selected_count !== ids.length) + throw new Error("The preview does not match this draft. Review access again."); + return value; + }); + if (answer && currentKey.current === stamp) setPreview({ key: stamp, value: answer }); + }; + const save = async (intent: DashboardRequestIntent) => { + if (!canSave || locked) return; + // Mark before sending; a canceled or unreadable answer must never invite another mutation. + setUncertain(true); setInspected(null); + setBinding({ org, callerKey, namespace, slot, request_id: requestId }); + const answer = await request.run(async (signal) => { + if (source) { + const latest = await mcpInspect({ org, namespace, name: source.name }, signal); + if (!latest.found || !latest.source || latest.source.name !== source.name || latest.source.namespace !== namespace || + latest.source.slot !== source.slot || latest.source.reader_policy !== source.reader_policy || latest.source.scope_revision !== source.scope_revision) + throw new Error("The source revision changed. Inspect its current state before editing."); + if (source.scope_revision === null) throw new Error("This source has no editable scope revision."); + return mcpUpdate({ org, namespace, name: source.name, if_scope_revision: source.scope_revision, + resource_ids: ids, mode, label: label || null, confirm_copy_authority: consent }, signal, intent); + } + return mcpAdd({ ...selection, request_id: requestId, label: label || null, confirm_copy_authority: consent }, signal, intent); + }); + if (answer) { setUncertain(false); setSaved(answer.source); onSaved(answer.source); } + }; + const reconcile = async () => { + if (!binding || binding.org !== org || binding.callerKey !== callerKey || request.busy) return; + setInspected(null); + const answer = await request.run((signal) => mcpInspect(source ? + { org: binding.org, namespace: binding.namespace, name: source.name } : + { org: binding.org, namespace: binding.namespace, slot: binding.slot, request_id: binding.request_id }, signal)); + if (!answer) return; + const matches = answer.found && answer.source && answer.source.namespace === binding.namespace && answer.source.slot === binding.slot && + (!source || answer.source.name === source.name); + setInspected(matches && answer.source ? { key, source: answer.source } : null); + setNotice(matches ? (source ? "Current source state returned. This does not attest completion of the original update." : "The server reconciled the original request and destination. Review its current registration before accepting it.") : "No matching owned registration was returned. The original result remains uncertain; do not resubmit."); + }; + return ( + { if (!open && !request.busy && !uncertain && !connectionUncertain) onClose(); }} width={760} + title={source ? "Edit MCP source selection" : "Set up an MCP source"} + description="Choose an account, a fixed selection and a collection, then review server access rules." + footer={<> + + {saved ? : + } + }> +

{copy.privacy}

+ {!source && { invalidate(); setChosen(value); }} />} + {(source || chosen) && <> + {!source && chosen && { invalidate(); setResources((value) => value ? `${value}\n${id}` : id); }} />} + {source &&

Registration: {source.name}. Destination: {source.namespace}. Audience: {source.reader_policy}. Audience and connection are fixed; changing either requires a new registration.

} +
+ { invalidate(); setResources(value); }} aria-describedby="mcp-selection-hint" /> +

{copy.selection} Select 1–1,000 distinct IDs without empty lines.

+ { invalidate(); setLabel(value); }} /> + { invalidate(); setMode(value); }} /> + {!source && { invalidate(); setAudience(value); }} options={[ + { value: "owner_only", label: "Private to me", hint: "Collection membership does not broaden this source's audience." }, + { value: "collection_copy", label: "Copy to collection readers", hint: "Requires operator approval, current collection admin and explicit publication authority.", disabled: mode === "live" }, + ]} />} +
+

{copy.audience}

+ {!source && { if (value.org === org && value.callerKey === callerKey) setCreated((old) => [...new Set([...old, value.namespace])]); }} />} + + {result && } + {result && (result.rule.publication_confirmation_required || audience === "collection_copy") && setConsent(value === true)} />} + } + {created.length > 0 &&

Confirmed collections retained: {created.join(", ")}. A failed source registration does not remove them.

} + {request.busy && } + {!!request.error && } + {uncertain &&
+ +

Original destination: {binding?.namespace}. Original slot: {binding?.slot}. Retained request ID: {binding?.request_id}.

+ + {inspected && <> +

{inspected.name}: {inspected.state}; {inspected.mode}; {inspected.reader_policy}; revision {inspected.scope_revision}. IDs: {inspected.resource_ids.join("; ")}

+ + } +
} + {notice &&

{notice}

} + {saved && <> +

Registration name: {saved.name}. Destination: {saved.namespace}.

+

Server registration state: {saved.state}. Refresh state: {saved.refresh_state}. This does not attest upstream access or completed synchronization.

+ } +
+ ); +} + +/** Newline is the sole delimiter; neither URLs nor opaque identities are normalized. */ +export function resourceIDs(value: string): string[] { return value === "" ? [] : value.split("\n"); } + +export function MCPAccessPreview({ preview }: { preview: MCPPreview }) { + return
+

Server access rule: {preview.rule.access}. Reason: {preview.rule.reason || "No additional reason returned"}.

+

{preview.rule.explanation}

+

Stores a copy: {preview.rule.stores_copy ? "yes" : "no"}. Refresh: {preview.refresh_state}. Selected IDs: {preview.selected_count}.

+

Checked at: {preview.checked_at}. Preview grants authority: no. Remote permission evidence: {preview.permission_evidence}. Reader list complete: no.

+

Read evidence expires after {preview.read_evidence_stale_seconds} seconds. Snapshot read access expires without manual refresh; retained bytes do not grant permanent access. Both audiences require current authorization and fresh evidence.

+
    {preview.limitations.map((line, index) =>
  • {line}
  • )}
+
; +} diff --git a/frontend/src/flows/MembersDialog.tsx b/frontend/src/flows/MembersDialog.tsx index ccea54b515..6ff818f730 100644 --- a/frontend/src/flows/MembersDialog.tsx +++ b/frontend/src/flows/MembersDialog.tsx @@ -307,7 +307,7 @@ export function MembersDialog({ setBusy("__add__"); setErr(null); try { - await createGrant({ org, namespace }, subj, newRole); + await createGrant({ org, namespace }, subj, newRole, undefined, "explicit"); toast(`Added ${subjectLabel(subj, org)} as ${newRole}`, "ok"); setNewSubject(""); setNewRole(defaultRole); @@ -326,7 +326,7 @@ export function MembersDialog({ try { // The role Select is the one deliberate "lower this member" control; // it says so to the server. onAdd never does. - await createGrant({ org, namespace }, subject, role, { replace: true }); + await createGrant({ org, namespace }, subject, role, { replace: true }, "explicit"); toast(`${subjectLabel(subject, org)} → ${role}`, "ok"); load(); onChanged?.(); @@ -376,7 +376,7 @@ export function MembersDialog({ return; setBusy(subject); try { - await revokeGrant({ org, namespace }, subject); + await revokeGrant({ org, namespace }, subject, "explicit"); toast(toEveryone ? `Stopped sharing with everyone in ${org}` : `Removed ${who}`, "ok"); load(); onChanged?.(); @@ -401,7 +401,7 @@ export function MembersDialog({ let firstError: unknown = null; for (const t of targets) { try { - await approveGrant({ org, namespace: t.namespace }, subject, decision); + await approveGrant({ org, namespace: t.namespace }, subject, decision, undefined, "explicit"); ok++; } catch (e) { firstError ??= e; @@ -559,7 +559,7 @@ export function MembersDialog({ return; setBusy(r.subject); try { - await cancelNamespaceRequest(org, namespace); + await cancelNamespaceRequest(org, namespace, "explicit"); toast(`Withdrew ${r.requested_role} request`, "ok"); load(); } catch (e) { diff --git a/frontend/src/flows/MemoryReasonDialogs.tsx b/frontend/src/flows/MemoryReasonDialogs.tsx index f77e7cf332..da6a5416a2 100644 --- a/frontend/src/flows/MemoryReasonDialogs.tsx +++ b/frontend/src/flows/MemoryReasonDialogs.tsx @@ -39,7 +39,7 @@ export function LockMemoryDialog({ confirm="Lock" onClose={onClose} onSubmit={async (reason) => { - const r = await lockMemory(row, memoryKey, mode, reason); + const r = await lockMemory(row, memoryKey, mode, reason, "explicit"); if (!r.locked) throw new Error("This memory is no longer live."); toast("Locked", "ok"); onDone(); @@ -75,7 +75,7 @@ export function RejectMemoryDialog({ danger onClose={onClose} onSubmit={async (reason) => { - await rejectMemory(row, memoryKey, reason); + await rejectMemory(row, memoryKey, reason, "explicit"); toast("Marked as wrong", "ok"); onDone(); }} diff --git a/frontend/src/flows/MoveCollectionDialog.test.tsx b/frontend/src/flows/MoveCollectionDialog.test.tsx index 7a712910e3..9ad8cad609 100644 --- a/frontend/src/flows/MoveCollectionDialog.test.tsx +++ b/frontend/src/flows/MoveCollectionDialog.test.tsx @@ -56,7 +56,7 @@ describe("MoveCollectionDialog", () => { screen.getByText("At the top, only its own members reach it. Whoever reached it only through finance loses it."), ).toBeInTheDocument(); await userEvent.click(screen.getByRole("button", { name: "Move" })); - await waitFor(() => expect(api.moveCollection).toHaveBeenCalledWith("acme", "q3", "")); + await waitFor(() => expect(api.moveCollection).toHaveBeenCalledWith("acme", "q3", "", "explicit")); expect(onClose).toHaveBeenCalled(); expect(changed).toHaveBeenCalled(); }); diff --git a/frontend/src/flows/MoveCollectionDialog.tsx b/frontend/src/flows/MoveCollectionDialog.tsx index 6224634ab3..61325eca3a 100644 --- a/frontend/src/flows/MoveCollectionDialog.tsx +++ b/frontend/src/flows/MoveCollectionDialog.tsx @@ -56,7 +56,7 @@ export function MoveCollectionDialog({ setBusy(true); setError(null); try { - await moveCollection(org, collection.namespace, target); + await moveCollection(org, collection.namespace, target, "explicit"); invalidateSharedCollections(); toast(target ? `Moved ${self} into ${shown(target)}` : `${self} is top-level`, "ok"); onMoved?.(); diff --git a/frontend/src/flows/MoveDocumentsDialog.test.tsx b/frontend/src/flows/MoveDocumentsDialog.test.tsx index e2e4de4531..7823e7446a 100644 --- a/frontend/src/flows/MoveDocumentsDialog.test.tsx +++ b/frontend/src/flows/MoveDocumentsDialog.test.tsx @@ -115,6 +115,7 @@ describe("MoveDocumentsDialog", () => { ["doc://a.md"], expect.any(AbortSignal), expect.any(Function), + "explicit", ); await waitFor(() => expect(onMoved).toHaveBeenCalledWith(["doc://a.md"])); expect(toast).toHaveBeenCalledWith("Moved 1 document to Engineering", "ok"); @@ -149,6 +150,7 @@ describe("MoveDocumentsDialog", () => { ["doc://b.md"], expect.any(AbortSignal), expect.any(Function), + "explicit", ); }); it("moves to the place picked and says whose sharing they take", async () => { @@ -171,6 +173,7 @@ describe("MoveDocumentsDialog", () => { ["doc://a.md", "doc://b.md"], expect.any(AbortSignal), expect.any(Function), + "explicit", ); await waitFor(() => expect(onMoved).toHaveBeenCalledWith(["doc://a.md", "doc://b.md"])); expect(toast).toHaveBeenCalledWith("Moved 2 documents to Storage", "ok"); @@ -234,6 +237,7 @@ describe("MoveDocumentsDialog", () => { ["doc://b.md"], expect.any(AbortSignal), expect.any(Function), + "explicit", ); }); diff --git a/frontend/src/flows/MoveDocumentsDialog.tsx b/frontend/src/flows/MoveDocumentsDialog.tsx index 8f3cf0db7e..85c99b058a 100644 --- a/frontend/src/flows/MoveDocumentsDialog.tsx +++ b/frontend/src/flows/MoveDocumentsDialog.tsx @@ -106,6 +106,7 @@ export function MoveDocumentsDialog({ const movedOf = (results: KnowledgeMoveResult[]) => results.filter((x) => x.moved).map((x) => x.source_uri); const r = await moveKnowledge({ org, namespace: from }, target.namespace, left, controller.signal, (results) => onMoved(movedOf(results)), + "explicit", ); const moved = movedOf(r.results); if (controller.signal.aborted) return; // closed meanwhile: each call read the list again diff --git a/frontend/src/flows/NamespaceSettingsDialog.costCap.test.tsx b/frontend/src/flows/NamespaceSettingsDialog.costCap.test.tsx index 33bec97a1e..e3da6c0113 100644 --- a/frontend/src/flows/NamespaceSettingsDialog.costCap.test.tsx +++ b/frontend/src/flows/NamespaceSettingsDialog.costCap.test.tsx @@ -53,7 +53,7 @@ describe("NamespaceSettingsDialog cost cap", () => { expect(api.reregisterNamespace).toHaveBeenCalledTimes(1); expect(api.reregisterNamespace).toHaveBeenCalledWith({ org: "dev", namespace: "ns" }, row("ns", 5), { daily_cost_cap_usd: 12, - }); + }, "explicit"); }); it("Enter commits", async () => { @@ -63,7 +63,7 @@ describe("NamespaceSettingsDialog cost cap", () => { expect(api.reregisterNamespace).toHaveBeenCalledTimes(1); expect(api.reregisterNamespace).toHaveBeenCalledWith({ org: "dev", namespace: "ns" }, row("ns", 5), { daily_cost_cap_usd: 7.5, - }); + }, "explicit"); }); it.each(["-1", "", "5"])("%j sends nothing and reverts to the stored cap", async (text) => { diff --git a/frontend/src/flows/NamespaceSettingsDialog.tsx b/frontend/src/flows/NamespaceSettingsDialog.tsx index 4fefaaadc8..647cb7954b 100644 --- a/frontend/src/flows/NamespaceSettingsDialog.tsx +++ b/frontend/src/flows/NamespaceSettingsDialog.tsx @@ -133,7 +133,7 @@ export function NamespaceSettingsDialog({ open, onOpenChange, org, namespace, la const savedKey = key; setSaving(true); try { - await reregisterNamespace({ org, namespace }, ns, patch); + await reregisterNamespace({ org, namespace }, ns, patch, "explicit"); toast("Settings saved", "ok"); const next = await getNamespace({ org, namespace }); // The dialog moved to another namespace while this save was in flight. @@ -174,7 +174,7 @@ export function NamespaceSettingsDialog({ open, onOpenChange, org, namespace, la return; setSaving(true); try { - const r = await deleteNamespace({ org, namespace }); + const r = await deleteNamespace({ org, namespace }, "explicit"); if (r.deleted) { toast(`Deleted ${namespace}`, "ok"); onOpenChange(false); diff --git a/frontend/src/flows/RepoDocDialogs.tsx b/frontend/src/flows/RepoDocDialogs.tsx index 9332b461dc..2f4893756a 100644 --- a/frontend/src/flows/RepoDocDialogs.tsx +++ b/frontend/src/flows/RepoDocDialogs.tsx @@ -117,7 +117,7 @@ export function RepoDocAddDialog({ setStep(line); setBusy(phase); }, - { signal: ctrl.signal }, + { signal: ctrl.signal, intent: "explicit" }, ); if (status.state === "ready") return null; if (status.state === "partial") return status.coverage?.lost ?? []; @@ -136,6 +136,7 @@ export function RepoDocAddDialog({ await addKnowledge( { org, namespace }, { source_uri: uri, content: pasted, title: title.trim(), description: description.trim(), upsert: false }, + "explicit", ); onAdded(title.trim(), lost); onOpenChange(false); diff --git a/frontend/src/flows/RunGrade.test.tsx b/frontend/src/flows/RunGrade.test.tsx index 073115b0e6..e680bd940c 100644 --- a/frontend/src/flows/RunGrade.test.tsx +++ b/frontend/src/flows/RunGrade.test.tsx @@ -32,7 +32,7 @@ describe("RunGrade", () => { await userEvent.type(screen.getByLabelText("Why (optional)"), "CI went green"); await userEvent.click(screen.getByRole("button", { name: "Held up" })); await waitFor(() => - expect(api.gradeRun).toHaveBeenCalledWith(identity, "r1", "pass", "CI went green", "dashboard"), + expect(api.gradeRun).toHaveBeenCalledWith(identity, "r1", "pass", "CI went green", "dashboard", "explicit"), ); expect(await screen.findByText("Graded as held up by dashboard: CI went green")).toBeInTheDocument(); }); @@ -64,7 +64,7 @@ describe("RunGrade", () => { }); render(); await userEvent.click(screen.getByRole("button", { name: "Did not hold" })); - await waitFor(() => expect(api.gradeRun).toHaveBeenCalledWith(identity, "r1", "fail", "", "alice")); + await waitFor(() => expect(api.gradeRun).toHaveBeenCalledWith(identity, "r1", "fail", "", "alice", "explicit")); expect(toast).toHaveBeenCalledWith("Graded: did not hold, 2 proposals decided", "ok"); expect(await screen.findByText("Graded as did not hold by alice")).toBeInTheDocument(); }); diff --git a/frontend/src/flows/RunGrade.tsx b/frontend/src/flows/RunGrade.tsx index e802da6d60..5ee92634fd 100644 --- a/frontend/src/flows/RunGrade.tsx +++ b/frontend/src/flows/RunGrade.tsx @@ -28,7 +28,7 @@ export function RunGrade({ const grade = async (g: "pass" | "fail") => { setBusy(true); try { - const r = await gradeRun(identity, run.run_id, g, reason.trim(), grader); + const r = await gradeRun(identity, run.run_id, g, reason.trim(), grader, "explicit"); // Under an owner's auto policy any grade, an unchanged one too, may accept or reject proposals. const n = r.proposals_decided.length; const decided = n ? `, ${n} proposal${n === 1 ? "" : "s"} decided` : ""; diff --git a/frontend/src/flows/SourcePushDialog.test.tsx b/frontend/src/flows/SourcePushDialog.test.tsx deleted file mode 100644 index c5dc9f4fda..0000000000 --- a/frontend/src/flows/SourcePushDialog.test.tsx +++ /dev/null @@ -1,147 +0,0 @@ -import { cleanup, render, screen, waitFor } from "../test/rtl"; -import userEvent from "@testing-library/user-event"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { axeViolations } from "../test/axe"; -import * as api from "../api/sourcePush"; -import type { PushStatus } from "../api/sourcePush"; -import { SourcePushDialog } from "./SourcePushDialog"; - -vi.mock("../api/sourcePush", () => ({ - sourcePushStatus: vi.fn(), - configureSourcePush: vi.fn(), - confirmSourcePush: vi.fn(), -})); -const source = { org: "org", namespace: "docs", name: "source" }; -const disabled: PushStatus = { - enabled: true, - status: "disabled", - provider: "notion", - generation: "", - callback_url: "", - challenge_fingerprint: "", - verification_token: "", - channels: 0, - expires_at: 0, -}; -const pending: PushStatus = { - ...disabled, - status: "pending", - generation: "generation", - callback_url: "https://loom.example/hooks/knowledge/docs/id/generation?org=org", -}; - -beforeEach(() => { - vi.resetAllMocks(); - vi.mocked(api.sourcePushStatus).mockResolvedValue(disabled); -}); -afterEach(cleanup); - -describe("SourcePushDialog", () => { - it("pauses setup when the deployment opts out while keeping Disable available", async () => { - const user = userEvent.setup(); - vi.mocked(api.sourcePushStatus).mockResolvedValue({ ...pending, enabled: false, status: "active" }); - vi.mocked(api.configureSourcePush).mockResolvedValue({ ...disabled, enabled: false }); - render( {}} />); - expect(await screen.findByText("Paused")).toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Start setup" })).toBeNull(); - await user.click(screen.getByRole("button", { name: "Disable push" })); - expect(api.configureSourcePush).toHaveBeenCalledWith(source, false); - await waitFor(() => expect(screen.queryByRole("button", { name: "Disable push" })).toBeNull()); - expect(screen.queryByRole("button", { name: "Start setup" })).toBeNull(); - }); - it("prepares a Linear address before asking for its secret and confirms the same setup", async () => { - const user = userEvent.setup(); - vi.mocked(api.configureSourcePush).mockResolvedValue({ ...pending, provider: "linear" }); - vi.mocked(api.confirmSourcePush).mockResolvedValue({ ...pending, provider: "linear", status: "active" }); - render( {}} />); - await user.click(await screen.findByRole("button", { name: "Start setup" })); - expect(api.configureSourcePush).toHaveBeenCalledWith(source, true); - expect(await screen.findByText(pending.callback_url)).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Refresh" })).toHaveFocus(); - await user.type(screen.getByLabelText("Webhook signing secret", { exact: true }), "signing-secret"); - expect(await axeViolations(document.body)).toEqual([]); - await user.click(screen.getByRole("button", { name: "Enable push" })); - expect(api.confirmSourcePush).toHaveBeenCalledWith(source, { ...pending, provider: "linear" }, "signing-secret"); - expect(await screen.findByText("Active")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Refresh" })).toHaveFocus(); - expect(screen.queryByDisplayValue("signing-secret")).toBeNull(); - }); - - it("reveals a Notion token explicitly, then removes it after confirmation", async () => { - const user = userEvent.setup(); - const inspected = { ...pending, challenge_fingerprint: "fingerprint" }; - const revealed = { ...inspected, verification_token: "verification-secret" }; - vi.mocked(api.sourcePushStatus).mockResolvedValueOnce(inspected).mockResolvedValueOnce(revealed); - vi.mocked(api.confirmSourcePush).mockResolvedValue({ ...pending, status: "active" }); - render( {}} />); - expect(screen.queryByText("verification-secret")).toBeNull(); - await user.click(await screen.findByRole("button", { name: "Reveal verification token" })); - expect(api.sourcePushStatus).toHaveBeenLastCalledWith(source, true); - expect(await screen.findByText("verification-secret")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Refresh" })).toHaveFocus(); - await user.click(screen.getByRole("button", { name: "I verified in Notion" })); - expect(api.confirmSourcePush).toHaveBeenCalledWith(source, revealed); - expect(await screen.findByText("Active")).toBeInTheDocument(); - expect(screen.queryByText("verification-secret")).toBeNull(); - expect(screen.getByRole("button", { name: "Refresh" })).toHaveFocus(); - }); - - it.each([ - { status: "expired", enabled: true }, - { status: "expired", enabled: false }, - { status: "obsolete", enabled: true }, - { status: "obsolete", enabled: false }, - ])("retires $status Drive setup with deployment enabled=$enabled", async ({ status, enabled }) => { - const user = userEvent.setup(); - vi.mocked(api.sourcePushStatus).mockResolvedValue({ - ...disabled, - provider: "gdrive", - status, - enabled, - generation: status === "expired" ? "generation" : "", - channels: status === "expired" ? 1 : 0, - expires_at: status === "expired" ? 1 : 0, - }); - vi.mocked(api.configureSourcePush).mockResolvedValue({ ...disabled, provider: "gdrive", enabled }); - render( {}} />); - await screen.findByText( - enabled ? (status === "expired" ? "Expired; set up again" : "Source changed; set up again") : "Paused", - ); - expect(await axeViolations(document.body)).toEqual([]); - await user.click(screen.getByRole("button", { name: "Disable push" })); - expect(api.configureSourcePush).toHaveBeenCalledWith(source, false); - await waitFor(() => expect(screen.queryByRole("button", { name: "Disable push" })).toBeNull()); - expect(screen.getByRole("button", { name: "Refresh" })).toHaveFocus(); - }); - - it("moves focus to Refresh after disabling push", async () => { - const user = userEvent.setup(); - vi.mocked(api.sourcePushStatus).mockResolvedValue({ ...pending, status: "active" }); - vi.mocked(api.configureSourcePush).mockResolvedValue(disabled); - render( {}} />); - await user.click(await screen.findByRole("button", { name: "Disable push" })); - expect(api.configureSourcePush).toHaveBeenCalledWith(source, false); - expect(await screen.findByText("Disabled")).toBeInTheDocument(); - expect(screen.getByRole("button", { name: "Refresh" })).toHaveFocus(); - }); - - it("drops a late initial read after a refresh and setup complete", async () => { - const user = userEvent.setup(); - let finishInitial: (status: PushStatus) => void = () => {}; - vi.mocked(api.sourcePushStatus) - .mockReturnValueOnce( - new Promise((resolve) => { - finishInitial = resolve; - }), - ) - .mockResolvedValueOnce(disabled); - vi.mocked(api.configureSourcePush).mockResolvedValue(pending); - render( {}} />); - await user.click(screen.getByRole("button", { name: "Refresh" })); - await user.click(await screen.findByRole("button", { name: "Start setup" })); - expect(await screen.findByText("Waiting for verification")).toBeInTheDocument(); - finishInitial(disabled); - await waitFor(() => expect(screen.getByText("Waiting for verification")).toBeInTheDocument()); - expect(screen.queryByRole("button", { name: "Start setup" })).toBeNull(); - }); -}); diff --git a/frontend/src/flows/SourcePushDialog.tsx b/frontend/src/flows/SourcePushDialog.tsx deleted file mode 100644 index a95ea69663..0000000000 --- a/frontend/src/flows/SourcePushDialog.tsx +++ /dev/null @@ -1,219 +0,0 @@ -import { useId, useRef, useState } from "react"; -import { Button } from "@clickhouse/click-ui/Button"; -import { PasswordField } from "@clickhouse/click-ui/PasswordField"; -import { CopyButton } from "../components/CopyButton"; -import { Alert, Loading, MetaList, MetaRow } from "../components/ui"; -import { BusyButton } from "../components/ui/BusyButton"; -import { configureSourcePush, confirmSourcePush, sourcePushStatus, type PushStatus } from "../api/sourcePush"; -import { humanizeError } from "../lib/errorWords"; -import { useAbortableEffect } from "../lib/hooks"; -import { DialogFrame } from "./TaskDialogFrame"; - -export function SourcePushDialog({ - org, - namespace, - name, - kind, - onClose, -}: { - org: string; - namespace: string; - name: string; - kind: string; - onClose: () => void; -}) { - const source = { org, namespace, name }; - const hintId = useId(); - const [status, setStatus] = useState(null); - const [secret, setSecret] = useState(""); - const [error, setError] = useState(null); - const [busy, setBusy] = useState(false); - const refresh = useRef(null); - const revision = useRef(0); - useAbortableEffect( - (signal, live) => { - const version = ++revision.current; - sourcePushStatus(source, false, signal) - .then((result) => live() && revision.current === version && setStatus(result)) - .catch((e) => live() && revision.current === version && setError(e)); - }, - [org, namespace, name], - ); - - const act = async (work: () => Promise) => { - if (busy) return; - const version = ++revision.current; - setBusy(true); - setError(null); - try { - const result = await work(); - if (revision.current !== version) return; - setStatus(result); - setSecret(""); - } catch (e) { - setError(e); - } finally { - setBusy(false); - refresh.current?.focus(); - } - }; - const pending = status?.status === "pending"; - const active = status?.status === "active"; - const configurable = status?.enabled && !active && !pending; - return ( - !open && onClose()} - title={`Push notifications for ${name}`} - description="Ask for a sync when the source changes. Regular polling continues if a notification is missed." - footer={ - - } - > - {!!error && } - {!status && !error && } - {status && ( - <> - {!status.enabled && ( - - )} - - - {!status.enabled - ? "Paused" - : pending && kind !== "notion" - ? "Setup incomplete" - : (STATUS[status.status] ?? status.status)} - - {status.channels > 0 && {status.channels}} - {status.expires_at > 0 && ( - {new Date(status.expires_at * 1000).toLocaleString()} - )} - - {status.callback_url && ( -
-

Notification address

-

{status.callback_url}

- -
- )} - {kind === "linear" && pending && status.enabled && ( -
- -

- Create a webhook in Linear using the notification address above, then copy its signing secret here. -

- void act(() => confirmSourcePush(source, status, secret))} - > - Enable push - -
- )} - {pending && kind === "notion" && status.enabled && ( -
-

- Add the notification address to your Notion connection. Refresh after Notion sends its verification - token. -

- {status.challenge_fingerprint && !status.verification_token && ( - void act(() => sourcePushStatus(source, true))} - > - Reveal verification token - - )} - {status.verification_token && ( - <> -

{status.verification_token}

- -

- Paste this token into Notion and verify the subscription there, then confirm below. -

- void act(() => confirmSourcePush(source, status))} - > - I verified in Notion - - - )} -
- )} - {configurable && kind === "gdrive" && ( -

- Drive setup watches the account and up to 19 shared drives it belongs to. An operator can enable automatic - renewal. -

- )} - - )} -
- void act(() => sourcePushStatus(source))} - > - Refresh - - {configurable && ( - void act(() => configureSourcePush(source, true))} - > - {kind === "gdrive" ? "Enable push" : "Start setup"} - - )} - {pending && status?.enabled && ( - void act(() => configureSourcePush(source, true))} - > - Restart setup - - )} - {(active || pending || status?.status === "expired" || status?.status === "obsolete") && ( - void act(() => configureSourcePush(source, false))} - > - Disable push - - )} -
-
- ); -} - -const STATUS: Record = { - disabled: "Disabled", - pending: "Waiting for verification", - active: "Active", - obsolete: "Source changed; set up again", - expired: "Expired; set up again", -}; diff --git a/frontend/src/flows/TaskActionDialog.tsx b/frontend/src/flows/TaskActionDialog.tsx index afa22dc093..c029e589fe 100644 --- a/frontend/src/flows/TaskActionDialog.tsx +++ b/frontend/src/flows/TaskActionDialog.tsx @@ -142,34 +142,34 @@ export function TaskActionDialog({ result = await acceptTask(identity, id, { ...(priority !== task.priority ? { priority } : {}), ...(note.trim() ? { note: note.trim() } : {}), - }); + }, "explicit"); break; case "complete": - result = await completeTask(identity, id, fence, note.trim()); + result = await completeTask(identity, id, fence, note.trim(), "explicit"); break; case "fail": - result = await failTask(identity, id, fence, r); + result = await failTask(identity, id, fence, r, "explicit"); break; case "wont_do": - result = await wontDoTask(identity, id, r); + result = await wontDoTask(identity, id, r, "explicit"); break; case "defer": - result = await deferTask(identity, id, r, isoFromLocal(resumeAt), fence); + result = await deferTask(identity, id, r, isoFromLocal(resumeAt), fence, "explicit"); break; case "block": - result = await blockTask(identity, id, r, blockedOn, fence); + result = await blockTask(identity, id, r, blockedOn, fence, "explicit"); break; case "unblock": - result = await unblockTask(identity, id, note.trim()); + result = await unblockTask(identity, id, note.trim(), "explicit"); break; case "cancel": - result = await cancelTask(identity, id, r); + result = await cancelTask(identity, id, r, "explicit"); break; case "reopen": - result = await reopenTask(identity, id, r); + result = await reopenTask(identity, id, r, "explicit"); break; case "reassign": - result = await reassignTask(identity, id, toInbox, r); + result = await reassignTask(identity, id, toInbox, r, "explicit"); break; } toast(actionDone(action, task.title), "ok"); diff --git a/frontend/src/flows/TaskEditDialog.tsx b/frontend/src/flows/TaskEditDialog.tsx index 989a1f7cf2..4ad0386ef4 100644 --- a/frontend/src/flows/TaskEditDialog.tsx +++ b/frontend/src/flows/TaskEditDialog.tsx @@ -98,7 +98,7 @@ export function TaskEditDialog({ open, onOpenChange, identity, mode, onSaved }: ? { clear_not_before: true } : {}), ...(note.trim() ? { note: note.trim() } : {}), - }); + }, "explicit"); toast("Task updated", "ok"); onSaved(r.task); } else { @@ -111,7 +111,7 @@ export function TaskEditDialog({ open, onOpenChange, identity, mode, onSaved }: disclosure, not_before: isoFromLocal(notBefore), deadline: isoFromLocal(deadline), - }); + }, "explicit"); toast(r.task.status === "triage" ? "Task posted — waiting in triage" : "Task posted", "ok"); onSaved(r.task); } diff --git a/frontend/src/flows/ThreadActions.test.tsx b/frontend/src/flows/ThreadActions.test.tsx index 8bc5cf3959..2d32b2fb8f 100644 --- a/frontend/src/flows/ThreadActions.test.tsx +++ b/frontend/src/flows/ThreadActions.test.tsx @@ -84,10 +84,10 @@ describe("ThreadActions", () => { await userEvent.clear(field); await userEvent.type(field, "Release plan"); await userEvent.click(within(dialog).getByRole("button", { name: "Rename" })); - await waitFor(() => expect(api.renameThread).toHaveBeenCalledWith(identity, "claude-code", "t1", "Release plan")); + await waitFor(() => expect(api.renameThread).toHaveBeenCalledWith(identity, "claude-code", "t1", "Release plan", "explicit")); await userEvent.click(screen.getByRole("button", { name: "Actions for Deploy plan" })); await userEvent.click(await screen.findByRole("menuitem", { name: "Delete" })); - await waitFor(() => expect(api.deleteThread).toHaveBeenCalledWith(identity, "claude-code", "t1")); + await waitFor(() => expect(api.deleteThread).toHaveBeenCalledWith(identity, "claude-code", "t1", "explicit")); expect(onChanged).toHaveBeenCalledTimes(2); }); @@ -114,7 +114,7 @@ describe("ThreadActions", () => { await userEvent.type(within(dialog).getByLabelText("Title"), "Release plan"); await userEvent.click(within(dialog).getByRole("button", { name: "Rename" })); await waitFor(() => - expect(api.createThreadRow).toHaveBeenCalledWith(identity, "claude-code", "t1", "Release plan"), + expect(api.createThreadRow).toHaveBeenCalledWith(identity, "claude-code", "t1", "Release plan", "explicit"), ); expect(api.renameThread).not.toHaveBeenCalled(); }); @@ -137,7 +137,7 @@ describe("ThreadActions", () => { await userEvent.click(await screen.findByRole("menuitem", { name: "Rename" })); const dialog = await screen.findByRole("dialog", { name: "Rename conversation" }); await userEvent.click(within(dialog).getByRole("button", { name: "Rename" })); - await waitFor(() => expect(api.createThreadRow).toHaveBeenCalledWith(identity, "claude-code", "t1", "Deploy plan")); + await waitFor(() => expect(api.createThreadRow).toHaveBeenCalledWith(identity, "claude-code", "t1", "Deploy plan", "explicit")); }); it("renames as the agent that owns the thread's row, not the last writer", async () => { @@ -160,7 +160,7 @@ describe("ThreadActions", () => { await userEvent.click(await screen.findByRole("menuitem", { name: "Rename" })); const dialog = await screen.findByRole("dialog", { name: "Rename conversation" }); await userEvent.click(within(dialog).getByRole("button", { name: "Rename" })); - await waitFor(() => expect(api.renameThread).toHaveBeenCalledWith(identity, "codex", "t1", "Deploy plan")); + await waitFor(() => expect(api.renameThread).toHaveBeenCalledWith(identity, "codex", "t1", "Deploy plan", "explicit")); expect(api.createThreadRow).not.toHaveBeenCalled(); }); @@ -329,7 +329,7 @@ describe("ThreadActions", () => { await userEvent.click(await screen.findByRole("menuitem", { name: "Rename" })); const dialog = await screen.findByRole("dialog", { name: "Rename conversation" }); await userEvent.click(within(dialog).getByRole("button", { name: "Rename" })); - await waitFor(() => expect(api.renameThread).toHaveBeenLastCalledWith(identity, "cursor", "t1", "Deploy plan")); + await waitFor(() => expect(api.renameThread).toHaveBeenLastCalledWith(identity, "cursor", "t1", "Deploy plan", "explicit")); expect(api.createThreadRow).not.toHaveBeenCalled(); }); @@ -378,7 +378,7 @@ describe("ThreadActions", () => { const dialog = await screen.findByRole("dialog", { name: "Rename conversation" }); await userEvent.click(within(dialog).getByRole("button", { name: "Rename" })); await waitFor(() => expect(toast).toHaveBeenCalledWith("This conversation was deleted", "info")); - expect(api.renameThread).toHaveBeenCalledWith(identity, "codex", "t1", "Deploy plan"); + expect(api.renameThread).toHaveBeenCalledWith(identity, "codex", "t1", "Deploy plan", "explicit"); expect(api.createThreadRow).not.toHaveBeenCalled(); expect(onChanged).toHaveBeenCalled(); }); diff --git a/frontend/src/flows/ThreadActions.tsx b/frontend/src/flows/ThreadActions.tsx index 46cced07e7..d267b2b6ee 100644 --- a/frontend/src/flows/ThreadActions.tsx +++ b/frontend/src/flows/ThreadActions.tsx @@ -49,7 +49,7 @@ export function ThreadActions({ danger: true, }); if (!ok) return; - const r = await deleteEveryAgent(identity, thread); + const r = await deleteEveryAgent(identity, thread, "explicit"); if (r.error) { const why = humanizeError(r.error, { bare: true }); // The error's words end the line: they may close with a full stop and a retry tail. @@ -103,7 +103,7 @@ function RenameDialog({ if (reason) return; setBusy(true); try { - const renamed = await retitle(identity, thread, title.trim()); + const renamed = await retitle(identity, thread, title.trim(), "explicit"); toast(renamed ? "Renamed" : "This conversation was deleted", renamed ? "ok" : "info"); onClose(true); } catch (e) { @@ -149,13 +149,14 @@ const MAX_AGENTS = 20; async function deleteEveryAgent( id: Pick, thread: Thread, + intent: "automatic" | "explicit" = "automatic", ): Promise<{ parts: number; left: number; error?: unknown }> { let agent = thread.agent; let parts = 0; let left = 0; try { while (parts < MAX_AGENTS) { - await deleteThread(id, agent, thread.thread_id); + await deleteThread(id, agent, thread.thread_id, intent); parts++; // What was left before this delete is no longer known. left = 0; @@ -176,17 +177,17 @@ async function deleteEveryAgent( * writer), or write one for a thread built by appends, which has none. When the update * finds the row changed or gone, the head is read and the rename tried once more. * Answers false when the conversation is gone. */ -async function retitle(id: Pick, thread: Thread, title: string): Promise { +async function retitle(id: Pick, thread: Thread, title: string, intent: "automatic" | "explicit" = "automatic"): Promise { for (let tries = 0; tries < 2; tries++) { const head = await readHead(id, thread.thread_id); if (!head.found) return false; if (!head.created_at) { // conversation.create replaces a row written since the read, metadata included; // it has no create-if-absent, so that window stays open. - await createThreadRow(id, thread.agent, thread.thread_id, title); + await createThreadRow(id, thread.agent, thread.thread_id, title, intent); return true; } - if ((await renameThread(id, head.agent, thread.thread_id, title)).updated) return true; + if ((await renameThread(id, head.agent, thread.thread_id, title, intent)).updated) return true; } throw new Error("The conversation changed during the rename; try again"); } diff --git a/frontend/src/flows/TrackerSourceDialogs.test.tsx b/frontend/src/flows/TrackerSourceDialogs.test.tsx index ee16692a23..ed7750700b 100644 --- a/frontend/src/flows/TrackerSourceDialogs.test.tsx +++ b/frontend/src/flows/TrackerSourceDialogs.test.tsx @@ -724,6 +724,6 @@ describe("Retire a tracker", () => { fireEvent.change(screen.getByLabelText(/to confirm/), { target: { value: "kj" } }); fireEvent.click(go); await waitFor(() => expect(onRetired).toHaveBeenCalledWith(["tracker-kj"])); - expect(removeTrackerSource).toHaveBeenCalledWith("dev", "kj", "kj"); + expect(removeTrackerSource).toHaveBeenCalledWith("dev", "kj", "kj", "explicit"); }); }); diff --git a/frontend/src/flows/TrackerSourceDialogs.tsx b/frontend/src/flows/TrackerSourceDialogs.tsx index 0c5c1d9985..588c80f1f7 100644 --- a/frontend/src/flows/TrackerSourceDialogs.tsx +++ b/frontend/src/flows/TrackerSourceDialogs.tsx @@ -322,7 +322,7 @@ export function RegisterTrackerSourceDialog({ setBusy(dryRun ? "check" : "add"); setRefusal(null); try { - const out = await addTrackerSource(sourceAddBody(org, form, dryRun, mode === "mapping" ? mapping : null)); + const out = await addTrackerSource(sourceAddBody(org, form, dryRun, mode === "mapping" ? mapping : null), undefined, "explicit"); if (dryRun) { setChecked({ fp, result: out }); } else { @@ -1291,7 +1291,7 @@ export function RotateCredentialDialog({ setBusy(true); setError(null); try { - await rotateTrackerSource(org, name, user.trim(), password); + await rotateTrackerSource(org, name, user.trim(), password, "explicit"); onRotated(); onOpenChange(false); } catch (e) { @@ -1351,7 +1351,7 @@ export function RetireSourceDialog({ setBusy(true); setError(null); try { - const out = await removeTrackerSource(org, name, typed.trim()); + const out = await removeTrackerSource(org, name, typed.trim(), "explicit"); onRetired(out.namespaces_retired); onOpenChange(false); } catch (e) { @@ -1447,7 +1447,7 @@ export function EditMappingDialog({ setBusy(dryRun ? "check" : "save"); setError(null); try { - const out = await setTrackerMapping(org, source.name, mapping, dryRun); + const out = await setTrackerMapping(org, source.name, mapping, dryRun, "explicit"); if (dryRun) setChecked({ fp, contract: out.contract }); else { onSaved(); diff --git a/frontend/src/flows/mcpSourceCopy.ts b/frontend/src/flows/mcpSourceCopy.ts new file mode 100644 index 0000000000..6f28ac0fec --- /dev/null +++ b/frontend/src/flows/mcpSourceCopy.ts @@ -0,0 +1,34 @@ +import type { SourceDestinationCopy } from "./SourceDestinationStep"; + +// Source-local copy is the catalog handoff boundary; no unresolved catalog keys are rendered. +export const mcpSourceCopy = { + title: "MCP document sources", + transport: "Connect to an operator-approved remote HTTPS MCP server using Streamable HTTP. Supported authentication is anonymous or a preissued bearer. OAuth and local stdio are not supported.", + selection: "Enter explicit opaque resource IDs, one per line. IDs are sent exactly as entered; links are not normalized. Folder traversal, search-based scope rules, future-item inclusion and complete enumeration are not supported.", + privacy: "Live lookup does not import documents. Protected source content requires current server authorization and fresh read evidence for both audiences. Snapshot read access expires without manual refresh; expiry does not erase retained bytes or history. Copies and protected progress state follow server retention and erasure rules. Ordinary content logs, traces and caches shared across readers exclude private content. Privileged database logs and backups may retain values after erasure; deployment operators control their access and retention. Disconnecting does not erase copies or revoke the upstream credential. This is not a zero-retention service.", + audience: "A private source stays owner-only even in a team collection. Collection copies use current and future inherited collection grants. Those grants do not delegate your connection. Remote ACL and deletion synchronization are unsupported.", + authority: "I have authority to publish this selection to current and future readers of this collection, including inherited grants.", + retained: "Retained bytes do not grant current access. Reconnecting or changing an operator profile requires a new registration.", + uncertain: "The mutation result is uncertain. The draft and request ID are retained in this open flow. Inspect server state before taking another action; the mutation will not be sent again.", + modes: [ + { value: "live", label: "Live lookup", hint: "Read on demand without importing documents." }, + { value: "snapshot", label: "Selected snapshot", hint: "Copy the fixed selection; later refresh is explicit." }, + { value: "selected_refresh", label: "Refresh selected items", hint: "Refresh only these IDs when the server enables refresh." }, + ], +} as const; + +export const mcpDestinationCopy: SourceDestinationCopy = { + title: "Destination", description: "Choose or create an ordinary private or team collection. Review access before saving.", + searchLabel: "Search this page", searchHint: "Search names and addresses on this page. Load more to read the next page.", + pageScope: "this page", destinationsLabel: "Writable collections", loading: "Loading collections", + loadError: "Collections could not be loaded.", things: "collections", empty: "No writable ordinary collections on this page.", + previous: "Previous page", next: "Load more", refresh: "Refresh collections", create: "New collection", + createHint: "Create at the top level or inside a writable collection on this page.", + topLevelHint: "Top-level collection. Review its grants before publishing.", + selectionHint: "The server checks effective access again when saving.", + pagingError: "The next page repeated a cursor. Refresh the collection list.", + pagingLimit: "More collections exist. This view has reached its page limit.", + inheritanceHint: (parent) => `Inherits grants from ${parent}. Review effective access before publishing.`, + created: (namespace) => `Collection confirmed: ${namespace}. Select it after reviewing the list.`, + selected: (namespace) => `Selected destination: ${namespace}`, page: (number) => `Page ${number}`, +}; diff --git a/frontend/src/flows/useMCPRequest.ts b/frontend/src/flows/useMCPRequest.ts new file mode 100644 index 0000000000..db28e4d727 --- /dev/null +++ b/frontend/src/flows/useMCPRequest.ts @@ -0,0 +1,33 @@ +import { useCallback, useEffect, useRef, useState } from "react"; + +/** One abortable request lane. A caller or draft change rejects even an abort-ignoring answer. */ +export function useMCPRequest(scope: string) { + const current = useRef(scope); + current.current = scope; + const pending = useRef(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + useEffect(() => { + setBusy(false); + setError(null); + return () => { pending.current?.abort(); }; + }, [scope]); + const run = useCallback(async (work: (signal: AbortSignal) => Promise): Promise => { + pending.current?.abort(); + const controller = new AbortController(); + pending.current = controller; + const stamp = current.current; + setBusy(true); + setError(null); + try { + const result = await work(controller.signal); + if (!controller.signal.aborted && current.current === stamp) return result; + } catch (failure) { + if (!controller.signal.aborted && current.current === stamp) setError(failure); + } finally { + if (!controller.signal.aborted && current.current === stamp) setBusy(false); + } + return undefined; + }, []); + return { run, busy, error }; +} diff --git a/frontend/src/layout/MobileMore.tsx b/frontend/src/layout/MobileMore.tsx index 3ecbeb8df7..7e4cf7a6d2 100644 --- a/frontend/src/layout/MobileMore.tsx +++ b/frontend/src/layout/MobileMore.tsx @@ -108,7 +108,7 @@ export default function MoreSheet({ onClose }: { onClose: () => void }) {
{g.group}
{g.items.map((m) => { - const active = view === m.id || (m.id === "setup" && view === "connected-accounts"); + const active = view === m.id; return ( setView("setup")} /> diff --git a/frontend/src/lib/batchIngest.ts b/frontend/src/lib/batchIngest.ts index 29405ddc2c..73d65c21d3 100644 --- a/frontend/src/lib/batchIngest.ts +++ b/frontend/src/lib/batchIngest.ts @@ -344,6 +344,7 @@ export function skipRepeats(rows: BatchRow[], where: (r: BatchRow) => string): B const SENT: ReadonlySet = new Set(["done", "partial", "working", "goes_on"]); export interface BatchOptions { + intent?: "automatic" | "explicit"; fields: { tags: string[]; allow_partial: boolean }; /** Sends no more files. A job already queued goes on, unless `cancelling` says the * person stopped the batch, when its row cancels it. */ @@ -395,6 +396,7 @@ async function sendRow(start: BatchRow, opts: BatchOptions): Promise { }, { signal: opts.signal, + intent: opts.intent, onQueued: (ingestionId) => set({ ingestionId }), // Into a collection made a moment ago, a refusal can mean another replica has not // learned of it yet. @@ -411,7 +413,7 @@ async function sendRow(start: BatchRow, opts: BatchOptions): Promise { set({ ingestionId: undefined, ...ended(status, row) }); } catch (e) { if (opts.signal.aborted && row.ingestionId) { - if (opts.cancelling?.()) await cancelRow(row.target, row.ingestionId, set); + if (opts.cancelling?.()) await cancelRow(row.target, row.ingestionId, set, opts.intent); else set({ state: "goes_on", line: STILL }); return; } @@ -445,10 +447,11 @@ async function cancelRow( target: BatchRow["target"], ingestionId: string, set: (patch: Partial) => void, + intent: "automatic" | "explicit" = "automatic", ): Promise { set({ line: "Stopping…" }); try { - const out = await cancelIngestion(target, ingestionId); + const out = await cancelIngestion(target, ingestionId, intent); if (out.found && (out.state === "ready" || out.state === "partial")) set({ state: "done", line: "Added before it could stop" }); // A running job stops before it publishes, unless it was already publishing. diff --git a/frontend/src/lib/dashboardSessionProtection.ts b/frontend/src/lib/dashboardSessionProtection.ts new file mode 100644 index 0000000000..1fa054374b --- /dev/null +++ b/frontend/src/lib/dashboardSessionProtection.ts @@ -0,0 +1,175 @@ +import { + SessionProtection, + type SessionProtectionStore, + SessionProtectionUnavailable, +} from "../../../sdk/typescript/src/session-protection.js"; + +const DATABASE = "loom-dashboard-session-protection"; +const STORE = "authority"; +const KEY = "dashboard"; +const WITNESS = "loom-dashboard-session-protection-v1"; + +interface Authority { + version: 1; + family: string; + state: "protected"; +} + +function authority(value: unknown, family: string): value is Authority { + if (value === null || typeof value !== "object") return false; + const row = value as Partial; + return Object.keys(value).length === 3 && row.version === 1 && row.family === family && row.state === "protected"; +} + +/** One content-free family for every dashboard namespace, tab and restored conversation. */ +export class DashboardSessionProtectionStore implements SessionProtectionStore { + private readonly database: IDBDatabase; + private readonly storage: Storage; + private readonly family: string; + + private constructor( + database: IDBDatabase, + storage: Storage, + family: string, + ) { + this.database = database; + this.storage = storage; + this.family = family; + } + + static open(): Promise { + return new Promise((resolve, reject) => { + let storage: Storage; + let witness: string | null; + let opening: IDBOpenDBRequest; + let family: string | undefined; + let refused = false; + const timer = setTimeout(() => refuse(), 60_000); + const refuse = () => { + refused = true; + clearTimeout(timer); + reject(new SessionProtectionUnavailable()); + }; + try { + storage = window.localStorage; + witness = storage.getItem(WITNESS); + opening = window.indexedDB.open(DATABASE, 1); + } catch { + refuse(); + return; + } + opening.onblocked = refuse; + opening.onerror = refuse; + opening.onupgradeneeded = (event) => { + try { + // A surviving witness means this is lost proof, not a first installation. + if (refused || witness !== null || event.oldVersion !== 0) { + opening.transaction?.abort(); + refuse(); + return; + } + family = window.crypto.randomUUID(); + const store = opening.result.createObjectStore(STORE); + // No blank browser or complete storage wipe can manufacture a clean family. + store.add({ version: 1, family, state: "protected" } satisfies Authority, KEY); + storage.setItem(WITNESS, family); + } catch { + opening.transaction?.abort(); + refuse(); + } + }; + opening.onsuccess = () => { + const database = opening.result; + if (refused) { + database.close(); + return; + } + database.onversionchange = () => database.close(); + try { + // Another tab may have provisioned while this open waited for its upgrade. + family ??= storage.getItem(WITNESS) ?? undefined; + } catch { + database.close(); + refuse(); + return; + } + if (!family) { + database.close(); + refuse(); + return; + } + const store = new DashboardSessionProtectionStore(database, storage, family); + store.mark().then( + () => { + if (refused) database.close(); + else { + clearTimeout(timer); + resolve(store); + } + }, + () => { + database.close(); + refuse(); + }, + ); + }; + }); + } + + private transaction(mark: boolean): Promise<"protected"> { + return new Promise((resolve, reject) => { + let transaction: IDBTransaction; + let valid = false; + const refuse = () => reject(new SessionProtectionUnavailable()); + try { + if (this.storage.getItem(WITNESS) !== this.family) throw new SessionProtectionUnavailable(); + transaction = this.database.transaction(STORE, mark ? "readwrite" : "readonly", { + durability: "strict", + }); + const store = transaction.objectStore(STORE); + const request = store.get(KEY); + request.onsuccess = () => { + try { + if (this.storage.getItem(WITNESS) !== this.family || !authority(request.result, this.family)) { + transaction.abort(); + return; + } + valid = true; + // Never repair a missing row and never write clean, even after a storage reset. + if (mark) store.put({ version: 1, family: this.family, state: "protected" } satisfies Authority, KEY); + } catch { + transaction.abort(); + } + }; + transaction.oncomplete = () => { + try { + if (!valid || this.storage.getItem(WITNESS) !== this.family) throw new SessionProtectionUnavailable(); + resolve("protected"); + } catch { + refuse(); + } + }; + transaction.onabort = refuse; + transaction.onerror = refuse; + } catch { + refuse(); + } + }); + } + + read(): Promise<"protected"> { + return this.transaction(false); + } + + async mark(): Promise { + await this.transaction(true); + } +} + +let retained: Promise | undefined; + +/** A rejected restore stays rejected; requests cannot provision a replacement family. */ +export function dashboardSessionProtection(): Promise { + retained ??= DashboardSessionProtectionStore.open().then((store) => new SessionProtection(store)); + return retained; +} diff --git a/frontend/src/lib/dashboardSourceReads.test.ts b/frontend/src/lib/dashboardSourceReads.test.ts new file mode 100644 index 0000000000..90b893cabd --- /dev/null +++ b/frontend/src/lib/dashboardSourceReads.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it, vi } from "vitest"; +import { + AutomaticCaptureSuppressed, + SessionProtection, +} from "../../../sdk/typescript/src/session-protection.js"; +import { createDashboardTransport } from "./dashboardTransport"; +import { OP_BY_NAME } from "../../../sdk/typescript/src/generated/ops.js"; +import { ADMIN_SETTINGS_READ_ROUTES } from "../api/adminReadRoutes"; + +function sender() { + const family = new SessionProtection({ + read: async () => "protected", + mark: async () => {}, + }); + const fetch = vi.fn(async (_url: string, _init: RequestInit) => new Response('{"mirrored":true}', { + headers: { "Content-Type": "application/json" }, + })); + return { fetch, send: createDashboardTransport({ baseUrl: "https://dashboard.example", family: async () => family, fetch }) }; +} + +describe("source read dispatch classification", () => { + it.each(Object.values(ADMIN_SETTINGS_READ_ROUTES))( + "observes the dedicated operator read %s without granting a mutation", async (path) => { + const { fetch, send } = sender(); + await send(path, { method: "POST", body: "{}" }); + expect(fetch).toHaveBeenCalledOnce(); + await expect(send("/v1/admin/settings.set", { method: "POST", body: "{}" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).toHaveBeenCalledOnce(); + }, + ); + it.each(["/v1/admin/settings.list?prefix=secret", "/v1/admin/settings.list/", "/v1/admin/settings.history#fragment", "/v1/admin/settings.reset"])( + "keeps the unregistered operator variant %s guarded", async (path) => { + const { fetch, send } = sender(); + await expect(send(path, { method: "POST", body: "{}" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).not.toHaveBeenCalled(); + }, + ); + it.each(Object.entries(OP_BY_NAME).filter(([, spec]) => spec.readOnly).map(([name]) => name))( + "admits the generated read-only contract for %s", async (op) => { + const { fetch, send } = sender(); + await send(`/v1/${op}`, { method: "POST", body: "{}" }); + expect(fetch).toHaveBeenCalledOnce(); + }, + ); + + it.each(["/v1/constructor", "/v1/__proto__", "/v1/memory.list?limit=1", "/v1/memory.list/", "https://dashboard.example/v1/memory.list"])( + "keeps noncanonical or unknown POST %s guarded", async (path) => { + const { fetch, send } = sender(); + await expect(send(path, { method: "POST", body: "{}" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).not.toHaveBeenCalled(); + }, + ); + it.each(["memory.list", "memory.get", "conversation.list", "conversation.search", "namespace.inventory"])( + "admits the trusted generated read-only operation %s", async (op) => { + expect(OP_BY_NAME[op as keyof typeof OP_BY_NAME]?.readOnly).toBe(true); + const { fetch, send } = sender(); + await send(`/v1/${op}`, { method: "POST", body: "{}" }); + expect(fetch).toHaveBeenCalledOnce(); + }, + ); + it.each([ + "source.mcp_read", "connection.mcp_browse", "source.mcp_preview", "source.mcp_list", + "source.mcp_inspect", "source.mcp_profiles", "connection.mcp_list", "connection.mcp_inspect", + ])("observes %s without treating it as automatic publication", async (op) => { + const { fetch, send } = sender(); + const path = `/v1/knowledge.${op}`; + const response = await send(path, { method: "POST", body: "{}" }); + expect(await response.json()).toEqual({ mirrored: true }); + expect(new Headers(fetch.mock.calls[0]?.[1]?.headers).get("x-loom-session-protection")).toBe("v1"); + await expect(send("/v1/memory.set", { method: "POST", body: "{}" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it.each([ + "source.mcp_add", "source.mcp_update", "source.mcp_remove", "source.mcp_refresh", + "source.mcp_pause", "source.mcp_resume", "connection.mcp_connect", "connection.mcp_disconnect", + "connection.mcp_discover", "source.mcp_read?write=true", "source.mcp_read/extra", + "source.mcp_read#fragment", "source.mcp_read%3Fwrite", "unknown.get", "constructor", + ])("keeps %s guarded without inferring manual intent", async (op) => { + const { fetch, send } = sender(); + await expect(send(`/v1/knowledge.${op}`, { method: "POST", body: "{}" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/lib/dashboardTransport.test.ts b/frontend/src/lib/dashboardTransport.test.ts new file mode 100644 index 0000000000..26dc006e05 --- /dev/null +++ b/frontend/src/lib/dashboardTransport.test.ts @@ -0,0 +1,218 @@ +import { describe, expect, it, vi } from "vitest"; +import { + AutomaticCaptureSuppressed, + SessionProtection, + type SessionProtectionStore, + SessionProtectionUnavailable, +} from "../../../sdk/typescript/src/session-protection.js"; +import { createDashboardTransport } from "./dashboardTransport"; + +function control() { + let state: "clean" | "protected" | "missing" = "clean"; + const store: SessionProtectionStore = { + async read() { + if (state === "missing") throw new Error("missing proof"); + return state; + }, + async mark() { + if (state === "missing") throw new Error("missing proof"); + state = "protected"; + }, + }; + return { + family: new SessionProtection(store), + store, + lose: () => { state = "missing"; }, + state: () => state, + }; +} + +function json(value: unknown, status = 200) { + return new Response(JSON.stringify(value), { + status, + headers: { "Content-Type": "application/json", "X-Request-Id": "retained-request" }, + }); +} + +const post: RequestInit = { method: "POST", body: "{}" }; +const baseUrl = "https://dashboard.example"; + +describe("dashboard transport", () => { + it("observes a manual private read before blocking all later automatic destinations", async () => { + const state = control(); + const family = vi.fn(async () => state.family); + const fetch = vi.fn(async (_url: string, _init: RequestInit) => json({ mirrored: true, text: "private" })); + const send = createDashboardTransport({ baseUrl, family, fetch }); + const response = await send("/v1/knowledge.source.mcp_read", post, "explicit"); + expect(state.state()).toBe("protected"); + expect(await response.json()).toEqual({ mirrored: true, text: "private" }); + expect(new Headers(fetch.mock.calls[0]?.[1]?.headers).get("x-loom-session-protection")).toBe("v1"); + await expect(send("/v1/memory.set", { + ...post, body: JSON.stringify({ namespace: "another", session_id: "new-request", value: "private" }), + })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + await expect(send("/v1/conversation.create", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).toHaveBeenCalledTimes(1); + expect(family).toHaveBeenCalledTimes(1); + }); + + it("allows a clean automatic call without manufacturing a declaration in application code", async () => { + const state = control(); + const fetch = vi.fn(async (_url: string, _init: RequestInit) => json({ ok: true })); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + await expect((await send("/v1/memory.set", post)).json()).resolves.toEqual({ ok: true }); + expect(new Headers(fetch.mock.calls[0]?.[1]?.headers).get("x-loom-session-protection")).toBe("v1"); + expect(state.state()).toBe("clean"); + }); + + it("keeps manual intent on one invocation and observes further explicit writes", async () => { + const state = control(); + await state.family.mark(); + const fetch = vi.fn(async () => json({ mirrored: true, saved: true })); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + expect((await send("/v1/memory.set", post, "explicit")).status).toBe(200); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("observes error metadata before returning status, headers or diagnostics", async () => { + const state = control(); + const fetch = vi.fn(async () => json({ error: { data: { mirrored: true } } }, 500)); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + const response = await send("/v1/knowledge.source.mcp_read", post, "explicit"); + expect(state.state()).toBe("protected"); + expect(response.status).toBe(500); + expect(response.headers.get("X-Request-Id")).toBe("retained-request"); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + }); + + it.each([200, 403, 503])("refuses malformed private JSON at HTTP %i", async (status) => { + const state = control(); + const fetch = vi.fn(async () => new Response('{"mirrored":true,', { + status, headers: { "Content-Type": "application/json" }, + })); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + await expect(send("/v1/knowledge.source.mcp_read", post, "explicit")).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(state.state()).toBe("protected"); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + }); + + it("rejects missing proof for manual calls and does not replace the retained family", async () => { + const state = control(); + const family = vi.fn(async () => state.family); + const fetch = vi.fn(async () => json({})); + const send = createDashboardTransport({ baseUrl, family, fetch }); + await send("/v1/memory.get", post, "explicit"); + state.lose(); + await expect(send("/v1/memory.get", post, "explicit")).rejects.toBeInstanceOf(SessionProtectionUnavailable); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(family).toHaveBeenCalledTimes(1); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("does not retry a failed application restore", async () => { + const family = vi.fn(async (): Promise => { throw new SessionProtectionUnavailable(); }); + const fetch = vi.fn(async () => json({})); + const send = createDashboardTransport({ baseUrl, family, fetch }); + await expect(send("/v1/memory.set", post, "explicit")).rejects.toBeInstanceOf(SessionProtectionUnavailable); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(family).toHaveBeenCalledTimes(1); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("observes SSE before a private frame is released", async () => { + const state = control(); + const frame = 'data: {"mirrored":true,"delta":"private"}\n\n'; + const fetch = vi.fn(async () => new Response(frame, { headers: { "Content-Type": "text/event-stream" } })); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + const response = await send("/v1/assistant.chat", post, "explicit"); + expect(await response.text()).toBe(frame); + expect(state.state()).toBe("protected"); + await expect(send("/v1/conversation.create", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + }); + + it("joins stream cancellation and refuses automatic work before unread content can escape", async () => { + const state = control(); + const cancel = vi.fn(); + const body = new ReadableStream({ cancel }, { highWaterMark: 0 }); + const fetch = vi.fn(async () => new Response(body, { headers: { "Content-Type": "text/event-stream" } })); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + const response = await send("/v1/assistant.chat", post, "explicit"); + await response.body?.cancel(); + expect(cancel).toHaveBeenCalledTimes(1); + expect(state.state()).toBe("protected"); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + }); + + it("refuses incomplete SSE EOF and retains the same family for later requests", async () => { + const state = control(); + const fetch = vi.fn(async () => new Response('data: {"mirrored":true}', { + headers: { "Content-Type": "text/event-stream" }, + })); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + const response = await send("/v1/assistant.chat", post, "explicit"); + await expect(response.text()).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(state.state()).toBe("protected"); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("marks the retained family when the caller aborts an outstanding JSON request", async () => { + const state = control(); + let started: () => void = () => {}; + const opening = new Promise((resolve) => { started = resolve; }); + const fetch = vi.fn((_url: string, init: RequestInit) => new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true }); + started(); + })); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + const controller = new AbortController(); + const pending = send("/v1/knowledge.source.mcp_read", { ...post, signal: controller.signal }, "explicit"); + await opening; + controller.abort(); + await expect(pending).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(state.state()).toBe("protected"); + await expect(send("/v1/memory.set", post)).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("waits for durable marking before releasing content or admitting another automatic callback", async () => { + let state: "clean" | "protected" = "clean"; + let marking: () => void = () => {}; + const started = new Promise((resolve) => { marking = resolve; }); + let commit: () => void = () => {}; + const committed = new Promise((resolve) => { commit = resolve; }); + const family = new SessionProtection({ + read: async () => state, + mark: async () => { marking(); await committed; state = "protected"; }, + }); + const fetch = vi.fn(async () => json({ mirrored: true, text: "private" })); + const send = createDashboardTransport({ baseUrl, family: async () => family, fetch }); + let released = false; + const pending = send("/v1/knowledge.source.mcp_read", post, "explicit").then((response) => { + released = true; + return response; + }); + await started; + expect(released).toBe(false); + expect(family.locallyProtected).toBe(true); + const automatic = send("/v1/memory.set", post); + const refused = expect(automatic).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + commit(); + await expect((await pending).json()).resolves.toEqual({ mirrored: true, text: "private" }); + await refused; + expect(fetch).toHaveBeenCalledTimes(1); + }); + + it("rejects foreign origins and caller declarations before sending credentials", async () => { + const state = control(); + const fetch = vi.fn(async () => json({})); + const send = createDashboardTransport({ baseUrl, family: async () => state.family, fetch }); + await expect(send("https://other.example/v1/memory.set", { + ...post, headers: { Authorization: "Bearer example" }, + }, "explicit")).rejects.toBeInstanceOf(SessionProtectionUnavailable); + await expect(send("/v1/memory.set", { + ...post, headers: { "x-loom-session-protection": "v1" }, + }, "explicit")).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/frontend/src/lib/dashboardTransport.ts b/frontend/src/lib/dashboardTransport.ts new file mode 100644 index 0000000000..f0a7bb34a4 --- /dev/null +++ b/frontend/src/lib/dashboardTransport.ts @@ -0,0 +1,51 @@ +import { protectedBrowserTransport } from "../../../sdk/typescript/src/browser-protection.js"; +import type { SessionProtection } from "../../../sdk/typescript/src/session-protection.js"; +import { OP_BY_NAME } from "../../../sdk/typescript/src/generated/ops.js"; +import { dashboardSessionProtection } from "./dashboardSessionProtection"; +import { ADMIN_SETTINGS_READ_ROUTES } from "../api/adminReadRoutes"; + +/** Explicit intent belongs to one invocation. Never retain it in a client or callback. */ +export type DashboardRequestIntent = "automatic" | "explicit"; + +function isReadOnlyOperation(input: string, init: RequestInit): boolean { + if (init.method !== "POST" || !input.startsWith("/v1/")) return false; + if (Object.values(ADMIN_SETTINGS_READ_ROUTES).some((path) => path === input)) return true; + const name = input.slice(4); + return Object.hasOwn(OP_BY_NAME, name) && OP_BY_NAME[name as keyof typeof OP_BY_NAME].readOnly === true; +} + +export function createDashboardTransport(options: { + baseUrl: string; + family: () => Promise; + fetch: (input: string, init: RequestInit) => Promise; +}) { + // The same promise and handle survive request, credential, namespace and conversation changes. + let retained: ReturnType | undefined; + return async (input: string, init: RequestInit, intent: DashboardRequestIntent = "automatic", download = false) => { + retained ??= options.family(); + const transport = protectedBrowserTransport({ + baseUrl: options.baseUrl, + sessionProtection: await retained, + fetch: options.fetch, + }); + if (download) return transport.downloadFetch(input, init); + const read = init.method === "GET" || isReadOnlyOperation(input, init); + return intent === "explicit" || read ? transport.fetch(input, init) : transport.automaticFetch(input, init); + }; +} + +let retained: ReturnType | undefined; + +export function dashboardFetch( + input: string, + init: RequestInit, + intent: DashboardRequestIntent = "automatic", + download = false, +): Promise { + retained ??= createDashboardTransport({ + baseUrl: window.location.origin, + family: dashboardSessionProtection, + fetch: (url, options) => globalThis.fetch(url, options), + }); + return retained(input, init, intent, download); +} diff --git a/frontend/src/lib/fileIngest.ts b/frontend/src/lib/fileIngest.ts index f98280afba..d0c45a4576 100644 --- a/frontend/src/lib/fileIngest.ts +++ b/frontend/src/lib/fileIngest.ts @@ -154,6 +154,7 @@ export async function ingestFile( fields: KnowledgeIngestFields, onStep: (line: string, phase: IngestPhase) => void, opts: { + intent?: "automatic" | "explicit"; signal?: AbortSignal; onQueued?: (ingestionId: string) => void; /** Wraps the upload and the ingest call, to send each again when the server allows. */ @@ -166,10 +167,10 @@ export async function ingestFile( const retry = opts.retry ?? ((step) => step()); const poll = opts.poll ?? ((step) => step()); onStep("Uploading…", "upload"); - const up = await retry(() => uploadKnowledgeFile(id, file, signal)); + const up = await retry(() => uploadKnowledgeFile(id, file, signal, opts.intent)); signal?.throwIfAborted(); // cancelled while the bytes went: nothing is queued onStep("Queuing…", "queue"); - const job = await retry(() => ingestKnowledge(id, { ...fields, upload_id: up.upload_id })); + const job = await retry(() => ingestKnowledge(id, { ...fields, upload_id: up.upload_id }, opts.intent)); opts.onQueued?.(job.ingestion_id); let missed = 0; for (;;) { diff --git a/frontend/src/lib/folderUpload.ts b/frontend/src/lib/folderUpload.ts index 177105263c..91f43c3e8f 100644 --- a/frontend/src/lib/folderUpload.ts +++ b/frontend/src/lib/folderUpload.ts @@ -345,6 +345,7 @@ export class FolderCollections { /** Collections an earlier upload from the same dialog made: other replicas may not * know them yet either. */ private earlier: readonly string[] = [], + private intent: "automatic" | "explicit" = "automatic", ) {} /** The collections this upload made, parents first. */ @@ -376,7 +377,7 @@ export class FolderCollections { try { r = await this.retry(() => whileNew( - () => createCollection(this.org, "", { parent: parent.namespace, title: plan.title, deriveName: true }), + () => createCollection(this.org, "", { parent: parent.namespace, title: plan.title, deriveName: true }, this.intent), parent.fresh, signal, ), diff --git a/frontend/src/lib/joinActions.ts b/frontend/src/lib/joinActions.ts index 44d0993200..ee1e9296df 100644 --- a/frontend/src/lib/joinActions.ts +++ b/frontend/src/lib/joinActions.ts @@ -40,9 +40,9 @@ export interface JoinTarget { export type JoinRole = "viewer" | "admin"; /** `namespace.join`; the toast says whether the reader is in or queued. */ -export async function joinTarget(t: JoinTarget, role: JoinRole = "viewer"): Promise { +export async function joinTarget(t: JoinTarget, role: JoinRole = "viewer", intent: "automatic" | "explicit" = "automatic"): Promise { try { - const res = await joinNamespace(t.org, t.namespace, { role }); + const res = await joinNamespace(t.org, t.namespace, { role }, intent); if (res.status === "pending") { const n = (res.pending_admins || []).length; const what = role === "admin" ? "Maintainer role requested" : "Access requested"; @@ -58,7 +58,7 @@ export async function joinTarget(t: JoinTarget, role: JoinRole = "viewer"): Prom } /** Confirm, then `namespace.cancel_request`. Resolves true when withdrawn. */ -export async function withdrawTarget(t: JoinTarget): Promise { +export async function withdrawTarget(t: JoinTarget, intent: "automatic" | "explicit" = "automatic"): Promise { if ( !(await confirmAction({ title: `Withdraw your request for ${t.label}?`, @@ -68,7 +68,7 @@ export async function withdrawTarget(t: JoinTarget): Promise { ) return false; try { - await cancelNamespaceRequest(t.org, t.namespace); + await cancelNamespaceRequest(t.org, t.namespace, intent); toast(`Request withdrawn for ${t.label}`, "ok"); return true; } catch (e) { @@ -78,7 +78,7 @@ export async function withdrawTarget(t: JoinTarget): Promise { } /** Confirm, then `namespace.leave`. Resolves true when left. */ -export async function leaveTarget(t: JoinTarget): Promise { +export async function leaveTarget(t: JoinTarget, intent: "automatic" | "explicit" = "automatic"): Promise { if ( !(await confirmAction({ title: `Leave ${t.label}?`, @@ -88,7 +88,7 @@ export async function leaveTarget(t: JoinTarget): Promise { ) return false; try { - await leaveNamespace(t.org, t.namespace); + await leaveNamespace(t.org, t.namespace, intent); toast(`Left ${t.label}`, "ok"); return true; } catch (e) { diff --git a/frontend/src/lib/knowledgeSources.test.ts b/frontend/src/lib/knowledgeSources.test.ts index 03c393b204..1c7aa68ef8 100644 --- a/frontend/src/lib/knowledgeSources.test.ts +++ b/frontend/src/lib/knowledgeSources.test.ts @@ -2,20 +2,15 @@ import { describe, expect, it } from "vitest"; import { credentialLabel, emptySourceForm, - folderIds, kindLabel, - databaseIds, meetingIds, - pageIds, probeCount, - projectIds, retiredMessage, sourceAddBody, sourceFormFingerprint, sourceFormProblems, syncBadge, syncCounts, - toggleInclude, unconvertedDetail, type KnowledgeSourceSync, } from "./knowledgeSources"; @@ -36,8 +31,6 @@ function sync(over: Partial = {}): KnowledgeSourceSync { }; } -const FOLDER = "1AbCdEfGhIjKlMnOp"; - describe("syncBadge", () => { it("names each state with its tone", () => { expect(syncBadge(sync())).toMatchObject({ text: "Never synced", tone: "muted" }); @@ -47,11 +40,11 @@ describe("syncBadge", () => { expect(syncBadge(sync({ status: "failed", error: "http_403" })).tip).toContain("http_403"); }); - it("directs retired Meet sources to Shared folder without suggesting credential rotation", () => { + it("describes retired providers without offering replaced source setup", () => { expect(syncBadge(sync({ status: "provider_removed" }))).toEqual({ - text: "Meet sync retired", + text: "Provider unavailable", tone: "warn", - tip: "Add a Shared folder source for Meet transcripts and notes. Existing documents stay unless you ask to delete them.", + tip: "This provider is unavailable. Retained bytes and history do not grant current access.", }); }); @@ -86,129 +79,18 @@ describe("syncCounts", () => { }); }); -describe("the add form", () => { - it("takes folder ids or links, one per line or comma-separated, without duplicates", () => { - expect(folderIds(`${FOLDER}\nhttps://example.com/drive/folders/${FOLDER}?usp=sharing, 2ZyXwVuTsRqPoNm`)).toEqual([ - FOLDER, - "2ZyXwVuTsRqPoNm", - ]); - }); - - it("lists every problem until the form can be checked", () => { +describe("recording setup", () => { + const named = { ...emptySourceForm(), name: "notes", credential: "k" }; + it("validates a name, meeting selection and credential before checking", () => { expect(sourceFormProblems(emptySourceForm())).toHaveLength(3); - const ok = { ...emptySourceForm(), name: " Design-Docs ", folders: FOLDER, credential: "{}" }; - expect(sourceFormProblems(ok)).toEqual([]); - expect(sourceFormProblems({ ...ok, folders: "short" })).toEqual(["Not a folder id: short."]); - expect(sourceFormProblems({ ...ok, include: [] })).toEqual(["Pick at least one file kind."]); - }); - - it("sends the normalised name and the config, and fingerprints what the check read", () => { - const f = { ...emptySourceForm(), name: " Design-Docs ", folders: FOLDER, credential: " {} " }; - expect(sourceAddBody("o", "code-x", f, true)).toEqual({ - org: "o", - namespace: "code-x", - name: "design-docs", - kind: "gdrive", - config: { folder_ids: [FOLDER], include: ["docs", "slides", "pdf", "pptx"] }, - credential: "{}", - dry_run: true, + expect(sourceFormProblems({ ...named, meetings: "81234567890" })).toEqual([]); + expect(sourceAddBody("o", "docs", { ...named, meetings: "81234567890" }, false)).toEqual({ + org: "o", namespace: "docs", name: "notes", kind: "recording", + config: { provider: "zoom", ids: ["81234567890"] }, credential: "k", dry_run: false, }); - expect(sourceFormFingerprint(f)).toBe(sourceFormFingerprint({ ...f, name: "design-docs" })); - expect(sourceFormFingerprint(f)).not.toBe(sourceFormFingerprint({ ...f, credential: "{ }" })); - }); - - it("counts a probe, a lower bound when there are more", () => { - expect(probeCount({ documents: 1, more: false, sample: [] })).toBe("1 document"); + expect(sourceFormFingerprint({ ...named, meetings: "81234567890" })).not.toBe(sourceFormFingerprint({ ...named, meetings: "91234567890" })); expect(probeCount({ documents: 1000, more: true, sample: [] })).toBe("1000+ documents"); }); -}); - -const PROJECT = "0f8b2c4e-1a2b-4c3d-8e9f-0123456789ab"; -const PAGE = "1a2b3c4d5e6f708192a3b4c5d6e7f809"; -const DATABASE = "abcdefabcdefabcdefabcdefabcdef01"; - -describe("the add form's other kinds", () => { - const named = { ...emptySourceForm(), name: "notes", credential: "k" }; - - it("sends a project tracker's project ids, lower-cased", () => { - const f = { ...named, kind: "linear" as const, projects: `${PROJECT.toUpperCase()}\n${PROJECT}` }; - expect(sourceFormProblems(f)).toEqual([]); - expect(sourceAddBody("o", "code-x", f, true)).toEqual({ - org: "o", - namespace: "code-x", - name: "notes", - kind: "linear", - config: { project_ids: [PROJECT] }, - credential: "k", - dry_run: true, - }); - // A project id is lower-cased; anything else, such as a pasted link, is named as typed. - const link = "https://tracker.example/Team/project/Roadmap-3f2a"; - expect(projectIds(`${PROJECT.toUpperCase()} ${link}`)).toEqual([PROJECT, link]); - expect(sourceFormProblems({ ...f, projects: link })).toEqual([`Not a project id (a UUID): ${link}.`]); - expect(sourceFormProblems({ ...f, projects: "" })).toEqual(["Add at least one project."]); - expect(sourceFormProblems({ ...f, projects: "my-project" })).toEqual(["Not a project id (a UUID): my-project."]); - expect(sourceFormProblems({ ...f, credential: "" })).toEqual(["Paste the read-only API key."]); - }); - - it("sends a page store's page and database ids, from ids with or without dashes or from links", () => { - const dashed = `${PAGE.slice(0, 8)}-${PAGE.slice(8, 12)}-${PAGE.slice(12, 16)}-${PAGE.slice(16, 20)}-${PAGE.slice(20)}`; - expect(pageIds(`${dashed}, https://pages.example/team/Design-Notes-${PAGE}`)).toEqual([PAGE]); - // A link with no title, and one to a block on the page. - expect(pageIds(`https://pages.example/${PAGE}?pvs=4`)).toEqual([PAGE]); - expect(pageIds(`https://pages.example/team/Design-Notes-${PAGE}#${DATABASE}`)).toEqual([PAGE]); - // A database link's view id (`?v=`) is not the database's id; under Databases it - // gives the database, under Pages it is named as a database link. - const dbLink = `https://pages.example/team/${DATABASE}?v=${PAGE}`; - expect(databaseIds(dbLink)).toEqual([DATABASE]); - expect(pageIds(dbLink)).toEqual([dbLink]); - expect(sourceFormProblems({ ...named, kind: "notion", pages: dbLink })).toEqual([ - `Paste a database link under Databases: ${dbLink}.`, - ]); - // A peek link opens a page of the database: the page is its `p=`. - const VIEW = "0123456789abcdef0123456789abcdef"; - const peekLink = `https://pages.example/team/${DATABASE}?v=${VIEW}&p=${PAGE}&pm=s`; - expect(pageIds(peekLink)).toEqual([PAGE]); - // A row's peek link on its parent page (a `p=`, no `v=`) is a page: under Pages it - // gives the row, under Databases it is named, never read as the parent page. - const rowLink = `https://pages.example/team/Parent-${DATABASE}?p=${PAGE}&pm=s`; - expect(pageIds(rowLink)).toEqual([PAGE]); - expect(databaseIds(rowLink)).toEqual([rowLink]); - expect(sourceFormProblems({ ...named, kind: "notion", databases: rowLink })).toEqual([ - `Paste a page link under Pages: ${rowLink}.`, - ]); - // A mistyped page in a peek link is named, never read as the database. - const badPeek = `https://pages.example/team/${DATABASE}?v=${VIEW}&p=${PAGE}0&pm=s`; - expect(pageIds(badPeek)).toEqual([badPeek]); - // In the databases field the same link is its database. - expect(databaseIds(peekLink)).toEqual([DATABASE]); - expect(sourceAddBody("o", "x", { ...emptySourceForm(), kind: "notion", databases: peekLink }, true).config).toEqual( - { page_ids: [], database_ids: [DATABASE] }, - ); - // Kept as typed, so the problem names it: an id one digit long is not cut to 32. - expect(pageIds(`${PAGE}0`)).toEqual([`${PAGE}0`]); - // A link whose id is mistyped one digit long is not cut to another id. - expect(pageIds(`https://pages.example/team/Home-${PAGE}0`)).toEqual([`https://pages.example/team/Home-${PAGE}0`]); - expect(pageIds(`https://pages.example/team/${PAGE}0`)).toEqual([`https://pages.example/team/${PAGE}0`]); - const f = { ...named, kind: "notion" as const, pages: PAGE, databases: DATABASE.toUpperCase() }; - expect(sourceFormProblems(f)).toEqual([]); - expect(sourceAddBody("o", "code-x", f, true).config).toEqual({ page_ids: [PAGE], database_ids: [DATABASE] }); - expect(sourceAddBody("o", "code-x", { ...f, databases: "" }, true).config).toEqual({ - page_ids: [PAGE], - database_ids: [], - }); - expect(sourceFormProblems({ ...f, pages: "", databases: "" })).toEqual(["Add at least one page or database."]); - expect(sourceFormProblems({ ...f, pages: "home" })).toEqual(["Not an id (32 hex digits): home."]); - const many = Array.from({ length: 11 }, (_, i) => i.toString(16).padStart(32, "0")); - expect( - sourceFormProblems({ - ...f, - pages: many.join("\n"), - databases: many.map((id) => id.replace(/^0/, "f")).join("\n"), - }), - ).toEqual(["At most 20 pages and databases in all."]); - }); - it("sends Zoom meeting ids and rejects space ids and meeting links", () => { const zoom = { ...named, kind: "recording" as const, meetings: "81234567890" }; expect(sourceFormProblems(zoom)).toEqual([]); @@ -246,27 +128,6 @@ describe("the add form's other kinds", () => { expect(sourceFormProblems({ ...zoom, meetings: "" })).toEqual(["Add at least one meeting id."]); }); - it("sends only the chosen kind's config, so switching kinds keeps the other kinds' ids out of the body", () => { - const f = { ...named, folders: FOLDER, projects: PROJECT }; - expect(sourceAddBody("o", "x", f, true).config).toEqual({ - folder_ids: [FOLDER], - include: ["docs", "slides", "pdf", "pptx"], - }); - expect(sourceAddBody("o", "x", { ...f, kind: "linear" }, true).config).toEqual({ project_ids: [PROJECT] }); - expect(sourceFormFingerprint(f)).not.toBe(sourceFormFingerprint({ ...f, kind: "linear" })); - }); -}); - -describe("toggleInclude", () => { - it("keeps the options' order, so unticking and ticking again gives the same list", () => { - const defaults = emptySourceForm().include; - expect(defaults).not.toContain("docx"); - const without = toggleInclude(defaults, "docs"); - expect(without).toEqual(["slides", "pdf", "pptx"]); - expect(toggleInclude(without, "docs")).toEqual(defaults); - expect(toggleInclude(["pptx"], "pdf")).toEqual(["pdf", "pptx"]); - expect(toggleInclude(["docx"], "pdf")).toEqual(["pdf", "docx"]); - }); }); describe("retiredMessage", () => { @@ -281,15 +142,9 @@ describe("retiredMessage", () => { }); describe("kind words", () => { - it("names each served kind and its credential, and an unknown one by its wire name", () => { - expect(kindLabel("gdrive")).toBe("shared folder"); - expect(kindLabel("linear")).toBe("project documents"); - expect(kindLabel("notion")).toBe("pages"); + it("names recording and renders unsupported metadata without a runtime claim", () => { expect(kindLabel("recording")).toBe("meeting transcripts"); - expect(kindLabel("other")).toBe("other"); - expect(credentialLabel("linear")).toMatch(/^Read-only API key/); - expect(credentialLabel("notion")).toMatch(/^Integration token/); + for (const kind of ["gdrive", "linear", "notion", "other"]) expect(kindLabel(kind)).toBe(`Unsupported source (${kind})`); expect(credentialLabel("recording")).toMatch(/^Read-only credential/); - expect(credentialLabel("other")).toMatch(/^Credential/); }); }); diff --git a/frontend/src/lib/knowledgeSources.ts b/frontend/src/lib/knowledgeSources.ts index c77b1a3a61..2d3c2acd03 100644 --- a/frontend/src/lib/knowledgeSources.ts +++ b/frontend/src/lib/knowledgeSources.ts @@ -106,21 +106,15 @@ export const SYNC_OFF = "Sync is off on this deployment: sources are stored and /** What each kind reads, in the words the card uses. */ const KIND_LABEL: Record = { - gdrive: "shared folder", - linear: "project documents", - notion: "pages", recording: "meeting transcripts", }; export function kindLabel(kind: string): string { - return KIND_LABEL[kind] ?? kind; + return KIND_LABEL[kind] ?? `Unsupported source (${kind})`; } /** The credential field's label for a kind, in the add and rotate forms. */ const CREDENTIAL_LABEL: Record = { - gdrive: "Service account key (JSON; stored encrypted, never shown again)", - linear: "Read-only API key (stored encrypted, never shown again)", - notion: "Integration token (stored encrypted, never shown again)", recording: "Read-only credential (JSON; stored encrypted, never shown again)", }; @@ -160,9 +154,9 @@ export function syncBadge(sync: KnowledgeSourceSync): SyncBadge { return { text: "Synced with a note", tone: "warn", tip: `The last sync noted: ${sync.error}.` }; case "provider_removed": return { - text: "Meet sync retired", + text: "Provider unavailable", tone: "warn", - tip: "Add a Shared folder source for Meet transcripts and notes. Existing documents stay unless you ask to delete them.", + tip: "This provider is unavailable. Retained bytes and history do not grant current access.", }; case "rate_limited": return { text: "Rate limited", tone: "warn", tip: "The source limited the last sync; the next one retries." }; @@ -215,114 +209,31 @@ export function unconvertedDetail(reasons: Record): string { // The add form // --------------------------------------------------------------------------- -/** The kinds the add form serves, in the order the form offers them. */ -const SOURCE_KINDS = ["gdrive", "linear", "notion", "recording"] as const; -type SourceKind = (typeof SOURCE_KINDS)[number]; - -/** What the form says about each kind: the dialog's description, what a passed check - * read, and what to ask for when no credential is typed. */ -export const KIND_FORM: Record = { - gdrive: { - about: - "A shared folder of documents, presentations, PDFs, .pptx decks and .docx documents, including Meet notes and transcripts saved as documents. Share it read-only with a service account and paste the account's key; Loom checks the key and the folders before anything is stored.", - reads: "The key reads the folders", - noCredential: "Paste the service account's key.", - }, - linear: { - about: - "The documents of a project tracker's projects. Paste a read-only API key of an account that sees the projects; Loom checks the key and the projects before anything is stored.", - reads: "The key reads the projects", - noCredential: "Paste the read-only API key.", - }, - notion: { - about: - "A page store's pages and databases. Share them with an integration that has read content access and paste its token; Loom checks the token and every page and database before anything is stored.", - reads: "The token reads the pages and databases", - noCredential: "Paste the integration token.", - }, +/** Recording setup is separate from generic MCP document sources. */ +export const KIND_FORM = { recording: { - about: - "Zoom cloud recording transcripts. Paste a server-to-server app's JSON credential (account_id, client_id, client_secret) with read-only scopes; Loom checks it and every meeting id before anything is stored. For Meet notes and transcripts, choose Shared folder.", + about: "Zoom cloud recording transcripts. Paste a server-to-server app's JSON credential (account_id, client_id, client_secret) with read-only scopes; Loom checks it and every meeting id before anything is stored.", reads: "The credential reads the meetings", noCredential: "Paste the read-only credential.", }, }; -/** Add choices name the active stores; stored recordings keep their generic kind label. */ -export const KIND_OPTIONS = SOURCE_KINDS.map((k) => { - const label = k === "recording" ? "Zoom transcripts" : kindLabel(k); - return { value: k, label: label.charAt(0).toUpperCase() + label.slice(1) }; -}); - -/** The file kinds a shared folder's `include` takes, with the words the form shows. */ -export const INCLUDE_OPTIONS = [ - { value: "docs", label: "Documents" }, - { value: "slides", label: "Presentations" }, - { value: "pdf", label: "PDF files" }, - { value: "pptx", label: ".pptx decks" }, - { value: "docx", label: ".docx documents" }, -] as const; - -/** The kinds a folder takes unless its form says otherwise: the server's default - * `include` (GDRIVE_DEFAULT_INCLUDE), which leaves .docx out. */ -export const DEFAULT_INCLUDE = ["docs", "slides", "pdf", "pptx"] as const; - -/** Each kind's id fields live side by side, so switching the kind keeps them; only the - * chosen kind's are sent, and the credential is cleared. */ export interface SourceForm { name: string; - kind: SourceKind; - /** gdrive: folder ids or folder links, one per line or comma-separated. */ - folders: string; - include: string[]; - /** linear: project ids (UUIDs). */ - projects: string; - /** notion: page ids and database ids, or their links. */ - pages: string; - databases: string; - /** recording: Zoom meeting ids. */ + kind: "recording"; meetings: string; - /** Held in the dialog only: sent with add, never shown back. */ credential: string; } -/** `include` with `kind` ticked or unticked, always in INCLUDE_OPTIONS order, so a box - * unticked and ticked again gives the form the check passed. */ -export function toggleInclude(include: readonly string[], kind: string): string[] { - const next = include.includes(kind) ? include.filter((k) => k !== kind) : [...include, kind]; - return INCLUDE_OPTIONS.map((o) => o.value).filter((v) => next.includes(v)); -} - export function emptySourceForm(): SourceForm { - return { - name: "", - kind: "gdrive", - folders: "", - include: [...DEFAULT_INCLUDE], - projects: "", - pages: "", - databases: "", - meetings: "", - credential: "", - }; + return { name: "", kind: "recording", meetings: "", credential: "" }; } -// The server's rules (server/knowledge/domain/sources.py), checked here so Check stays -// off until the server would read the config; the server checks them again. const NAME_RE = /^[a-z][a-z0-9_-]{1,31}$/; -const FOLDER_ID_RE = /^[A-Za-z0-9_-]{10,128}$/; -const PROJECT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; -const PAGE_ID_RE = /^[0-9a-f]{32}$/; const MEETING_ID_RE = /^[0-9]{9,12}$/; -// Each kind takes 1 to 20 ids; a page store's pages and databases count together. const MAX_IDS = 20; - -// What separates the ids typed into a field: any space, comma or line break; a meeting -// id is shown with spaces inside it, so its field splits on commas and lines only. -const ANY_SPACE = /[\s,]+/; const LINES = /[\r\n,]+/; -/** The pieces of what was typed, each normalised, empty ones and duplicates dropped. */ function pieces(text: string, separators: RegExp, normal: (piece: string) => string): string[] { const out: string[] = []; for (const piece of text.split(separators)) { @@ -332,59 +243,7 @@ function pieces(text: string, separators: RegExp, normal: (piece: string) => str return out; } -/** The folder ids in what was typed: a bare id, or the id after `/folders/` in a pasted - * folder link. Duplicates are dropped, the order kept. */ -export function folderIds(text: string): string[] { - return pieces(text, ANY_SPACE, (p) => /\/folders\/([^/?#]+)/.exec(p)?.[1] ?? p); -} - -/** Project ids, lower-cased as the server stores them; any other piece (a pasted link) - * is kept as typed, so the form can name it. */ -export function projectIds(text: string): string[] { - return pieces(text, ANY_SPACE, (p) => (PROJECT_ID_RE.test(p.toLowerCase()) ? p.toLowerCase() : p)); -} - -/** A bare id (dashed or not), a peek link's `p=` (pages field), or the 32 hex digits ending - * a link's last path segment; a link in the wrong field, or anything else, is kept as - * typed so the form names it. Lower-case without dashes; the server stores it dashed. */ -function pageStoreId(piece: string, inPages: boolean): string { - if (!piece.includes("/")) return bareId(piece) || piece; - const page = inPages ? /[?&]p=([^&#]*)/.exec(piece)?.[1] : undefined; - if (page !== undefined) return bareId(page) || piece; - if (inPages ? isDatabaseLink(piece) : isPageLink(piece)) return piece; - // The id is the whole segment, or what follows the title's last `-`. - const segment = (piece.split(/[?#]/)[0] ?? "").replace(/\/+$/, "").split("/").pop() ?? ""; - return /(?:^|-)([0-9a-f]{32})$/.exec(segment.toLowerCase())?.[1] ?? piece; -} - -/** A page store id with or without dashes as its 32 lower-case hex digits, or "". */ -function bareId(text: string): string { - const hexes = text.toLowerCase().replace(/-/g, ""); - return PAGE_ID_RE.test(hexes) ? hexes : ""; -} - -/** A link to a database's view: a `v=` and no `p=`. */ -function isDatabaseLink(piece: string): boolean { - return /[?&]v=/.test(piece) && !/[?&]p=/.test(piece); -} - -/** A peek link to a page from its parent page: a `p=` and no `v=`. */ -function isPageLink(piece: string): boolean { - return /[?&]p=/.test(piece) && !/[?&]v=/.test(piece); -} - -/** Page ids; a peek link gives the page it opens. */ -export function pageIds(text: string): string[] { - return pieces(text, ANY_SPACE, (p) => pageStoreId(p, true)); -} - -/** Database ids; a peek link gives its database, never the page it opens. */ -export function databaseIds(text: string): string[] { - return pieces(text, ANY_SPACE, (p) => pageStoreId(p, false)); -} - -/** Zoom meeting ids with the spaces they are shown with dropped (`812 3456 7890`). - * Any other piece is kept as typed, so the form can name it. */ +/** Recording meeting IDs may include spaces between digit groups. */ export function meetingIds(text: string): string[] { return pieces(text, LINES, (p) => { const digits = p.replace(/\s+/g, ""); @@ -419,61 +278,18 @@ function idProblems(ids: string[], re: RegExp, what: string, notOne: string): st return problems; } -function configProblems(f: SourceForm): string[] { - switch (f.kind) { - case "gdrive": { - const problems = idProblems(folderIds(f.folders), FOLDER_ID_RE, "folder", "a folder id"); - if (f.include.length === 0) problems.push("Pick at least one file kind."); - return problems; - } - case "linear": - return idProblems(projectIds(f.projects), PROJECT_ID_RE, "project", "a project id (a UUID)"); - case "notion": { - const pages = pageIds(f.pages); - const databases = databaseIds(f.databases); - const all = [...pages, ...databases]; - if (all.length === 0) return ["Add at least one page or database."]; - const problems = all.length > MAX_IDS ? [`At most ${MAX_IDS} pages and databases in all.`] : []; - const linked = pages.filter(isDatabaseLink); - if (linked.length > 0) problems.push(`Paste a database link under Databases: ${linked.join(", ")}.`); - const pageLinks = databases.filter(isPageLink); - if (pageLinks.length > 0) problems.push(`Paste a page link under Pages: ${pageLinks.join(", ")}.`); - const bad = all.filter((id) => !PAGE_ID_RE.test(id) && !linked.includes(id) && !pageLinks.includes(id)); - if (bad.length > 0) problems.push(`Not an id (32 hex digits): ${bad.join(", ")}.`); - return problems; - } - case "recording": - return zoomProblems(meetingIds(f.meetings)); - } -} - -/** What keeps the form from being checked, one line each; [] when it can be. */ export function sourceFormProblems(f: SourceForm): string[] { const problems: string[] = []; if (!NAME_RE.test(normalisedName(f.name))) problems.push("Name: 2-32 lower-case letters, digits, - or _, starting with a letter."); - problems.push(...configProblems(f)); + problems.push(...zoomProblems(meetingIds(f.meetings))); if (!f.credential.trim()) problems.push(KIND_FORM[f.kind].noCredential); return problems; } -/** The chosen kind's config, in the keys the server reads for it. */ -function sourceConfig(f: SourceForm): Record { - switch (f.kind) { - case "gdrive": - return { folder_ids: folderIds(f.folders), include: [...f.include] }; - case "linear": - return { project_ids: projectIds(f.projects) }; - case "notion": - return { page_ids: pageIds(f.pages), database_ids: databaseIds(f.databases) }; - case "recording": - return { provider: "zoom", ids: meetingIds(f.meetings) }; - } -} - -/** Whether anything but the kind was typed, so the problems list can wait. */ +/** Show validation once a recording field has been touched. */ export function sourceFormTouched(f: SourceForm): boolean { - return [f.name, f.folders, f.projects, f.pages, f.databases, f.meetings, f.credential].some((v) => v !== ""); + return [f.name, f.meetings, f.credential].some((v) => v !== ""); } export function sourceAddBody(org: string, namespace: string, f: SourceForm, dryRun: boolean) { @@ -481,8 +297,8 @@ export function sourceAddBody(org: string, namespace: string, f: SourceForm, dry org, namespace, name: normalisedName(f.name), - kind: f.kind, - config: sourceConfig(f), + kind: "recording", + config: { provider: "zoom", ids: meetingIds(f.meetings) }, credential: f.credential.trim(), dry_run: dryRun, }; diff --git a/frontend/src/lib/state.ts b/frontend/src/lib/state.ts index 3c36d1cda8..48bd5c6285 100644 --- a/frontend/src/lib/state.ts +++ b/frontend/src/lib/state.ts @@ -19,7 +19,6 @@ export type View = | "code" | "tasks" | "setup" - | "connected-accounts" | "admin:review_queue" | "admin:health" | "admin:guardrails" @@ -44,7 +43,6 @@ export const ALL_VIEWS: View[] = [ "code", "tasks", "setup", - "connected-accounts", "admin:review_queue", "admin:health", "admin:guardrails", @@ -65,7 +63,6 @@ const CANONICAL_PATH: Partial> = { sharing: "flow", browse: "spaces", setup: "settings", - "connected-accounts": "settings/connected-accounts", }; /** View → URL path segment, e.g. "admin:health" → "admin/health". */ @@ -96,7 +93,6 @@ const VIEW_QUERY_KEYS: Partial> = { tasks: ["inbox", "task"], // Settings carries its open tab (`?tab=memory|system`). setup: ["tab"], - "connected-accounts": ["kind"], // The object open on a page rides its URL, so a deep link, a reload and Back reopen it: // the memory in the drawer, the document in the preview, the thread in the replay. memories: ["memory"], diff --git a/frontend/src/lib/vitals.protection.test.ts b/frontend/src/lib/vitals.protection.test.ts new file mode 100644 index 0000000000..d7675879df --- /dev/null +++ b/frontend/src/lib/vitals.protection.test.ts @@ -0,0 +1,22 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { dashboardFetch } from "./dashboardTransport"; +import { flushView, startView } from "./vitals"; + +vi.mock("./dashboardSessionProtection", async () => { + const { SessionProtection } = await import("../../../sdk/typescript/src/session-protection.js"); + const family = new SessionProtection({ read: async () => "protected", mark: async () => {} }); + return { dashboardSessionProtection: async () => family }; +}); + +afterEach(() => vi.unstubAllGlobals()); + +it("guards automatic telemetry with the retained protected family", async () => { + const fetch = vi.fn(async () => new Response("{}", { headers: { "Content-Type": "application/json" } })); + vi.stubGlobal("fetch", fetch); + startView("knowledge"); + flushView({ org: "one", namespace: "one" }, "build"); + // Joining another automatic invocation uses the same opening family and guard. + await expect(dashboardFetch("/v1/ui.vitals", { method: "POST", body: "{}" })) + .rejects.toMatchObject({ name: "AutomaticCaptureSuppressed" }); + expect(fetch).not.toHaveBeenCalled(); +}); diff --git a/frontend/src/lib/vitals.test.ts b/frontend/src/lib/vitals.test.ts index 89efaee5bd..b675351fe8 100644 --- a/frontend/src/lib/vitals.test.ts +++ b/frontend/src/lib/vitals.test.ts @@ -3,6 +3,11 @@ import { _resetVitals, flushView, installVitals, startView } from "./vitals"; import { noteCallEnd, noteCallStart } from "./vitalsCounter"; import { setPageOwner, setToken } from "../api"; +// Payload assertions observe dispatch input; the protection test exercises the real guard. +vi.mock("./dashboardTransport", () => ({ + dashboardFetch: (input: string, init: RequestInit) => globalThis.fetch(input, init), +})); + // One ui.vitals row per page view, posted when the view ends, carrying the route, the // view's call count and span, the DOM size and the build; LCP only on the first view of // the document. diff --git a/frontend/src/lib/vitals.ts b/frontend/src/lib/vitals.ts index 445667e3b2..6fc53cc9dc 100644 --- a/frontend/src/lib/vitals.ts +++ b/frontend/src/lib/vitals.ts @@ -4,6 +4,7 @@ // hiding), never inside the view's own measured window. Every observer is optional: a // browser without one reports what it has. import { authHeader, ownsToken, storedToken, UI_CONSUMER } from "../api"; +import { dashboardFetch } from "./dashboardTransport"; import { readCalls, resetCalls } from "./vitalsCounter"; type Identity = { org: string; namespace: string }; @@ -86,7 +87,7 @@ export function flushView(identity: Identity | null, build: string): void { // Nothing of this page goes out under another person's token (another tab's sign-in). if (!ownsToken(storedToken())) return; try { - void fetch("/v1/ui.vitals", { + void dashboardFetch("/v1/ui.vitals", { method: "POST", keepalive: true, headers: { "Content-Type": "application/json", ...authHeader() }, diff --git a/frontend/src/test/mcpSources.ts b/frontend/src/test/mcpSources.ts new file mode 100644 index 0000000000..e87be30538 --- /dev/null +++ b/frontend/src/test/mcpSources.ts @@ -0,0 +1,36 @@ +import type { MCPAccessRule, MCPConnection, MCPDiscovery, MCPPreview, MCPProfile, MCPSource, MCPSourceResult, MCPSourceSummary } from "../api/mcpSources"; + +export const mcpProfile: MCPProfile = { + id: "approved", label: "Approved remote server", auth: "bearer", endpoint_origin: "https://source.example", + profile_sha256: "profile-digest", approved_tools: ["read_selected"], allow_collection_copy: true, +}; +export const mcpConnection: MCPConnection = { + slot: "00000000-0000-4000-8000-000000000001", generation: "generation-a", state: "configured", + profile_id: "approved", profile_sha256: "profile-digest", label: "My connection", + compatibility: "unchecked", remote_identity_verified: false, +}; +export const mcpDiscovery: MCPDiscovery = { + slot: mcpConnection.slot, generation: mcpConnection.generation, resources: true, mapped_read: false, + mapped_search: false, supported_reads: true, limitations: ["No complete enumeration"], remote_identity_verified: false, +}; +export const mcpRule: MCPAccessRule = { + access: "owner_only", reason: "private_source", stores_copy: true, future_items_included: false, + upstream_permissions: "unsupported", reader_list_complete: false, collection_readers_receive_copy: false, + inherited_grants_apply: true, membership_changes_affect_copy: false, publication_confirmation_required: false, + explanation: "Only the signed-in source owner can read this source, including in a team collection.", +}; +export const mcpPreviewValue: MCPPreview = { + namespace: "col-team", mode: "snapshot", rule: mcpRule, connection_state: "configured", + compatibility: "unchecked", permission_evidence: "unsupported", refresh_state: "not_applicable", selected_count: 1, + checked_at: "2026-01-01T00:00:00Z", read_evidence_stale_seconds: 300, preview_grants_authority: false, limitations: ["Remote ACL synchronization is unsupported"], +}; +export const mcpSummary: MCPSourceSummary = { + name: "mcp-registration", source_id: "source-id", slot: mcpConnection.slot, namespace: "col-team", + state: "registered", mode: "snapshot", reader_policy: "owner_only", scope_revision: 4, label: "Private documents", + selected_count: 1, sync_enabled: false, read_evidence_stale_seconds: 300, refresh_state: "disabled", compatibility: "unchecked", + upstream_permissions: "unsupported", complete_enumeration: false, upstream_deletion_tracking: false, + future_items_included: false, current_access_attested: false, local_authority: "current", pending_erasure: false, + rule: mcpRule, +}; +export const mcpSource: MCPSource = { ...mcpSummary, resource_ids: ["opaque://A?x=%2F"] }; +export const mcpResult: MCPSourceResult = { source: mcpSource, copies: "retained", refresh_requested: false }; diff --git a/frontend/src/views/Browse.rows.test.tsx b/frontend/src/views/Browse.rows.test.tsx index b73439b2b9..a16e5dae7c 100644 --- a/frontend/src/views/Browse.rows.test.tsx +++ b/frontend/src/views/Browse.rows.test.tsx @@ -184,7 +184,7 @@ describe("Namespaces in your org: the rows", () => { // beta's guide opens from its summary link, so its menu does not offer it twice. expect(within(menu).queryByRole("menuitem", { name: "Guide" })).toBeNull(); await user.click(within(menu).getByRole("menuitem", { name: "Leave" })); - await waitFor(() => expect(leaveNamespace).toHaveBeenCalledWith("acme", "beta")); + await waitFor(() => expect(leaveNamespace).toHaveBeenCalledWith("acme", "beta", "explicit")); }); it("your personal namespace offers its guide like any namespace you manage", async () => { @@ -378,7 +378,7 @@ describe("Namespaces in your org: requesting a private namespace by name", () => "No listed public namespace named support.", ); await userEvent.click(screen.getByRole("button", { name: "Request access" })); - expect(joinNamespace).toHaveBeenCalledWith("acme", "support", { role: "viewer" }); + expect(joinNamespace).toHaveBeenCalledWith("acme", "support", { role: "viewer" }, "explicit"); }); it("says nothing matches a search that is no namespace name, and offers no request", async () => { @@ -642,7 +642,7 @@ describe("Namespaces in your org: requesting a private namespace by name", () => await userEvent.type(box, "secret-ops"); await userEvent.click(await screen.findByRole("button", { name: "Request access" })); await waitFor(() => expect(box).toHaveValue("")); - expect(joinNamespace).toHaveBeenCalledWith("acme", "secret-ops", { role: "viewer" }); + expect(joinNamespace).toHaveBeenCalledWith("acme", "secret-ops", { role: "viewer" }, "explicit"); // The card names the deferred text, so it leaves a render after the box empties. await waitFor(() => expect(screen.queryByRole("button", { name: "Request access" })).toBeNull()); }); diff --git a/frontend/src/views/Browse.tsx b/frontend/src/views/Browse.tsx index 1971935694..1bf52d34f1 100644 --- a/frontend/src/views/Browse.tsx +++ b/frontend/src/views/Browse.tsx @@ -159,7 +159,7 @@ export function Browse() { const onJoin = async (ns: string, role: JoinRole) => { setJoining(ns); try { - const r = await joinNamespace(identity.org, ns, { role }); + const r = await joinNamespace(identity.org, ns, { role }, "explicit"); const isPending = r.status === "pending"; if (isPending) { const admins = (r.pending_admins || []).slice(0, 3).join(", ") || "an admin"; @@ -262,7 +262,7 @@ export function Browse() { ) return; try { - await cancelNamespaceRequest(identity.org, ns); + await cancelNamespaceRequest(identity.org, ns, "explicit"); toast(`Withdrew request on ${ns}`, "ok"); load(); } catch (e) { @@ -280,7 +280,7 @@ export function Browse() { ) return; try { - await leaveNamespace(identity.org, ns); + await leaveNamespace(identity.org, ns, "explicit"); toast(`Left ${ns}`, "ok"); load(); } catch (e) { @@ -950,7 +950,7 @@ function RequestAccessCard({ setBusy(true); setError(null); try { - const r = await joinNamespace(org, typedName, { role }); + const r = await joinNamespace(org, typedName, { role }, "explicit"); if (r.status === "pending") { const admins = (r.pending_admins || []).slice(0, 3).join(", ") + ((r.pending_admins?.length || 0) > 3 ? ", …" : ""); diff --git a/frontend/src/views/Code.tsx b/frontend/src/views/Code.tsx index ebbbff556c..cff2f042cb 100644 --- a/frontend/src/views/Code.tsx +++ b/frontend/src/views/Code.tsx @@ -255,7 +255,7 @@ function useJoinActions(onChanged: () => void) { const join = async (r: CodeRepoSummary, role: RepoRole = "viewer") => { setBusy(r.namespace); try { - if (await joinTarget(branchTarget(r), role)) onChanged(); + if (await joinTarget(branchTarget(r), role, "explicit")) onChanged(); } finally { setBusy(null); } @@ -263,7 +263,7 @@ function useJoinActions(onChanged: () => void) { const cancel = async (r: CodeRepoSummary) => { setBusy(r.namespace); try { - if (await withdrawTarget(branchTarget(r))) onChanged(); + if (await withdrawTarget(branchTarget(r), "explicit")) onChanged(); } finally { setBusy(null); } @@ -271,7 +271,7 @@ function useJoinActions(onChanged: () => void) { const leave = async (r: CodeRepoSummary) => { setBusy(r.namespace); try { - if (await leaveTarget(branchTarget(r))) onChanged(); + if (await leaveTarget(branchTarget(r), "explicit")) onChanged(); } finally { setBusy(null); } @@ -293,7 +293,7 @@ function useJoinActions(onChanged: () => void) { failed = 0; for (const b of plan.join) { try { - const res = await joinNamespace(b.org, b.namespace, { role: "viewer" }); + const res = await joinNamespace(b.org, b.namespace, { role: "viewer" }, "explicit"); if (res.status === "pending") requested++; else joined++; } catch { @@ -302,7 +302,7 @@ function useJoinActions(onChanged: () => void) { } for (const b of plan.leave) { try { - await leaveNamespace(b.org, b.namespace); + await leaveNamespace(b.org, b.namespace, "explicit"); left++; } catch { failed++; @@ -310,7 +310,7 @@ function useJoinActions(onChanged: () => void) { } for (const b of plan.withdraw) { try { - await cancelNamespaceRequest(b.org, b.namespace); + await cancelNamespaceRequest(b.org, b.namespace, "explicit"); withdrawn++; } catch { failed++; @@ -490,7 +490,7 @@ function RepositoriesHome({ const bindSource = async (g: RepoGroup, tracker_namespaces: string[]) => { try { - const out = await setCodeRepoSource(g.primary.org, g.primary.namespace, tracker_namespaces); + const out = await setCodeRepoSource(g.primary.org, g.primary.namespace, tracker_namespaces, "explicit"); toast(...linkedToast(g.primary.repo, out)); onChanged(); } catch (e) { @@ -499,7 +499,7 @@ function RepositoriesHome({ }; const refreshBranch = async (b: CodeRepoSummary) => { try { - const r = await codeRefresh({ org: b.org, namespace: b.namespace }); + const r = await codeRefresh({ org: b.org, namespace: b.namespace }, "explicit"); toast( r.already_running ? `An ingest pass is already running on ${b.repo} @ ${b.branch}` @@ -521,7 +521,7 @@ function RepositoriesHome({ ) return; try { - const out = await removeCodeRepo(b.org, b.namespace); + const out = await removeCodeRepo(b.org, b.namespace, "explicit"); toast(`Retired ${out.repo} @ ${out.branch} · its rows are purging in the background`, "ok"); onChanged(); } catch (e) { @@ -553,7 +553,7 @@ function RepositoriesHome({ let done = 0; for (const b of mine) { try { - await setCodeRepoAccess(b.org, b.namespace, classification, join_policy, opening ? b.namespace : ""); + await setCodeRepoAccess(b.org, b.namespace, classification, join_policy, opening ? b.namespace : "", "explicit"); done += 1; } catch (e) { toastError(`Couldn't change access on ${b.namespace}`, e); @@ -1259,7 +1259,7 @@ export function AddRepositoryDialog({ exclude_generated: skipGenerated, scip_producer: producer, branches: others, - }); + }, "explicit"); const n = 1 + (out.also?.length ?? 0); const skipped = out.skipped?.length ? `; ${out.skipped.length} branch${out.skipped.length === 1 ? "" : "es"} refused: ${out.skipped.map((x) => x.branch).join(", ")}` @@ -1626,7 +1626,7 @@ function AddBranchDialog({ setBusy(true); setError(null); try { - const out = await addCodeBranch(src.org, src.namespace, branch.trim()); + const out = await addCodeBranch(src.org, src.namespace, branch.trim(), "explicit"); toast(`Added ${out.repo} @ ${out.branch} — it shares the mirror, indexing starts within two minutes`, "ok"); onOpenChange(false); onAdded(); @@ -1996,7 +1996,7 @@ export function HealthTab({ id, repo }: { id: CodeId; repo: CodeRepoSummary }) { if (refreshReason) return; setRefreshing(true); try { - const r = await codeRefresh(id); + const r = await codeRefresh(id, "explicit"); toast(r.already_running ? "An ingest pass is already running" : "Ingest pass triggered", "ok"); setTimeout(load, 2500); } catch (e) { @@ -3144,7 +3144,7 @@ export function AccessTab({ return; setBusy("rule"); try { - await reregisterNamespace(id, ns, { join_policy: next }); + await reregisterNamespace(id, ns, { join_policy: next }, "explicit"); toast(`${id.namespace} is now ${RULE_META[next].label.toLowerCase()}`, "ok"); load(); } catch (err) { @@ -3157,7 +3157,7 @@ export function AccessTab({ const decide = async (g: GrantEntry, decision: "approve" | "reject", as?: RepoRole) => { setBusy(g.subject); try { - await approveGrant(id, g.subject, decision, as); + await approveGrant(id, g.subject, decision, as, "explicit"); const granted = as ?? askedFor(g); toast( decision === "approve" @@ -3180,7 +3180,7 @@ export function AccessTab({ let ok = 0; for (const g of waiting) { try { - await approveGrant(id, g.subject, "approve"); + await approveGrant(id, g.subject, "approve", undefined, "explicit"); ok++; } catch { /* keep going */ @@ -3197,7 +3197,7 @@ export function AccessTab({ if (!s || !canManage) return; setBusy("add"); try { - await createGrant(id, s, role); + await createGrant(id, s, role, undefined, "explicit"); toast(`${s} is now a ${roleWord(role)}`, "ok"); setSubject(""); load(); @@ -3219,7 +3219,7 @@ export function AccessTab({ ) return; try { - await revokeGrant(id, g.subject); + await revokeGrant(id, g.subject, "explicit"); toast(`Removed ${g.subject}`, "ok"); load(); } catch (err) { @@ -3271,7 +3271,7 @@ export function AccessTab({ let ok = 0; for (const t of targets) { try { - await approveGrant(t, g.subject, "approve"); + await approveGrant(t, g.subject, "approve", undefined, "explicit"); ok++; } catch { /* keep going */ @@ -3657,7 +3657,7 @@ export function AccessTab({ return; setBusy("retire"); try { - const out = await removeCodeRepo(id.org, id.namespace); + const out = await removeCodeRepo(id.org, id.namespace, "explicit"); toast( `Retired ${out.repo} @ ${out.branch} · ${out.purged_tables} tables purging as erasure ${out.erasure_id.slice(0, 8)}${out.mirror_removed ? " · mirror removed" : ""}`, "ok", diff --git a/frontend/src/views/CollectionSharing.test.tsx b/frontend/src/views/CollectionSharing.test.tsx index ed5ec173e8..5025212c75 100644 --- a/frontend/src/views/CollectionSharing.test.tsx +++ b/frontend/src/views/CollectionSharing.test.tsx @@ -669,14 +669,14 @@ describe("the collection header", () => { "approval", async (dialog) => { fireEvent.click(within(dialog).getByRole("button", { name: /^Approve as/ })); - await waitFor(() => expect(api.approveGrant).toHaveBeenCalledWith(expect.anything(), "carol", "approve")); + await waitFor(() => expect(api.approveGrant).toHaveBeenCalledWith(expect.anything(), "carol", "approve", undefined, "explicit")); }, ], [ "rejection", async (dialog) => { fireEvent.click(within(dialog).getByRole("button", { name: "Reject" })); - await waitFor(() => expect(api.approveGrant).toHaveBeenCalledWith(expect.anything(), "carol", "reject")); + await waitFor(() => expect(api.approveGrant).toHaveBeenCalledWith(expect.anything(), "carol", "reject", undefined, "explicit")); }, ], ]; diff --git a/frontend/src/views/ConnectedAccounts.test.tsx b/frontend/src/views/ConnectedAccounts.test.tsx deleted file mode 100644 index 319bff6fdd..0000000000 --- a/frontend/src/views/ConnectedAccounts.test.tsx +++ /dev/null @@ -1,269 +0,0 @@ -import { StrictMode } from "react"; -import userEvent from "@testing-library/user-event"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { act, cleanup, render, screen, waitFor } from "../test/rtl"; -import { axeViolations } from "../test/axe"; -import * as api from "../api/connections"; -import { confirmAction } from "../components/ConfirmDialog"; -import { toast, toastError } from "../components/Toast"; -import { canCallOwnConnections } from "../lib/canCall"; -import { goToConnectionConsent } from "../lib/navigation"; -import { navigationHref, pathnameView, useStore } from "../lib/state"; -import { ConnectedAccounts } from "./ConnectedAccounts"; - -vi.mock("../api/connections", async (original) => ({ - ...(await original()), - listConnections: vi.fn(), - startConnection: vi.fn(), - disconnectConnection: vi.fn(), -})); -vi.mock("../components/ConfirmDialog", () => ({ confirmAction: vi.fn(async () => true) })); -vi.mock("../components/Toast", () => ({ toast: vi.fn(), toastError: vi.fn() })); -vi.mock("../lib/navigation", () => ({ goToConnectionConsent: vi.fn() })); - -function entries(email = "reader@example.com"): api.ConnectionEntry[] { - return api.CONNECTION_KINDS.map((kind) => ({ - kind, - connected: kind === "gdrive", - account_email: kind === "gdrive" ? email : null, - scopes: ["private-scope-proof"], - connect_url: `/settings/connected-accounts?kind=${kind}`, - })); -} - -function pending() { - let resolve!: (value: T) => void; - let reject!: (reason: unknown) => void; - const promise = new Promise((yes, no) => { - resolve = yes; - reject = no; - }); - return { promise, resolve, reject }; -} - -function account(subject = "reader", org = "acme") { - useStore.setState({ - authed: true, - sessionExpired: false, - identity: { org, namespace: "", agent: "loom-ui" }, - whoami: { authenticated: true, subject, org, roles: ["viewer"] }, - view: "connected-accounts", - deniedNamespace: null, - }); -} - -beforeEach(() => { - vi.resetAllMocks(); - history.replaceState(null, "", "/settings/connected-accounts?kind=notion"); - account(); - vi.mocked(api.listConnections).mockResolvedValue({ connections: entries() }); - vi.mocked(api.startConnection).mockResolvedValue({ - authorization_url: "https://consent.example/authorize?state=consent-proof", - }); - vi.mocked(api.disconnectConnection).mockResolvedValue({ disconnected: true }); - vi.mocked(confirmAction).mockResolvedValue(true); -}); -afterEach(() => { - cleanup(); - useStore.setState({ whoami: null, identity: null, authed: false }); -}); - -describe("Connected accounts", () => { - it("resolves the public deep link, drops unrelated keys, and focuses the requested provider", async () => { - expect(pathnameView()).toBe("connected-accounts"); - history.replaceState(null, "", "/settings/connected-accounts?kind=notion&state=drop&code=drop"); - expect(navigationHref("connected-accounts")).toBe("/settings/connected-accounts?kind=notion"); - render(); - await screen.findByText("reader@example.com"); - await waitFor(() => expect(screen.getByRole("heading", { name: "Notion" })).toHaveFocus()); - expect(api.startConnection).not.toHaveBeenCalled(); - await userEvent.click(screen.getByRole("button", { name: "Back to settings" })); - expect(useStore.getState().view).toBe("setup"); - }); - - it("shows three statuses and only supplied emails, without scopes or credential controls", async () => { - const { container } = render(); - await screen.findByText("reader@example.com"); - expect(screen.getAllByText("Connected", { exact: true })).toHaveLength(1); - expect(screen.getAllByText("Not connected", { exact: true })).toHaveLength(2); - expect(screen.queryByText("private-scope-proof")).toBeNull(); - expect(container.querySelector("input")).toBeNull(); - expect(api.listConnections).toHaveBeenCalledWith("acme", { signal: expect.any(AbortSignal) }); - expect(await axeViolations(container)).toEqual([]); - }); - - it("reads a personal viewer's connections without a namespace and refuses other known identities", () => { - const whoami = useStore.getState().whoami; - expect(canCallOwnConnections(whoami)).toBe(true); - for (const identity of [ - null, - { authenticated: false }, - { ...whoami, authenticated: true, is_service_account: true }, - { ...whoami, authenticated: true, org: "*" }, - ]) { - expect(canCallOwnConnections(identity)).toBe(false); - } - }); - - it("starts consent only after a click and keeps the URL out of dashboard history and storage", async () => { - render( - - - , - ); - await userEvent.click(await screen.findByRole("button", { name: "Connect Notion" })); - await waitFor(() => - expect(goToConnectionConsent).toHaveBeenCalledWith("https://consent.example/authorize?state=consent-proof"), - ); - const opts = vi.mocked(api.startConnection).mock.calls[0][1]; - expect(opts?.signal?.aborted).toBe(false); - expect(location.search).toBe("?kind=notion"); - expect(JSON.stringify(localStorage)).not.toContain("consent-proof"); - expect(JSON.stringify(sessionStorage)).not.toContain("consent-proof"); - expect(screen.queryByText(/consent-proof/)).toBeNull(); - }); - - it("offers reconnect through the same consent route", async () => { - render(); - await userEvent.click(await screen.findByRole("button", { name: "Reconnect Google Drive" })); - expect(api.startConnection).toHaveBeenCalledWith("gdrive", { signal: expect.any(AbortSignal) }); - }); - - it("confirms that disconnect stops owned sources, then refreshes status", async () => { - render(); - await userEvent.click(await screen.findByRole("button", { name: "Disconnect Google Drive" })); - expect(confirmAction).toHaveBeenCalledWith( - expect.objectContaining({ - message: "This stops your document sources that use this connection.", - confirmLabel: "Disconnect", - danger: true, - }), - ); - expect(api.disconnectConnection).toHaveBeenCalledWith("acme", "gdrive", { signal: expect.any(AbortSignal) }); - await waitFor(() => expect(api.listConnections).toHaveBeenCalledTimes(2)); - expect(toast).toHaveBeenCalledWith("Google Drive disconnected", "ok"); - }); - - it("does not disconnect when confirmation is cancelled", async () => { - vi.mocked(confirmAction).mockResolvedValue(false); - render(); - await userEvent.click(await screen.findByRole("button", { name: "Disconnect Google Drive" })); - expect(api.disconnectConnection).not.toHaveBeenCalled(); - }); - - it("reports consent and disconnect failures through the shared error presentation", async () => { - const failure = new Error("connection unavailable"); - vi.mocked(api.startConnection).mockRejectedValueOnce(failure); - vi.mocked(api.disconnectConnection).mockRejectedValueOnce(failure); - render(); - await userEvent.click(await screen.findByRole("button", { name: "Connect Notion" })); - await waitFor(() => expect(toastError).toHaveBeenCalledWith("Couldn't connect account", failure)); - await userEvent.click(screen.getByRole("button", { name: "Disconnect Google Drive" })); - await waitFor(() => expect(toastError).toHaveBeenCalledWith("Disconnect failed", failure)); - expect(screen.getByText("reader@example.com")).toBeInTheDocument(); - expect(goToConnectionConsent).not.toHaveBeenCalled(); - }); - - it("keeps pending and failed reads distinct from disconnected accounts and supports Retry", async () => { - const load = pending<{ connections: api.ConnectionEntry[] }>(); - vi.mocked(api.listConnections).mockReturnValueOnce(load.promise); - render(); - expect(screen.queryByText("Not connected")).toBeNull(); - await act(async () => load.reject(new Error("read failed"))); - expect(await screen.findByText("Couldn't load connected accounts")).toBeInTheDocument(); - await userEvent.click(screen.getByRole("button", { name: "Retry" })); - expect(await screen.findByText("reader@example.com")).toBeInTheDocument(); - }); - - it("keeps keyboard focus on Refresh and ignores another press while its read is pending", async () => { - const user = userEvent.setup(); - render(); - await screen.findByText("reader@example.com"); - const load = pending<{ connections: api.ConnectionEntry[] }>(); - vi.mocked(api.listConnections).mockReturnValueOnce(load.promise); - const refresh = screen.getByRole("button", { name: "Refresh" }); - screen.getByRole("button", { name: "Back to settings" }).focus(); - await user.tab(); - expect(refresh).toHaveFocus(); - await user.keyboard("{Enter}"); - await waitFor(() => expect(refresh).toHaveAttribute("aria-busy", "true")); - expect(refresh).not.toBeDisabled(); - expect(refresh).toHaveFocus(); - expect(screen.getByText("reader@example.com")).toBeInTheDocument(); - await user.keyboard("{Enter}"); - expect(api.listConnections).toHaveBeenCalledTimes(2); - await act(async () => load.resolve({ connections: entries("refreshed@example.com") })); - expect(await screen.findByText("refreshed@example.com")).toBeInTheDocument(); - expect(refresh).not.toHaveAttribute("aria-busy"); - expect(refresh).not.toBeDisabled(); - expect(refresh).toHaveFocus(); - }); - - it.each(["person", "organization"])("clears displayed and late data on a change of %s", async (change) => { - render(); - await screen.findByText("reader@example.com"); - const old = pending<{ connections: api.ConnectionEntry[] }>(); - vi.mocked(api.listConnections).mockReturnValueOnce(old.promise); - await userEvent.click(screen.getByRole("button", { name: "Refresh" })); - const oldSignal = vi.mocked(api.listConnections).mock.calls.at(-1)?.[1]?.signal; - const next = pending<{ connections: api.ConnectionEntry[] }>(); - vi.mocked(api.listConnections).mockReturnValueOnce(next.promise); - act(() => account(change === "person" ? "next-reader" : "reader", change === "organization" ? "next-org" : "acme")); - expect(screen.queryByText("reader@example.com")).toBeNull(); - expect(oldSignal?.aborted).toBe(true); - await act(async () => old.resolve({ connections: entries("old-private@example.com") })); - expect(screen.queryByText("old-private@example.com")).toBeNull(); - await act(async () => next.resolve({ connections: entries("next@example.com") })); - expect(await screen.findByText("next@example.com")).toBeInTheDocument(); - }); - - it("drops late consent navigation and aborts the action after an owner change", async () => { - const consent = pending<{ authorization_url: string }>(); - vi.mocked(api.startConnection).mockReturnValueOnce(consent.promise); - render(); - await userEvent.click(await screen.findByRole("button", { name: "Connect Linear" })); - const signal = vi.mocked(api.startConnection).mock.calls[0][1]?.signal; - act(() => account("next-reader")); - expect(signal?.aborted).toBe(true); - await act(async () => consent.resolve({ authorization_url: "https://consent.example/private" })); - expect(goToConnectionConsent).not.toHaveBeenCalled(); - }); - - it("does not send an old owner's disconnect after confirmation", async () => { - const confirm = pending(); - vi.mocked(confirmAction).mockReturnValueOnce(confirm.promise); - render(); - await userEvent.click(await screen.findByRole("button", { name: "Disconnect Google Drive" })); - act(() => account("next-reader")); - await act(async () => confirm.resolve(true)); - expect(api.disconnectConnection).not.toHaveBeenCalled(); - expect(toastError).not.toHaveBeenCalled(); - }); - - it("does not show a previous owner's late action failure", async () => { - const stop = pending<{ disconnected: boolean }>(); - vi.mocked(api.disconnectConnection).mockReturnValueOnce(stop.promise); - render(); - await userEvent.click(await screen.findByRole("button", { name: "Disconnect Google Drive" })); - act(() => account("next-reader")); - await act(async () => stop.reject(new Error("old owner's failure"))); - expect(toastError).not.toHaveBeenCalled(); - expect(toast).not.toHaveBeenCalled(); - }); - - it("makes no connection request for a service account", () => { - const whoami = useStore.getState().whoami; - useStore.setState({ whoami: { ...whoami, authenticated: true, is_service_account: true } }); - render(); - expect(screen.getByRole("status")).toHaveTextContent("Sign in with a personal account"); - expect(api.listConnections).not.toHaveBeenCalled(); - }); - - it("shows no previous account data or actions after session expiry", async () => { - render(); - await screen.findByText("reader@example.com"); - act(() => useStore.setState({ sessionExpired: true })); - expect(screen.queryByText("reader@example.com")).toBeNull(); - expect(screen.queryByRole("button", { name: "Disconnect Google Drive" })).toBeNull(); - }); -}); diff --git a/frontend/src/views/ConnectedAccounts.tsx b/frontend/src/views/ConnectedAccounts.tsx deleted file mode 100644 index 0466618784..0000000000 --- a/frontend/src/views/ConnectedAccounts.tsx +++ /dev/null @@ -1,217 +0,0 @@ -import { useEffect, useRef, useState } from "react"; -import { Badge } from "@clickhouse/click-ui/Badge"; -import { Button } from "@clickhouse/click-ui/Button"; -import { - CONNECTION_KINDS, - disconnectConnection, - listConnections, - startConnection, - type ConnectionEntry, - type ConnectionKind, -} from "../api/connections"; -import { confirmAction } from "../components/ConfirmDialog"; -import { toast, toastError } from "../components/Toast"; -import { Loading, PageHeader } from "../components/ui"; -import { BusyButton } from "../components/ui/BusyButton"; -import { ListState } from "../components/ui/ListState"; -import { SectionHeading } from "../components/ui/SectionHeading"; -import { PageContainer } from "../layout/PageContainer"; -import { canCallOwnConnections } from "../lib/canCall"; -import { useAbortableEffect, useMounted } from "../lib/hooks"; -import { goToConnectionConsent } from "../lib/navigation"; -import { urlParam, useStore } from "../lib/state"; - -const LABELS: Record = { gdrive: "Google Drive", notion: "Notion", linear: "Linear" }; - -export function ConnectedAccounts() { - const whoami = useStore((s) => s.whoami); - const org = useStore((s) => s.identity?.org ?? ""); - const authed = useStore((s) => s.authed); - const expired = useStore((s) => s.sessionExpired); - const setView = useStore((s) => s.setView); - const available = authed && !expired && canCallOwnConnections(whoami) && whoami?.org === org; - - return ( - - setView("setup")}> - Back to settings - - } - /> -

- Connect your own account to use it with document sources. These connections belong to you in this organization. -

- {available && whoami?.subject ? ( - - ) : ( -

- Sign in with a personal account to manage connected accounts. -

- )} -
- ); -} - -function OwnConnections({ org, subject }: { org: string; subject: string }) { - const mounted = useMounted(); - const actions = useRef(null); - useEffect(() => { - const controller = new AbortController(); - actions.current = controller; - return () => controller.abort(); - }, []); - const current = () => { - const s = useStore.getState(); - return ( - mounted.current && - s.authed && - !s.sessionExpired && - s.identity?.org === org && - s.whoami?.org === org && - s.whoami.subject === subject && - canCallOwnConnections(s.whoami) - ); - }; - const [connections, setConnections] = useState(null); - const [error, setError] = useState(null); - const [reading, setReading] = useState(true); - const [reload, setReload] = useState(0); - const [busy, setBusy] = useState<{ kind: ConnectionKind; disconnect: boolean } | null>(null); - const busyRef = useRef(false); - const navSeq = useStore((s) => s.navSeq); - const asked = urlParam("kind"); - const selected = CONNECTION_KINDS.find((kind) => kind === asked); - const providerList = useRef(null); - const focusProvider = (kind: ConnectionKind) => { - providerList.current?.querySelector(`#connection-${kind}`)?.focus(); - }; - useEffect(() => { - if (selected && connections) focusProvider(selected); - }, [selected, connections !== null, navSeq]); - - useAbortableEffect( - async (signal, live) => { - if (!current()) return; - setReading(true); - setError(null); - try { - const result = await listConnections(org, { signal }); - if (live() && current()) setConnections(result.connections); - } catch (e) { - if (live() && current()) setError(e); - } finally { - if (live() && current()) setReading(false); - } - }, - [org, subject, reload], - ); - - const act = async (entry: ConnectionEntry, disconnect: boolean) => { - if (busyRef.current || reading || !current()) return; - busyRef.current = true; - setBusy({ kind: entry.kind, disconnect }); - try { - if (disconnect) { - const confirmed = await confirmAction({ - title: `Disconnect ${LABELS[entry.kind]}?`, - message: "This stops your document sources that use this connection.", - confirmLabel: "Disconnect", - danger: true, - }); - if (!confirmed || !current()) return; - const result = await disconnectConnection(org, entry.kind, { signal: actions.current?.signal }); - if (!current()) return; - if (result.disconnected) { - focusProvider(entry.kind); - setConnections( - (rows) => - rows?.map((row) => - row.kind === entry.kind ? { ...row, connected: false, account_email: null, scopes: [] } : row, - ) ?? null, - ); - toast(`${LABELS[entry.kind]} disconnected`, "ok"); - } - setReload((n) => n + 1); - } else { - const result = await startConnection(entry.kind, { signal: actions.current?.signal }); - if (current()) goToConnectionConsent(result.authorization_url); - } - } catch (e) { - if (current()) toastError(disconnect ? "Disconnect failed" : "Couldn't connect account", e); - } finally { - busyRef.current = false; - if (current()) setBusy(null); - } - }; - - return ( -
-
- setReload((n) => n + 1)} - > - Refresh - -
- {!!error && ( - setReload((n) => n + 1)} /> - )} - {!error && connections === null && } - {!error && connections !== null && ( -
    - {CONNECTION_KINDS.map((kind) => { - const entry = connections.find((row) => row.kind === kind); - return ( -
  • -
    - - {entry?.connected && entry.account_email && ( -

    {entry.account_email}

    - )} - -
    - {entry && ( -
    - - {entry.connected && ( - - )} -
    - )} -
  • - ); - })} -
- )} -
- ); -} diff --git a/frontend/src/views/Conversations.tsx b/frontend/src/views/Conversations.tsx index 1752e9b391..ab0c25bd89 100644 --- a/frontend/src/views/Conversations.tsx +++ b/frontend/src/views/Conversations.tsx @@ -332,7 +332,7 @@ export function Conversations() { const gen = scopeGen.current; setLoggingEnabled(next); // optimistic try { - await setConversationLogging(identity, next); + await setConversationLogging(identity, next, "explicit"); toast(next ? "Conversation recording on" : "Recording off — new turns won't be stored", "ok"); } catch (e) { if (gen === scopeGen.current) setLoggingEnabled(!next); // revert diff --git a/frontend/src/views/Documents.all.test.tsx b/frontend/src/views/Documents.all.test.tsx index cfcd600588..f01c3cf571 100644 --- a/frontend/src/views/Documents.all.test.tsx +++ b/frontend/src/views/Documents.all.test.tsx @@ -157,8 +157,8 @@ describe("All documents", () => { expect(add).toHaveAccessibleDescription("Add to collection… takes documents from one place at a time."); await userEvent.click(within(bar).getByRole("button", { name: "Delete" })); await waitFor(() => expect(api.bulkDeleteKnowledge).toHaveBeenCalledTimes(2)); - expect(api.bulkDeleteKnowledge).toHaveBeenCalledWith({ org: "acme", namespace: "team" }, ["notes/plan.md"]); - expect(api.bulkDeleteKnowledge).toHaveBeenCalledWith({ org: "acme", namespace: "col-eng" }, ["runbooks/drain.md"]); + expect(api.bulkDeleteKnowledge).toHaveBeenCalledWith({ org: "acme", namespace: "team" }, ["notes/plan.md"], "explicit"); + expect(api.bulkDeleteKnowledge).toHaveBeenCalledWith({ org: "acme", namespace: "col-eng" }, ["runbooks/drain.md"], "explicit"); }); it("moves a selection from the place its rows are in, and a row from its own place", async () => { @@ -245,6 +245,7 @@ describe("All documents", () => { ["runbooks/drain.md", "runbooks/fill.md"], expect.any(AbortSignal), expect.any(Function), + "explicit", ), ); await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); diff --git a/frontend/src/views/Documents.download.test.tsx b/frontend/src/views/Documents.download.test.tsx index 1b8dc9e068..9250727ba1 100644 --- a/frontend/src/views/Documents.download.test.tsx +++ b/frontend/src/views/Documents.download.test.tsx @@ -117,7 +117,7 @@ describe("Library download", () => { await settle(); await pick("Handbook", "Delete"); await settle(); - expect(api.deleteKnowledge).toHaveBeenCalledWith({ org: ORG, namespace: NS }, "docs/handbook.pdf"); + expect(api.deleteKnowledge).toHaveBeenCalledWith({ org: ORG, namespace: NS }, "docs/handbook.pdf", "explicit"); const alert = screen.getByRole("alert"); expect(alert.textContent).toContain("Delete failed"); expect(alert.textContent).toContain("request id rid-123"); diff --git a/frontend/src/views/Documents.drag.test.tsx b/frontend/src/views/Documents.drag.test.tsx index e358d89dca..191a9d49dc 100644 --- a/frontend/src/views/Documents.drag.test.tsx +++ b/frontend/src/views/Documents.drag.test.tsx @@ -162,6 +162,7 @@ describe("dragging documents onto the Library's tree", () => { ["runbooks/drain.md"], expect.anything(), expect.any(Function), + "explicit", ), ); expect(toasts.toast).toHaveBeenCalledWith("Moved 1 document to My files", "ok"); diff --git a/frontend/src/views/Documents.restore.test.tsx b/frontend/src/views/Documents.restore.test.tsx index 13052d8ee6..4882a86345 100644 --- a/frontend/src/views/Documents.restore.test.tsx +++ b/frontend/src/views/Documents.restore.test.tsx @@ -76,7 +76,7 @@ describe("Library delete Undo", () => { const reads = api.listKnowledge.mock.calls.length; act(() => useStore.setState({ identity: { org: "acme", namespace: "other", agent: "loom-ui" } })); await userEvent.click(undo); - expect(api.restoreKnowledge).toHaveBeenCalledWith({ org: "acme", namespace: "team" }, "docs/refunds.md"); + expect(api.restoreKnowledge).toHaveBeenCalledWith({ org: "acme", namespace: "team" }, "docs/refunds.md", "explicit"); expect(await screen.findByText("Restored docs/refunds.md")).toBeInTheDocument(); expect(screen.queryByRole("button", { name: "Undo" })).toBeNull(); expect(screen.getByLabelText("Search library")).toHaveFocus(); diff --git a/frontend/src/views/Documents.tsx b/frontend/src/views/Documents.tsx index 435489119b..b1e6c7325a 100644 --- a/frontend/src/views/Documents.tsx +++ b/frontend/src/views/Documents.tsx @@ -708,7 +708,7 @@ export function Documents() { return; const place = placeOf(r); try { - await deleteKnowledge(place, source_uri); + await deleteKnowledge(place, source_uri, "explicit"); toast(`Deleted ${source_uri}`, "ok", undoNotice(place, source_uri)); } catch (e) { if (!isPublicationPending(e)) { @@ -733,7 +733,7 @@ export function Documents() { // when the notice outlived the Library. (searchRef.current ?? document.getElementById("main"))?.focus(); try { - const r = await restoreKnowledge(place, source_uri); + const r = await restoreKnowledge(place, source_uri, "explicit"); if (r.restored) { toast( r.original === "gone" @@ -1052,7 +1052,7 @@ export function Documents() { const uris = inPlace.map((r) => r.source_uri); const keys = inPlace.map((r) => rowKeyOf(r, across)); try { - const r = await bulkDeleteKnowledge({ org: identity.org, namespace: ns }, uris); + const r = await bulkDeleteKnowledge({ org: identity.org, namespace: ns }, uris, "explicit"); deleted += r.total_tombstoned; answered = true; gone.push(...keys); diff --git a/frontend/src/views/KnowledgeGaps.test.tsx b/frontend/src/views/KnowledgeGaps.test.tsx index 47ba493ff9..a93dfe2ef4 100644 --- a/frontend/src/views/KnowledgeGaps.test.tsx +++ b/frontend/src/views/KnowledgeGaps.test.tsx @@ -81,6 +81,6 @@ it("queues one private draft and says where to review it", async () => { const action = await screen.findByRole("button", { name: "Draft definition for what is arr" }); fireEvent.click(action); await screen.findByText(/Review the draft in Review queue/); - expect(draftKnowledgeGap).toHaveBeenCalledWith({ org: "o", namespace: "ns" }, "g1"); + expect(draftKnowledgeGap).toHaveBeenCalledWith({ org: "o", namespace: "ns" }, "g1", "explicit"); expect(action).toBeDisabled(); }); diff --git a/frontend/src/views/KnowledgeGaps.tsx b/frontend/src/views/KnowledgeGaps.tsx index 0af63e2866..0578706ccb 100644 --- a/frontend/src/views/KnowledgeGaps.tsx +++ b/frontend/src/views/KnowledgeGaps.tsx @@ -94,7 +94,7 @@ function GapDraftAction({ org, namespace, gap }: { org: string; namespace: strin setBusy(true); setError(""); try { - await draftKnowledgeGap({ org, namespace }, gap.gap_id); + await draftKnowledgeGap({ org, namespace }, gap.gap_id, "explicit"); if (mounted.current) setQueued(true); } catch (e) { if (mounted.current) setError(humanizeError(e, { bare: true })); diff --git a/frontend/src/views/LibraryCollections.test.tsx b/frontend/src/views/LibraryCollections.test.tsx index 263a05f4bd..d95d4157d7 100644 --- a/frontend/src/views/LibraryCollections.test.tsx +++ b/frontend/src/views/LibraryCollections.test.tsx @@ -1236,6 +1236,7 @@ describe("the Library on a collection", () => { "acme", expect.any(String), expect.objectContaining({ parent: "", title: "Q3" }), + "explicit", ); const at = location.search; const docs = api.listKnowledge.mock.calls.length; diff --git a/frontend/src/views/LibraryCollections.tsx b/frontend/src/views/LibraryCollections.tsx index e9358e805a..9c60776930 100644 --- a/frontend/src/views/LibraryCollections.tsx +++ b/frontend/src/views/LibraryCollections.tsx @@ -288,7 +288,7 @@ export function LibraryCollections({ }); if (!ok) return; try { - const r = await deleteCollection(org, c.namespace); + const r = await deleteCollection(org, c.namespace, "explicit"); // The titles and places other pages show come from one shared read. invalidateSharedCollections(); if (r.erasure_status && r.erasure_status !== "completed") { diff --git a/frontend/src/views/LibraryTree.tsx b/frontend/src/views/LibraryTree.tsx index e949ef46aa..89a2d924c3 100644 --- a/frontend/src/views/LibraryTree.tsx +++ b/frontend/src/views/LibraryTree.tsx @@ -642,7 +642,7 @@ function NewCollectionForm({ const version = claimCreateVersion(); let r: CollectionCreated; try { - r = await createCollection(org, "", { parent, title: trimmed, deriveName: true }); + r = await createCollection(org, "", { parent, title: trimmed, deriveName: true }, "explicit"); } catch (err) { toastError(`Couldn't create ${trimmed}`, err); setBusy(false); diff --git a/frontend/src/views/MCPSources.test.tsx b/frontend/src/views/MCPSources.test.tsx new file mode 100644 index 0000000000..28912be025 --- /dev/null +++ b/frontend/src/views/MCPSources.test.tsx @@ -0,0 +1,145 @@ +import userEvent from "@testing-library/user-event"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, fireEvent, render, screen, waitFor } from "../test/rtl"; +import { axeViolations } from "../test/axe"; +import { mcpResult, mcpSource, mcpSummary as summary } from "../test/mcpSources"; +import type { MCPSourceSummary } from "../api/mcpSources"; +vi.mock("../api/mcpSources", async (original) => ({ + ...(await original()), mcpList: vi.fn(), mcpInspect: vi.fn(), + mcpControl: vi.fn(), mcpRemove: vi.fn(), +})); +vi.mock("../api/knowledgeSources", async (original) => ({ + ...(await original()), listKnowledgeSources: vi.fn(), +})); +import * as api from "../api/mcpSources"; +import { listKnowledgeSources } from "../api/knowledgeSources"; +import { useStore } from "../lib/state"; +import { MCPSources } from "./MCPSources"; +import { SourcesList } from "./SourcesList"; + +const initialStore = useStore.getState(); +async function openDetails() { await userEvent.click(await screen.findByRole("button", { name: "Private documents", exact: true })); await screen.findByRole("dialog"); } +async function action(label: string) { + await userEvent.click(screen.getByRole("button", { name: `Actions for ${mcpSource.name}` })); + await userEvent.click(await screen.findByRole("menuitem", { name: label, exact: true })); +} +function owned() { + useStore.setState({ authed: true, sessionExpired: false, + identity: { org: "acme", namespace: "col-team", agent: "dashboard" }, + whoami: { org: "acme", subject: "owner-a", roles: ["ADMIN"], authenticated: true }, myNamespaces: [], + }); +} + +describe("owner MCP source management", () => { + beforeEach(() => { + vi.clearAllMocks(); owned(); + vi.mocked(api.mcpList).mockResolvedValue({ sources: [summary], next_cursor: null }); + vi.mocked(api.mcpInspect).mockResolvedValue({ found: true, source: mcpSource }); + vi.mocked(api.mcpControl).mockResolvedValue({ ...mcpResult, source: { ...mcpSource, state: "paused" } }); + vi.mocked(api.mcpRemove).mockResolvedValue({ ...mcpResult, source: { ...mcpSource, state: "retired" } }); + vi.mocked(listKnowledgeSources).mockRejectedValue(new Error("native source operation unavailable")); + }); + afterEach(() => { cleanup(); useStore.setState(initialStore); vi.restoreAllMocks(); }); + + it("integrates into the real Sources entry point even when the replaced adapter read fails", async () => { + const panel = document.createElement("div"); document.body.append(panel); + const view = render(); + await userEvent.click(await screen.findByRole("button", { name: "MCP sources", exact: true })); + expect(await screen.findByRole("button", { name: "Set up MCP source" })).toBeInTheDocument(); + expect(await screen.findByRole("button", { name: "Private documents", exact: true })).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Add a source", exact: true })).toBeNull(); + view.unmount(); panel.remove(); + }); + it("pages owner-only summaries without displaying resource IDs until exact inspection", async () => { + vi.mocked(api.mcpInspect).mockResolvedValue({ found: true, source: { ...mcpSource, name: "second" } }); + vi.mocked(api.mcpList).mockResolvedValueOnce({ sources: [summary], next_cursor: "next-page" }).mockResolvedValueOnce({ sources: [{ ...summary, name: "second", label: "Second registration" }], next_cursor: null }); + render(); + await screen.findByRole("button", { name: "Private documents", exact: true }); + expect(screen.queryByText(mcpSource.resource_ids[0] ?? "missing")).toBeNull(); + await userEvent.click(screen.getByRole("button", { name: "Load more registrations" })); + expect(await screen.findByRole("button", { name: "Second registration", exact: true })).toBeInTheDocument(); + expect(api.mcpList).toHaveBeenLastCalledWith("acme", "col-team", "next-page", expect.any(AbortSignal)); + expect(screen.getByRole("button", { name: "Previous registrations" })).toBeInTheDocument(); + await userEvent.click(screen.getByRole("button", { name: "Second registration", exact: true })); + expect(api.mcpInspect).toHaveBeenCalledWith({ org: "acme", namespace: "col-team", name: "second" }, expect.any(AbortSignal)); + expect(await screen.findByText(mcpSource.resource_ids[0] ?? "missing")).toBeInTheDocument(); + }); + it("requires exact removal confirmation, retains copies by default, and reports server disposition", async () => { + render(); await openDetails(); await action("Remove registration"); + expect(screen.getByRole("button", { name: "Confirm removal" })).toBeDisabled(); + expect(screen.getByRole("checkbox", { name: "Also request erasure of stored copies" })).not.toBeChecked(); + await userEvent.type(screen.getByLabelText("Repeat the exact registration name to remove"), mcpSource.name); + await userEvent.click(screen.getByRole("button", { name: "Confirm removal" })); + expect(api.mcpRemove).toHaveBeenCalledWith({ org: "acme", namespace: "col-team", name: mcpSource.name, confirm: mcpSource.name, delete_documents: false }, expect.any(AbortSignal), "explicit"); + expect(await screen.findByText(/Copies: retained/)).toBeInTheDocument(); + }); + it("requires separate explicit erasure confirmation", async () => { + vi.mocked(api.mcpRemove).mockResolvedValue({ ...mcpResult, copies: "erasure_requested", source: { ...mcpSource, state: "retired", pending_erasure: true } }); + render(); await openDetails(); await action("Remove registration"); + await userEvent.type(screen.getByLabelText("Repeat the exact registration name to remove"), mcpSource.name); + fireEvent.click(screen.getByRole("checkbox", { name: "Also request erasure of stored copies" })); + expect(screen.getByRole("button", { name: "Confirm removal" })).toBeDisabled(); + await userEvent.type(screen.getByLabelText("Type ERASE to confirm asynchronous copy erasure"), "ERASE"); + await userEvent.click(screen.getByRole("button", { name: "Confirm removal" })); + expect(api.mcpRemove).toHaveBeenCalledWith(expect.objectContaining({ delete_documents: true }), expect.any(AbortSignal), "explicit"); + expect(await screen.findByText(/Copies: erasure_requested/)).toBeInTheDocument(); + }); + it("pauses, resumes and explicitly refreshes nonlive registrations using server truth", async () => { + render(); await openDetails(); await action("Pause"); + expect(api.mcpControl).toHaveBeenLastCalledWith(expect.objectContaining({ name: mcpSource.name }), "pause", expect.any(AbortSignal), "explicit"); + await screen.findByText(/Server state: paused/); + vi.mocked(api.mcpControl).mockResolvedValue({ ...mcpResult, source: mcpSource }); + await action("Resume"); await screen.findByText(/Server state: registered/); + vi.mocked(api.mcpControl).mockResolvedValue({ ...mcpResult, refresh_requested: true }); + await action("Refresh selected items"); + expect(api.mcpControl).toHaveBeenLastCalledWith(expect.any(Object), "refresh", expect.any(AbortSignal), "explicit"); + expect(await screen.findByText(/Refresh requested: yes/)).toBeInTheDocument(); + }); + it("disables explicit refresh in live mode", async () => { + vi.mocked(api.mcpInspect).mockResolvedValue({ found: true, source: { ...mcpSource, mode: "live" } }); + render(); await openDetails(); + await userEvent.click(screen.getByRole("button", { name: `Actions for ${mcpSource.name}` })); + expect(screen.getByRole("menuitem", { name: "Refresh selected items" })).toHaveAttribute("aria-disabled", "true"); + expect(api.mcpControl).not.toHaveBeenCalled(); + }); + it("reconciles uncertain mutations without issuing them again", async () => { + vi.mocked(api.mcpControl).mockRejectedValue(new Error("cut response")); + render(); await openDetails(); await action("Pause"); + await screen.findByText(/The mutation result is uncertain/); + await userEvent.click(screen.getByRole("button", { name: "Inspect current source state" })); + await screen.findByText(/Current server state inspected/); + expect(api.mcpControl).toHaveBeenCalledTimes(1); + expect(api.mcpInspect).toHaveBeenCalledTimes(2); + }); + it("does not show another caller's late owner list", async () => { + let release!: (value: { sources: MCPSourceSummary[]; next_cursor: null }) => void; + const held = new Promise<{ sources: MCPSourceSummary[]; next_cursor: null }>((resolve) => { release = resolve; }); + vi.mocked(api.mcpList).mockReturnValueOnce(held).mockResolvedValue({ sources: [], next_cursor: null }); + render(); + await waitFor(() => expect(api.mcpList).toHaveBeenCalledTimes(1)); + act(() => useStore.setState({ whoami: { org: "acme", subject: "owner-b", roles: ["ADMIN"], authenticated: true } })); + await screen.findByText(/No owned MCP registrations/); + await act(async () => { release({ sources: [summary], next_cursor: null }); await held; }); + expect(screen.queryByRole("button", { name: "Private documents", exact: true })).toBeNull(); + }); + it("removes old owner metadata on session revocation and makes no new source call", async () => { + render(); await openDetails(); + act(() => useStore.setState({ sessionExpired: true })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(screen.queryByText(mcpSource.resource_ids[0] ?? "missing")).toBeNull(); + expect(screen.getByText(/Sign in with your own user account/)).toBeInTheDocument(); + expect(api.mcpList).toHaveBeenCalledTimes(1); + }); + it("shows the writer requirement after destination grant loss", async () => { + render(); await openDetails(); + act(() => useStore.setState({ whoami: { org: "acme", subject: "owner-a", roles: ["VIEWER"], authenticated: true }, myNamespaces: [] })); + expect(screen.queryByRole("dialog")).toBeNull(); + expect(screen.getByText(/Needs writer on col-team/)).toBeInTheDocument(); + }); + it("has no axe violations on the owner list and management dialog", async () => { + const view = render(); + await screen.findByRole("button", { name: "Private documents", exact: true }); + expect(await axeViolations(view.container)).toEqual([]); + await openDetails(); expect(await axeViolations(screen.getByRole("dialog"))).toEqual([]); + }); +}); diff --git a/frontend/src/views/MCPSources.tsx b/frontend/src/views/MCPSources.tsx new file mode 100644 index 0000000000..cc89984363 --- /dev/null +++ b/frontend/src/views/MCPSources.tsx @@ -0,0 +1,197 @@ +import { Button } from "@clickhouse/click-ui/Button"; +import { Checkbox } from "@clickhouse/click-ui/Checkbox"; +import { TextField } from "@clickhouse/click-ui/TextField"; +import { lazy, Suspense, useEffect, useId, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { + type MCPSource, type MCPSourceSummary, mcpControl, mcpInspect, mcpList, mcpRemove, +} from "../api/mcpSources"; +import { Alert } from "../components/ui/Alert"; +import { ListRow } from "../components/ui/ListRow"; +import { ListState } from "../components/ui/ListState"; +import { Loading } from "../components/ui/Loading"; +import { RowMenu, type RowMenuItem } from "../components/ui/RowMenu"; +import { DialogFrame } from "../flows/TaskDialogFrame"; +import { mcpSourceCopy as copy } from "../flows/mcpSourceCopy"; +import { useMCPRequest } from "../flows/useMCPRequest"; +import { MCPLiveRead } from "../flows/MCPLiveRead"; +import { canCallOwnConnections } from "../lib/canCall"; +import { onCollectionsChanged } from "../lib/collectionPlaces"; +import { humanizeError } from "../lib/errorWords"; +import { useAbortableEffect } from "../lib/hooks"; +import { needsRole, useNamespaceRoleRead } from "../lib/namespaceRole"; +import { useStore } from "../lib/state"; +import { useRowNav } from "../lib/useRowNav"; + +const MCPSourceSetup = lazy(() => import("../flows/MCPSourceSetup").then((m) => ({ default: m.MCPSourceSetup }))); +const MCPConnectionsDialog = lazy(() => import("../flows/MCPConnectionStep").then((m) => ({ default: m.MCPConnectionsDialog }))); + +/** Mounted by the Library and repository Sources entry point, independently of native adapters. */ +export function MCPSources({ org, namespace, section, panel, busy = false }: { + org: string; namespace: string; section?: string; panel?: HTMLElement | null; busy?: boolean; +}) { + const whoami = useStore((s) => s.whoami); + const identityOrg = useStore((s) => s.identity?.org); + const authed = useStore((s) => s.authed); + const expired = useStore((s) => s.sessionExpired); + const role = useNamespaceRoleRead(namespace); + const [open, setOpen] = useState(false); + const heading = useRef(null); + const headingId = useId(); + const panelId = useId(); + const allowed = authed && !expired && identityOrg === org && whoami?.org === org && canCallOwnConnections(whoami); + const writer = role.role === "writer" || role.role === "admin"; + const callerKey = JSON.stringify([org, whoami?.subject]); + const collectionVersion = JSON.stringify([whoami, role.rows]); + useEffect(() => { if (open) heading.current?.focus(); }, [open]); + const content =
+

{copy.title}

+ {!allowed ?

Sign in with your own user account to manage your MCP sources.

: !writer ? +

{role.loading ? "Checking your collection role…" : needsRole("writer", namespace)}

: + } +
; + if (!section) return content; + return <> + + {open && panel && createPortal(content, panel)} + ; +} + +function SourceRegistrations({ org, namespace, callerKey, collectionVersion, disabled }: { + org: string; namespace: string; callerKey: string; collectionVersion: string; disabled: boolean; +}) { + const [cursor, setCursor] = useState(null); + const [previous, setPrevious] = useState<(string | null)[]>([]); + const [revision, setRevision] = useState(0); + const [authorityEpoch, setAuthorityEpoch] = useState(0); + const [answer, setAnswer] = useState> | null>(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [adding, setAdding] = useState(false); + const [connectionsOpen, setConnectionsOpen] = useState(false); + const [details, setDetails] = useState(null); + const [editing, setEditing] = useState(false); + const [notice, setNotice] = useState(""); + const top = useRef(null); + const request = useMCPRequest(JSON.stringify([org, namespace, callerKey, collectionVersion, authorityEpoch, cursor])); + const rowNav = useRowNav({ enabled: !details && !adding && !connectionsOpen }); + const reload = () => { setLoading(true); setCursor(null); setPrevious([]); setRevision((value) => value + 1); }; + const refreshRef = useRef(() => {}); + refreshRef.current = () => { setAuthorityEpoch((v) => v + 1); reload(); }; + useEffect(() => { + const off = onCollectionsChanged((value) => { if (!value || value.org === org) refreshRef.current(); }); + const focus = () => refreshRef.current(); + window.addEventListener("focus", focus); + return () => { off(); window.removeEventListener("focus", focus); }; + }, [org]); + useAbortableEffect(async (signal, live) => { + setLoading(true); setError(null); + try { + const value = await mcpList(org, namespace, cursor, signal); + if (live()) { setAnswer(value); setLoading(false); } + } catch (failure) { if (live()) { setError(failure); setLoading(false); } } + }, [org, namespace, callerKey, cursor, revision, collectionVersion]); + const inspect = async (row: MCPSourceSummary) => { + if (disabled || loading || request.busy) return; + const result = await request.run((signal) => mcpInspect({ org, namespace, name: row.name }, signal)); + if (result?.found && result.source?.name === row.name && result.source.namespace === namespace) { setDetails(result.source); setEditing(false); } + else if (result) { setNotice("No owned source was returned. Refresh this collection's registrations."); reload(); } + }; + const saved = (source: MCPSource) => { setNotice(`Server source ${source.name} in ${source.namespace}: ${source.state}. Refresh state: ${source.refresh_state}.`); reload(); }; + const nextCursor = answer?.next_cursor; + const repeated = !!nextCursor && (nextCursor === cursor || previous.includes(nextCursor)); + const page = (next: string | null, back: boolean) => { + if (loading || request.busy) return; + if (back) setPrevious((values) => values.slice(0, -1)); else setPrevious((values) => [...values, cursor]); + setLoading(true); setAnswer(null); setCursor(next); top.current?.focus(); + }; + return
+

Your registrations in {namespace}, 20 per page. Other owners' registrations and resource IDs are not listed.

+

{copy.retained}

+
+ + + +
+ {loading && } + {!!error && } + {!loading && !error && answer?.sources.length === 0 && } + {!error &&
+ {(answer?.sources ?? []).map((source) => + +

{source.state} · {source.mode} · {source.reader_policy} · refresh {source.refresh_state} · local authority {source.local_authority}

+
)} +
} +
+ {previous.length > 0 && } + {nextCursor && } +
+ {repeated &&

The server repeated a cursor. Refresh registrations before paging further.

} + {!!request.error && } + {notice &&

{notice}

} + {adding && }> setAdding(false)} />} + {connectionsOpen && }> { setConnectionsOpen(false); refreshRef.current(); }} />} + {details && !editing && setDetails(null)} + onChanged={(source) => { setDetails(source); saved(source); }} onEdit={() => setEditing(true)} />} + {details && editing && }> { setDetails(source); saved(source); }} onClose={() => setEditing(false)} />} +
; +} + +function MCPSourceDetails({ org, source, contextKey, onClose, onChanged, onEdit }: { + org: string; source: MCPSource; contextKey: string; onClose: () => void; onChanged: (value: MCPSource) => void; onEdit: () => void; +}) { + const [pending, setPending] = useState(false); + const [remove, setRemove] = useState(false); + const [confirm, setConfirm] = useState(""); + const [erase, setErase] = useState(false); + const [eraseConfirm, setEraseConfirm] = useState(""); + const [notice, setNotice] = useState(""); + const request = useMCPRequest(contextKey); + const key = { org, namespace: source.namespace, name: source.name }; + const mutate = async (action: "pause" | "resume" | "refresh" | "remove", intent: "automatic" | "explicit") => { + if (pending || request.busy || (action === "remove" && (confirm !== source.name || (erase && eraseConfirm !== "ERASE")))) return; + setPending(true); + const result = await request.run((signal) => action === "remove" ? + mcpRemove({ ...key, confirm, delete_documents: erase }, signal, intent) : mcpControl(key, action, signal, intent)); + if (result) { + setPending(false); setRemove(false); setErase(false); setConfirm(""); setEraseConfirm(""); onChanged(result.source); + setNotice(`Server state: ${result.source.state}. Copies: ${result.copies}. Refresh requested: ${result.refresh_requested ? "yes" : "no"}.`); + } + }; + const reconcile = async () => { + const result = await request.run((signal) => mcpInspect(key, signal)); + if (result?.found && result.source?.name === source.name && result.source.namespace === source.namespace) { + onChanged(result.source); + setNotice("Current server state inspected. This inspection does not attest completion of the original mutation; resubmission remains blocked."); + } else if (result) setNotice("No owned registration was returned. Do not repeat the mutation."); + }; + const items: RowMenuItem[] = [ + { label: "Edit selection", disabled: pending || request.busy || source.state === "retired" || source.state === "unsupported", onSelect: onEdit }, + { label: "Pause", disabled: pending || request.busy || source.state !== "registered", onSelect: () => void mutate("pause", "explicit") }, + { label: "Resume", disabled: pending || request.busy || source.state !== "paused", onSelect: () => void mutate("resume", "explicit") }, + { label: "Refresh selected items", disabled: pending || request.busy || source.mode === "live" || source.state !== "registered", onSelect: () => void mutate("refresh", "explicit") }, + { label: "Remove registration", danger: true, disabled: pending || request.busy || source.state === "retired", onSelect: () => setRemove(true) }, + ]; + return { if (!open && !request.busy && !pending) onClose(); }} title="MCP source registration" description="Current server registration metadata; upstream permissions remain unsupported." + footer={}> +

{source.label || source.name}

+

Name: {source.name}. State: {source.state}. Mode: {source.mode}. Audience: {source.reader_policy}. Revision: {source.scope_revision}. Refresh: {source.refresh_state}. Local authority: {source.local_authority}. Pending erasure: {source.pending_erasure ? "yes" : "no"}.

+ {source.rule &&

Server access: {source.rule.access}. {source.rule.reason} {source.rule.explanation}

} +
    {source.resource_ids.map((id, index) =>
  • {id}
  • )}
+

{copy.retained}

+

Read evidence expires after {source.read_evidence_stale_seconds} seconds. Snapshot access expires without manual refresh while bytes remain retained. Both audiences require current authorization and fresh evidence.

+ {source.mode === "live" && source.reader_policy === "owner_only" && source.state === "registered" && } + {remove &&
+

Remove this registration. Stored copies are retained by default; access still requires current authorization.

+ + { setErase(value === true); setEraseConfirm(""); }} /> + {erase && } + + +
} + {pending && <>} + {!!request.error && } + {notice &&

{notice}

} +
; +} diff --git a/frontend/src/views/ModelsSettings.tsx b/frontend/src/views/ModelsSettings.tsx index 3e1dee5a5d..5b9cc6b80d 100644 --- a/frontend/src/views/ModelsSettings.tsx +++ b/frontend/src/views/ModelsSettings.tsx @@ -127,7 +127,7 @@ export function ModelsSettings() { if (resetting) return; setResetting(true); try { - await resetModelConfiguration(status.version); + await resetModelConfiguration(status.version, "explicit"); setConfirmReset(false); setReload((value) => value + 1); } catch (e) { @@ -170,7 +170,7 @@ export function ModelsSettings() { if (!status.pending || retrying) return; setRetrying(true); try { - await retryModelConfiguration(status.pending.config_id); + await retryModelConfiguration(status.pending.config_id, "explicit"); setReload((value) => value + 1); } catch (e) { setError(`Couldn't retry the rebuild: ${errorLine(e)}`); @@ -195,10 +195,10 @@ export function ModelsSettings() { status={status} onValidate={(configuration) => { setSaved(false); - return validateModelConfiguration(configuration); + return validateModelConfiguration(configuration, "explicit"); }} onSave={async (configuration) => { - await saveModelConfiguration(configuration); + await saveModelConfiguration(configuration, "explicit"); setSaved(true); setReload((value) => value + 1); }} diff --git a/frontend/src/views/Profile.tsx b/frontend/src/views/Profile.tsx index b1a5185aa6..6a8e336c66 100644 --- a/frontend/src/views/Profile.tsx +++ b/frontend/src/views/Profile.tsx @@ -113,7 +113,7 @@ export function Profile() { if (!ok) return; setBulkBusy(true); try { - await Promise.all(Array.from(selected).map((label) => deleteProfileSection(identity, label))); + await Promise.all(Array.from(selected).map((label) => deleteProfileSection(identity, label, "explicit"))); toast(`Deleted ${selected.size} section${selected.size === 1 ? "" : "s"}`, "ok"); selection.clear(); refresh(); @@ -885,7 +885,7 @@ function SectionEditor({ } setSaving(true); try { - await setProfileSection(identity, label.trim(), value, DEFAULT_CHAR_LIMIT); + await setProfileSection(identity, label.trim(), value, DEFAULT_CHAR_LIMIT, "explicit"); toast(isNew ? "Section created" : "Section saved", "ok"); onSaved(); } catch (e) { @@ -960,7 +960,7 @@ async function onDelete(identity: Identity, label: string, refresh: () => void) }); if (!ok) return; try { - await deleteProfileSection(identity, label); + await deleteProfileSection(identity, label, "explicit"); toast("Section deleted", "ok"); refresh(); } catch (e) { diff --git a/frontend/src/views/QueryHistorySources.tsx b/frontend/src/views/QueryHistorySources.tsx index 167f2ac2e9..863e6832dd 100644 --- a/frontend/src/views/QueryHistorySources.tsx +++ b/frontend/src/views/QueryHistorySources.tsx @@ -120,7 +120,7 @@ function SourceList({ org, namespace, focusDisclosure }: Scope & { focusDisclosu setBusy(name); setWriteError(""); try { - await removeQueryHistory(scope, name); + await removeQueryHistory(scope, name, "explicit"); if (mounted.current) { reload(); if (connectButton.current) connectButton.current.focus(); @@ -249,6 +249,7 @@ function SourceForm({ org, namespace, onDone, onCancel }: Scope & { onDone: () = .map((s) => s.trim()) .filter(Boolean), }, + "explicit", ); if (mounted.current) onDone(); } catch (e) { diff --git a/frontend/src/views/Recent.lists.test.tsx b/frontend/src/views/Recent.lists.test.tsx index ee09b1d0a7..305eba712a 100644 --- a/frontend/src/views/Recent.lists.test.tsx +++ b/frontend/src/views/Recent.lists.test.tsx @@ -481,6 +481,7 @@ describe("Memories list chrome", () => { { org: "dev", namespace: "team", agent: "claude-desktop" }, "d/plain", detail, + "explicit", ]); }); diff --git a/frontend/src/views/Recent.tsx b/frontend/src/views/Recent.tsx index 6d4530d94a..d510fbffda 100644 --- a/frontend/src/views/Recent.tsx +++ b/frontend/src/views/Recent.tsx @@ -480,7 +480,7 @@ function MemoryList() { const readId = { ...rowId, user_id: entry.user_id || "-", session_id: entry.session_id || "-" }; const got = await getMemory(readId, k); if (got && got.found) { - await pinMemory(rowId, k, got); + await pinMemory(rowId, k, got, "explicit"); ok++; } else { fail++; @@ -527,7 +527,7 @@ function MemoryList() { // `tombstoned: false` is a 200, not a throw — counting only the absence // of an exception is what made this report "Deleted N" and then show // every row again on refresh. - const r = await deleteMemory(identityForRow(entry?.agent), k); + const r = await deleteMemory(identityForRow(entry?.agent), k, "explicit"); if (r.tombstoned) ok++; else fail++; } catch { @@ -998,7 +998,7 @@ function MemoryList() { const r = await restoreMemory({ ...identity, agent: e.agent || "-" }, e.memory_key, { user_id: e.user_id || "-", session_id: e.session_id || "-", - }); + }, "explicit"); if (r.restored) { toast(`Restored ${e.memory_key}`, "ok"); bumpMemoriesVersion(); diff --git a/frontend/src/views/RepoDocs.test.tsx b/frontend/src/views/RepoDocs.test.tsx index 6b0d2b443a..2038aed4dd 100644 --- a/frontend/src/views/RepoDocs.test.tsx +++ b/frontend/src/views/RepoDocs.test.tsx @@ -284,6 +284,7 @@ describe("RepoDocsList", () => { description: "", upsert: false, }, + "explicit", ]); }); @@ -327,6 +328,7 @@ describe("RepoDocsList", () => { expected_revision: 0, upload_id: "up-1", }, + "explicit", ]); expect(addKnowledge).not.toHaveBeenCalled(); }); diff --git a/frontend/src/views/RepoDocs.tsx b/frontend/src/views/RepoDocs.tsx index bc1836403e..a2dea65a9a 100644 --- a/frontend/src/views/RepoDocs.tsx +++ b/frontend/src/views/RepoDocs.tsx @@ -107,7 +107,7 @@ export function RepoDocsList({ return; setRemoving(doc.source_uri); try { - await deleteKnowledge(id, doc.source_uri); + await deleteKnowledge(id, doc.source_uri, "explicit"); toast(`Removed ${doc.title || doc.source_uri}`, "ok"); setNonce((n) => n + 1); } catch (e) { diff --git a/frontend/src/views/Setup.title.test.tsx b/frontend/src/views/Setup.title.test.tsx index 0a1340b99b..27c335ea9d 100644 --- a/frontend/src/views/Setup.title.test.tsx +++ b/frontend/src/views/Setup.title.test.tsx @@ -45,12 +45,10 @@ afterEach(() => { }); describe("Settings", () => { - it("opens Connected accounts from its page action", async () => { + it("keeps native document account setup out of Settings", () => { seed("team"); render(); - await userEvent.click(screen.getByRole("button", { name: "Connected accounts" })); - expect(useStore.getState().view).toBe("connected-accounts"); - expect(window.location.pathname).toBe("/settings/connected-accounts"); + expect(screen.queryByRole("button", { name: "Connected accounts" })).toBeNull(); }); it("titles the document after the open tab", async () => { diff --git a/frontend/src/views/Setup.tsx b/frontend/src/views/Setup.tsx index e896191844..26fd868c06 100644 --- a/frontend/src/views/Setup.tsx +++ b/frontend/src/views/Setup.tsx @@ -95,11 +95,6 @@ export function Setup() { setView("connected-accounts")}> - Connected accounts - - } > {tab === "models" ? ( Deployment-wide @@ -277,6 +272,7 @@ function ImportCuratedPanel({ unavailable }: { unavailable: string | null }) { const r = await importCuratedDoc( { org: identity.org, namespace: identity.namespace }, { content, source_uri: sourceUri.trim() || "curated_doc" }, + "explicit", ); setResult(r); const tone = r.rejected > 0 ? "error" : r.written > 0 ? "ok" : "info"; diff --git a/frontend/src/views/SourcesList.test.tsx b/frontend/src/views/SourcesList.test.tsx index b07d40e22c..6349c181fc 100644 --- a/frontend/src/views/SourcesList.test.tsx +++ b/frontend/src/views/SourcesList.test.tsx @@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event"; import { afterEach, describe, expect, it, vi } from "vitest"; import { ApiError } from "../lib/errors"; import type { KnowledgeSourceList } from "../lib/knowledgeSources"; +import { inspectKnowledgeSource } from "../api/knowledgeSources"; import { SourcesList } from "./SourcesList"; // A failed read of the document sources shows the error, its request id and a Retry that @@ -12,6 +13,7 @@ const sources = vi.hoisted(() => ({ listKnowledgeSources: vi.fn() })); vi.mock("../api/knowledgeSources", async (importOriginal) => ({ ...(await importOriginal()), ...sources, + inspectKnowledgeSource: vi.fn(), })); const LISTED: KnowledgeSourceList = { @@ -96,4 +98,32 @@ describe("SourcesList", () => { expect(await screen.findByRole("button", { name: "design-docs" })).toBeInTheDocument(); panel.remove(); }); + it.each(["gdrive", "notion", "linear", "unknown-kind"])("keeps %s metadata unavailable without native runtime actions", async (kind) => { + sources.listKnowledgeSources.mockResolvedValue({ ...LISTED, sources: LISTED.sources.map((source) => ({ ...source, kind })) }); + render(); + expect(await screen.findByText(`Unsupported source (${kind})`)).toBeInTheDocument(); + expect(screen.getByText("Unavailable")).toBeInTheDocument(); + expect(screen.getByText(/Unavailable retained registration/)).toBeInTheDocument(); + expect(screen.queryByRole("button", { name: "Actions for design-docs" })).toBeNull(); + expect(screen.queryByText("Synced")).toBeNull(); + expect(screen.getByRole("button", { name: "design-docs" })).toBeInTheDocument(); + expect(inspectKnowledgeSource).not.toHaveBeenCalled(); + }); + it("offers recording-only setup from the real entry point", async () => { + sources.listKnowledgeSources.mockResolvedValue({ enabled: true, accepts_sources: true, sources: [] }); + render(); + await userEvent.click(await screen.findByRole("button", { name: "Add recording source" })); + expect(await screen.findByRole("dialog", { name: /Add a recording source/ })).toBeInTheDocument(); + expect(screen.getByLabelText(/^Meetings/)).toBeInTheDocument(); + expect(screen.getByLabelText(/^Read-only credential/)).toHaveAttribute("type", "password"); + expect(screen.queryByLabelText(/^Folders/)).toBeNull(); + expect(screen.queryByRole("radio", { name: "Pages" })).toBeNull(); + }); + it("preserves recording management actions", async () => { + sources.listKnowledgeSources.mockResolvedValue({ ...LISTED, sources: LISTED.sources.map((source) => ({ ...source, kind: "recording", config: { provider: "zoom", ids: ["81234567890"] } })) }); + render(); + await userEvent.click(await screen.findByRole("button", { name: "Actions for design-docs" })); + for (const name of ["Check", "Sync now", "Rotate credential", "Retire"]) expect(screen.getByRole("menuitem", { name, exact: true })).toBeInTheDocument(); + expect(screen.queryByRole("menuitem", { name: "Push notifications" })).toBeNull(); + }); }); diff --git a/frontend/src/views/SourcesList.tsx b/frontend/src/views/SourcesList.tsx index 36e48e466e..006129193d 100644 --- a/frontend/src/views/SourcesList.tsx +++ b/frontend/src/views/SourcesList.tsx @@ -1,14 +1,5 @@ -/** - * A namespace's document sources: the shared folders, project document stores, page - * stores' pages and meeting transcripts its documents are pulled from, each with its - * last sync. Shown on a repository's card (for its docs namespace) and on the Library - * (for the namespace in view): a reader sees them and an admin manages them: Add a - * source, Check, Sync now, Rotate credential, Retire. - * Read once when the card is opened (a folded card asks nothing) or the Library's place - * view opens, the read deciding whether its button shows; the dialogs load on first - * use. The counts are information only: nothing waits for a person to confirm a row. - */ -import { lazy, Suspense, useEffect, useId, useRef, useState } from "react"; +/** Generic MCP setup, recording setup and retained source metadata. */ +import { type ComponentProps, lazy, Suspense, useEffect, useId, useRef, useState } from "react"; import { createPortal } from "react-dom"; import { Badge, type BadgeState } from "@clickhouse/click-ui/Badge"; import { Button } from "@clickhouse/click-ui/Button"; @@ -34,9 +25,7 @@ import { ListTime, LoadingSkeleton, TipTarget } from "../components/ui"; import { ListState } from "../components/ui/ListState"; import { RowMenu, type RowMenuItem } from "../components/ui/RowMenu"; -const AddSourceDialog = lazy(() => - import("../flows/KnowledgeSourceDialog").then((m) => ({ default: m.AddSourceDialog })), -); +const MCPSources = lazy(() => import("./MCPSources").then((m) => ({ default: m.MCPSources }))); const CheckSourceDialog = lazy(() => import("../flows/KnowledgeSourceDialog").then((m) => ({ default: m.CheckSourceDialog })), ); @@ -47,7 +36,7 @@ const RotateSourceDialog = lazy(() => const SourceDetailsDialog = lazy(() => import("../flows/SourceDetailsDialog").then((m) => ({ default: m.SourceDetailsDialog })), ); -const SourcePushDialog = lazy(() => import("../flows/SourcePushDialog").then((m) => ({ default: m.SourcePushDialog }))); +const AddRecordingSourceDialog = lazy(() => import("../flows/KnowledgeSourceDialog").then((m) => ({ default: m.AddRecordingSourceDialog }))); const RetireSourceDialog = lazy(() => import("../flows/KnowledgeSourceDialog").then((m) => ({ default: m.RetireSourceDialog })), ); @@ -61,12 +50,13 @@ type State = | { kind: "refused" } | { kind: "error"; error: unknown }; -type Verb = "check" | "sync" | "rotate" | "retire" | "push"; +type Verb = "check" | "sync" | "rotate" | "retire"; function SourceRow({ s, items, onOpen }: { s: KnowledgeSource; items: RowMenuItem[]; onOpen: () => void }) { - const badge = syncBadge(s.sync); - const counts = syncCounts(s.sync); - const reasons = unconvertedDetail(s.sync.unconverted_reasons); + const supported = s.kind === "recording"; + const badge = supported ? syncBadge(s.sync) : { text: "Unavailable", tone: "warn" as const, tip: "Retained source metadata and bytes do not grant current access. This source kind is unsupported." }; + const counts = supported ? syncCounts(s.sync) : ""; + const reasons = supported ? unconvertedDetail(s.sync.unconverted_reasons) : ""; return (
  • @@ -79,12 +69,12 @@ function SourceRow({ s, items, onOpen }: { s: KnowledgeSource; items: RowMenuIte - {s.sync.last_synced_at && ( + {supported && s.sync.last_synced_at && ( synced )} - {s.sync.requested_at && ( + {supported && s.sync.requested_at && ( sync requested @@ -101,7 +91,8 @@ function SourceRow({ s, items, onOpen }: { s: KnowledgeSource; items: RowMenuIte )}
    )} - {s.sync.error && s.sync.status !== "ok" && ( + {!supported &&

    Unavailable retained registration. Metadata and history remain; retained bytes do not grant read access. Runtime controls are unavailable.

    } + {supported && s.sync.error && s.sync.status !== "ok" && (
    {s.sync.error}
    )}
  • @@ -113,7 +104,14 @@ function SourceRow({ s, items, onOpen }: { s: KnowledgeSource; items: RowMenuIte /** The place a list belongs to: what the add dialog's title names, and what the copy calls it. */ export type SourcesPlace = { label: string; noun: "repository" | "namespace" | "collection" }; -export function SourcesList({ +export function SourcesList(props: ComponentProps) { + return <> + + + ; +} + +function NativeSourcesList({ org, namespace, place, @@ -150,8 +148,8 @@ export function SourcesList({ if (open) heading.current?.focus(); }, [open]); const [nonce, setNonce] = useState(0); - const [adding, setAdding] = useState(false); const [acting, setActing] = useState<{ verb: Verb; source: KnowledgeSource } | null>(null); + const [addingRecording, setAddingRecording] = useState(false); // Details is a read: any reader may open it. const [details, setDetails] = useState(null); const id = { org, namespace }; @@ -174,7 +172,7 @@ export function SourcesList({ ); const menu = (s: KnowledgeSource): RowMenuItem[] => { - if (!manageable) return []; + if (!manageable || s.kind !== "recording") return []; const act = (verb: Verb) => () => setActing({ verb, source: s }); const check: RowMenuItem = { label: "Check", icon: "check", onSelect: act("check") }; const sync: RowMenuItem = { label: "Sync now", icon: "refresh", onSelect: act("sync") }; @@ -183,9 +181,6 @@ export function SourcesList({ // A place that takes no new source refuses a sync and a rotation: Check and Retire remain. const closed = state.kind === "ready" && !state.accepts; const items = closed ? [check, retire] : [check, sync, rotate, retire]; - if (!closed && ["gdrive", "notion", "linear"].includes(s.kind)) { - items.splice(2, 0, { label: "Push notifications", icon: "refresh", onSelect: act("push") }); - } return items.map((item) => ({ ...item, disabled: busy })); }; const close = (v: boolean) => { @@ -202,6 +197,8 @@ export function SourcesList({ if (section && (closedAndEmpty || nothingForReader || loading || failedForReader)) return null; const list = (
    + {manageable && state.kind === "ready" && state.accepts && } + {addingRecording && { setAddingRecording(false); reload(); }} />} {state.kind === "loading" && ( @@ -216,19 +213,16 @@ export function SourcesList({ {state.kind === "error" && ( )} - {state.kind === "ready" && !state.enabled &&

    {SYNC_OFF}

    } + {state.kind === "ready" && !state.enabled && state.sources.some((s) => s.kind === "recording") &&

    {SYNC_OFF}

    } {state.kind === "ready" && !state.accepts && (

    - This {place.noun} takes no new document sources - {manageable && state.sources.length > 0 ? "; retire these when they are no longer needed." : "."} + This {place.noun} takes no new recording sources. Retained source metadata remains available.

    )} {state.kind === "ready" && state.accepts && state.sources.length === 0 && (

    No document sources.{" "} - {manageable - ? `Add a source and Loom keeps the ${place.noun}'s documents in step with it.` - : `Anyone with admin on the ${place.noun} adds them.`} + Manage your remote MCP registrations through MCP sources.

    )} {state.kind === "ready" && state.sources.length > 0 && ( @@ -238,44 +232,13 @@ export function SourcesList({ ))} )} - {manageable && state.kind === "ready" && state.accepts && ( - - )} {details && ( setDetails(null)} /> )} - {adding && ( - - { - if (!v) setAdding(false); - }} - onAdded={(name) => { - toast(`Added ${name}`, "ok"); - reload(); - }} - /> - - )} {acting && ( - {acting.verb === "push" && ( - setActing(null)} - /> - )} {acting.verb === "check" && ( )} diff --git a/frontend/src/views/StructureTab.tsx b/frontend/src/views/StructureTab.tsx index c17288e0e3..d190da22d1 100644 --- a/frontend/src/views/StructureTab.tsx +++ b/frontend/src/views/StructureTab.tsx @@ -115,7 +115,7 @@ function RecordSchemas({ registerReason, decideReason }: { registerReason: Reaso const decide = async (name: string, decision: "approve" | "reject") => { setDeciding(name); try { - await decideRecordSchema(identity, name, decision); + await decideRecordSchema(identity, name, decision, "explicit"); toast(decision === "approve" ? `Approved ${name}` : `Rejected ${name}`, "ok"); refresh(); } catch (e) { @@ -230,6 +230,7 @@ function NewSchemaDialog({ existing, onClose }: { existing: RecordSchema[]; onCl name.trim(), description.trim(), named.map((f) => ({ ...f, name: f.name.trim() })), + "explicit", ); toast(`${replaces ? "Replaced" : "Registered"} ${name.trim()}`, "ok"); onClose(true); @@ -480,11 +481,11 @@ function ProfileSchemaPanel({ setReason, clearReason }: { setReason: Reason; cle try { if (clear) { // Clear answers the schema it removed, so the panel goes empty itself. - await clearProfileSchema(identity); + await clearProfileSchema(identity, "explicit"); setData({ found: false, json_schema: {}, updated_by: "", updated_at: null }); } else { // Set answers the schema as it now stands: shown at once. - setData(await setProfileSchema(identity, JSON.parse(shown))); + setData(await setProfileSchema(identity, JSON.parse(shown), "explicit")); } toast(clear ? "Profile schema removed" : "Profile schema saved", "ok"); setDraft(null); @@ -562,7 +563,7 @@ function Ontology({ registerReason }: { registerReason: Reason }) { const accept = async (e: OntologyEntry) => { setBusy(true); try { - await registerOntologyTerm(identity, e); + await registerOntologyTerm(identity, e, "explicit"); toast(`Accepted ${e.name}`, "ok"); refresh(); } catch (err) { @@ -574,7 +575,7 @@ function Ontology({ registerReason }: { registerReason: Reason }) { const add = async () => { setBusy(true); try { - await registerOntologyTerm(identity, { kind, name: name.trim(), description: "", cardinality: "" }); + await registerOntologyTerm(identity, { kind, name: name.trim(), description: "", cardinality: "" }, "explicit"); toast(`Added ${name.trim()}`, "ok"); setName(""); refresh(); @@ -676,7 +677,7 @@ function Categories({ addReason }: { addReason: Reason }) { const add = async () => { setBusy(true); try { - const r = await registerCategory(identity, name.trim(), description.trim()); + const r = await registerCategory(identity, name.trim(), description.trim(), "explicit"); if (r.embedded) toast(`Added ${name.trim()}`, "ok"); else toast(`Added ${name.trim()}, but category search cannot find it: it could not be indexed`, "info"); setName(""); diff --git a/frontend/src/views/Tasks.tsx b/frontend/src/views/Tasks.tsx index 7fcca72f7f..78fd0d5251 100644 --- a/frontend/src/views/Tasks.tsx +++ b/frontend/src/views/Tasks.tsx @@ -522,12 +522,12 @@ export function Tasks() { try { const r = action === "accept" - ? await acceptTask(caller, task.task_id) + ? await acceptTask(caller, task.task_id, undefined, "explicit") : action === "start" - ? await claimTask(caller, task.task_id) + ? await claimTask(caller, task.task_id, "explicit") : action === "unblock" - ? await unblockTask(caller, task.task_id) - : await resumeTask(caller, task.task_id); + ? await unblockTask(caller, task.task_id, undefined, "explicit") + : await resumeTask(caller, task.task_id, undefined, "explicit"); toast(actionDone(action, task.title), "ok"); // A switch while the move was out: the list on screen is another namespace's. if (callerNow.current !== caller) return; diff --git a/frontend/src/views/Tokens.tsx b/frontend/src/views/Tokens.tsx index 896c5af86c..7f2efe56ad 100644 --- a/frontend/src/views/Tokens.tsx +++ b/frontend/src/views/Tokens.tsx @@ -203,7 +203,7 @@ export function TokensSection({ ) return; try { - await revokeToken(tokenName); + await revokeToken(tokenName, "explicit"); toast("Revoked", "ok"); reloadTokens(); } catch (e) { @@ -676,6 +676,7 @@ function TokenForm({ await registerNamespace( { org: identity.org, namespace: ns }, { owner_email: owner, description: "Namespace for a token" }, + "explicit", ); // The new admin grant must reach every reader of list_mine at once: the store's // copy and the shared cache. @@ -719,7 +720,7 @@ function TokenForm({ const savesTo = reach === "listed" && listSaves ? { saves_to: listSaves } : {}; setBusy(true); try { - onCreated(await createToken({ name: name.trim() || undefined, namespaces, ttl_days: ttl, ...savesTo })); + onCreated(await createToken({ name: name.trim() || undefined, namespaces, ttl_days: ttl, ...savesTo }, "explicit")); setName(""); } catch (e) { toastError("Failed", e); diff --git a/frontend/src/views/TrackerSources.tsx b/frontend/src/views/TrackerSources.tsx index 40ee158203..09ab737459 100644 --- a/frontend/src/views/TrackerSources.tsx +++ b/frontend/src/views/TrackerSources.tsx @@ -176,7 +176,7 @@ export function useRecordActions(org: string, refresh: () => Promise): Rec return; setBusy(ns.namespace); try { - if (await joinTarget(target(ns), "viewer")) await refresh(); + if (await joinTarget(target(ns), "viewer", "explicit")) await refresh(); } finally { setBusy(null); } @@ -192,7 +192,7 @@ export function useRecordActions(org: string, refresh: () => Promise): Rec return; setBusy(ns.namespace); try { - if (await joinTarget(target(ns), "viewer")) await refresh(); + if (await joinTarget(target(ns), "viewer", "explicit")) await refresh(); } finally { setBusy(null); } @@ -200,7 +200,7 @@ export function useRecordActions(org: string, refresh: () => Promise): Rec const cancel = async (ns: TrackerSourceNamespace) => { setBusy(ns.namespace); try { - if (await withdrawTarget(target(ns))) await refresh(); + if (await withdrawTarget(target(ns), "explicit")) await refresh(); } finally { setBusy(null); } @@ -208,7 +208,7 @@ export function useRecordActions(org: string, refresh: () => Promise): Rec const leave = async (ns: TrackerSourceNamespace) => { setBusy(ns.namespace); try { - if (await leaveTarget(target(ns))) await refresh(); + if (await leaveTarget(target(ns), "explicit")) await refresh(); } finally { setBusy(null); } diff --git a/frontend/src/views/WebhooksSection.tsx b/frontend/src/views/WebhooksSection.tsx index 386d9fee7b..e1c9a4930e 100644 --- a/frontend/src/views/WebhooksSection.tsx +++ b/frontend/src/views/WebhooksSection.tsx @@ -69,7 +69,7 @@ export function WebhooksSection({ unavailable = null }: { unavailable?: string | return; setRemoving((ids) => new Set(ids).add(h.webhook_id)); try { - const r = await removeWebhook(identity, h.webhook_id); + const r = await removeWebhook(identity, h.webhook_id, "explicit"); toast(r.removed ? "Webhook removed" : "This webhook was already removed", r.removed ? "ok" : "info"); // Off the list at once, so no second Remove reaches it before the reread answers. setHooks((hs) => hs && hs.filter((x) => x.webhook_id !== h.webhook_id)); @@ -183,6 +183,7 @@ function AddWebhookDialog({ onClose }: { onClose: (added: boolean) => void }) { url.trim(), secretRef.trim(), WEBHOOK_EVENTS.filter((e) => events.has(e)), + "explicit", ); toast("Webhook added", "ok"); onClose(true); diff --git a/frontend/src/views/admin/Blacklist.tsx b/frontend/src/views/admin/Blacklist.tsx index 2680431db1..aad6d4df84 100644 --- a/frontend/src/views/admin/Blacklist.tsx +++ b/frontend/src/views/admin/Blacklist.tsx @@ -151,7 +151,7 @@ export function PrivacyFilters({ pattern_type: "substring", scope, reason: reason.trim() || undefined, - }); + }, "explicit"); setPattern(""); setReason(""); toast("Pattern added", "ok"); @@ -163,7 +163,7 @@ export function PrivacyFilters({ const remove = async (pattern_id: string) => { try { - await removeBlacklist({ org: identity.org }, pattern_id); + await removeBlacklist({ org: identity.org }, pattern_id, undefined, "explicit"); reload(); } catch (e) { toastError("Failed", e); @@ -185,7 +185,7 @@ export function PrivacyFilters({ if (!ok) return; setSweeping(r.pattern_id); try { - const s = await sweepBlacklistPattern(identity, r.pattern_id); + const s = await sweepBlacklistPattern(identity, r.pattern_id, "explicit"); if (s.error) throw new Error(s.error); // Name the scope the sweep ran in: the page may have moved on before it answers. const where = inNamespace ? identity.namespace : identity.org; diff --git a/frontend/src/views/admin/DeploymentSettings.tsx b/frontend/src/views/admin/DeploymentSettings.tsx index 3fe5eb8b50..be347112d9 100644 --- a/frontend/src/views/admin/DeploymentSettings.tsx +++ b/frontend/src/views/admin/DeploymentSettings.tsx @@ -251,7 +251,7 @@ function SettingsTable({ rows, onChanged }: { rows: SettingRow[]; onChanged: () const save = async (row: SettingRow) => { setBusy(true); try { - const after = await adminSettingSet(row.name, parsed(draft, row), expected); + const after = await adminSettingSet(row.name, parsed(draft, row), expected, "explicit"); toast(`${row.name} is ${shown(after.value)} on every replica within seconds`, "ok"); close(row.name, true); onChanged(); @@ -271,7 +271,7 @@ function SettingsTable({ rows, onChanged }: { rows: SettingRow[]; onChanged: () ) return; try { - await adminSettingReset(row.name, row.value); + await adminSettingReset(row.name, row.value, "explicit"); setFocusNext({ id: controlId("change", row.name), after: rows }); onChanged(); } catch (e) { diff --git a/frontend/src/views/admin/Duplicates.tsx b/frontend/src/views/admin/Duplicates.tsx index 02dda17a46..d37027a5c0 100644 --- a/frontend/src/views/admin/Duplicates.tsx +++ b/frontend/src/views/admin/Duplicates.tsx @@ -159,7 +159,7 @@ function MemoryCluster({ } setWorking(true); try { - await resolveMemoryDuplicate(scope, cluster, duplicateId, decision); + await resolveMemoryDuplicate(scope, cluster, duplicateId, decision, "explicit"); toast("Resolved", "ok"); onDone(); } catch (e) { @@ -280,7 +280,7 @@ function DocumentCluster({ if (!ok) return; setWorking(true); try { - await retireDocumentDuplicate(scope, keep.source_uri, uri); + await retireDocumentDuplicate(scope, keep.source_uri, uri, "explicit"); toast("Copy retired", "ok"); onDone(); } catch (e) { @@ -370,7 +370,7 @@ function Repairs({ scope, onDone }: { scope: Scope; onDone: () => void }) { const restamp = () => run( async () => { - const r = await collapseMemoryDuplicates(scope, true); + const r = await collapseMemoryDuplicates(scope, true, "explicit"); // The op reads the same first pairs every call: past them, nothing is known. const among = r.truncated ? ` among the first ${COLLAPSE_PAIRS.toLocaleString()} duplicate pairs` : ""; if (r.mirror_stale === 0) @@ -382,21 +382,21 @@ function Repairs({ scope, onDone }: { scope: Scope; onDone: () => void }) { }; }, async () => { - const r = await collapseMemoryDuplicates(scope, false); + const r = await collapseMemoryDuplicates(scope, false, "explicit"); return `Marked ${r.restamped} search row${r.restamped === 1 ? "" : "s"}.`; }, ); const repair = () => run( async () => { - const r = await repairOrphanDuplicates(scope, true); + const r = await repairOrphanDuplicates(scope, true, "explicit"); if (r.candidates === 0) return nothingToDo("No duplicate has lost its canonical."); return { title: `Bring back ${r.candidates} duplicate${r.candidates === 1 ? "" : "s"} whose canonical is gone?`, }; }, async () => { - const n = (await repairOrphanDuplicates(scope, false)).reactivated; + const n = (await repairOrphanDuplicates(scope, false, "explicit")).reactivated; return `Brought back ${n} duplicate${n === 1 ? "" : "s"}.`; }, ); @@ -411,7 +411,7 @@ function Repairs({ scope, onDone }: { scope: Scope; onDone: () => void }) { danger: true, }), async () => { - const r = await consolidateMemories(scope, agent); + const r = await consolidateMemories(scope, agent, "explicit"); if (r.clusters_found === 0) return `Read ${r.examined} of ${agent}'s memories: no near-duplicates.`; const kept = r.clusters_failed; const why = r.clusters_refused_lossy ? ` (${r.clusters_refused_lossy} because the merge lost a detail)` : ""; diff --git a/frontend/src/views/admin/Erasures.tsx b/frontend/src/views/admin/Erasures.tsx index d625c58001..6581c3c47b 100644 --- a/frontend/src/views/admin/Erasures.tsx +++ b/frontend/src/views/admin/Erasures.tsx @@ -278,7 +278,7 @@ function ScopeDialog({ const signal = AbortSignal.timeout(LONG_CALL_MS); try { if (erase) { - const r = await requestErasure(identity.org, scope, requester, purges, signal); + const r = await requestErasure(identity.org, scope, requester, purges, signal, "explicit"); toast( r.status === "failed" ? `Erasure failed: ${r.failure_reason}` : `Erasure ${r.status}`, r.status === "failed" ? "error" : "ok", diff --git a/frontend/src/views/admin/OrgGuardrails.tsx b/frontend/src/views/admin/OrgGuardrails.tsx index 49e407cab1..3b711eac81 100644 --- a/frontend/src/views/admin/OrgGuardrails.tsx +++ b/frontend/src/views/admin/OrgGuardrails.tsx @@ -73,8 +73,8 @@ function ExtractionRules({ scope }: { scope: PolicyScope }) { setBusy(true); try { const p = clear - ? await clearExtractionPolicy(identity, scope) - : await setExtractionPolicy(identity, scope, draft.trim()); + ? await clearExtractionPolicy(identity, scope, "explicit") + : await setExtractionPolicy(identity, scope, draft.trim(), "explicit"); setPolicy(p); setDraft(p.policy); // Name the panel's scope: a save can answer after a switch. @@ -192,7 +192,7 @@ function ModelCallsPanel() { return; setBusy(true); try { - setState(await setOrgModelCalls(identity.org, enabled, reason.trim())); + setState(await setOrgModelCalls(identity.org, enabled, reason.trim(), "explicit")); setReason(""); toast(`Model calls ${enabled ? "on" : "off"} for ${identity.org}`, "ok"); } catch (e) { diff --git a/frontend/src/views/admin/Policies.tsx b/frontend/src/views/admin/Policies.tsx index 94c0ff4de3..8e53d1a676 100644 --- a/frontend/src/views/admin/Policies.tsx +++ b/frontend/src/views/admin/Policies.tsx @@ -273,7 +273,7 @@ export function Policies() { ) return; try { - await deletePolicy({ org: identity.org, namespace: identity.namespace }, r.policy_id); + await deletePolicy({ org: identity.org, namespace: identity.namespace }, r.policy_id, "explicit"); toast("Rule deleted", "ok"); setReads((n) => n + 1); } catch (e) { @@ -461,6 +461,7 @@ function AddRuleDialog({ open, onClose, onSaved }: { open: boolean; onClose: () const out = await setPolicy( { org: identity.org, namespace: identity.namespace }, { policy_id: id, effect, actions: acts, condition: cond, description: description.trim() || undefined }, + "explicit", ); toast(`Rule "${out.rule.policy_id}" saved (${out.leaf_count} leaf${out.leaf_count === 1 ? "" : "s"})`, "ok"); reset(); @@ -591,6 +592,7 @@ function DryRunPanel({ onRan }: { onRan: () => void }) { const out = await checkPolicy( { org: identity.org, namespace: identity.namespace }, { operation: op, agent: agent.trim() || undefined, args: parsed }, + "explicit", ); setResult(out); onRan(); diff --git a/frontend/src/views/admin/ProjectionFailures.tsx b/frontend/src/views/admin/ProjectionFailures.tsx index 903a60881d..f234debe6a 100644 --- a/frontend/src/views/admin/ProjectionFailures.tsx +++ b/frontend/src/views/admin/ProjectionFailures.tsx @@ -54,7 +54,7 @@ export function ProjectionFailuresPanel() { }; const retry = () => act(async () => { - const r = await retryProjectionFailures(identity); + const r = await retryProjectionFailures(identity, "explicit"); const count = (keep: (x: ProjectionRetry) => boolean) => r.results.filter(keep).length; const fixed = count((x) => x.resolved); const failedAgain = count((x) => x.retried && !x.resolved && !x.abandoned); @@ -71,7 +71,7 @@ export function ProjectionFailuresPanel() { }); const dismiss = (id: string) => act(async () => { - await resolveProjectionFailures(identity.org, [id]); + await resolveProjectionFailures(identity.org, [id], "explicit"); toast("Dismissed", "ok"); }); diff --git a/frontend/src/views/admin/Proposals.tsx b/frontend/src/views/admin/Proposals.tsx index 3436479a0c..24802142de 100644 --- a/frontend/src/views/admin/Proposals.tsx +++ b/frontend/src/views/admin/Proposals.tsx @@ -101,7 +101,7 @@ export function ProposalsPanel() { try { const r = await decideProposals(scope, [key], decision, { [key]: approvedHash, - }); + }, "explicit"); const result = r.results[0]; if (r.decided === 0) // Not a proposal any more: decided by the policy or by someone else first. diff --git a/frontend/src/views/admin/Repairs.tsx b/frontend/src/views/admin/Repairs.tsx index 5afc0a5fad..d6d111d1cf 100644 --- a/frontend/src/views/admin/Repairs.tsx +++ b/frontend/src/views/admin/Repairs.tsx @@ -45,7 +45,7 @@ export function RepairsPanel({ unavailable = null }: { unavailable?: string | nu const sweep = () => run(async () => { - const preview = await sweepExpired(identity, true); + const preview = await sweepExpired(identity, true, "explicit"); const due = preview.tombstoned + preview.demoted + preview.anonymized; if (due === 0) { const locked = preview.locked_skipped; @@ -62,7 +62,7 @@ export function RepairsPanel({ unavailable = null }: { unavailable?: string | nu })) ) return; - const r = await sweepExpired(identity, false); + const r = await sweepExpired(identity, false, "explicit"); const done = r.tombstoned + r.demoted + r.anonymized; // The pass counts before it writes: a scan or insert failure wrote nothing; a mirror // failure means the memories expired but their search rows were not updated. @@ -83,7 +83,7 @@ export function RepairsPanel({ unavailable = null }: { unavailable?: string | nu confirmLabel: "Re-embed", }); if (!ok) return; - const r = await reembedMemories(identity); + const r = await reembedMemories(identity, "explicit"); if (r.processed === 0) return toast(`No memory here needs re-embedding with ${r.target_model}.`, "info"); const rest = r.processed === REEMBED_LIMIT ? "; run it again for the rest" : ""; toast(`Re-embedded ${r.processed} with ${r.target_model}${rest}`, "ok"); @@ -99,7 +99,7 @@ export function RepairsPanel({ unavailable = null }: { unavailable?: string | nu danger: true, }); if (!ok) return; - const r = await expireAdapterFacts(identity, name); + const r = await expireAdapterFacts(identity, name, "explicit"); toast(`Removed ${r.expired_triples} facts and ${r.expired_triple_memories} memory links`, "ok"); setAdapter(""); }); @@ -107,7 +107,7 @@ export function RepairsPanel({ unavailable = null }: { unavailable?: string | nu const rollback = () => run(async () => { const at = new Date(asOf).toISOString(); - const preview = await rollbackNamespace(identity, at, true); + const preview = await rollbackNamespace(identity, at, true, "explicit"); if (preview.reinstate + preview.remove === 0) return toast("Every memory already stands as it did then.", "info"); const more = preview.truncated ? " (the first 5,000 keys)" : ""; const ok = await confirmAction({ @@ -117,14 +117,14 @@ export function RepairsPanel({ unavailable = null }: { unavailable?: string | nu danger: true, }); if (!ok) return; - const r = await rollbackNamespace(identity, at, false); + const r = await rollbackNamespace(identity, at, false, "explicit"); const rest = r.truncated ? "; run it again for the rest" : ""; toast(`Rolled back: ${r.reinstate} reinstated, ${r.remove} removed${rest}`, "ok"); }); const download = () => run(async () => { - saveJson(await snapshotNamespace(identity), `${identity.namespace}-snapshot.json`); + saveJson(await snapshotNamespace(identity, "explicit"), `${identity.namespace}-snapshot.json`); }); const restore = (file: File) => @@ -137,7 +137,7 @@ export function RepairsPanel({ unavailable = null }: { unavailable?: string | nu danger: true, }); if (!ok) return; - const r = await restoreNamespace(identity.org, identity.namespace, payload); + const r = await restoreNamespace(identity.org, identity.namespace, payload, "explicit"); if (!r.restored) return toast("This snapshot was already restored here", "info"); const erased = r.counts.erased_skipped ? `, ${r.counts.erased_skipped} skipped as erased` : ""; // `memories` is the file's count; the erased ones in it were not written. diff --git a/frontend/src/views/admin/ReviewQueue.tsx b/frontend/src/views/admin/ReviewQueue.tsx index f6b8ab7883..59e07f6c12 100644 --- a/frontend/src/views/admin/ReviewQueue.tsx +++ b/frontend/src/views/admin/ReviewQueue.tsx @@ -462,6 +462,7 @@ function ConflictsPanel() { current.memory_id, decision, reason.trim() ? { reason: reason.trim() } : {}, + "explicit", ); // Nothing was resolved (the row is gone or out of scope): the queue is read again // rather than dropping a row on a claim. @@ -624,7 +625,7 @@ function RevisionHint({ memoryId }: { memoryId: string }) { const ask = async () => { setBusy(true); try { - const r = await proposeRevision({ org: identity.org, namespace: identity.namespace }, memoryId); + const r = await proposeRevision({ org: identity.org, namespace: identity.namespace }, memoryId, "explicit"); setHint(r.found ? r.suggestions : "gone"); // The link that had focus is gone; the answer takes it. region.current?.focus(); @@ -830,7 +831,7 @@ function LearningsPanel({ const decide = async (id: string, decision: "promote" | "reject") => { if (reviewReason) return; try { - await reviewLearning({ org: identity.org, namespace: identity.namespace }, id, decision, reason[id] || ""); + await reviewLearning({ org: identity.org, namespace: identity.namespace }, id, decision, reason[id] || "", "explicit"); toast(decision === "promote" ? "Promoted" : "Rejected", "ok"); setReload((n) => n + 1); } catch (e) { @@ -1117,6 +1118,7 @@ function AutoResolvedPanel() { { org: identity.org, namespace: identity.namespace, agent: r.agent }, r.memory_key, { user_id: r.user_id, session_id: r.session_id, if_superseded_by: r.superseded_by }, + "explicit", ); if (!mounted.current) return; setOutcome((m) => new Map(m).set(k, out.restored ? "restored" : "gone")); @@ -1304,7 +1306,7 @@ function AllowlistPanel({ initial, onSeedUsed }: { initial?: AllowlistRow[] | nu ) return; try { - await removeAllowlist({ org: identity.org, namespace: identity.namespace }, a, b); + await removeAllowlist({ org: identity.org, namespace: identity.namespace }, a, b, undefined, "explicit"); toast("Removed", "ok"); setReload((n) => n + 1); } catch (e) { diff --git a/frontend/src/views/admin/Spending.tsx b/frontend/src/views/admin/Spending.tsx index 1639dcf693..63f281c760 100644 --- a/frontend/src/views/admin/Spending.tsx +++ b/frontend/src/views/admin/Spending.tsx @@ -568,7 +568,7 @@ function BudgetCapEditor({ toast("Namespace not found", "error"); return; } - await reregisterNamespace({ org, namespace }, ns, { daily_cost_cap_usd: v }); + await reregisterNamespace({ org, namespace }, ns, { daily_cost_cap_usd: v }, "explicit"); // The sidebar's badge and this page read budget status through one shared cache. invalidateShared(`budget:${org}/${namespace}`); toast(v > 0 ? `Cap set to $${v.toFixed(4)}/day` : "Cap removed (inherits global default)", "ok"); diff --git a/frontend/src/views/admin/Users.tsx b/frontend/src/views/admin/Users.tsx index 9d59689850..a03cb9693d 100644 --- a/frontend/src/views/admin/Users.tsx +++ b/frontend/src/views/admin/Users.tsx @@ -317,7 +317,7 @@ function ClaimReleaseSection() { return; setBusy(true); try { - const r = await claimRelease(identity.org, ns.trim(), reason.trim()); + const r = await claimRelease(identity.org, ns.trim(), reason.trim(), "explicit"); setResult( `Released ${r.namespace} (was owned by ${r.previous_owner || "unknown"}, revoked ${r.grants_revoked} grants).`, ); diff --git a/frontend/src/views/assistant/Chat.tsx b/frontend/src/views/assistant/Chat.tsx index 61d206a91b..7ca0a01c64 100644 --- a/frontend/src/views/assistant/Chat.tsx +++ b/frontend/src/views/assistant/Chat.tsx @@ -183,7 +183,7 @@ export function AssistantChat({ // The button pressed goes once the answer starts: the focus goes to the question field. const askAgain = (t: Turn, withSources?: boolean) => { if (blocked) return; - retry(t.id, namespace, { withSources }); + retry(t.id, namespace, { withSources }, "explicit"); field.current?.focus(); }; const edit = () => { @@ -215,8 +215,8 @@ export function AssistantChat({ replace: edited.id, fromField: true, ...(editing?.withSources ? { withSources: true } : {}), - }); - else ask(question, namespace, asked); + }, "explicit"); + else ask(question, namespace, asked, null, {}, "explicit"); }; const onKeyDown = (e: KeyboardEvent) => { diff --git a/frontend/src/views/assistant/Dock.tsx b/frontend/src/views/assistant/Dock.tsx index c382b1a3de..27c3a5d9b4 100644 --- a/frontend/src/views/assistant/Dock.tsx +++ b/frontend/src/views/assistant/Dock.tsx @@ -268,7 +268,7 @@ export function DockBody() { // A turn asked again and refused is answered again in its place, as it was asked again; // the field empties only when it holds the question. const { question, asked: _asked, ...again } = pending; - ask(question, c.namespace ?? header, asked, null, { ...again, fromField: draft === question }); + ask(question, c.namespace ?? header, asked, null, { ...again, fromField: draft === question }, "explicit"); }; // Chat not set up or its setup failing: the panel is its empty state and the starters, diff --git a/frontend/src/views/assistant/SearchAnswer.tsx b/frontend/src/views/assistant/SearchAnswer.tsx index d68591e4bc..df51cfcea1 100644 --- a/frontend/src/views/assistant/SearchAnswer.tsx +++ b/frontend/src/views/assistant/SearchAnswer.tsx @@ -23,7 +23,7 @@ import { pageContext } from "./pageContext"; * an answer is still coming in, which nothing interrupts: the question then waits in the * panel's empty field. */ -export function askFromSearch(question: string, onTurn: (turnId: string) => void): boolean { +export function askFromSearch(question: string, onTurn: (turnId: string) => void, intent: "automatic" | "explicit" = "automatic"): boolean { const st = useStore.getState(); const header = st.identity?.namespace ?? ""; if (useChat.getState().answering) { @@ -39,7 +39,7 @@ export function askFromSearch(question: string, onTurn: (turnId: string) => void // leaves the field, so the panel does not ask it again. if (useDock.getState().draft === question) useDock.setState({ draft: "" }); const context = pageContext(st.view, null, useDock.getState().pageOff); - ask(question, header, { context, item: null }, null, { fromField: false, keepChip: true, shown: onTurn }); + ask(question, header, { context, item: null }, null, { fromField: false, keepChip: true, shown: onTurn }, intent); // Said as the panel's Ask about this says it (ask() clears the notice as it starts). if (line) { useChat.setState({ notice: line }); diff --git a/frontend/src/views/assistant/cards/Card.tsx b/frontend/src/views/assistant/cards/Card.tsx index efd70b89a5..e0bde39e27 100644 --- a/frontend/src/views/assistant/cards/Card.tsx +++ b/frontend/src/views/assistant/cards/Card.tsx @@ -163,6 +163,7 @@ function Body({ "memory.inspect", { subject, id }, { alsoAsk: now.asks, gate: gate("memory.inspect"), namespace, unanswered: now.unanswered }, + "explicit", ); }; // A pick is off as the subject starter is: while an answer comes in, and when its read diff --git a/frontend/src/views/assistant/cards/Starters.tsx b/frontend/src/views/assistant/cards/Starters.tsx index 404f07ec22..7c35acf480 100644 --- a/frontend/src/views/assistant/cards/Starters.tsx +++ b/frontend/src/views/assistant/cards/Starters.tsx @@ -88,7 +88,7 @@ export function Starters({ gate: gate(s.op), namespace, unanswered, - }); + }, "explicit"); }; // A starter is off only when it can do nothing: its read is not allowed and nothing is asked. const off = (s: Starter) => (answering ? "An answer is still coming in." : asks ? null : gate(s.op)); diff --git a/frontend/src/views/assistant/cards/TuneBody.tsx b/frontend/src/views/assistant/cards/TuneBody.tsx index 7e6524a49b..6bf3cc7877 100644 --- a/frontend/src/views/assistant/cards/TuneBody.tsx +++ b/frontend/src/views/assistant/cards/TuneBody.tsx @@ -46,7 +46,7 @@ export function TuneBody({ tune, fresh, readAt }: { tune: NamespaceTune; fresh: }); if (!ok) return; try { - const r = await registerCategory(scope, name, description); + const r = await registerCategory(scope, name, description, "explicit"); toast( r.embedded ? `Registered ${name}` : `Registered ${name}; category search finds it once it is embedded`, "ok", diff --git a/frontend/src/views/assistant/cards/cardStore.ts b/frontend/src/views/assistant/cards/cardStore.ts index e73dc26acd..5250bb28b0 100644 --- a/frontend/src/views/assistant/cards/cardStore.ts +++ b/frontend/src/views/assistant/cards/cardStore.ts @@ -196,6 +196,7 @@ export function startStarter( namespace, unanswered, }: { alsoAsk: boolean; gate: string | null; namespace: string; unanswered?: string | null }, + intent: "automatic" | "explicit" = "automatic", ): void { const st = useChat.getState(); // With the chat off a stored conversation is read-only: nothing is appended to it. @@ -222,7 +223,7 @@ export function startStarter( readCard(turnId, gate); }; if (alsoAsk) { - ask(question, namespace, { context: null, item: null }, { card, shown: (id) => readCard(id, gate), alone }); + ask(question, namespace, { context: null, item: null }, { card, shown: (id) => readCard(id, gate), alone }, {}, intent); return; } useChat.setState({ notice: null }); diff --git a/frontend/src/views/assistant/chatStore.ts b/frontend/src/views/assistant/chatStore.ts index 817e200e33..8fe19fac7e 100644 --- a/frontend/src/views/assistant/chatStore.ts +++ b/frontend/src/views/assistant/chatStore.ts @@ -391,6 +391,7 @@ export function ask( asked: Asked = { context: null, item: null }, withCard: WithCard | null = null, opts: AskOptions = {}, + intent: "automatic" | "explicit" = "automatic", ): void { const s = useChat.getState(); if (s.answering) return; @@ -401,7 +402,7 @@ export function ask( // Answering from here on, so a second Ask waits; the turn shows once the lock is held. useChat.setState({ answering: true, notice: null }); useDock.setState({ working: true }); - const run = (held: boolean) => answer(id, ns, question, asked, mine, held, withCard, opts); + const run = (held: boolean) => answer(id, ns, question, asked, mine, held, withCard, opts, intent); const locks = webLocks(); if (!locks?.request) { void run(false); @@ -467,6 +468,7 @@ async function answer( held: boolean, withCard: WithCard | null, opts: AskOptions, + intent: "automatic" | "explicit", ): Promise { const context = asked.context; // Stopped, or the chat reset, before the lock came: nothing is asked. @@ -586,6 +588,7 @@ async function answer( }, }, mine.signal, + intent, ); } catch (e: unknown) { failure = e; @@ -742,7 +745,7 @@ const lastAsked = (): Turn | null => lastAskedOf(useChat.getState()); /** Ask the last turn's question again in its place, with the context line it was asked * with (Retry), or with CITE_SOURCES (`withSources`, "Ask again with sources"). A * starter's turn reads its card again. */ -export function retry(turnId: string, namespace: string, { withSources }: { withSources?: boolean } = {}): void { +export function retry(turnId: string, namespace: string, { withSources }: { withSources?: boolean } = {}, intent: "automatic" | "explicit" = "automatic"): void { const t = lastAsked(); if (!t || t.id !== turnId) return; // A refused question was given back to the field: asked again, it leaves it. @@ -751,7 +754,7 @@ export function retry(turnId: string, namespace: string, { withSources }: { with replace: t.id, withSources: withSources ?? t.withSources === true, fromField, - }); + }, intent); } /** Put the last question in an empty field to be edited; Ask then answers that turn again, diff --git a/frontend/src/views/registry.ts b/frontend/src/views/registry.ts index b04890182f..ac89d2caaf 100644 --- a/frontend/src/views/registry.ts +++ b/frontend/src/views/registry.ts @@ -19,7 +19,6 @@ export const VIEW_LOADERS: Record Promise> = { code: () => import("./Code"), tasks: () => import("./Tasks"), setup: () => import("./Setup"), - "connected-accounts": () => import("./ConnectedAccounts"), "admin:review_queue": () => import("./admin/ReviewQueue"), "admin:health": () => import("./admin/Health"), "admin:guardrails": () => import("./admin/Blacklist"), diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 2fef744ab8..923586e32a 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,4 +1,5 @@ import { defineConfig, type Plugin, type Rollup } from "vite"; +import { fileURLToPath } from "node:url"; import react from "@vitejs/plugin-react"; import tailwindcss from "@tailwindcss/vite"; import { fileURLToPath } from "node:url"; @@ -91,6 +92,8 @@ export default defineConfig({ }, }, server: { + // The protected browser adapter and operation metadata are maintained SDK source. + fs: { allow: [fileURLToPath(new URL(".", import.meta.url)), fileURLToPath(new URL("../sdk/typescript/src", import.meta.url))] }, port: 5173, proxy: { "/v1": "http://127.0.0.1:7777", diff --git a/llms.txt b/llms.txt index 198065d5fa..c2a46d2861 100644 --- a/llms.txt +++ b/llms.txt @@ -94,6 +94,7 @@ Start with [the docs map](docs/index.md). To install Loom, a coding agent reads - [Headless bots](docs/guides/headless-bots.md): A headless bot runs with no person to paste a token, notice a silent failure or say "remember this". - [Import ClickGap memory](docs/guides/importing-clickgap-memory.md): `loom import-clickgap` loads one SQLite export shape, a ClickGap `lessons` store, into a Loom namespace; skip this page unless you have such an export. - [Store an investigation agent's memory](docs/guides/investigation-agent-memory.md): An investigation agent produces several kinds of state, and Loom has a plane for each. +- [Manage MCP sources from the CLI](docs/guides/mcp-source-cli.md): The Python SDK supplies source controls through `python -m loom.source_cli source`. - [Optimize a namespace from its audit](docs/guides/optimize-namespace.md): A writer that uses `memory.set` as an object store (JSON blobs under hash keys, leases as memories, documents as claims) leaves every table consistent and recall useless. - [Tune Loom's performance](docs/guides/performance-tuning.md): Every lever on this page is a setting or a request field. - [Query Loom from Postgres](docs/guides/query-from-postgres.md): This guide reads a tenant's memories, conversations and usage from the org's own Postgres, where they can be joined with the application's tables. @@ -165,8 +166,11 @@ 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 and Notion registrations. - [LLM and embedding architecture](docs/architecture/llm-architecture.md): Loom has two pluggable providers: an embedder (`server/embedding/`) that turns text into vectors, and an LLM client (`server/llm/`) that completes prompts. +- [MCP document sources](docs/architecture/mcp-document-sources.md): Needs authentication and `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED=true`; enrollment also needs `LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED=true`. - [Outbound MCP source client](docs/architecture/mcp-source-client.md): The outbound MCP source client reads resources through a configured remote HTTP endpoint. +- [Selected MCP source execution](docs/architecture/mcp-source-execution.md): Selected MCP source execution copies explicitly registered text resources into a protected mirror. - [MCP source lifecycle format](docs/architecture/mcp-source-lifecycle.md): MCP source metadata uses the existing connected-account and document-source stores. +- [MCP source setup](docs/architecture/mcp-source-setup.md): MCP source controls register a fixed selection against the signed-in owner's connection and an ordinary destination namespace or collection. - [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. @@ -177,6 +181,7 @@ Start with [the docs map](docs/index.md). To install Loom, a coding agent reads - [Security](docs/architecture/security.md): Loom separates tenants by columns: every row carries the identity tuple, and every read filters on it. - [Server layout](docs/architecture/server-layout.md): `server/` is organised by domain. - [Sharing knowledge](docs/architecture/sharing.md): A collection is a namespace that only grants open. +- [Source CLI execution](docs/architecture/source-cli.md): Source controls execute in the installed Python SDK so browse and read use the maintained session-protection transport. - [Document source push notifications](docs/architecture/source-push.md): Needs `LOOM_KNOWLEDGE_SOURCE_PUSH_ENABLED=true` to request document source syncs from provider notifications. - [Storage authority: Postgres for live memory, ClickHouse for search](docs/architecture/storage-authority.md): Loom runs with one of two memory authorities, chosen per deployment by `LOOM_STORAGE_AUTHORITY`. - [Storage layout: which store holds each table, and why](docs/architecture/storage-layout.md): Each Loom table belongs in Postgres or ClickHouse by how it is read and written; this page places every table, with the wave that moves it. diff --git a/scripts/ops/qualify_mcp_source_scale.py b/scripts/ops/qualify_mcp_source_scale.py new file mode 100644 index 0000000000..7dc189c4bd --- /dev/null +++ b/scripts/ops/qualify_mcp_source_scale.py @@ -0,0 +1,305 @@ +"""Hosted-only synthetic source capacity contract; emit bounded numeric evidence.""" + +from __future__ import annotations + +import argparse +import json +import math +import os +from pathlib import Path +from typing import Any + +from scripts.ops.qualify_mcp_sources import bucket, preflight, quiet + +# Frozen before the first hosted run. Changing these requires a capacity decision. +BOUNDS = { + "registered_min": 10000, + "eligible_min": 1000, + "catalog_p95_seconds": 1.5, + "catalog_p99_seconds": 3.0, + "live_p95_seconds": 5.0, + "live_p99_seconds": 10.0, + "refresh_all_seconds": 600.0, + "tenant_first_seconds": 120.0, + "tenant_first_rounds": 2, + "source_sockets": 32, + "queue": 256, + "rss_bytes": 1073741824, + "rss_delta_bytes": 536870912, + "cancel_join_seconds": 5.0, + "teardown_seconds": 10.0, +} +METRICS = frozenset( + """ +registered registered_distinct eligible eligible_distinct orgs users endpoint_count +healthy_eligible healthy_completed healthy_tenants healthy_tenants_completed +catalog_count catalog_p50 catalog_p95 catalog_p99 live_count live_p50 live_p95 live_p99 +refresh_count refresh_p50 refresh_p95 refresh_p99 refresh_all_seconds throughput +healthy_tenant_first_max healthy_tenant_first_round_max queue_highwater inflight_highwater +org_highwater endpoint_highwater process_peak rss_peak_bytes rss_delta_bytes cpu_seconds +process_sockets_peak source_sockets_peak cancel_join_seconds teardown_seconds +owned_tasks_after_teardown source_inflight_after_teardown restart_restored overlap_fenced +store_requests store_read_rows store_read_bytes store_written_rows store_written_bytes +store_memory_peak_bytes document_count chunk_count original_readbacks failed_turns +rate_limited_endpoints denied_endpoints malformed_endpoints stalled_endpoints +store_rss_peak_bytes store_cpu_percent_peak +""".split() +) + + +def accepted(m: dict[str, float | int]) -> bool: + return set(m) == METRICS and _workload_passes(m) and _capacity_passes(m) + + +def _workload_passes(m: dict[str, float | int]) -> bool: + return all( + ( + m["registered"] >= BOUNDS["registered_min"], + m["registered_distinct"] == m["registered"], + m["eligible"] >= BOUNDS["eligible_min"], + m["eligible_distinct"] == m["eligible"], + m["orgs"] >= 2, + m["users"] >= 2, + m["endpoint_count"] == 10, + m["healthy_eligible"] + == m["healthy_completed"] + == m["refresh_count"] + == m["document_count"], + m["healthy_eligible"] > 0, + m["chunk_count"] >= m["document_count"], + m["original_readbacks"] == m["healthy_completed"], + m["healthy_tenants"] == m["healthy_tenants_completed"], + m["healthy_tenants"] >= 2, + m["catalog_count"] >= 500, + ) + ) + + +def _capacity_passes(m: dict[str, float | int]) -> bool: + return all( + ( + m["live_count"] == m["healthy_eligible"], + m["catalog_p95"] <= BOUNDS["catalog_p95_seconds"], + m["catalog_p99"] <= BOUNDS["catalog_p99_seconds"], + m["live_p95"] <= BOUNDS["live_p95_seconds"], + m["live_p99"] <= BOUNDS["live_p99_seconds"], + m["refresh_all_seconds"] <= BOUNDS["refresh_all_seconds"], + m["healthy_tenant_first_max"] <= BOUNDS["tenant_first_seconds"], + m["healthy_tenant_first_round_max"] <= BOUNDS["tenant_first_rounds"], + m["queue_highwater"] <= 256, + m["inflight_highwater"] <= 16, + m["org_highwater"] <= 4, + m["endpoint_highwater"] <= 2, + m["source_sockets_peak"] <= 32, + m["process_peak"] == 1, + m["rss_peak_bytes"] <= BOUNDS["rss_bytes"], + m["rss_delta_bytes"] <= BOUNDS["rss_delta_bytes"], + m["cancel_join_seconds"] <= 5, + m["teardown_seconds"] <= 10, + m["owned_tasks_after_teardown"] == m["source_inflight_after_teardown"] == 0, + m["restart_restored"] == m["overlap_fenced"] == 1, + all( + m[key] > 0 + for key in ( + "store_requests", + "store_read_rows", + "store_read_bytes", + "store_written_rows", + "store_written_bytes", + "store_rss_peak_bytes", + ) + ), + all( + m[key] == 2 + for key in ( + "rate_limited_endpoints", + "denied_endpoints", + "malformed_endpoints", + "stalled_endpoints", + ) + ), + m["failed_turns"] > 0, + ) + ) + + +class Results: + def __init__(self, path: Path) -> None: + self.path = path + self.metrics: dict[str, float | int] = {} + self.test_passed = False + self.test_failed = False + self.collected = 0 + self.cleanup = "pending" + self.commit = os.environ.get("QUALIFICATION_SHA", "") + self.authority = os.environ.get("LOOM_STORAGE_AUTHORITY", "unknown") + + def record(self, **values: float | int) -> None: + assert set(values) <= METRICS + assert all(type(v) in (int, float) and math.isfinite(v) and v >= 0 for v in values.values()) + self.metrics.update(values) + self.write() + + def write(self) -> None: + report = { + "schema_version": 1, + "bounds": BOUNDS, + "commit": self.commit + if len(self.commit) == 40 and all(c in "0123456789abcdef" for c in self.commit) + else "", + "authority": self.authority + if self.authority in {"clickhouse", "postgres"} + else "unknown", + "status": "passed" + if self.passed() + else "incomplete" + if self.cleanup == "pending" + else "failed", + "stores_cleanup": self.cleanup, + "test_passed": self.test_passed, + "test_failed": self.test_failed, + "collected": self.collected, + "metrics": self.metrics, + "fixture": { + "text_bytes": 8192, + "endpoint_count": 10, + "transport": "asgi", + "registration": "real_store_seed_from_api_template", + "embedding": "fake_ngram_1024", + "extraction": "plain_text_no_extractor", + "store_work": "clickhouse_query_log_bucket_readbacks", + "api_worker_processes": 1, + "asgi_applications": 10, + "tcp_listeners": 0, + "connection_rows": 200, + "registration_api_calls": 200, + "additional_store_seeded_rows": 9800, + "unique_remote_id_strings": 1, + "unique_endpoint_remote_id_pairs": 10, + "healthy_live_source_ids": 40, + "catalog_page_rows": 20, + "scheduler_page_rows": 100, + "source_turn_seconds": 5, + "sources_share_endpoint_by_kind_and_fault": True, + }, + "excluded": [ + "tcp_tls_dns_proxy_capacity", + "vendor_capacity", + "deployment_capacity", + "registration_api_throughput", + "primary_privacy_qualification", + "cross_process_replica_handover", + "postgres_query_work_accounting", + "process_crash_recovery", + ], + } + encoded = json.dumps(report, separators=(",", ":"), sort_keys=True) + "\n" + assert len(encoded) <= 16384 + temporary = self.path.with_suffix(".tmp") + temporary.write_text(encoded) + temporary.replace(self.path) + + def passed(self) -> bool: + return ( + self.cleanup == "passed" + and self.collected == 1 + and self.test_passed + and not self.test_failed + and accepted(self.metrics) + ) + + def pytest_configure(self, config: Any) -> None: + config._mcp_scale_result = self + + def pytest_collection_finish(self, session: Any) -> None: + self.collected = len(session.items) + if self.collected != 1 or {item.name for item in session.items} != { + "test_source_scale_contract" + }: + self.test_failed = True + self.write() + + def pytest_collectreport(self, report: Any) -> None: + if report.failed: + self.test_failed = True + self.write() + + def pytest_runtest_logreport(self, report: Any) -> None: + if report.failed or report.skipped: + self.test_failed = True + if report.when == "call" and report.passed: + self.test_passed = True + self.write() + + +def run(result: Results) -> int: + preflight() + assert os.environ.get("LOOM_MCP_SOURCE_SCALE") == "github-owned" + bucket() + import pytest + + code = int( + pytest.main( + [ + "tests/integration/mcp_source_scale_acceptance.py", + "-q", + "--tb=no", + "--show-capture=no", + ], + plugins=[result], + ) + ) + if code: + result.test_failed = True + result.write() + return ( + 0 + if not code and result.test_passed and not result.test_failed and accepted(result.metrics) + else 1 + ) + + +def finalize(result: Results, cleanup: str) -> int: + raw = result.path.read_bytes() + assert len(raw) <= 16384 + report = json.loads(raw) + assert report["bounds"] == BOUNDS and report["commit"] == result.commit + assert report["authority"] == result.authority and report["schema_version"] == 1 + assert type(report["test_passed"]) is bool and type(report["test_failed"]) is bool + assert type(report["collected"]) is int and 0 <= report["collected"] <= 10000 + result.test_passed, result.test_failed = report["test_passed"], report["test_failed"] + result.collected = report["collected"] + result.record(**report["metrics"]) + result.cleanup = "passed" if cleanup == "0" else "failed" + result.write() + return 0 if result.passed() else 1 + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--result", type=Path, required=True) + parser.add_argument("--cleanup-status", choices=("0", "1")) + args = parser.parse_args() + if args.result.name != "scale-report.json" or not args.result.parent.is_dir(): + parser.error("result must name scale-report.json in an existing directory") + result = Results(args.result) + if args.cleanup_status is None: + result.write() + try: + with quiet(): + code = ( + run(result) + if args.cleanup_status is None + else finalize(result, args.cleanup_status) + ) + except Exception: # noqa: BLE001 — private failures must not reach job output + result.test_failed = True + result.cleanup = "failed" if args.cleanup_status is not None else "pending" + result.write() + code = 1 + print("MCP source scale: status=" + ("passed" if not code else "failed")) + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/ops/qualify_mcp_sources.py b/scripts/ops/qualify_mcp_sources.py new file mode 100644 index 0000000000..7dc6226524 --- /dev/null +++ b/scripts/ops/qualify_mcp_sources.py @@ -0,0 +1,319 @@ +"""Run the owned hosted MCP cases and emit only bounded status/count evidence.""" + +from __future__ import annotations + +import argparse +import contextlib +import json +import os +import re +import sys +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +CASE_NAMES = ( + "writes_refresh", + "owner_privacy", + "source_identity", + "team_copy_grants", + "copy_consent", + "account_revocation", + "owner_grant_revocation", + "profile_revocation", + "pause", + "read_failure", + "scope_revision", + "snapshot", + "schema_drift", + "partial_listing", + "cancellation", + "live", +) +EXPECTED = {f"test_{name}[{kind}]" for name in CASE_NAMES for kind in ("resources", "tools")} + + +@contextlib.contextmanager +def quiet() -> Iterator[None]: + """Native libraries, test hooks and exception reprs must not reach job output.""" + sys.stdout.flush() + sys.stderr.flush() + stdout, stderr = os.dup(1), os.dup(2) + try: + with open(os.devnull, "w") as sink: + os.dup2(sink.fileno(), 1) + os.dup2(sink.fileno(), 2) + yield + finally: + sys.stdout.flush() + sys.stderr.flush() + os.dup2(stdout, 1) + os.dup2(stderr, 2) + os.close(stdout) + os.close(stderr) + + +class Results: + def __init__(self, path: Path) -> None: + self.path = path + self.cases = {name: "unrun" for name in sorted(EXPECTED)} + self.collected = 0 + self.errors = 0 + self.exit_code = 1 + self.stage = "preflight" + commit = os.environ.get("QUALIFICATION_SHA", "") + self.commit = commit if re.fullmatch(r"[0-9a-f]{40}", commit) else "" + authority = os.environ.get("LOOM_STORAGE_AUTHORITY", "") + self.authority = authority if authority in {"clickhouse", "postgres"} else "unknown" + self.cleanup = "pending" + + def write(self) -> None: + counts = { + status: list(self.cases.values()).count(status) + for status in ("passed", "failed", "skipped", "unrun") + } + passed = ( + self.cleanup == "passed" + and self.exit_code == 0 + and self.errors == 0 + and self.collected == len(EXPECTED) + and counts["passed"] == len(EXPECTED) + ) + report = { + "schema_version": 1, + "commit": self.commit, + "authority": self.authority, + "status": "passed" + if passed + else "incomplete" + if self.cleanup == "pending" + else "failed", + "stage": self.stage, + "stores_cleanup": self.cleanup, + "test_exit_code": min(max(self.exit_code, 0), 5), + "expected": len(EXPECTED), + "collected": self.collected, + "errors": self.errors, + "counts": counts, + "cases": self.cases, + "seams": [ + "fixture_asgi_https_routing", + "operator_catalog_input", + "local_ngram_embedding", + "text_requires_no_extractor", + ], + "excluded": [ + "vendors", + "tls_dns_proxy", + "oauth", + "stdio", + "legacy_sse", + "binary", + "durable_derived_memory", + "document_admin_export", + "scale", + "performance", + ], + "dependencies": ["sdk_protected_request_admission"], + } + data = json.dumps(report, sort_keys=True, separators=(",", ":")) + "\n" + assert len(data) <= 8192 + temporary = self.path.with_suffix(".tmp") + temporary.write_text(data, encoding="utf-8") + temporary.replace(self.path) + + def pytest_collection_finish(self, session: Any) -> None: + self.collected = len(session.items) + names = {item.name for item in session.items} + if names != EXPECTED or self.collected != len(EXPECTED): + self.errors += 1 + self.write() + + def pytest_collectreport(self, report: Any) -> None: + if report.failed: + self.errors += 1 + self.write() + + def pytest_runtest_logreport(self, report: Any) -> None: + name = report.nodeid.rsplit("::", 1)[-1] + if name not in self.cases: + self.errors += 1 + elif report.failed: + self.cases[name] = "failed" + elif report.skipped and self.cases[name] != "failed": + self.cases[name] = "skipped" + elif report.when == "call" and report.passed and self.cases[name] == "unrun": + self.cases[name] = "passed" + self.write() + + +def preflight() -> None: + required = { + "GITHUB_ACTIONS": "true", + "RUNNER_ENVIRONMENT": "github-hosted", + "LOOM_MCP_SOURCE_QUALIFICATION": "github-owned", + "LOOM_ENV_FILE": "", + "LOOM_CH_HOST": "127.0.0.1", + "LOOM_AUTH_REQUIRED": "true", + "LOOM_BACKGROUND_WORKERS": "off", + "LOOM_LLM_PROVIDER": "fake", + "LOOM_EMBEDDING_MODEL": "fake-ngram-1024", + "LOOM_DOCUMENT_OBJECT_STORE": "s3", + "LOOM_DOCUMENT_S3_ENDPOINT_URL": "http://127.0.0.1:9000", + "AWS_EC2_METADATA_DISABLED": "true", + } + assert all(os.environ.get(key) == value for key, value in required.items()) + assert os.environ["LOOM_STORAGE_AUTHORITY"] in {"clickhouse", "postgres"} + assert os.environ.get("LOOM_PG_DSN", "") == ( + "postgres://loom:loomdev@127.0.0.1:5432/loom" + if os.environ["LOOM_STORAGE_AUTHORITY"] == "postgres" + else "" + ) + assert re.fullmatch(r"[0-9a-f]{40}", os.environ["QUALIFICATION_SHA"]) + assert not os.environ.get("LOOM_LLM_FALLBACK_MODEL") + assert all( + not os.environ.get(key) + for key in ( + "OPENAI_API_KEY", + "ANTHROPIC_API_KEY", + "GOOGLE_API_KEY", + "GEMINI_API_KEY", + "AWS_SESSION_TOKEN", + "AWS_PROFILE", + ) + ) + assert all( + len(os.environ.get(key, "")) >= 32 + for key in ( + "LOOM_JWT_SECRET", + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + ) + ) + assert re.fullmatch(r"mcp-qualification-[0-9a-f]{24}", os.environ["LOOM_DOCUMENT_S3_BUCKET"]) + + +def bucket() -> None: + import boto3 + from botocore.config import Config + + client = boto3.client( + "s3", + endpoint_url=os.environ["LOOM_DOCUMENT_S3_ENDPOINT_URL"], + region_name="us-east-1", + config=Config(retries={"max_attempts": 0}), + ) + try: + client.create_bucket(Bucket=os.environ["LOOM_DOCUMENT_S3_BUCKET"]) + finally: + client.close() + + +def run(result: Results) -> int: + preflight() + result.stage = "bucket" + result.write() + bucket() + result.stage = "tests" + result.write() + import pytest + + code = int( + pytest.main( + [ + "tests/integration/test_mcp_source_qualification.py", + "-q", + "--tb=no", + "--show-capture=no", + ], + plugins=[result], + ) + ) + result.exit_code = code + result.stage = "finished" + result.write() + return ( + 0 + if code == 0 + and result.errors == 0 + and all(state == "passed" for state in result.cases.values()) + and result.collected == len(EXPECTED) + else 1 + ) + + +def finalize(result: Results, cleanup: str) -> int: + # Read only our fixed, bounded report; never forward arbitrary JSON to an artifact. + raw = result.path.read_bytes() + assert len(raw) <= 8192 + report = json.loads(raw) + assert report["schema_version"] == 1 and set(report["cases"]) == EXPECTED + assert all( + value in {"unrun", "passed", "failed", "skipped"} for value in report["cases"].values() + ) + assert report["commit"] == result.commit and report["authority"] == result.authority + for field in ("collected", "errors", "test_exit_code"): + assert type(report[field]) is int and 0 <= report[field] <= 10000 + result.cases = report["cases"] + result.collected, result.errors = report["collected"], report["errors"] + result.exit_code = report["test_exit_code"] + result.cleanup = "passed" if cleanup == "0" else "failed" + result.stage = "finished" + result.write() + return ( + 0 + if cleanup == "0" + and result.exit_code == 0 + and result.errors == 0 + and all(state == "passed" for state in result.cases.values()) + and result.collected == len(EXPECTED) + else 1 + ) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--result", type=Path, required=True) + parser.add_argument("--cleanup-status", choices=("0", "1")) + args = parser.parse_args() + if args.result.name != "qualification-report.json" or not args.result.parent.is_dir(): + parser.error("result must name qualification-report.json in an existing directory") + result = Results(args.result) + if args.cleanup_status is None: + result.write() + try: + with quiet(): + code = ( + run(result) + if args.cleanup_status is None + else finalize(result, args.cleanup_status) + ) + except Exception as e: # noqa: BLE001 — exception text can contain private fixture payloads + del e + result.errors += 1 + if args.cleanup_status is not None: + result.cleanup = "failed" + result.stage = "finished" + result.write() + code = 1 + passed = list(result.cases.values()).count("passed") + status = ( + "passed" + if code == 0 and result.cleanup == "passed" + else ("tests_passed" if code == 0 else "failed") + ) + print( + f"MCP source qualification: status={status} " + f"passed={passed} expected={len(EXPECTED)} errors={result.errors}" + ) + if args.cleanup_status is not None and os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary: + summary.write( + f"MCP source functional qualification ({result.authority}): {status}; " + f"passed {passed}/{len(EXPECTED)}, errors {result.errors}.\n" + ) + return code + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/sdk/python/README.md b/sdk/python/README.md index a2d2cad377..bcab63c2dc 100644 --- a/sdk/python/README.md +++ b/sdk/python/README.md @@ -218,3 +218,9 @@ The SDK logs through the stdlib logger `loom` (a `NullHandler` by default; your ## License Apache-2.0. See [LICENSE](https://github.com/ClickHouse/loom/blob/main/LICENSE). + +## Protected source clients + +[Session protection](SESSION_PROTECTION.md) describes request readiness, durable +conversation ownership and the automatic-capture interface for CLI and framework +integrations. diff --git a/sdk/python/SESSION_PROTECTION.md b/sdk/python/SESSION_PROTECTION.md new file mode 100644 index 0000000000..043a932806 --- /dev/null +++ b/sdk/python/SESSION_PROTECTION.md @@ -0,0 +1,54 @@ +# Protected source clients + +Bind an application-owned `SessionProtection` to the existing `Agent` or `Transport` +before reading a protected source. The transport validates that capsule and its +response observer before declaring the server's existing request protection +protocol. An unbound ordinary client sends no declaration. Caller-supplied +declarations, duplicate declaration headers and protected requests to another +origin refuse before dispatch. + +```python +from loom.session_protection import SessionProtection +from loom.transport import Transport + +family = SessionProtection.open(saved_pointer) +transport = Transport( + "https://loom.example", api_key=token, + session_protection=family, +) +``` + +Use `SessionProtection.create()` only for an explicitly new independent family. +Save its content-free `pointer()` in trusted application control state. Restores +reopen that pointer; missing or incompatible state refuses. Share the capsule +across clients, tokens, servers and sessions that contribute to the same logical +conversation. Independent conversations use independent capsules. + +CLI and framework owners can pass `session_protection=family` to `Transport` +without changing operation bodies. Wrap every automatic capture callback in +`with family.automatic():`, including writes to another namespace. Marked replies +protect the family before any explicit response is returned. Later automatic +reads and writes raise `AutomaticCaptureSuppressed`. Explicit operations remain +available and still observe their responses. Retain the contributing family for +buffered or deferred work; opening another client must not reset it. + +JSON envelopes are observed before status handling and typed conversion. SSE +observers retain opening families, inspect bounded complete frames before output, +and protect the family on interruption or early close. HTTP errors retain their +envelopes and headers. Invalid JSON and unsupported protected response types +withhold private body diagnostics. No credential is sent to an upstream MCP +server; these clients talk to the configured Loom API. + +The command owner must bind this interface in the CLI. Dashboard wiring, other +maintained clients, durable browser storage and hosted source qualification have +separate integration requirements. These facilities do not activate mirrors. + +`Transport.download(path, params=...)` returns bounded opaque GET bytes. It marks +all opening families before reading or returning the body, including JSON exports +that have no operation-envelope contract. The request makes no retry. The caller +can lower `max_bytes` from its 64 MiB ceiling and `timeout_s` from 60 seconds; +response bookkeeping also stops at 4096 chunks. The owned HTTP response closes on +success, failure or cancellation. Downloads request identity encoding and refuse +a compressed content-encoding response. Ordinary JSON operations keep their +existing response observer. Server authorization still decides which bytes may +be read, and an unbound public download makes no private-result capability claim. diff --git a/sdk/python/loom/cli.py b/sdk/python/loom/cli.py index cb7e702faf..b43cd4848e 100644 --- a/sdk/python/loom/cli.py +++ b/sdk/python/loom/cli.py @@ -21,7 +21,6 @@ from __future__ import annotations import argparse -import asyncio import json import math import os @@ -284,7 +283,23 @@ def _list_ops() -> None: def run(args: argparse.Namespace) -> int: + from loom.cli_context import ContextUnavailable, command_intent + from loom.session_protection import AutomaticCaptureSuppressed, SessionProtectionUnavailable + + try: + with command_intent(args): + return _run(args) + except (ContextUnavailable, AutomaticCaptureSuppressed, SessionProtectionUnavailable): + print( + "Trusted CLI session protection refused; retain its context and proof.", file=sys.stderr + ) + return 2 + + +def _run(args: argparse.Namespace) -> int: """Run one parsed command: prints the answer, returns the exit code.""" + from loom.cli_context import guarded_command, run_sync + try: if args.cmd == "login": credentials.login( @@ -300,9 +315,11 @@ def run(args: argparse.Namespace) -> int: elif args.cmd == "whoami": print(json.dumps(credentials.whoami(args.profile), indent=2)) elif args.cmd == "token": - print(json.dumps(asyncio.run(_token(args)), indent=2, default=str)) + print( + json.dumps(run_sync(lambda: guarded_command(args, _token)), indent=2, default=str) + ) elif args.cmd == "connect": - url = asyncio.run(_connect(args)) + url = run_sync(lambda: guarded_command(args, _connect)) print(f"To connect {args.provider}, open:\n{url}") print("Sign in as the intended account owner and choose Connect or Reconnect.") elif args.list: @@ -314,7 +331,7 @@ def run(args: argparse.Namespace) -> int: ) print(f"loom call: {what} (`loom call --list` lists the ops)", file=sys.stderr) return 2 - result = asyncio.run(_call(args)) + result = run_sync(lambda: guarded_command(args, _call)) if result is not None: print(json.dumps(result, indent=2, default=str)) except (LoomError, httpx.HTTPError, ValueError, OSError) as e: @@ -335,6 +352,12 @@ def run(args: argparse.Namespace) -> int: def main(argv: list[str] | None = None, prog: str = "python -m loom") -> int: parser = argparse.ArgumentParser(prog=prog, description="Use Loom from the command line.") + parser.add_argument( + "--request-intent", + choices=("automatic", "explicit"), + default="automatic", + help="Explicit is one direct human request; automatic is the default.", + ) sub = parser.add_subparsers(dest="cmd", required=True) for name, help_text in ( ("login", "sign in on any browser with a one-time code"), @@ -349,6 +372,12 @@ def main(argv: list[str] | None = None, prog: str = "python -m loom") -> int: formatter_class=argparse.RawDescriptionHelpFormatter, ) p.add_argument("--profile", help="credentials profile (default: LOOM_PROFILE or 'default')") + p.add_argument( + "--request-intent", + choices=("automatic", "explicit"), + default=argparse.SUPPRESS, + help="Explicit is one direct human request; automatic is the default.", + ) if name in ("login", "call"): p.add_argument("--server", help="server URL (default: LOOM_BASE_URL or localhost)") if name == "login": diff --git a/sdk/python/loom/cli_context.py b/sdk/python/loom/cli_context.py new file mode 100644 index 0000000000..faf890d1ab --- /dev/null +++ b/sdk/python/loom/cli_context.py @@ -0,0 +1,283 @@ +"""Trusted CLI context shared by source controls and the server CLI.""" + +from __future__ import annotations + +import asyncio +import contextlib +import contextvars +import json +import os +import threading +from collections.abc import AsyncIterator, Awaitable, Callable, Iterator, Mapping +from concurrent.futures import Future +from dataclasses import dataclass +from typing import Any, TypeVar +from urllib.parse import urlsplit + +import httpx + +from loom.errors import LoomError +from loom.ops import spec +from loom.retry import RetryPolicy +from loom.session_protection import ( + AutomaticCaptureSuppressed as AutomaticCaptureSuppressed, +) +from loom.session_protection import ( + SessionProtection, + SessionProtectionUnavailable, + observation_scope, +) +from loom.transport import Transport + +CLI_CONTEXT_API = 1 +CONTEXT_ENV = "LOOM_SOURCE_SESSION_CONTEXT" +T = TypeVar("T") + + +@dataclass +class _Intent: + explicit: bool + capsule: str | None + active: bool = True + task: object | None = None + + +_intent: contextvars.ContextVar[_Intent | None] = contextvars.ContextVar( + "loom_sdk_cli_intent", default=None +) + + +@contextlib.contextmanager +def command_intent(args: Any) -> Iterator[None]: + """Consume explicit intent once, without retaining it on parsed args or clients.""" + value = _Intent( + vars(args).pop("request_intent", "automatic") == "explicit", + os.environ.get(CONTEXT_ENV), + ) + token = _intent.set(value) + try: + yield + finally: + value.active = False + _intent.reset(token) + + +async def guarded_command(args: Any, action: Callable[[Any], Awaitable[T]]) -> T: + method, path = "POST", "/unknown-cli-route" + if args.cmd == "call": + path = args.target if args.target.startswith("/") else "/v1/" + args.target + method = args.method or ( + "POST" if args.body is not None or not args.target.startswith("/") else "GET" + ) + intent = _intent.get() + if intent is not None and intent.capsule != os.environ.get(CONTEXT_ENV): + raise ContextUnavailable("Trusted CLI session environment changed during dispatch.") + task = asyncio.current_task() + if intent is not None and intent.task is None: + intent.task = task + async with configured_scope( + method, + path, + explicit=intent is not None and intent.active and intent.explicit and intent.task is task, + ): + return await action(args) + + +@contextlib.asynccontextmanager +async def configured_scope( + method: str, path: str, *, explicit: bool = False +) -> AsyncIterator[None]: + """Bind the SDK CLI's maintained clients to the inherited application context.""" + capsule = os.environ.get(CONTEXT_ENV) + if capsule is None: + yield + return + family = open_context(capsule) + with observation_scope((family,)), request_scope(family, method, path, explicit=explicit): + yield + + +class ContextUnavailable(RuntimeError): + """Configured application authority cannot be restored.""" + + +def session_environment(path: str) -> dict[str, str]: + """Provision once in the trusted launcher; retain this environment on resume.""" + from loom.source_cli import open_session + + family = open_session(path) + return { + CONTEXT_ENV: json.dumps( + {"version": 1, "path": path, "pointer": family.pointer()}, + sort_keys=True, + separators=(",", ":"), + ) + } + + +def open_context(capsule: str, *, session_file: str | None = None) -> SessionProtection: + """Reopen the pinned pointer, without creating or repairing authority.""" + from loom.source_cli import _json_object, open_session + + try: + if len(capsule.encode()) > 16 * 1024: + raise ValueError + value = _json_object(capsule) + if ( + set(value) != {"version", "path", "pointer"} + or type(value["version"]) is not int + or value["version"] != 1 + or not isinstance(value["path"], str) + or not isinstance(value["pointer"], dict) + or (session_file is not None and value["path"] != session_file) + ): + raise ValueError + family = open_session(value["path"]) + if family.pointer() != value["pointer"]: + raise ValueError + return family + except (OSError, ValueError, SessionProtectionUnavailable) as exc: + raise ContextUnavailable( + "Trusted CLI session context is unavailable or replaced; restore the original " + "pointer and proof. No reset or cleanup was attempted." + ) from exc + + +@contextlib.contextmanager +def request_scope( + family: SessionProtection, method: str, path: str, *, explicit: bool = False +) -> Iterator[None]: + """Only generated read metadata or direct user intent permits a protected call.""" + family.require_ready() + route = urlsplit(path).path + operation = spec(route[4:]) if method == "POST" and route.startswith("/v1/") else None + readonly = operation is not None and operation.read_only + scope = contextlib.nullcontext() if explicit or readonly else family.automatic() + with scope: + yield + + +def _target(url: str) -> tuple[str, str]: + value = urlsplit(url) + if ( + value.scheme not in ("http", "https") + or not value.netloc + or value.username is not None + or value.password is not None + or value.fragment + ): + raise ContextUnavailable( + "Trusted CLI requests require an HTTP server URL without userinfo." + ) + return value.scheme + "://" + value.netloc, (value.path or "/") + ( + "?" + value.query if value.query else "" + ) + + +def _transport(base: str, token: str, family: SessionProtection, timeout: float) -> Transport: + return Transport( + base, + api_key=token, + session_protection=family, + timeout_s=timeout, + retry=RetryPolicy(max_attempts=1), + pacing=False, + ratelimit_max_wait_s=0, + ) + + +async def request( + capsule: str, + method: str, + url: str, + token: str, + *, + body: Mapping[str, Any] | None = None, + content: bytes | None = None, + timeout_s: float = 90.0, + explicit: bool = False, +) -> httpx.Response: + """One maintained SDK dispatch, observed before returning any response.""" + family = open_context(capsule) + base, path = _target(url) + with request_scope(family, method, path, explicit=explicit): + transport = _transport(base, token, family, timeout_s) + try: + try: + return await transport.request(method, path, json=body, content=content) + except LoomError as exc: + # The SDK already observed the error; never copy private diagnostics to stderr. + return httpx.Response( + exc.status or 503, + json={"detail": {"code": "CLI_REQUEST_FAILED"}}, + request=httpx.Request(method, url), + ) + finally: + await transport.close() + + +@contextlib.asynccontextmanager +async def stream( + capsule: str, + url: str, + token: str, + *, + body: Mapping[str, Any], + timeout_s: float = 90.0, + explicit: bool = False, +) -> AsyncIterator[httpx.Response]: + """Retain SDK observation through stream consumption, cancellation and close.""" + family = open_context(capsule) + base, path = _target(url) + with request_scope(family, "POST", path, explicit=explicit): + transport = _transport(base, token, family, timeout_s) + try: + async with transport.stream(path, json=body) as response: + yield response + finally: + await transport.close() + + +def run_sync(factory: Callable[[], Awaitable[T]]) -> T: + """Run a fresh async client even when a synchronous CLI is called within a loop.""" + + async def direct() -> T: + return await factory() + + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(direct()) + + result: Future[T] = Future() + context = contextvars.copy_context() + running: list[tuple[asyncio.AbstractEventLoop, asyncio.Task[Any]]] = [] + cancelled = threading.Event() + + async def invoke() -> T: + task = asyncio.current_task() + assert task is not None + running.append((asyncio.get_running_loop(), task)) + if cancelled.is_set(): + task.cancel() + return await factory() + + def worker() -> None: + try: + result.set_result(context.run(asyncio.run, invoke())) + except BaseException as exc: # noqa: BLE001 — transfer every failure to the waiting caller + result.set_exception(exc) + + thread = threading.Thread(target=worker, name="loom-cli-request") + thread.start() + try: + return result.result() + except KeyboardInterrupt: + cancelled.set() + if running: + loop, task = running[0] + with contextlib.suppress(RuntimeError): + loop.call_soon_threadsafe(task.cancel) + raise + finally: + thread.join() diff --git a/sdk/python/loom/client.py b/sdk/python/loom/client.py index 25005698f9..9de57e70b6 100644 --- a/sdk/python/loom/client.py +++ b/sdk/python/loom/client.py @@ -677,33 +677,6 @@ async def resolve( ) -class ConnectionOps: - """The `connection.*` operations.""" - - # SyncAgent proxies a nested client's coroutines as blocking calls. - _loom_nested_client = True - - def __init__(self, agent: Agent) -> None: - self._agent = agent - - async def disconnect( - self, body: _ops.ConnectionDisconnectBody | None = None, /, **options: Any - ) -> _ops.ConnectionDisconnectOutput: - """`connection.disconnect`.""" - return cast( - "_ops.ConnectionDisconnectOutput", - await self._agent.call("connection.disconnect", body, **options), - ) - - async def list( - self, body: _ops.ConnectionListBody | None = None, /, **options: Any - ) -> _ops.ConnectionListOutput: - """`connection.list`.""" - return cast( - "_ops.ConnectionListOutput", await self._agent.call("connection.list", body, **options) - ) - - class ConsolidationsOps: """The `consolidations.*` operations.""" @@ -1318,6 +1291,15 @@ async def bulk_delete( await self._agent.call("knowledge.bulk_delete", body, **options), ) + async def connection_mcp_browse( + self, body: _ops.KnowledgeConnectionMcpBrowseBody | None = None, /, **options: Any + ) -> _ops.KnowledgeConnectionMcpBrowseOutput: + """`knowledge.connection.mcp_browse`.""" + return cast( + "_ops.KnowledgeConnectionMcpBrowseOutput", + await self._agent.call("knowledge.connection.mcp_browse", body, **options), + ) + async def connection_mcp_connect( self, body: _ops.KnowledgeConnectionMcpConnectBody | None = None, /, **options: Any ) -> _ops.KnowledgeConnectionMcpConnectOutput: @@ -1601,6 +1583,42 @@ async def source_list( await self._agent.call("knowledge.source.list", body, **options), ) + async def source_mcp_add( + self, body: _ops.KnowledgeSourceMcpAddBody | None = None, /, **options: Any + ) -> _ops.MCPSourceOutput: + """`knowledge.source.mcp_add`.""" + return cast( + "_ops.MCPSourceOutput", + await self._agent.call("knowledge.source.mcp_add", body, **options), + ) + + async def source_mcp_inspect( + self, body: _ops.KnowledgeSourceMcpInspectBody | None = None, /, **options: Any + ) -> _ops.KnowledgeSourceMcpInspectOutput: + """`knowledge.source.mcp_inspect`.""" + return cast( + "_ops.KnowledgeSourceMcpInspectOutput", + await self._agent.call("knowledge.source.mcp_inspect", body, **options), + ) + + async def source_mcp_list( + self, body: _ops.KnowledgeSourceMcpListBody | None = None, /, **options: Any + ) -> _ops.KnowledgeSourceMcpListOutput: + """`knowledge.source.mcp_list`.""" + return cast( + "_ops.KnowledgeSourceMcpListOutput", + await self._agent.call("knowledge.source.mcp_list", body, **options), + ) + + async def source_mcp_pause( + self, body: _ops.MCPSourceBody | None = None, /, **options: Any + ) -> _ops.MCPSourceOutput: + """`knowledge.source.mcp_pause`.""" + return cast( + "_ops.MCPSourceOutput", + await self._agent.call("knowledge.source.mcp_pause", body, **options), + ) + async def source_mcp_preview( self, body: _ops.KnowledgeSourceMcpPreviewBody | None = None, /, **options: Any ) -> _ops.KnowledgeSourceMcpPreviewOutput: @@ -1619,40 +1637,49 @@ async def source_mcp_profiles( await self._agent.call("knowledge.source.mcp_profiles", body, **options), ) - async def source_parse_links( - self, body: _ops.KnowledgeSourceParseLinksBody | None = None, /, **options: Any - ) -> _ops.KnowledgeSourceParseLinksOutput: - """`knowledge.source.parse_links`.""" + async def source_mcp_read( + self, body: _ops.KnowledgeSourceMcpReadBody | None = None, /, **options: Any + ) -> _ops.KnowledgeSourceMcpReadOutput: + """`knowledge.source.mcp_read`.""" return cast( - "_ops.KnowledgeSourceParseLinksOutput", - await self._agent.call("knowledge.source.parse_links", body, **options), + "_ops.KnowledgeSourceMcpReadOutput", + await self._agent.call("knowledge.source.mcp_read", body, **options), ) - async def source_push_configure( - self, body: _ops.KnowledgeSourcePushConfigureBody | None = None, /, **options: Any - ) -> _ops.PushStatusOutput: - """`knowledge.source.push_configure`.""" + async def source_mcp_refresh( + self, body: _ops.MCPSourceBody | None = None, /, **options: Any + ) -> _ops.MCPSourceOutput: + """`knowledge.source.mcp_refresh`.""" return cast( - "_ops.PushStatusOutput", - await self._agent.call("knowledge.source.push_configure", body, **options), + "_ops.MCPSourceOutput", + await self._agent.call("knowledge.source.mcp_refresh", body, **options), ) - async def source_push_confirm( - self, body: _ops.KnowledgeSourcePushConfirmBody | None = None, /, **options: Any - ) -> _ops.PushStatusOutput: - """`knowledge.source.push_confirm`.""" + async def source_mcp_remove( + self, body: _ops.KnowledgeSourceMcpRemoveBody | None = None, /, **options: Any + ) -> _ops.MCPSourceOutput: + """`knowledge.source.mcp_remove`.""" return cast( - "_ops.PushStatusOutput", - await self._agent.call("knowledge.source.push_confirm", body, **options), + "_ops.MCPSourceOutput", + await self._agent.call("knowledge.source.mcp_remove", body, **options), ) - async def source_push_status( - self, body: _ops.KnowledgeSourcePushStatusBody | None = None, /, **options: Any - ) -> _ops.PushStatusOutput: - """`knowledge.source.push_status`.""" + async def source_mcp_resume( + self, body: _ops.MCPSourceBody | None = None, /, **options: Any + ) -> _ops.MCPSourceOutput: + """`knowledge.source.mcp_resume`.""" return cast( - "_ops.PushStatusOutput", - await self._agent.call("knowledge.source.push_status", body, **options), + "_ops.MCPSourceOutput", + await self._agent.call("knowledge.source.mcp_resume", body, **options), + ) + + async def source_mcp_update( + self, body: _ops.KnowledgeSourceMcpUpdateBody | None = None, /, **options: Any + ) -> _ops.MCPSourceOutput: + """`knowledge.source.mcp_update`.""" + return cast( + "_ops.MCPSourceOutput", + await self._agent.call("knowledge.source.mcp_update", body, **options), ) async def source_remove( @@ -1682,15 +1709,6 @@ async def source_sync_now( await self._agent.call("knowledge.source.sync_now", body, **options), ) - async def source_update( - self, body: _ops.KnowledgeSourceUpdateBody | None = None, /, **options: Any - ) -> _ops.KnowledgeSourceUpdateOutput: - """`knowledge.source.update`.""" - return cast( - "_ops.KnowledgeSourceUpdateOutput", - await self._agent.call("knowledge.source.update", body, **options), - ) - async def synthesize( self, body: _ops.KnowledgeSynthesizeBody | None = None, /, **options: Any ) -> _ops.KnowledgeSynthesizeOutput: @@ -3626,7 +3644,6 @@ def __init__(self, agent: Agent) -> None: self.code = CodeOps(agent) self.collection = CollectionOps(agent) self.conflicts = ConflictsOps(agent) - self.connection = ConnectionOps(agent) self.consolidations = ConsolidationsOps(agent) self.context = ContextOps(agent) self.conversation = ConversationOps(agent) diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index bfefd2f2b9..06e189a406 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -109,8 +109,6 @@ class OpSpec: "conflicts.list", "conflicts.propose_revision", "conflicts.resolve", - "connection.disconnect", - "connection.list", "consolidations.list", "context.fetch", "context.offload", @@ -169,6 +167,7 @@ class OpSpec: "knowledge.add", "knowledge.bulk_add", "knowledge.bulk_delete", + "knowledge.connection.mcp_browse", "knowledge.connection.mcp_connect", "knowledge.connection.mcp_disconnect", "knowledge.connection.mcp_discover", @@ -201,16 +200,20 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.mcp_add", + "knowledge.source.mcp_inspect", + "knowledge.source.mcp_list", + "knowledge.source.mcp_pause", "knowledge.source.mcp_preview", "knowledge.source.mcp_profiles", - "knowledge.source.parse_links", - "knowledge.source.push_configure", - "knowledge.source.push_confirm", - "knowledge.source.push_status", + "knowledge.source.mcp_read", + "knowledge.source.mcp_refresh", + "knowledge.source.mcp_remove", + "knowledge.source.mcp_resume", + "knowledge.source.mcp_update", "knowledge.source.remove", "knowledge.source.rotate", "knowledge.source.sync_now", - "knowledge.source.update", "knowledge.synthesize", "knowledge.update_metadata", "knowledge.upsert", @@ -495,8 +498,6 @@ class OpSpec: "conflicts.list", "conflicts.propose_revision", "conflicts.resolve", - "connection.disconnect", - "connection.list", "consolidations.list", "context.fetch", "context.offload", @@ -555,6 +556,7 @@ class OpSpec: "knowledge.add", "knowledge.bulk_add", "knowledge.bulk_delete", + "knowledge.connection.mcp_browse", "knowledge.connection.mcp_connect", "knowledge.connection.mcp_disconnect", "knowledge.connection.mcp_discover", @@ -587,16 +589,20 @@ class OpSpec: "knowledge.source.check", "knowledge.source.inspect", "knowledge.source.list", + "knowledge.source.mcp_add", + "knowledge.source.mcp_inspect", + "knowledge.source.mcp_list", + "knowledge.source.mcp_pause", "knowledge.source.mcp_preview", "knowledge.source.mcp_profiles", - "knowledge.source.parse_links", - "knowledge.source.push_configure", - "knowledge.source.push_confirm", - "knowledge.source.push_status", + "knowledge.source.mcp_read", + "knowledge.source.mcp_refresh", + "knowledge.source.mcp_remove", + "knowledge.source.mcp_resume", + "knowledge.source.mcp_update", "knowledge.source.remove", "knowledge.source.rotate", "knowledge.source.sync_now", - "knowledge.source.update", "knowledge.synthesize", "knowledge.update_metadata", "knowledge.upsert", @@ -1651,30 +1657,6 @@ class OpSpec: True, False, ), - "connection.disconnect": OpSpec( - "connection.disconnect", - "ConnectionDisconnectInput", - "ConnectionDisconnectBody", - "ConnectionDisconnectOutput", - True, - "viewer", - "experimental", - 30000, - False, - False, - ), - "connection.list": OpSpec( - "connection.list", - "ConnectionListInput", - "ConnectionListBody", - "ConnectionListOutput", - True, - "viewer", - "experimental", - 1000, - False, - True, - ), "consolidations.list": OpSpec( "consolidations.list", "ConsolidationsListInput", @@ -2371,6 +2353,18 @@ class OpSpec: True, False, ), + "knowledge.connection.mcp_browse": OpSpec( + "knowledge.connection.mcp_browse", + "KnowledgeConnectionMcpBrowseInput", + "KnowledgeConnectionMcpBrowseBody", + "KnowledgeConnectionMcpBrowseOutput", + True, + "viewer", + "experimental", + 5000, + False, + True, + ), "knowledge.connection.mcp_connect": OpSpec( "knowledge.connection.mcp_connect", "KnowledgeConnectionMcpConnectInput", @@ -2755,6 +2749,54 @@ class OpSpec: False, True, ), + "knowledge.source.mcp_add": OpSpec( + "knowledge.source.mcp_add", + "KnowledgeSourceMcpAddInput", + "KnowledgeSourceMcpAddBody", + "MCPSourceOutput", + False, + "writer", + "experimental", + 30000, + True, + False, + ), + "knowledge.source.mcp_inspect": OpSpec( + "knowledge.source.mcp_inspect", + "KnowledgeSourceMcpInspectInput", + "KnowledgeSourceMcpInspectBody", + "KnowledgeSourceMcpInspectOutput", + True, + "writer", + "experimental", + 5000, + False, + False, + ), + "knowledge.source.mcp_list": OpSpec( + "knowledge.source.mcp_list", + "KnowledgeSourceMcpListInput", + "KnowledgeSourceMcpListBody", + "KnowledgeSourceMcpListOutput", + True, + "writer", + "experimental", + 5000, + False, + False, + ), + "knowledge.source.mcp_pause": OpSpec( + "knowledge.source.mcp_pause", + "MCPSourceInput", + "MCPSourceBody", + "MCPSourceOutput", + False, + "writer", + "experimental", + 5000, + True, + False, + ), "knowledge.source.mcp_preview": OpSpec( "knowledge.source.mcp_preview", "KnowledgeSourceMcpPreviewInput", @@ -2779,52 +2821,64 @@ class OpSpec: False, True, ), - "knowledge.source.parse_links": OpSpec( - "knowledge.source.parse_links", - "KnowledgeSourceParseLinksInput", - "KnowledgeSourceParseLinksBody", - "KnowledgeSourceParseLinksOutput", + "knowledge.source.mcp_read": OpSpec( + "knowledge.source.mcp_read", + "KnowledgeSourceMcpReadInput", + "KnowledgeSourceMcpReadBody", + "KnowledgeSourceMcpReadOutput", True, "viewer", "experimental", - 50, + 5000, False, True, ), - "knowledge.source.push_configure": OpSpec( - "knowledge.source.push_configure", - "KnowledgeSourcePushConfigureInput", - "KnowledgeSourcePushConfigureBody", - "PushStatusOutput", + "knowledge.source.mcp_refresh": OpSpec( + "knowledge.source.mcp_refresh", + "MCPSourceInput", + "MCPSourceBody", + "MCPSourceOutput", False, - "admin", + "writer", "experimental", - 60000, + 5000, True, False, ), - "knowledge.source.push_confirm": OpSpec( - "knowledge.source.push_confirm", - "KnowledgeSourcePushConfirmInput", - "KnowledgeSourcePushConfirmBody", - "PushStatusOutput", + "knowledge.source.mcp_remove": OpSpec( + "knowledge.source.mcp_remove", + "KnowledgeSourceMcpRemoveInput", + "KnowledgeSourceMcpRemoveBody", + "MCPSourceOutput", False, - "admin", + "writer", "experimental", - 1000, + 5000, True, False, ), - "knowledge.source.push_status": OpSpec( - "knowledge.source.push_status", - "KnowledgeSourcePushStatusInput", - "KnowledgeSourcePushStatusBody", - "PushStatusOutput", + "knowledge.source.mcp_resume": OpSpec( + "knowledge.source.mcp_resume", + "MCPSourceInput", + "MCPSourceBody", + "MCPSourceOutput", False, - "admin", + "writer", "experimental", - 1000, + 5000, + True, False, + ), + "knowledge.source.mcp_update": OpSpec( + "knowledge.source.mcp_update", + "KnowledgeSourceMcpUpdateInput", + "KnowledgeSourceMcpUpdateBody", + "MCPSourceOutput", + False, + "writer", + "experimental", + 5000, + True, False, ), "knowledge.source.remove": OpSpec( @@ -2863,18 +2917,6 @@ class OpSpec: True, False, ), - "knowledge.source.update": OpSpec( - "knowledge.source.update", - "KnowledgeSourceUpdateInput", - "KnowledgeSourceUpdateBody", - "KnowledgeSourceUpdateOutput", - False, - "writer", - "experimental", - 60000, - True, - False, - ), "knowledge.synthesize": OpSpec( "knowledge.synthesize", "KnowledgeSynthesizeInput", @@ -8511,48 +8553,6 @@ class ConflictsResolveOutput(TypedDict, total=False): total: NotRequired[Optional[int]] -class ConnectionDisconnectInput(TypedDict, total=False): - "Disconnect the caller's own provider account and stop its connected sources." - - org: Required[str] - kind: Required[Literal["gdrive", "notion", "linear"]] - - -class ConnectionDisconnectBody(TypedDict, total=False): - "Disconnect the caller's own provider account and stop its connected sources." - - org: NotRequired[str] - kind: Required[Literal["gdrive", "notion", "linear"]] - - -class ConnectionDisconnectOutput(TypedDict, total=False): - disconnected: Required[bool] - - -class ConnectionListInput(TypedDict, total=False): - "List the signed-in caller's own connected provider accounts." - - org: Required[str] - - -class ConnectionListBody(TypedDict, total=False): - "List the signed-in caller's own connected provider accounts." - - org: NotRequired[str] - - -class ConnectionListOutput(TypedDict, total=False): - connections: Required[list["ConnectionEntry"]] - - -class ConnectionEntry(TypedDict, total=False): - kind: Required[Literal["gdrive", "notion", "linear"]] - connected: Required[bool] - account_email: NotRequired[Optional[str]] - scopes: NotRequired[list[str]] - connect_url: Required[str] - - class ConsolidationsListInput(TypedDict, total=False): "Namespace-scoped consolidation-run history. agent + user_id are" @@ -10676,6 +10676,46 @@ class KnowledgeBulkDeleteResult(TypedDict, total=False): chunks_tombstoned: Required[int] +class KnowledgeConnectionMcpBrowseInput(TypedDict, total=False): + org: Required[str] + slot: Required[str] + mode: Required[Literal["resources", "search"]] + query: NotRequired[str] + limit: NotRequired[int] + + +class KnowledgeConnectionMcpBrowseBody(TypedDict, total=False): + org: NotRequired[str] + slot: Required[str] + mode: Required[Literal["resources", "search"]] + query: NotRequired[str] + limit: NotRequired[int] + + +class KnowledgeConnectionMcpBrowseOutput(TypedDict, total=False): + slot: Required[str] + generation: Required[str] + mode: Required[Literal["resources", "search"]] + supported: NotRequired[bool] + resources: Required[Optional[bool]] + mapped_read: Required[bool] + mapped_search: Required[bool] + capabilities_checked: NotRequired[bool] + items: NotRequired[list["MCPBrowseItem"]] + complete: NotRequired[bool] + truncated: NotRequired[bool] + reason: NotRequired[Optional[str]] + limitations: Required[list[str]] + manual_resource_ids_supported: NotRequired[Literal[True]] + remote_identity_verified: NotRequired[Literal[False]] + + +class MCPBrowseItem(TypedDict, total=False): + id: Required[str] + title: Required[str] + uri: Required[str] + + class KnowledgeConnectionMcpConnectInput(TypedDict, total=False): org: Required[str] profile_id: Required[str] @@ -11925,34 +11965,26 @@ class SearchHit(TypedDict, total=False): class KnowledgeSourceAddInput(TypedDict, total=False): - "Register a document source on a namespace: a kind, what it reads (items" + "Register a shared recording source after checking its read-only credential." org: Required[str] namespace: Required[str] name: Required[str] - kind: Required[str] - items: NotRequired[Optional[list[dict[str, Any]]]] - links: NotRequired[Optional[list[str]]] - config: NotRequired[Optional[dict[str, Any]]] - include: NotRequired[Optional[list[str]]] - credential_mode: NotRequired[Literal["shared", "connected"]] - credential: NotRequired[str] + kind: NotRequired[Literal["recording"]] + config: Required[dict[str, Any]] + credential: Required[str] dry_run: NotRequired[bool] class KnowledgeSourceAddBody(TypedDict, total=False): - "Register a document source on a namespace: a kind, what it reads (items" + "Register a shared recording source after checking its read-only credential." org: NotRequired[str] namespace: NotRequired[str] name: Required[str] - kind: Required[str] - items: NotRequired[Optional[list[dict[str, Any]]]] - links: NotRequired[Optional[list[str]]] - config: NotRequired[Optional[dict[str, Any]]] - include: NotRequired[Optional[list[str]]] - credential_mode: NotRequired[Literal["shared", "connected"]] - credential: NotRequired[str] + kind: NotRequired[Literal["recording"]] + config: Required[dict[str, Any]] + credential: Required[str] dry_run: NotRequired[bool] @@ -11960,8 +11992,6 @@ class KnowledgeSourceAddOutput(TypedDict, total=False): name: Required[str] kind: Required[str] namespace: Required[str] - items: NotRequired[list[dict[str, Any]]] - include: NotRequired[list[str]] config: NotRequired[dict[str, Any]] probe: NotRequired["KnowledgeSourceProbe"] dry_run: NotRequired[bool] @@ -11973,12 +12003,10 @@ class KnowledgeSourceProbe(TypedDict, total=False): documents: NotRequired[int] more: NotRequired[bool] sample: NotRequired[list[str]] - checked: NotRequired[int] - sampled: NotRequired[bool] class KnowledgeSourceCheckInput(TypedDict, total=False): - "Probe a registered document source with its stored credential now (a check of" + "Probe a shared recording with its stored credential without writing." org: Required[str] namespace: Required[str] @@ -11986,7 +12014,7 @@ class KnowledgeSourceCheckInput(TypedDict, total=False): class KnowledgeSourceCheckBody(TypedDict, total=False): - "Probe a registered document source with its stored credential now (a check of" + "Probe a shared recording with its stored credential without writing." org: NotRequired[str] namespace: NotRequired[str] @@ -11999,14 +12027,12 @@ class KnowledgeSourceCheckOutput(TypedDict, total=False): documents: NotRequired[int] more: NotRequired[bool] sample: NotRequired[list[str]] - checked: NotRequired[int] - sampled: NotRequired[bool] summary: NotRequired[str] checked_at: NotRequired[str] class KnowledgeSourceInspectInput(TypedDict, total=False): - "One registered document source: its items, its sync state and the" + "One registered document source: its config, its sync state and the" org: Required[str] namespace: Required[str] @@ -12014,7 +12040,7 @@ class KnowledgeSourceInspectInput(TypedDict, total=False): class KnowledgeSourceInspectBody(TypedDict, total=False): - "One registered document source: its items, its sync state and the" + "One registered document source: its config, its sync state and the" org: NotRequired[str] namespace: NotRequired[str] @@ -12027,8 +12053,6 @@ class KnowledgeSourceInspectOutput(TypedDict, total=False): credential_mode: NotRequired[str] access: NotRequired[str] owner_subject: NotRequired[str] - items: NotRequired[list[dict[str, Any]]] - include: NotRequired[list[str]] config: NotRequired[dict[str, Any]] created_by: NotRequired[str] created_at: NotRequired[str] @@ -12090,44 +12114,68 @@ class KnowledgeSourceEntry(TypedDict, total=False): credential_mode: NotRequired[str] access: NotRequired[str] owner_subject: NotRequired[str] - items: NotRequired[list[dict[str, Any]]] - include: NotRequired[list[str]] config: NotRequired[dict[str, Any]] created_by: NotRequired[str] created_at: NotRequired[str] sync: NotRequired["KnowledgeSourceSync"] -class KnowledgeSourceMcpPreviewInput(TypedDict, total=False): +class KnowledgeSourceMcpAddInput(TypedDict, total=False): org: Required[str] namespace: Required[str] slot: Required[str] mode: Required[Literal["live", "snapshot", "selected_refresh"]] reader_policy: NotRequired[Literal["owner_only", "collection_copy"]] resource_ids: Required[list[str]] + request_id: Required[str] + label: NotRequired[Optional[str]] + confirm_copy_authority: NotRequired[bool] -class KnowledgeSourceMcpPreviewBody(TypedDict, total=False): +class KnowledgeSourceMcpAddBody(TypedDict, total=False): org: NotRequired[str] namespace: NotRequired[str] slot: Required[str] mode: Required[Literal["live", "snapshot", "selected_refresh"]] reader_policy: NotRequired[Literal["owner_only", "collection_copy"]] resource_ids: Required[list[str]] + request_id: Required[str] + label: NotRequired[Optional[str]] + confirm_copy_authority: NotRequired[bool] -class KnowledgeSourceMcpPreviewOutput(TypedDict, total=False): +class MCPSourceOutput(TypedDict, total=False): + source: Required["MCPSourceEntry"] + copies: NotRequired[Literal["retained", "erasure_requested"]] + refresh_requested: NotRequired[bool] + + +class MCPSourceEntry(TypedDict, total=False): + name: Required[str] + source_id: Required[str] + slot: Required[str] namespace: Required[str] - mode: Required[Literal["live", "snapshot", "selected_refresh"]] - rule: Required["MCPAccessRule"] - connection_state: Required[Literal["configured", "stopped", "unavailable", "approval_drift"]] + state: Required[Literal["registered", "paused", "retired", "unsupported"]] + mode: NotRequired[Optional[Literal["live", "snapshot", "selected_refresh"]]] + reader_policy: NotRequired[Optional[Literal["owner_only", "collection_copy"]]] + scope_revision: NotRequired[Optional[int]] + label: NotRequired[Optional[str]] + selected_count: NotRequired[Optional[int]] + sync_enabled: Required[bool] + read_evidence_stale_seconds: Required[int] + refresh_state: Required[ + Literal["not_applicable", "enabled", "disabled", "paused", "retired", "unsupported"] + ] compatibility: NotRequired[Literal["unchecked"]] - permission_evidence: NotRequired[Literal["unsupported"]] - refresh_state: Required[Literal["not_applicable", "enabled", "disabled"]] - selected_count: Required[int] - checked_at: Required[str] - preview_grants_authority: NotRequired[Literal[False]] - limitations: Required[list[str]] + upstream_permissions: NotRequired[Literal["unsupported"]] + complete_enumeration: NotRequired[Literal[False]] + upstream_deletion_tracking: NotRequired[Literal[False]] + future_items_included: NotRequired[Literal[False]] + current_access_attested: NotRequired[Literal[False]] + local_authority: NotRequired[Literal["current", "unavailable", "unchecked"]] + pending_erasure: NotRequired[bool] + rule: NotRequired[Optional["MCPAccessRule"]] + resource_ids: NotRequired[list[str]] class MCPAccessRule(TypedDict, total=False): @@ -12144,6 +12192,120 @@ class MCPAccessRule(TypedDict, total=False): explanation: Required[str] +class KnowledgeSourceMcpInspectInput(TypedDict, total=False): + org: Required[str] + namespace: Required[str] + name: NotRequired[str] + slot: NotRequired[str] + request_id: NotRequired[str] + + +class KnowledgeSourceMcpInspectBody(TypedDict, total=False): + org: NotRequired[str] + namespace: NotRequired[str] + name: NotRequired[str] + slot: NotRequired[str] + request_id: NotRequired[str] + + +class KnowledgeSourceMcpInspectOutput(TypedDict, total=False): + found: Required[bool] + source: NotRequired[Optional["MCPSourceEntry"]] + + +class KnowledgeSourceMcpListInput(TypedDict, total=False): + org: Required[str] + namespace: Required[str] + cursor: NotRequired[Optional[str]] + limit: NotRequired[int] + include_retired: NotRequired[bool] + + +class KnowledgeSourceMcpListBody(TypedDict, total=False): + org: NotRequired[str] + namespace: NotRequired[str] + cursor: NotRequired[Optional[str]] + limit: NotRequired[int] + include_retired: NotRequired[bool] + + +class KnowledgeSourceMcpListOutput(TypedDict, total=False): + sources: Required[list["MCPSourceSummary"]] + next_cursor: NotRequired[Optional[str]] + + +class MCPSourceSummary(TypedDict, total=False): + name: Required[str] + source_id: Required[str] + slot: Required[str] + namespace: Required[str] + state: Required[Literal["registered", "paused", "retired", "unsupported"]] + mode: NotRequired[Optional[Literal["live", "snapshot", "selected_refresh"]]] + reader_policy: NotRequired[Optional[Literal["owner_only", "collection_copy"]]] + scope_revision: NotRequired[Optional[int]] + label: NotRequired[Optional[str]] + selected_count: NotRequired[Optional[int]] + sync_enabled: Required[bool] + read_evidence_stale_seconds: Required[int] + refresh_state: Required[ + Literal["not_applicable", "enabled", "disabled", "paused", "retired", "unsupported"] + ] + compatibility: NotRequired[Literal["unchecked"]] + upstream_permissions: NotRequired[Literal["unsupported"]] + complete_enumeration: NotRequired[Literal[False]] + upstream_deletion_tracking: NotRequired[Literal[False]] + future_items_included: NotRequired[Literal[False]] + current_access_attested: NotRequired[Literal[False]] + local_authority: NotRequired[Literal["current", "unavailable", "unchecked"]] + pending_erasure: NotRequired[bool] + rule: NotRequired[Optional["MCPAccessRule"]] + + +class MCPSourceInput(TypedDict, total=False): + org: Required[str] + namespace: Required[str] + name: Required[str] + + +class MCPSourceBody(TypedDict, total=False): + org: NotRequired[str] + namespace: NotRequired[str] + name: Required[str] + + +class KnowledgeSourceMcpPreviewInput(TypedDict, total=False): + org: Required[str] + namespace: Required[str] + slot: Required[str] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + reader_policy: NotRequired[Literal["owner_only", "collection_copy"]] + resource_ids: Required[list[str]] + + +class KnowledgeSourceMcpPreviewBody(TypedDict, total=False): + org: NotRequired[str] + namespace: NotRequired[str] + slot: Required[str] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + reader_policy: NotRequired[Literal["owner_only", "collection_copy"]] + resource_ids: Required[list[str]] + + +class KnowledgeSourceMcpPreviewOutput(TypedDict, total=False): + namespace: Required[str] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + rule: Required["MCPAccessRule"] + connection_state: Required[Literal["configured", "stopped", "unavailable", "approval_drift"]] + compatibility: NotRequired[Literal["unchecked"]] + permission_evidence: NotRequired[Literal["unsupported"]] + refresh_state: Required[Literal["not_applicable", "enabled", "disabled"]] + selected_count: Required[int] + checked_at: Required[str] + read_evidence_stale_seconds: Required[int] + preview_grants_authority: NotRequired[Literal[False]] + limitations: Required[list[str]] + + class KnowledgeSourceMcpProfilesInput(TypedDict, total=False): "List approved profile declarations for the signed-in caller's organization." @@ -12174,113 +12336,75 @@ class MCPProfileEntry(TypedDict, total=False): id: Required[str] label: Required[str] auth: Required[Literal["none", "bearer"]] + endpoint_origin: Required[str] profile_sha256: Required[str] approved_tools: Required[list[str]] allow_collection_copy: Required[bool] -class KnowledgeSourceParseLinksInput(TypedDict, total=False): - "Read pasted links as a source's items, with no request to any store and" - - org: Required[str] - namespace: Required[str] - links: Required[list[str]] - - -class KnowledgeSourceParseLinksBody(TypedDict, total=False): - "Read pasted links as a source's items, with no request to any store and" - - org: NotRequired[str] - namespace: NotRequired[str] - links: Required[list[str]] - - -class KnowledgeSourceParseLinksOutput(TypedDict, total=False): - links: NotRequired[list["KnowledgeSourceParsedLink"]] - - -class KnowledgeSourceParsedLink(TypedDict, total=False): - link: Required[str] - kind: NotRequired[str] - item: NotRequired[dict[str, Any]] - unreadable: NotRequired[str] - - -class KnowledgeSourcePushConfigureInput(TypedDict, total=False): - "Enable provider sync hints for an existing source, or disable its setup." - +class KnowledgeSourceMcpReadInput(TypedDict, total=False): org: Required[str] namespace: Required[str] name: Required[str] - enabled: NotRequired[bool] - agent: NotRequired[str] - user_id: NotRequired[str] - session_id: NotRequired[str] + resource_id: Required[str] -class KnowledgeSourcePushConfigureBody(TypedDict, total=False): - "Enable provider sync hints for an existing source, or disable its setup." - +class KnowledgeSourceMcpReadBody(TypedDict, total=False): org: NotRequired[str] namespace: NotRequired[str] name: Required[str] - enabled: NotRequired[bool] - agent: NotRequired[str] - user_id: NotRequired[str] - session_id: NotRequired[str] + resource_id: Required[str] -class PushStatusOutput(TypedDict, total=False): - enabled: NotRequired[bool] - status: NotRequired[str] - provider: NotRequired[str] - generation: NotRequired[str] - callback_url: NotRequired[str] - provider_id: NotRequired[str] - challenge_fingerprint: NotRequired[str] - verification_token: NotRequired[str] - channels: NotRequired[int] - expires_at: NotRequired[float] - +class KnowledgeSourceMcpReadOutput(TypedDict, total=False): + source_id: Required[str] + resource_id: Required[str] + uri: Required[str] + title: Required[str] + text: Required[str] + mime_type: Required[str] + resource_identity_verified: Required[bool] + remote_identity_verified: NotRequired[Literal[False]] + upstream_acl_verified: NotRequired[Literal[False]] + limitations: Required[list[str]] -class KnowledgeSourcePushConfirmInput(TypedDict, total=False): - "Activate the exact pending setup." +class KnowledgeSourceMcpRemoveInput(TypedDict, total=False): org: Required[str] namespace: Required[str] name: Required[str] - generation: Required[str] - challenge_fingerprint: NotRequired[str] - signing_secret: NotRequired[str] - + confirm: Required[str] + delete_documents: NotRequired[bool] -class KnowledgeSourcePushConfirmBody(TypedDict, total=False): - "Activate the exact pending setup." +class KnowledgeSourceMcpRemoveBody(TypedDict, total=False): org: NotRequired[str] namespace: NotRequired[str] name: Required[str] - generation: Required[str] - challenge_fingerprint: NotRequired[str] - signing_secret: NotRequired[str] - + confirm: Required[str] + delete_documents: NotRequired[bool] -class KnowledgeSourcePushStatusInput(TypedDict, total=False): - "Read push setup as a namespace admin." +class KnowledgeSourceMcpUpdateInput(TypedDict, total=False): org: Required[str] namespace: Required[str] name: Required[str] - reveal_challenge: NotRequired[bool] - + if_scope_revision: NotRequired[Optional[int]] + resource_ids: Required[list[str]] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + label: NotRequired[Optional[str]] + confirm_copy_authority: NotRequired[bool] -class KnowledgeSourcePushStatusBody(TypedDict, total=False): - "Read push setup as a namespace admin." +class KnowledgeSourceMcpUpdateBody(TypedDict, total=False): org: NotRequired[str] namespace: NotRequired[str] name: Required[str] - reveal_challenge: NotRequired[bool] + if_scope_revision: NotRequired[Optional[int]] + resource_ids: Required[list[str]] + mode: Required[Literal["live", "snapshot", "selected_refresh"]] + label: NotRequired[Optional[str]] + confirm_copy_authority: NotRequired[bool] class KnowledgeSourceRemoveInput(TypedDict, total=False): @@ -12355,42 +12479,6 @@ class KnowledgeSourceSyncNowOutput(TypedDict, total=False): enabled: NotRequired[bool] -class KnowledgeSourceUpdateInput(TypedDict, total=False): - "Add items to a registered document source or remove them, or change a gdrive" - - org: Required[str] - namespace: Required[str] - name: Required[str] - add_items: NotRequired[list[dict[str, Any]]] - add_links: NotRequired[list[str]] - remove_items: NotRequired[list[dict[str, Any]]] - remove_links: NotRequired[list[str]] - include: NotRequired[Optional[list[str]]] - - -class KnowledgeSourceUpdateBody(TypedDict, total=False): - "Add items to a registered document source or remove them, or change a gdrive" - - org: NotRequired[str] - namespace: NotRequired[str] - name: Required[str] - add_items: NotRequired[list[dict[str, Any]]] - add_links: NotRequired[list[str]] - remove_items: NotRequired[list[dict[str, Any]]] - remove_links: NotRequired[list[str]] - include: NotRequired[Optional[list[str]]] - - -class KnowledgeSourceUpdateOutput(TypedDict, total=False): - name: Required[str] - items: NotRequired[list[dict[str, Any]]] - include: NotRequired[list[str]] - config: NotRequired[dict[str, Any]] - added: NotRequired[list[dict[str, Any]]] - removed: NotRequired[list[dict[str, Any]]] - probe: NotRequired["KnowledgeSourceProbe"] - - class KnowledgeSynthesizeInput(TypedDict, total=False): "Complete a task over WHOLE documents, not a search slice:" @@ -19571,7 +19659,8 @@ class LiveSearchHit(TypedDict, total=False): id: Required[str] title: Required[str] url: Required[str] - provider: Required[Literal["gdrive", "notion", "linear"]] + provider: Required[Literal["mcp"]] + resource_identity_verified: Required[bool] content: NotRequired[str] live: NotRequired[Literal[True]] diff --git a/sdk/python/loom/session_protection.py b/sdk/python/loom/session_protection.py index d2bf12b00a..156979a2b0 100644 --- a/sdk/python/loom/session_protection.py +++ b/sdk/python/loom/session_protection.py @@ -130,6 +130,16 @@ def pointer(self) -> dict[str, str]: """Content-free control state, independent of token or server scope.""" return {"base": str(self.base), "id": self.id} + def require_ready(self) -> None: + """Confirm existing readable and writable control state before admission.""" + try: + directory = self._location() + with _file(directory / "state", os.O_RDWR | os.O_APPEND) as fd: + if os.read(fd, 3) not in (b"0\n", b"0\n1"): + raise SessionProtectionUnavailable() + except Exception: # noqa: BLE001 — missing control authority cannot promise protection + raise SessionProtectionUnavailable() from None + def _location(self) -> Path: if ( not self.base.is_absolute() @@ -266,6 +276,7 @@ def observe_response(value: Any, root: SessionProtection | None) -> Any: refused = False for family in roots: try: + family.require_ready() family.observe(value) except SessionProtectionUnavailable: refused = True @@ -296,6 +307,8 @@ def _marked(value: Any) -> bool: for key in ("result", "structuredContent"): if isinstance(item.get(key), dict): pending.append(item[key]) + if isinstance(item.get("error"), dict) and isinstance(item["error"].get("data"), dict): + pending.append(item["error"]["data"]) if isinstance(item.get("items"), list): if len(pending) + len(item["items"]) > remaining: raise SessionProtectionUnavailable() diff --git a/sdk/python/loom/source_cli.py b/sdk/python/loom/source_cli.py new file mode 100644 index 0000000000..0533002c8f --- /dev/null +++ b/sdk/python/loom/source_cli.py @@ -0,0 +1,513 @@ +"""Installed-SDK source CLI; all requests use retained session protection.""" + +from __future__ import annotations + +import argparse +import contextlib +import json +import os +import re +import stat +import sys +from collections.abc import Callable, Iterator +from dataclasses import dataclass +from pathlib import Path +from typing import Any, TextIO +from uuid import UUID + +from loom.cli_context import CONTEXT_ENV, ContextUnavailable, open_context, request_scope, run_sync +from loom.errors import LoomError +from loom.retry import RetryPolicy +from loom.session_protection import ( + AutomaticCaptureSuppressed, + SessionProtection, + SessionProtectionUnavailable, +) +from loom.transport import Transport + +SOURCE_CLI_API = 2 +MAX_REQUEST_BYTES = 1024 * 1024 +MAX_SECRET_BYTES = 64 * 1024 +MAX_POINTER_BYTES = 4096 +_LOCAL_FAILURE = "Local input or session authority is unavailable; no reset or retry was attempted." +_PROTECTION_FAILURE = ( + "Session protection refused this operation; retain the existing context and restore its proof. " + "No reset or retry was attempted." +) + + +@dataclass(frozen=True) +class Command: + op: str + fields: str = "" + required: str = "" + secret: str = "" + + +_PREVIEW_FIELDS = "namespace slot mode reader_policy resource_ids" +_SOURCE_FIELDS = "namespace name" +_COMMANDS: dict[str, Command] = { + "preview": Command( + "knowledge.source.mcp_preview", _PREVIEW_FIELDS, "namespace slot mode resource_ids" + ), + "add": Command( + "knowledge.source.mcp_add", + _PREVIEW_FIELDS + " request_id label confirm_copy_authority", + "namespace slot mode resource_ids request_id", + ), + "update": Command( + "knowledge.source.mcp_update", + _SOURCE_FIELDS + " if_scope_revision resource_ids mode label confirm_copy_authority", + _SOURCE_FIELDS + " resource_ids mode", + ), + "list": Command( + "knowledge.source.mcp_list", "namespace cursor limit include_retired", "namespace" + ), + "inspect": Command( + "knowledge.source.mcp_inspect", "namespace name slot request_id", "namespace" + ), + "pause": Command("knowledge.source.mcp_pause", _SOURCE_FIELDS, _SOURCE_FIELDS), + "resume": Command("knowledge.source.mcp_resume", _SOURCE_FIELDS, _SOURCE_FIELDS), + "refresh": Command("knowledge.source.mcp_refresh", _SOURCE_FIELDS, _SOURCE_FIELDS), + "read": Command( + "knowledge.source.mcp_read", + _SOURCE_FIELDS + " resource_id", + _SOURCE_FIELDS + " resource_id", + ), + "remove": Command( + "knowledge.source.mcp_remove", + _SOURCE_FIELDS + " confirm delete_documents", + _SOURCE_FIELDS + " confirm", + ), +} +_CONNECTION_COMMANDS = { + "profiles": Command("knowledge.source.mcp_profiles", "query cursor limit"), + "connect": Command( + "knowledge.connection.mcp_connect", + "profile_id request_id label", + "profile_id request_id", + "bearer", + ), + "list": Command("knowledge.connection.mcp_list", "cursor limit"), + "inspect": Command("knowledge.connection.mcp_inspect", "slot request_id"), + "discover": Command("knowledge.connection.mcp_discover", "slot", "slot"), + "browse": Command("knowledge.connection.mcp_browse", "slot mode query limit", "slot mode"), + "disconnect": Command("knowledge.connection.mcp_disconnect", "slot", "slot"), +} +_DESTINATION_COMMANDS = { + "list": Command("collection.list", "limit include_document_counts cursor"), + "create": Command("collection.create", "namespace title derive_name parent description"), + "grants": Command("grants.list", "namespace limit cursor fields", "namespace"), + "grant": Command( + "grants.create", "namespace subject role granted_by replace", "namespace subject role" + ), + "preview": _COMMANDS["preview"], +} +_RECORDING_COMMANDS = { + "add": Command( + "knowledge.source.add", + "namespace name kind config dry_run", + "namespace name config", + "credential", + ), + "list": Command("knowledge.source.list", "namespace", "namespace"), + "sync-now": Command("knowledge.source.sync_now", _SOURCE_FIELDS + " full", _SOURCE_FIELDS), +} +_RETAINED_COMMANDS = { + "list": Command("knowledge.source.list", "namespace", "namespace"), + "inspect": Command("knowledge.source.inspect", _SOURCE_FIELDS, _SOURCE_FIELDS), + "remove": Command( + "knowledge.source.remove", + _SOURCE_FIELDS + " confirm delete_documents", + _SOURCE_FIELDS + " confirm", + ), +} + + +class InputError(ValueError): + """A local input failure whose message contains no request or credential values.""" + + +def _private_file(fd: int) -> None: + info = os.fstat(fd) + if ( + not stat.S_ISREG(info.st_mode) + or info.st_uid != os.getuid() + or info.st_mode & 0o077 + or info.st_nlink != 1 + ): + raise InputError("Use an owned private regular file (mode 0600), without links.") + + +@contextlib.contextmanager +def _pointer_directory(path: Path) -> Iterator[int]: + if os.name != "posix" or not path.is_absolute(): + raise InputError("Session pointers require an absolute path in private POSIX storage.") + directory = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + try: + info = os.fstat(directory) + if info.st_uid != os.getuid() or info.st_mode & 0o077: + raise InputError("The session pointer directory must be owned and mode 0700.") + yield directory + finally: + os.close(directory) + + +def _read_input(path: str, maximum: int, *, private: bool = False) -> str: + if path == "-": + raw = sys.stdin.buffer.read(maximum + 1) + else: + fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + with os.fdopen(fd, "rb") as stream: + if private: + _private_file(stream.fileno()) + elif not stat.S_ISREG(os.fstat(stream.fileno()).st_mode): + raise InputError("Request input must be a regular file or stdin.") + raw = stream.read(maximum + 1) + if len(raw) > maximum: + raise InputError("Input exceeds its byte limit.") + try: + return raw.decode("utf-8") + except UnicodeDecodeError: + raise InputError("Input must be UTF-8 text.") from None + + +def _object(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + value: dict[str, Any] = {} + for key, item in pairs: + if key in value: + raise InputError("JSON input contains duplicate fields.") + value[key] = item + return value + + +def _json_object(raw: str) -> dict[str, Any]: + try: + value = json.loads(raw, object_pairs_hook=_object, parse_constant=_nonfinite) + except (ValueError, RecursionError): + raise InputError("Input must contain one JSON object without duplicate fields.") from None + if not isinstance(value, dict): + raise InputError("Input must contain one JSON object.") + return value + + +def _nonfinite(value: str) -> Any: + raise InputError("JSON input cannot contain nonfinite numbers.") + + +def save_session_pointer(path: str | Path, family: SessionProtection) -> None: + """Application provisioning only: persist once, never replace a resumed pointer.""" + family.require_ready() + raw = json.dumps({"version": 1, "pointer": family.pointer()}).encode() + with _pointer_directory(Path(path)) as directory: + fd = os.open( + Path(path).name, + os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, + 0o600, + dir_fd=directory, + ) + try: + with os.fdopen(fd, "wb") as stream: + stream.write(raw) + stream.flush() + os.fsync(stream.fileno()) + os.fsync(directory) + except OSError: + # Leave incomplete authority in place; restore must refuse instead of resetting it. + raise InputError( + "Session pointer persistence failed; restore is unavailable." + ) from None + + +def open_session(path: str) -> SessionProtection: + """Reopen only existing application-owned authority; do not create or repair it.""" + with _pointer_directory(Path(path)) as directory: + fd = os.open(Path(path).name, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory) + with os.fdopen(fd, "rb") as stream: + _private_file(stream.fileno()) + raw = stream.read(MAX_POINTER_BYTES + 1) + if len(raw) > MAX_POINTER_BYTES: + raise InputError("Session pointer exceeds its byte limit.") + try: + value = _json_object(raw.decode("utf-8")) + except UnicodeDecodeError: + raise InputError("Session pointer is invalid.") from None + if ( + set(value) != {"version", "pointer"} + or type(value["version"]) is not int + or value["version"] != 1 + or not isinstance(value["pointer"], dict) + ): + raise InputError("Session pointer is invalid.") + family = SessionProtection.open(value["pointer"]) + family.require_ready() + return family + + +def _common(parser: argparse.ArgumentParser, command: Command) -> None: + parser.add_argument("--server-url", required=True) + parser.add_argument("--org", required=True) + if "namespace" in command.fields.split(): + parser.add_argument( + "--namespace", help="Ordinary destination; must agree with the JSON field." + ) + parser.add_argument( + "--request-file", + help="UTF-8 JSON object, at most 1 MiB; - reads stdin. API fields: " + + (command.fields or "none"), + ) + parser.add_argument( + "--token-file", help="Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY." + ) + parser.add_argument( + "--session-file", + required=True, + help="Existing application-owned private session pointer; " + "never initialized by this command.", + ) + parser.add_argument( + "--intent", + choices=("automatic", "explicit"), + default="automatic", + help="Default automatic guards every call; explicit is a direct user action.", + ) + if command.secret: + parser.add_argument( + "--" + command.secret + "-file", + required=command.secret == "credential", + help="Owned mode-0600 credential file or - for stdin. Never an argv secret.", + ) + parser.set_defaults(func=run_command, source_spec=command) + + +def _commands(sub: Any, commands: dict[str, Command]) -> None: + for name, command in commands.items(): + parser = sub.add_parser( + name, + allow_abbrev=False, + help=command.op, + description=command.op + + ". No automatic retries; pagination and reconciliation are explicit.", + ) + _common(parser, command) + + +def register_source_cli(sub: Any) -> None: + parser = sub.add_parser( + "source", help="MCP sources, connections, collection destinations and recordings." + ) + actions = parser.add_subparsers(dest="source_command", required=True) + _commands(actions, _COMMANDS) + for name, commands in ( + ("connection", _CONNECTION_COMMANDS), + ("destination", _DESTINATION_COMMANDS), + ("recording", _RECORDING_COMMANDS), + ("retained", _RETAINED_COMMANDS), + ): + group = actions.add_parser(name) + _commands(group.add_subparsers(dest="source_action", required=True), commands) + + +def run_server_entry(args: argparse.Namespace) -> int: + """Versioned execution interface for the separately packaged server parser.""" + groups = { + "connection": _CONNECTION_COMMANDS, + "destination": _DESTINATION_COMMANDS, + "recording": _RECORDING_COMMANDS, + "retained": _RETAINED_COMMANDS, + } + if args.source_command in groups: + args.source_spec = groups[args.source_command][args.source_action] + else: + args.source_spec = _COMMANDS[args.source_command] + return run_command(args) + + +def _uuid(value: Any) -> None: + try: + if not isinstance(value, str) or str(UUID(value)) != value: + raise ValueError + except (ValueError, AttributeError): + raise InputError( + "request_id must be the original canonical UUID; the CLI never invents a replacement." + ) from None + + +def _request(args: argparse.Namespace, command: Command) -> dict[str, Any]: + body = ( + _json_object(_read_input(args.request_file, MAX_REQUEST_BYTES)) if args.request_file else {} + ) + if set(body) - set(command.fields.split()): + raise InputError( + "Unexpected request fields; use the API field names in command help. " + "Credentials require a separate private file or stdin." + ) + namespace = getattr(args, "namespace", None) + if namespace is not None: + if "namespace" in body and body["namespace"] != namespace: + raise InputError("--namespace conflicts with the request's namespace field.") + body["namespace"] = namespace + if any(field not in body for field in command.required.split()): + raise InputError("Required API fields are missing; see command help.") + if "request_id" in body and body["request_id"] != "": + _uuid(body["request_id"]) + if command.op in ("knowledge.connection.mcp_connect", "knowledge.source.mcp_add"): + _uuid(body["request_id"]) + if command.op == "knowledge.source.add": + if body.get("kind", "recording") != "recording": + raise InputError( + "Only recording is supported here; document sources use MCP source add." + ) + body["kind"] = "recording" + return {"org": args.org, **body} + + +def _credentials(args: argparse.Namespace, command: Command, body: dict[str, Any]) -> str: + secret_path = getattr(args, command.secret + "_file", None) if command.secret else None + token = ( + _read_input(args.token_file, MAX_SECRET_BYTES, private=True).strip() + if args.token_file + else os.environ.get("LOOM_API_KEY", "").strip() + ) + if not token: + raise InputError( + "Supply --token-file or LOOM_API_KEY; saved human credentials are not borrowed." + ) + if len(token.encode("utf-8")) > MAX_SECRET_BYTES: + raise InputError("Token input exceeds its byte limit.") + if secret_path: + secret = _read_input(secret_path, MAX_SECRET_BYTES, private=True).strip() + if not secret: + raise InputError("The credential input is empty.") + body[command.secret] = secret + return token + + +async def call_source( + command: Command, + body: dict[str, Any], + *, + server_url: str, + token: str, + family: SessionProtection, + automatic: bool = True, + transport_factory: Callable[..., Transport] = Transport, +) -> dict[str, Any]: + """One observed dispatch; callers retain the same family across tasks and scopes.""" + family.require_ready() + with request_scope(family, "POST", "/v1/" + command.op, explicit=not automatic): + transport = transport_factory( + server_url, + api_key=token, + session_protection=family, + retry=RetryPolicy(max_attempts=1), + pacing=False, + ratelimit_max_wait_s=0, + ) + try: + result = await transport.post_with_meta( + "/v1/" + command.op, body, request_id=body.get("request_id") + ) + return result.data + finally: + await transport.close() + + +def _reconcile(command: Command, body: dict[str, Any], err: TextIO) -> None: + request_id = body.get("request_id") + if command.op == "knowledge.connection.mcp_connect" and request_id: + print( + "Reconcile with connection inspect using the original request_id=" + + request_id + + "; do not reconnect with a new UUID.", + file=err, + ) + elif command.op == "knowledge.source.mcp_add" and request_id: + print( + "Reconcile with source inspect using the original namespace, slot and request_id=" + + request_id + + "; do not add with a new UUID.", + file=err, + ) + + +def _inputs( + args: argparse.Namespace, command: Command +) -> tuple[SessionProtection, dict[str, Any], str]: + secret_path = getattr(args, command.secret + "_file", None) if command.secret else None + if [args.request_file, args.token_file, secret_path].count("-") > 1: + raise InputError("Only one input can consume stdin.") + capsule = os.environ.get(CONTEXT_ENV) + if capsule is None and args.intent == "automatic": + raise InputError( + "Automatic source commands require inherited LOOM_SOURCE_SESSION_CONTEXT " + "matching --session-file. Retain the trusted launcher context across commands." + ) + family = ( + open_context(capsule, session_file=args.session_file) + if capsule is not None + else open_session(args.session_file) + ) + body = _request(args, command) + return family, body, _credentials(args, command, body) + + +def _request_failure(exc: LoomError, command: Command, body: dict[str, Any]) -> int: + code = ( + exc.code + if isinstance(exc.code, str) and re.fullmatch(r"[A-Z][A-Z0-9_]{0,79}", exc.code) + else "REQUEST_FAILED" + ) + print("Source request failed: " + code + ". No retry was attempted.", file=sys.stderr) + _reconcile(command, body, sys.stderr) + return 1 + + +def run_command(args: argparse.Namespace) -> int: + command: Command = args.source_spec + body: dict[str, Any] = {} + try: + family, body, token = _inputs(args, command) + out = run_sync( + lambda: call_source( + command, + body, + server_url=args.server_url, + token=token, + family=family, + automatic=args.intent == "automatic", + ) + ) + except (InputError, ContextUnavailable) as exc: + print(str(exc), file=sys.stderr) + return 2 + except (OSError, ValueError, RecursionError): + print(_LOCAL_FAILURE, file=sys.stderr) + _reconcile(command, body, sys.stderr) + return 2 + except (SessionProtectionUnavailable, AutomaticCaptureSuppressed): + print(_PROTECTION_FAILURE, file=sys.stderr) + _reconcile(command, body, sys.stderr) + return 2 + except LoomError as exc: + return _request_failure(exc, command, body) + print(json.dumps(out, indent=2, sort_keys=True)) + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(prog="python -m loom.source_cli") + register_source_cli(parser.add_subparsers(required=True)) + try: + args = parser.parse_args(argv) + return int(args.func(args)) + except KeyboardInterrupt: + print( + "Interrupted; retain the original request UUID and session proof for reconciliation.", + file=sys.stderr, + ) + return 130 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/sdk/python/loom/transport.py b/sdk/python/loom/transport.py index 38985bf042..872fcc4a9d 100644 --- a/sdk/python/loom/transport.py +++ b/sdk/python/loom/transport.py @@ -283,6 +283,19 @@ def unreachable_error( return err +async def _download_body(response: httpx.Response, maximum: int) -> bytes: + if response.headers.get("content-encoding", "identity").strip().lower() not in {"", "identity"}: + raise SessionProtectionUnavailable() + parts: list[bytes] = [] + total = 0 + async for chunk in response.aiter_bytes(): + total += len(chunk) + if total > maximum or len(parts) >= 4096: + raise SessionProtectionUnavailable() + parts.append(chunk) + return b"".join(parts) + + class Transport: """One Transport per Agent. Owns an httpx AsyncClient with HTTP/2 + pool. @@ -370,6 +383,28 @@ def __init__( async def _before_dispatch(self, request: httpx.Request) -> None: # httpx invokes this after authentication and on each replay. require_automatic_allowed(self.session_protection) + roots = response_roots(self.session_protection) + declaration = "x-loom-session-protection" + previous = request.extensions.get("_loom_protection_roots") + values = request.headers.get_list(declaration) + if values and (previous is None or values != ["v1"]): + raise SessionProtectionUnavailable() + if roots: + target = httpx.URL(self._base_url) + if (request.url.scheme, request.url.host, request.url.port) != ( + target.scheme, + target.host, + target.port, + ) or self._before_response not in self._client.event_hooks["response"]: + raise SessionProtectionUnavailable() + for root in roots: + if not isinstance(root, SessionProtection): + raise SessionProtectionUnavailable() + root.require_ready() + request.extensions["_loom_protection_roots"] = roots + request.headers[declaration] = "v1" + elif values: + raise SessionProtectionUnavailable() if has_protection(self.session_protection) and ( "text/event-stream" in request.headers.get("Accept", "").lower() or request.url.path == "/v1/assistant/chat/completions" @@ -377,11 +412,29 @@ async def _before_dispatch(self, request: httpx.Request) -> None: request.headers["Accept-Encoding"] = "identity" async def _before_response(self, response: httpx.Response) -> None: - roots = response_roots(self.session_protection) + roots = tuple( + dict.fromkeys( + ( + *response.request.extensions.get("_loom_protection_roots", ()), + *response_roots(self.session_protection), + ) + ) + ) if not roots: return + for root in roots: + root.require_ready() + if response.request.extensions.get("_loom_opaque_download") is True: + # Downloads have no envelope contract, including JSON and line-delimited exports. + for root in roots: + root.mark() + return content_type = response.headers.get("content-type", "").lower() - if response.status_code >= 400 or "json" in content_type: + if ( + response.status_code >= 400 + or response.status_code in {204, 304} + or "json" in content_type + ): with observation_scope(roots): try: await response.aread() @@ -393,6 +446,9 @@ async def _before_response(self, response: httpx.Response) -> None: self._observe_json(response) elif "text/event-stream" in content_type: protect_event_stream(response, roots) + else: + with observation_scope(roots): + refuse_response(self.session_protection) def _observe_json(self, response: httpx.Response) -> Any: if "_loom_observed_json" not in response.extensions: @@ -580,6 +636,55 @@ async def request( await asyncio.sleep(wait) waited_s += wait + async def download( + self, + path: str, + *, + params: Mapping[str, Any] | None = None, + max_bytes: int = 64 * 1024 * 1024, + timeout_s: float = 60.0, + ) -> httpx.Response: + """An observed GET with opaque bytes protected before release, without retries. + + The application can lower the 64 MiB/60-second ceilings. Decoded response + bytes and chunk bookkeeping are bounded; the owned response always closes. + """ + if type(max_bytes) is not int or not 0 < max_bytes <= 64 * 1024 * 1024: + raise ValueError("download byte bound is invalid") + if isinstance(timeout_s, bool) or not 0 < timeout_s <= 60: + raise ValueError("download time bound is invalid") + if not path.startswith("/") or path.startswith("//"): + raise ValueError("download requires a path on this server") + require_automatic_allowed(self.session_protection) + roots = response_roots(self.session_protection) + automatic = automatic_roots(self.session_protection) + headers = { + **self._ident_headers, + "X-Request-Id": str(uuid.uuid4()), + "Accept-Encoding": "identity", + } + request = self._client.build_request("GET", path, params=params, headers=headers) + request.extensions["_loom_opaque_download"] = True + with automatic_for(automatic), observation_scope(roots): + async with asyncio.timeout(timeout_s): + response = await self._client.send(request, stream=True) + try: + content = await _download_body(response, max_bytes) + result_headers = httpx.Headers(response.headers) + for name in ("Content-Encoding", "Content-Length", "Transfer-Encoding"): + result_headers.pop(name, None) + result = httpx.Response( + response.status_code, + headers=result_headers, + content=content, + request=response.request, + ) + if result.status_code >= 400: + raise self._error_for(path, result, headers["X-Request-Id"]) + return result + finally: + await response.aclose() + async def request_json( self, method: str, diff --git a/sdk/python/tests/qualify_cli_source_context.py b/sdk/python/tests/qualify_cli_source_context.py new file mode 100644 index 0000000000..6b5c16a510 --- /dev/null +++ b/sdk/python/tests/qualify_cli_source_context.py @@ -0,0 +1,171 @@ +"""Hosted private-source CLI qualification against the normally installed server and SDK. + +The functional qualification owner supplies a real admitted private MCP source and +its expected content marker. This file is selected explicitly after that fixture is +provisioned; it is not part of local unit discovery. Missing setup fails the run. +""" + +import json +import os +import subprocess +import sys +from uuid import uuid4 + +from loom.cli_context import CONTEXT_ENV, session_environment +from loom.session_protection import SessionProtection +from loom.source_cli import save_session_pointer + +ENTRY = "from server.cli.app import main; raise SystemExit(main())" +LEGACY_ENTRY = """ +import json +import os +import sys +from server.cli._client import post_bytes, post_json, post_op +from server.cli._session_context import CLIContextError +mode, base, body = sys.argv[1], sys.argv[2], json.loads(sys.argv[3]) +token = os.environ['LOOM_API_KEY'] +try: + if mode == 'file': + post_bytes(base + '/v1/knowledge.upload', b'blocked-file', token) + elif mode == 'json': + post_json(base + '/v1/memory.set', body, token) + else: + post_op(base, 'memory.set', body, token) +except CLIContextError: + print('protection refused', file=sys.stderr) + raise SystemExit(2) +raise SystemExit('protected legacy request was not suppressed') +""" + + +def cli(env, *argv): + return subprocess.run( + [sys.executable, "-c", ENTRY, *argv], + env=env, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + + +def test_actual_private_source_then_other_command_and_explicit_write(tmp_path): + base = os.environ["LOOM_CLI_QUAL_BASE_URL"] + org = os.environ["LOOM_CLI_QUAL_ORG"] + token = os.environ["LOOM_CLI_QUAL_TOKEN"] + other_token = os.environ["LOOM_CLI_QUAL_OTHER_TOKEN"] + destination = os.environ["LOOM_CLI_QUAL_WRITE_NAMESPACE"] + request = json.loads(os.environ["LOOM_CLI_QUAL_PRIVATE_READ_REQUEST"]) + marker = os.environ["LOOM_CLI_QUAL_PRIVATE_MARKER"] + assert request["namespace"] != destination + assert other_token != token + root = tmp_path / "application" + root.mkdir(mode=0o700) + family = SessionProtection.create(base=root / "families") + pointer = root / "pointer.json" + save_session_pointer(pointer, family) + env = {**os.environ, **session_environment(str(pointer)), "LOOM_API_KEY": token} + source = root / "read.json" + source.write_text(json.dumps(request)) + read = cli( + env, + "knowledge", + "source", + "read", + "--server-url", + base, + "--org", + org, + "--session-file", + str(pointer), + "--request-file", + str(source), + ) + assert read.returncode == 0, read.stderr + assert marker in json.dumps(json.loads(read.stdout)) + assert family.protected + assert SessionProtection.open(family.pointer()).protected + + key = "cli-context-" + uuid4().hex + fields = ["org=" + org, "namespace=" + destination, "key=" + key, "value=explicit-user-value"] + # A separate process uses the same normal root CLI and a different installed client path. + denied = cli( + {**env, "LOOM_API_KEY": other_token}, "call", "memory.set", "--server", base, *fields + ) + assert denied.returncode == 2 and "protection refused" in denied.stderr + assert marker not in denied.stderr and marker not in denied.stdout + # An unreachable origin distinguishes local suppression from an HTTP/auth failure. + origin = cli( + {**env, "LOOM_API_KEY": other_token}, + "call", + "memory.set", + "--server", + "https://127.0.0.1:1", + *fields, + ) + assert origin.returncode == 2 and "protection refused" in origin.stderr + for mode in ("file", "json", "op"): + legacy = subprocess.run( + [ + sys.executable, + "-c", + LEGACY_ENTRY, + mode, + "https://127.0.0.1:1", + json.dumps( + {"org": org, "namespace": destination, "key": key, "value": "blocked-legacy"} + ), + ], + env={**env, "LOOM_API_KEY": other_token}, + capture_output=True, + text=True, + timeout=30, + check=False, + ) + assert legacy.returncode == 2 and "protection refused" in legacy.stderr + ordinary_read = cli( + env, + "call", + "memory.keys", + "--server", + base, + "org=" + org, + "namespace=" + destination, + ) + assert ordinary_read.returncode == 0, ordinary_read.stderr + assert key not in ordinary_read.stdout + + positive = cli( + env, "--request-intent", "explicit", "call", "memory.set", "--server", base, *fields + ) + assert positive.returncode == 0, positive.stderr + verify = cli( + env, + "call", + "memory.get", + "--server", + base, + "org=" + org, + "namespace=" + destination, + "key=" + key, + ) + assert verify.returncode == 0, verify.stderr + assert json.loads(verify.stdout)["value"] == "explicit-user-value" + # Explicit intent ended with that process; the unchanged capsule remains protected. + again = cli(env, "call", "memory.set", "--server", base, *fields) + assert again.returncode == 2 and "protection refused" in again.stderr + + original_capsule = env[CONTEXT_ENV] + pointer.unlink() + missing = cli( + env, + "call", + "memory.get", + "--server", + base, + "org=" + org, + "namespace=" + destination, + "key=" + key, + ) + assert missing.returncode == 2 and not pointer.exists() + assert env[CONTEXT_ENV] == original_capsule diff --git a/sdk/python/tests/test_cli_context.py b/sdk/python/tests/test_cli_context.py new file mode 100644 index 0000000000..9fe7848edc --- /dev/null +++ b/sdk/python/tests/test_cli_context.py @@ -0,0 +1,304 @@ +"""Installed SDK CLI context behavior; hosted SDK environment only.""" + +import argparse +import asyncio +import contextvars +import threading +from concurrent.futures import Future + +import httpx +import pytest +from loom import cli_context as context +from loom import source_cli +from loom.session_protection import AutomaticCaptureSuppressed, SessionProtection + + +def provision(tmp_path, monkeypatch): + root = tmp_path / "application" + root.mkdir(mode=0o700) + path = root / "pointer.json" + family = SessionProtection.create(base=root / "families") + source_cli.save_session_pointer(path, family) + raw = context.session_environment(str(path))[context.CONTEXT_ENV] + monkeypatch.setenv(context.CONTEXT_ENV, raw) + return family, path, raw + + +def http(monkeypatch, handler): + original = httpx.AsyncClient + clients = [] + + def client(*args, **kwargs): + result = original(*args, transport=httpx.MockTransport(handler), **kwargs) + clients.append(result) + return result + + monkeypatch.setattr(httpx, "AsyncClient", client) + return clients + + +def test_read_observation_blocks_other_scope_write_but_allows_known_read_and_explicit( + tmp_path, monkeypatch +): + family, _, raw = provision(tmp_path, monkeypatch) + sent = [] + + def handler(request): + sent.append(request) + return httpx.Response(200, json={"mirrored": True, "value": "private"}) + + clients = http(monkeypatch, handler) + + async def scenario(): + assert ( + await context.request( + raw, + "POST", + "https://one.invalid/v1/memory.get", + "one", + body={"namespace": "private"}, + ) + ).json()["value"] == "private" + assert family.protected + for route in ("memory.set", "not-in-generated-metadata", "knowledge.upload"): + with pytest.raises(AutomaticCaptureSuppressed): + await context.request( + raw, + "POST", + "https://other.invalid/v1/" + route, + "changed", + body={"namespace": "another"}, + ) + await context.request(raw, "POST", "https://one.invalid/v1/memory.get", "one", body={}) + await context.request( + raw, "POST", "https://one.invalid/v1/memory.set", "one", body={}, explicit=True + ) + + asyncio.run(scenario()) + assert len(sent) == 3 + assert all(client.is_closed for client in clients) + + +@pytest.mark.parametrize("damage", ["missing-pointer", "lost-proof", "replacement", "malformed"]) +def test_pinned_context_refuses_without_repair_or_http(tmp_path, monkeypatch, damage): + family, path, raw = provision(tmp_path, monkeypatch) + if damage == "missing-pointer": + path.unlink() + elif damage == "lost-proof": + (family.base / family.id / "state").unlink() + elif damage == "malformed": + path.write_text("{}") + else: + path.unlink() + other = SessionProtection.create(base=tmp_path / "other") + source_cli.save_session_pointer(path, other) + before = sorted(item.name for item in family.base.iterdir()) + + def forbidden(request): + raise AssertionError("Configured context must refuse before HTTP") + + clients = http(monkeypatch, forbidden) + with pytest.raises(context.ContextUnavailable): + asyncio.run(context.request(raw, "POST", "https://one.invalid/v1/memory.get", "one")) + assert clients == [] + assert sorted(item.name for item in family.base.iterdir()) == before + if damage == "missing-pointer": + assert not path.exists() + + +def test_automatic_source_requires_matching_inherited_context(tmp_path, monkeypatch): + _, path, raw = provision(tmp_path, monkeypatch) + args = argparse.Namespace( + request_file=None, + token_file=None, + session_file=str(path), + intent="automatic", + namespace="private", + org="org", + ) + command = source_cli._COMMANDS["list"] + monkeypatch.delenv(context.CONTEXT_ENV) + with pytest.raises(source_cli.InputError, match="require inherited"): + source_cli._inputs(args, command) + monkeypatch.setenv(context.CONTEXT_ENV, raw) + monkeypatch.setenv("LOOM_API_KEY", "token") + assert source_cli._inputs(args, command)[1] == {"org": "org", "namespace": "private"} + args.session_file = str(path.with_name("other.json")) + with pytest.raises(context.ContextUnavailable): + source_cli._inputs(args, command) + + +@pytest.mark.parametrize("status", [429, 500, 503]) +def test_error_response_observed_once_and_all_resources_closed(tmp_path, monkeypatch, status): + family, _, raw = provision(tmp_path, monkeypatch) + sent = [] + + def handler(request): + sent.append(request) + return httpx.Response(status, json={"mirrored": True, "detail": {"message": "private"}}) + + clients = http(monkeypatch, handler) + response = asyncio.run(context.request(raw, "POST", "https://one.invalid/v1/memory.get", "one")) + assert response.status_code == status + assert "private" not in response.text + assert len(sent) == 1 and family.protected + assert all(client.is_closed for client in clients) + + +def test_cancelled_request_closes_transport(tmp_path, monkeypatch): + _, _, raw = provision(tmp_path, monkeypatch) + entered = asyncio.Event() + released = asyncio.Event() + + async def handler(request): + entered.set() + try: + await asyncio.Event().wait() + finally: + released.set() + + clients = http(monkeypatch, handler) + + async def scenario(): + task = asyncio.create_task( + context.request(raw, "POST", "https://one.invalid/v1/memory.get", "one") + ) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert released.is_set() + + asyncio.run(scenario()) + assert all(client.is_closed for client in clients) + + +def test_stream_keeps_observers_until_cancel_and_close(tmp_path, monkeypatch): + family, _, raw = provision(tmp_path, monkeypatch) + closed = [] + consumed = asyncio.Event() + + class Events(httpx.AsyncByteStream): + async def __aiter__(self): + yield b'data: {"mirrored":true,"text":"private"}\n\n' + await asyncio.Event().wait() + + async def aclose(self): + closed.append(True) + + clients = http( + monkeypatch, + lambda request: httpx.Response( + 200, headers={"content-type": "text/event-stream"}, stream=Events() + ), + ) + + async def consume(): + async with context.stream( + raw, "https://one.invalid/v1/assistant/chat", "one", body={}, explicit=True + ) as response: + async for chunk in response.aiter_bytes(): + assert chunk and family.protected + consumed.set() + + async def scenario(): + task = asyncio.create_task(consume()) + await consumed.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + asyncio.run(scenario()) + assert closed and all(client.is_closed for client in clients) + + +def test_run_sync_inside_existing_loop_preserves_context_and_closes(): + value = contextvars.ContextVar("caller", default="missing") + + async def scenario(): + value.set("inherited") + parent = asyncio.get_running_loop() + + async def child(): + assert asyncio.get_running_loop() is not parent + assert value.get() == "inherited" + return 7 + + assert context.run_sync(child) == 7 + + asyncio.run(scenario()) + + +def test_run_sync_interrupt_cancels_and_joins_owned_loop(monkeypatch): + entered = threading.Event() + closed = threading.Event() + + class Interrupted(Future): + def result(self, timeout=None): + assert entered.wait(5) + raise KeyboardInterrupt + + monkeypatch.setattr(context, "Future", Interrupted) + + async def work(): + try: + entered.set() + await asyncio.Event().wait() + finally: + closed.set() + + async def scenario(): + with pytest.raises(KeyboardInterrupt): + context.run_sync(work) + assert closed.is_set() + + asyncio.run(scenario()) + + +def test_explicit_sdk_intent_is_consumed_and_revoked_for_copied_callbacks(tmp_path, monkeypatch): + family, _, _ = provision(tmp_path, monkeypatch) + family.mark() + args = argparse.Namespace( + cmd="call", target="memory.set", method=None, body={}, request_intent="explicit" + ) + + async def write(args): + return 7 + + with context.command_intent(args): + assert not hasattr(args, "request_intent") + copied = contextvars.copy_context() + assert asyncio.run(context.guarded_command(args, write)) == 7 + with pytest.raises(AutomaticCaptureSuppressed): + copied.run(asyncio.run, context.guarded_command(args, write)) + + +def test_sdk_cli_actual_dispatch_observes_and_guards_without_agent_facade_flags( + tmp_path, monkeypatch, capsys +): + from loom import cli + + family, _, _ = provision(tmp_path, monkeypatch) + monkeypatch.setenv("LOOM_API_KEY", "test-token") + seen = [] + + def handler(request): + seen.append(request) + return httpx.Response(200, json={"mirrored": True, "value": "private"}) + + clients = http(monkeypatch, handler) + common = ["--server", "https://one.invalid", "--org", "test-org", "--namespace", "private"] + assert cli.main(["call", "memory.get", *common, "key=x"]) == 0 + assert family.protected and "private" in capsys.readouterr().out + assert cli.main(["call", "memory.set", *common, "key=x", "value=automatic"]) == 2 + assert "protection refused" in capsys.readouterr().err + assert len(seen) == 1 + assert ( + cli.main( + ["--request-intent", "explicit", "call", "memory.set", *common, "key=x", "value=human"] + ) + == 0 + ) + capsys.readouterr() + assert cli.main(["call", "memory.get", *common, "key=x"]) == 0 + assert len(seen) == 3 and all(client.is_closed for client in clients) diff --git a/sdk/python/tests/test_source_cli.py b/sdk/python/tests/test_source_cli.py new file mode 100644 index 0000000000..92c6dfb51e --- /dev/null +++ b/sdk/python/tests/test_source_cli.py @@ -0,0 +1,558 @@ +"""Source CLI behavior with the installed SDK and actual transport hooks.""" + +from __future__ import annotations + +import argparse +import asyncio +import io +import json +from pathlib import Path + +import httpx +import pytest +from loom import source_cli as cli +from loom.cli_context import CONTEXT_ENV, session_environment +from loom.errors import LoomError +from loom.session_protection import ( + AutomaticCaptureSuppressed, + SessionProtection, + SessionProtectionUnavailable, +) +from loom.transport import Transport + +REQUEST_ID = "10000000-0000-4000-8000-000000000001" +SLOT = "20000000-0000-4000-8000-000000000002" + + +def pointer(tmp_path: Path) -> tuple[SessionProtection, Path]: + directory = tmp_path / "application" + directory.mkdir(mode=0o700) + family = SessionProtection.create(base=tmp_path / "families") + path = directory / "session.json" + cli.save_session_pointer(path, family) + return family, path + + +def arguments(path: Path, *command: str) -> argparse.Namespace: + parser = argparse.ArgumentParser() + cli.register_source_cli(parser.add_subparsers(required=True)) + return parser.parse_args( + [ + "source", + *command, + "--server-url", + "https://loom.invalid", + "--org", + "test-org", + "--session-file", + str(path), + ] + ) + + +def factory(respond, opened: list[Transport] | None = None): + def create(*args, **kwargs): + transport = Transport(*args, **kwargs) + transport._client._transport = httpx.MockTransport(respond) + transport._client._mounts.clear() + if opened is not None: + opened.append(transport) + return transport + + return create + + +@pytest.mark.parametrize( + ("command", "op"), + [ + (("connection", "profiles"), "knowledge.source.mcp_profiles"), + (("connection", "connect"), "knowledge.connection.mcp_connect"), + (("connection", "list"), "knowledge.connection.mcp_list"), + (("connection", "inspect"), "knowledge.connection.mcp_inspect"), + (("connection", "discover"), "knowledge.connection.mcp_discover"), + (("connection", "browse"), "knowledge.connection.mcp_browse"), + (("connection", "disconnect"), "knowledge.connection.mcp_disconnect"), + *( + ((name,), "knowledge.source.mcp_" + name) + for name in ( + "preview", + "add", + "update", + "list", + "inspect", + "pause", + "resume", + "refresh", + "read", + "remove", + ) + ), + (("destination", "list"), "collection.list"), + (("destination", "create"), "collection.create"), + (("destination", "grant"), "grants.create"), + (("destination", "grants"), "grants.list"), + (("destination", "preview"), "knowledge.source.mcp_preview"), + (("recording", "list"), "knowledge.source.list"), + (("recording", "sync-now"), "knowledge.source.sync_now"), + (("retained", "list"), "knowledge.source.list"), + (("retained", "inspect"), "knowledge.source.inspect"), + (("retained", "remove"), "knowledge.source.remove"), + ], +) +def test_commands_select_exact_common_operation(tmp_path, command, op): + args = arguments(tmp_path / "unused", *command) + assert args.source_spec.op == op + assert args.intent == "automatic" + + +@pytest.mark.parametrize("mode", ["live", "snapshot", "selected_refresh"]) +@pytest.mark.parametrize("policy", ["owner_only", "collection_copy"]) +def test_add_preserves_exact_selection_and_publication_fields(tmp_path, mode, policy): + data = { + "namespace": "col-destination", + "slot": SLOT, + "mode": mode, + "reader_policy": policy, + "resource_ids": ["resource:one", "resource:two"], + "request_id": REQUEST_ID, + "label": "Selected documents", + "confirm_copy_authority": True, + } + request = tmp_path / "request.json" + request.write_text(json.dumps(data)) + args = arguments(tmp_path / "unused", "add", "--request-file", str(request)) + assert cli._request(args, args.source_spec) == {"org": "test-org", **data} + + +def test_update_preserves_revision_without_converting_it(tmp_path): + data = { + "namespace": "col-destination", + "name": "opaque", + "if_scope_revision": 7, + "resource_ids": ["resource:two"], + "mode": "selected_refresh", + "label": None, + "confirm_copy_authority": False, + } + request = tmp_path / "request.json" + request.write_text(json.dumps(data)) + args = arguments(tmp_path / "unused", "update", "--request-file", str(request)) + assert cli._request(args, args.source_spec) == {"org": "test-org", **data} + + +@pytest.mark.parametrize( + "data", + [ + {"links": ["https://example.invalid/private"]}, + {"items": [{"id": "private"}]}, + {"include": ["pdf"]}, + {"bearer": "private-secret"}, + {"credential": "private-secret"}, + {"request_id": "not-the-original-uuid"}, + ], +) +def test_native_fields_and_argv_secrets_are_rejected_without_echo(tmp_path, data): + request = tmp_path / "request.json" + request.write_text(json.dumps(data)) + args = arguments(tmp_path / "unused", "add", "--request-file", str(request)) + with pytest.raises(cli.InputError) as caught: + cli._request(args, args.source_spec) + assert "private" not in str(caught.value) + + +@pytest.mark.parametrize("flag", ["--link", "--item-json", "--include", "--token", "--bearer"]) +def test_removed_flags_have_no_parser_path(tmp_path, flag): + with pytest.raises(SystemExit) as caught: + arguments(tmp_path / "unused", "add", flag, "value") + assert caught.value.code == 2 + + +def test_connect_rejects_abbreviated_secret_flags(tmp_path): + with pytest.raises(SystemExit) as caught: + arguments(tmp_path / "unused", "connection", "connect", "--bearer", "value") + assert caught.value.code == 2 + + +def test_recording_add_keeps_config_and_private_credential(tmp_path, monkeypatch): + request = tmp_path / "request.json" + request.write_text( + json.dumps( + { + "namespace": "col-recordings", + "name": "notes", + "config": {"provider": "zoom", "ids": ["meeting"]}, + "dry_run": True, + } + ) + ) + secret = tmp_path / "credential" + secret.write_text("private-credential\n") + secret.chmod(0o600) + monkeypatch.setenv("LOOM_API_KEY", "explicit-environment-token") + args = arguments( + tmp_path / "unused", + "recording", + "add", + "--request-file", + str(request), + "--credential-file", + str(secret), + ) + body = cli._request(args, args.source_spec) + assert cli._credentials(args, args.source_spec, body) == "explicit-environment-token" + assert body == { + "org": "test-org", + "namespace": "col-recordings", + "name": "notes", + "kind": "recording", + "config": {"provider": "zoom", "ids": ["meeting"]}, + "dry_run": True, + "credential": "private-credential", + } + + +@pytest.mark.parametrize("kind", ["gdrive", "notion", "linear"]) +def test_recording_cannot_register_native_documents(tmp_path, kind): + path = tmp_path / "request.json" + path.write_text( + json.dumps({"namespace": "col-destination", "name": "native", "config": {}, "kind": kind}) + ) + args = arguments( + tmp_path / "unused", + "recording", + "add", + "--request-file", + str(path), + "--credential-file", + "-", + ) + with pytest.raises(cli.InputError, match="Only recording"): + cli._request(args, args.source_spec) + + +def test_private_read_survives_reopen_and_blocks_other_namespace_write(tmp_path): + family, path = pointer(tmp_path) + seen = [] + opened = [] + + def respond(request): + seen.append(request) + assert request.url.path == "/v1/knowledge.source.mcp_read" + assert request.headers.get_list("x-loom-session-protection") == ["v1"] + return httpx.Response(200, json={"mirrored": True, "text": "private-content"}) + + async def scenario(): + out = await cli.call_source( + cli._COMMANDS["read"], + { + "org": "test-org", + "namespace": "col-private", + "name": "source", + "resource_id": "resource:one", + }, + server_url="https://loom.invalid", + token="token", + family=cli.open_session(str(path)), + automatic=False, + transport_factory=factory(respond, opened), + ) + assert out["text"] == "private-content" + restored = cli.open_session(str(path)) + assert family.protected and restored.protected + with pytest.raises(AutomaticCaptureSuppressed): + await cli.call_source( + cli._DESTINATION_COMMANDS["grant"], + {"org": "other-org", "namespace": "col-team", "subject": "other", "role": "writer"}, + server_url="https://other.invalid", + token="changed-token", + family=restored, + transport_factory=factory(respond, opened), + ) + + asyncio.run(scenario()) + assert len(seen) == len(opened) == 1 + assert opened[0]._client.is_closed + + +@pytest.mark.parametrize("status", [429, 500, 503]) +def test_uncertain_connect_sends_original_uuid_once_and_closes(tmp_path, status): + family, _ = pointer(tmp_path) + seen = [] + opened = [] + body = {"org": "test-org", "profile_id": "approved", "request_id": REQUEST_ID} + + def respond(request): + seen.append(request) + assert request.headers["x-request-id"] == REQUEST_ID + assert json.loads(request.content) == body + return httpx.Response(status, json={"detail": {"code": "TEST_FAILURE"}}) + + async def scenario(): + with pytest.raises(LoomError): + await cli.call_source( + cli._CONNECTION_COMMANDS["connect"], + body, + server_url="https://loom.invalid", + token="token", + family=family, + transport_factory=factory(respond, opened), + ) + + asyncio.run(scenario()) + assert len(seen) == 1 + assert opened[0]._client.is_closed + + +@pytest.mark.parametrize("target", ["connect", "add"]) +def test_reconciliation_preserves_original_uuid(tmp_path, target): + body = {"request_id": REQUEST_ID, "namespace": "col-selected", "slot": SLOT} + out = io.StringIO() + command = cli._CONNECTION_COMMANDS["connect"] if target == "connect" else cli._COMMANDS["add"] + cli._reconcile(command, body, out) + assert REQUEST_ID in out.getvalue() + assert "inspect" in out.getvalue() + if target == "add": + assert "namespace, slot" in out.getvalue() + + +def test_pointer_is_exclusive_private_and_reopens_same_family(tmp_path): + family, path = pointer(tmp_path) + assert cli.open_session(str(path)).pointer() == family.pointer() + assert path.stat().st_mode & 0o777 == 0o600 + with pytest.raises(FileExistsError): + cli.save_session_pointer(path, SessionProtection.create(base=tmp_path / "other")) + assert cli.open_session(str(path)).pointer() == family.pointer() + + +@pytest.mark.parametrize("damage", ["missing", "public", "symlink", "malformed", "lost-proof"]) +def test_restore_damage_refuses_without_new_family(tmp_path, damage): + family, path = pointer(tmp_path) + if damage == "missing": + path.unlink() + elif damage == "public": + path.chmod(0o644) + elif damage == "symlink": + original = path.with_name("original") + path.rename(original) + path.symlink_to(original) + elif damage == "malformed": + path.write_text('{"version":1,"pointer":{}}') + else: + (family.base / family.id / "state").unlink() + before = sorted(item.name for item in family.base.iterdir()) + with pytest.raises((OSError, cli.InputError, SessionProtectionUnavailable)): + cli.open_session(str(path)) + assert sorted(item.name for item in family.base.iterdir()) == before + + +@pytest.mark.parametrize("raw", ['{"limit":1,"limit":2}', "[]", '{"secret":']) +def test_malformed_and_duplicate_json_never_echoes_body(raw): + with pytest.raises(cli.InputError) as caught: + cli._json_object(raw) + assert "secret" not in str(caught.value) + + +def test_bounded_requests_and_private_secret_file(tmp_path): + path = tmp_path / "input" + path.write_bytes(b"x" * (cli.MAX_REQUEST_BYTES + 1)) + with pytest.raises(cli.InputError, match="byte limit"): + cli._read_input(str(path), cli.MAX_REQUEST_BYTES) + path.write_text("secret") + path.chmod(0o644) + with pytest.raises(cli.InputError, match="private regular file"): + cli._read_input(str(path), cli.MAX_SECRET_BYTES, private=True) + + +def test_conflicting_namespace_cannot_redirect_selection(tmp_path): + path = tmp_path / "request.json" + path.write_text('{"namespace":"col-original"}') + args = arguments( + tmp_path / "unused", "list", "--namespace", "col-other", "--request-file", str(path) + ) + with pytest.raises(cli.InputError, match="conflicts"): + cli._request(args, args.source_spec) + + +def test_private_and_team_destinations_use_ordinary_collections(tmp_path): + for extra in ({}, {"parent": "col-team"}): + path = tmp_path / "request.json" + path.write_text(json.dumps({"namespace": "col-notes", "title": "Notes", **extra})) + args = arguments(tmp_path / "unused", "destination", "create", "--request-file", str(path)) + assert cli._request(args, args.source_spec) == { + "org": "test-org", + "namespace": "col-notes", + "title": "Notes", + **extra, + } + preview = arguments(tmp_path / "unused", "destination", "preview") + assert preview.source_spec is cli._COMMANDS["preview"] + + +def _mock_http(monkeypatch, respond): + client = httpx.AsyncClient + + def create(*args, **kwargs): + return client(*args, transport=httpx.MockTransport(respond), **kwargs) + + monkeypatch.setattr(httpx, "AsyncClient", create) + + +def _argv(path, *command): + return [ + "source", + *command, + "--server-url", + "https://loom.invalid", + "--org", + "test-org", + "--session-file", + str(path), + ] + + +def test_actual_cli_read_then_automatic_grant_uses_same_restored_proof( + tmp_path, monkeypatch, capsys +): + family, path = pointer(tmp_path) + monkeypatch.setenv(CONTEXT_ENV, session_environment(str(path))[CONTEXT_ENV]) + monkeypatch.setenv("LOOM_API_KEY", "test-token") + seen = [] + + def respond(request): + seen.append(request) + assert request.url.path == "/v1/knowledge.source.mcp_read" + assert request.headers.get_list("x-loom-session-protection") == ["v1"] + return httpx.Response(200, json={"mirrored": True, "text": "private-content"}) + + _mock_http(monkeypatch, respond) + request = tmp_path / "request.json" + request.write_text( + json.dumps({"namespace": "col-private", "name": "opaque", "resource_id": "r:one"}) + ) + assert ( + cli.main(_argv(path, "read", "--request-file", str(request), "--intent", "explicit")) == 0 + ) + assert json.loads(capsys.readouterr().out)["text"] == "private-content" + request.write_text( + json.dumps({"namespace": "col-other", "subject": "another", "role": "viewer"}) + ) + assert cli.main(_argv(path, "destination", "grant", "--request-file", str(request))) == 2 + output = capsys.readouterr() + assert output.out == "" + assert "private-content" not in output.err + assert "Session protection refused" in output.err + assert len(seen) == 1 and family.protected + + +def test_stdin_inputs_cannot_share_one_stream(tmp_path, capsys): + _, path = pointer(tmp_path) + assert ( + cli.main(_argv(path, "recording", "add", "--request-file", "-", "--credential-file", "-")) + == 2 + ) + assert "Only one input" in capsys.readouterr().err + + +def test_cli_missing_pointer_refuses_before_any_transport(tmp_path, monkeypatch, capsys): + def forbidden(*args, **kwargs): + raise AssertionError("No request can begin without restore proof") + + monkeypatch.setattr(httpx, "AsyncClient", forbidden) + assert ( + cli.main( + _argv( + tmp_path / "missing", + "list", + "--namespace", + "col-destination", + "--intent", + "explicit", + ) + ) + == 2 + ) + output = capsys.readouterr() + assert output.out == "" + assert "unavailable" in output.err + assert not (tmp_path / "missing").exists() + + +def test_cli_reconciles_connect_by_original_uuid_without_resubmitting( + tmp_path, monkeypatch, capsys +): + _, path = pointer(tmp_path) + monkeypatch.setenv(CONTEXT_ENV, session_environment(str(path))[CONTEXT_ENV]) + monkeypatch.setenv("LOOM_API_KEY", "test-token") + seen = [] + + def respond(request): + seen.append(request) + if len(seen) == 1: + assert request.headers["x-request-id"] == REQUEST_ID + return httpx.Response( + 503, json={"detail": {"code": "TEST_FAILURE", "message": "private-diagnostic"}} + ) + assert request.url.path == "/v1/knowledge.connection.mcp_inspect" + assert json.loads(request.content) == {"org": "test-org", "request_id": REQUEST_ID} + return httpx.Response(200, json={"found": True, "reconciliation": "present", "slot": SLOT}) + + _mock_http(monkeypatch, respond) + request = tmp_path / "request.json" + request.write_text(json.dumps({"profile_id": "approved", "request_id": REQUEST_ID})) + assert cli.main(_argv(path, "connection", "connect", "--request-file", str(request))) == 1 + output = capsys.readouterr() + assert len(seen) == 1 and output.out == "" + assert REQUEST_ID in output.err and "private-diagnostic" not in output.err + request.write_text(json.dumps({"request_id": REQUEST_ID})) + assert cli.main(_argv(path, "connection", "inspect", "--request-file", str(request))) == 0 + assert json.loads(capsys.readouterr().out)["reconciliation"] == "present" + assert len(seen) == 2 + + +@pytest.mark.parametrize("request_id", ["", "not-a-uuid", None, 1]) +def test_connect_requires_original_uuid_without_generating_one(tmp_path, request_id): + request = tmp_path / "request.json" + request.write_text(json.dumps({"profile_id": "approved", "request_id": request_id})) + args = arguments(tmp_path / "unused", "connection", "connect", "--request-file", str(request)) + with pytest.raises(cli.InputError, match="original canonical UUID"): + cli._request(args, args.source_spec) + + +@pytest.mark.parametrize("raw", ['{"limit":NaN}', '{"limit":Infinity}', '{"limit":-Infinity}']) +def test_nonfinite_values_are_not_json_inputs(raw): + with pytest.raises(cli.InputError): + cli._json_object(raw) + + +def test_private_error_status_is_observed_before_error_release(tmp_path): + family, _ = pointer(tmp_path) + seen = [] + + def respond(request): + seen.append(request) + return httpx.Response(403, json={"mirrored": True, "detail": {"code": "ACCESS_DENIED"}}) + + async def scenario(): + with pytest.raises(LoomError): + await cli.call_source( + cli._COMMANDS["read"], + {"org": "test-org"}, + server_url="https://loom.invalid", + token="token", + family=family, + automatic=False, + transport_factory=factory(respond), + ) + assert family.protected + with pytest.raises(AutomaticCaptureSuppressed): + await cli.call_source( + cli._RECORDING_COMMANDS["add"], + {"org": "other-org", "namespace": "col-recordings"}, + server_url="https://other.invalid", + token="changed-token", + family=family, + transport_factory=factory(respond), + ) + + asyncio.run(scenario()) + assert len(seen) == 1 diff --git a/sdk/ruby/README.md b/sdk/ruby/README.md index 14f0b31c31..8413fb5f22 100644 --- a/sdk/ruby/README.md +++ b/sdk/ruby/README.md @@ -173,3 +173,7 @@ cd sdk/ruby && bundle install && bundle exec rake test ``` The tests run against a local fake server and need no running Loom. + +## Session protection + +Bind a durable conversation handle before reading protected sources, and retain its capture for every automatic write. See [Session protection](SESSION_PROTECTION.md) for restore, callback and response limits. diff --git a/sdk/ruby/SESSION_PROTECTION.md b/sdk/ruby/SESSION_PROTECTION.md new file mode 100644 index 0000000000..d0f92e9bab --- /dev/null +++ b/sdk/ruby/SESSION_PROTECTION.md @@ -0,0 +1,33 @@ +# Session protection + +Bind an application-owned `SessionProtection` to every client that reads protected sources. The handle uses a private POSIX directory containing an identity, a monotonic protection bit and pending request markers. It stores no response bodies, credentials or source identifiers. The application owns the directory and stores its pointer in the trusted conversation record. + +```ruby +require "clickhouse/loom" + +family = Loom::SessionProtection.create(conversation_state_directory) +conversation.save_protection_pointer(family.pointer) +client = Loom::Client.new(session_protection: family) +answer = client.call("knowledge.source.mcp_read", read_arguments) +``` + +On resume, use `SessionProtection.open(conversation.protection_pointer)`. Missing, invalid or inaccessible state raises `SessionProtectionUnavailable`. Never replace a failed restore with `create`. Reopening a directory with a pending request latches protection, including after a process interruption. Share the same handle among active clients rather than reopening it per request. Back up and restore the pointer and its directory together; the application must prevent rollback or replacement of trusted storage. + +Retain a capture before scheduling automatic work. Its callback guards every operation inside its scope, including calls through another client, identity or namespace. An automatic operation refuses once any contributor is protected or has a response still pending. Explicit user operations remain available and still observe metadata. + +```ruby +capture = family.capture +queue.enqueue do + capture.call do + another_client.call("memory.set", automatic_write_arguments) + end +end +# For one operation: +# another_client.call_automatic(capture, "memory.set", automatic_write_arguments) +``` + +`capture.contribute(other_family)` returns a capture retaining both families. Creating a capture within another capture's callback retains its contributors too. Ruby's scope follows the current fiber; pass the retained capture into other fibers, threads and queued callbacks and enter `capture.call` there. Application code must use this API for every automatic write, including direct calls to another namespace. A new client alone carries no conversation identity or protection authority. + +The actual `Client#post` boundary declares `x-loom-session-protection: v1` only after durable admission and with the installed observer. There is no public header override. Every retry passes the final automatic guard. Response JSON is bounded to 4 MiB and observed at every HTTP status before decoding or constructing API errors. Mirrored metadata latches every opening family. Invalid envelopes, oversized responses and interrupted body reads refuse and latch protection. An interrupted request retains a durable pending marker if cleanup cannot acknowledge completion. + +Protected streaming is unavailable. Event streams and other unsupported media refuse without returning response bytes. Ordinary unbound requests preserve their existing behavior and send no declaration. The application must qualify its actual source operations and deferred work before activation; generated operation availability is independent of transport readiness. diff --git a/sdk/ruby/lib/clickhouse/loom/client.rb b/sdk/ruby/lib/clickhouse/loom/client.rb index b31c240e78..72a8c660cb 100644 --- a/sdk/ruby/lib/clickhouse/loom/client.rb +++ b/sdk/ruby/lib/clickhouse/loom/client.rb @@ -7,6 +7,7 @@ require "uri" require_relative "errors" +require_relative "session_protection" require_relative "version" require_relative "configuration" require_relative "retry_policy" @@ -73,7 +74,8 @@ class Client # out 429 answers (default 15, 0 raises the first). +sleeper+ is called with the # seconds to wait between attempts (a test seam; default Kernel#sleep). def initialize(base_url: nil, api_key: nil, org: nil, namespace: nil, agent: nil, open_timeout: nil, - read_timeout: nil, retry_policy: nil, rate_limit_max_wait: nil, sleeper: nil) + read_timeout: nil, retry_policy: nil, rate_limit_max_wait: nil, sleeper: nil, + session_protection: nil) config = Loom.configuration @base_url = first_non_blank(base_url, config.base_url, ENV.fetch("LOOM_BASE_URL", nil), DEFAULT_BASE_URL).sub(%r{/+\z}, "") @@ -88,6 +90,11 @@ def initialize(base_url: nil, api_key: nil, org: nil, namespace: nil, agent: nil @retry_policy = RetryPolicy.resolve(@retry_policy, retry_policy, "Client") @rate_limit_max_wait = Float(rate_limit_max_wait || config.rate_limit_max_wait || 15) @sleeper = sleeper || ->(seconds) { sleep(seconds) } + unless session_protection.nil? || session_protection.is_a?(SessionProtection) + raise ArgumentError, "session_protection must be a SessionProtection" + end + @session_protection = session_protection + @session_protection&.ready! @groups = {} end @@ -106,6 +113,11 @@ def call(op, input = nil, idempotency_key: nil, retry_policy: nil) send_with_retries(op, spec, body, request_headers(spec, idempotency_key), policy) end + # Retained automatic work uses the same barrier with every client and namespace. + def call_automatic(capture, op, input = nil, **options) + capture.call { call(op, input, **options) } + end + # Saves +value+ under +key+: plain text, or any Hash, Array or scalar. Writing a # key that already holds a row adds a new version. +memory_type+ left nil lets the # server use "semantic". @@ -256,9 +268,69 @@ def post(op, body, headers) request = Net::HTTP::Post.new(uri) headers.each { |name, value| request[name] = value } request.body = body + if headers.keys.any? { |name| name.downcase == "x-loom-session-protection" } + raise SessionProtectionUnavailable + end + capture = SessionCapture.current + families = [@session_protection, *SessionCapture.current_families].compact.uniq { |family| family.pointer } + capture = SessionCapture.new(families) if capture + capture&.guard! Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https", open_timeout: @open_timeout, read_timeout: @read_timeout) do |http| - http.request(request) + if families.empty? + http.request(request) + else + protected_post(http, request, families, capture) + end + end + end + + def protected_post(http, request, families, capture) + attempts = [] + complete = false + begin + families.each { |family| family.ready! } + capture&.guard! + families.each { |family| attempts << [family, family.begin_attempt] } + request["X-Loom-Session-Protection"] = "v1" + attempts.each { |family, name| family.attempt_ready!(name) } + capture&.families&.each do |family| + own = attempts.find { |candidate, _| candidate.pointer == family.pointer }&.last + raise AutomaticCaptureSuppressed if family.protected? || family.pending_except?(own) + end + response = http.request(request) do |answer| + media = answer["Content-Type"].to_s.split(";", 2).first.to_s.strip.downcase + unless media == "application/json" || media.end_with?("+json") || [204, 304].include?(answer.code.to_i) + raise SessionProtectionUnavailable + end + bytes = +"" + answer.read_body do |chunk| + raise SessionProtectionUnavailable if bytes.bytesize + chunk.bytesize > SessionProtection::MAX_BODY + + bytes << chunk + end + value = bytes.empty? && [204, 304].include?(answer.code.to_i) ? {} : JSON.parse(bytes) + raise SessionProtectionUnavailable unless value.is_a?(Hash) + + families.each { |family| family.ready! } + families.each(&:mark!) if SessionProtection.marked?(value) + answer.body = bytes + end + attempts.each { |family, name| family.finish_attempt(name) } + complete = true + response + rescue JSON::ParserError, JSON::NestingError + raise SessionProtectionUnavailable + ensure + unless complete + families.each do |family| + begin + family.mark! + rescue SessionProtectionUnavailable + # The durable pending marker also refuses resumed automatic writes. + end + end + end end end diff --git a/sdk/ruby/lib/clickhouse/loom/generated/errors.rb b/sdk/ruby/lib/clickhouse/loom/generated/errors.rb index 4c9e15c08f..284403d052 100644 --- a/sdk/ruby/lib/clickhouse/loom/generated/errors.rb +++ b/sdk/ruby/lib/clickhouse/loom/generated/errors.rb @@ -125,11 +125,6 @@ class BadKind < Error CODE = "BAD_KIND" end - # `BAD_LINK`: Server code - class BadLink < Error - CODE = "BAD_LINK" - end - # `BAD_MAPPING`: Server code class BadMapping < Error CODE = "BAD_MAPPING" @@ -480,6 +475,11 @@ class MappingFailed < Error CODE = "MAPPING_FAILED" end + # `MCP_SOURCE_UNAVAILABLE`: Server code + class McpSourceUnavailable < Error + CODE = "MCP_SOURCE_UNAVAILABLE" + end + # `MISDIRECTED_REQUEST`: Server code class MisdirectedRequest < Error CODE = "MISDIRECTED_REQUEST" @@ -997,7 +997,6 @@ class WrongCell < Error "BAD_INPUT" => BadInput, "BAD_JOIN_POLICY" => BadJoinPolicy, "BAD_KIND" => BadKind, - "BAD_LINK" => BadLink, "BAD_MAPPING" => BadMapping, "BAD_NAME" => BadName, "BAD_NAMESPACE" => BadNamespace, @@ -1068,6 +1067,7 @@ class WrongCell < Error "KEY_HOLDS_FACT" => KeyHoldsFact, "LOCKED" => Locked, "MAPPING_FAILED" => MappingFailed, + "MCP_SOURCE_UNAVAILABLE" => McpSourceUnavailable, "MISDIRECTED_REQUEST" => MisdirectedRequest, "MISSING_IDENTITY_FIELD" => MissingIdentityField, "MISSING_REQUIRED_FIELD" => MissingRequiredField, diff --git a/sdk/ruby/lib/clickhouse/loom/generated/ops.rb b/sdk/ruby/lib/clickhouse/loom/generated/ops.rb index a1f6ec5794..ff87e27504 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 = 383 + OP_COUNT = 386 # The declared spec of every served op, by name; the HTTP path is /v1/. OPS = { @@ -82,8 +82,6 @@ module Generated "conflicts.list" => OpSpec.new("conflicts.list", "conflicts", "list", true, true, "viewer", "stable", %w[org namespace limit before_version count_only fresh keys_only fields].freeze, %w[org namespace].freeze), "conflicts.propose_revision" => OpSpec.new("conflicts.propose_revision", "conflicts", "propose_revision", true, true, "viewer", "experimental", %w[org namespace memory_id peer_id].freeze, %w[org namespace memory_id].freeze), "conflicts.resolve" => OpSpec.new("conflicts.resolve", "conflicts", "resolve", true, false, "admin", "stable", %w[org namespace memory_id decision peer_id reason resolved_by].freeze, %w[org namespace memory_id decision].freeze), - "connection.disconnect" => OpSpec.new("connection.disconnect", "connection", "disconnect", true, false, "viewer", "experimental", %w[org kind].freeze, %w[org kind].freeze), - "connection.list" => OpSpec.new("connection.list", "connection", "list", true, true, "viewer", "experimental", %w[org].freeze, %w[org].freeze), "consolidations.list" => OpSpec.new("consolidations.list", "consolidations", "list", true, true, "viewer", "experimental", %w[org namespace agent user_id session_id run_id limit].freeze, %w[org namespace].freeze), "context.fetch" => OpSpec.new("context.fetch", "context", "fetch", true, true, "viewer", "experimental", %w[org namespace agent user_id session_id run_id blob_key offset limit pattern context_lines].freeze, %w[org namespace agent blob_key].freeze), "context.offload" => OpSpec.new("context.offload", "context", "offload", true, false, "writer", "experimental", %w[org namespace agent user_id session_id run_id content blob_key content_type summary ttl_seconds].freeze, %w[org namespace agent content].freeze), @@ -142,6 +140,7 @@ module Generated "knowledge.add" => OpSpec.new("knowledge.add", "knowledge", "add", true, false, "writer", "stable", %w[org namespace source_uri content title description tags metadata original_bytes_b64 original_filename blob_content_type agent session_id source_class].freeze, %w[org namespace source_uri content].freeze), "knowledge.bulk_add" => OpSpec.new("knowledge.bulk_add", "knowledge", "bulk_add", true, false, "writer", "stable", %w[org namespace entries agent session_id source_class].freeze, %w[org namespace entries].freeze), "knowledge.bulk_delete" => OpSpec.new("knowledge.bulk_delete", "knowledge", "bulk_delete", true, false, "writer", "experimental", %w[org namespace source_uris].freeze, %w[org namespace source_uris].freeze), + "knowledge.connection.mcp_browse" => OpSpec.new("knowledge.connection.mcp_browse", "knowledge", "connection_mcp_browse", true, true, "viewer", "experimental", %w[org slot mode query limit].freeze, %w[org slot mode].freeze), "knowledge.connection.mcp_connect" => OpSpec.new("knowledge.connection.mcp_connect", "knowledge", "connection_mcp_connect", false, false, "viewer", "experimental", %w[org profile_id request_id label bearer].freeze, %w[org profile_id request_id].freeze), "knowledge.connection.mcp_disconnect" => OpSpec.new("knowledge.connection.mcp_disconnect", "knowledge", "connection_mcp_disconnect", false, false, "viewer", "experimental", %w[org slot].freeze, %w[org slot].freeze), "knowledge.connection.mcp_discover" => OpSpec.new("knowledge.connection.mcp_discover", "knowledge", "connection_mcp_discover", true, true, "viewer", "experimental", %w[org slot].freeze, %w[org slot].freeze), @@ -170,20 +169,24 @@ module Generated "knowledge.reads" => OpSpec.new("knowledge.reads", "knowledge", "reads", true, true, "viewer", "experimental", %w[org namespace days source_uris].freeze, %w[org namespace].freeze), "knowledge.restore" => OpSpec.new("knowledge.restore", "knowledge", "restore", true, false, "writer", "experimental", %w[org namespace source_uri if_revision].freeze, %w[org namespace source_uri].freeze), "knowledge.search" => OpSpec.new("knowledge.search", "knowledge", "search", true, true, "viewer", "stable", %w[org namespace query tags since_seconds top_k namespace_scope namespaces search_mode lexical_weight narrow_spans collapse_sections uri_prefix session_ids source_classes formats block_types rerank].freeze, %w[org namespace query].freeze), - "knowledge.source.add" => OpSpec.new("knowledge.source.add", "knowledge", "source_add", false, false, "writer", "experimental", %w[org namespace name kind items links config include credential_mode credential dry_run].freeze, %w[org namespace name kind].freeze), + "knowledge.source.add" => OpSpec.new("knowledge.source.add", "knowledge", "source_add", false, false, "writer", "experimental", %w[org namespace name kind config credential dry_run].freeze, %w[org namespace name config credential].freeze), "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.mcp_add" => OpSpec.new("knowledge.source.mcp_add", "knowledge", "source_mcp_add", false, false, "writer", "experimental", %w[org namespace slot mode reader_policy resource_ids request_id label confirm_copy_authority].freeze, %w[org namespace slot mode resource_ids request_id].freeze), + "knowledge.source.mcp_inspect" => OpSpec.new("knowledge.source.mcp_inspect", "knowledge", "source_mcp_inspect", true, false, "writer", "experimental", %w[org namespace name slot request_id].freeze, %w[org namespace].freeze), + "knowledge.source.mcp_list" => OpSpec.new("knowledge.source.mcp_list", "knowledge", "source_mcp_list", true, false, "writer", "experimental", %w[org namespace cursor limit include_retired].freeze, %w[org namespace].freeze), + "knowledge.source.mcp_pause" => OpSpec.new("knowledge.source.mcp_pause", "knowledge", "source_mcp_pause", false, false, "writer", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), "knowledge.source.mcp_preview" => OpSpec.new("knowledge.source.mcp_preview", "knowledge", "source_mcp_preview", true, false, "writer", "experimental", %w[org namespace slot mode reader_policy resource_ids].freeze, %w[org namespace slot mode resource_ids].freeze), "knowledge.source.mcp_profiles" => OpSpec.new("knowledge.source.mcp_profiles", "knowledge", "source_mcp_profiles", true, true, "viewer", "experimental", %w[org query cursor limit].freeze, %w[org].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), - "knowledge.source.push_status" => OpSpec.new("knowledge.source.push_status", "knowledge", "source_push_status", false, false, "admin", "experimental", %w[org namespace name reveal_challenge].freeze, %w[org namespace name].freeze), + "knowledge.source.mcp_read" => OpSpec.new("knowledge.source.mcp_read", "knowledge", "source_mcp_read", true, true, "viewer", "experimental", %w[org namespace name resource_id].freeze, %w[org namespace name resource_id].freeze), + "knowledge.source.mcp_refresh" => OpSpec.new("knowledge.source.mcp_refresh", "knowledge", "source_mcp_refresh", false, false, "writer", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), + "knowledge.source.mcp_remove" => OpSpec.new("knowledge.source.mcp_remove", "knowledge", "source_mcp_remove", false, false, "writer", "experimental", %w[org namespace name confirm delete_documents].freeze, %w[org namespace name confirm].freeze), + "knowledge.source.mcp_resume" => OpSpec.new("knowledge.source.mcp_resume", "knowledge", "source_mcp_resume", false, false, "writer", "experimental", %w[org namespace name].freeze, %w[org namespace name].freeze), + "knowledge.source.mcp_update" => OpSpec.new("knowledge.source.mcp_update", "knowledge", "source_mcp_update", false, false, "writer", "experimental", %w[org namespace name if_scope_revision resource_ids mode label confirm_copy_authority].freeze, %w[org namespace name resource_ids mode].freeze), "knowledge.source.remove" => OpSpec.new("knowledge.source.remove", "knowledge", "source_remove", false, false, "writer", "experimental", %w[org namespace name confirm delete_documents].freeze, %w[org namespace name confirm].freeze), "knowledge.source.rotate" => OpSpec.new("knowledge.source.rotate", "knowledge", "source_rotate", false, false, "admin", "experimental", %w[org namespace name credential].freeze, %w[org namespace name credential].freeze), "knowledge.source.sync_now" => OpSpec.new("knowledge.source.sync_now", "knowledge", "source_sync_now", true, false, "writer", "experimental", %w[org namespace name full].freeze, %w[org namespace name].freeze), - "knowledge.source.update" => OpSpec.new("knowledge.source.update", "knowledge", "source_update", false, false, "writer", "experimental", %w[org namespace name add_items add_links remove_items remove_links include].freeze, %w[org namespace name].freeze), "knowledge.synthesize" => OpSpec.new("knowledge.synthesize", "knowledge", "synthesize", true, false, "viewer", "experimental", %w[org namespace user_id source_uris datasets task window_chars max_answer_chars max_windows].freeze, %w[org namespace task].freeze), "knowledge.update_metadata" => OpSpec.new("knowledge.update_metadata", "knowledge", "update_metadata", true, false, "writer", "experimental", %w[org namespace source_uri title description tags reindex].freeze, %w[org namespace source_uri].freeze), "knowledge.upsert" => OpSpec.new("knowledge.upsert", "knowledge", "upsert", true, false, "writer", "experimental", %w[org namespace source_uri content title description tags metadata original_bytes_b64 original_filename blob_content_type agent session_id source_class].freeze, %w[org namespace source_uri content].freeze), @@ -853,23 +856,6 @@ def resolve(body = nil, request_options: nil, **fields) end end - # The `connection.*` operations. - class ConnectionOps < OpGroup - # `connection.disconnect` (viewer, writes, Idempotency-Key, experimental). - # Disconnect the caller's own provider account and stop its connected sources. - # Required: org, kind. - def disconnect(body = nil, request_options: nil, **fields) - call_op("connection.disconnect", body, fields, request_options) - end - - # `connection.list` (viewer, read-only, experimental). - # List the signed-in caller's own connected provider accounts. - # Required: org. - def list(body = nil, request_options: nil, **fields) - call_op("connection.list", body, fields, request_options) - end - end - # The `consolidations.*` operations. class ConsolidationsOps < OpGroup # `consolidations.list` (viewer, read-only, experimental). @@ -1283,6 +1269,12 @@ def bulk_delete(body = nil, request_options: nil, **fields) call_op("knowledge.bulk_delete", body, fields, request_options) end + # `knowledge.connection.mcp_browse` (viewer, read-only, experimental). + # Required: org, slot, mode. + def connection_mcp_browse(body = nil, request_options: nil, **fields) + call_op("knowledge.connection.mcp_browse", body, fields, request_options) + end + # `knowledge.connection.mcp_connect` (viewer, writes, experimental). # Required: org, profile_id, request_id. def connection_mcp_connect(body = nil, request_options: nil, **fields) @@ -1473,21 +1465,21 @@ def search(body = nil, request_options: nil, **fields) end # `knowledge.source.add` (writer, writes, experimental). - # Register a document source on a namespace: a kind, what it reads (items - # Required: org, namespace, name, kind. + # Register a shared recording source after checking its read-only credential. + # Required: org, namespace, name, config, credential. def source_add(body = nil, request_options: nil, **fields) call_op("knowledge.source.add", body, fields, request_options) end # `knowledge.source.check` (writer, writes, Idempotency-Key, experimental). - # Probe a registered document source with its stored credential now (a check of + # Probe a shared recording with its stored credential without writing. # Required: org, namespace, name. def source_check(body = nil, request_options: nil, **fields) call_op("knowledge.source.check", body, fields, request_options) end # `knowledge.source.inspect` (viewer, read-only, experimental). - # One registered document source: its items, its sync state and the + # One registered document source: its config, its sync state and the # Required: org, namespace, name. def source_inspect(body = nil, request_options: nil, **fields) call_op("knowledge.source.inspect", body, fields, request_options) @@ -1500,6 +1492,30 @@ def source_list(body = nil, request_options: nil, **fields) call_op("knowledge.source.list", body, fields, request_options) end + # `knowledge.source.mcp_add` (writer, writes, experimental). + # Required: org, namespace, slot, mode, resource_ids, request_id. + def source_mcp_add(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_add", body, fields, request_options) + end + + # `knowledge.source.mcp_inspect` (writer, writes, Idempotency-Key, experimental). + # Required: org, namespace. + def source_mcp_inspect(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_inspect", body, fields, request_options) + end + + # `knowledge.source.mcp_list` (writer, writes, Idempotency-Key, experimental). + # Required: org, namespace. + def source_mcp_list(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_list", body, fields, request_options) + end + + # `knowledge.source.mcp_pause` (writer, writes, experimental). + # Required: org, namespace, name. + def source_mcp_pause(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_pause", body, fields, request_options) + end + # `knowledge.source.mcp_preview` (writer, writes, Idempotency-Key, experimental). # Required: org, namespace, slot, mode, resource_ids. def source_mcp_preview(body = nil, request_options: nil, **fields) @@ -1513,32 +1529,34 @@ def source_mcp_profiles(body = nil, request_options: nil, **fields) call_op("knowledge.source.mcp_profiles", 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. - def source_parse_links(body = nil, request_options: nil, **fields) - call_op("knowledge.source.parse_links", body, fields, request_options) + # `knowledge.source.mcp_read` (viewer, read-only, experimental). + # Required: org, namespace, name, resource_id. + def source_mcp_read(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_read", body, fields, request_options) end - # `knowledge.source.push_configure` (admin, writes, experimental). - # Enable provider sync hints for an existing source, or disable its setup. + # `knowledge.source.mcp_refresh` (writer, writes, experimental). # Required: org, namespace, name. - def source_push_configure(body = nil, request_options: nil, **fields) - call_op("knowledge.source.push_configure", body, fields, request_options) + def source_mcp_refresh(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_refresh", body, fields, request_options) end - # `knowledge.source.push_confirm` (admin, writes, experimental). - # Activate the exact pending setup. - # Required: org, namespace, name, generation. - def source_push_confirm(body = nil, request_options: nil, **fields) - call_op("knowledge.source.push_confirm", body, fields, request_options) + # `knowledge.source.mcp_remove` (writer, writes, experimental). + # Required: org, namespace, name, confirm. + def source_mcp_remove(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_remove", body, fields, request_options) end - # `knowledge.source.push_status` (admin, writes, experimental). - # Read push setup as a namespace admin. + # `knowledge.source.mcp_resume` (writer, writes, experimental). # Required: org, namespace, name. - def source_push_status(body = nil, request_options: nil, **fields) - call_op("knowledge.source.push_status", body, fields, request_options) + def source_mcp_resume(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_resume", body, fields, request_options) + end + + # `knowledge.source.mcp_update` (writer, writes, experimental). + # Required: org, namespace, name, resource_ids, mode. + def source_mcp_update(body = nil, request_options: nil, **fields) + call_op("knowledge.source.mcp_update", body, fields, request_options) end # `knowledge.source.remove` (writer, writes, experimental). @@ -1562,13 +1580,6 @@ def source_sync_now(body = nil, request_options: nil, **fields) call_op("knowledge.source.sync_now", body, fields, request_options) end - # `knowledge.source.update` (writer, writes, experimental). - # Add items to a registered document source or remove them, or change a gdrive - # Required: org, namespace, name. - def source_update(body = nil, request_options: nil, **fields) - call_op("knowledge.source.update", body, fields, request_options) - end - # `knowledge.synthesize` (viewer, writes, Idempotency-Key, experimental). # Complete a task over WHOLE documents, not a search slice: # Required: org, namespace, task. @@ -3024,7 +3035,6 @@ def set(body = nil, request_options: nil, **fields) "code" => CodeOps, "collection" => CollectionOps, "conflicts" => ConflictsOps, - "connection" => ConnectionOps, "consolidations" => ConsolidationsOps, "context" => ContextOps, "conversation" => ConversationOps, @@ -3098,10 +3108,6 @@ def conflicts op_group("conflicts") end - def connection - op_group("connection") - end - def consolidations op_group("consolidations") end diff --git a/sdk/ruby/lib/clickhouse/loom/session_protection.rb b/sdk/ruby/lib/clickhouse/loom/session_protection.rb new file mode 100644 index 0000000000..91c9e1469d --- /dev/null +++ b/sdk/ruby/lib/clickhouse/loom/session_protection.rb @@ -0,0 +1,246 @@ +# frozen_string_literal: true + +require "json" +require "securerandom" + +module ClickHouse + module Loom + class SessionProtectionUnavailable < StandardError + def initialize + super("Session protection state could not be confirmed") + end + end + + class AutomaticCaptureSuppressed < StandardError + def initialize + super("Automatic capture is suppressed for this session") + end + end + + # The application retains the pointer in its trusted conversation record. + # The directory contains no response bodies or credentials. + class SessionProtection + MAX_BODY = 4 * 1024 * 1024 + CONTEXT = :loom_session_capture + + def self.create(path) + Dir.mkdir(path, 0o700) + id = SecureRandom.uuid + { "identity" => id, "state" => "0" }.each do |name, value| + File.open(File.join(path, name), File::WRONLY | File::CREAT | File::EXCL, 0o600) do |file| + file.write(value) + file.fsync + end + end + sync_directory(path) + open({ "path" => File.expand_path(path), "id" => id }) + rescue SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def self.open(pointer) + raise SessionProtectionUnavailable unless pointer.is_a?(Hash) + + family = new(pointer.fetch("path"), pointer.fetch("id")) + family.ready! + family.mark! if family.pending? + family + rescue KeyError, TypeError, SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def self.sync_directory(path) + File.open(path, File::RDONLY) { |directory| directory.fsync } + end + + def initialize(path, id) + raise SessionProtectionUnavailable unless path.is_a?(String) && File.absolute_path(path) == path && + id.is_a?(String) && id.match?(/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/) + + @path = File.expand_path(path).freeze + @id = id.dup.freeze + @latched = false + @mutex = Mutex.new + end + private_class_method :new + + def pointer + { "path" => @path, "id" => @id } + end + + def ready! + @mutex.synchronize do + directory = File.lstat(@path) + raise SessionProtectionUnavailable unless directory.directory? && directory.uid == Process.uid && + (directory.mode & 0o077).zero? + raise SessionProtectionUnavailable unless read_private("identity", 36) == @id + + state = read_private("state", 1) + raise SessionProtectionUnavailable unless ["0", "1"].include?(state) + raise SessionProtectionUnavailable if @latched && state != "1" + + @latched ||= state == "1" + end + self + rescue SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def protected? + ready! + @latched + end + + def mark! + ready! + @mutex.synchronize do + @latched = true + File.open(File.join(@path, "state"), File::WRONLY | File::NOFOLLOW) do |file| + file.write("1") + file.fsync + end + end + self + rescue SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def pending? + pending_except?(nil) + end + + def pending_except?(own) + count = 0 + Dir.each_child(@path) do |name| + count += 1 + raise SessionProtectionUnavailable if count > 10_000 + return true if name.start_with?("pending-") && File.join(@path, name) != own + end + false + rescue SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def begin_attempt + ready! + name = File.join(@path, "pending-#{SecureRandom.uuid}") + File.open(name, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |file| file.fsync } + self.class.sync_directory(@path) + name + rescue SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def attempt_ready!(name) + ready! + raise SessionProtectionUnavailable unless File.dirname(name) == @path && + File.basename(name).start_with?("pending-") + read_private(File.basename(name), 0) + self + rescue SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def finish_attempt(name) + attempt_ready!(name) + File.unlink(name) + self.class.sync_directory(@path) + rescue SystemCallError, IOError + raise SessionProtectionUnavailable + end + + def capture + SessionCapture.new([self, *SessionCapture.current_families]) + end + + def self.marked?(value) + pending = [value] + remaining = 10_000 + text_bytes = MAX_BODY + until pending.empty? + remaining -= 1 + raise SessionProtectionUnavailable if remaining.negative? + + item = pending.pop + next unless item.is_a?(Hash) + if item.key?("mirrored") && item["mirrored"] != true && item["mirrored"] != false + raise SessionProtectionUnavailable + end + return true if item["mirrored"] == true + + %w[result structuredContent].each { |key| pending << item[key] if item[key].is_a?(Hash) } + data = item["error"].is_a?(Hash) ? item["error"]["data"] : nil + pending << data if data.is_a?(Hash) + items = item["items"] + pending.concat(items) if items.is_a?(Array) + content = item["content"] + if content.is_a?(Array) + remaining -= content.length + content.each do |block| + next unless block.is_a?(Hash) && block["type"] == "text" && block["text"].is_a?(String) + + text_bytes -= block["text"].bytesize + raise SessionProtectionUnavailable if text_bytes.negative? + pending << JSON.parse(block["text"]) if block["text"].lstrip.start_with?("{") + end + end + raise SessionProtectionUnavailable if pending.length > remaining + end + false + rescue JSON::ParserError, JSON::NestingError + raise SessionProtectionUnavailable + end + + private + + def read_private(name, size) + File.open(File.join(@path, name), File::RDWR | File::NOFOLLOW) do |file| + stat = file.stat + raise SessionProtectionUnavailable unless stat.file? && stat.uid == Process.uid && + (stat.mode & 0o077).zero? && stat.size == size + file.read(size + 1) + end + end + end + + # Retain this object when scheduling work; call it again in the later callback. + class SessionCapture + def self.current + Thread.current[SessionProtection::CONTEXT] + end + + def self.current_families + current ? current.families : [] + end + + def initialize(families) + unless families.is_a?(Array) && !families.empty? && families.all? { |family| family.is_a?(SessionProtection) } + raise ArgumentError, "a capture requires contributing SessionProtection handles" + end + @families = families.uniq { |family| family.pointer }.freeze + end + + attr_reader :families + + def contribute(family) + self.class.new([*@families, family, *self.class.current_families]) + end + + def guard! + @families.each do |family| + raise AutomaticCaptureSuppressed if family.protected? || family.pending? + end + end + + def call + previous = self.class.current + retained = self.class.new([*@families, *self.class.current_families]) + retained.guard! + Thread.current[SessionProtection::CONTEXT] = retained + yield + ensure + Thread.current[SessionProtection::CONTEXT] = previous + end + end + end +end diff --git a/sdk/ruby/test/session_protection_http_test.rb b/sdk/ruby/test/session_protection_http_test.rb new file mode 100644 index 0000000000..bc2682b4fb --- /dev/null +++ b/sdk/ruby/test/session_protection_http_test.rb @@ -0,0 +1,257 @@ +# frozen_string_literal: true + +require "fileutils" +require "tmpdir" +require "timeout" +require_relative "test_helper" + +# One owned worker handles the sequential complete-response cases. +class ProtectionHTTPServer < FakeServer + def close + @server.close unless @server.closed? + raise "HTTP server did not stop" unless @thread.join(4) + @thread.value + end + + private + + def serve + loop do + socket = @server.accept + Timeout.timeout(3) { handle(socket) } + end + rescue IOError, Errno::EBADF + raise unless @server.closed? + end +end + +# Complete responses use FakeServer. This variant holds one chunked response so +# cancellation can prove that Net::HTTP closes the connection it owns. +class ProtectionChunkServer < FakeServer + attr_reader :chunk_sent, :peer_closed + + def initialize(interrupt: false) + @interrupt = interrupt + @chunk_sent = Queue.new + @peer_closed = Queue.new + @socket_lock = Mutex.new + @socket = nil + super() + end + + def close + @server.close unless @server.closed? + @socket_lock.synchronize { @socket&.close unless @socket&.closed? } + raise "chunk server did not stop" unless @thread.join(3) + @thread.value + end + + private + + def serve + socket = @server.accept + @socket_lock.synchronize { @socket = socket } + Timeout.timeout(3) do + method, path, = socket.gets.split + headers = {} + while (line = socket.gets) && line != "\r\n" + name, value = line.split(":", 2) + headers[name.downcase] = value.strip + end + body = socket.read(Integer(headers.fetch("content-length"))) + @requests << Request.new(method, path, headers, body) + socket.write("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n") + chunk = '{"result":{"mirrored":true,"private":"' + socket.write("#{chunk.bytesize.to_s(16)}\r\n#{chunk}\r\n") + socket.flush + @chunk_sent << true + if @interrupt + socket.close + else + @peer_closed << socket.read(1).nil? + end + end + rescue IOError, Errno::EBADF + raise unless @server.closed? + ensure + socket&.close unless socket&.closed? + end +end + +class SessionProtectionHTTPTest < Minitest::Test + Loom = ClickHouse::Loom + SOURCE_READ = "knowledge.source.mcp_read" + PRIVATE_VALUE = "synthetic-private-source-value" + + def setup + @server = ProtectionHTTPServer.new + @root = Dir.mktmpdir("loom-sdk-wire-") + @family = family("bound") + end + + def teardown + @server&.close + ensure + FileUtils.remove_entry(@root) if @root + end + + def family(name) + Loom::SessionProtection.create(File.join(@root, name)) + end + + def protected_client(bound = @family, **options) + defaults = { base_url: @server.base_url, org: "dev", namespace: "local", agent: "assistant", + retry_policy: { max_attempts: 1 }, rate_limit_max_wait: 0, + session_protection: bound, api_key: "synthetic-token", open_timeout: 2, read_timeout: 2 } + Loom::Client.new(**defaults, **options) + end + + def json_response(status, value, headers = {}) + @server.respond(status, JSON.generate(value), { "Content-Type" => "application/json" }.merge(headers)) + end + + def read_private(reader = protected_client) + json_response(200, { "result" => { "mirrored" => true, "value" => PRIVATE_VALUE } }) + answer = reader.call(SOURCE_READ, source_body) + assert_equal PRIVATE_VALUE, answer.fetch("result").fetch("value") + assert_wire(@server.requests.last, SOURCE_READ, "local", "synthetic-token") + end + + def assert_wire(request, op, namespace, token, bound: true) + assert_equal "POST", request.method + assert_equal "/v1/#{op}", request.path + assert_equal "Bearer #{token}", request.headers.fetch("authorization") + assert_equal "application/json", request.headers.fetch("content-type") + if bound + assert_equal "v1", request.headers.fetch("x-loom-session-protection") + else + refute request.headers.key?("x-loom-session-protection") + end + expected = (op == SOURCE_READ ? source_body : write_body).transform_keys(&:to_s) + expected.merge!("org" => "dev", "namespace" => namespace, "agent" => "assistant") + assert_equal expected, JSON.parse(request.body) + end + + def source_body + { name: "synthetic-source", resource_id: "synthetic-resource" } + end + + def write_body + { memory_key: "wire-key", value: "explicit-value" } + end + + def test_actual_source_read_reopens_and_suppresses_clean_retained_capture_on_other_clients + clean = family("clean") + retained = clean.capture + reader = protected_client + json_response(200, { "status" => "ok" }) + assert_equal "ok", reader.call_automatic(retained, "memory.set", write_body).fetch("status") + assert_wire(@server.requests.last, "memory.set", "local", "synthetic-token") + read_private(reader) + refute clean.protected? + refute clean.pending? + reopened = Loom::SessionProtection.open(@family.pointer) + assert reopened.protected? + refute @family.pending? + [reader.dup, protected_client(reopened, namespace: "other", api_key: "other-token")].each do |writer| + before = @server.requests.length + assert_raises(Loom::AutomaticCaptureSuppressed) do + writer.call_automatic(retained, "memory.set", write_body) + end + assert_equal before, @server.requests.length + end + json_response(200, { "status" => "ok" }) + assert_equal "ok", reader.call("memory.set", write_body).fetch("status") + assert_wire(@server.requests.last, "memory.set", "local", "synthetic-token") + json_response(200, { "status" => "ok" }) + ordinary = protected_client(nil, namespace: "ordinary", api_key: "ordinary-token") + assert_equal "ok", ordinary.call("memory.set", write_body).fetch("status") + assert_wire(@server.requests.last, "memory.set", "ordinary", "ordinary-token", bound: false) + end + + def test_actual_error_metadata_is_durable_before_typed_error_escapes + json_response(403, { "detail" => { "code" => "FORBIDDEN", "message" => "denied" }, + "error" => { "data" => { "mirrored" => true, "value" => PRIVATE_VALUE } } }) + error = assert_raises(Loom::Error) { protected_client.call(SOURCE_READ, source_body) } + assert_equal 403, error.status + assert Loom::SessionProtection.open(@family.pointer).protected? + refute @family.pending? + assert_wire(@server.requests.last, SOURCE_READ, "local", "synthetic-token") + end + + def test_actual_chunked_interruption_and_cancellation_keep_proof_and_close_connections + [true, false].each do |interrupt| + stream_family = family("stream-#{interrupt}") + server = ProtectionChunkServer.new(interrupt: interrupt) + reader = protected_client(stream_family, base_url: server.base_url) + worker = Thread.new do + begin + reader.call(SOURCE_READ, source_body) + rescue Loom::Error, Loom::SessionProtectionUnavailable => error + error + end + end + worker.report_on_exception = false + Timeout.timeout(3) { server.chunk_sent.pop } + unless interrupt + assert_nil worker.join(0.05), "incomplete chunked body unexpectedly completed" + worker.kill + end + assert worker.join(3), "request worker did not stop" + assert_kind_of StandardError, worker.value if interrupt + assert Timeout.timeout(3) { server.peer_closed.pop } unless interrupt + assert Loom::SessionProtection.open(stream_family.pointer).protected? + assert stream_family.pending? + assert_wire(server.requests.fetch(0), SOURCE_READ, "local", "synthetic-token") + assert_raises(Loom::AutomaticCaptureSuppressed) do + reader.call_automatic(family("stream-clean-#{interrupt}").capture, "memory.set", write_body) + end + assert_equal 1, server.requests.length + ensure + worker&.kill if worker&.alive? + worker&.join(3) + server&.close + end + end + + def test_actual_retry_and_pacing_recheck_protection_acquired_after_first_response + [429, 503].each do |status| + bound = family("wait-bound-#{status}") + clean = family("wait-clean-#{status}") + reader = protected_client(bound) + before = @server.requests.length + sleeps = [] + code = status == 429 ? "RATE_LIMITED" : "INTERNAL_ERROR" + json_response(status, { "detail" => { "code" => code, "message" => "wait" } }, "Retry-After" => "1") + writer = protected_client(bound, rate_limit_max_wait: 2, retry_policy: { max_attempts: 2 }, + sleeper: lambda { |delay| + sleeps << delay + read_private(reader) + }) + assert_raises(Loom::AutomaticCaptureSuppressed) do + writer.call_automatic(clean.capture, "memory.set", write_body) + end + assert_equal [1.0], sleeps + requests = @server.requests.drop(before) + assert_equal ["/v1/memory.set", "/v1/#{SOURCE_READ}"], requests.map(&:path) + assert_wire(requests.first, "memory.set", "local", "synthetic-token") + assert Loom::SessionProtection.open(bound.pointer).protected? + end + end + + def test_lost_or_changed_pointer_refuses_before_actual_http + [:lost, :changed].each do |mode| + bound = family(mode.to_s) + writer = protected_client(bound) + pointer = bound.pointer + if mode == :lost + File.unlink(File.join(pointer.fetch("path"), "state")) + else + File.write(File.join(pointer.fetch("path"), "identity"), "00000000-0000-0000-0000-000000000000") + end + assert_raises(Loom::SessionProtectionUnavailable) { Loom::SessionProtection.open(pointer) } + assert_raises(Loom::SessionProtectionUnavailable) { writer.call("memory.set", write_body) } + assert_empty @server.requests + end + end +end diff --git a/sdk/ruby/test/session_protection_test.rb b/sdk/ruby/test/session_protection_test.rb new file mode 100644 index 0000000000..2c176fceaa --- /dev/null +++ b/sdk/ruby/test/session_protection_test.rb @@ -0,0 +1,188 @@ +# frozen_string_literal: true + +require "fileutils" +require "minitest/autorun" +require "tmpdir" +require_relative "../lib/clickhouse/loom" + +class SessionProtectionTest < Minitest::Test + def setup + @root = Dir.mktmpdir + @family = Loom::SessionProtection.create(File.join(@root, "family")) + @sent = [] + end + + def teardown + FileUtils.remove_entry(@root) + end + + def client(family = @family, **options) + Loom::Client.new(base_url: "https://loom.invalid", org: "o", namespace: "n", agent: "a", + session_protection: family, retry_policy: { max_attempts: 1 }, **options) + end + + def response(status, body, media = "application/json") + klass = Net::HTTPResponse::CODE_TO_OBJ.fetch(status.to_s) + answer = klass.new("1.1", status.to_s, "response") + answer["Content-Type"] = media + answer.body = body + answer.instance_variable_set(:@read, true) + answer.define_singleton_method(:read_body) { |&block| block.call(body) } + answer + end + + def with_http(*answers, before: nil) + sent = @sent + fake = Object.new + fake.define_singleton_method(:request) do |request, &block| + before&.call + sent << request + answer = answers.shift + raise answer if answer.is_a?(Exception) + + block&.call(answer) + answer + end + Net::HTTP.stub(:start, ->(*_args, **_kwargs, &block) { block.call(fake) }) { yield } + end + + def test_declaration_exists_only_with_installed_observer_and_store + with_http(response(200, '{"found":false}'), response(200, '{"found":false}')) do + client.get("k") + client(nil).get("k") + end + assert_equal "v1", @sent[0]["X-Loom-Session-Protection"] + assert_nil @sent[1]["X-Loom-Session-Protection"] + refute @family.protected? + refute @family.pending? + end + + def test_error_metadata_latches_before_error_escapes_and_survives_reopen + with_http(response(403, '{"error":{"data":{"mirrored":true}}}')) do + assert_raises(Loom::Error) { client.call("knowledge.source.mcp_read", {}) } + end + assert @family.protected? + assert Loom::SessionProtection.open(@family.pointer).protected? + end + + def test_nested_text_envelope_and_typed_response_observation + body = JSON.generate({ "content" => [{ "type" => "text", "text" => '{"items":[{"mirrored":true}]}' }] }) + with_http(response(200, body)) { client.get("k") } + assert @family.protected? + end + + def test_retained_callback_refuses_new_client_and_other_namespace + capture = @family.capture + with_http(response(200, '{"mirrored":true}')) { client.get("k") } + assert_raises(Loom::AutomaticCaptureSuppressed) do + client(nil, namespace: "other").call_automatic(capture, "memory.set", { value: "private" }) + end + assert_equal 1, @sent.length + end + + def test_clean_capture_cannot_omit_the_bound_clients_protection_or_pending_response + [:protected, :pending].each do |state| + bound = Loom::SessionProtection.create(File.join(@root, state.to_s)) + state == :protected ? bound.mark! : bound.begin_attempt + Net::HTTP.stub(:start, ->(*_args, **_kwargs) { flunk "automatic dispatch opened a connection" }) do + assert_raises(Loom::AutomaticCaptureSuppressed) do + client(bound, namespace: "other").call_automatic(@family.capture, "memory.set", { value: "private" }) + end + end + assert_empty @sent + end + end + + def test_active_capture_observes_other_family_and_nested_callback_retains_it + other = Loom::SessionProtection.create(File.join(@root, "other")) + later = nil + with_http(response(200, '{"mirrored":true}')) do + @family.capture.call do + later = other.capture + client(other).get("k") + end + end + assert @family.protected? + assert other.protected? + assert_raises(Loom::AutomaticCaptureSuppressed) { later.call { flunk "write escaped" } } + assert_nil Loom::SessionCapture.current + end + + def test_callback_failure_restores_ambient_scope + assert_raises(RuntimeError) { @family.capture.call { raise "callback failed" } } + assert_nil Loom::SessionCapture.current + refute @family.protected? + end + + def test_read_error_and_malformed_metadata_latch_without_returning_private_body + ['{"mirrored":"false"}', '{"result":{"mirrored":null}}', 'private {'].each_with_index do |body, index| + family = Loom::SessionProtection.create(File.join(@root, "bad-#{index}")) + with_http(response(200, body)) do + error = assert_raises(Loom::SessionProtectionUnavailable) { client(family).get("k") } + refute_includes error.message, body + end + assert family.protected? + end + end + + def test_unsupported_stream_and_oversized_body_refuse + [["data: private\n\n", "text/event-stream"], ["x" * (Loom::SessionProtection::MAX_BODY + 1), "application/json"]].each_with_index do |(body, media), index| + family = Loom::SessionProtection.create(File.join(@root, "bounded-#{index}")) + with_http(response(200, body, media)) do + assert_raises(Loom::SessionProtectionUnavailable) { client(family).get("k") } + end + assert family.protected? + end + end + + def test_interrupted_body_keeps_pending_proof_and_latches + answer = response(200, "") + answer.define_singleton_method(:read_body) { |_block = nil| raise IOError, "interrupted" } + with_http(answer) { assert_raises(Loom::Error) { client.get("k") } } + assert @family.pending? + assert Loom::SessionProtection.open(@family.pointer).protected? + end + + def test_lost_state_and_interrupted_resume_never_create_clean_family + pointer = @family.pointer + @family.begin_attempt + assert Loom::SessionProtection.open(pointer).protected? + File.unlink(File.join(pointer["path"], "state")) + assert_raises(Loom::SessionProtectionUnavailable) { Loom::SessionProtection.open(pointer) } + assert_raises(Loom::SessionProtectionUnavailable) { client.get("k") } + assert_empty @sent + end + + def test_retry_barrier_runs_after_pacing_and_observes_error_status + sleeper = ->(_delay) { @family.mark! } + first = response(429, '{"detail":{"message":"wait"}}') + first["Retry-After"] = "0.1" + with_http(first, response(200, '{}')) do + assert_raises(Loom::AutomaticCaptureSuppressed) do + @family.capture.call { client(sleeper: sleeper).get("k") } + end + end + assert_equal 1, @sent.length + end + + def test_forged_protocol_header_refuses_before_post + assert_raises(Loom::SessionProtectionUnavailable) do + client.send(:post, "memory.get", "{}", { "X-Loom-Session-Protection" => "v1" }) + end + assert_empty @sent + end + + def test_cancellation_latches_and_keeps_pending_before_escape + answer = response(200, "") + answer.define_singleton_method(:read_body) { |_block = nil| raise Interrupt } + with_http(answer) { assert_raises(Interrupt) { client.get("k") } } + assert @family.protected? + assert @family.pending? + end + + def test_monotonic_local_latch_rejects_state_rollback + @family.mark! + File.write(File.join(@family.pointer["path"], "state"), "0") + assert_raises(Loom::SessionProtectionUnavailable) { @family.ready! } + end +end diff --git a/sdk/rust/README.md b/sdk/rust/README.md index 03f9a15cec..d77da28c59 100644 --- a/sdk/rust/README.md +++ b/sdk/rust/README.md @@ -266,3 +266,7 @@ A consuming application controls its own dependency lockfile. ## License Apache-2.0. See [LICENSE](LICENSE). + +## Session protection + +Bind a durable conversation handle before reading protected sources, and retain its capture for every automatic write. See [Session protection](SESSION_PROTECTION.md) for restore, task cancellation and response limits. diff --git a/sdk/rust/SESSION_PROTECTION.md b/sdk/rust/SESSION_PROTECTION.md new file mode 100644 index 0000000000..ae4382311d --- /dev/null +++ b/sdk/rust/SESSION_PROTECTION.md @@ -0,0 +1,41 @@ +# Session protection + +`SessionProtection` binds an application-owned durable authority to a logical conversation. Its clones share the authority independently of client credentials and identity. The built-in store requires a private POSIX directory. It contains an identity, a monotonic protection bit and pending request markers; it contains no bodies or credentials. Other filesystem platforms refuse readiness. + +```rust,no_run +use clickhouse_loom::{Client, SessionProtection}; +use serde_json::Value; + +# async fn example(directory: &std::path::Path, arguments: Value) -> Result<(), clickhouse_loom::Error> { +let family = SessionProtection::create(directory)?; +let pointer = family.pointer(); // Persist in the trusted conversation record. +let client = Client::builder("org", "namespace", "agent") + .session_protection(family.clone()) + .build()?; +let answer: Value = client.call("knowledge.source.mcp_read", &arguments).await?; +# Ok(()) +# } +``` + +On resume, reopen the stored pointer with `SessionProtection::open`. Missing or invalid state refuses. Never create a replacement family after restore failure. Any interrupted request still pending on reopen latches protection. Share handle clones among active clients rather than reopening the directory per request. The application must retain the pointer and its directory together and prevent trusted storage rollback or replacement. + +Retain a `SessionCapture` before scheduling work. It holds all contributing handles and checks them on every automatic attempt, including another client or namespace. Use `capture.contribute(&other_family)` for additional contributors. Nested captures retain their parent's contributors. Client clones and `with_retry` preserve the bound authority. + +```rust,no_run +# use clickhouse_loom::{Client, SessionProtection, Error}; +# use serde_json::{json, Value}; +# async fn example(family: SessionProtection, another_client: Client) -> Result<(), Error> { +let capture = family.capture(); +let result: Value = another_client.call_automatic( + &capture, "memory.set", &json!({"memory_key":"note", "value":"automatic"}) +).await?; +// Several operations can run inside capture.scope(async { ... }).await?. +# Ok(()) +# } +``` + +The capture scope follows its Tokio task across awaits. Spawned tasks and queued callbacks must receive a retained capture and enter its scope. Every automatic write must use a capture, including calls made through a newly constructed client. Explicit calls remain available and still observe protection metadata. + +`Client::call` owns the declaration, durable admission and response observer. It sends `x-loom-session-protection: v1` only with an installed authority. Each retry checks the retained capture immediately before `send`. Every HTTP status is observed before typed deserialization or API error construction. Protected JSON responses are bounded to 4 MiB; malformed envelopes and unsupported media refuse. Dropping an incomplete request future latches its opening authorities; a process interruption leaves durable pending proof. Cancellation cannot undo a request already sent. + +Protected streaming is unavailable. A stream response refuses without returning its body. Ordinary unbound calls send no declaration and preserve their existing behavior. Generic `call` supports explicit operations without requiring generated helpers. Real HTTP, source operations and task cancellation require hosted qualification before activation. diff --git a/sdk/rust/src/client.rs b/sdk/rust/src/client.rs index 551f714328..610d523623 100644 --- a/sdk/rust/src/client.rs +++ b/sdk/rust/src/client.rs @@ -18,6 +18,8 @@ use crate::{ SetRequest, SetResponse, }; use tokio::sync::Mutex; +use crate::session_protection::{Observation, MAX_BODY}; +use crate::{SessionCapture, SessionProtection}; const DEFAULT_URL: &str = "http://localhost:7777"; @@ -34,6 +36,7 @@ pub struct Client { pacing: bool, ratelimit_max_wait: Duration, rate_state: Arc>>, + session_protection: Option, } /// Explicit endpoint and token options override LOOM_BASE_URL and LOOM_API_KEY. @@ -45,6 +48,7 @@ pub struct ClientBuilder { retry: RetryPolicy, pacing: bool, ratelimit_max_wait: Duration, + session_protection: Option, } impl Client { @@ -61,6 +65,7 @@ impl Client { retry: RetryPolicy::default(), pacing: true, ratelimit_max_wait: Duration::from_secs(15), + session_protection: None, } } @@ -95,7 +100,8 @@ impl Client { }) } - async fn call( + /// Call an explicit operation; bound protection observes before typed decoding. + pub async fn call( &self, op: &str, request: &impl Serialize, @@ -171,21 +177,44 @@ impl Client { if let Some(authorization) = &self.authorization { request = request.header(AUTHORIZATION, authorization); } + let mut observation = Observation::begin(self.session_protection.as_ref())?; + if observation.installed() { + request = request.header("x-loom-session-protection", "v1"); + } sent += 1; log::debug!(target: "clickhouse_loom", "{op} attempt={attempt} sent={sent} rid={request_id}"); let received = async { - let response = request.send().await?; + observation.before_send()?; + let mut response = request.send().await + .map_err(|e| Error::Transport(e.without_url()))?; let status = response.status(); let headers = response.headers().clone(); - let bytes = response.bytes().await?; - Ok::<_, reqwest::Error>((status, headers, bytes)) + let media = headers.get("content-type").and_then(|v| v.to_str().ok()).unwrap_or(""); + observation.check_media(media, status.as_u16())?; + let bytes = if observation.installed() { + let mut bytes = Vec::new(); + while let Some(chunk) = response.chunk().await + .map_err(|e| Error::Transport(e.without_url()))? { + if chunk.len() > MAX_BODY.saturating_sub(bytes.len()) { + return Err(Error::Configuration("session protection response limit exceeded".into())); + } + bytes.extend_from_slice(&chunk); + } + bytes + } else { + response.bytes().await + .map_err(|e| Error::Transport(e.without_url()))?.to_vec() + }; + observation.observe(&bytes, media, status.as_u16())?; + Ok::<_, Error>((status, headers, bytes)) } .await; let (error, allowed, hint) = match received { - Err(error) => { + Err(Error::Transport(error)) => { let allowed = self.retry.retries_transport(&error, replayable); (Error::Transport(error.without_url()), allowed, None) } + Err(error) => return Err(error), Ok((status, headers, bytes)) => { self.record_rate_state(op, &headers).await; if status.is_success() { @@ -245,6 +274,16 @@ impl Client { } } + /// Run automatic work with all retained contributing sessions, even on another client. + pub async fn call_automatic( + &self, + capture: &SessionCapture, + op: &str, + request: &impl Serialize, + ) -> Result { + capture.scope(self.call(op, request)).await? + } + async fn record_rate_state(&self, op: &str, headers: &HeaderMap) { let number = |key| headers.get(key)?.to_str().ok()?.parse::().ok(); if let (Some(limit), Some(remaining), Some(reset)) = ( @@ -306,6 +345,12 @@ impl ClientBuilder { self } + /// Bind the application's durable conversation authority. Clones retain it. + pub fn session_protection(mut self, protection: SessionProtection) -> Self { + self.session_protection = Some(protection); + self + } + pub fn build(self) -> Result { self.retry.validate()?; for key in ["org", "namespace", "agent"] { @@ -362,6 +407,7 @@ impl ClientBuilder { pacing: self.pacing, ratelimit_max_wait: self.ratelimit_max_wait, rate_state: Arc::new(Mutex::new(HashMap::new())), + session_protection: self.session_protection, }) } } diff --git a/sdk/rust/src/lib.rs b/sdk/rust/src/lib.rs index e69043f438..2344776189 100644 --- a/sdk/rust/src/lib.rs +++ b/sdk/rust/src/lib.rs @@ -105,6 +105,7 @@ mod client; mod error; mod models; mod retry; +mod session_protection; pub use client::{Client, ClientBuilder}; pub use error::{ApiError, Error}; @@ -112,3 +113,4 @@ pub use models::{ DeleteResponse, GetResponse, SearchHit, SearchRequest, SearchResponse, SetRequest, SetResponse, }; pub use retry::{RetryPolicy, RetryTimeouts}; +pub use session_protection::{SessionCapture, SessionProtection, SessionProtectionPointer}; diff --git a/sdk/rust/src/session_protection.rs b/sdk/rust/src/session_protection.rs new file mode 100644 index 0000000000..63e85d659e --- /dev/null +++ b/sdk/rust/src/session_protection.rs @@ -0,0 +1,528 @@ +//! Durable, content-free conversation protection and retained automatic captures. + +use std::{ + fs::{self, File, OpenOptions}, + io::{Read, Write}, + path::{Path, PathBuf}, + sync::{atomic::{AtomicBool, Ordering}, Arc}, +}; + +use serde_json::Value; +use crate::Error; + +pub(crate) const MAX_BODY: usize = 4 * 1024 * 1024; + +fn unavailable() -> Error { + Error::Configuration("session protection state could not be confirmed".into()) +} + +fn io(result: std::io::Result) -> Result { + result.map_err(|_| unavailable()) +} + +/// Keep both fields in the application's trusted conversation record. Never recreate +/// a family when restoring this pointer fails. +#[derive(Clone)] +pub struct SessionProtectionPointer { + pub path: PathBuf, + pub id: String, +} + +struct Authority { + pointer: SessionProtectionPointer, + latched: AtomicBool, +} + +/// Clones share an authority independently of client identity, namespace and token. +#[derive(Clone)] +pub struct SessionProtection(Arc); + +impl SessionProtection { + pub fn create(path: impl AsRef) -> Result { + let path = path.as_ref(); + let mut directory = fs::DirBuilder::new(); + #[cfg(unix)] + { + use std::os::unix::fs::DirBuilderExt; + directory.mode(0o700); + } + io(directory.create(path))?; + let id = uuid::Uuid::new_v4().to_string(); + for (name, data) in [("identity", id.as_bytes()), ("state", b"0".as_slice())] { + let mut file = create_private(&path.join(name))?; + io(file.write_all(data))?; + io(file.sync_all())?; + } + sync_directory(path)?; + Self::open(SessionProtectionPointer { path: io(fs::canonicalize(path))?, id }) + } + + pub fn open(pointer: SessionProtectionPointer) -> Result { + if uuid::Uuid::parse_str(&pointer.id).is_err() || !pointer.path.is_absolute() { + return Err(unavailable()); + } + let family = Self(Arc::new(Authority { pointer, latched: AtomicBool::new(false) })); + family.require_ready()?; + // An interrupted request cannot acknowledge that its response was public. + if family.pending_except(None)? { + family.mark()?; + } + Ok(family) + } + + pub fn pointer(&self) -> SessionProtectionPointer { + self.0.pointer.clone() + } + + pub fn require_ready(&self) -> Result<(), Error> { + let directory = io(fs::symlink_metadata(&self.0.pointer.path))?; + if !directory.is_dir() || directory.file_type().is_symlink() || !private(&directory) { + return Err(unavailable()); + } + if self.read("identity", 36)? != self.0.pointer.id.as_bytes() { + return Err(unavailable()); + } + match self.read("state", 1)?.as_slice() { + b"1" => { self.0.latched.store(true, Ordering::SeqCst); } + b"0" if !self.0.latched.load(Ordering::SeqCst) => {} + _ => return Err(unavailable()), + } + Ok(()) + } + + pub fn protected(&self) -> Result { + self.require_ready()?; + Ok(self.0.latched.load(Ordering::SeqCst)) + } + + pub fn mark(&self) -> Result<(), Error> { + self.require_ready()?; + self.0.latched.store(true, Ordering::SeqCst); + let path = self.0.pointer.path.join("state"); + let mut file = io(OpenOptions::new().write(true).open(path))?; + io(file.write_all(b"1"))?; + io(file.sync_all()) + } + + pub fn capture(&self) -> SessionCapture { + let mut capture = SessionCapture::current().unwrap_or_else(SessionCapture::empty); + capture.add(self.clone()); + capture + } + + fn read(&self, name: &str, size: u64) -> Result, Error> { + let path = self.0.pointer.path.join(name); + let stat = io(fs::symlink_metadata(&path))?; + if !stat.is_file() || stat.file_type().is_symlink() || !private(&stat) || stat.len() != size { + return Err(unavailable()); + } + let file = io(OpenOptions::new().read(true).write(true).open(path))?; + let mut bytes = Vec::new(); + io(file.take(size + 1).read_to_end(&mut bytes))?; + if bytes.len() as u64 != size { return Err(unavailable()); } + Ok(bytes) + } + + fn pending_except(&self, own: Option<&Path>) -> Result { + for (count, item) in io(fs::read_dir(&self.0.pointer.path))?.enumerate() { + if count >= 10_000 { return Err(unavailable()); } + let item = io(item)?; + if item.file_name().to_string_lossy().starts_with("pending-") + && own != Some(item.path().as_path()) { + return Ok(true); + } + } + Ok(false) + } +} + +fn create_private(path: &Path) -> Result { + let mut options = OpenOptions::new(); + options.write(true).create_new(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + io(options.open(path)) +} + +fn private(stat: &fs::Metadata) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + stat.permissions().mode() & 0o077 == 0 + } + #[cfg(not(unix))] + { let _ = stat; false } +} + +fn sync_directory(path: &Path) -> Result<(), Error> { + io(io(File::open(path))?.sync_all()) +} + +tokio::task_local! { + static CAPTURE: SessionCapture; +} + +/// Retain the capture for deferred work. `scope` carries it across awaits and into +/// calls made through any client in that task. Spawned tasks must receive a clone. +#[derive(Clone)] +pub struct SessionCapture { + families: Vec, +} + +impl SessionCapture { + fn empty() -> Self { + Self { families: Vec::new() } + } + + pub fn contribute(mut self, family: &SessionProtection) -> Self { + if let Some(parent) = Self::current() { + for contributor in parent.families { self.add(contributor); } + } + self.add(family.clone()); + self + } + + fn add(&mut self, family: SessionProtection) { + if !self.families.iter().any(|f| f.0.pointer.path == family.0.pointer.path + && f.0.pointer.id == family.0.pointer.id) { + self.families.push(family); + } + } + + pub(crate) fn current() -> Option { + CAPTURE.try_with(Clone::clone).ok() + } + + pub async fn scope(&self, work: F) -> Result { + let mut retained = self.clone(); + if let Some(parent) = Self::current() { + for family in parent.families { retained.add(family); } + } + retained.guard(&[])?; + Ok(CAPTURE.scope(retained, work).await) + } + + fn guard(&self, attempts: &[(SessionProtection, PathBuf)]) -> Result<(), Error> { + for family in &self.families { + let own = attempts.iter().find(|(f, _)| f.0.pointer.path == family.0.pointer.path && f.0.pointer.id == family.0.pointer.id) + .map(|(_, path)| path.as_path()); + if family.protected()? || family.pending_except(own)? { + return Err(Error::Input("automatic capture is suppressed for this session".into())); + } + } + Ok(()) + } +} + +/// Dropping an incomplete attempt (including cancellation) latches every opening +/// family. A crash leaves pending markers for the next trusted reopen. +pub(crate) struct Observation { + families: Vec, + automatic: Option, + attempts: Vec<(SessionProtection, PathBuf)>, + complete: bool, +} + +impl Observation { + pub(crate) fn begin(bound: Option<&SessionProtection>) -> Result { + let automatic = SessionCapture::current(); + let mut retained = automatic.clone().unwrap_or_else(SessionCapture::empty); + if let Some(bound) = bound { retained.add(bound.clone()); } + let automatic = automatic.map(|_| retained.clone()); + let mut observation = Self { families: retained.families, automatic, attempts: vec![], complete: false }; + if let Some(capture) = &observation.automatic { capture.guard(&[])?; } + for family in &observation.families { + family.require_ready()?; + let path = family.0.pointer.path.join(format!("pending-{}", uuid::Uuid::new_v4())); + let file = create_private(&path)?; + observation.attempts.push((family.clone(), path)); + io(file.sync_all())?; + sync_directory(&family.0.pointer.path)?; + } + observation.before_send()?; + Ok(observation) + } + + pub(crate) fn installed(&self) -> bool { !self.families.is_empty() } + + pub(crate) fn before_send(&self) -> Result<(), Error> { + for family in &self.families { family.require_ready()?; } + for (family, path) in &self.attempts { + let name = path.file_name().and_then(|v| v.to_str()).ok_or_else(unavailable)?; + family.read(name, 0)?; + } + if let Some(capture) = &self.automatic { capture.guard(&self.attempts)?; } + Ok(()) + } + + pub(crate) fn check_media(&self, media: &str, status: u16) -> Result<(), Error> { + if !self.installed() { return Ok(()); } + let media = media.split(';').next().unwrap_or("").trim().to_ascii_lowercase(); + if media != "application/json" && !media.ends_with("+json") && ![204, 304].contains(&status) { + return Err(unavailable()); + } + Ok(()) + } + + pub(crate) fn observe(&mut self, bytes: &[u8], media: &str, status: u16) -> Result<(), Error> { + if !self.installed() { self.complete = true; return Ok(()); } + if bytes.len() > MAX_BODY { return Err(unavailable()); } + self.check_media(media, status)?; + let value = if bytes.is_empty() && [204, 304].contains(&status) { + serde_json::json!({}) + } else { serde_json::from_slice::(bytes).map_err(|_| unavailable())? }; + if !value.is_object() { return Err(unavailable()); } + let protected = marked(&value)?; + for family in &self.families { + family.require_ready()?; + if protected { family.mark()?; } + } + for (family, path) in &self.attempts { + io(fs::remove_file(path))?; + sync_directory(&family.0.pointer.path)?; + } + self.complete = true; + Ok(()) + } +} + +impl Drop for Observation { + fn drop(&mut self) { + if !self.complete { + for family in &self.families { + // Pending markers preserve refusal if storage cannot acknowledge the latch. + let _ = family.mark(); + } + } + } +} + +fn marked(value: &Value) -> Result { + let mut pending = vec![value.clone()]; + let mut remaining = 10_000usize; + let mut text_bytes = MAX_BODY; + while let Some(value) = pending.pop() { + remaining = remaining.checked_sub(1).ok_or_else(unavailable)?; + let Some(item) = value.as_object() else { continue; }; + if let Some(flag) = item.get("mirrored") { + match flag.as_bool() { Some(true) => return Ok(true), Some(false) => {}, None => return Err(unavailable()) } + } + for key in ["result", "structuredContent"] { + if let Some(value) = item.get(key).filter(|v| v.is_object()) { pending.push(value.clone()); } + } + if let Some(data) = item.get("error").and_then(|v| v.get("data")).filter(|v| v.is_object()) { + pending.push(data.clone()); + } + if let Some(items) = item.get("items").and_then(Value::as_array) { + if items.len() > remaining.saturating_sub(pending.len()) { return Err(unavailable()); } + pending.extend(items.iter().cloned()); + } + if let Some(content) = item.get("content").and_then(Value::as_array) { + remaining = remaining.checked_sub(content.len()).ok_or_else(unavailable)?; + for block in content { + if block.get("type").and_then(Value::as_str) != Some("text") { continue; } + if let Some(text) = block.get("text").and_then(Value::as_str) { + text_bytes = text_bytes.checked_sub(text.len()).ok_or_else(unavailable)?; + if text.trim_start().starts_with('{') { + pending.push(serde_json::from_str(text).map_err(|_| unavailable())?); + } + } + } + } + if pending.len() > remaining { return Err(unavailable()); } + } + Ok(false) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + struct Store(PathBuf); + impl Store { + fn family() -> (Self, SessionProtection) { + let path = std::env::temp_dir().join(format!("loom-protection-{}", uuid::Uuid::new_v4())); + let family = SessionProtection::create(&path).unwrap(); + (Self(path), family) + } + } + impl Drop for Store { + fn drop(&mut self) { fs::remove_dir_all(&self.0).unwrap(); } + } + + #[test] + fn durable_latch_and_pending_resume_refuse_missing_or_rolled_back_state() { + let (_store, family) = Store::family(); + assert!(!family.protected().unwrap()); + let pending = Observation::begin(Some(&family)).unwrap(); + let restored = SessionProtection::open(family.pointer()).unwrap(); + assert!(restored.protected().unwrap()); + drop(pending); + io(fs::write(family.0.pointer.path.join("state"), b"0")).unwrap(); + assert!(family.require_ready().is_err()); + fs::remove_file(family.0.pointer.path.join("state")).unwrap(); + assert!(SessionProtection::open(family.pointer()).is_err()); + } + + #[test] + fn explicit_error_metadata_latches_before_typed_decoding() { + let (_store, family) = Store::family(); + let mut observation = Observation::begin(Some(&family)).unwrap(); + observation.observe(br#"{"error":{"data":{"items":[{"mirrored":true}]}}}"#, + "application/json", 403).unwrap(); + assert!(family.protected().unwrap()); + assert!(!family.pending_except(None).unwrap()); + assert!(SessionProtection::open(family.pointer()).unwrap().protected().unwrap()); + } + + #[test] + fn malformed_envelopes_streams_and_body_limits_latch_without_payload_errors() { + for (bytes, media) in [ + (br#"{"mirrored":"false"}"#.to_vec(), "application/json"), + (br#"{"content":[{"type":"text","text":"{private"}]}"#.to_vec(), "application/json"), + (b"private".to_vec(), "text/event-stream"), + (vec![b'x'; MAX_BODY + 1], "application/json"), + ] { + let (_store, family) = Store::family(); + let mut observation = Observation::begin(Some(&family)).unwrap(); + let error = observation.observe(&bytes, media, 500).unwrap_err(); + assert!(!error.to_string().contains("private")); + drop(observation); + assert!(family.protected().unwrap()); + } + } + + #[test] + fn clean_observation_finishes_pending_and_empty_statuses_are_valid() { + let (_store, family) = Store::family(); + for (bytes, media, status) in [(b"{}".as_slice(), "application/json; charset=utf-8", 500), + (b"".as_slice(), "", 204)] { + let mut observation = Observation::begin(Some(&family)).unwrap(); + assert!(observation.installed()); + observation.observe(bytes, media, status).unwrap(); + assert!(!family.pending_except(None).unwrap()); + assert!(!family.protected().unwrap()); + } + } + + #[test] + fn incomplete_attempt_drop_marks_every_opening_family() { + let (_store, family) = Store::family(); + drop(Observation::begin(Some(&family)).unwrap()); + assert!(family.protected().unwrap()); + assert!(family.pending_except(None).unwrap()); + } + + #[tokio::test] + async fn automatic_capture_carries_into_new_clients_and_clone_shared_policy() { + let (_store, family) = Store::family(); + let client = crate::Client::builder("o", "n", "a").session_protection(family.clone()).build().unwrap(); + let cloned = client.with_retry(crate::RetryPolicy::default()).unwrap(); + let capture = family.capture(); + family.mark().unwrap(); + let other = crate::Client::builder("other", "other", "other").build().unwrap(); + assert!(other.call_automatic::(&capture, "memory.set", &serde_json::json!({"value":"private"})).await.is_err()); + assert!(cloned.call_automatic::(&capture, "memory.set", &serde_json::json!({})).await.is_err()); + assert!(SessionCapture::current().is_none()); + } + + #[tokio::test] + async fn clean_capture_cannot_omit_a_bound_familys_protection_or_pending_response() { + for pending in [false, true] { + let (_clean_store, clean) = Store::family(); + let (_bound_store, bound) = Store::family(); + let opening = if pending { + Some(Observation::begin(Some(&bound)).unwrap()) + } else { + bound.mark().unwrap(); + None + }; + let capture = clean.capture(); + let result = capture.scope(async { Observation::begin(Some(&bound)) }).await.unwrap(); + assert!(matches!(result, Err(Error::Input(message)) if message.contains("automatic capture is suppressed"))); + let client = crate::Client::builder("o", "n", "a") + .api_key("synthetic-token").session_protection(bound.clone()).build().unwrap(); + let cloned = client.with_retry(crate::RetryPolicy::default()).unwrap(); + for target in [&client, &cloned] { + let (_contributor_store, contributor) = Store::family(); + let capture = contributor.capture(); + let result = target.call_automatic::( + &capture, "memory.set", &serde_json::json!({"namespace":"other", "value":"private"}) + ).await; + assert!(matches!(result, Err(Error::Input(message)) if message.contains("automatic capture is suppressed"))); + } + drop(opening); + } + } + + #[tokio::test] + async fn response_retains_contributors_and_final_attempt_barrier_rechecks() { + let (_first_store, first) = Store::family(); + let (_second_store, second) = Store::family(); + let capture = first.capture(); + let retained = capture.scope(async { + let retained = second.capture(); + let mut observation = Observation::begin(Some(&second)).unwrap(); + observation.observe(br#"{"structuredContent":{"mirrored":true}}"#, "application/json", 200).unwrap(); + retained + }).await.unwrap(); + assert!(first.protected().unwrap()); + assert!(second.protected().unwrap()); + assert!(retained.scope(async { panic!("automatic write escaped"); }).await.is_err()); + assert!(SessionCapture::current().is_none()); + + let (_store, clean) = Store::family(); + let capture = clean.capture(); + capture.scope(async { + let first_attempt = Observation::begin(Some(&clean)).unwrap(); + clean.mark().unwrap(); + assert!(first_attempt.before_send().is_err()); + drop(first_attempt); + assert!(Observation::begin(Some(&clean)).is_err()); + }).await.unwrap(); + } + + #[tokio::test] + async fn cancelled_scope_keeps_durable_pending_and_restores_context() { + let (_store, family) = Store::family(); + let capture = family.capture(); + let (admitted, ready) = tokio::sync::oneshot::channel(); + let task = tokio::spawn({ + let family = family.clone(); + async move { + capture.scope(async { + let _observation = Observation::begin(Some(&family)).unwrap(); + admitted.send(()).unwrap(); + std::future::pending::<()>().await; + }).await + } + }); + tokio::time::timeout(std::time::Duration::from_secs(5), ready).await.unwrap().unwrap(); + assert!(family.pending_except(None).unwrap()); + task.abort(); + assert!(task.await.unwrap_err().is_cancelled()); + assert!(family.protected().unwrap()); + assert!(SessionProtection::open(family.pointer()).unwrap().protected().unwrap()); + assert!(SessionCapture::current().is_none()); + } + + #[test] + fn missing_pending_proof_refuses_at_final_boundary() { + let (_store, family) = Store::family(); + let observation = Observation::begin(Some(&family)).unwrap(); + fs::remove_file(&observation.attempts[0].1).unwrap(); + assert!(observation.before_send().is_err()); + drop(observation); + assert!(family.protected().unwrap()); + } + + #[test] + fn nested_text_and_budgeted_envelopes_follow_wire_contract() { + assert!(marked(&serde_json::json!({"content":[{"type":"text","text":"{\"result\":{\"mirrored\":true}}"}]})).unwrap()); + assert!(marked(&serde_json::json!({"items": vec![serde_json::json!({}); 10_001]})).is_err()); + assert!(!marked(&serde_json::json!({"value":"mirrored: true", "mirrored":false})).unwrap()); + } +} diff --git a/sdk/rust/tests/client.rs b/sdk/rust/tests/client.rs index a75f172320..87330c3695 100644 --- a/sdk/rust/tests/client.rs +++ b/sdk/rust/tests/client.rs @@ -22,6 +22,9 @@ const VERSION: u64 = 1_790_000_000_000_000_123; #[path = "network_cases/mod.rs"] mod network; +#[path = "network_cases/session_protection_http.rs"] +mod protection_http; + struct Request { line: String, headers: HashMap, diff --git a/sdk/rust/tests/network_cases/session_protection_http.rs b/sdk/rust/tests/network_cases/session_protection_http.rs new file mode 100644 index 0000000000..5094e09b80 --- /dev/null +++ b/sdk/rust/tests/network_cases/session_protection_http.rs @@ -0,0 +1,497 @@ +//! SDK wire qualification against owned HTTP fixtures, without a Loom backend. + +#![cfg(unix)] + +use super::{read_request, response, Request, Server}; +use clickhouse_loom::{Client, Error, RetryPolicy, SessionProtection}; +use serde_json::{json, Value}; +use std::{ + fs, + io::{Read, Write}, + net::{Shutdown, TcpListener, TcpStream}, + path::PathBuf, + sync::{ + atomic::{AtomicBool, Ordering}, + Arc, Mutex as StdMutex, + }, + thread::{self, JoinHandle}, + time::{Duration, Instant}, +}; +use tokio::sync::oneshot; + +const SOURCE_READ: &str = "knowledge.source.mcp_read"; +const PRIVATE_VALUE: &str = "synthetic-private-source-value"; + +struct Roots(PathBuf); + +impl Roots { + fn new() -> Self { + let path = std::env::temp_dir().join(format!("loom-sdk-wire-{}", uuid::Uuid::new_v4())); + fs::create_dir(&path).unwrap(); + Self(path) + } + + fn family(&self, name: &str) -> SessionProtection { + SessionProtection::create(self.0.join(name)).unwrap() + } +} + +impl Drop for Roots { + fn drop(&mut self) { + fs::remove_dir_all(&self.0).unwrap(); + } +} + +fn client(url: &str, family: Option<&SessionProtection>, namespace: &str, token: &str) -> Client { + let mut builder = Client::builder("org", namespace, "bot") + .base_url(url) + .api_key(token) + .timeout(Duration::from_secs(3)) + .pacing(false) + .retry(RetryPolicy { + max_attempts: 1, + ..RetryPolicy::default() + }); + if let Some(family) = family { + builder = builder.session_protection(family.clone()); + } + builder.build().unwrap() +} + +fn source_body() -> Value { + json!({"name":"synthetic-source", "resource_id":"synthetic-resource"}) +} + +fn write_body() -> Value { + json!({"memory_key":"wire-key", "value":"explicit-value"}) +} + +fn private_response() -> String { + response( + 200, + json!({"result":{"mirrored":true,"value":PRIVATE_VALUE}}), + "Content-Type: application/json\r\n", + ) +} + +fn assert_wire(request: &Request, op: &str, namespace: &str, token: &str, bound: bool) { + assert_eq!(request.line, format!("POST /v1/{op} HTTP/1.1")); + assert_eq!(request.headers["authorization"], format!("Bearer {token}")); + assert_eq!(request.headers["content-type"], "application/json"); + if bound { + assert_eq!(request.headers["x-loom-session-protection"], "v1"); + } else { + assert!(!request.headers.contains_key("x-loom-session-protection")); + } + let mut expected = if op == SOURCE_READ { + source_body() + } else { + write_body() + }; + expected["org"] = json!("org"); + expected["namespace"] = json!(namespace); + expected["agent"] = json!("bot"); + assert_eq!(request.body, expected); +} + +fn suppressed(error: Error) { + assert!( + matches!(error, Error::Input(ref message) + if message == "automatic capture is suppressed for this session"), + "{error:?}" + ); +} + +async fn no_request(server: &Server) { + assert!(matches!( + server.requests.lock().await.try_recv(), + Err(tokio::sync::mpsc::error::TryRecvError::Empty) + | Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) + )); +} + +#[tokio::test] +async fn source_read_reopens_proof_and_blocks_clean_capture_on_other_tokens_and_clones() { + let roots = Roots::new(); + let bound = roots.family("bound"); + let clean = roots.family("clean"); + let capture = clean.capture(); + let server = Server::new(vec![ + response( + 200, + json!({"status":"ok"}), + "Content-Type: application/json\r\n", + ), + private_response(), + response( + 200, + json!({"status":"ok"}), + "Content-Type: application/json\r\n", + ), + response( + 200, + json!({"status":"ok"}), + "Content-Type: application/json\r\n", + ), + ]); + let reader = client(&server.url, Some(&bound), "ns", "synthetic-token"); + let answer: Value = reader + .call_automatic(&capture, "memory.set", &write_body()) + .await + .unwrap(); + assert_eq!(answer["status"], "ok"); + assert_wire( + &server.request().await, + "memory.set", + "ns", + "synthetic-token", + true, + ); + let answer: Value = reader.call(SOURCE_READ, &source_body()).await.unwrap(); + assert_eq!(answer["result"]["value"], PRIVATE_VALUE); + assert!(!clean.protected().unwrap()); + assert!(!pending(&clean)); + assert_wire( + &server.request().await, + SOURCE_READ, + "ns", + "synthetic-token", + true, + ); + let reopened = SessionProtection::open(bound.pointer()).unwrap(); + assert!(reopened.protected().unwrap()); + assert!(!pending(&bound)); + for writer in [ + reader.clone(), + reader.with_retry(RetryPolicy::default()).unwrap(), + client(&server.url, Some(&reopened), "other", "other-token"), + ] { + suppressed( + writer + .call_automatic::(&capture, "memory.set", &write_body()) + .await + .unwrap_err(), + ); + no_request(&server).await; + } + let answer: Value = reader.call("memory.set", &write_body()).await.unwrap(); + assert_eq!(answer["status"], "ok"); + assert_wire( + &server.request().await, + "memory.set", + "ns", + "synthetic-token", + true, + ); + let ordinary = client(&server.url, None, "ordinary", "ordinary-token"); + let answer: Value = ordinary.call("memory.set", &write_body()).await.unwrap(); + assert_eq!(answer["status"], "ok"); + assert_wire( + &server.request().await, + "memory.set", + "ordinary", + "ordinary-token", + false, + ); +} + +#[tokio::test] +async fn error_metadata_is_durable_before_api_error_and_typed_decode_error() { + for status in [403, 200] { + let roots = Roots::new(); + let family = roots.family("bound"); + let server = Server::new(vec![response( + status, + json!({"detail":{"code":"FORBIDDEN","message":"denied"}, + "error":{"data":{"mirrored":true,"value":PRIVATE_VALUE}}}), + "Content-Type: application/json\r\n", + )]); + let reader = client(&server.url, Some(&family), "ns", "synthetic-token"); + let error = reader + .call::(SOURCE_READ, &source_body()) + .await + .unwrap_err(); + if status == 403 { + assert!(matches!(error, Error::Api(ref api) if api.status == 403)); + } else { + assert!(matches!(error, Error::Protocol { status: 200, .. })); + } + assert!(SessionProtection::open(family.pointer()) + .unwrap() + .protected() + .unwrap()); + assert!(!pending(&family)); + assert_wire( + &server.request().await, + SOURCE_READ, + "ns", + "synthetic-token", + true, + ); + } +} + +fn pending(family: &SessionProtection) -> bool { + fs::read_dir(family.pointer().path).unwrap().any(|entry| { + entry + .unwrap() + .file_name() + .to_string_lossy() + .starts_with("pending-") + }) +} + +// Parsing is shared with the normal network fixture. This worker owns one socket +// and reports EOF after cancellation, so dropping the test cannot strand it. +struct ChunkServer { + url: String, + started: Option>, + peer_closed: Option>, + stop: Arc, + socket: Arc>>, + worker: Option>, +} + +impl ChunkServer { + fn new(interrupt: bool) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + listener.set_nonblocking(true).unwrap(); + let stop = Arc::new(AtomicBool::new(false)); + let stopped = stop.clone(); + let socket = Arc::new(StdMutex::new(None)); + let active = socket.clone(); + let (sent, started) = oneshot::channel(); + let (closed, peer_closed) = oneshot::channel(); + let worker = thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(5); + let mut stream = loop { + if stopped.load(Ordering::Relaxed) || Instant::now() >= deadline { + return; + } + match listener.accept() { + Ok((stream, _)) => break stream, + Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => { + thread::park_timeout(Duration::from_millis(5)); + } + Err(error) => panic!("accept: {error}"), + } + }; + stream.set_nonblocking(false).unwrap(); + stream + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + stream + .set_write_timeout(Some(Duration::from_secs(2))) + .unwrap(); + *active.lock().unwrap() = Some(stream.try_clone().unwrap()); + let request = read_request(&mut stream); + let chunk = b"{\"result\":{\"mirrored\":true,\"value\":\""; + write!(stream, "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n{:x}\r\n", chunk.len()).unwrap(); + stream.write_all(chunk).unwrap(); + stream.write_all(b"\r\n").unwrap(); + stream.flush().unwrap(); + let _ = sent.send(request); + if interrupt { + stream.shutdown(Shutdown::Both).unwrap(); + } else { + let mut byte = [0]; + let eof = matches!(stream.read(&mut byte), Ok(0)); + let _ = closed.send(eof); + } + active.lock().unwrap().take(); + }); + Self { + url, + started: Some(started), + peer_closed: Some(peer_closed), + stop, + socket, + worker: Some(worker), + } + } + + async fn started(&mut self) -> Request { + tokio::time::timeout(Duration::from_secs(5), self.started.take().unwrap()) + .await + .unwrap() + .unwrap() + } + + async fn closed(&mut self) -> bool { + tokio::time::timeout(Duration::from_secs(3), self.peer_closed.take().unwrap()) + .await + .unwrap() + .unwrap() + } +} + +impl Drop for ChunkServer { + fn drop(&mut self) { + self.stop.store(true, Ordering::Relaxed); + if let Some(socket) = self.socket.lock().unwrap().as_ref() { + let _ = socket.shutdown(Shutdown::Both); + } + if let Some(worker) = self.worker.take() { + worker.thread().unpark(); + worker.join().unwrap(); + } + } +} + +#[tokio::test] +async fn chunked_interruption_and_future_cancellation_keep_proof_and_close_the_owned_socket() { + for interrupt in [true, false] { + let roots = Roots::new(); + let family = roots.family("bound"); + let mut server = ChunkServer::new(interrupt); + let reader = client(&server.url, Some(&family), "ns", "synthetic-token"); + let input = source_body(); + let mut work = Box::pin(reader.call::(SOURCE_READ, &input)); + if interrupt { + let (request, result) = tokio::join!( + server.started(), + tokio::time::timeout(Duration::from_secs(4), &mut work), + ); + assert_wire(&request, SOURCE_READ, "ns", "synthetic-token", true); + assert!(matches!(result.unwrap(), Err(Error::Transport(_)))); + } else { + let request = tokio::select! { + request = server.started() => request, + result = &mut work => panic!("incomplete response finished: {result:?}"), + }; + assert_wire(&request, SOURCE_READ, "ns", "synthetic-token", true); + assert!(tokio::time::timeout(Duration::from_millis(50), &mut work) + .await + .is_err()); + drop(work); + assert!(server.closed().await); + } + assert!(pending(&family)); + assert!(SessionProtection::open(family.pointer()) + .unwrap() + .protected() + .unwrap()); + suppressed( + reader + .call_automatic::( + &roots.family("clean").capture(), + "memory.set", + &write_body(), + ) + .await + .unwrap_err(), + ); + } +} + +#[tokio::test] +async fn retry_and_pacing_recheck_protection_acquired_after_a_completed_first_attempt() { + for status in [429, 503] { + wait_barrier(status).await; + } +} + +async fn wait_barrier(status: u16) { + let roots = Roots::new(); + let bound = roots.family("bound"); + let clean = roots.family("clean"); + let capture = clean.capture(); + let server = Server::new(vec![response( + status, + json!({"detail":{"code":if status == 429 { "RATE_LIMITED" } else { "INTERNAL_ERROR" },"message":"wait"}}), + "Content-Type: application/json\r\nRetry-After: 5\r\n", + )]); + let writer = Client::builder("org", "ns", "bot") + .base_url(&server.url) + .api_key("synthetic-token") + .session_protection(bound.clone()) + .timeout(Duration::from_secs(3)) + .ratelimit_max_wait(Duration::from_secs(5)) + .retry(RetryPolicy { + max_attempts: 2, + backoff: Duration::from_secs(5), + backoff_max: Duration::from_secs(5), + backoff_jitter: 0.0, + statuses: [503].into_iter().collect(), + respect_retry_after: true, + max_retry_after: Duration::from_secs(5), + ..RetryPolicy::default() + }) + .build() + .unwrap(); + let input = write_body(); + let mut work = Box::pin(writer.call_automatic::(&capture, "memory.set", &input)); + let request = tokio::select! { + request = server.request() => request, + result = &mut work => panic!("first attempt finished without waiting: {result:?}"), + }; + assert_wire(&request, "memory.set", "ns", "synthetic-token", true); + let acknowledged = tokio::time::timeout(Duration::from_secs(2), async { + while pending(&bound) { + tokio::task::yield_now().await; + } + }); + tokio::select! { + result = acknowledged => result.unwrap(), + result = &mut work => panic!("wait ended before protection acquisition: {result:?}"), + } + let source = Server::new(vec![private_response()]); + let reader = client(&source.url, Some(&bound), "other", "other-token"); + let input = source_body(); + let answer: Value = tokio::select! { + result = reader.call(SOURCE_READ, &input) => result.unwrap(), + result = &mut work => panic!("wait ended before protection acquisition: {result:?}"), + }; + assert_eq!(answer["result"]["value"], PRIVATE_VALUE); + assert_wire( + &source.request().await, + SOURCE_READ, + "other", + "other-token", + true, + ); + let error = tokio::time::timeout(Duration::from_secs(6), &mut work) + .await + .unwrap() + .unwrap_err(); + suppressed(error); + no_request(&server).await; + assert!(SessionProtection::open(bound.pointer()) + .unwrap() + .protected() + .unwrap()); +} + +#[tokio::test] +async fn lost_and_changed_trusted_pointers_refuse_before_http() { + for lost in [true, false] { + let roots = Roots::new(); + let family = roots.family("bound"); + let server = Server::new(vec![response( + 200, + "{}", + "Content-Type: application/json\r\n", + )]); + let writer = client(&server.url, Some(&family), "ns", "synthetic-token"); + let pointer = family.pointer(); + if lost { + fs::remove_file(pointer.path.join("state")).unwrap(); + } else { + fs::write( + pointer.path.join("identity"), + "00000000-0000-0000-0000-000000000000", + ) + .unwrap(); + } + assert!(matches!( + SessionProtection::open(pointer), + Err(Error::Configuration(_)) + )); + assert!(matches!( + writer.call::("memory.set", &write_body()).await, + Err(Error::Configuration(_)) + )); + no_request(&server).await; + } +} diff --git a/sdk/typescript/README.md b/sdk/typescript/README.md index 1e06e4f9d9..3a5b30d0de 100644 --- a/sdk/typescript/README.md +++ b/sdk/typescript/README.md @@ -141,10 +141,23 @@ Explicit offload, fetch and note remain available and observe all retained handl For an explicit call outside Session, `observe: new SessionCapture(roots)` retains response observers without making the call automatic. -This control covers JSON/SSE transport observation and Session buffer ownership. -It does not qualify framework callbacks, restored host lineage or a concrete storage -backend. Binding a handle does not send a session protection capability declaration -or enable mirrored-source creation. +The transport validates its retained handles before each dispatch and sends the +server's session protection declaration only when response observation is installed. +Caller-supplied declaration headers refuse, including duplicate names with different +case. Unbound ordinary calls send no declaration. Missing or incompatible durable +state refuses before sending. Redirects refuse rather than forwarding credentials. + +Browser applications can wrap their existing authenticated fetch with +`protectedBrowserTransport({ baseUrl, sessionProtection, fetch })`. Its `fetch` +observes explicit JSON and SSE responses, including HTTP errors; `automaticFetch` +also guards automatic callbacks and writes to any namespace. Supply a durable +`SessionProtectionStore` and restore the same authority in every relevant context. +Missing state must reject rather than initialize a clean conversation. The adapter +stores neither credentials nor private bodies. It is an alternative to using the +SDK transport directly; do not nest two declaring transports. + +These facilities do not qualify framework callbacks, restored host lineage or a +concrete storage backend, and do not enable mirrored-source creation. ## Errors @@ -600,3 +613,11 @@ python ../../scripts/codegen/sdk_ts_gen.py # regenerate the types after a se ``` The package ships ESM (`dist/index.mjs`) and CommonJS (`dist/index.cjs`) with their own declaration files, has no side effects, and imports no Node built-in (it runs on `fetch`). `test/package/exports.test.ts` lists every runtime export; adding one is a deliberate API change. `src/types.test-d.ts` holds the type-level contract (what `call`, the group accessors and `Body` infer and reject), checked by `vitest --typecheck` inside `npm test`. `prepublishOnly` runs both check scripts. + +`protectedBrowserTransport.downloadFetch` handles same-origin GET downloads as opaque +content. It durably marks every contributing family before returning any bytes, +including JSON and line-delimited exports. The response is buffered within +`maxDownloadBytes` (64 MiB by default and at most) and 4096 chunks; callers can set a +tighter byte bound. JSON operation responses retain their separate 4 MiB bound. +Download cancellation joins the owned reader and retains protection. A download +entry never sends a POST or grants a read beyond the server's authorization. diff --git a/sdk/typescript/src/browser-download.test.ts b/sdk/typescript/src/browser-download.test.ts new file mode 100644 index 0000000000..04cccccdd4 --- /dev/null +++ b/sdk/typescript/src/browser-download.test.ts @@ -0,0 +1,123 @@ +import { describe, expect, it, vi } from "vitest"; +import { protectedBrowserTransport } from "./browser-protection.js"; +import { AutomaticCaptureSuppressed, SessionProtection, SessionProtectionUnavailable } from "./session-protection.js"; + +function fixture() { + const state: { value: "clean" | "protected" } = { value: "clean" }; + const root = new SessionProtection({ + read: async () => state.value, + mark: async () => { state.value = "protected"; }, + }); + return { state, root }; +} + +describe("observed opaque GET downloads", () => { + it.each(["application/octet-stream", "text/plain", "application/pdf", "application/x-ndjson", "application/json"])( + "marks before releasing %s content without inferring an envelope", async (media) => { + const { state, root } = fixture(); + const fetch = vi.fn(async () => new Response("opaque\ncontent", { headers: { "Content-Type": media } })); + const transport = protectedBrowserTransport({ baseUrl: "https://loom.invalid", sessionProtection: root, fetch }); + const response = await transport.downloadFetch("/download", { method: "GET" }); + expect(state.value).toBe("protected"); + expect(await response.text()).toBe("opaque\ncontent"); + expect(fetch).toHaveBeenCalledOnce(); + await expect(transport.automaticFetch("/v1/memory.set", { method: "POST" })).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(fetch).toHaveBeenCalledOnce(); + }, + ); + + it("holds the response until durable marking is acknowledged", async () => { + let release!: () => void; + let marking!: () => void; + const ack = new Promise((resolve) => { release = resolve; }); + const entered = new Promise((resolve) => { marking = resolve; }); + let state: "clean" | "protected" = "clean"; + const root = new SessionProtection({ + read: async () => state, + mark: async () => { marking(); await ack; state = "protected"; }, + }); + const transport = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", sessionProtection: root, + fetch: async () => new Response("private bytes"), + }); + let returned = false; + const pending = transport.downloadFetch("/download", { method: "GET" }); + void pending.then(() => { returned = true; }, () => { returned = true; }); + await entered; + expect(returned).toBe(false); + release(); + expect(await (await pending).text()).toBe("private bytes"); + expect(state).toBe("protected"); + }); + + it("refuses failed durable marking before returning an opaque body", async () => { + const root = new SessionProtection({ read: async () => "clean", mark: async () => { throw new Error("lost proof"); } }); + const transport = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", sessionProtection: root, + fetch: async () => new Response("unreleased bytes"), + }); + await expect(transport.downloadFetch("/download", { method: "GET" })).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(root.locallyProtected).toBe(true); + }); + + it("enforces the application's tighter byte bound and retains protection", async () => { + const { state, root } = fixture(); + const transport = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", sessionProtection: root, maxDownloadBytes: 8, + fetch: async () => new Response("123456789"), + }); + await expect(transport.downloadFetch("/download", { method: "GET" })).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(state.value).toBe("protected"); + }); + + it("refuses POST downloads and foreign-origin credential dispatch", async () => { + const { root } = fixture(); + const fetch = vi.fn(async () => new Response("must not be fetched")); + const transport = protectedBrowserTransport({ baseUrl: "https://loom.invalid", sessionProtection: root, fetch }); + await expect(transport.downloadFetch("/download", { method: "POST" })).rejects.toBeInstanceOf(SessionProtectionUnavailable); + await expect(transport.downloadFetch("https://other.invalid/download", { method: "GET" })).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(fetch).not.toHaveBeenCalled(); + }); +}); + +it("joins a cancelled opaque reader and keeps its family protected", async () => { + const { state, root } = fixture(); + let calls = 0; + let cancelled = false; + let stalled!: () => void; + const waiting = new Promise((resolve) => { stalled = resolve; }); + const body = new ReadableStream({ + pull(controller) { + if (++calls === 1) controller.enqueue(new TextEncoder().encode("prefix")); + else stalled(); + }, + cancel() { cancelled = true; }, + }); + const signal = new AbortController(); + const transport = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", sessionProtection: root, + fetch: async () => new Response(body), + }); + const pending = transport.downloadFetch("/download", { method: "GET", signal: signal.signal }); + await waiting; + signal.abort(); + await expect(pending).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(cancelled).toBe(true); + expect(state.value).toBe("protected"); +}); + +it("bounds opaque chunk bookkeeping independently from response bytes", async () => { + const { state, root } = fixture(); + let cancelled = false; + const body = new ReadableStream({ + pull(controller) { controller.enqueue(new Uint8Array([1])); }, + cancel() { cancelled = true; }, + }); + const transport = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", sessionProtection: root, + fetch: async () => new Response(body), + }); + await expect(transport.downloadFetch("/download", { method: "GET" })).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(cancelled).toBe(true); + expect(state.value).toBe("protected"); +}); diff --git a/sdk/typescript/src/browser-protection.ts b/sdk/typescript/src/browser-protection.ts new file mode 100644 index 0000000000..c32388638d --- /dev/null +++ b/sdk/typescript/src/browser-protection.ts @@ -0,0 +1,182 @@ +import { protectEventStream } from "./protected-stream.js"; +import { + AutomaticCaptureSuppressed, + boundProtection, + observeJsonResponse, + protectionHeaders, + refuseResponse, + requireAutomaticAllowed, + requireAutomaticLocallyAllowed, + SessionCapture, + type SessionProtection, + SessionProtectionUnavailable, +} from "./session-protection.js"; +import type { FetchLike } from "./transport.js"; + +export interface ProtectedBrowserTransport { + /** Explicit reads and writes still observe every response. */ + fetch: FetchLike; + /** Use for all automatic callbacks, including writes to another namespace. */ + automaticFetch: FetchLike; + /** GET downloads are conservatively marked before any opaque bytes are released. */ + downloadFetch: FetchLike; +} + +async function readDownloadBody( + response: Response, + roots: readonly SessionProtection[], + timeoutMs: number, + signal: AbortSignal, + maximum: number, +): Promise { + const reader = response.body?.getReader(); + if (!reader) return new ArrayBuffer(0); + const parts: Uint8Array[] = []; + let bytes = 0; + try { + for (;;) { + const part = await boundProtection(reader.read(), roots, timeoutMs, signal); + if (part.done) break; + bytes += part.value.byteLength; + if (bytes > maximum || parts.length >= 4096) throw new SessionProtectionUnavailable(); + parts.push(part.value); + } + const body = new ArrayBuffer(bytes); + const joined = new Uint8Array(body); + let offset = 0; + for (const part of parts) { + joined.set(part, offset); + offset += part.byteLength; + } + return body; + } catch (error) { + await boundProtection(reader.cancel(), roots, timeoutMs); + throw error; + } finally { + reader.releaseLock(); + } +} + +async function readJsonBody( + response: Response, + roots: readonly SessionProtection[], + timeoutMs: number, + signal: AbortSignal, +): Promise { + if (!response.body) return ""; + const reader = response.body.getReader(); + const decoder = new TextDecoder("utf-8", { fatal: true }); + let text = ""; + let bytes = 0; + try { + for (;;) { + const chunk = await boundProtection(reader.read(), roots, timeoutMs, signal); + if (chunk.done) return text + decoder.decode(); + bytes += chunk.value.byteLength; + if (bytes > 4 * 1024 * 1024) throw new SessionProtectionUnavailable(); + text += decoder.decode(chunk.value, { stream: true }); + } + } catch (error) { + await boundProtection(reader.cancel(), roots, timeoutMs); + throw error; + } finally { + reader.releaseLock(); + } +} + +/** Bind the application's existing durable family before its first private read. */ +export function protectedBrowserTransport(options: { + baseUrl: string; + sessionProtection: SessionProtection; + fetch?: FetchLike; + timeoutMs?: number; + /** Opaque downloads may lower this 64 MiB ceiling; JSON keeps its separate 4 MiB bound. */ + maxDownloadBytes?: number; +}): ProtectedBrowserTransport { + const base = new URL(options.baseUrl); + const roots = new SessionCapture([options.sessionProtection]).roots; + const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis); + const timeoutMs = options.timeoutMs ?? 60_000; + const maxDownloadBytes = options.maxDownloadBytes ?? 64 * 1024 * 1024; + if (!Number.isSafeInteger(maxDownloadBytes) || maxDownloadBytes < 1 || maxDownloadBytes > 64 * 1024 * 1024) { + throw new SessionProtectionUnavailable(); + } + if (base.username || base.password || !["http:", "https:"].includes(base.protocol)) { + throw new SessionProtectionUnavailable(); + } + + async function send(input: string, init: RequestInit, automatic: boolean, download = false): Promise { + const url = new URL(input, base); + if (url.origin !== base.origin || url.username || url.password) throw new SessionProtectionUnavailable(); + if (download && (init.method ?? "GET").toUpperCase() !== "GET") throw new SessionProtectionUnavailable(); + const controller = new AbortController(); + const onAbort = () => controller.abort(); + init.signal?.addEventListener("abort", onAbort, { once: true }); + if (init.signal?.aborted) controller.abort(); + const timer = setTimeout(onAbort, timeoutMs); + let response: Response | undefined; + try { + // Presence refuses even when Headers has normalized duplicate values. + const given: Record = {}; + new Headers(init.headers).forEach((value, name) => { + given[name] = value; + }); + const headers = await boundProtection( + protectionHeaders(given, roots), + roots, + timeoutMs, + controller.signal, + ); + await boundProtection(requireAutomaticAllowed(roots, automatic), roots, timeoutMs, controller.signal); + requireAutomaticLocallyAllowed(roots, automatic); + if (controller.signal.aborted) throw new SessionProtectionUnavailable(); + response = await boundProtection( + fetchImpl(url.href, { ...init, headers, signal: controller.signal, redirect: "error" }), + roots, + timeoutMs, + controller.signal, + ); + if (download && ![204, 304].includes(response.status)) { + // Opaque exports have no envelope contract, including JSON and line-delimited JSON. + await boundProtection(Promise.all(roots.map((root) => root.mark())), roots, timeoutMs, controller.signal); + const body = await readDownloadBody(response, roots, timeoutMs, controller.signal, maxDownloadBytes); + return new Response(body, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); + } + if (response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === "text/event-stream") { + // The returned observer owns cancellation after these opening listeners are detached. + return await protectEventStream(response, roots, timeoutMs, init.signal ?? undefined); + } + if (!response.headers.get("content-type")?.toLowerCase().includes("json") && ![204, 304].includes(response.status)) { + return await boundProtection(refuseResponse(roots), roots, timeoutMs, controller.signal); + } + const text = await readJsonBody(response, roots, timeoutMs, controller.signal); + await boundProtection(observeJsonResponse(text, response.status, roots), roots, timeoutMs, controller.signal); + return new Response([204, 304].includes(response.status) ? null : text, { + status: response.status, + statusText: response.statusText, + headers: response.headers, + }); + } catch (error) { + // An unconfirmed response never becomes a clean family after cancellation or decoding failure. + await Promise.allSettled([ + boundProtection(refuseResponse(roots), roots, timeoutMs), + boundProtection(Promise.resolve(response?.body?.cancel()), roots, timeoutMs), + ]); + if (error instanceof AutomaticCaptureSuppressed || error instanceof SessionProtectionUnavailable) throw error; + throw new SessionProtectionUnavailable(); + } finally { + clearTimeout(timer); + init.signal?.removeEventListener("abort", onAbort); + } + } + + return Object.freeze({ + fetch: (input: string, init: RequestInit) => send(input, init, false), + automaticFetch: (input: string, init: RequestInit) => send(input, init, true), + downloadFetch: (input: string, init: RequestInit) => send(input, init, false, true), + }); +} diff --git a/sdk/typescript/src/index.ts b/sdk/typescript/src/index.ts index 9d9b3347fd..0407ff4d77 100644 --- a/sdk/typescript/src/index.ts +++ b/sdk/typescript/src/index.ts @@ -21,6 +21,8 @@ export type { AssistantTurn, } from "./assistant.js"; export { ASSISTANT_ROUTE } from "./assistant.js"; +export type { ProtectedBrowserTransport } from "./browser-protection.js"; +export { protectedBrowserTransport } from "./browser-protection.js"; export type { ProbeResult } from "./capabilities.js"; export { Capabilities, capabilities, probe } from "./capabilities.js"; export type { diff --git a/sdk/typescript/src/session-protection.ts b/sdk/typescript/src/session-protection.ts index 47e7f325fe..3d78ac8875 100644 --- a/sdk/typescript/src/session-protection.ts +++ b/sdk/typescript/src/session-protection.ts @@ -49,6 +49,19 @@ export class SessionProtection { return this.#tainted; } + async requireReady(): Promise { + try { + if (this.#pending) await this.#pending; + const state = await this.#read(); + if (state !== "clean" && state !== "protected") throw new SessionProtectionUnavailable(); + if (state === "protected") this.#tainted = true; + if (this.#tainted && state !== "protected") throw new SessionProtectionUnavailable(); + } catch { + this.#tainted = true; + throw new SessionProtectionUnavailable(); + } + } + mark(): Promise { // The latch stops concurrent callbacks; only the durable acknowledgement releases content. this.#tainted = true; @@ -90,7 +103,21 @@ export function responseRoots( capture?: SessionCapture, observe?: SessionCapture, ): readonly SessionProtection[] { - return Object.freeze([...new Set([...(capture?.roots ?? []), ...(observe?.roots ?? []), ...(root ? [root] : [])])]); + const roots = [...new Set([...(capture?.roots ?? []), ...(observe?.roots ?? []), ...(root ? [root] : [])])]; + if (roots.some((family) => !(family instanceof SessionProtection))) throw new SessionProtectionUnavailable(); + return Object.freeze(roots); +} + +/** Only an installed observer may declare the existing request protocol. */ +export async function protectionHeaders( + headers: Record, + roots: readonly SessionProtection[], +): Promise> { + if (Object.keys(headers).some((name) => name.toLowerCase() === "x-loom-session-protection")) { + throw new SessionProtectionUnavailable(); + } + await Promise.all(roots.map((root) => root.requireReady())); + return roots.length ? { ...headers, "X-Loom-Session-Protection": "v1" } : { ...headers }; } export async function requireAutomaticAllowed(roots: readonly SessionProtection[], automatic: boolean): Promise { @@ -162,6 +189,7 @@ export async function observeResponse(value: T, roots: readonly SessionProtec if (!roots.length) return value; let marked: boolean; try { + await Promise.all(roots.map((root) => root.requireReady())); if (!object(value)) throw new SessionProtectionUnavailable(); marked = markedEnvelope(value); } catch { diff --git a/sdk/typescript/src/source-client-readiness.test.ts b/sdk/typescript/src/source-client-readiness.test.ts new file mode 100644 index 0000000000..77f189643b --- /dev/null +++ b/sdk/typescript/src/source-client-readiness.test.ts @@ -0,0 +1,356 @@ +import { describe, expect, it } from "vitest"; +import { protectedBrowserTransport } from "./browser-protection.js"; +import { + AutomaticCaptureSuppressed, + SessionCapture, + SessionProtection, + SessionProtectionUnavailable, +} from "./session-protection.js"; +import { Transport } from "./transport.js"; + +const declaration = "x-loom-session-protection"; +const privateValue = "private-source-value"; + +function family() { + let state: "clean" | "protected" = "clean"; + let missing = false; + const root = new SessionProtection({ + async read() { + if (missing) throw new Error(privateValue); + return state; + }, + async mark() { + if (missing) throw new Error(privateValue); + state = "protected"; + }, + }); + return { + root, + lose: () => { + missing = true; + }, + state: () => state, + }; +} + +function json(value: unknown, status = 200) { + return new Response(JSON.stringify(value), { + status, + headers: { "content-type": "application/json", "X-Request-Id": "protected" }, + }); +} + +describe("actual SDK request readiness", () => { + it("declares only with a bound family and blocks cross-namespace automatic capture after observation", async () => { + const source = family(); + const requests: RequestInit[] = []; + const client = new Transport({ + baseUrl: "https://loom.invalid", + apiKey: "secret", + sessionProtection: source.root, + logLevel: "off", + fetch: async (_url, init) => { + requests.push(init); + return json({ mirrored: true, value: privateValue }); + }, + }); + expect(await client.post("knowledge.source.mcp_read", {})).toEqual({ mirrored: true, value: privateValue }); + expect(new Headers(requests[0]?.headers).get(declaration)).toBe("v1"); + expect(new Headers(requests[0]?.headers).get("authorization")).toBe("Bearer secret"); + expect(source.state()).toBe("protected"); + await expect( + client.post( + "memory.set", + { namespace: "other", value: privateValue }, + { capture: new SessionCapture([source.root]) }, + ), + ).rejects.toBeInstanceOf(AutomaticCaptureSuppressed); + expect(requests).toHaveLength(1); + await client.post("memory.get", { org: "other", session_id: "other" }); + expect(requests).toHaveLength(2); + }); + + it("does not change the promise of ordinary sessions", async () => { + const client = new Transport({ + baseUrl: "https://loom.invalid", + logLevel: "off", + fetch: async (_url, init) => { + expect(new Headers(init.headers).has(declaration)).toBe(false); + return json({ ok: true }); + }, + }); + expect(await client.post("memory.get", {})).toEqual({ ok: true }); + }); + + it("preserves the server readiness refusal for an unbound source read", async () => { + const client = new Transport({ + baseUrl: "https://loom.invalid", + logLevel: "off", + fetch: async (url, init) => { + expect(new URL(url).pathname).toBe("/v1/knowledge.source.mcp_read"); + expect(new Headers(init.headers).has(declaration)).toBe(false); + return json({ detail: { code: "SESSION_PROTECTION_REQUIRED", message: "Session protection required" } }, 409); + }, + }); + await expect(client.post("knowledge.source.mcp_read", {})).rejects.toMatchObject({ + code: "SESSION_PROTECTION_REQUIRED", + }); + }); + + it.each([ + { [declaration]: "v1" }, + { [declaration]: "v2" }, + { [declaration]: "v1", "X-Loom-Session-Protection": "v1" }, + ])("refuses caller declarations %j", async (headers) => { + let sent = 0; + for (const bound of [false, true]) { + const client = new Transport({ + baseUrl: "https://loom.invalid", + headers, + sessionProtection: bound ? family().root : undefined, + logLevel: "off", + fetch: async () => { + sent++; + return json({}); + }, + }); + await expect(client.post("knowledge.source.mcp_read", {})).rejects.toBeInstanceOf(SessionProtectionUnavailable); + } + expect(sent).toBe(0); + }); + + it("refuses lost state without exposing store diagnostics", async () => { + const source = family(); + source.lose(); + let sent = 0; + const client = new Transport({ + baseUrl: "https://loom.invalid", + sessionProtection: source.root, + logLevel: "off", + fetch: async () => { + sent++; + return json({}); + }, + }); + await expect(client.post("knowledge.source.mcp_read", {})).rejects.toThrow( + "Session protection state could not be confirmed", + ); + expect(sent).toBe(0); + }); + + it("rechecks automatic protection after the admission storage wait", async () => { + let reads = 0; + let sent = 0; + const root = new SessionProtection({ + async read() { + return ++reads === 1 ? "clean" : "protected"; + }, + async mark() {}, + }); + const client = new Transport({ + baseUrl: "https://loom.invalid", + sessionProtection: root, + logLevel: "off", + fetch: async () => { + sent++; + return json({}); + }, + }); + await expect(client.post("memory.set", {}, { capture: new SessionCapture([root]) })).rejects.toBeInstanceOf( + AutomaticCaptureSuppressed, + ); + expect(sent).toBe(0); + }); + + it("refuses a supplied declaration on stream requests", async () => { + let sent = 0; + const client = new Transport({ + baseUrl: "https://loom.invalid", + sessionProtection: family().root, + logLevel: "off", + fetch: async () => { + sent++; + return json({}); + }, + }); + await expect(client.stream("/v1/source-events", {}, { headers: { [declaration]: "v1" } })).rejects.toBeInstanceOf( + SessionProtectionUnavailable, + ); + expect(sent).toBe(0); + }); + + it("retains independent families across clients and origins", async () => { + const first = family(); + const second = family(); + const a = new Transport({ + baseUrl: "https://one.invalid", + sessionProtection: first.root, + logLevel: "off", + fetch: async () => json({ mirrored: true }), + }); + const b = new Transport({ + baseUrl: "https://two.invalid", + sessionProtection: second.root, + logLevel: "off", + fetch: async (_url, init) => { + expect(new Headers(init.headers).get(declaration)).toBe("v1"); + return json({ ok: true }); + }, + }); + await a.post("knowledge.source.mcp_read", {}); + await expect(b.post("memory.get", {}, { capture: new SessionCapture([second.root]) })).resolves.toEqual({ ok: true }); + await expect(b.post("memory.set", {}, { capture: new SessionCapture([first.root]) })).rejects.toBeInstanceOf( + AutomaticCaptureSuppressed, + ); + expect(second.state()).toBe("clean"); + }); + + it.each([200, 403])("withholds malformed private JSON at status %i", async (status) => { + const source = family(); + const client = new Transport({ + baseUrl: "https://loom.invalid", + sessionProtection: source.root, + logLevel: "off", + fetch: async (_url, init) => { + expect(new Headers(init.headers).get(declaration)).toBe("v1"); + return new Response(privateValue, { status, headers: { "content-type": "application/json" } }); + }, + }); + await expect(client.post("knowledge.source.mcp_read", {})).rejects.toThrow( + "Session protection state could not be confirmed", + ); + expect(source.state()).toBe("protected"); + }); + + it("observes stream metadata before output and guards cancellation", async () => { + const source = family(); + let closed = false; + const client = new Transport({ + baseUrl: "https://loom.invalid", + sessionProtection: source.root, + logLevel: "off", + fetch: async (_url, init) => { + expect(new Headers(init.headers).get(declaration)).toBe("v1"); + expect(init.redirect).toBe("error"); + return new Response( + new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('data: {"mirrored":true,"value":"private-source-value"}\n\n')); + }, + cancel() { + closed = true; + }, + }), + { headers: { "content-type": "text/event-stream", "X-Request-Id": "events" } }, + ); + }, + }); + const response = await client.stream("/v1/source-events", {}); + expect(response.headers.get("X-Request-Id")).toBe("events"); + if (!response.body) throw new Error("Expected response body"); + const reader = response.body.getReader(); + const chunk = await reader.read(); + expect(source.state()).toBe("protected"); + expect(new TextDecoder().decode(chunk.value)).toContain(privateValue); + await reader.cancel(); + reader.releaseLock(); + expect(closed).toBe(true); + await expect(client.post("memory.set", {}, { capture: new SessionCapture([source.root]) })).rejects.toBeInstanceOf( + AutomaticCaptureSuppressed, + ); + }); +}); + +describe("browser protection adapter", () => { + it("preserves HTTP error status, headers and envelope after observation", async () => { + const source = family(); + const client = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", + sessionProtection: source.root, + fetch: async (_url, init) => { + expect(new Headers(init.headers).get(declaration)).toBe("v1"); + return json({ error: { data: { mirrored: true }, message: "refused" } }, 403); + }, + }); + const response = await client.fetch("/v1/knowledge.source.mcp_read", {}); + expect(source.state()).toBe("protected"); + expect(response.status).toBe(403); + expect(response.headers.get("X-Request-Id")).toBe("protected"); + expect(await response.json()).toEqual({ error: { data: { mirrored: true }, message: "refused" } }); + await expect(client.automaticFetch("/v1/memory.set", { method: "POST", body: privateValue })).rejects.toBeInstanceOf( + AutomaticCaptureSuppressed, + ); + }); + + it("never forwards credentials or readiness to another origin", async () => { + let sent = 0; + const client = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", + sessionProtection: family().root, + fetch: async () => { + sent++; + return json({}); + }, + }); + await expect( + client.fetch("https://upstream.invalid/mcp", { headers: { Authorization: "Bearer secret" } }), + ).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(sent).toBe(0); + }); + + it("refuses duplicate header tuples and missing restored proof", async () => { + const source = family(); + let sent = 0; + const client = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", + sessionProtection: source.root, + fetch: async () => { + sent++; + return json({}); + }, + }); + await expect( + client.fetch("/v1/memory.get", { + headers: [ + [declaration, "v1"], + [declaration, "v1"], + ], + }), + ).rejects.toBeInstanceOf(SessionProtectionUnavailable); + source.lose(); + await expect(client.fetch("/v1/memory.get", {})).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(sent).toBe(0); + }); + + it("joins owned cancellation and withholds raw private diagnostics", async () => { + const source = family(); + const controller = new AbortController(); + let cancelled = false; + const client = protectedBrowserTransport({ + baseUrl: "https://loom.invalid", + sessionProtection: source.root, + fetch: async (_url, init) => { + expect(new Headers(init.headers).get(declaration)).toBe("v1"); + return new Response( + new ReadableStream( + { + pull() { + controller.abort(); + }, + cancel() { + cancelled = true; + }, + }, + { highWaterMark: 0 }, + ), + { headers: { "content-type": "application/json" } }, + ); + }, + }); + await expect( + client.fetch("/v1/knowledge.source.mcp_read", { signal: controller.signal }), + ).rejects.toBeInstanceOf(SessionProtectionUnavailable); + expect(source.state()).toBe("protected"); + expect(cancelled).toBe(true); + }); +}); diff --git a/sdk/typescript/src/transport.ts b/sdk/typescript/src/transport.ts index acaebdab92..b344683540 100644 --- a/sdk/typescript/src/transport.ts +++ b/sdk/typescript/src/transport.ts @@ -71,6 +71,7 @@ import { envVar, isBrowser, runtimeIdent } from "./runtime.js"; import { boundProtection, observeJsonResponse, + protectionHeaders, refuseResponse, requireAutomaticAllowed, requireAutomaticLocallyAllowed, @@ -86,7 +87,7 @@ export type FetchLike = (input: string, init: RequestInit) => Promise; export interface TransportOptions { baseUrl: string; - /** Application-owned durable control; binding alone does not declare protocol capability. */ + /** Application-owned durable control, validated before declaring request protection. */ sessionProtection?: SessionProtection; apiKey?: string; /** A credential fetched per request (a bot's `MachineLogin`, a `StoredLogin`); not with `apiKey`. */ @@ -361,10 +362,19 @@ export class Transport { if (bearer) headers.Authorization = `Bearer ${bearer}`; } if (automatic) await boundProtection(requireAutomaticAllowed(roots, true), roots, this.timeoutMs, opts.signal); + const admitted = roots.length + ? await boundProtection(protectionHeaders(headers, roots), roots, this.timeoutMs, opts.signal) + : await protectionHeaders(headers, roots); requireAutomaticLocallyAllowed(roots, automatic); let res: Response; try { - res = await this.fetchImpl(url, { method: "POST", headers, body: payload, signal: opts.signal }); + res = await this.fetchImpl(url, { + method: "POST", + headers: admitted, + body: payload, + signal: opts.signal, + redirect: "error", + }); } catch (e) { if (opts.signal?.aborted) throw aborted(e); const err = new BackendUnavailable(`${path}: cannot reach ${this.baseUrl}: ${describe(e)}`, { @@ -508,15 +518,20 @@ export class Transport { await boundProtection(requireAutomaticAllowed(ctx.roots, true), ctx.roots, timeoutMs, ctrl.signal); } throwIfAborted(ctx); + const headers = ctx.roots.length + ? await boundProtection(protectionHeaders(ctx.headers, ctx.roots), ctx.roots, timeoutMs, ctrl.signal) + : await protectionHeaders(ctx.headers, ctx.roots); + throwIfAborted(ctx); requireAutomaticLocallyAllowed(ctx.roots, ctx.automatic); let res: Response; try { res = await this.fetchImpl(ctx.url, { method: ctx.method, - headers: ctx.headers, + headers, // A byte array is a fetch body; TypeScript's lib types narrow it to ArrayBuffer-backed views. body: ctx.payload as BodyInit | undefined, signal: ctrl.signal, + redirect: "error", }); } catch (e) { return { failed: "connect", error: e }; diff --git a/server/cli/_client.py b/server/cli/_client.py index fc3d4ab312..9f6e307ce8 100644 --- a/server/cli/_client.py +++ b/server/cli/_client.py @@ -198,6 +198,10 @@ def _read_error(e: urllib.error.HTTPError) -> dict[str, Any]: def _send(req: urllib.request.Request, timeout: float) -> tuple[int, dict[str, Any]]: + from server.cli import _session_context + + if (protected := _session_context.send(req, timeout)) is not None: + return protected try: with urllib.request.urlopen(req, timeout=timeout) as r: status, raw = r.status, r.read() diff --git a/server/cli/_session_context.py b/server/cli/_session_context.py new file mode 100644 index 0000000000..4d6e6dba01 --- /dev/null +++ b/server/cli/_session_context.py @@ -0,0 +1,201 @@ +"""Lazy installed-SDK bridge for application-owned CLI session context.""" + +from __future__ import annotations + +import asyncio +import contextlib +import contextvars +import importlib +import os +import threading +from collections.abc import Awaitable, Callable, Iterator +from dataclasses import dataclass +from typing import Any, cast + +CONTEXT_ENV = "LOOM_SOURCE_SESSION_CONTEXT" +_DEPENDENCY = ( + "Trusted CLI session context requires the matching-release clickhouse-loom Python SDK " + "alongside the server CLI. Install the SDK from the same release artifact. " + "The server-only wheel cannot provide protected requests." +) + + +class CLIContextError(RuntimeError): + """A configured context refused before an unprotected request could be sent.""" + + +def _task() -> object | None: + try: + return asyncio.current_task() + except RuntimeError: + return None + + +@dataclass +class _Invocation: + capsule: str | None + explicit: bool + thread: int + task: object | None + active: bool = True + parent: _Invocation | None = None + + +_current: contextvars.ContextVar[_Invocation | None] = contextvars.ContextVar( + "loom_cli_invocation", default=None +) + + +@contextlib.contextmanager +def invocation(intent: str = "automatic") -> Iterator[None]: + """Bind one dispatch; expire authority in contexts copied by retained callbacks.""" + value = _Invocation( + os.environ.get(CONTEXT_ENV), intent == "explicit", threading.get_ident(), _task() + ) + token = _current.set(value) + try: + yield + finally: + value.active = False + _current.reset(token) + + +def capsule() -> str | None: + value = _current.get() + raw = os.environ.get(CONTEXT_ENV) + if value is not None and value.capsule != raw: + raise CLIContextError( + "Trusted CLI session environment changed during dispatch; restore it." + ) + return raw + + +def configured() -> bool: + return capsule() is not None + + +def _explicit() -> bool: + value = _current.get() + if value is None or not value.active or not value.explicit: + return False + parent = value.parent + while parent is not None: + if not parent.active: + return False + parent = parent.parent + if value.thread != threading.get_ident(): + return False + task = _task() + if value.task is None and task is not None: + value.task = task + return value.task is task + + +def _entry() -> Any: + try: + entry = importlib.import_module("loom.cli_context") + except ImportError: + raise CLIContextError(_DEPENDENCY) from None + if getattr(entry, "CLI_CONTEXT_API", None) != 1: + raise CLIContextError(_DEPENDENCY) + return entry + + +def require_sdk() -> None: + """Refuse delegation to an SDK without the inherited context contract.""" + _entry() + + +def run_async[T](factory: Callable[[], Awaitable[T]]) -> T: + """Keep a configured CLI dispatch and its resources on one owned async loop.""" + if not configured(): + try: + asyncio.get_running_loop() + except RuntimeError: + + async def ordinary() -> T: + return await factory() + + return asyncio.run(ordinary()) + raise CLIContextError("Call the synchronous CLI outside the active event loop.") + entry = _entry() + parent = _current.get() + raw, explicit = capsule(), _explicit() + + async def owned() -> T: + child = _Invocation(raw, explicit, threading.get_ident(), _task(), parent=parent) + token = _current.set(child) + try: + return await factory() + finally: + child.active = False + _current.reset(token) + + return cast(T, entry.run_sync(owned)) + + +async def post( + client: Any, url: str, token: str, *, body: dict[str, Any], timeout_s: float = 90.0 +) -> Any: + """Keep ordinary clients unchanged; configured clients use observed SDK dispatch.""" + raw = capsule() + if raw is None: + return await client.post(url, json=body) + entry = _entry() + try: + return await entry.request( + raw, "POST", url, token, body=body, timeout_s=timeout_s, explicit=_explicit() + ) + except ( + RuntimeError, + OSError, + ValueError, + entry.AutomaticCaptureSuppressed, + entry.SessionProtectionUnavailable, + ) as exc: + raise CLIContextError( + "Trusted CLI session protection refused; retain the original context and proof." + ) from exc + + +def send(req: Any, timeout: float) -> tuple[int, dict[str, Any]] | None: + """urllib-compatible JSON/file boundary; None selects the ordinary unbound path.""" + raw = capsule() + if raw is None: + return None + entry = _entry() + explicit = _explicit() + content = req.data + body = None + if content is not None and req.get_header("Content-type", "").startswith("application/json"): + import json + + body = json.loads(content) + content = None + auth = req.get_header("Authorization", "") + token = auth[7:] if auth.startswith("Bearer ") else "" + try: + response = entry.run_sync( + lambda: entry.request( + raw, + req.get_method(), + req.full_url, + token, + body=body, + content=content, + timeout_s=timeout, + explicit=explicit, + ) + ) + result = response.json() + return response.status_code, result if isinstance(result, dict) else {} + except ( + RuntimeError, + OSError, + ValueError, + entry.AutomaticCaptureSuppressed, + entry.SessionProtectionUnavailable, + ) as exc: + raise CLIContextError( + "Trusted CLI session protection refused; retain the original context and proof." + ) from exc diff --git a/server/cli/app.py b/server/cli/app.py index e82bab470f..f932807758 100644 --- a/server/cli/app.py +++ b/server/cli/app.py @@ -377,15 +377,34 @@ def main(argv: list[str] | None = None) -> int: # Before the checkout's .env, which describes the server and would # otherwise override the user's own session (LOOM_API_KEY, LOOM_BASE_URL). return run_sdk_command(raw) + if (len(raw) > 2 and raw[0] == "--request-intent" and raw[2] in SDK_COMMANDS) or ( + len(raw) > 1 and raw[0].startswith("--request-intent=") and raw[1] in SDK_COMMANDS + ): + return run_sdk_command(raw) _load_dotenv_like_the_container() parser = argparse.ArgumentParser( prog="loom", description="Loom — vendor-neutral agent memory plane on ClickHouse.", ) parser.add_argument("--version", action="version", version=f"loom {_version()}") + parser.add_argument( + "--request-intent", + choices=("automatic", "explicit"), + default="automatic", + help="Explicit is one direct human request; automatic is the default.", + ) sub = parser.add_subparsers(dest="cmd", required=True) for _add_parsers in _SUBCOMMAND_BUILDERS: _add_parsers(sub) args = parser.parse_args(argv) wire() - return _dispatch(args) + from server.cli._session_context import CLIContextError, invocation + + intent = args.request_intent + del args.request_intent + try: + with invocation(intent): + return _dispatch(args) + except CLIContextError as exc: + print(str(exc), file=sys.stderr) + return 2 diff --git a/server/cli/import_recall.py b/server/cli/import_recall.py index 6e49c95b84..8ef20da026 100644 --- a/server/cli/import_recall.py +++ b/server/cli/import_recall.py @@ -662,7 +662,6 @@ def _cmd_import_recall(args: argparse.Namespace) -> int: --token T JWT for --base-url mode --dry-run introspect + plan, print the summary, no writes """ - import asyncio import sqlite3 import sys @@ -741,7 +740,9 @@ async def _run() -> int: print(f"✓ import complete: {ok} writes ok, {failed} failed") return 0 if failed == 0 else 1 - return asyncio.run(_run()) + from server.cli._session_context import run_async + + return run_async(_run) _OpHandlers = dict[str, Callable[[dict[str, Any]], Awaitable[Any]]] @@ -772,7 +773,11 @@ def _make_http_writer( base = base_url.rstrip("/") async def _http_writer(op: str, payload: dict[str, Any]) -> None: - r = await client.post(f"{base}/v1/{op}", json=_recall_jsonable(payload)) + from server.cli import _session_context + + r = await _session_context.post( + client, f"{base}/v1/{op}", token, body=_recall_jsonable(payload), timeout_s=timeout_s + ) if _publication_pending(r): return # committed; the server's delivery worker publishes it r.raise_for_status() diff --git a/server/cli/knowledge_source.py b/server/cli/knowledge_source.py index 07b62de149..37f41f3483 100644 --- a/server/cli/knowledge_source.py +++ b/server/cli/knowledge_source.py @@ -1,188 +1,103 @@ -"""`loom knowledge source list|add|update`: a namespace's document sources over a -running server's `knowledge.source.*` ops, as the token's principal. Items are -given as pasted links (`--link`) or as JSON objects (`--item-json`); a credential -is read from a file, never from the command line.""" +"""Source controls use the matching installed SDK's protected request path.""" from __future__ import annotations import argparse -import json +import importlib import sys -from http import HTTPStatus -from pathlib import Path from typing import Any -from server.cli._client import ( - default_base_url, - detail_line, - jwt_claims, - post_op, - refused_for_agent, - resolve_token, +_SOURCE_CLI_API = 2 +_DEPENDENCY_MESSAGE = ( + "Source controls require the matching-release clickhouse-loom Python SDK " + "alongside the server CLI. Install the SDK from the same release artifact, " + "or use that SDK's python -m loom.source_cli entry point. " + "The server-only wheel does not contain the SDK." ) +_ACTIONS = ( + "preview", + "add", + "update", + "list", + "inspect", + "pause", + "resume", + "refresh", + "read", + "remove", +) +_GROUPS = { + "connection": ("profiles", "connect", "list", "inspect", "discover", "browse", "disconnect"), + "destination": ("list", "create", "grants", "grant", "preview"), + "recording": ("add", "list", "sync-now"), + "retained": ("list", "inspect", "remove"), +} def register_knowledge_source_cli(ksub: Any) -> None: - p = ksub.add_parser("source", help="A namespace's document sources, over a running server.") - ssub = p.add_subparsers(dest="source_command", required=True) - p_list = ssub.add_parser("list", help="List the namespace's sources, items and sync state.") - _common(p_list) - p_list.set_defaults(func=_cmd_list) - p_add = ssub.add_parser( - "add", - help="Register a source from links or items, probed with the credential before " - "anything is stored (knowledge.source.add).", - ) - _common(p_add) - p_add.add_argument("--name", required=True) - p_add.add_argument("--kind", required=True, help="gdrive, notion or linear") - _items(p_add) - _include(p_add) - p_add.add_argument( - "--credential-file", - required=True, - help="The file holding the source's read-only credential; - reads it from stdin", + parser = ksub.add_parser( + "source", help="MCP sources, connections, collection destinations and recordings." ) - p_add.add_argument("--dry-run", action="store_true", help="Probe and store nothing") - p_add.set_defaults(func=_cmd_add) - p_update = ssub.add_parser( - "update", - help="Add and remove a source's items or change its file kinds, the added items " - "probed with the stored credential (knowledge.source.update).", + actions = parser.add_subparsers(dest="source_command", required=True) + for action in _ACTIONS: + _command(actions, "", action) + for group, names in _GROUPS.items(): + nested = actions.add_parser(group).add_subparsers(dest="source_action", required=True) + for action in names: + _command(nested, group, action) + + +def _command(sub: Any, group: str, action: str) -> None: + parser = sub.add_parser(action, allow_abbrev=False) + parser.add_argument("--server-url", required=True) + parser.add_argument("--org", required=True) + if group != "connection" and (group, action) != ("destination", "list"): + parser.add_argument( + "--namespace", help="Ordinary destination; must agree with the JSON field." + ) + parser.add_argument( + "--request-file", + help="UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", ) - _common(p_update) - p_update.add_argument("--name", required=True) - _items(p_update) - _include(p_update) - _items(p_update, prefix="remove-", verb="remove") - p_update.set_defaults(func=_cmd_update) - - -def _common(p: argparse.ArgumentParser) -> None: - p.add_argument( - "--namespace", required=True, help="The namespace the source's documents live in" - ) - p.add_argument("--org", default="", help="Default: the token's org") - p.add_argument("--server-url", default=default_base_url()) - p.add_argument("--token", default=None, help="JWT (default: $LOOM_API_KEY, ~/.loom/token)") - - -def _items(p: argparse.ArgumentParser, prefix: str = "", verb: str = "read") -> None: - p.add_argument( - f"--{prefix}link", action="append", default=[], help=f"A link to {verb}; repeatable" + parser.add_argument( + "--token-file", help="Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY." ) - p.add_argument( - f"--{prefix}item-json", - action="append", - default=[], - help=f'An item to {verb} as JSON, such as {{"type": "folder", "id": "..."}}; repeatable', + parser.add_argument( + "--session-file", + required=True, + help="Existing application-owned private session pointer; " + "never initialized by this command.", ) - - -def _include(p: argparse.ArgumentParser) -> None: - p.add_argument( - "--include", - action="append", - default=None, - help="gdrive: a file kind to read (docs, slides, pdf, pptx, docx); repeatable", + parser.add_argument( + "--intent", + choices=("automatic", "explicit"), + default="automatic", + help="Default automatic guards every call; explicit is a direct user action.", ) - - -def _item_objects(values: list[str], flag: str = "--item-json") -> list[dict[str, Any]] | None: - """The items as objects, or None (with the reason printed) when one is not one.""" - out = [] - for value in values: - try: - item = json.loads(value) - except ValueError: - item = None - if not isinstance(item, dict): - print(f"{flag}: not a JSON object: {value[:80]}", file=sys.stderr) - return None - out.append(item) - return out - - -def _phrase(status: int) -> str: + if (group, action) == ("connection", "connect"): + parser.add_argument( + "--bearer-file", + help="Owned mode-0600 credential file or - for stdin. Never an argv secret.", + ) + if (group, action) == ("recording", "add"): + parser.add_argument( + "--credential-file", + required=True, + help="Owned mode-0600 credential file or - for stdin. Never an argv secret.", + ) + parser.set_defaults(func=_dispatch) + + +def _dispatch(args: argparse.Namespace) -> int: try: - return HTTPStatus(status).phrase - except ValueError: - return "" - - -def _call(args: argparse.Namespace, op: str, body: dict[str, Any]) -> int: - token, source = resolve_token(args.token) - if refused_for_agent(source): - return 2 - org = args.org or str(jwt_claims(token).get("org") or "") - if not org: - print("Could not infer org from the token; pass --org.", file=sys.stderr) - return 2 - status, out = post_op( - args.server_url, op, {"org": org, "namespace": args.namespace, **body}, token - ) - if status == 0: - print(f"{op} → no Loom answer: {out.get('detail', '')}", file=sys.stderr) - return 1 - if status != 200: - phrase = _phrase(status) - detail = out.get("detail") - # A string detail here is another server's page (a proxy's), never printed. - line = detail_line(status, phrase, None if isinstance(detail, str) else detail) - print(f"{op} → {line}", file=sys.stderr) - return 1 - print(json.dumps(out, indent=2, sort_keys=True)) - return 0 - - -def _cmd_list(args: argparse.Namespace) -> int: - return _call(args, "knowledge.source.list", {}) - - -def _cmd_add(args: argparse.Namespace) -> int: - if not args.link and not args.item_json: - print("give --link or --item-json", file=sys.stderr) - return 2 - items = _item_objects(args.item_json) - if items is None: - return 2 - path = args.credential_file - try: - credential = sys.stdin.read() if path == "-" else Path(path).read_text(encoding="utf-8") - except (OSError, UnicodeDecodeError) as e: - why = "not UTF-8 text" if isinstance(e, UnicodeDecodeError) else e.strerror - print(f"--credential-file: cannot read {path} ({why})", file=sys.stderr) - return 2 - body: dict[str, Any] = { - "name": args.name, - "kind": args.kind, - "credential": credential.strip(), - "dry_run": args.dry_run, - } - if items: - body["items"] = items - if args.link: - body["links"] = args.link - if args.include: - body["include"] = args.include - return _call(args, "knowledge.source.add", body) - - -def _cmd_update(args: argparse.Namespace) -> int: - added = _item_objects(args.item_json) - removed = _item_objects(args.remove_item_json, "--remove-item-json") - if added is None or removed is None: - return 2 - body: dict[str, Any] = { - "name": args.name, - "add_items": added, - "add_links": args.link, - "remove_items": removed, - "remove_links": args.remove_link, - } - if args.include: - body["include"] = args.include - return _call(args, "knowledge.source.update", body) - - -__all__ = ["register_knowledge_source_cli"] + entry = importlib.import_module("loom.source_cli") + except ImportError: + entry = None + if entry is not None and getattr(entry, "SOURCE_CLI_API", None) == _SOURCE_CLI_API: + from server.cli import _session_context + + if _session_context._explicit(): + args = argparse.Namespace(**{**vars(args), "intent": "explicit"}) + return int(entry.run_server_entry(args)) + print(_DEPENDENCY_MESSAGE, file=sys.stderr) + return 2 diff --git a/server/cli/login.py b/server/cli/login.py index eadcbdd2f0..588256d5af 100644 --- a/server/cli/login.py +++ b/server/cli/login.py @@ -20,6 +20,14 @@ def run_sdk_command(argv: list[str]) -> int: + from server.cli import _session_context + + if _session_context.configured(): + try: + _session_context.require_sdk() + except _session_context.CLIContextError as exc: + print(str(exc), file=sys.stderr) + return 2 try: from loom.cli import main except ImportError: diff --git a/server/cli/okf.py b/server/cli/okf.py index c1a79cd7db..fb725b0900 100644 --- a/server/cli/okf.py +++ b/server/cli/okf.py @@ -37,7 +37,6 @@ from __future__ import annotations import argparse -import asyncio import math import sys from collections import Counter @@ -130,7 +129,16 @@ async def post(self, op: str, body: dict[str, Any]) -> dict[str, Any]: import httpx try: - r = await self._c.post(f"/v1/{op}", json=body) + from server.cli import _session_context + + auth = self._c.headers.get("Authorization", "") + r = await _session_context.post( + self._c, + str(self._c.base_url.join(f"/v1/{op}")), + auth[7:] if auth.startswith("Bearer ") else "", + body=body, + timeout_s=60.0, + ) except httpx.HTTPError as e: raise RuntimeError(f"{op} → no answer ({type(e).__name__}: {e})") from e if r.status_code != 200: @@ -640,7 +648,9 @@ async def _go() -> int: print(" validate with: okf validate", out_dir, "--drift") return 0 - return asyncio.run(_go()) + from server.cli._session_context import run_async + + return run_async(_go) # ------------------------------------------------------------------ @@ -1319,7 +1329,9 @@ async def _go() -> int: failures = ("failed", "links_failed", "prune_failed", "evidence_failed", "verify_failed") return 1 if any(n[k] for k in failures) else 0 - return asyncio.run(_go()) + from server.cli._session_context import run_async + + return run_async(_go) # ------------------------------------------------------------------ diff --git a/server/cli/shell.py b/server/cli/shell.py index 1cf3653345..4322c50674 100644 --- a/server/cli/shell.py +++ b/server/cli/shell.py @@ -29,7 +29,6 @@ def _cmd_memory_search(args: argparse.Namespace) -> int: {"command": "search", "query": ..., "results": [...]} envelope for line-oriented-JSON pipelines. """ - import asyncio import json as _json import sys @@ -56,11 +55,20 @@ def _cmd_memory_search(args: argparse.Namespace) -> int: async def _go() -> int: async with httpx.AsyncClient(timeout=30.0) as client: try: - r = await client.post( - f"{args.server_url}/v1/memory.search", - json=body, - headers=headers, - ) + from server.cli import _session_context + + if _session_context.configured(): + r = await _session_context.post( + client, + f"{args.server_url}/v1/memory.search", + token, + body=body, + timeout_s=30.0, + ) + else: + r = await client.post( + f"{args.server_url}/v1/memory.search", json=body, headers=headers + ) except httpx.HTTPError as e: # refused, timed out, dropped print( f" ✗ memory.search: no answer from {args.server_url} ({type(e).__name__})", @@ -115,7 +123,9 @@ async def _go() -> int: print(f" {excerpt}") return 0 - return asyncio.run(_go()) + from server.cli._session_context import run_async + + return run_async(_go) def _default_thread_id(src: Path) -> str: @@ -267,6 +277,16 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: headers=headers, method="POST", ) + from server.cli import _session_context + + protected = _session_context.send(req, 15.0) + if protected is not None: + status, _ = protected + if status != 200: + print(f"ERROR: turn {i} failed: HTTP {status}", file=sys.stderr) + return 6 + written += 1 + continue try: with urllib.request.urlopen(req, timeout=15) as resp: resp.read() diff --git a/tests/integration/mcp_source_qualification_fixtures.py b/tests/integration/mcp_source_qualification_fixtures.py new file mode 100644 index 0000000000..27aacc7101 --- /dev/null +++ b/tests/integration/mcp_source_qualification_fixtures.py @@ -0,0 +1,361 @@ +"""Real application and store fixtures for the hosted finite MCP qualification.""" + +from __future__ import annotations + +import asyncio +import json +import os +from collections.abc import AsyncIterator +from contextlib import AsyncExitStack, asynccontextmanager +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import httpx +import pytest +import pytest_asyncio +from loom.session_protection import SessionProtection +from loom.transport import Transport + +from server.auth.jwt import mint_token +from server.clients import mcp_source +from server.core.ch import get_client, set_query_tag +from server.embedding.embedder import get_embedder +from server.knowledge.app import mcp_connections, mcp_profiles, source_sync +from server.knowledge.domain.mcp_identity import resource_uri +from server.knowledge.store import documents +from server.knowledge.store import sources as source_store +from tests.integration._resources import unique_org +from tests.integration.mcp_source_qualification_servers import ( + SECOND, + SELECTED, + SourceTransport, + SyntheticSource, +) + + +@dataclass +class Reader: + org: str + subject: str + transport: Transport + protection: SessionProtection + + async def call(self, op: str, **body: Any) -> dict[str, Any]: + set_query_tag("test.mcp_source_qualification.api") + return await self.transport.post("/v1/" + op, {"org": self.org, **body}) + + +@asynccontextmanager +async def reader(app: Any, base: Path, org: str, subject: str) -> AsyncIterator[Reader]: + protection = SessionProtection.create(base=base) + token = mint_token( + subject, + org, + ["*"], + ["admin"], + ttl_seconds=1800, + is_service_account=False, + session_id=str(uuid4()), + ) + transport = Transport( + "https://loom-qualification.example", + api_key=token, + pacing=False, + retry={"max_attempts": 1}, + session_protection=protection, + ) + # Preserve every SDK header and hook when replacing the HTTP connection. + original = transport._client + await original.aclose() + transport._client = httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), + base_url=transport.base_url, + headers=original.headers, + auth=original.auth, + timeout=60, + event_hooks=original.event_hooks, + ) + try: + yield Reader(org, subject, transport, protection) + finally: + await transport._client.aclose() + + +@pytest_asyncio.fixture +async def qualification_app() -> AsyncIterator[Any]: + # These checks run before importing the application or connecting to a store. + if not os.environ.get("LOOM_MCP_SOURCE_QUALIFICATION"): + pytest.skip("requires the owned hosted MCP qualification stores") + assert os.environ.get("LOOM_MCP_SOURCE_QUALIFICATION") == "github-owned" + assert os.environ.get("GITHUB_ACTIONS") == "true" + assert os.environ.get("RUNNER_ENVIRONMENT") == "github-hosted" + assert os.environ.get("LOOM_CH_HOST") == "127.0.0.1" + from server.main import app + from server.settings import settings + + assert settings.auth_actually_required() + assert settings.background_workers == "off" + assert settings.llm_provider == "fake" + assert settings.embedding_model == "fake-ngram-1024" + assert not settings.llm_fallback_model.strip() + assert settings.document_object_store == "s3" + await asyncio.to_thread(require_source_checkout) + async with app.router.lifespan_context(app): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=app), base_url="https://loom-qualification.example" + ) as client: + health = await client.get("/v1/health") + assert health.status_code == 200 + status = health.json() + assert status["readiness"]["ready"] is True + assert status["fake_embedding"] is status["fake_llm"] is True + assert status["build_commit"] == os.environ["QUALIFICATION_SHA"] + denied = await client.post("/v1/knowledge.get", json={}) + assert denied.status_code == 401 + yield app + + +def require_source_checkout() -> None: + import server + + assert Path(server.__file__).resolve().parent == Path.cwd() / "server" + + +@dataclass +class CatalogInput: + current: mcp_profiles.MCPProfileCatalog + + +@dataclass +class World: + owner: Reader + other: Reader + foreign: Reader + source: SyntheticSource + namespace: str + team: str + child: str + catalog: CatalogInput + embed_calls: list[int] = field(default_factory=list) + slot: str = "" + entry: dict[str, Any] = field(default_factory=dict) + private_marker: str = "" + + def __post_init__(self) -> None: + if not self.private_marker: + self.private_marker = self.source.marker + + @property + def uri(self) -> str: + return resource_uri(self.entry["source_id"], SELECTED) + + async def add( + self, + *, + mode: str = "selected_refresh", + copy: bool = False, + namespace: str | None = None, + ids: list[str] | None = None, + confirm: bool | None = None, + ) -> dict[str, Any]: + reads = list(self.source.reads) + output = await self.owner.call( + "knowledge.source.mcp_add", + namespace=namespace or self.namespace, + slot=self.slot, + mode=mode, + reader_policy="collection_copy" if copy else "owner_only", + resource_ids=ids or [SELECTED], + request_id=str(uuid4()), + confirm_copy_authority=copy if confirm is None else confirm, + ) + self.entry = output["source"] + assert self.source.reads == reads + for table in ("documents", "chunks"): + set_query_tag("test.mcp_source_qualification.registration") + assert await get_client().query_one( + f"SELECT count() AS count FROM loom.{table} WHERE org = {{org:String}} " + "AND source_uri = {uri:String}", + params={"org": self.owner.org, "uri": self.uri}, + ) == {"count": 0} + return output + + async def source_row(self) -> Any: + row = await source_store.get_source( + self.owner.org, self.entry["namespace"], self.entry["name"] + ) + assert row is not None + assert row.config == {} and row.items == [] + assert row.kind == "mcp" and row.source_id == self.entry["source_id"] + return row + + async def sync(self) -> Any: + row = await self.source_row() + states = await source_sync._states([row]) + state = states.get(source_sync._cursor_of(row), {}) + result = await source_sync._sync_one( + row, state, source_sync.Pass(source_sync._budget(), left=8), source_sync.PassResult() + ) + assert result is not None + return result + + async def head(self, identity: str = SELECTED) -> Any: + row = await self.source_row() + assert row.mirror + uri = resource_uri(row.source_id, identity) + found = await documents.get_many_by_uris(row.org, row.mirror, [uri]) + assert len(found) == 1 + return found[0] + + async def chunks(self) -> list[dict[str, Any]]: + row = await self.source_row() + return await get_client().query_all( + "SELECT chunk_idx, content, embedding_model, embedding_dim, embedding, doc_version " + "FROM loom.chunks WHERE org = {org:String} AND namespace = {namespace:String} " + "AND source_uri = {uri:String} ORDER BY doc_version, chunk_idx LIMIT 64", + params={"org": row.org, "namespace": row.mirror, "uri": self.uri}, + ) + + async def control(self, action: str, **body: Any) -> dict[str, Any]: + result = await self.owner.call( + "knowledge.source.mcp_" + action, + namespace=self.entry["namespace"], + name=self.entry["name"], + **body, + ) + if "source" in result: + self.entry = result["source"] + return result + + async def get(self, who: Reader | None = None, **body: Any) -> dict[str, Any]: + return await (who or self.owner).call( + "knowledge.get", namespace=self.entry["namespace"], source_uri=self.uri, **body + ) + + async def download(self, who: Reader | None = None) -> httpx.Response: + actor = who or self.owner + return await actor.transport.download( + "/v1/knowledge.download", + params={"org": actor.org, "namespace": self.entry["namespace"], "source_uri": self.uri}, + ) + + +async def initialize(world: World) -> None: + for namespace, parent in ((world.namespace, ""), (world.team, ""), (world.child, world.team)): + set_query_tag("test.mcp_source_qualification.setup") + await world.owner.call("collection.create", namespace=namespace, parent=parent) + # A real collection grant makes same-collection source isolation nontrivial. + for namespace in (world.namespace, world.team): + set_query_tag("test.mcp_source_qualification.setup") + await world.owner.call( + "grants.create", namespace=namespace, subject=world.other.subject, role="viewer" + ) + connected = await world.owner.call( + "knowledge.connection.mcp_connect", + profile_id="qualification-" + world.source.kind, + request_id=str(uuid4()), + bearer=world.source.bearer, + ) + world.slot = connected["connection"]["slot"] + assert connected["connection"]["state"] == "configured" + + +@pytest_asyncio.fixture +async def world( + request: pytest.FixtureRequest, + qualification_app: Any, + tmp_path: Path, +) -> AsyncIterator[World]: + source = SyntheticSource(request.param, json_response=request.param == "resources") + org, foreign_org = unique_org("mcp-qualification"), unique_org("mcp-qualification-other") + catalog = CatalogInput( + mcp_profiles.MCPProfileCatalog.parse( + json.dumps({"version": 1, "profiles": [source.profile([org, foreign_org])]}) + ) + ) + patch = pytest.MonkeyPatch() + embed_calls: list[int] = [] + try: + install_transport(patch, source, catalog) + install_embedding_counter(patch, embed_calls) + async with AsyncExitStack() as stack: + await stack.enter_async_context(source.application()) + owner = await stack.enter_async_context( + reader(qualification_app, tmp_path / "owner", org, "owner@example.test") + ) + other = await stack.enter_async_context( + reader(qualification_app, tmp_path / "other", org, "other@example.test") + ) + foreign = await stack.enter_async_context( + reader(qualification_app, tmp_path / "foreign", foreign_org, "owner@example.test") + ) + prefix = "col-q-" + uuid4().hex[:12] + result = World( + owner, + other, + foreign, + source, + prefix, + prefix + "-team", + prefix + "-child", + catalog, + embed_calls, + ) + await initialize(result) + yield result + finally: + source.release.set() + patch.undo() + assert source.in_flight == 0 + + +def install_transport( + patch: pytest.MonkeyPatch, source: SyntheticSource, catalog: CatalogInput +) -> None: + real_init = mcp_source.MCPSourceClient.__init__ + + def injected_init(self: Any, *args: Any, **kwargs: Any) -> None: + assert "_transport" not in kwargs + real_init(self, *args, **kwargs, _transport=SourceTransport([source])) + + async def pin(url: str, **kwargs: Any) -> tuple[str, str, str, str]: + assert url == source.endpoint and kwargs == {"schemes": ("https",)} + return "", "https://203.0.113.8/mcp", source.host, source.host + + patch.setattr(mcp_source.MCPSourceClient, "__init__", injected_init) + patch.setattr(mcp_source, "pinned_target", pin) + # Trusted operator input uses the actual parser and binding checks. + patch.setattr(mcp_profiles, "load_mcp_profile_catalog", lambda: catalog.current) + patch.setattr(mcp_connections, "load_mcp_profile_catalog", lambda: catalog.current) + + +def install_embedding_counter(patch: pytest.MonkeyPatch, embed_calls: list[int]) -> None: + embedder = get_embedder() + embed_many = type(embedder).embed_many + + async def counted(self: Any, texts: list[str]) -> list[list[float]]: + embed_calls.append(len(texts)) + return await embed_many(self, texts) + + patch.setattr(type(embedder), "embed_many", counted) + + +async def cancel_owned(task: asyncio.Task[Any], source: SyntheticSource) -> None: + task.cancel() + source.release.set() + try: + async with asyncio.timeout(10): + await task + except asyncio.CancelledError: + pass + assert task.done() and source.in_flight == 0 + + +def require_clean_selection(world: World) -> None: + assert set(world.source.reads) <= {SELECTED, SECOND} + assert not any( + name not in {"read_document", "search_documents", "resources/list"} + for name in world.source.calls + ) diff --git a/tests/integration/mcp_source_qualification_servers.py b/tests/integration/mcp_source_qualification_servers.py new file mode 100644 index 0000000000..c78f0a36f7 --- /dev/null +++ b/tests/integration/mcp_source_qualification_servers.py @@ -0,0 +1,269 @@ +"""Owned SDK protocol fixtures; no public endpoint or provider is contacted.""" + +from __future__ import annotations + +import asyncio +import copy +import json +import secrets +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager +from dataclasses import dataclass, field +from typing import Any + +import httpx +from mcp import types +from mcp.server.fastmcp import FastMCP +from mcp.server.lowlevel import Server +from mcp.server.streamable_http_manager import StreamableHTTPSessionManager +from mcp.server.transport_security import TransportSecuritySettings +from starlette.applications import Starlette +from starlette.responses import JSONResponse +from starlette.routing import Route +from starlette.types import ASGIApp, Receive, Scope, Send + +SELECTED = "qualification://documents/selected" +SECOND = "qualification://documents/second" +UNSELECTED = "qualification://documents/unselected" + + +def object_schema(properties: dict[str, Any], required: list[str]) -> dict[str, Any]: + return { + "type": "object", + "properties": properties, + "required": required, + "additionalProperties": False, + } + + +STRING = {"type": "string", "maxLength": 4096} +DOCUMENT = object_schema( + {key: STRING for key in ("id", "title", "text", "uri")}, ["id", "title", "text", "uri"] +) +READ_INPUT = object_schema({"id": STRING}, ["id"]) +SEARCH_INPUT = object_schema({"query": STRING, "cursor": STRING}, ["query"]) +SEARCH_OUTPUT = object_schema( + {"items": {"type": "array", "items": DOCUMENT, "maxItems": 3}, "next_cursor": STRING}, + ["items"], +) + + +@dataclass +class SyntheticSource: + kind: str + json_response: bool = True + bearer: str = field(default_factory=lambda: secrets.token_hex(32), repr=False) + marker: str = field(default_factory=lambda: "qualificationcontent" + secrets.token_hex(12)) + text: str = "" + denied: bool = False + drift: bool = False + partial: bool = False + block_read: bool = False + reads: list[str] = field(default_factory=list) + calls: list[str] = field(default_factory=list) + started: asyncio.Event = field(default_factory=asyncio.Event) + release: asyncio.Event = field(default_factory=asyncio.Event) + in_flight: int = 0 + app: ASGIApp | None = field(default=None, repr=False) + + def __post_init__(self) -> None: + self.text = "# Selected document\n\n" + self.marker + " café 日本語.\n" + + @property + def host(self) -> str: + return self.kind + ".mcp-qualification.example" + + @property + def endpoint(self) -> str: + return "https://" + self.host + "/mcp" + + async def read(self, identity: str) -> str: + assert identity in {SELECTED, SECOND}, "Unselected content must never be read" + self.reads.append(identity) + self.in_flight += 1 + self.started.set() + try: + if self.block_read: + await self.release.wait() + return self.text if identity == SELECTED else "Second selected document." + finally: + self.in_flight -= 1 + + def profile(self, orgs: list[str], *, copy_allowed: bool = True) -> dict[str, Any]: + config: dict[str, Any] = { + "endpoint": self.endpoint, + "bearer_audience": self.endpoint, + "limits": {"timeout_seconds": 20, "request_seconds": 10, "max_pages": 2}, + } + if self.kind == "tools": + config.update( + approved_tools=["search_documents", "read_document"], + read={ + "name": "read_document", + "input_schema": READ_INPUT, + "output_schema": DOCUMENT, + "argument_name": "id", + }, + search={ + "name": "search_documents", + "input_schema": SEARCH_INPUT, + "output_schema": SEARCH_OUTPUT, + "argument_name": "query", + "items_path": ["items"], + "cursor_argument": "cursor", + "next_cursor_path": ["next_cursor"], + }, + ) + return { + "id": "qualification-" + self.kind, + "label": "Synthetic MCP source", + "auth": "bearer", + "allowed_orgs": orgs, + "allow_collection_copy": copy_allowed, + "config": config, + } + + def resource_server(self) -> FastMCP: + server = FastMCP( + "Qualification resources", + stateless_http=True, + json_response=self.json_response, + transport_security=TransportSecuritySettings(allowed_hosts=[self.host]), + ) + + @server.resource(SELECTED, name="Selected synthetic document") + async def selected() -> str: + return await self.read(SELECTED) + + @server.resource(SECOND, name="Second synthetic document") + async def second() -> str: + return await self.read(SECOND) + + @server.resource(UNSELECTED, name="Unselected synthetic document") + async def unselected() -> str: + raise AssertionError("Unselected resource was read") + + original = server._mcp_server.request_handlers[types.ListResourcesRequest] + + async def listing(request: types.ListResourcesRequest) -> types.ServerResult: + self.calls.append("resources/list") + result = await original(request) + if self.partial: + assert isinstance(result.root, types.ListResourcesResult) + result.root.resources = result.root.resources[:1] + result.root.nextCursor = "unfinished" + return result + + server._mcp_server.request_handlers[types.ListResourcesRequest] = listing + + return server + + def tool_server(self) -> Server: + # The low-level SDK server exercises a separate dispatch implementation. + server = Server("Qualification mapped tools") + + @server.list_tools() + async def list_tools() -> list[types.Tool]: + schema = copy.deepcopy(READ_INPUT) + if self.drift: + schema["properties"]["id"]["maxLength"] = 64 + return [ + types.Tool(name="read_document", inputSchema=schema, outputSchema=DOCUMENT), + types.Tool( + name="search_documents", inputSchema=SEARCH_INPUT, outputSchema=SEARCH_OUTPUT + ), + ] + + @server.call_tool() + async def call_tool(name: str, arguments: dict[str, Any]) -> types.CallToolResult: + self.calls.append(name) + if name == "read_document": + identity = arguments["id"] + text = await self.read(identity) + result: dict[str, Any] = { + "id": identity, + "uri": identity, + "title": "Selected synthetic document", + "text": text, + } + else: + assert name == "search_documents" + result = { + "items": [ + { + "id": identity, + "uri": identity, + "title": "Search result", + "text": "Search snippet only", + } + for identity in (SELECTED, UNSELECTED) + ], + } + if self.partial: + result["next_cursor"] = "unfinished" + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(result))], + structuredContent=result, + ) + + return server + + @asynccontextmanager + async def application(self) -> AsyncIterator[None]: + if self.kind == "resources": + app = self.resource_server().streamable_http_app() + async with app.router.lifespan_context(app): + self.app = app + try: + yield + finally: + self.release.set() + self.app = None + else: + manager = StreamableHTTPSessionManager( + app=self.tool_server(), + json_response=self.json_response, + stateless=True, + security_settings=TransportSecuritySettings(allowed_hosts=[self.host]), + ) + + class Endpoint: + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + await manager.handle_request(scope, receive, send) + + async with manager.run(): + self.app = Starlette( + routes=[Route("/mcp", Endpoint(), methods=["POST", "GET", "DELETE"])] + ) + try: + yield + finally: + self.release.set() + self.app = None + assert self.in_flight == 0 + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + assert self.app is not None + assert scope["path"] == "/mcp" + headers = dict(scope["headers"]) + assert headers[b"host"] == self.host.encode() + if self.denied or headers.get(b"authorization") != ("Bearer " + self.bearer).encode(): + await JSONResponse({"error": "Synthetic refusal"}, status_code=403)( + scope, receive, send + ) + return + await self.app(scope, receive, send) + + +class SourceTransport(httpx.AsyncBaseTransport): + """Only owned canonical fixture names can reach the in-process SDK servers.""" + + def __init__(self, sources: list[SyntheticSource]) -> None: + self.sources = {source.host: source for source in sources} + + async def handle_async_request(self, request: httpx.Request) -> httpx.Response: + # The real pinned transport changes the connect address, retaining Host/SNI. + source = self.sources[request.headers["host"]] + assert request.url.host == "203.0.113.8" + assert request.extensions["sni_hostname"] in {source.host, source.host.encode()} + return await httpx.ASGITransport(app=source).handle_async_request(request) diff --git a/tests/integration/mcp_source_scale_acceptance.py b/tests/integration/mcp_source_scale_acceptance.py new file mode 100644 index 0000000000..5edbe267d7 --- /dev/null +++ b/tests/integration/mcp_source_scale_acceptance.py @@ -0,0 +1,233 @@ +"""Frozen hosted source scheduling workload; never imported by local validation.""" + +from __future__ import annotations + +import asyncio +import time +from contextlib import AsyncExitStack +from dataclasses import asdict +from datetime import UTC, datetime +from functools import partial +from pathlib import Path +from typing import Any + +import pytest + +from scripts.ops.qualify_mcp_source_scale import accepted +from server.core.ch import get_client, set_query_tag +from server.knowledge.app import source_sync +from server.knowledge.app.mcp_source_schedule import PROGRESS_WORKER, run_pass +from server.knowledge.store.mcp_source_schedule import candidate_page +from server.settings import settings +from server.workers import status_store +from tests.integration.mcp_source_qualification_fixtures import qualification_app +from tests.integration.mcp_source_scale_fixtures import ( + ScaleWorld, + catalog_latencies, + operator_limits, + query_limits, + setup_world, +) +from tests.integration.mcp_source_scale_metrics import Sampler, percentiles, store_work + +__all__ = ["qualification_app"] + + +async def source_copy_count(case: Any) -> int: + set_query_tag("worker.knowledge_source_sync") + row = await get_client().query_one( + "SELECT count() AS n FROM loom.documents FINAL WHERE org = {org:String} " + "AND namespace = {ns:String} AND source_uri = {uri:String}", + params={"org": case.owner.org, "ns": (await case.source_row()).mirror, "uri": case.uri}, + ) + assert row is not None + return int(row["n"]) + + +async def cancellation_and_overlap(world: ScaleWorld) -> dict[str, float | int]: + case = next(case for case in world.eligible.values() if case.source.role == "healthy") + source = case.source + assert await source_copy_count(case) == 0 + source.hold = True + source.started.clear() + source.release.clear() + task = asyncio.create_task(case.sync()) + joined = 0.0 + try: + async with asyncio.timeout(10): + await source.started.wait() + # Both turns use the actual source lease against the job's own Keeper. + async with asyncio.timeout(5): + overlap = await case.sync() + assert overlap is None and not task.done() + started = time.monotonic() + task.cancel() + async with asyncio.timeout(5): + await asyncio.gather(task, return_exceptions=True) + joined = time.monotonic() - started + assert task.cancelled() and source.in_flight == 0 + assert await source_copy_count(case) == 0 + finally: + source.hold = False + source.release.set() + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + return {"cancel_join_seconds": joined, "overlap_fenced": 1} + + +async def scheduled_pass(world: ScaleWorld) -> tuple[dict[str, int], bool]: + budget = source_sync._budget() + parent = source_sync.Pass(budget, left=settings.knowledge_source_sync_documents_per_pass) + metrics = await run_pass( + limits=operator_limits(), + parent=parent, + make_pass=lambda credits: source_sync.Pass(budget, left=credits), + execute=world.execute, + endpoint_key=world.endpoint_key, + deadline=min(budget.stop_after, world.started + 600), + page=partial(candidate_page, query_limits=query_limits()), + progress_timeout=query_limits().seconds, + ) + observed = await status_store.resume_cursor(PROGRESS_WORKER) + assert observed.startswith("mcp1:") + return asdict(metrics), observed == "mcp1:" + "0" * 64 + + +async def refresh_rounds(world: ScaleWorld, result: Any) -> dict[str, float | int]: + world.started = time.monotonic() + peaks = { + key: 0 + for key in ("queue_highwater", "inflight_highwater", "org_highwater", "endpoint_highwater") + } + # This finite census bounds the number of pass restarts independently of time. + passes = 2 * (len(world.eligible) + operator_limits().ready + 1) + for _ in range(passes): + set_query_tag("worker.knowledge_source_sync") + if time.monotonic() - world.started >= 600: + break + metrics, wrapped = await scheduled_pass(world) + world.failed_turns += metrics["failed"] + metrics["timed_out"] + for key in peaks: + peaks[key] = max(peaks[key], metrics[key]) + result.record( + **peaks, healthy_completed=len(world.healthy_done), failed_turns=world.failed_turns + ) + if wrapped: + world.round += 1 + if len(world.attempted) == len(world.eligible) and len(world.healthy_done) == 200: + break + if world.round > 2: + break + elapsed = time.monotonic() - world.started + assert len(world.attempted) == 1000 + return { + **peaks, + **percentiles(world.live_latencies, "live"), + **percentiles(world.refresh_latencies, "refresh"), + "healthy_completed": len(world.healthy_done), + "refresh_all_seconds": elapsed, + "healthy_tenants_completed": len(world.first_tenant), + "healthy_tenant_first_max": max(value[0] for value in world.first_tenant.values()), + "healthy_tenant_first_round_max": max(value[1] for value in world.first_tenant.values()), + "throughput": len(world.healthy_done) / elapsed, + "failed_turns": world.failed_turns, + "restart_restored": 1, + "original_readbacks": world.original_readbacks, + } + + +async def persisted_copies(world: ScaleWorld) -> dict[str, int]: + result: dict[str, int] = {} + for table, key in (("documents", "document_count"), ("chunks", "chunk_count")): + set_query_tag("worker.knowledge_source_sync") + row = await get_client().query_one( + f"SELECT count() AS n FROM loom.{table} FINAL WHERE org IN {{orgs:Array(String)}}", + params={"orgs": world.orgs}, + ) + assert row is not None + result[key] = int(row["n"]) + return result + + +async def workload(world: ScaleWorld, result: Any, app: Any, base: Path) -> None: + for index, org in enumerate(world.orgs): + for user in range(2): + set_query_tag("worker.knowledge_source_sync") + await world.seed_owner(app, base / str(index) / str(user), org, user) + counts = await world.counts() + result.record( + **counts, + healthy_eligible=200, + healthy_tenants=10, + endpoint_count=10, + rate_limited_endpoints=2, + denied_endpoints=2, + malformed_endpoints=2, + stalled_endpoints=2, + ) + assert counts["registered"] == counts["registered_distinct"] == 10000 + assert counts["eligible"] == counts["eligible_distinct"] == len(world.eligible) == 1000 + result.record(**await cancellation_and_overlap(world)) + for source in world.sources: + source.faults_enabled = True + async with asyncio.TaskGroup() as group: + refresh = group.create_task(refresh_rounds(world, result)) + catalog = group.create_task(catalog_latencies(world)) + result.record(**refresh.result(), **percentiles(catalog.result(), "catalog")) + result.record(**await persisted_copies(world)) + + +@pytest.mark.asyncio +async def test_source_scale_contract(qualification_app: Any, tmp_path: Path, request: Any) -> None: + result = request.config._mcp_scale_result + limits = operator_limits() + assert ( + limits.page_size, + limits.ready, + limits.global_inflight, + limits.per_org, + limits.per_endpoint, + ) == (100, 256, 16, 4, 2) + assert limits.documents == 1 and limits.source_seconds == 5 + assert query_limits().rows == 1000000 and query_limits().bytes == 67108864 + started = datetime.now(UTC).isoformat() + sampler, patch = Sampler(), pytest.MonkeyPatch() + await sampler.start() + # Prime the ordinary status writer before the ownership baseline; its lifecycle belongs to the app. + now = datetime.now(UTC) + await status_store.record_manual_pass( + PROGRESS_WORKER, + namespace="", + status="ok", + started=now, + finished=now, + resume_cursor="mcp1:" + "0" * 64, + ) + baseline = set(asyncio.all_tasks()) + world: ScaleWorld | None = None + teardown_started = 0.0 + try: + async with AsyncExitStack() as stack: + world = await setup_world(stack, patch) + try: + await workload(world, result, qualification_app, tmp_path) + finally: + teardown_started = time.monotonic() + for source in world.sources: + source.release.set() + finally: + patch.undo() + teardown = time.monotonic() - teardown_started if teardown_started else 0.0 + await sampler.close() + residue = {task for task in asyncio.all_tasks() - baseline if not task.done()} + result.record( + **sampler.metrics(), + teardown_seconds=teardown, + owned_tasks_after_teardown=len(residue), + source_inflight_after_teardown=sum(source.in_flight for source in world.sources) + if world + else 0, + ) + result.record(**await store_work(started)) + assert accepted(result.metrics) diff --git a/tests/integration/mcp_source_scale_fixtures.py b/tests/integration/mcp_source_scale_fixtures.py new file mode 100644 index 0000000000..aa8bf53ca4 --- /dev/null +++ b/tests/integration/mcp_source_scale_fixtures.py @@ -0,0 +1,269 @@ +"""Real-store scale seeds and lazy source turns; registration throughput is excluded.""" + +from __future__ import annotations + +import hashlib +import json +import time +from contextlib import AsyncExitStack +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import httpx +import pytest + +from server.clients import mcp_source +from server.core.ch import get_client, set_query_tag +from server.knowledge.app import mcp_connections, mcp_profiles, source_sync +from server.knowledge.app.mcp_source_schedule import Limits +from server.knowledge.store import sources as source_store +from server.knowledge.store.mcp_source_schedule import Header, QueryLimits +from server.settings import settings +from tests.integration._resources import unique_org +from tests.integration.mcp_source_qualification_fixtures import CatalogInput, World, reader +from tests.integration.mcp_source_qualification_servers import SELECTED, SourceTransport +from tests.integration.mcp_source_scale_servers import ROLES, ScaleSource + + +def operator_limits() -> Limits: + return Limits( + page_size=settings.knowledge_source_mcp_schedule_page_size, + scan_pages=settings.knowledge_source_mcp_schedule_scan_pages, + ready=settings.knowledge_source_mcp_schedule_ready, + global_inflight=settings.knowledge_source_mcp_schedule_global, + per_org=settings.knowledge_source_mcp_schedule_per_org, + per_endpoint=settings.knowledge_source_mcp_schedule_per_endpoint, + documents=settings.knowledge_source_mcp_schedule_documents, + source_seconds=settings.knowledge_source_mcp_schedule_source_seconds, + ) + + +def query_limits() -> QueryLimits: + return QueryLimits( + settings.knowledge_source_mcp_schedule_query_rows, + settings.knowledge_source_mcp_schedule_query_bytes, + settings.knowledge_source_mcp_schedule_query_seconds, + ) + + +def inject(patch: pytest.MonkeyPatch, sources: list[ScaleSource], catalog: CatalogInput) -> None: + real_init = mcp_source.MCPSourceClient.__init__ + by_url = {source.endpoint: source for source in sources} + + def initialized(self: Any, *args: Any, **kwargs: Any) -> None: + assert "_transport" not in kwargs + real_init(self, *args, **kwargs, _transport=SourceTransport(sources)) + + async def pin(url: str, **kwargs: Any) -> tuple[str, str, str, str]: + source = by_url[url] + assert kwargs == {"schemes": ("https",)} + return "", "https://203.0.113.8/mcp", source.host, source.host + + patch.setattr(mcp_source.MCPSourceClient, "__init__", initialized) + patch.setattr(mcp_source, "pinned_target", pin) + patch.setattr(mcp_profiles, "load_mcp_profile_catalog", lambda: catalog.current) + patch.setattr(mcp_connections, "load_mcp_profile_catalog", lambda: catalog.current) + + +@dataclass +class ScaleWorld: + stack: AsyncExitStack + catalog: CatalogInput + sources: list[ScaleSource] + orgs: list[str] + eligible: dict[str, World] = field(default_factory=dict) + live: dict[str, World] = field(default_factory=dict) + owners: list[Any] = field(default_factory=list) + catalog_scopes: list[tuple[Any, str]] = field(default_factory=list) + healthy_done: set[str] = field(default_factory=set) + attempted: set[str] = field(default_factory=set) + first_tenant: dict[str, tuple[float, int]] = field(default_factory=dict) + live_latencies: list[float] = field(default_factory=list) + refresh_latencies: list[float] = field(default_factory=list) + failed_turns: int = 0 + original_readbacks: int = 0 + started: float = 0 + round: int = 1 + + def endpoint_key(self, header: Header) -> str: + profile = self.catalog.current.get(header.org, header.profile_id) + if profile.metadata.profile_sha256 != header.profile_sha256: + raise ValueError("scale_profile_changed") + endpoint = str(httpx.URL(json.loads(profile.config_snapshot)["config"]["endpoint"])) + return hashlib.sha256(endpoint.encode()).hexdigest() + + async def seed_owner(self, app: Any, base: Path, org: str, user: int) -> None: + owner = await self.stack.enter_async_context( + reader(app, base, org, f"owner{user}@example.test") + ) + self.owners.append(owner) + namespace = "col-scale-" + uuid4().hex + await owner.call("collection.create", namespace=namespace) + self.catalog_scopes.append((owner, namespace)) + for source in self.sources: + set_query_tag("worker.knowledge_source_sync") + connected = await owner.call( + "knowledge.connection.mcp_connect", + profile_id=source.profile([org])["id"], + request_id=str(uuid4()), + bearer=source.bearer, + ) + template = World( + owner, + owner, + owner, + source, + namespace, + namespace, + namespace, + self.catalog, + slot=connected["connection"]["slot"], + ) + await template.add() + await self.seed_sources(template) + + async def seed_sources(self, template: World) -> None: + source = await template.source_row() + original = json.loads(source.generic_config_json) + live: World | None = None + selected: list[World] = [] + for index in range(50): + set_query_tag("worker.knowledge_source_sync") + identity = source.source_id if index == 0 else str(uuid4()) + config = dict(original) + if index >= 5: + config["mode"] = "live" if index % 2 else "selected_refresh" + config["paused"] = index % 2 == 0 + if index == 49: + config["version"] = 2 + row = replace( + source, + source_id=identity, + name=source.name if index == 0 else "mcp-" + identity.replace("-", ""), + source_contract_version=2 if index == 49 else 1, + generic_config_json=json.dumps(config, separators=(",", ":")), + ) + if index: + await source_store.insert_source(row) + case = replace( + template, + entry={"source_id": identity, "name": row.name, "namespace": row.namespace}, + ) + if index < 5: + selected.append(case) + self.eligible[identity] = case + elif index == 5: + live = case + assert live is not None + for case in selected: + self.live[case.entry["source_id"]] = live + + async def counts(self) -> dict[str, int]: + set_query_tag("worker.knowledge_source_sync") + from server.knowledge.store.mcp_source_schedule import _ELIGIBLE + + row = await get_client().query_one( + "SELECT count() AS registered, uniqExact(source_id) AS registered_distinct, " + f"countIf({_ELIGIBLE}) AS eligible, " + f"uniqExactIf(source_id, {_ELIGIBLE}) AS eligible_distinct, " + "uniqExact(org) AS orgs, uniqExact(tuple(org, owner_subject)) AS users " + "FROM loom.knowledge_sources FINAL WHERE org IN {orgs:Array(String)}", + params={"orgs": self.orgs}, + ) + assert row is not None + return {key: int(value) for key, value in row.items()} + + async def execute(self, header: Header, run: source_sync.Pass) -> None: + self.attempted.add(header.source_id) + case = self.eligible[header.source_id] + assert (header.org, header.namespace, header.name) == ( + case.owner.org, + case.namespace, + case.entry["name"], + ) + set_query_tag("worker.knowledge_source_sync") + row = await case.source_row() + states = await source_sync._states([row]) + state = states.get(source_sync._cursor_of(row), {}) + refresh_started = time.monotonic() + turn = await source_sync._sync_one(row, state, run, source_sync.PassResult()) + assert turn is not None and turn.status == "ok" and turn.complete + refresh_seconds = time.monotonic() - refresh_started + if case.source.role != "healthy": + raise AssertionError("fault_fixture_unexpected_success") + if header.source_id not in self.healthy_done: + await self.verify_copy(case) + live_seconds = await self.read_live(header.source_id) + self.healthy_done.add(header.source_id) + self.live_latencies.append(live_seconds) + self.refresh_latencies.append(refresh_seconds) + self.first_tenant.setdefault(header.org, (time.monotonic() - self.started, self.round)) + + async def read_live(self, source_id: str) -> float: + live = self.live[source_id] + started = time.monotonic() + result = await live.owner.call( + "knowledge.source.mcp_read", + namespace=live.namespace, + name=live.entry["name"], + resource_id=SELECTED, + ) + assert result["text"] == live.source.text and len(result["text"].encode()) == 8192 + assert result["source_id"] == live.entry["source_id"] + return time.monotonic() - started + + async def verify_copy(self, case: World) -> None: + head = await case.head() + assert head.content == case.source.text and head.revision == 1 + chunks = await case.chunks() + assert chunks and all(len(chunk["embedding"]) == 1024 for chunk in chunks) + original = await case.download() + assert original.status_code == 200 and original.headers["x-loom-download-source"] == "blob" + assert original.content == case.source.text.encode() + self.original_readbacks += 1 + + +async def setup_world(stack: AsyncExitStack, patch: pytest.MonkeyPatch) -> ScaleWorld: + orgs = [unique_org("mcp-scale") for _ in range(10)] + sources = [ + ScaleSource(kind, json_response=kind == "resources", role=role) + for kind in ("resources", "tools") + for role in ROLES + ] + catalog = CatalogInput( + mcp_profiles.MCPProfileCatalog.parse( + json.dumps({"version": 1, "profiles": [source.profile(orgs) for source in sources]}) + ) + ) + inject(patch, sources, catalog) + for source in sources: + await stack.enter_async_context(source.application()) + return ScaleWorld(stack, catalog, sources, orgs) + + +async def catalog_latencies(world: ScaleWorld) -> list[float]: + values: list[float] = [] + # The actual owner API hydrates only its existing 20-row page, without a fixture list substitute. + for owner, namespace in world.catalog_scopes: + cursor = None + found: set[str] = set() + for _ in range(26): + set_query_tag("worker.knowledge_source_sync") + start = time.monotonic() + page = await owner.call( + "knowledge.source.mcp_list", namespace=namespace, limit=20, cursor=cursor + ) + values.append(time.monotonic() - start) + assert len(page["sources"]) <= 20 + for source in page["sources"]: + assert source["source_id"] not in found + found.add(source["source_id"]) + cursor = page.get("next_cursor") + if cursor is None: + break + else: + raise AssertionError("scale_catalog_did_not_terminate") + assert len(found) == 500 + return values diff --git a/tests/integration/mcp_source_scale_metrics.py b/tests/integration/mcp_source_scale_metrics.py new file mode 100644 index 0000000000..b07edc5688 --- /dev/null +++ b/tests/integration/mcp_source_scale_metrics.py @@ -0,0 +1,139 @@ +"""Content-free Linux process and owned-store measurements for hosted scale cases.""" + +from __future__ import annotations + +import asyncio +import json +import math +import os +import resource +from pathlib import Path + +from server.core.ch import get_client, set_query_tag + + +def percentiles(values: list[float], prefix: str) -> dict[str, float | int]: + assert values + values = sorted(values) + return { + prefix + "_count": len(values), + **{ + prefix + "_p" + str(p): values[max(0, math.ceil(p * len(values) / 100) - 1)] + for p in (50, 95, 99) + }, + } + + +def process_sample() -> tuple[int, int, float]: + usage = resource.getrusage(resource.RUSAGE_SELF) + peak = int(usage.ru_maxrss * 1024) + sockets = 0 + for fd in Path("/proc/self/fd").iterdir(): + try: + sockets += os.readlink(fd).startswith("socket:") + except FileNotFoundError: + continue + return peak, sockets, usage.ru_utime + usage.ru_stime + + +def _bytes(value: str) -> float: + for suffix, scale in (("GiB", 1024**3), ("MiB", 1024**2), ("KiB", 1024), ("B", 1)): + if value.endswith(suffix): + return float(value.removesuffix(suffix)) * scale + raise ValueError("scale_store_memory_unit") + + +async def store_sample() -> tuple[float, float]: + names = [os.environ["LOOM_CH_CONTAINER"], "mcp-source-scale-objects"] + if os.environ["LOOM_STORAGE_AUTHORITY"] == "postgres": + names += [os.environ["LOOM_PG_CONTAINER"], os.environ["LOOM_PG_CONTAINER"] + "-standby"] + process = await asyncio.create_subprocess_exec( + "docker", + "stats", + "--no-stream", + "--format", + "{{json .}}", + *names, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.DEVNULL, + ) + try: + async with asyncio.timeout(10): + output, _ = await process.communicate() + assert process.returncode == 0 and len(output) <= 16384 + rows = [json.loads(line) for line in output.splitlines()] + assert len(rows) == len(names) + return ( + sum(_bytes(row["MemUsage"].split(" / ")[0]) for row in rows), + sum(float(row["CPUPerc"].removesuffix("%")) for row in rows), + ) + finally: + if process.returncode is None: + process.kill() + await process.wait() + + +class Sampler: + def __init__(self) -> None: + self.rss = self.sockets = self.cpu = self.store_rss = self.store_cpu = 0.0 + self.idle = 0 + self.task: asyncio.Task[None] | None = None + self.samples = 0 + + async def sample(self) -> None: + rss, sockets, cpu = await asyncio.to_thread(process_sample) + self.rss, self.sockets, self.cpu = max(self.rss, rss), max(self.sockets, sockets), cpu + if self.samples % 20 == 0: + rss_store, cpu_store = await store_sample() + self.store_rss = max(self.store_rss, rss_store) + self.store_cpu = max(self.store_cpu, cpu_store) + self.samples += 1 + + async def start(self) -> None: + await self.sample() + self.idle = int(self.rss) + self.task = asyncio.create_task(self.loop()) + + async def loop(self) -> None: + set_query_tag("worker.knowledge_source_sync") + while True: + await asyncio.sleep(0.1) + await self.sample() + + async def close(self) -> None: + assert self.task is not None + self.task.cancel() + await asyncio.gather(self.task, return_exceptions=True) + # A sampler failure invalidates metrics rather than disappearing in gather. + if not self.task.cancelled(): + self.task.result() + await self.sample() + + def metrics(self) -> dict[str, float | int]: + return { + "process_peak": 1, + "rss_peak_bytes": self.rss, + "rss_delta_bytes": max(0, self.rss - self.idle), + "cpu_seconds": self.cpu, + "process_sockets_peak": self.sockets, + "source_sockets_peak": 0, + "store_rss_peak_bytes": self.store_rss, + "store_cpu_percent_peak": self.store_cpu, + } + + +async def store_work(started: str) -> dict[str, int]: + set_query_tag("worker.knowledge_source_sync") + # system.query_log arrives asynchronously; flush only the job's disposable store. + await get_client().execute("SYSTEM FLUSH LOGS") + row = await get_client().query_one( + "SELECT count() AS store_requests, sum(read_rows) AS store_read_rows, " + "sum(read_bytes) AS store_read_bytes, sum(written_rows) AS store_written_rows, " + "sum(written_bytes) AS store_written_bytes, max(memory_usage) AS store_memory_peak_bytes " + "FROM system.query_log WHERE type = 'QueryFinish' " + "AND event_time_microseconds >= parseDateTime64BestEffort({started:String}) " + "AND is_initial_query AND current_database = 'loom'", + params={"started": started}, + ) + assert row is not None + return {key: int(value) for key, value in row.items()} diff --git a/tests/integration/mcp_source_scale_servers.py b/tests/integration/mcp_source_scale_servers.py new file mode 100644 index 0000000000..ea330494e0 --- /dev/null +++ b/tests/integration/mcp_source_scale_servers.py @@ -0,0 +1,103 @@ +"""Official SDK fixtures for a fixed source workload; all transport is ASGI.""" + +from __future__ import annotations + +import asyncio +import copy +import json +from dataclasses import dataclass +from typing import Any + +from mcp import types +from mcp.server.lowlevel import Server +from starlette.responses import JSONResponse +from starlette.types import Receive, Scope, Send + +from tests.integration.mcp_source_qualification_servers import ( + DOCUMENT, + READ_INPUT, + SELECTED, + SyntheticSource, +) + +SCALE_DOCUMENT = copy.deepcopy(DOCUMENT) +SCALE_DOCUMENT["properties"]["text"]["maxLength"] = 8192 +ROLES = ("healthy", "stalled", "rate_limited", "denied", "malformed") + + +@dataclass +class ScaleSource(SyntheticSource): + role: str = "healthy" + faults_enabled: bool = False + hold: bool = False + + def __post_init__(self) -> None: + super().__post_init__() + self.text = "Synthetic selected text.\n" + "x" * (8192 - len("Synthetic selected text.\n")) + assert len(self.text.encode()) == 8192 + + @property + def host(self) -> str: + return self.kind + "-" + self.role.replace("_", "-") + ".mcp-scale.example" + + def profile(self, orgs: list[str], *, copy_allowed: bool = True) -> dict[str, Any]: + value = super().profile(orgs, copy_allowed=copy_allowed) + value["id"] = "scale-" + self.kind + "-" + self.role + if self.kind == "tools": + value["config"]["approved_tools"] = ["read_document"] + value["config"]["read"]["output_schema"] = copy.deepcopy(SCALE_DOCUMENT) + del value["config"]["search"] + return value + + async def read(self, identity: str) -> str: + assert identity == SELECTED + self.reads.append(identity) + self.in_flight += 1 + self.started.set() + try: + if self.hold or self.faults_enabled and self.role == "stalled": + await self.release.wait() + else: + await asyncio.sleep(0.02) + return self.text + finally: + self.in_flight -= 1 + + def tool_server(self) -> Server: + server = Server("Scale mapped tools") + + @server.list_tools() + async def listing() -> list[types.Tool]: + return [ + types.Tool( + name="read_document", inputSchema=READ_INPUT, outputSchema=SCALE_DOCUMENT + ) + ] + + @server.call_tool() + async def call(name: str, arguments: dict[str, Any]) -> types.CallToolResult: + assert name == "read_document" + identity = arguments["id"] + result = { + "id": identity, + "uri": identity, + "title": "Synthetic selected text", + "text": await self.read(identity), + } + return types.CallToolResult( + content=[types.TextContent(type="text", text=json.dumps(result))], + structuredContent=result, + ) + + return server + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if self.faults_enabled and self.role in {"rate_limited", "denied", "malformed"}: + code = {"rate_limited": 429, "denied": 403, "malformed": 200}[self.role] + await JSONResponse( + {"fixture": "unavailable"}, + status_code=code, + headers={"Retry-After": "1"} if code == 429 else {}, + )(scope, receive, send) + return + await super().__call__(scope, receive, send) diff --git a/tests/integration/test_mcp_source_qualification.py b/tests/integration/test_mcp_source_qualification.py new file mode 100644 index 0000000000..e2809cc60e --- /dev/null +++ b/tests/integration/test_mcp_source_qualification.py @@ -0,0 +1,542 @@ +"""Finite real-store MCP qualification; run only on the owned hosted fixture.""" + +from __future__ import annotations + +import asyncio +import json +from dataclasses import replace +from typing import Any +from uuid import uuid4 + +import pytest +from loom.errors import LoomError +from loom.session_protection import AutomaticCaptureSuppressed + +from server.core.ch import get_client, set_query_tag +from server.knowledge.app import mcp_profiles, mcp_source_authority +from tests.integration.mcp_source_qualification_fixtures import ( + Reader, + World, + cancel_owned, + qualification_app, + require_clean_selection, + world, +) +from tests.integration.mcp_source_qualification_servers import SECOND, SELECTED, UNSELECTED + +# Imported fixtures are collected by pytest; every case owns its application lifespan. +__all__ = ["qualification_app", "world"] +pytestmark = [ + pytest.mark.asyncio, + pytest.mark.parametrize("world", ["resources", "tools"], indirect=True), +] + + +async def imported(case: World, **kwargs: Any) -> Any: + await case.add(**kwargs) + result = await case.sync() + assert result.status == "ok" and result.complete + head = await case.head() + assert head.content == case.source.text and head.revision == 1 + return head + + +def no_content(value: Any, case: World, *, raw_identity: bool = True) -> None: + encoded = json.dumps(value, ensure_ascii=False) + assert case.private_marker not in encoded + assert case.source.bearer not in encoded + if raw_identity: + assert SELECTED not in encoded and UNSELECTED not in encoded + + +async def admitted_reads(case: World, actor: Reader) -> None: + namespace = case.entry["namespace"] + got = await case.get(actor) + assert got["found"] is True and got["content"] == case.source.text + assert got["source_uri"] == case.uri and got["revision"] >= 1 + assert actor.protection.protected + for op, body in ( + ("knowledge.list", {"limit": 20}), + ("knowledge.search", {"query": case.source.marker, "search_mode": "hybrid"}), + ("knowledge.outline", {"source_uri": case.uri}), + ("knowledge.inspect", {"sample_limit": 20}), + ): + set_query_tag("test.mcp_source_qualification.admitted") + result = await actor.call(op, namespace=namespace, **body) + assert case.uri in json.dumps(result), op + assert case.source.bearer not in json.dumps(result) + download = await case.download(actor) + assert download.status_code == 200 + assert download.headers["x-loom-download-source"] == "blob" + assert download.content == case.source.text.encode() + + +async def denied_reads( + case: World, actor: Reader, *, grant_denied: bool = False, allow_other: bool = False +) -> None: + namespace = case.entry["namespace"] + for op, body in ( + ("knowledge.get", {"source_uri": case.uri}), + ("knowledge.get", {"source_uri": case.uri, "include_superseded": True}), + ("knowledge.list", {"include_superseded": True, "limit": 20}), + ("knowledge.search", {"query": "Selected document", "search_mode": "hybrid"}), + ("knowledge.outline", {"source_uri": case.uri}), + ("knowledge.inspect", {"sample_limit": 20}), + ("memory.export_evidence", {"kind": "chunks", "include_high": True, "limit": 20}), + ): + set_query_tag("test.mcp_source_qualification.denied") + try: + result = await actor.call(op, namespace=namespace, **body) + except LoomError as error: + assert grant_denied and error.status in {403, 404} + no_content(error.detail, case) + else: + no_content(result, case, raw_identity=not allow_other) + if op in {"knowledge.get", "knowledge.outline"}: + assert result["found"] is False + elif op != "memory.export_evidence": + assert case.uri not in json.dumps(result) + try: + await case.download(actor) + except LoomError as error: + assert error.status in ({403, 404} if grant_denied else {404}) + no_content(error.detail, case) + else: + pytest.fail("Denied original was released") + + +async def test_writes_refresh(world: World) -> None: + first = await imported(world) + chunks = await world.chunks() + assert chunks and any(world.source.marker in chunk["content"] for chunk in chunks) + assert all( + chunk["embedding_dim"] == 1024 + and len(chunk["embedding"]) == 1024 + and chunk["embedding_model"] == "fake-ngram-1024" + for chunk in chunks + ) + assert first.blob_path and first.blob_size == len(world.source.text.encode()) + assert first.source_class == "imported" and first.actor + row = await world.source_row() + blob = await get_client().query_one( + "SELECT location, length(data) AS inline_bytes, size FROM loom.document_blobs FINAL " + "WHERE org = {org:String} AND namespace = {namespace:String} " + "AND sha256 = {sha:String} LIMIT 1", + params={"org": row.org, "namespace": row.mirror, "sha": first.blob_path}, + ) + assert blob and blob["location"].startswith("s3://") and blob["inline_bytes"] == 0 + assert blob["size"] == len(world.source.text.encode()) + metadata = json.loads(first.metadata) + assert metadata["mcp_source_id"] == world.entry["source_id"] + assert metadata["mcp_read_at"] and len(metadata["mcp_scope_sha256"]) == 64 + assert metadata["mcp_read_operation"] == ( + "tools/call" if world.source.kind == "tools" else "resources/read" + ) + await admitted_reads(world, world.owner) + embeds = list(world.embed_calls) + assert (await world.sync()).complete + unchanged = await world.head() + assert unchanged.doc_id == first.doc_id and unchanged.revision == first.revision + assert unchanged.blob_path == first.blob_path and await world.chunks() == chunks + assert unchanged.model_dump(exclude={"version", "metadata"}) == first.model_dump( + exclude={"version", "metadata"} + ) + assert world.embed_calls == embeds + world.source.text += "\nChanged selected content.\n" + await world.control("refresh") + assert (await world.sync()).complete + changed = await world.head() + assert changed.content == world.source.text and changed.revision == first.revision + 1 + assert changed.blob_path != first.blob_path and changed.content_sha256 != first.content_sha256 + await admitted_reads(world, world.owner) + require_clean_selection(world) + + +async def test_owner_privacy(world: World) -> None: + await imported(world) + await admitted_reads(world, world.owner) + await denied_reads(world, world.other) + await denied_reads(world, world.foreign, grant_denied=True) + with pytest.raises(LoomError) as cross_org: + await world.foreign.call( + "knowledge.get", org=world.owner.org, namespace=world.namespace, source_uri=world.uri + ) + assert cross_org.value.status == 403 + no_content(cross_org.value.detail, world) + listed = await world.other.call("knowledge.connection.mcp_list") + assert listed["connections"] == [] + inspected = await world.other.call("knowledge.connection.mcp_inspect", slot=world.slot) + assert inspected["found"] is False + # A protected response must stop automatic derived capture before it dispatches. + with pytest.raises(AutomaticCaptureSuppressed), world.owner.protection.automatic(): + await world.owner.call( + "memory.set", + namespace=world.namespace, + agent="qualification", + memory_key="automatic-copy", + content=world.source.text, + ) + history = await world.owner.call( + "memory.history", + namespace=world.namespace, + agent="qualification", + memory_key="automatic-copy", + limit=20, + ) + no_content(history, world) + + +async def test_source_identity(world: World) -> None: + await imported(world) + first_text = world.source.text + await world.owner.call( + "grants.create", + namespace=world.namespace, + subject=world.other.subject, + role="writer", + replace=True, + ) + connection = await world.other.call( + "knowledge.connection.mcp_connect", + profile_id="qualification-" + world.source.kind, + request_id=str(uuid4()), + bearer=world.source.bearer, + ) + second_marker = "qualificationcontent" + uuid4().hex + world.source.text = "# Selected document\n\n" + second_marker + second = replace( + world, + owner=world.other, + other=world.owner, + slot=connection["connection"]["slot"], + entry={}, + private_marker=second_marker, + ) + await imported(second) + assert second.uri != world.uri and second.entry["source_id"] != world.entry["source_id"] + assert (await world.get())["content"] == first_text + assert (await second.get())["content"] == world.source.text + await denied_reads(world, world.other, allow_other=True) + await denied_reads(second, world.owner, allow_other=True) + + +async def test_team_copy_grants(world: World) -> None: + await imported(world, namespace=world.child, copy=True) + await admitted_reads(world, world.other) + await world.owner.call("grants.revoke", namespace=world.team, subject=world.other.subject) + # The same warmed client and capsule must lose inherited access. + await denied_reads(world, world.other, grant_denied=True) + await admitted_reads(world, world.owner) + + +async def test_copy_consent(world: World) -> None: + with pytest.raises(LoomError): + await world.add(namespace=world.child, copy=True, confirm=False) + assert world.source.reads == [] + await writer_cannot_publish(world) + await operator_copy_approval(world) + + +async def operator_copy_approval(world: World) -> None: + replacement = mcp_profiles.MCPProfileCatalog.parse( + json.dumps( + { + "version": 1, + "profiles": [ + world.source.profile([world.owner.org, world.foreign.org], copy_allowed=False) + ], + } + ) + ) + world.catalog.current = replacement + connection = await world.owner.call( + "knowledge.connection.mcp_connect", + profile_id="qualification-" + world.source.kind, + request_id=str(uuid4()), + bearer=world.source.bearer, + ) + world.slot = connection["connection"]["slot"] + with pytest.raises(LoomError): + await world.add(namespace=world.child, copy=True) + await world.add() + + +async def writer_cannot_publish(world: World) -> None: + # A writer can import privately but cannot publish to collection readers. + await world.owner.call( + "grants.create", + namespace=world.team, + subject=world.other.subject, + role="writer", + replace=True, + ) + connection = await world.other.call( + "knowledge.connection.mcp_connect", + profile_id="qualification-" + world.source.kind, + request_id=str(uuid4()), + bearer=world.source.bearer, + ) + private = await world.other.call( + "knowledge.source.mcp_add", + namespace=world.child, + slot=connection["connection"]["slot"], + mode="snapshot", + reader_policy="owner_only", + resource_ids=[SELECTED], + request_id=str(uuid4()), + ) + assert private["source"]["reader_policy"] == "owner_only" + with pytest.raises(LoomError): + await world.other.call( + "knowledge.source.mcp_add", + namespace=world.child, + slot=connection["connection"]["slot"], + mode="snapshot", + reader_policy="collection_copy", + resource_ids=[SELECTED], + request_id=str(uuid4()), + confirm_copy_authority=True, + ) + assert world.source.reads == [] + + +async def test_account_revocation(world: World) -> None: + await imported(world) + await admitted_reads(world, world.owner) + await world.owner.call("knowledge.connection.mcp_disconnect", slot=world.slot) + await denied_reads(world, world.owner) + assert (await world.head()).content == world.source.text + + +async def test_owner_grant_revocation(world: World) -> None: + await imported(world) + await admitted_reads(world, world.owner) + # A second administrator revokes the source owner's destination authority. + await world.owner.call( + "grants.create", + namespace=world.namespace, + subject=world.other.subject, + role="admin", + replace=True, + ) + await world.other.call("grants.revoke", namespace=world.namespace, subject=world.owner.subject) + await denied_reads(world, world.owner, grant_denied=True) + await denied_reads(world, world.other) + + +async def test_profile_revocation(world: World) -> None: + await imported(world) + await admitted_reads(world, world.owner) + # Mutate the owned operator catalog, leaving sealed credentials and rows intact. + world.catalog.current = mcp_profiles.MCPProfileCatalog.parse( + json.dumps({"version": 1, "profiles": []}) + ) + await denied_reads(world, world.owner) + assert (await world.head()).content == world.source.text + + +async def test_pause(world: World) -> None: + await imported(world) + await admitted_reads(world, world.owner) + await world.control("pause") + await denied_reads(world, world.owner) + assert (await world.head()).content == world.source.text + await world.control("resume") + await admitted_reads(world, world.owner) + + +async def test_read_failure(world: World) -> None: + head = await imported(world) + world.source.denied = True + result = await world.sync() + assert result.status != "ok" and not result.complete + invalidated = await world.head() + metadata = json.loads(invalidated.metadata) + assert "mcp_scope_sha256" not in metadata and "mcp_read_at" not in metadata + assert invalidated.content == head.content and invalidated.blob_path == head.blob_path + assert invalidated.superseded_at is None + await denied_reads(world, world.owner) + world.source.denied = False + assert (await world.sync()).complete + assert (await world.head()).revision == head.revision + await admitted_reads(world, world.owner) + + +async def test_scope_revision(world: World) -> None: + first = await imported(world) + old_uri, old_id = world.uri, world.entry["source_id"] + revision = world.entry["scope_revision"] + with pytest.raises(LoomError) as audience: + await world.control( + "update", + resource_ids=[SELECTED], + mode="selected_refresh", + if_scope_revision=revision, + reader_policy="collection_copy", + ) + assert audience.value.status == 422 + assert world.entry["source_id"] == old_id and world.entry["reader_policy"] == "owner_only" + await world.control( + "update", + resource_ids=[SECOND], + mode="selected_refresh", + if_scope_revision=revision, + ) + assert world.entry["scope_revision"] > revision and world.entry["source_id"] == old_id + assert (await world.get())["found"] is False + assert (await world.head()).blob_path == first.blob_path + assert (await world.sync()).complete + revision = world.entry["scope_revision"] + await world.control( + "update", + resource_ids=[SELECTED], + mode="snapshot", + if_scope_revision=revision, + ) + assert world.entry["scope_revision"] > revision and world.uri == old_uri + assert (await world.get())["found"] is False + assert (await world.sync()).complete + await admitted_reads(world, world.owner) + with pytest.raises(LoomError): + await world.control( + "update", + resource_ids=[SECOND], + mode="live", + if_scope_revision=revision, + ) + require_clean_selection(world) + + +async def test_snapshot(world: World) -> None: + head = await imported(world, mode="snapshot") + reads = list(world.source.reads) + world.source.text += "\nUnrequested later content.\n" + assert (await world.sync()).complete + assert world.source.reads == reads and (await world.head()).content == head.content + await world.control("refresh") + assert (await world.sync()).complete + assert (await world.head()).content == world.source.text + + +async def test_schema_drift(world: World) -> None: + head = await imported(world) + if world.source.kind == "tools": + world.source.drift = True + else: + # Resource servers have no mapped tool schema; operator approval drift still fences them. + changed = world.source.profile([world.owner.org, world.foreign.org]) + changed["config"]["limits"]["max_pages"] = 1 + replacement = mcp_profiles.MCPProfileCatalog.parse( + json.dumps({"version": 1, "profiles": [changed]}) + ) + world.catalog.current = replacement + reads = len(world.source.reads) + result = await world.sync() + assert result.status != "ok" and not result.complete + assert len(world.source.reads) == reads + assert (await world.head()).content == head.content + await denied_reads(world, world.owner) + + +async def test_partial_listing(world: World) -> None: + await world.add(ids=[SELECTED, SECOND]) + world.source.partial = True + bound = await mcp_source_authority.validate_source(await world.source_row()) + async with bound.client() as client: + await client.discover() + page = await ( + client.search("Selected document") + if world.source.kind == "tools" + else client.list_resources() + ) + assert page.items and page.complete is False + assert all(item.receipt is None for item in page.items) + assert world.source.reads == [] + listing_calls = list(world.source.calls) + assert (await world.sync()).complete + assert world.source.calls.count("resources/list") == listing_calls.count("resources/list") + assert world.source.calls.count("search_documents") == listing_calls.count("search_documents") + first, second = await world.head(), await world.head(SECOND) + # Selected refresh never enumerates upstream or treats an omitted page as deletion. + world.source.denied = True + assert not (await world.sync()).complete + assert (await world.head()).content == first.content + assert (await world.head(SECOND)).content == second.content + inspected = await world.control("inspect") + source = inspected["source"] + assert source["complete_enumeration"] is source["upstream_deletion_tracking"] is False + assert source["current_access_attested"] is False + require_clean_selection(world) + + +async def test_cancellation(world: World) -> None: + await world.add() + world.source.block_read = True + task = asyncio.create_task(world.sync(), name="mcp-source-qualification-owned-turn") + try: + async with asyncio.timeout(15): + await world.source.started.wait() + finally: + await cancel_owned(task, world.source) + row = await world.source_row() + assert await get_client().query_one( + "SELECT count() AS count FROM loom.documents WHERE org = {org:String} " + "AND namespace = {namespace:String} AND source_uri = {uri:String}", + params={"org": row.org, "namespace": row.mirror, "uri": world.uri}, + ) == {"count": 0} + world.source.block_read = False + result = await world.sync() + assert result.complete and (await world.head()).content == world.source.text + + +async def test_live(world: World) -> None: + await world.add(mode="live") + assert (await world.sync()).complete and world.source.reads == [] + selected = await world.owner.call( + "knowledge.source.mcp_read", + namespace=world.namespace, + name=world.entry["name"], + resource_id=SELECTED, + ) + assert selected["text"] == world.source.text and selected["uri"] == world.uri + assert selected["source_id"] == world.entry["source_id"] + assert selected["resource_id"] == SELECTED + assert selected["remote_identity_verified"] is selected["upstream_acl_verified"] is False + assert world.owner.protection.protected + for actor, identity in ((world.other, SELECTED), (world.owner, UNSELECTED)): + set_query_tag("test.mcp_source_qualification.live_denied") + reads = list(world.source.reads) + with pytest.raises(LoomError) as refused: + await actor.call( + "knowledge.source.mcp_read", + namespace=world.namespace, + name=world.entry["name"], + resource_id=identity, + ) + assert refused.value.status in {400, 403, 404, 422} + no_content(refused.value.detail, world, raw_identity=False) + assert world.source.reads == reads + if world.source.kind == "tools": + result = await world.owner.call( + "search.query", + namespace=world.namespace, + query="Selected document", + live=True, + ) + assert world.source.marker in json.dumps(result) + assert world.uri in json.dumps(result) and world.source.reads + assert UNSELECTED not in world.source.reads + denied = await world.other.call( + "search.query", + namespace=world.namespace, + query="Selected document", + live=True, + ) + no_content(denied, world) + for table in ("documents", "chunks", "memory"): + set_query_tag("test.mcp_source_qualification.no_import") + assert await get_client().query_one( + f"SELECT count() AS count FROM loom.{table} WHERE org = {{org:String}}", + params={"org": world.owner.org}, + ) == {"count": 0} + require_clean_selection(world) diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index fd848f2a93..e084239e4f 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -1,9 +1,9 @@ { "loom": [ - "usage: loom [-h] [--version] {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect} ...", + "usage: loom [-h] [--version] [--request-intent {automatic,explicit}] {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect} ...", "Loom — vendor-neutral agent memory plane on ClickHouse.", "positional arguments: {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect} code Code intelligence plane operations. decisions Decision records mined from documents. knowledge Knowledge documents and their sources. export-okf Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. import-okf Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. okf-lint Lint an OKF bundle directory offline — the compile gate a mirror repository's CI runs. Exit 2 critical, 1 warnings, 0 clean. up Boot the local stack (Loom, its document extractor and ClickHouse) and print how to connect: creates .env and the ClickHouse config from their templates, runs docker compose up --build, waits for /v1/health, then prints the dashboard URL and the first memory.set (curl + Python SDK) and `claude mcp add` snippets — minting a writer token first when auth is on. Re-run any time. down Stop the local stack while preserving data; --delete-data performs a confirmed reset. ch-setup Prepare a self-managed ClickHouse or a ClickHouse Cloud service for Loom: create the loom database and the read-only reader user, or print the SQL for an admin. participant The Loom processes a provider change waits for. deployment The configuration every replica checks itself against. settings Every setting's value in force, and overrides of the live ones. secrets Credentials and signing keys stored sealed in ClickHouse. signing-key The token signing keys beside LOOM_JWT_SECRET, kept in ClickHouse. provider-lock The provider configuration lock. export-analytics Write one UTC day of usage and a namespace snapshot to S3 as Parquet, names hashed under LOOM_ANALYTICS_EXPORT_NAME_KEY. Never replaces an object, so a repeated run is safe. sql-access Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views. reembed Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them. reextract Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is never written. deploy-delta What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side of the swap, with flags for what moved past a coarse threshold. entity-export Export a namespace's entity graph (co-occurrence edges + triples) to GraphML or JSON-LD for an external graph or RDF tool. Read-only; every edge carries its provenance and a note that a path is declared, not proven. audit-namespace How a namespace is being used (namespace.audit): exact-key reads vs searches, hash keys, double-encoded and oversized values, hand-rolled index rows, leases stored as memories, version churn. Read-only; prints a table (code, severity, kind, count, share, first sample) or --json. Exit 1 on a critical finding. mentor The store's advice to one agent (mentor.brief): what it called, the planes its namespace offers, the hints with their evidence, and how often past hints were followed. Read-only; prints a table or --json. Exit 1 when a warning-level hint fires. serve Boot the control plane (uvicorn). migrate Apply schema migrations against the configured CH. reconcile-status Re-emit memory_embeddings rows whose status diverged from loom.memory (superseded / conflicted / duplicate marks the pool never saw), compared and re-emitted per identity row (org, namespace, agent, user_id, session_id, key). Dry run by default (counts by status, the rows it would write); --apply writes. period-digest Write period digests — one derived semantic memory over K consecutive session digests of each identity in one namespace. Additive and idempotent. Dry run by default (plans only); --apply writes. demote-activity-narration Find a namespace's extracted facts that narrate tool activity ('User read lines 1-1000 of X', 'Claude ran a command on …') with no durable outcome and demote (confidence x0.25) or label them through memory.apply. Dry run by default; keys an agent read by name in the last --days are left alone. Never deletes. recalibrate Re-probe the embedder + run per-NS calibration immediately (otherwise this runs weekly via the recalibration worker). import-clickgap Import a ClickGap (Detector→Validator→Reviewer) SQLite export into Loom (lessons + typed entities + categories). Reembed-only; preserves kind→memory_type, per-row TTL, recall_count (→ ranking via reinforcement_count), suppression polarity, and provenance. Idempotent via deterministic keys + per-run version. import-recall Import an external vector-recall agent-memory SQLite export into Loom. Introspects the DB at runtime (schema not assumed): tables are classified by column heuristics into memories (→ memory.set) or conversation transcripts (→ conversation.append, grouped by conversation id); unmatched tables/rows are skipped, never crash. Idempotent via deterministic keys. import-brain Import a markdown agent 'brain' directory into Loom: MEMORY.md (always- injected HOT layer) → profile.set sections; memory/contexts/*.md (read-on- demand WARM layer) → knowledge.add docs. Completes the migration alongside import-recall (the deep vector layer). Missing files are skipped, never crash. claim-release Release a self-signup claim: revoke its grants, clear the owner, deactivate it. The name stays reserved. mint-token Mint a JWT locally (requires LOOM_JWT_SECRET and verified stores). revoke-token Revoke one token by jti or subject (writes loom.revoked_tokens through the revocation module; needs the configured ClickHouse). sso Carry password accounts over to single sign-on. bot Bots and CI jobs that sign in with a key or their CI's identity. doctor Diagnose pre-boot misconfig (Python version, settings, JWT, CH reachability) and print the problem list /v1/health carries, each with its fix. With --client, also examine this machine as a coding-agent client. report Print the bug form's Environment field: versions and the `loom doctor` checks. drops Print the memory ingest drop ledger (loom.memory_drops) for a namespace, by stage/reason — what the pipeline discarded, truncated or gave up on. namespaces-gc List (default) or erase throwaway namespaces — finished bench runs under the bench prefixes that nobody registered and nobody has written to for --idle-hours — in one list-scoped erasure saga per batch. erasure-re-verify Re-verify failed erasure sagas: print each one's last step-named reason and a fresh residue census (default, read-only); --resume re-runs them from their checkpoint past the recovery worker's attempts budget; --orphan-graph lists namespaces whose entity graph outlived their memories and, with --erase, purges them. reconcile After a restore of ClickHouse or Postgres, run again in the restored store the erasures and redactions the other records past the restore point, and (after a ClickHouse restore) publish again every revision committed after it. Stop every server and worker first. Dry run by default. router The router in front of a deployment's cells. cell Operate a deployment's cells through the router's directory. tracker-probe Read-only first contact with the tracker source: counts and newest timestamps per upstream table per credential, breaker states, the configured tracker namespaces. tracker-contract-check Read-only: does each tracker source's schema meet the record contract (docs/features/tracker/record-contract.md)? Names missing tables / columns, optional tables present, feature columns. Exit 0 when every checked source meets it. tracker-dupcheck-fit Refit tracker.duplicate_check's calibrated confidence for one tracker namespace now: replays the duplicate gold at filing time, fits, stores the fit. tracker-embed-reset Clear the tracker_embed pass cursors of one tracker namespace so the next pass re-walks the window and re-embeds every item whose text recipe changed. Dry run by default (prints the cursors); --apply clears them. tracker-feed Maintain a team's GitHub tracker record namespaces-adopt Give namespaces that hold live memory and no registry row an owner row: kind=bench under the bench prefixes, else memory; retention_days 0, no TTL. Dry run unless --apply. sensitivity-sweep Label live rows the sensitivity detector would have labelled on write but a path skipped. Dry run by default: counts by level, probe shape and namespace. --apply writes one new version per row, tombstones a high row's embedding rows and tags a medium row's. The closing line is the high- sensitivity invariant (high rows with a live embedding). integrity-repair Read the row-level integrity gauges (dim-0 rows holding a vector, tombstoned_at/status drift, active rows past valid_to) and, with --apply, re-emit the dim-0 rows with their true dimension so search can return them again. Drift and valid_to are listed, not repaired. rechunk Re-chunk and re-embed a namespace's knowledge documents from stored content through the current chunker, so every document carries section metadata, chunk context and document frequency. Idempotent; one embedding per new chunk. Dry run by default (counts the documents and chunks); --apply re-chunks. export-actions Export the action schema derived from the operation registry — an MCP tools/list manifest with loom extras (json) or the Cedar schema (cedar) a policy gateway governs the surface with. lexical-stats-rebuild Recompute BM25 document frequency for a namespace from its live rows (the term-frequency views only see inserts; supersession and tombstones leave stale vocabulary behind). version Print installed Loom version. install Wire Loom into a local AI client's config. Writes the MCP server block into Claude Desktop / Cursor / VS Code's config file, atomically, merging with anything already there; for Claude Code it runs (or prints) `claude mcp add` and for Codex `codex mcp add`. Restart the client afterwards. demo The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. On the stock fake-LLM stack it prints the top knowledge.search hits and says what a real answer needs. init Create an identity on a Loom server. `--agent NAME` signs an agent up by itself (server needs LOOM_SELF_SIGNUP=open): mints a writer token on a fresh agent- namespace, saves it to ~/.loom/token, and prints the claim code a person enters once, with a password of their own, to claim the namespace. ingest-transcript Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. Generic ingest for tools without an MCP integration (Aider, Continue.dev, JetBrains AI, anything else): export the chat → run this command → the thread shows in the dashboard's Conversations. memory-search Run a memory.search from the shell. Default human output; --json-agent emits a structured envelope agents can pipe through (a `{command, results}` JSON shape). set-host Designate the Loom host(s) for this deployment. Writes the given login handle(s) or email(s) to LOOM_PLATFORM_ADMINS in the .env (--env-file, default ./.env): a handle promotes that password account to platform_admin, an email promotes an SSO sign-in with that verified email. Multiple OK (on-call rotation, co-operators, etc.). Re-login required after to pick up the role. login Sign in to a Loom server on any browser with a one-time code. logout End the stored session on the server and forget it here. whoami Show who the stored session signs you in as. call Call any operation or API route with the stored session (`loom call --help`). token Make, list and revoke your own tokens for CI and agents (`loom token --help`). connect Print the dashboard link to connect your own Google, Notion or Linear account.", - "options: -h, --help show this help message and exit --version show program's version number and exit" + "options: -h, --help show this help message and exit --version show program's version number and exit --request-intent {automatic,explicit} Explicit is one direct human request; automatic is the default." ], "loom code": [ "usage: loom code [-h] {init,backfill,reconcile,compact,reembed,vector-twin,crossref,coverage-import,export-pairs,backfill-prs,repack,describe,answers-purge,scip-full,scip-lock-path,entry-lock,scip-delta,entries,warm,scip-retry,backfill-reviews,backfill-assignees,backfill-items,stats,export-matrix,lint-instructions} ...", @@ -128,7 +128,7 @@ ], "loom knowledge": [ "usage: loom knowledge [-h] {sync,source,migrate-originals} ...", - "positional arguments: {sync,source,migrate-originals} sync Run one sync pass over a repository namespace's document sources now: list each source's changed files (every file with --full), write the changed ones as documents and retire those a full listing no longer has, then mine each document written since it was last mined for decisions (model calls, within LOOM_KNOWLEDGE_SOURCE_SYNC_CAP_SHARE of the namespace's cost cap), bounded like a worker pass by LOOM_KNOWLEDGE_SOURCE_SYNC_DOCUMENTS_PER_PASS; run it again to go on. Leaves a manual knowledge_source_sync row in loom.worker_status. Exits 1 when a source's turn or a document's extraction failed. source A namespace's document sources, over a running server. migrate-originals Move the document originals still held in ClickHouse, that a document, upload or ingestion needs, to LOOM_DOCUMENT_S3_BUCKET: each is copied to its own object, hash-verified and switched, fenced by the erasure ledger. Needs LOOM_DOCUMENT_OBJECT_STORE=s3 on every replica first (a dry run does not). Idempotent. Exits 1 when an original was not moved, a namespace was refused, or a switch could not be confirmed; each is listed. See docs/features/knowledge.md, Where originals are stored.", + "positional arguments: {sync,source,migrate-originals} sync Run one sync pass over a repository namespace's document sources now: list each source's changed files (every file with --full), write the changed ones as documents and retire those a full listing no longer has, then mine each document written since it was last mined for decisions (model calls, within LOOM_KNOWLEDGE_SOURCE_SYNC_CAP_SHARE of the namespace's cost cap), bounded like a worker pass by LOOM_KNOWLEDGE_SOURCE_SYNC_DOCUMENTS_PER_PASS; run it again to go on. Leaves a manual knowledge_source_sync row in loom.worker_status. Exits 1 when a source's turn or a document's extraction failed. source MCP sources, connections, collection destinations and recordings. migrate-originals Move the document originals still held in ClickHouse, that a document, upload or ingestion needs, to LOOM_DOCUMENT_S3_BUCKET: each is copied to its own object, hash-verified and switched, fenced by the erasure ledger. Needs LOOM_DOCUMENT_OBJECT_STORE=s3 on every replica first (a dry run does not). Idempotent. Exits 1 when an original was not moved, a namespace was refused, or a switch could not be confirmed; each is listed. See docs/features/knowledge.md, Where originals are stored.", "options: -h, --help show this help message and exit" ], "loom knowledge sync": [ @@ -136,21 +136,141 @@ "options: -h, --help show this help message and exit --org ORG --namespace NAMESPACE The namespace the sources live in --source SOURCE Only the source of this name --full Record a full sync request for each source, as knowledge.source.sync_now full=true does, so every file is listed and waiting files are retried; a run while that request is unfinished goes on with it" ], "loom knowledge source": [ - "usage: loom knowledge source [-h] {list,add,update} ...", - "positional arguments: {list,add,update} list List the namespace's sources, items and sync state. add Register a source from links or items, probed with the credential before anything is stored (knowledge.source.add). update Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update).", + "usage: loom knowledge source [-h] {preview,add,update,list,inspect,pause,resume,refresh,read,remove,connection,destination,recording,retained} ...", + "positional arguments: {preview,add,update,list,inspect,pause,resume,refresh,read,remove,connection,destination,recording,retained}", "options: -h, --help show this help message and exit" ], - "loom knowledge source list": [ - "usage: loom knowledge source list [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN]", - "options: -h, --help show this help message and exit --namespace NAMESPACE The namespace the source's documents live in --org ORG Default: the token's org --server-url SERVER_URL --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token)" + "loom knowledge source preview": [ + "usage: loom knowledge source preview [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." ], "loom knowledge source add": [ - "usage: loom knowledge source add [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME --kind KIND [--link LINK] [--item-json ITEM_JSON] [--include INCLUDE] --credential-file CREDENTIAL_FILE [--dry-run]", - "options: -h, --help show this help message and exit --namespace NAMESPACE The namespace the source's documents live in --org ORG Default: the token's org --server-url SERVER_URL --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME --kind KIND gdrive, notion or linear --link LINK A link to read; repeatable --item-json ITEM_JSON An item to read as JSON, such as {\"type\": \"folder\", \"id\": \"...\"}; repeatable --include INCLUDE gdrive: a file kind to read (docs, slides, pdf, pptx, docx); repeatable --credential-file CREDENTIAL_FILE The file holding the source's read-only credential; - reads it from stdin --dry-run Probe and store nothing" + "usage: loom knowledge source add [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." ], "loom knowledge source update": [ - "usage: loom knowledge source update [-h] --namespace NAMESPACE [--org ORG] [--server-url SERVER_URL] [--token TOKEN] --name NAME [--link LINK] [--item-json ITEM_JSON] [--include INCLUDE] [--remove-link REMOVE_LINK] [--remove-item-json REMOVE_ITEM_JSON]", - "options: -h, --help show this help message and exit --namespace NAMESPACE The namespace the source's documents live in --org ORG Default: the token's org --server-url SERVER_URL --token TOKEN JWT (default: $LOOM_API_KEY, ~/.loom/token) --name NAME --link LINK A link to read; repeatable --item-json ITEM_JSON An item to read as JSON, such as {\"type\": \"folder\", \"id\": \"...\"}; repeatable --include INCLUDE gdrive: a file kind to read (docs, slides, pdf, pptx, docx); repeatable --remove-link REMOVE_LINK A link to remove; repeatable --remove-item-json REMOVE_ITEM_JSON An item to remove as JSON, such as {\"type\": \"folder\", \"id\": \"...\"}; repeatable" + "usage: loom knowledge source update [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source list": [ + "usage: loom knowledge source list [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source inspect": [ + "usage: loom knowledge source inspect [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source pause": [ + "usage: loom knowledge source pause [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source resume": [ + "usage: loom knowledge source resume [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source refresh": [ + "usage: loom knowledge source refresh [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source read": [ + "usage: loom knowledge source read [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source remove": [ + "usage: loom knowledge source remove [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source connection": [ + "usage: loom knowledge source connection [-h] {profiles,connect,list,inspect,discover,browse,disconnect} ...", + "positional arguments: {profiles,connect,list,inspect,discover,browse,disconnect}", + "options: -h, --help show this help message and exit" + ], + "loom knowledge source connection profiles": [ + "usage: loom knowledge source connection profiles [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source connection connect": [ + "usage: loom knowledge source connection connect [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}] [--bearer-file BEARER_FILE]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action. --bearer-file BEARER_FILE Owned mode-0600 credential file or - for stdin. Never an argv secret." + ], + "loom knowledge source connection list": [ + "usage: loom knowledge source connection list [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source connection inspect": [ + "usage: loom knowledge source connection inspect [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source connection discover": [ + "usage: loom knowledge source connection discover [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source connection browse": [ + "usage: loom knowledge source connection browse [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source connection disconnect": [ + "usage: loom knowledge source connection disconnect [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source destination": [ + "usage: loom knowledge source destination [-h] {list,create,grants,grant,preview} ...", + "positional arguments: {list,create,grants,grant,preview}", + "options: -h, --help show this help message and exit" + ], + "loom knowledge source destination list": [ + "usage: loom knowledge source destination list [-h] --server-url SERVER_URL --org ORG [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source destination create": [ + "usage: loom knowledge source destination create [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source destination grants": [ + "usage: loom knowledge source destination grants [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source destination grant": [ + "usage: loom knowledge source destination grant [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source destination preview": [ + "usage: loom knowledge source destination preview [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source recording": [ + "usage: loom knowledge source recording [-h] {add,list,sync-now} ...", + "positional arguments: {add,list,sync-now}", + "options: -h, --help show this help message and exit" + ], + "loom knowledge source recording add": [ + "usage: loom knowledge source recording add [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}] --credential-file CREDENTIAL_FILE", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action. --credential-file CREDENTIAL_FILE Owned mode-0600 credential file or - for stdin. Never an argv secret." + ], + "loom knowledge source recording list": [ + "usage: loom knowledge source recording list [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source recording sync-now": [ + "usage: loom knowledge source recording sync-now [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source retained": [ + "usage: loom knowledge source retained [-h] {list,inspect,remove} ...", + "positional arguments: {list,inspect,remove}", + "options: -h, --help show this help message and exit" + ], + "loom knowledge source retained list": [ + "usage: loom knowledge source retained list [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source retained inspect": [ + "usage: loom knowledge source retained inspect [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." + ], + "loom knowledge source retained remove": [ + "usage: loom knowledge source retained remove [-h] --server-url SERVER_URL --org ORG [--namespace NAMESPACE] [--request-file REQUEST_FILE] [--token-file TOKEN_FILE] --session-file SESSION_FILE [--intent {automatic,explicit}]", + "options: -h, --help show this help message and exit --server-url SERVER_URL --org ORG --namespace NAMESPACE Ordinary destination; must agree with the JSON field. --request-file REQUEST_FILE UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide. --token-file TOKEN_FILE Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY. --session-file SESSION_FILE Existing application-owned private session pointer; never initialized by this command. --intent {automatic,explicit} Default automatic guards every call; explicit is a direct user action." ], "loom knowledge migrate-originals": [ "usage: loom knowledge migrate-originals [-h] [--org ORG] [--namespace NAMESPACE] [--dry-run]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index b5ea5829ab..04b73a84de 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -20,7 +20,8 @@ "description": null, "dests": [ "help", - "version" + "version", + "request_intent" ] } ], @@ -58,6 +59,24 @@ "metavar": null, "version": "" }, + { + "option_strings": [ + "--request-intent" + ], + "dest": "request_intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Explicit is one direct human request; automatic is the default.", + "metavar": null + }, { "option_strings": [], "dest": "cmd", @@ -3871,16 +3890,16 @@ "help": null, "metavar": null, "subcommands": { - "list": { - "prog": "loom knowledge source list", + "preview": { + "prog": "loom knowledge source preview", "usage": null, "description": null, "epilog": null, "formatter_class": "argparse:HelpFormatter", "add_help": true, - "allow_abbrev": true, + "allow_abbrev": false, "defaults": { - "func": "server.cli.knowledge_source:_cmd_list" + "func": "server.cli.knowledge_source:_dispatch" }, "groups": [ { @@ -3893,10 +3912,13 @@ "description": null, "dests": [ "help", - "namespace", - "org", "server_url", - "token" + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" ] } ], @@ -3920,9 +3942,9 @@ }, { "option_strings": [ - "--namespace" + "--server-url" ], - "dest": "namespace", + "dest": "server_url", "action": "_StoreAction", "default": null, "const": null, @@ -3930,7 +3952,7 @@ "nargs": null, "type": null, "required": true, - "help": "The namespace the source's documents live in", + "help": null, "metavar": null }, { @@ -3939,43 +3961,91 @@ ], "dest": "org", "action": "_StoreAction", - "default": "", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": "Default: the token's org", + "help": "Ordinary destination; must agree with the JSON field.", "metavar": null }, { "option_strings": [ - "--server-url" + "--request-file" ], - "dest": "server_url", + "dest": "request_file", "action": "_StoreAction", - "default": "http://localhost:7777", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": null, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", "metavar": null }, { "option_strings": [ - "--token" + "--session-file" ], - "dest": "token", + "dest": "session_file", "action": "_StoreAction", "default": null, "const": null, "choices": null, "nargs": null, "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, "required": false, - "help": "JWT (default: $LOOM_API_KEY, ~/.loom/token)", + "help": "Default automatic guards every call; explicit is a direct user action.", "metavar": null } ] @@ -3987,9 +4057,9 @@ "epilog": null, "formatter_class": "argparse:HelpFormatter", "add_help": true, - "allow_abbrev": true, + "allow_abbrev": false, "defaults": { - "func": "server.cli.knowledge_source:_cmd_add" + "func": "server.cli.knowledge_source:_dispatch" }, "groups": [ { @@ -4002,17 +4072,13 @@ "description": null, "dests": [ "help", - "namespace", - "org", "server_url", - "token", - "name", - "kind", - "link", - "item_json", - "include", - "credential_file", - "dry_run" + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" ] } ], @@ -4036,9 +4102,9 @@ }, { "option_strings": [ - "--namespace" + "--server-url" ], - "dest": "namespace", + "dest": "server_url", "action": "_StoreAction", "default": null, "const": null, @@ -4046,7 +4112,7 @@ "nargs": null, "type": null, "required": true, - "help": "The namespace the source's documents live in", + "help": null, "metavar": null }, { @@ -4055,50 +4121,150 @@ ], "dest": "org", "action": "_StoreAction", - "default": "", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": "Default: the token's org", + "help": "Ordinary destination; must agree with the JSON field.", "metavar": null }, { "option_strings": [ - "--server-url" + "--request-file" ], - "dest": "server_url", + "dest": "request_file", "action": "_StoreAction", - "default": "http://localhost:7777", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": null, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", "metavar": null }, { "option_strings": [ - "--token" + "--session-file" ], - "dest": "token", + "dest": "session_file", "action": "_StoreAction", "default": null, "const": null, "choices": null, "nargs": null, "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "update": { + "prog": "loom knowledge source update", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, "required": false, - "help": "JWT (default: $LOOM_API_KEY, ~/.loom/token)", + "help": "show this help message and exit", "metavar": null }, { "option_strings": [ - "--name" + "--server-url" ], - "dest": "name", + "dest": "server_url", "action": "_StoreAction", "default": null, "const": null, @@ -4111,9 +4277,9 @@ }, { "option_strings": [ - "--kind" + "--org" ], - "dest": "kind", + "dest": "org", "action": "_StoreAction", "default": null, "const": null, @@ -4121,59 +4287,59 @@ "nargs": null, "type": null, "required": true, - "help": "gdrive, notion or linear", + "help": null, "metavar": null }, { "option_strings": [ - "--link" + "--namespace" ], - "dest": "link", - "action": "_AppendAction", - "default": [], + "dest": "namespace", + "action": "_StoreAction", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": "A link to read; repeatable", + "help": "Ordinary destination; must agree with the JSON field.", "metavar": null }, { "option_strings": [ - "--item-json" + "--request-file" ], - "dest": "item_json", - "action": "_AppendAction", - "default": [], + "dest": "request_file", + "action": "_StoreAction", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": "An item to read as JSON, such as {\"type\": \"folder\", \"id\": \"...\"}; repeatable", + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", "metavar": null }, { "option_strings": [ - "--include" + "--token-file" ], - "dest": "include", - "action": "_AppendAction", + "dest": "token_file", + "action": "_StoreAction", "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": "gdrive: a file kind to read (docs, slides, pdf, pptx, docx); repeatable", + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", "metavar": null }, { "option_strings": [ - "--credential-file" + "--session-file" ], - "dest": "credential_file", + "dest": "session_file", "action": "_StoreAction", "default": null, "const": null, @@ -4181,36 +4347,39 @@ "nargs": null, "type": null, "required": true, - "help": "The file holding the source's read-only credential; - reads it from stdin", + "help": "Existing application-owned private session pointer; never initialized by this command.", "metavar": null }, { "option_strings": [ - "--dry-run" + "--intent" ], - "dest": "dry_run", - "action": "_StoreTrueAction", - "default": false, - "const": true, - "choices": null, - "nargs": 0, + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, "type": null, "required": false, - "help": "Probe and store nothing", + "help": "Default automatic guards every call; explicit is a direct user action.", "metavar": null } ] }, - "update": { - "prog": "loom knowledge source update", + "list": { + "prog": "loom knowledge source list", "usage": null, "description": null, "epilog": null, "formatter_class": "argparse:HelpFormatter", "add_help": true, - "allow_abbrev": true, + "allow_abbrev": false, "defaults": { - "func": "server.cli.knowledge_source:_cmd_update" + "func": "server.cli.knowledge_source:_dispatch" }, "groups": [ { @@ -4223,16 +4392,13 @@ "description": null, "dests": [ "help", - "namespace", - "org", "server_url", - "token", - "name", - "link", - "item_json", - "include", - "remove_link", - "remove_item_json" + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" ] } ], @@ -4256,9 +4422,9 @@ }, { "option_strings": [ - "--namespace" + "--server-url" ], - "dest": "namespace", + "dest": "server_url", "action": "_StoreAction", "default": null, "const": null, @@ -4266,7 +4432,7 @@ "nargs": null, "type": null, "required": true, - "help": "The namespace the source's documents live in", + "help": null, "metavar": null }, { @@ -4275,35 +4441,35 @@ ], "dest": "org", "action": "_StoreAction", - "default": "", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, - "required": false, - "help": "Default: the token's org", + "required": true, + "help": null, "metavar": null }, { "option_strings": [ - "--server-url" + "--namespace" ], - "dest": "server_url", + "dest": "namespace", "action": "_StoreAction", - "default": "http://localhost:7777", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": null, + "help": "Ordinary destination; must agree with the JSON field.", "metavar": null }, { "option_strings": [ - "--token" + "--request-file" ], - "dest": "token", + "dest": "request_file", "action": "_StoreAction", "default": null, "const": null, @@ -4311,124 +4477,4091 @@ "nargs": null, "type": null, "required": false, - "help": "JWT (default: $LOOM_API_KEY, ~/.loom/token)", + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", "metavar": null }, { "option_strings": [ - "--name" + "--token-file" ], - "dest": "name", + "dest": "token_file", "action": "_StoreAction", "default": null, "const": null, "choices": null, "nargs": null, "type": null, - "required": true, - "help": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", "metavar": null }, { "option_strings": [ - "--link" + "--session-file" ], - "dest": "link", - "action": "_AppendAction", - "default": [], + "dest": "session_file", + "action": "_StoreAction", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, - "required": false, - "help": "A link to read; repeatable", + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", "metavar": null }, { "option_strings": [ - "--item-json" + "--intent" ], - "dest": "item_json", - "action": "_AppendAction", - "default": [], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", "const": null, - "choices": null, + "choices": [ + "automatic", + "explicit" + ], "nargs": null, "type": null, "required": false, - "help": "An item to read as JSON, such as {\"type\": \"folder\", \"id\": \"...\"}; repeatable", + "help": "Default automatic guards every call; explicit is a direct user action.", "metavar": null + } + ] + }, + "inspect": { + "prog": "loom knowledge source inspect", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ { "option_strings": [ - "--include" + "-h", + "--help" ], - "dest": "include", - "action": "_AppendAction", - "default": null, + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", "const": null, "choices": null, - "nargs": null, + "nargs": 0, "type": null, "required": false, - "help": "gdrive: a file kind to read (docs, slides, pdf, pptx, docx); repeatable", + "help": "show this help message and exit", "metavar": null }, { "option_strings": [ - "--remove-link" + "--server-url" ], - "dest": "remove_link", - "action": "_AppendAction", - "default": [], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "pause": { + "prog": "loom knowledge source pause", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "resume": { + "prog": "loom knowledge source resume", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "refresh": { + "prog": "loom knowledge source refresh", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "read": { + "prog": "loom knowledge source read", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "remove": { + "prog": "loom knowledge source remove", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, "required": false, - "help": "A link to remove; repeatable", + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", "metavar": null }, { "option_strings": [ - "--remove-item-json" + "--session-file" ], - "dest": "remove_item_json", - "action": "_AppendAction", - "default": [], + "dest": "session_file", + "action": "_StoreAction", + "default": null, "const": null, "choices": null, "nargs": null, "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "connection": { + "prog": "loom knowledge source connection", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": true, + "defaults": {}, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [ + "source_action" + ] + }, + { + "title": "options", + "description": null, + "dests": [ + "help" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [], + "dest": "source_action", + "action": "_SubParsersAction", + "default": null, + "const": null, + "choices": null, + "nargs": "A...", + "type": null, + "required": true, + "help": null, + "metavar": null, + "subcommands": { + "profiles": { + "prog": "loom knowledge source connection profiles", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "connect": { + "prog": "loom knowledge source connection connect", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent", + "bearer_file" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + }, + { + "option_strings": [ + "--bearer-file" + ], + "dest": "bearer_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 credential file or - for stdin. Never an argv secret.", + "metavar": null + } + ] + }, + "list": { + "prog": "loom knowledge source connection list", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "inspect": { + "prog": "loom knowledge source connection inspect", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "discover": { + "prog": "loom knowledge source connection discover", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "browse": { + "prog": "loom knowledge source connection browse", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "disconnect": { + "prog": "loom knowledge source connection disconnect", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + } + }, + "aliases_of": { + "profiles": "loom knowledge source connection profiles", + "connect": "loom knowledge source connection connect", + "list": "loom knowledge source connection list", + "inspect": "loom knowledge source connection inspect", + "discover": "loom knowledge source connection discover", + "browse": "loom knowledge source connection browse", + "disconnect": "loom knowledge source connection disconnect" + }, + "choices_help": [] + } + ] + }, + "destination": { + "prog": "loom knowledge source destination", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": true, + "defaults": {}, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [ + "source_action" + ] + }, + { + "title": "options", + "description": null, + "dests": [ + "help" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [], + "dest": "source_action", + "action": "_SubParsersAction", + "default": null, + "const": null, + "choices": null, + "nargs": "A...", + "type": null, + "required": true, + "help": null, + "metavar": null, + "subcommands": { + "list": { + "prog": "loom knowledge source destination list", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "create": { + "prog": "loom knowledge source destination create", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "grants": { + "prog": "loom knowledge source destination grants", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "grant": { + "prog": "loom knowledge source destination grant", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "preview": { + "prog": "loom knowledge source destination preview", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + } + }, + "aliases_of": { + "list": "loom knowledge source destination list", + "create": "loom knowledge source destination create", + "grants": "loom knowledge source destination grants", + "grant": "loom knowledge source destination grant", + "preview": "loom knowledge source destination preview" + }, + "choices_help": [] + } + ] + }, + "recording": { + "prog": "loom knowledge source recording", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": true, + "defaults": {}, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [ + "source_action" + ] + }, + { + "title": "options", + "description": null, + "dests": [ + "help" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [], + "dest": "source_action", + "action": "_SubParsersAction", + "default": null, + "const": null, + "choices": null, + "nargs": "A...", + "type": null, + "required": true, + "help": null, + "metavar": null, + "subcommands": { + "add": { + "prog": "loom knowledge source recording add", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent", + "credential_file" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + }, + { + "option_strings": [ + "--credential-file" + ], + "dest": "credential_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Owned mode-0600 credential file or - for stdin. Never an argv secret.", + "metavar": null + } + ] + }, + "list": { + "prog": "loom knowledge source recording list", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "sync-now": { + "prog": "loom knowledge source recording sync-now", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + } + }, + "aliases_of": { + "add": "loom knowledge source recording add", + "list": "loom knowledge source recording list", + "sync-now": "loom knowledge source recording sync-now" + }, + "choices_help": [] + } + ] + }, + "retained": { + "prog": "loom knowledge source retained", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": true, + "defaults": {}, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [ + "source_action" + ] + }, + { + "title": "options", + "description": null, + "dests": [ + "help" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, "required": false, - "help": "An item to remove as JSON, such as {\"type\": \"folder\", \"id\": \"...\"}; repeatable", + "help": "show this help message and exit", "metavar": null + }, + { + "option_strings": [], + "dest": "source_action", + "action": "_SubParsersAction", + "default": null, + "const": null, + "choices": null, + "nargs": "A...", + "type": null, + "required": true, + "help": null, + "metavar": null, + "subcommands": { + "list": { + "prog": "loom knowledge source retained list", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "inspect": { + "prog": "loom knowledge source retained inspect", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + }, + "remove": { + "prog": "loom knowledge source retained remove", + "usage": null, + "description": null, + "epilog": null, + "formatter_class": "argparse:HelpFormatter", + "add_help": true, + "allow_abbrev": false, + "defaults": { + "func": "server.cli.knowledge_source:_dispatch" + }, + "groups": [ + { + "title": "positional arguments", + "description": null, + "dests": [] + }, + { + "title": "options", + "description": null, + "dests": [ + "help", + "server_url", + "org", + "namespace", + "request_file", + "token_file", + "session_file", + "intent" + ] + } + ], + "mutually_exclusive": [], + "arguments": [ + { + "option_strings": [ + "-h", + "--help" + ], + "dest": "help", + "action": "_HelpAction", + "default": "==SUPPRESS==", + "const": null, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "show this help message and exit", + "metavar": null + }, + { + "option_strings": [ + "--server-url" + ], + "dest": "server_url", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--org" + ], + "dest": "org", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": null, + "metavar": null + }, + { + "option_strings": [ + "--namespace" + ], + "dest": "namespace", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Ordinary destination; must agree with the JSON field.", + "metavar": null + }, + { + "option_strings": [ + "--request-file" + ], + "dest": "request_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "UTF-8 JSON API fields, at most 1 MiB; - reads stdin. See the source CLI guide.", + "metavar": null + }, + { + "option_strings": [ + "--token-file" + ], + "dest": "token_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Owned mode-0600 token file or - for stdin; otherwise LOOM_API_KEY.", + "metavar": null + }, + { + "option_strings": [ + "--session-file" + ], + "dest": "session_file", + "action": "_StoreAction", + "default": null, + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": true, + "help": "Existing application-owned private session pointer; never initialized by this command.", + "metavar": null + }, + { + "option_strings": [ + "--intent" + ], + "dest": "intent", + "action": "_StoreAction", + "default": "automatic", + "const": null, + "choices": [ + "automatic", + "explicit" + ], + "nargs": null, + "type": null, + "required": false, + "help": "Default automatic guards every call; explicit is a direct user action.", + "metavar": null + } + ] + } + }, + "aliases_of": { + "list": "loom knowledge source retained list", + "inspect": "loom knowledge source retained inspect", + "remove": "loom knowledge source retained remove" + }, + "choices_help": [] } ] } }, "aliases_of": { - "list": "loom knowledge source list", + "preview": "loom knowledge source preview", "add": "loom knowledge source add", - "update": "loom knowledge source update" + "update": "loom knowledge source update", + "list": "loom knowledge source list", + "inspect": "loom knowledge source inspect", + "pause": "loom knowledge source pause", + "resume": "loom knowledge source resume", + "refresh": "loom knowledge source refresh", + "read": "loom knowledge source read", + "remove": "loom knowledge source remove", + "connection": "loom knowledge source connection", + "destination": "loom knowledge source destination", + "recording": "loom knowledge source recording", + "retained": "loom knowledge source retained" }, - "choices_help": [ - { - "dest": "list", - "help": "List the namespace's sources, items and sync state.", - "metavar": "list" - }, - { - "dest": "add", - "help": "Register a source from links or items, probed with the credential before anything is stored (knowledge.source.add).", - "metavar": "add" - }, - { - "dest": "update", - "help": "Add and remove a source's items or change its file kinds, the added items probed with the stored credential (knowledge.source.update).", - "metavar": "update" - } - ] + "choices_help": [] } ] }, @@ -4539,7 +8672,7 @@ }, { "dest": "source", - "help": "A namespace's document sources, over a running server.", + "help": "MCP sources, connections, collection destinations and recordings.", "metavar": "source" }, { diff --git a/tests/unit/test_cli_knowledge_source.py b/tests/unit/test_cli_knowledge_source.py index db79005c9b..4b6743ff43 100644 --- a/tests/unit/test_cli_knowledge_source.py +++ b/tests/unit/test_cli_knowledge_source.py @@ -1,171 +1,125 @@ -"""`loom knowledge source add|update`: the op body each builds from its flags, and the -refusals it answers on its own, before any request.""" +"""The server CLI delegates source execution to the versioned SDK entry.""" -from __future__ import annotations - -from pathlib import Path +import argparse from types import SimpleNamespace -from typing import Any import pytest -from server.cli import knowledge_source as cli +from server.cli import knowledge_source -LINK = "https://drive.google.com/drive/folders/1AbCdEfGhIjKlMnOp" +def parser(): + value = argparse.ArgumentParser() + knowledge_source.register_knowledge_source_cli(value.add_subparsers(required=True)) + return value -@pytest.fixture -def calls(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, dict[str, Any]]]: - seen: list[tuple[str, dict[str, Any]]] = [] - def _call(args: Any, op: str, body: dict[str, Any]) -> int: - seen.append((op, body)) - return 0 +def arguments(*action): + return parser().parse_args( + [ + "source", + *action, + "--server-url", + "https://loom.invalid", + "--org", + "test-org", + "--session-file", + "/application/session.json", + ] + ) - monkeypatch.setattr(cli, "_call", _call) - return seen +def test_missing_sdk_fails_with_supported_installation_message(monkeypatch, capsys): + def missing(name): + assert name == "loom.source_cli" + raise ModuleNotFoundError("loom") -def _args(**kw: Any) -> SimpleNamespace: - base = {"name": "decks", "kind": "gdrive", "credential_file": "", "dry_run": False} - base |= {"item_json": [], "link": [], "include": [], "remove_item_json": [], "remove_link": []} - return SimpleNamespace(**(base | kw)) + monkeypatch.setattr(knowledge_source.importlib, "import_module", missing) + args = arguments("read", "--request-file", "input.json") + assert args.func(args) == 2 + out = capsys.readouterr() + assert out.out == "" + assert "matching-release clickhouse-loom" in out.err + assert "python -m loom.source_cli" in out.err + assert "server-only wheel" in out.err -def test_add_sends_its_links_and_the_credential_read_from_its_file( - tmp_path: Path, calls: list[Any] -) -> None: - key = tmp_path / "key.json" - key.write_text(' {"k": 1}\n', encoding="utf-8") - assert cli._cmd_add(_args(credential_file=str(key), link=[LINK], include=["pdf"])) == 0 - assert calls == [ - ( - "knowledge.source.add", - { - "name": "decks", - "kind": "gdrive", - "credential": '{"k": 1}', - "dry_run": False, - "links": [LINK], - "include": ["pdf"], - }, - ) - ] +def test_incompatible_entry_does_not_dispatch(monkeypatch, capsys): + entry = SimpleNamespace(SOURCE_CLI_API=0) + monkeypatch.setattr(knowledge_source.importlib, "import_module", lambda name: entry) + args = arguments("list") + assert args.func(args) == 2 + assert "matching-release" in capsys.readouterr().err -def test_add_sends_links_and_items_together(tmp_path: Path, calls: list[Any]) -> None: - key = tmp_path / "key.json" - key.write_text("k", encoding="utf-8") - args = _args(credential_file=str(key), link=[LINK], item_json=['{"type": "file", "id": "x"}']) - assert cli._cmd_add(args) == 0 - [(_, body)] = calls - assert body["items"] == [{"type": "file", "id": "x"}] and body["links"] == [LINK] +def test_matching_entry_receives_exact_parsed_arguments(monkeypatch): + seen = [] + def execute(args): + seen.append(args) + return 7 -def test_add_names_a_credential_file_it_cannot_read( - tmp_path: Path, calls: list[Any], capsys: pytest.CaptureFixture[str] -) -> None: - missing = tmp_path / "missing.json" - assert cli._cmd_add(_args(credential_file=str(missing), link=[LINK])) == 2 - assert "--credential-file: cannot read" in capsys.readouterr().err and calls == [] + entry = SimpleNamespace(SOURCE_CLI_API=2, run_server_entry=execute) + monkeypatch.setattr(knowledge_source.importlib, "import_module", lambda name: entry) + args = arguments("connection", "browse", "--request-file", "selection.json") + assert args.func(args) == 7 + assert seen == [args] + assert args.source_command == "connection" and args.source_action == "browse" + assert args.request_file == "selection.json" + assert args.intent == "automatic" -def test_update_sends_what_it_adds_and_removes(calls: list[Any]) -> None: - args = _args( - item_json=['{"type": "file", "id": "f1"}'], - remove_link=[LINK], - include=["docs"], - ) - assert cli._cmd_update(args) == 0 - assert calls == [ - ( - "knowledge.source.update", - { - "name": "decks", - "add_items": [{"type": "file", "id": "f1"}], - "add_links": [], - "remove_items": [], - "remove_links": [LINK], - "include": ["docs"], - }, - ) - ] +@pytest.mark.parametrize("action", knowledge_source._ACTIONS) +def test_mcp_source_actions_parse_without_importing_sdk(action, monkeypatch): + def forbidden(name): + raise AssertionError("Parser construction must not import SDK runtime") + monkeypatch.setattr(knowledge_source.importlib, "import_module", forbidden) + args = arguments(action, "--namespace", "col-destination") + assert args.source_command == action + assert args.namespace == "col-destination" + assert args.intent == "automatic" -@pytest.mark.parametrize("value", ["[1, 2]", "not json", '"a string"']) -def test_an_item_that_is_not_a_json_object_is_refused( - value: str, tmp_path: Path, calls: list[Any], capsys: pytest.CaptureFixture[str] -) -> None: - key = tmp_path / "key.json" - key.write_text("k", encoding="utf-8") - assert cli._cmd_add(_args(credential_file=str(key), item_json=[value])) == 2 - assert "not a JSON object" in capsys.readouterr().err and calls == [] +@pytest.mark.parametrize( + "flag", ["--link", "--item-json", "--include", "--token", "--credential-file"] +) +def test_native_document_setup_and_argv_credentials_are_absent(flag): + with pytest.raises(SystemExit) as caught: + arguments("add", flag, "value") + assert caught.value.code == 2 -def test_add_names_a_credential_file_that_is_not_text( - tmp_path: Path, calls: list[Any], capsys: pytest.CaptureFixture[str] -) -> None: - key = tmp_path / "key.p12" - key.write_bytes(b"\xff\xfe\x00") - assert cli._cmd_add(_args(credential_file=str(key), link=[LINK])) == 2 - assert "not UTF-8 text" in capsys.readouterr().err and calls == [] +def test_recording_keeps_separate_credential_input(): + args = arguments( + "recording", "add", "--request-file", "recording.json", "--credential-file", "-" + ) + assert args.source_command == "recording" and args.source_action == "add" + assert args.credential_file == "-" -def test_a_bad_remove_item_names_its_own_flag( - calls: list[Any], capsys: pytest.CaptureFixture[str] -) -> None: - assert cli._cmd_update(_args(remove_item_json=["[1]"])) == 2 and calls == [] - assert "--remove-item-json: not a JSON object" in capsys.readouterr().err +def test_connect_does_not_accept_bearer_as_an_argv_option(): + with pytest.raises(SystemExit) as caught: + arguments("connection", "connect", "--bearer", "value") + assert caught.value.code == 2 -@pytest.mark.parametrize( - ("status", "answer", "line"), - [ - ( - 422, - {"detail": {"code": "BAD_LINK", "message": "unreadable links: x"}}, - "knowledge.source.list → HTTP 422 BAD_LINK: unreadable links: x", - ), - ( - 0, - {"detail": "URLError: refused"}, - "knowledge.source.list → no Loom answer: URLError: refused", - ), - (502, {"detail": "login"}, "knowledge.source.list → HTTP 502 Bad Gateway"), - ( - 422, - {"detail": [{"loc": ["body", "links"], "msg": "List should have at most 300 items"}]}, - "knowledge.source.list → HTTP 422 validation_error: body.links: " - "List should have at most 300 items", - ), - ], -) -def test_a_failed_call_prints_one_line_and_exits_1( - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], - status: int, - answer: dict[str, Any], - line: str, -) -> None: - monkeypatch.setattr(cli, "resolve_token", lambda token: ("tok", "flag")) - monkeypatch.setattr(cli, "refused_for_agent", lambda source: False) - monkeypatch.setattr(cli, "post_op", lambda *a, **kw: (status, answer)) - args = SimpleNamespace(token=None, org="acme", namespace="docs", server_url="http://x") - assert cli._cmd_list(args) == 1 - assert capsys.readouterr().err.strip() == line - - -def test_add_with_nothing_to_read_is_refused_before_reading_the_credential( - calls: list[Any], capsys: pytest.CaptureFixture[str] -) -> None: - # No key file at all: the refusal comes first. - assert cli._cmd_add(_args(credential_file="/nonexistent/key.json")) == 2 and calls == [] - assert "give --link or --item-json" in capsys.readouterr().err - - -def test_a_bad_item_is_refused_before_the_credential_is_read( - calls: list[Any], capsys: pytest.CaptureFixture[str] -) -> None: - args = _args(credential_file="/nonexistent/key.json", item_json=["[1]"]) - assert cli._cmd_add(args) == 2 and calls == [] - assert "not a JSON object" in capsys.readouterr().err + +def test_session_pointer_is_required(): + with pytest.raises(SystemExit) as caught: + parser().parse_args( + ["source", "list", "--server-url", "https://loom.invalid", "--org", "test-org"] + ) + assert caught.value.code == 2 + + +def test_root_explicit_intent_is_forwarded_to_one_source_dispatch(monkeypatch): + from server.cli._session_context import invocation + + seen = [] + entry = SimpleNamespace(SOURCE_CLI_API=2, run_server_entry=lambda args: seen.append(args) or 7) + monkeypatch.setattr(knowledge_source.importlib, "import_module", lambda name: entry) + args = arguments("list") + with invocation("explicit"): + assert args.func(args) == 7 + assert seen[0] is not args and seen[0].intent == "explicit" + assert args.intent == "automatic" diff --git a/tests/unit/test_cli_knowledge_source_installed.py b/tests/unit/test_cli_knowledge_source_installed.py new file mode 100644 index 0000000000..e53a9502e9 --- /dev/null +++ b/tests/unit/test_cli_knowledge_source_installed.py @@ -0,0 +1,114 @@ +"""Installed server/SDK CLI contract; run in the hosted environment with both wheels.""" + +import argparse + +import pytest +from loom import cli_context, source_cli + +from server.cli import knowledge_source +from server.identity.api.models_collections import CollectionCreateInput, CollectionListInput +from server.identity.api.models_grants import GrantsCreateInput, GrantsListInput +from server.knowledge.api.models_mcp_connections import ( + MCPBrowseInput, + MCPConnectInput, + MCPInspectInput, + MCPListInput, + MCPSlotInput, +) +from server.knowledge.api.models_mcp_profiles import MCPProfilesInput +from server.knowledge.api.models_mcp_reads import MCPReadInput +from server.knowledge.api.models_mcp_sources import ( + MCPSourceAddInput, + MCPSourceInput, + MCPSourceInspectInput, + MCPSourceListInput, + MCPSourcePreviewInput, + MCPSourceRemoveInput, + MCPSourceUpdateInput, +) +from server.knowledge.api.models_sources import ( + KnowledgeSourceAddInput, + KnowledgeSourceInspectInput, + KnowledgeSourceListInput, + KnowledgeSourceRemoveInput, + KnowledgeSourceSyncNowInput, +) + +MODELS = { + "knowledge.connection.mcp_connect": MCPConnectInput, + "knowledge.connection.mcp_list": MCPListInput, + "knowledge.connection.mcp_inspect": MCPInspectInput, + "knowledge.connection.mcp_discover": MCPSlotInput, + "knowledge.connection.mcp_browse": MCPBrowseInput, + "knowledge.connection.mcp_disconnect": MCPSlotInput, + "knowledge.source.mcp_profiles": MCPProfilesInput, + "knowledge.source.mcp_preview": MCPSourcePreviewInput, + "knowledge.source.mcp_add": MCPSourceAddInput, + "knowledge.source.mcp_update": MCPSourceUpdateInput, + "knowledge.source.mcp_list": MCPSourceListInput, + "knowledge.source.mcp_inspect": MCPSourceInspectInput, + "knowledge.source.mcp_pause": MCPSourceInput, + "knowledge.source.mcp_resume": MCPSourceInput, + "knowledge.source.mcp_refresh": MCPSourceInput, + "knowledge.source.mcp_read": MCPReadInput, + "knowledge.source.mcp_remove": MCPSourceRemoveInput, + "collection.create": CollectionCreateInput, + "collection.list": CollectionListInput, + "grants.create": GrantsCreateInput, + "grants.list": GrantsListInput, + "knowledge.source.add": KnowledgeSourceAddInput, + "knowledge.source.list": KnowledgeSourceListInput, + "knowledge.source.inspect": KnowledgeSourceInspectInput, + "knowledge.source.remove": KnowledgeSourceRemoveInput, + "knowledge.source.sync_now": KnowledgeSourceSyncNowInput, +} +COMMAND_GROUPS = [ + source_cli._COMMANDS, + source_cli._CONNECTION_COMMANDS, + source_cli._DESTINATION_COMMANDS, + source_cli._RECORDING_COMMANDS, + source_cli._RETAINED_COMMANDS, +] + + +def leaves(parser, path=()): + result = {} + children = [a for a in parser._actions if isinstance(a, argparse._SubParsersAction)] + if not children: + result[path] = ( + parser.allow_abbrev, + {(a.dest, a.required, tuple(a.option_strings)) for a in parser._actions}, + ) + for child in children: + for name, nested in child.choices.items(): + result.update(leaves(nested, (*path, name))) + return result + + +def test_server_and_sdk_entry_points_expose_same_commands_and_input_requirements(): + server = argparse.ArgumentParser() + knowledge_source.register_knowledge_source_cli(server.add_subparsers(required=True)) + sdk = argparse.ArgumentParser() + source_cli.register_source_cli(sdk.add_subparsers(required=True)) + assert leaves(server) == leaves(sdk) + assert knowledge_source._SOURCE_CLI_API == source_cli.SOURCE_CLI_API + assert source_cli.SOURCE_CLI_API == 2 + assert cli_context.CLI_CONTEXT_API == 1 + assert cli_context.CONTEXT_ENV == "LOOM_SOURCE_SESSION_CONTEXT" + + +@pytest.mark.parametrize( + "command", [command for group in COMMAND_GROUPS for command in group.values()] +) +def test_cli_request_surface_matches_actual_api_fields(command): + model = MODELS[command.op] + fields = {"org", *command.fields.split()} + if command.secret: + fields.add(command.secret) + assert fields == set(model.model_fields) + required = {name for name, field in model.model_fields.items() if field.is_required()} + assert { + "org", + *command.required.split(), + *([command.secret] if command.secret == "credential" else []), + } == required diff --git a/tests/unit/test_cli_source_context.py b/tests/unit/test_cli_source_context.py new file mode 100644 index 0000000000..25dbdfe457 --- /dev/null +++ b/tests/unit/test_cli_source_context.py @@ -0,0 +1,173 @@ +"""Pure common CLI context and one-dispatch intent contracts; no installed SDK needed.""" + +import asyncio +import contextvars +import urllib.request +from types import SimpleNamespace + +import pytest + +from server.cli import _client +from server.cli import _session_context as context + + +@pytest.fixture +def bound(monkeypatch): + monkeypatch.setenv(context.CONTEXT_ENV, "trusted-capsule") + + +def test_unbound_helpers_do_not_load_sdk(monkeypatch): + monkeypatch.delenv(context.CONTEXT_ENV, raising=False) + + def forbidden(): + raise AssertionError("Unbound CLI must not import SDK") + + monkeypatch.setattr(context, "_entry", forbidden) + assert context.send(urllib.request.Request("https://loom.invalid/v1/memory.set"), 1) is None + + +def test_configured_context_has_actionable_missing_sdk_refusal(bound, monkeypatch): + def missing(name): + assert name == "loom.cli_context" + raise ModuleNotFoundError("loom") + + monkeypatch.setattr(context.importlib, "import_module", missing) + with pytest.raises(context.CLIContextError, match="matching-release clickhouse-loom"): + _client.post_op("https://loom.invalid", "memory.set", {}, "token") + + +def test_context_cannot_change_or_disappear_during_dispatch(bound, monkeypatch): + for replacement in (None, "other-capsule"): + with context.invocation(): + if replacement is None: + monkeypatch.delenv(context.CONTEXT_ENV) + else: + monkeypatch.setenv(context.CONTEXT_ENV, replacement) + with pytest.raises(context.CLIContextError, match="changed during dispatch"): + context.capsule() + monkeypatch.setenv(context.CONTEXT_ENV, "trusted-capsule") + + +def test_explicit_intent_expires_in_copied_callback_context(bound): + with context.invocation("explicit"): + assert context._explicit() + copied = contextvars.copy_context() + assert not context._explicit() + assert not copied.run(context._explicit) + with context.invocation(): + assert not context._explicit() + + +def test_automatic_task_cannot_inherit_direct_user_intent(bound): + async def scenario(): + with context.invocation("explicit"): + assert context._explicit() + + async def callback(): + return context._explicit() + + assert not await asyncio.create_task(callback()) + assert context._explicit() + assert not context._explicit() + + asyncio.run(scenario()) + + +def test_raw_file_and_json_posts_reach_same_bridge(bound, monkeypatch): + calls = [] + + async def request(*args, **kwargs): + calls.append((args, kwargs)) + return SimpleNamespace(status_code=200, json=lambda: {"ok": True}) + + def run_sync(factory): + return asyncio.run(factory()) + + entry = SimpleNamespace(request=request, run_sync=run_sync) + monkeypatch.setattr(context, "_entry", lambda: entry) + with context.invocation("explicit"): + assert _client.post_op("https://loom.invalid", "memory.set", {"key": "x"}, "token") == ( + 200, + {"ok": True}, + ) + assert _client.post_bytes( + "https://other.invalid/v1/knowledge.upload", b"file", "other" + ) == (200, {"ok": True}) + assert calls[0][0] == ("trusted-capsule", "POST", "https://loom.invalid/v1/memory.set", "token") + assert calls[0][1]["body"] == {"key": "x"} + assert calls[0][1]["content"] is None + assert calls[1][1]["content"] == b"file" and calls[1][1]["body"] is None + assert all(kwargs["explicit"] for _, kwargs in calls) + + +def test_async_helper_keeps_ordinary_client_request(monkeypatch): + monkeypatch.delenv(context.CONTEXT_ENV, raising=False) + calls = [] + + async def post(*args, **kwargs): + calls.append((args, kwargs)) + return "response" + + async def scenario(): + assert ( + await context.post( + SimpleNamespace(post=post), "/v1/memory.set", "token", body={"key": "x"} + ) + == "response" + ) + + asyncio.run(scenario()) + assert calls == [(("/v1/memory.set",), {"json": {"key": "x"}})] + + +def test_root_dispatch_consumes_and_expires_explicit_intent(bound, monkeypatch): + from server.cli import app + + copied = [] + + def build(sub): + sub.add_parser("test-request") + + def dispatch(args): + assert not hasattr(args, "request_intent") + assert context._explicit() + copied.append(contextvars.copy_context()) + return 7 + + monkeypatch.setattr(app, "_SUBCOMMAND_BUILDERS", [build]) + monkeypatch.setattr(app, "wire", lambda: None) + monkeypatch.setattr(app, "_load_dotenv_like_the_container", lambda: None) + monkeypatch.setattr(app, "_dispatch", dispatch) + assert app.main(["--request-intent", "explicit", "test-request"]) == 7 + assert not context._explicit() and not copied[0].run(context._explicit) + + +@pytest.mark.parametrize( + "prefix", [["--request-intent", "explicit"], ["--request-intent=explicit"]] +) +def test_root_sdk_delegation_keeps_one_invocation_intent(prefix, monkeypatch): + from server.cli import app + + seen = [] + monkeypatch.setattr(app, "run_sdk_command", lambda raw: seen.append(raw) or 7) + args = [*prefix, "call", "memory.set", "key=x"] + assert app.main(args) == 7 + assert seen == [args] + + +def test_async_command_borrows_intent_only_for_its_dispatch(bound, monkeypatch): + copied = [] + monkeypatch.setattr( + context, "_entry", lambda: SimpleNamespace(run_sync=lambda factory: asyncio.run(factory())) + ) + + async def command(): + assert context._explicit() + copied.append(contextvars.copy_context()) + return 7 + + with context.invocation("explicit"): + assert context.run_async(command) == 7 + assert context._explicit() + assert not copied[0].run(context._explicit) + assert not context._explicit() diff --git a/tests/unit/test_sdk_source_client_readiness.py b/tests/unit/test_sdk_source_client_readiness.py new file mode 100644 index 0000000000..d7e8a4d3f8 --- /dev/null +++ b/tests/unit/test_sdk_source_client_readiness.py @@ -0,0 +1,313 @@ +"""Request admission and response capture share the real HTTPX transport hooks.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import httpx +import pytest +from loom.errors import LoomError +from loom.session_protection import ( + AutomaticCaptureSuppressed, + SessionProtection, + SessionProtectionUnavailable, + observation_scope, +) +from loom.transport import Transport + +HEADER = "x-loom-session-protection" +PRIVATE = "private-source-value" + + +def client(root, respond): + transport = Transport( + "https://loom.invalid", "test-secret", pacing=False, session_protection=root + ) + # Preserve the real hooks, auth, header merge and response processing. + transport._client._transport = httpx.MockTransport(respond) + transport._client._mounts.clear() + return transport + + +@pytest.mark.asyncio +async def test_actual_source_request_declares_only_bound_ready_family(tmp_path: Path): + root = SessionProtection.create(base=tmp_path / "families") + requests = [] + + def respond(request): + requests.append(request) + return httpx.Response(200, json={"mirrored": True, "content": PRIVATE}) + + transport = client(root, respond) + try: + body = await transport.post("/v1/knowledge.source.mcp_read", {"namespace": "source"}) + assert body["content"] == PRIVATE + assert requests[0].url.path == "/v1/knowledge.source.mcp_read" + assert requests[0].headers.get_list(HEADER) == ["v1"] + assert requests[0].headers["authorization"] == "Bearer test-secret" + assert root.protected + with pytest.raises(AutomaticCaptureSuppressed), root.automatic(): + await transport.post("/v1/memory.set", {"namespace": "elsewhere", "value": PRIVATE}) + assert len(requests) == 1 + # Explicit actions remain observed, including after token/session changes. + transport._client.headers["Authorization"] = "Bearer changed-secret" + await transport.post("/v1/memory.get", {"org": "other", "session_id": "other"}) + assert root.protected + assert requests[-1].headers["authorization"] == "Bearer changed-secret" + finally: + await transport.close() + + +@pytest.mark.asyncio +async def test_ordinary_requests_make_no_promise(): + requests = [] + + def respond(request): + requests.append(request) + return httpx.Response(200, json={"ok": True}) + + transport = client(None, respond) + try: + assert await transport.post("/v1/memory.get", {}) == {"ok": True} + assert HEADER not in requests[0].headers + finally: + await transport.close() + + +@pytest.mark.asyncio +async def test_open_callback_cannot_publish_with_a_new_unbound_client(tmp_path: Path): + root = SessionProtection.create(base=tmp_path / "families") + requests = [] + + def respond(request): + requests.append(request) + assert request.headers.get_list(HEADER) == ["v1"] + return httpx.Response(200, json={"mirrored": True, "value": PRIVATE}) + + reader = client(root, respond) + writer = client(None, respond) + try: + with root.automatic(): + await reader.post("/v1/knowledge.source.mcp_read", {}) + with pytest.raises(AutomaticCaptureSuppressed): + await writer.post("/v1/memory.set", {"namespace": "elsewhere", "value": PRIVATE}) + assert len(requests) == 1 + assert root.protected + finally: + await reader.close() + await writer.close() + + +@pytest.mark.asyncio +async def test_unbound_source_read_preserves_server_readiness_refusal(): + def respond(request): + assert request.url.path == "/v1/knowledge.source.mcp_read" + assert HEADER not in request.headers + return httpx.Response( + 409, + json={ + "detail": { + "code": "SESSION_PROTECTION_REQUIRED", + "message": "Session protection required", + } + }, + ) + + transport = client(None, respond) + try: + with pytest.raises(LoomError) as caught: + await transport.post("/v1/knowledge.source.mcp_read", {}) + assert caught.value.code == "SESSION_PROTECTION_REQUIRED" + finally: + await transport.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("bound", [False, True]) +@pytest.mark.parametrize( + "headers", [{HEADER: "v1"}, {HEADER: "v2"}, {HEADER: "v1", HEADER.upper(): "v1"}] +) +async def test_caller_cannot_supply_or_duplicate_declaration(tmp_path: Path, bound, headers): + root = SessionProtection.create(base=tmp_path / "families") if bound else None + requests = [] + transport = client(root, lambda request: requests.append(request)) + try: + with pytest.raises(SessionProtectionUnavailable): + await transport.post_with_meta("/v1/memory.get", {}, extra_headers=headers) + assert requests == [] + finally: + await transport.close() + + +@pytest.mark.asyncio +async def test_callback_cannot_manufacture_readiness_and_failure_restores_scope(tmp_path: Path): + root = SessionProtection.create(base=tmp_path / "families") + transport = client(root, lambda request: httpx.Response(200, json={"ok": True})) + + async def callback(path, payload): + raise RuntimeError("callback failed") + + try: + transport.before_post = callback + with root.automatic(), pytest.raises(RuntimeError, match="callback failed"): + await transport.post("/v1/memory.get", {}) + assert not root.protected + transport.before_post = None + plain = client( + None, lambda request: httpx.Response(200, json={"declared": HEADER in request.headers}) + ) + try: + assert await plain.post("/v1/memory.get", {}) == {"declared": False} + finally: + await plain.close() + finally: + await transport.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("failure", ["missing", "incompatible", "observer"]) +async def test_invalid_control_or_missing_observer_refuses_before_network(tmp_path: Path, failure): + root = SessionProtection.create(base=tmp_path / "families") + requests = [] + transport = client(root, lambda request: requests.append(request)) + if failure == "missing": + await asyncio.to_thread((root.base / root.id / "state").unlink) + elif failure == "incompatible": + await asyncio.to_thread((root.base / root.id / "state").write_bytes, b"unknown") + else: + transport._client.event_hooks["response"].clear() + try: + with pytest.raises(SessionProtectionUnavailable): + await transport.post("/v1/knowledge.source.mcp_read", {}) + assert requests == [] + finally: + await transport.close() + + +@pytest.mark.asyncio +async def test_cross_origin_refusal_and_independent_families(tmp_path: Path): + first = SessionProtection.create(base=tmp_path / "families") + other = SessionProtection.create(base=tmp_path / "families") + requests = [] + transport = client(first, lambda request: requests.append(request)) + try: + with pytest.raises(SessionProtectionUnavailable): + await transport._client.get("https://upstream.invalid/resource") + assert requests == [] + first.mark() + second = client(other, lambda request: httpx.Response(200, json={"ok": True})) + try: + with other.automatic(): + assert await second.post("/v1/memory.get", {}) == {"ok": True} + assert not other.protected + with observation_scope((first,)): + assert await second.post("/v1/memory.get", {}) == {"ok": True} + assert first.protected and not other.protected + finally: + await second.close() + finally: + await transport.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [200, 403]) +async def test_json_errors_observed_without_private_diagnostics(tmp_path: Path, status): + root = SessionProtection.create(base=tmp_path / "families") + requests = [] + + def respond(request): + requests.append(request) + return httpx.Response(status, content=PRIVATE, headers={"content-type": "application/json"}) + + transport = client(root, respond) + try: + with pytest.raises(SessionProtectionUnavailable) as caught: + await transport.post("/v1/knowledge.source.mcp_read", {}) + assert PRIVATE not in str(caught.value) + assert root.protected + assert requests[0].headers[HEADER] == "v1" + finally: + await transport.close() + + +@pytest.mark.asyncio +async def test_error_data_marks_before_typed_error_and_preserves_headers(tmp_path: Path): + root = SessionProtection.create(base=tmp_path / "families") + transport = client( + root, + lambda request: httpx.Response( + 403, + json={ + "error": {"code": "FORBIDDEN", "message": "refused", "data": {"mirrored": True}}, + }, + headers={"X-Request-Id": "protected-error"}, + ), + ) + try: + with pytest.raises(LoomError) as caught: + await transport.post("/v1/knowledge.source.mcp_read", {}) + assert root.protected + assert caught.value.request_id == "protected-error" + finally: + await transport.close() + + +class Events(httpx.AsyncByteStream): + def __init__(self, mode): + self.mode = mode + self.closed = False + + async def __aiter__(self): + if self.mode == "cancel": + raise asyncio.CancelledError() + yield b'data: {"mirrored":true,"content":"private-source-value"}\n\n' + if self.mode == "partial": + yield b'data: {"content":"unfinished' + + async def aclose(self): + self.closed = True + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["complete", "partial", "cancel", "early"]) +async def test_stream_admission_observation_and_owned_cleanup(tmp_path: Path, mode): + root = SessionProtection.create(base=tmp_path / "families") + events = Events(mode) + requests = [] + + def respond(request): + requests.append(request) + return httpx.Response( + 200, + stream=events, + headers={"content-type": "text/event-stream", "X-Request-Id": "events"}, + ) + + transport = client(root, respond) + try: + + async def consume(): + async with transport.stream("/v1/source-events", json={}) as response: + assert response.headers["X-Request-Id"] == "events" + if mode == "early": + return + async for chunk in response.aiter_bytes(): + assert root.protected + assert PRIVATE.encode() in chunk + + if mode == "cancel": + with pytest.raises(asyncio.CancelledError): + await consume() + elif mode == "partial": + with pytest.raises(SessionProtectionUnavailable): + await consume() + else: + await consume() + assert requests[0].headers.get_list(HEADER) == ["v1"] + assert root.protected + assert events.closed + with pytest.raises(AutomaticCaptureSuppressed), root.automatic(): + await transport.post("/v1/memory.set", {"namespace": "elsewhere", "value": PRIVATE}) + finally: + await transport.close() diff --git a/tests/unit/test_sdk_source_download.py b/tests/unit/test_sdk_source_download.py new file mode 100644 index 0000000000..293072580c --- /dev/null +++ b/tests/unit/test_sdk_source_download.py @@ -0,0 +1,164 @@ +"""Opaque GET bytes retain durable response authority through the actual SDK hooks.""" + +from __future__ import annotations + +import asyncio +from pathlib import Path + +import httpx +import pytest +from loom.errors import LoomError +from loom.session_protection import ( + AutomaticCaptureSuppressed, + SessionProtection, + SessionProtectionUnavailable, +) + +from tests.unit.test_sdk_source_client_readiness import HEADER, PRIVATE, client + + +class Body(httpx.AsyncByteStream): + def __init__(self, chunks: list[bytes], *, hold: bool = False): + self.chunks = chunks + self.hold = hold + self.waiting = asyncio.Event() + self.closed = False + + async def __aiter__(self): + for chunk in self.chunks: + yield chunk + if self.hold: + self.waiting.set() + await asyncio.Event().wait() + + async def aclose(self): + self.closed = True + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "media", + [ + "text/plain", + "application/pdf", + "application/octet-stream", + "application/json", + "application/x-ndjson", + ], +) +async def test_opaque_download_marks_before_release_and_reopens(tmp_path: Path, media: str): + root = SessionProtection.create(base=tmp_path / "families") + sent = [] + stream = Body([PRIVATE.encode(), b"\nnot an envelope\n"]) + + def respond(request): + sent.append(request) + assert request.method == "GET" and request.url.path == "/v1/knowledge.download" + assert request.url.params["namespace"] == "source" + assert request.headers.get_list(HEADER) == ["v1"] + assert request.headers["accept-encoding"] == "identity" + return httpx.Response( + 200, headers={"Content-Type": media, "Content-Disposition": "attachment"}, stream=stream + ) + + transport = client(root, respond) + writer = client(None, respond) + try: + response = await transport.download( + "/v1/knowledge.download", params={"namespace": "source"} + ) + assert root.protected and SessionProtection.open(root.pointer()).protected + assert response.content == PRIVATE.encode() + b"\nnot an envelope\n" + assert response.headers["content-disposition"] == "attachment" + assert stream.closed and len(sent) == 1 + with pytest.raises(AutomaticCaptureSuppressed), root.automatic(): + await writer.post("/v1/memory.set", {"namespace": "other", "value": PRIVATE}) + assert len(sent) == 1 + finally: + await transport.close() + await writer.close() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["bytes", "chunks", "encoding", "error"]) +async def test_download_failure_retains_protection_and_closes(tmp_path: Path, mode: str): + root = SessionProtection.create(base=tmp_path / "families") + stream = Body([b"x"] * 4097 if mode == "chunks" else [b"123456789"]) + headers = {"Content-Type": "application/octet-stream"} + if mode == "encoding": + headers["Content-Encoding"] = "gzip" + if mode == "error": + stream = Body( + [b'{"error":{"code":"FAILED","message":"private diagnostic"},"mirrored":true}'] + ) + headers = {"Content-Type": "application/json"} + transport = client( + root, + lambda request: httpx.Response( + 403 if mode == "error" else 200, headers=headers, stream=stream + ), + ) + try: + with pytest.raises((SessionProtectionUnavailable, LoomError)): + await transport.download( + "/v1/knowledge.download", max_bytes=8 if mode == "bytes" else 8192 + ) + assert root.protected and stream.closed + finally: + await transport.close() + + +@pytest.mark.asyncio +async def test_cancelled_download_joins_owned_body(tmp_path: Path): + root = SessionProtection.create(base=tmp_path / "families") + stream = Body([b"prefix"], hold=True) + transport = client( + root, + lambda request: httpx.Response(200, headers={"Content-Type": "text/plain"}, stream=stream), + ) + task = asyncio.create_task(transport.download("/v1/knowledge.download")) + try: + await asyncio.wait_for(stream.waiting.wait(), 2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(task, 2) + assert root.protected and stream.closed + finally: + if not task.done(): + task.cancel() + await asyncio.gather(task, return_exceptions=True) + await transport.close() + + +@pytest.mark.asyncio +async def test_unbound_public_download_has_no_declaration(): + sent = [] + + def respond(request): + sent.append(request) + return httpx.Response(200, content=b"ordinary bytes") + + transport = client(None, respond) + try: + assert (await transport.download("/download")).content == b"ordinary bytes" + assert HEADER not in sent[0].headers + finally: + await transport.close() + + +@pytest.mark.asyncio +async def test_download_does_not_release_bytes_when_marking_fails(tmp_path: Path, monkeypatch): + root = SessionProtection.create(base=tmp_path / "families") + stream = Body([PRIVATE.encode()]) + transport = client(root, lambda request: httpx.Response(200, stream=stream)) + + def fail(self): + raise SessionProtectionUnavailable() + + monkeypatch.setattr(SessionProtection, "mark", fail) + try: + with pytest.raises(SessionProtectionUnavailable): + await transport.download("/download") + assert stream.closed + finally: + await transport.close() From 5c6d1499ac528ea0e7ecfab89be9a99a66ccca57 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 06:47:36 +0000 Subject: [PATCH 26/30] Exercise private source reads across installed CLI commands Use the hosted owned source fixture and built SDK wheel for cross-command protection checks. Remove the retired native account command and describe source setup and retained registrations. Signed-off-by: zlareb1 --- .../workflows/mcp-source-qualification.yml | 3 +- docs/architecture/mcp-document-sources.md | 8 +- docs/guides/mcp-source-cli.md | 10 +- docs/guides/mcp-sources.md | 92 ++++++++++++++++++ docs/reference/python-sdk.md | 13 ++- llms.txt | 1 + scripts/ops/qualify_mcp_sources.py | 2 + sdk/python/loom/cli.py | 81 +--------------- server/cli/login.py | 3 +- .../test_mcp_source_qualification.py | 97 +++++++++++++++++++ tests/unit/snapshots/cli_help.json | 7 +- tests/unit/snapshots/cli_tree.json | 32 +----- 12 files changed, 221 insertions(+), 128 deletions(-) create mode 100644 docs/guides/mcp-sources.md diff --git a/.github/workflows/mcp-source-qualification.yml b/.github/workflows/mcp-source-qualification.yml index 04a452721d..db04f028ad 100644 --- a/.github/workflows/mcp-source-qualification.yml +++ b/.github/workflows/mcp-source-qualification.yml @@ -171,7 +171,8 @@ jobs: - name: Install the locked dependencies run: | uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code >/dev/null 2>&1 - uv pip install --no-deps -e sdk/python >/dev/null 2>&1 + uv build --wheel sdk/python --out-dir "$RUNNER_TEMP/mcp-sdk-wheel" >/dev/null 2>&1 + uv pip install --no-deps "$RUNNER_TEMP"/mcp-sdk-wheel/*.whl >/dev/null 2>&1 echo "$PWD/.venv/bin" >> "$GITHUB_PATH" - name: Initialize fresh synthetic secrets and exact ownership id: ownership diff --git a/docs/architecture/mcp-document-sources.md b/docs/architecture/mcp-document-sources.md index 2977e9bf2c..107cc501fa 100644 --- a/docs/architecture/mcp-document-sources.md +++ b/docs/architecture/mcp-document-sources.md @@ -10,8 +10,8 @@ service differences; tool descriptions and models do not decide permissions. ## Transport and operation approval -The client uses the official MCP SDK over remote HTTPS Streamable HTTP. Qualified -profiles support anonymous access or a preissued bearer bound to the exact approved +The client uses the official MCP SDK over remote HTTPS Streamable HTTP. Supported +profiles use anonymous access or a preissued bearer bound to the exact approved origin and audience. Loom credentials never authenticate to the remote server. OAuth enrollment and refresh, local commands or stdio, legacy SSE, binary resources and unstructured tool-result inference are outside this contract. Protocol support @@ -181,7 +181,9 @@ Deterministic servers exercise resource-based and mapped-tool reads through the same official SDK engine. Functional qualification uses owned stores and synthetic identities, real knowledge writes and protected readbacks. Scale qualification uses a frozen synthetic registry and measures query work, bounded scheduling and -latency. In-process ASGI transport does not qualify TCP, TLS, DNS, proxy behavior, +latency. The CLI qualification also uses an owned loopback HTTP listener for +installed-client subprocesses. In-process remote ASGI transport does not qualify +external TCP, TLS, DNS, proxy behavior, external vendor capacity or every server marketed as MCP. No provider or model calls are needed for these tests. Only actual exact-head hosted receipts establish a qualification result; authored tests and protocol compatibility are not provider diff --git a/docs/guides/mcp-source-cli.md b/docs/guides/mcp-source-cli.md index e799f62f26..29250a05f6 100644 --- a/docs/guides/mcp-source-cli.md +++ b/docs/guides/mcp-source-cli.md @@ -204,8 +204,8 @@ original request file and session proof after cancellation or interruption. selected recording IDs. `recording list` calls `knowledge.source.list` with `namespace`; `recording sync-now` accepts `namespace`, `name` and optional `full`. -`retained list`, `retained inspect` and `retained remove` expose ordinary source -listing, inspection and retirement. Inspection takes `namespace` and `name`; -removal also requires `confirm` and accepts `delete_documents`. Retained native -document sources remain unavailable for execution. Document setup and updates use -the MCP controls above. +`retained list` exposes ordinary source metadata, and `retained remove` requests +explicit retirement with `namespace`, `name` and `confirm`; `delete_documents` +separately requests copy erasure. Inspection can refuse unsupported retained source +kinds. Retained native document sources remain unavailable for execution. Document +setup, updates and MCP inspection use the MCP controls above. diff --git a/docs/guides/mcp-sources.md b/docs/guides/mcp-sources.md new file mode 100644 index 0000000000..368b74184f --- /dev/null +++ b/docs/guides/mcp-sources.md @@ -0,0 +1,92 @@ +# Connect selected documents through MCP + +An MCP source reads selected resources from an operator-approved remote server. +The server must expose readable resources or approved read and search tools. +Protocol compatibility alone does not establish that a service can supply documents. + +Loom supports remote HTTPS Streamable HTTP with anonymous access or an existing +bearer for the exact approved endpoint and audience. OAuth enrollment and refresh, +local commands, stdio, legacy SSE and binary resource imports are outside this +source profile. Connecting never starts an arbitrary local server command. + +## Set up a source + +Open **Sources** from the Library, then choose an approved connection profile. +Check the displayed server origin, account-verification limits and capabilities. +A connection belongs to the signed-in owner. Another user's destination grant does +not let them use that owner's connection. This setup binds the supplied credential +to that owner; a team destination does not create a shareable account connection. + +1. Connect the account with its authorized credential. Keep the request identifier + until inspection confirms the result; an interrupted response is not evidence + that connecting failed. +2. Discover capabilities. Browse the bounded metadata window or enter exact + resource identities when enumeration is unavailable. Select the resources to read. + A server with only action tools cannot become a source by marking them read-only. +3. Choose **Live**, **Snapshot** or **Selected refresh**. Live returns selected + content on demand without importing it. Snapshot imports once; selected refresh + re-reads the saved selection. Neither mode discovers future documents automatically. +4. Choose an ordinary private or team collection, or create one. A team child inherits + its parent's grants. The automatic personal namespace cannot be a source destination. +5. Preview effective access and capability limits. Owner-only access requires both + the source owner and destination permission. A team copy is a separate intentional + publication: it requires operator approval, destination administrator authority + and explicit confirmation for that selection. A shared destination alone does + not publish private content. +6. Save once. If the outcome is uncertain, inspect using the original request + identifier and connection slot before making another mutation. + +The preview describes current rules and grants no authority. Changes to account +standing, grants, operator approval or selected scope can refuse a later request. +Collection grants describe local access, not a complete list of upstream readers. + +## Read and maintain the selection + +Live retrieval and direct reads use the existing search and protected-result paths. +Selected imports use ordinary knowledge documents, chunks, originals and revisions. +Their local citation identifies the source registration and exact resource; it is +not an upstream URL and grants no access. A protected participating client must +retain session proof and guard later automatic writes before it can receive private +results. Adding a header alone does not implement this contract. + +A snapshot's current-read proof expires under the ordinary freshness policy. +Refresh it explicitly when needed. Selected refresh needs the source worker enabled; +a saved registration by itself does not import anything. A changed selection has a +new scope revision, and old successful reads cannot authorize it. + +Pause and disconnect stop local access while retaining stored copies. Disconnect +does not revoke a bearer at its issuer. Remove explicitly retires the registration; +request document deletion separately when authorized. Missing resources, partial +pages and failed reads never authorize deletion. A schema mismatch can stop the +current binding and require a fresh owner-approved connection. + +The supported contract does not synchronize upstream ACLs, prove a complete listing +or infer deletion. For a team copy, confirm that you may publish the exact material +under the destination's grants. Imported bytes and account history follow ordinary +retention and writer-requested erasure. Live lookup has no persistent result cache +or automatic memory save; the remote host and participating clients retain their +own requests, traces and conversations under their respective policies. + +## API, SDK and CLI controls + +The API exposes approved profiles, connect, list, inspect, discover, browse and +disconnect under `knowledge.connection.mcp_*`. Source preview, add, update, list, +inspect, pause, resume, refresh, read and remove use `knowledge.source.mcp_*`. +Ordinary `collection.*` and `grants.*` operations manage destinations. SDK operation +calls use the same arguments and authority; no client grants additional access. + +Use the [source CLI guide](mcp-source-cli.md) for exact operation mappings, private +credential files, request reconciliation and the application-owned protected-session +context. The dashboard, CLI and SDKs require their actual protection implementation; +unbound automatic tools and nonparticipating applications are not qualified simply +because they can send HTTP. + +Native document-source registrations remain retained and unavailable in the +replacement build. They are not converted into MCP connections. Their owners must +choose an approved endpoint, authorize a fresh account binding, select content and +preview access. Existing documents, originals, credentials and checkpoints are not +deleted as upgrade cleanup. Recording sources remain separate. + +See [MCP document sources](../architecture/mcp-document-sources.md) for operator +approval, storage authority, rolling upgrades and qualification boundaries. Synthetic +protocol tests are not qualification of an external service. diff --git a/docs/reference/python-sdk.md b/docs/reference/python-sdk.md index 59bfca86bf..890ad71cf6 100644 --- a/docs/reference/python-sdk.md +++ b/docs/reference/python-sdk.md @@ -115,9 +115,16 @@ A marked response durably protects every known family before returning. A failed withholds the response. `with family.automatic():` classifies an application's callback; the final request hook checks protection after authentication and on every replay. Explicit actions outside automatic callbacks remain available after protection and still -observe responses. This option does not declare protocol capability. The serving build, -other consumers, launchers and framework callbacks require their separate qualification -before mirrored reads are enabled. +observe responses. The transport declares the session-protection protocol only when +the durable guard and raw-response observer are installed and ready. Supplied +capability headers are refused. The serving build, other consumers, launchers and +framework callbacks require their separate qualification before mirrored reads are +enabled. + +`Transport.download()` retains and protects all contributing families before returning +opaque bytes. It uses the same-origin request path, refuses compressed protected +responses and bounds body size, chunks and cleanup. Its 64 MiB ceiling can be lowered +per request. This method does not expand the supported remote MCP import media. `Session.resume()` and `history()` are automatic reads. The first marked recall can return after durable observation; a marked pack skips the optional history request. diff --git a/llms.txt b/llms.txt index c2a46d2861..18bbb8de6a 100644 --- a/llms.txt +++ b/llms.txt @@ -95,6 +95,7 @@ Start with [the docs map](docs/index.md). To install Loom, a coding agent reads - [Import ClickGap memory](docs/guides/importing-clickgap-memory.md): `loom import-clickgap` loads one SQLite export shape, a ClickGap `lessons` store, into a Loom namespace; skip this page unless you have such an export. - [Store an investigation agent's memory](docs/guides/investigation-agent-memory.md): An investigation agent produces several kinds of state, and Loom has a plane for each. - [Manage MCP sources from the CLI](docs/guides/mcp-source-cli.md): The Python SDK supplies source controls through `python -m loom.source_cli source`. +- [Connect selected documents through MCP](docs/guides/mcp-sources.md): An MCP source reads selected resources from an operator-approved remote server. - [Optimize a namespace from its audit](docs/guides/optimize-namespace.md): A writer that uses `memory.set` as an object store (JSON blobs under hash keys, leases as memories, documents as claims) leaves every table consistent and recall useless. - [Tune Loom's performance](docs/guides/performance-tuning.md): Every lever on this page is a setting or a request field. - [Query Loom from Postgres](docs/guides/query-from-postgres.md): This guide reads a tenant's memories, conversations and usage from the org's own Postgres, where they can be joined with the application's tables. diff --git a/scripts/ops/qualify_mcp_sources.py b/scripts/ops/qualify_mcp_sources.py index 7dc6226524..673b17b8de 100644 --- a/scripts/ops/qualify_mcp_sources.py +++ b/scripts/ops/qualify_mcp_sources.py @@ -29,6 +29,7 @@ "partial_listing", "cancellation", "live", + "cli_context", ) EXPECTED = {f"test_{name}[{kind}]" for name in CASE_NAMES for kind in ("resources", "tools")} @@ -98,6 +99,7 @@ def write(self) -> None: "cases": self.cases, "seams": [ "fixture_asgi_https_routing", + "cli_owned_loopback_http", "operator_catalog_input", "local_ngram_embedding", "text_requires_no_extractor", diff --git a/sdk/python/loom/cli.py b/sdk/python/loom/cli.py index b43cd4848e..6e74b91128 100644 --- a/sdk/python/loom/cli.py +++ b/sdk/python/loom/cli.py @@ -1,4 +1,4 @@ -"""`loom login | logout | whoami | call | token | connect`: use the dashboard's API +"""`loom login | logout | whoami | call | token`: use the dashboard's API from a terminal or an agent's shell. `python -m loom …` runs it with only the SDK installed; the server's `loom` command hands these commands to it. @@ -26,17 +26,14 @@ import os import sys from typing import Any -from urllib.parse import parse_qsl, urlsplit import httpx from loom import credentials -from loom.errors import BackendUnavailable, LoomError +from loom.errors import LoomError from loom.ops import OPS -COMMANDS = ("login", "logout", "whoami", "call", "token", "connect") - -_CONNECT_KINDS = {"google": "gdrive", "notion": "notion", "linear": "linear"} +COMMANDS = ("login", "logout", "whoami", "call", "token") def _field(pair: str) -> tuple[str, Any]: @@ -126,66 +123,6 @@ async def _token(args: argparse.Namespace) -> Any: await agent.close() -async def _connect(args: argparse.Namespace) -> str: - """Read the server's dashboard link; consent starts in the browser so its - callback receives the binding cookie set by the authenticated start route.""" - from loom.agent import Agent - - agent = Agent("", "", "loom-cli", base_url=_server(args), profile=args.profile) - try: - answer = await agent.client.connection.list() - kind = _CONNECT_KINDS[args.provider] - if not isinstance(answer, dict): - raise BackendUnavailable("invalid connected-account response") - entries = answer.get("connections") - if not isinstance(entries, list): - raise BackendUnavailable("invalid connected-account response") - matches = [ - entry for entry in entries if isinstance(entry, dict) and entry.get("kind") == kind - ] - if len(matches) != 1: - raise BackendUnavailable("invalid connected-account response") - return _connect_url(matches[0].get("connect_url"), kind) - finally: - await agent.close() - - -def _connect_url(value: Any, kind: str) -> str: - """Only print a provider dashboard link, never consent or credential material.""" - refused = BackendUnavailable("invalid connected-account dashboard link") - if not isinstance(value, str) or any(ord(c) <= 32 or ord(c) == 127 for c in value): - raise refused - try: - url = urlsplit(value) - if ( - url.scheme not in {"http", "https"} - or not url.hostname - or url.username is not None - or url.password is not None - or url.fragment - or "\\" in value - or not url.path.endswith("/settings/connected-accounts") - or parse_qsl(url.query, keep_blank_values=True) != [("kind", kind)] - ): - raise refused - _ = url.port - except ValueError: - raise refused from None - return value - - -def _connect_parser(sub: Any) -> None: - p = sub.add_parser( - "connect", - help="print the dashboard link to connect your own provider account", - description="Open the printed link, sign in to the dashboard as the intended account " - "owner, and choose Connect or Reconnect. Consent completes in that browser.", - ) - p.add_argument("provider", choices=tuple(_CONNECT_KINDS)) - p.add_argument("--profile", help="credentials profile (default: LOOM_PROFILE or 'default')") - p.add_argument("--server", help="server URL (default: the one `loom login` signed in to)") - - def _token_target(entries: list[Any], saves_to: str | None) -> tuple[Any, str | None]: """The namespaces and `saves_to` a `token create` sends. A `*` token records where it saves as the namespace named before `*`, so `--saves-to` moves that @@ -318,10 +255,6 @@ def _run(args: argparse.Namespace) -> int: print( json.dumps(run_sync(lambda: guarded_command(args, _token)), indent=2, default=str) ) - elif args.cmd == "connect": - url = run_sync(lambda: guarded_command(args, _connect)) - print(f"To connect {args.provider}, open:\n{url}") - print("Sign in as the intended account owner and choose Connect or Reconnect.") elif args.list: _list_ops() else: @@ -335,13 +268,6 @@ def _run(args: argparse.Namespace) -> int: if result is not None: print(json.dumps(result, indent=2, default=str)) except (LoomError, httpx.HTTPError, ValueError, OSError) as e: - if args.cmd == "connect": - print( - "loom connect: could not read your provider dashboard link. " - "Check your server and sign-in with `loom login`.", - file=sys.stderr, - ) - return 1 print(f"loom {args.cmd}: {e}", file=sys.stderr) for err in getattr(e, "detail", {}).get("errors") or []: where = ".".join(str(part) for part in err.get("loc", [])) @@ -400,7 +326,6 @@ def main(argv: list[str] | None = None, prog: str = "python -m loom") -> int: p.add_argument("--method", choices=("GET", "POST"), help="for a /path") p.add_argument("--list", action="store_true", help="list every op and its role") _token_parser(sub) - _connect_parser(sub) # Fields may follow options (`--namespace x query=…`), which argparse # leaves over; anything else left over is a mistake. args, extra = parser.parse_known_args(argv) diff --git a/server/cli/login.py b/server/cli/login.py index 588256d5af..4d16e44d99 100644 --- a/server/cli/login.py +++ b/server/cli/login.py @@ -1,4 +1,4 @@ -"""`loom login | logout | whoami | call | token | connect`: use a Loom server from the terminal +"""`loom login | logout | whoami | call | token`: use a Loom server from the terminal with the session `loom login` stores. They are the Python SDK's commands (`loom.cli`), so the CLI and `loom.login()` share one implementation and one credentials file; `main` hands their arguments straight to the SDK's parser. @@ -15,7 +15,6 @@ "whoami": "Show who the stored session signs you in as.", "call": "Call any operation or API route with the stored session (`loom call --help`).", "token": "Make, list and revoke your own tokens for CI and agents (`loom token --help`).", - "connect": "Print the dashboard link to connect your own Google, Notion or Linear account.", } diff --git a/tests/integration/test_mcp_source_qualification.py b/tests/integration/test_mcp_source_qualification.py index e2809cc60e..dc4e86c5ae 100644 --- a/tests/integration/test_mcp_source_qualification.py +++ b/tests/integration/test_mcp_source_qualification.py @@ -4,14 +4,19 @@ import asyncio import json +import os +import socket +import sys from dataclasses import replace from typing import Any from uuid import uuid4 import pytest +import uvicorn from loom.errors import LoomError from loom.session_protection import AutomaticCaptureSuppressed +from server.auth.jwt import mint_token from server.core.ch import get_client, set_query_tag from server.knowledge.app import mcp_profiles, mcp_source_authority from tests.integration.mcp_source_qualification_fixtures import ( @@ -540,3 +545,95 @@ async def test_live(world: World) -> None: params={"org": world.owner.org}, ) == {"count": 0} require_clean_selection(world) + + +async def test_cli_context(world: World, qualification_app: Any) -> None: + """A real private response protects subsequent installed-CLI subprocesses.""" + await world.add(mode="live") + tokens = [ + mint_token( + subject, + world.owner.org, + ["*"], + ["admin"], + ttl_seconds=1800, + is_service_account=False, + session_id=str(uuid4()), + ) + for subject in (world.owner.subject, world.other.subject) + ] + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + listener.bind(("127.0.0.1", 0)) + listener.listen(32) + listener.setblocking(False) + server = uvicorn.Server( + uvicorn.Config( + qualification_app, + host="127.0.0.1", + port=listener.getsockname()[1], + lifespan="off", # qualification_app owns the actual startup and shutdown. + access_log=False, + log_config=None, + log_level="critical", + ) + ) + serving = asyncio.create_task(server.serve(sockets=[listener]), name="mcp-cli-owned-http") + child: asyncio.subprocess.Process | None = None + try: + async with asyncio.timeout(10): + while not server.started: + if serving.done(): + await serving + pytest.fail("Owned CLI HTTP fixture did not start") + await asyncio.sleep(0.01) + env = { + **os.environ, + "LOOM_CLI_QUAL_BASE_URL": f"http://127.0.0.1:{listener.getsockname()[1]}", + "LOOM_CLI_QUAL_ORG": world.owner.org, + "LOOM_CLI_QUAL_TOKEN": tokens[0], + "LOOM_CLI_QUAL_OTHER_TOKEN": tokens[1], + "LOOM_CLI_QUAL_WRITE_NAMESPACE": world.team, + "LOOM_CLI_QUAL_PRIVATE_READ_REQUEST": json.dumps( + {"namespace": world.namespace, "name": world.entry["name"], "resource_id": SELECTED} + ), + "LOOM_CLI_QUAL_PRIVATE_MARKER": world.source.marker, + } + target = "sdk/python/tests/qualify_cli_source_context.py" + child = await asyncio.create_subprocess_exec( + sys.executable, + "-m", + "pytest", + str(target), + "-q", + "--tb=no", + "--show-capture=no", + env=env, + stdout=asyncio.subprocess.DEVNULL, + stderr=asyncio.subprocess.DEVNULL, + start_new_session=True, + ) + async with asyncio.timeout(180): + assert await child.wait() == 0 + assert world.source.reads == [SELECTED] + finally: + if child is not None and child.returncode is None: + # This process group contains only the explicitly owned CLI qualification. + import signal + + os.killpg(child.pid, signal.SIGTERM) + try: + async with asyncio.timeout(5): + await child.wait() + except TimeoutError: + os.killpg(child.pid, signal.SIGKILL) + await child.wait() + server.should_exit = True + try: + async with asyncio.timeout(5): + await asyncio.shield(serving) + except TimeoutError: + serving.cancel() + await asyncio.gather(serving, return_exceptions=True) + finally: + listener.close() + assert serving.done() diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index e084239e4f..7fa6c0e396 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -1,8 +1,8 @@ { "loom": [ - "usage: loom [-h] [--version] [--request-intent {automatic,explicit}] {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect} ...", + "usage: loom [-h] [--version] [--request-intent {automatic,explicit}] {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token} ...", "Loom — vendor-neutral agent memory plane on ClickHouse.", - "positional arguments: {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token,connect} code Code intelligence plane operations. decisions Decision records mined from documents. knowledge Knowledge documents and their sources. export-okf Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. import-okf Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. okf-lint Lint an OKF bundle directory offline — the compile gate a mirror repository's CI runs. Exit 2 critical, 1 warnings, 0 clean. up Boot the local stack (Loom, its document extractor and ClickHouse) and print how to connect: creates .env and the ClickHouse config from their templates, runs docker compose up --build, waits for /v1/health, then prints the dashboard URL and the first memory.set (curl + Python SDK) and `claude mcp add` snippets — minting a writer token first when auth is on. Re-run any time. down Stop the local stack while preserving data; --delete-data performs a confirmed reset. ch-setup Prepare a self-managed ClickHouse or a ClickHouse Cloud service for Loom: create the loom database and the read-only reader user, or print the SQL for an admin. participant The Loom processes a provider change waits for. deployment The configuration every replica checks itself against. settings Every setting's value in force, and overrides of the live ones. secrets Credentials and signing keys stored sealed in ClickHouse. signing-key The token signing keys beside LOOM_JWT_SECRET, kept in ClickHouse. provider-lock The provider configuration lock. export-analytics Write one UTC day of usage and a namespace snapshot to S3 as Parquet, names hashed under LOOM_ANALYTICS_EXPORT_NAME_KEY. Never replaces an object, so a repeated run is safe. sql-access Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views. reembed Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them. reextract Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is never written. deploy-delta What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side of the swap, with flags for what moved past a coarse threshold. entity-export Export a namespace's entity graph (co-occurrence edges + triples) to GraphML or JSON-LD for an external graph or RDF tool. Read-only; every edge carries its provenance and a note that a path is declared, not proven. audit-namespace How a namespace is being used (namespace.audit): exact-key reads vs searches, hash keys, double-encoded and oversized values, hand-rolled index rows, leases stored as memories, version churn. Read-only; prints a table (code, severity, kind, count, share, first sample) or --json. Exit 1 on a critical finding. mentor The store's advice to one agent (mentor.brief): what it called, the planes its namespace offers, the hints with their evidence, and how often past hints were followed. Read-only; prints a table or --json. Exit 1 when a warning-level hint fires. serve Boot the control plane (uvicorn). migrate Apply schema migrations against the configured CH. reconcile-status Re-emit memory_embeddings rows whose status diverged from loom.memory (superseded / conflicted / duplicate marks the pool never saw), compared and re-emitted per identity row (org, namespace, agent, user_id, session_id, key). Dry run by default (counts by status, the rows it would write); --apply writes. period-digest Write period digests — one derived semantic memory over K consecutive session digests of each identity in one namespace. Additive and idempotent. Dry run by default (plans only); --apply writes. demote-activity-narration Find a namespace's extracted facts that narrate tool activity ('User read lines 1-1000 of X', 'Claude ran a command on …') with no durable outcome and demote (confidence x0.25) or label them through memory.apply. Dry run by default; keys an agent read by name in the last --days are left alone. Never deletes. recalibrate Re-probe the embedder + run per-NS calibration immediately (otherwise this runs weekly via the recalibration worker). import-clickgap Import a ClickGap (Detector→Validator→Reviewer) SQLite export into Loom (lessons + typed entities + categories). Reembed-only; preserves kind→memory_type, per-row TTL, recall_count (→ ranking via reinforcement_count), suppression polarity, and provenance. Idempotent via deterministic keys + per-run version. import-recall Import an external vector-recall agent-memory SQLite export into Loom. Introspects the DB at runtime (schema not assumed): tables are classified by column heuristics into memories (→ memory.set) or conversation transcripts (→ conversation.append, grouped by conversation id); unmatched tables/rows are skipped, never crash. Idempotent via deterministic keys. import-brain Import a markdown agent 'brain' directory into Loom: MEMORY.md (always- injected HOT layer) → profile.set sections; memory/contexts/*.md (read-on- demand WARM layer) → knowledge.add docs. Completes the migration alongside import-recall (the deep vector layer). Missing files are skipped, never crash. claim-release Release a self-signup claim: revoke its grants, clear the owner, deactivate it. The name stays reserved. mint-token Mint a JWT locally (requires LOOM_JWT_SECRET and verified stores). revoke-token Revoke one token by jti or subject (writes loom.revoked_tokens through the revocation module; needs the configured ClickHouse). sso Carry password accounts over to single sign-on. bot Bots and CI jobs that sign in with a key or their CI's identity. doctor Diagnose pre-boot misconfig (Python version, settings, JWT, CH reachability) and print the problem list /v1/health carries, each with its fix. With --client, also examine this machine as a coding-agent client. report Print the bug form's Environment field: versions and the `loom doctor` checks. drops Print the memory ingest drop ledger (loom.memory_drops) for a namespace, by stage/reason — what the pipeline discarded, truncated or gave up on. namespaces-gc List (default) or erase throwaway namespaces — finished bench runs under the bench prefixes that nobody registered and nobody has written to for --idle-hours — in one list-scoped erasure saga per batch. erasure-re-verify Re-verify failed erasure sagas: print each one's last step-named reason and a fresh residue census (default, read-only); --resume re-runs them from their checkpoint past the recovery worker's attempts budget; --orphan-graph lists namespaces whose entity graph outlived their memories and, with --erase, purges them. reconcile After a restore of ClickHouse or Postgres, run again in the restored store the erasures and redactions the other records past the restore point, and (after a ClickHouse restore) publish again every revision committed after it. Stop every server and worker first. Dry run by default. router The router in front of a deployment's cells. cell Operate a deployment's cells through the router's directory. tracker-probe Read-only first contact with the tracker source: counts and newest timestamps per upstream table per credential, breaker states, the configured tracker namespaces. tracker-contract-check Read-only: does each tracker source's schema meet the record contract (docs/features/tracker/record-contract.md)? Names missing tables / columns, optional tables present, feature columns. Exit 0 when every checked source meets it. tracker-dupcheck-fit Refit tracker.duplicate_check's calibrated confidence for one tracker namespace now: replays the duplicate gold at filing time, fits, stores the fit. tracker-embed-reset Clear the tracker_embed pass cursors of one tracker namespace so the next pass re-walks the window and re-embeds every item whose text recipe changed. Dry run by default (prints the cursors); --apply clears them. tracker-feed Maintain a team's GitHub tracker record namespaces-adopt Give namespaces that hold live memory and no registry row an owner row: kind=bench under the bench prefixes, else memory; retention_days 0, no TTL. Dry run unless --apply. sensitivity-sweep Label live rows the sensitivity detector would have labelled on write but a path skipped. Dry run by default: counts by level, probe shape and namespace. --apply writes one new version per row, tombstones a high row's embedding rows and tags a medium row's. The closing line is the high- sensitivity invariant (high rows with a live embedding). integrity-repair Read the row-level integrity gauges (dim-0 rows holding a vector, tombstoned_at/status drift, active rows past valid_to) and, with --apply, re-emit the dim-0 rows with their true dimension so search can return them again. Drift and valid_to are listed, not repaired. rechunk Re-chunk and re-embed a namespace's knowledge documents from stored content through the current chunker, so every document carries section metadata, chunk context and document frequency. Idempotent; one embedding per new chunk. Dry run by default (counts the documents and chunks); --apply re-chunks. export-actions Export the action schema derived from the operation registry — an MCP tools/list manifest with loom extras (json) or the Cedar schema (cedar) a policy gateway governs the surface with. lexical-stats-rebuild Recompute BM25 document frequency for a namespace from its live rows (the term-frequency views only see inserts; supersession and tombstones leave stale vocabulary behind). version Print installed Loom version. install Wire Loom into a local AI client's config. Writes the MCP server block into Claude Desktop / Cursor / VS Code's config file, atomically, merging with anything already there; for Claude Code it runs (or prints) `claude mcp add` and for Codex `codex mcp add`. Restart the client afterwards. demo The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. On the stock fake-LLM stack it prints the top knowledge.search hits and says what a real answer needs. init Create an identity on a Loom server. `--agent NAME` signs an agent up by itself (server needs LOOM_SELF_SIGNUP=open): mints a writer token on a fresh agent- namespace, saves it to ~/.loom/token, and prints the claim code a person enters once, with a password of their own, to claim the namespace. ingest-transcript Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. Generic ingest for tools without an MCP integration (Aider, Continue.dev, JetBrains AI, anything else): export the chat → run this command → the thread shows in the dashboard's Conversations. memory-search Run a memory.search from the shell. Default human output; --json-agent emits a structured envelope agents can pipe through (a `{command, results}` JSON shape). set-host Designate the Loom host(s) for this deployment. Writes the given login handle(s) or email(s) to LOOM_PLATFORM_ADMINS in the .env (--env-file, default ./.env): a handle promotes that password account to platform_admin, an email promotes an SSO sign-in with that verified email. Multiple OK (on-call rotation, co-operators, etc.). Re-login required after to pick up the role. login Sign in to a Loom server on any browser with a one-time code. logout End the stored session on the server and forget it here. whoami Show who the stored session signs you in as. call Call any operation or API route with the stored session (`loom call --help`). token Make, list and revoke your own tokens for CI and agents (`loom token --help`). connect Print the dashboard link to connect your own Google, Notion or Linear account.", + "positional arguments: {code,decisions,knowledge,export-okf,import-okf,okf-lint,up,down,ch-setup,participant,deployment,settings,secrets,signing-key,provider-lock,export-analytics,sql-access,reembed,reextract,deploy-delta,entity-export,audit-namespace,mentor,serve,migrate,reconcile-status,period-digest,demote-activity-narration,recalibrate,import-clickgap,import-recall,import-brain,claim-release,mint-token,revoke-token,sso,bot,doctor,report,drops,namespaces-gc,erasure-re-verify,reconcile,router,cell,tracker-probe,tracker-contract-check,tracker-dupcheck-fit,tracker-embed-reset,tracker-feed,namespaces-adopt,sensitivity-sweep,integrity-repair,rechunk,export-actions,lexical-stats-rebuild,version,install,demo,init,ingest-transcript,memory-search,set-host,login,logout,whoami,call,token} code Code intelligence plane operations. decisions Decision records mined from documents. knowledge Knowledge documents and their sources. export-okf Render a namespace as an OKF v0.2 bundle (Markdown + frontmatter) — the git-reviewable projection of Loom memory. import-okf Write the concepts of an OKF v0.2 bundle into a namespace via memory.set. okf-lint Lint an OKF bundle directory offline — the compile gate a mirror repository's CI runs. Exit 2 critical, 1 warnings, 0 clean. up Boot the local stack (Loom, its document extractor and ClickHouse) and print how to connect: creates .env and the ClickHouse config from their templates, runs docker compose up --build, waits for /v1/health, then prints the dashboard URL and the first memory.set (curl + Python SDK) and `claude mcp add` snippets — minting a writer token first when auth is on. Re-run any time. down Stop the local stack while preserving data; --delete-data performs a confirmed reset. ch-setup Prepare a self-managed ClickHouse or a ClickHouse Cloud service for Loom: create the loom database and the read-only reader user, or print the SQL for an admin. participant The Loom processes a provider change waits for. deployment The configuration every replica checks itself against. settings Every setting's value in force, and overrides of the live ones. secrets Credentials and signing keys stored sealed in ClickHouse. signing-key The token signing keys beside LOOM_JWT_SECRET, kept in ClickHouse. provider-lock The provider configuration lock. export-analytics Write one UTC day of usage and a namespace snapshot to S3 as Parquet, names hashed under LOOM_ANALYTICS_EXPORT_NAME_KEY. Never replaces an object, so a repeated run is safe. sql-access Make, rescope or drop a ClickHouse user that reads a tenant's memory, conversations and request ledger through the sql_v1_* views. reembed Re-embed vectors whose embedding_model != the configured embedder (run after changing LOOM_EMBEDDING_MODEL — Loom does not auto-re-embed). Covers memory, entity, and conversation vectors. Coded vector tables keep their width: change a model of another width in Settings → Models & keys, which rebuilds them. reextract Replay a namespace's raw evidence (memory.set_from_messages turns) through a running server's write path into ANOTHER namespace — the current extractor over the stored transcripts; the source is never written. deploy-delta What a colour swap changed: the deployment's ledger rows (volume, errors, p50/p95, upstream spend per operation) and its ClickHouse statement shapes (runs, bytes, seconds) for a window on each side of the swap, with flags for what moved past a coarse threshold. entity-export Export a namespace's entity graph (co-occurrence edges + triples) to GraphML or JSON-LD for an external graph or RDF tool. Read-only; every edge carries its provenance and a note that a path is declared, not proven. audit-namespace How a namespace is being used (namespace.audit): exact-key reads vs searches, hash keys, double-encoded and oversized values, hand-rolled index rows, leases stored as memories, version churn. Read-only; prints a table (code, severity, kind, count, share, first sample) or --json. Exit 1 on a critical finding. mentor The store's advice to one agent (mentor.brief): what it called, the planes its namespace offers, the hints with their evidence, and how often past hints were followed. Read-only; prints a table or --json. Exit 1 when a warning-level hint fires. serve Boot the control plane (uvicorn). migrate Apply schema migrations against the configured CH. reconcile-status Re-emit memory_embeddings rows whose status diverged from loom.memory (superseded / conflicted / duplicate marks the pool never saw), compared and re-emitted per identity row (org, namespace, agent, user_id, session_id, key). Dry run by default (counts by status, the rows it would write); --apply writes. period-digest Write period digests — one derived semantic memory over K consecutive session digests of each identity in one namespace. Additive and idempotent. Dry run by default (plans only); --apply writes. demote-activity-narration Find a namespace's extracted facts that narrate tool activity ('User read lines 1-1000 of X', 'Claude ran a command on …') with no durable outcome and demote (confidence x0.25) or label them through memory.apply. Dry run by default; keys an agent read by name in the last --days are left alone. Never deletes. recalibrate Re-probe the embedder + run per-NS calibration immediately (otherwise this runs weekly via the recalibration worker). import-clickgap Import a ClickGap (Detector→Validator→Reviewer) SQLite export into Loom (lessons + typed entities + categories). Reembed-only; preserves kind→memory_type, per-row TTL, recall_count (→ ranking via reinforcement_count), suppression polarity, and provenance. Idempotent via deterministic keys + per-run version. import-recall Import an external vector-recall agent-memory SQLite export into Loom. Introspects the DB at runtime (schema not assumed): tables are classified by column heuristics into memories (→ memory.set) or conversation transcripts (→ conversation.append, grouped by conversation id); unmatched tables/rows are skipped, never crash. Idempotent via deterministic keys. import-brain Import a markdown agent 'brain' directory into Loom: MEMORY.md (always- injected HOT layer) → profile.set sections; memory/contexts/*.md (read-on- demand WARM layer) → knowledge.add docs. Completes the migration alongside import-recall (the deep vector layer). Missing files are skipped, never crash. claim-release Release a self-signup claim: revoke its grants, clear the owner, deactivate it. The name stays reserved. mint-token Mint a JWT locally (requires LOOM_JWT_SECRET and verified stores). revoke-token Revoke one token by jti or subject (writes loom.revoked_tokens through the revocation module; needs the configured ClickHouse). sso Carry password accounts over to single sign-on. bot Bots and CI jobs that sign in with a key or their CI's identity. doctor Diagnose pre-boot misconfig (Python version, settings, JWT, CH reachability) and print the problem list /v1/health carries, each with its fix. With --client, also examine this machine as a coding-agent client. report Print the bug form's Environment field: versions and the `loom doctor` checks. drops Print the memory ingest drop ledger (loom.memory_drops) for a namespace, by stage/reason — what the pipeline discarded, truncated or gave up on. namespaces-gc List (default) or erase throwaway namespaces — finished bench runs under the bench prefixes that nobody registered and nobody has written to for --idle-hours — in one list-scoped erasure saga per batch. erasure-re-verify Re-verify failed erasure sagas: print each one's last step-named reason and a fresh residue census (default, read-only); --resume re-runs them from their checkpoint past the recovery worker's attempts budget; --orphan-graph lists namespaces whose entity graph outlived their memories and, with --erase, purges them. reconcile After a restore of ClickHouse or Postgres, run again in the restored store the erasures and redactions the other records past the restore point, and (after a ClickHouse restore) publish again every revision committed after it. Stop every server and worker first. Dry run by default. router The router in front of a deployment's cells. cell Operate a deployment's cells through the router's directory. tracker-probe Read-only first contact with the tracker source: counts and newest timestamps per upstream table per credential, breaker states, the configured tracker namespaces. tracker-contract-check Read-only: does each tracker source's schema meet the record contract (docs/features/tracker/record-contract.md)? Names missing tables / columns, optional tables present, feature columns. Exit 0 when every checked source meets it. tracker-dupcheck-fit Refit tracker.duplicate_check's calibrated confidence for one tracker namespace now: replays the duplicate gold at filing time, fits, stores the fit. tracker-embed-reset Clear the tracker_embed pass cursors of one tracker namespace so the next pass re-walks the window and re-embeds every item whose text recipe changed. Dry run by default (prints the cursors); --apply clears them. tracker-feed Maintain a team's GitHub tracker record namespaces-adopt Give namespaces that hold live memory and no registry row an owner row: kind=bench under the bench prefixes, else memory; retention_days 0, no TTL. Dry run unless --apply. sensitivity-sweep Label live rows the sensitivity detector would have labelled on write but a path skipped. Dry run by default: counts by level, probe shape and namespace. --apply writes one new version per row, tombstones a high row's embedding rows and tags a medium row's. The closing line is the high- sensitivity invariant (high rows with a live embedding). integrity-repair Read the row-level integrity gauges (dim-0 rows holding a vector, tombstoned_at/status drift, active rows past valid_to) and, with --apply, re-emit the dim-0 rows with their true dimension so search can return them again. Drift and valid_to are listed, not repaired. rechunk Re-chunk and re-embed a namespace's knowledge documents from stored content through the current chunker, so every document carries section metadata, chunk context and document frequency. Idempotent; one embedding per new chunk. Dry run by default (counts the documents and chunks); --apply re-chunks. export-actions Export the action schema derived from the operation registry — an MCP tools/list manifest with loom extras (json) or the Cedar schema (cedar) a policy gateway governs the surface with. lexical-stats-rebuild Recompute BM25 document frequency for a namespace from its live rows (the term-frequency views only see inserts; supersession and tombstones leave stale vocabulary behind). version Print installed Loom version. install Wire Loom into a local AI client's config. Writes the MCP server block into Claude Desktop / Cursor / VS Code's config file, atomically, merging with anything already there; for Claude Code it runs (or prints) `claude mcp add` and for Codex `codex mcp add`. Restart the client afterwards. demo The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. On the stock fake-LLM stack it prints the top knowledge.search hits and says what a real answer needs. init Create an identity on a Loom server. `--agent NAME` signs an agent up by itself (server needs LOOM_SELF_SIGNUP=open): mints a writer token on a fresh agent- namespace, saves it to ~/.loom/token, and prints the claim code a person enters once, with a password of their own, to claim the namespace. ingest-transcript Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. Generic ingest for tools without an MCP integration (Aider, Continue.dev, JetBrains AI, anything else): export the chat → run this command → the thread shows in the dashboard's Conversations. memory-search Run a memory.search from the shell. Default human output; --json-agent emits a structured envelope agents can pipe through (a `{command, results}` JSON shape). set-host Designate the Loom host(s) for this deployment. Writes the given login handle(s) or email(s) to LOOM_PLATFORM_ADMINS in the .env (--env-file, default ./.env): a handle promotes that password account to platform_admin, an email promotes an SSO sign-in with that verified email. Multiple OK (on-call rotation, co-operators, etc.). Re-login required after to pick up the role. login Sign in to a Loom server on any browser with a one-time code. logout End the stored session on the server and forget it here. whoami Show who the stored session signs you in as. call Call any operation or API route with the stored session (`loom call --help`). token Make, list and revoke your own tokens for CI and agents (`loom token --help`).", "options: -h, --help show this help message and exit --version show program's version number and exit --request-intent {automatic,explicit} Explicit is one direct human request; automatic is the default." ], "loom code": [ @@ -701,8 +701,5 @@ ], "loom token": [ "usage: loom token" - ], - "loom connect": [ - "usage: loom connect" ] } diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 04b73a84de..15660c6631 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -20749,30 +20749,6 @@ ], "mutually_exclusive": [], "arguments": [] - }, - "connect": { - "prog": "loom connect", - "usage": null, - "description": null, - "epilog": null, - "formatter_class": "argparse:HelpFormatter", - "add_help": false, - "allow_abbrev": true, - "defaults": {}, - "groups": [ - { - "title": "positional arguments", - "description": null, - "dests": [] - }, - { - "title": "options", - "description": null, - "dests": [] - } - ], - "mutually_exclusive": [], - "arguments": [] } }, "aliases_of": { @@ -20843,8 +20819,7 @@ "logout": "loom logout", "whoami": "loom whoami", "call": "loom call", - "token": "loom token", - "connect": "loom connect" + "token": "loom token" }, "choices_help": [ { @@ -21186,11 +21161,6 @@ "dest": "token", "help": "Make, list and revoke your own tokens for CI and agents (`loom token --help`).", "metavar": "token" - }, - { - "dest": "connect", - "help": "Print the dashboard link to connect your own Google, Notion or Linear account.", - "metavar": "connect" } ] } From 7b28527023c05eb9ef0f0e02d035f176c2a773d6 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 06:55:56 +0000 Subject: [PATCH 27/30] Protect Java source requests with retained session authority Keep durable monotonic proof across clients and tasks, observe bounded raw responses before typed results, and exercise owned HTTP cancellation and publication boundaries in hosted tests. Native qualification remains pending. Signed-off-by: zlareb1 --- sdk/java/README.md | 5 +- sdk/java/SESSION_PROTECTION.md | 50 ++ .../java/com/clickhouse/loom/LoomClient.java | 88 +++- .../com/clickhouse/loom/ProtectedBody.java | 122 +++++ .../clickhouse/loom/SessionProtection.java | 344 ++++++++++++++ .../loom/SessionProtectionHttpTest.java | 428 ++++++++++++++++++ 6 files changed, 1034 insertions(+), 3 deletions(-) create mode 100644 sdk/java/SESSION_PROTECTION.md create mode 100644 sdk/java/src/main/java/com/clickhouse/loom/ProtectedBody.java create mode 100644 sdk/java/src/main/java/com/clickhouse/loom/SessionProtection.java create mode 100644 sdk/java/src/test/java/com/clickhouse/loom/SessionProtectionHttpTest.java diff --git a/sdk/java/README.md b/sdk/java/README.md index 50ff1ab78a..359438abb3 100644 --- a/sdk/java/README.md +++ b/sdk/java/README.md @@ -4,7 +4,10 @@ A minimal client for Loom's memory ops (`memory.set`, `memory.get`, `memory.sear `memory.delete`) and the conversation ops a chat memory needs (`conversation.append`, `get`, `create`, `delete`, `threads` and `set_logging`). It is a step towards a full Java SDK ([#53](https://github.com/ClickHouse/loom/issues/53)); the Python and TypeScript SDKs -cover every op. +cover every op. Java also exposes generic wire calls and map-based MCP source +controls. See [protected source sessions](SESSION_PROTECTION.md) for the required +application-owned conversation authority, explicit human calls, retained callback +captures, Linux storage limits and hosted qualification status. Two chat memory modules build on it, each its own Maven project so the client keeps no framework dependency: diff --git a/sdk/java/SESSION_PROTECTION.md b/sdk/java/SESSION_PROTECTION.md new file mode 100644 index 0000000000..36afb97bf5 --- /dev/null +++ b/sdk/java/SESSION_PROTECTION.md @@ -0,0 +1,50 @@ +# Protected source sessions + +`LoomClient` supports generic outbound MCP source controls through its normal HTTP boundary. `sourceMcpRead`, `sourceMcpList`, `sourceMcpPause` and `sourceMcpRefresh` accept the operation reference's input maps and default only `org` and `namespace`. `connectionMcpBrowse` defaults only `org`. Other controls use `call(operation, completeWireInput)`, which adds no identity fields. Results are Jackson `JsonNode` values. These methods do not infer upstream MCP methods or claim compatibility with every MCP server. + +Bind one `SessionProtection` to the application's logical conversation. Store its `Pointer` independently from mutable client settings, credentials and namespace selection. Reopen that exact pointer on resume; failure must stop the conversation's automatic dispatch. `create` is only for a new conversation and refuses an existing directory. Never recover a missing pointer by creating another family. + +```java +SessionProtection family = SessionProtection.create(privateParent.resolve("conversation")); +// Save every Pointer field in the application's trusted conversation record. +SessionProtection.Pointer pointer = family.pointer(); +LoomClient loom = LoomClient.builder().baseUrl(serverUrl).token(token) + .org(org).namespace(namespace).agent(agent).sessionProtection(family).build(); +JsonNode result = loom.sourceMcpRead(Map.of("name", sourceName, "resource_id", resourceId)); +// A later process uses SessionProtection.open(pointer), never create(...). +``` + +A protected response latches the family before returning bytes or typed results. Observation includes successful envelopes, `error.data` at any HTTP status, nested results, items, structured content and JSON text blocks. Invalid JSON, invalid protection metadata, interrupted responses, unsupported media or lost proof fail closed and retain protection. Only the installed durable guard and observer add exactly one `x-loom-session-protection: v1`. Ordinary unbound calls keep their existing behavior and send no declaration. There is no caller header override API. + +Calls on a bound client are automatic by default. No Java read-only operation catalog is generated yet, so every operation, including reads and unknown operations, is conservatively subject to the mutation guard. Once protected, `callHuman(operation, completeWireInput)` authorizes one explicit invocation. It still observes the response and does not clear the latch. This method must be chosen by the application for actual human intent, never exposed as a globally enabled automatic facade. + +```java +loom.callHuman("memory.set", Map.of("org", org, "namespace", destination, + "agent", agent, "memory_key", "chosen-key", "value", humanChosenValue)); +``` + +Retain contributors before queuing work or invoking another client. `Capture.call` installs a thread-local scope for its duration and restores the previous scope on exceptions. Nested scopes union their contributors. Thread pools and newly spawned threads receive no implicit inherited context; pass the capture explicitly. Every automatic call unions its retained contributors with the current client's bound family. A clean retained family cannot bypass a protected bound family. + +```java +SessionProtection.Capture capture = family.capture(); +// Persist the contributing family pointers with durable queued work; rebuild this capture on resume. +executor.submit(() -> anotherClient.callAutomatic(capture, "memory.set", completeWireInput)); +// Synchronous callbacks can use capture.call(() -> anotherClient.set(key, value)). +``` + +Changing client, namespace, token or origin creates no protection authority. Rebuilt clients must bind the same family; callbacks that use an unbound client must retain the capture. A callback queued during an explicit human call receives no lasting human authority. Java has no client clone API, SDK retries or pacing policy. Applications that retry must use the same bound client or retained capture on every attempt. Protected clients reject redirect-following HTTP clients and authenticators that could resend a request outside the admission boundary. Custom HTTP clients and their configuration are trusted application code. + +## Durable storage limits + +The built-in store supports Linux local POSIX filesystems with stable file identities, advisory file locking, private file permissions, file fsync and directory fsync. Windows, network filesystems and stores without these properties are unsupported; this SDK supplies no alternative storage adapter. Unsupported storage refuses readiness. Native behavior remains unqualified until the hosted tests pass. + +The application owns a private, trusted parent directory and all its ancestors. Each conversation directory is created with mode 0700 and its authority file with mode 0600. The independently stored pointer binds directory and authority file identities and a random family identity. Missing, corrupt or replaced authority refuses even explicit dispatch. A checksummed one-way protected bit and durable pending tokens in that same authority file survive process interruption. Pending proof prevents concurrent automatic requests and latches protection on resume. An explicit human invocation may proceed with pending proof, but cannot remove an abandoned marker or restore automatic authority. + +Trusted storage and the host must prevent rollback of both the authority and its pointer. This store cannot detect a coordinated filesystem snapshot rollback, a privileged host rewriting both records, or an application intentionally discarding its conversation identity. It is not an isolation boundary against hostile application code. It stores no credentials, response bodies or private document content. No cleanup API resets a family; retention and deletion belong to the application owner. + +Protected requests and responses are limited to 4 MiB, envelope work to 10,000 nodes, JSON text parsing to 4 MiB, contributors to 32 pending tokens to 1,024 and the authority file to 64 KiB. The conversation directory +accepts only its authority file; any extra entry refuses readiness. Protected responses use a bounded subscriber and an overall request deadline. Cancellation joins the owned subscriber callback boundary and cancels the HTTP future and body subscription before returning; incomplete responses retain pending proof. The owned-loopback cancellation test must confirm peer connection closure on the hosted JDK. Streaming and download publication are unsupported: media other than JSON is refused before bytes escape. The SDK creates no background retry or cleanup workers. + +## Qualification + +`SessionProtectionHttpTest` contains actual owned-loopback HTTP tests for success, HTTP errors, clean and ordinary traffic, retained contributors, cross-client/namespace/token/origin refusal, explicit human writes, lost and replaced proof, pending concurrency, malformed metadata, bounded bodies, stream refusal and cancellation. These tests need no service, database or provider. They are authored and UNRUN locally. Native compilation, formatting and tests belong to the hosted environment. No real Loom service, upstream MCP server, authorization or storage qualification follows from authoring these cases. diff --git a/sdk/java/src/main/java/com/clickhouse/loom/LoomClient.java b/sdk/java/src/main/java/com/clickhouse/loom/LoomClient.java index ca1111a91c..53f30fd84f 100644 --- a/sdk/java/src/main/java/com/clickhouse/loom/LoomClient.java +++ b/sdk/java/src/main/java/com/clickhouse/loom/LoomClient.java @@ -50,6 +50,7 @@ public final class LoomClient { private final String agent; private final Duration timeout; private final HttpClient http; + private final SessionProtection sessionProtection; private LoomClient(Builder b) { String base = b.baseUrl != null ? b.baseUrl : env("LOOM_BASE_URL"); @@ -63,6 +64,7 @@ private LoomClient(Builder b) { this.namespace = required(b.namespace, "namespace"); this.agent = required(b.agent, "agent"); this.timeout = b.timeout; + this.sessionProtection = b.sessionProtection; this.http = b.httpClient != null ? b.httpClient @@ -237,7 +239,74 @@ private ObjectNode body(Map extra) { return body; } + /** Generic wire operation. Inputs use the operation reference's exact field names. */ + public JsonNode call(String op, Map input) { + ObjectNode wire = JSON.valueToTree(input); + return call(op, wire); + } + + /** One explicit human invocation; callbacks retain no permission from this call. */ + public JsonNode callHuman(String op, Map input) { + return dispatch(op, JSON.valueToTree(input), true); + } + + /** Retains source contributors across a queued callback or another client. */ + public JsonNode callAutomatic(SessionProtection.Capture capture, String op, Map input) { + try { return capture.call(() -> call(op, input)); } + catch (RuntimeException e) { throw e; } + catch (Exception e) { throw new SessionProtection.Unavailable(e); } + } + + public JsonNode sourceMcpRead(Map input) { + return call("knowledge.source.mcp_read", sourceBody(input)); + } + + public JsonNode connectionMcpBrowse(Map input) { + ObjectNode wire = JSON.createObjectNode().put("org", org); + input.forEach((key, value) -> wire.set(key, JSON.valueToTree(value))); + return call("knowledge.connection.mcp_browse", wire); + } + + public JsonNode sourceMcpList(Map input) { + return call("knowledge.source.mcp_list", sourceBody(input)); + } + + public JsonNode sourceMcpPause(Map input) { + return call("knowledge.source.mcp_pause", sourceBody(input)); + } + + public JsonNode sourceMcpRefresh(Map input) { + return call("knowledge.source.mcp_refresh", sourceBody(input)); + } + + private ObjectNode sourceBody(Map input) { + ObjectNode wire = JSON.createObjectNode().put("org", org).put("namespace", namespace); + input.forEach((key, value) -> wire.set(key, JSON.valueToTree(value))); + return wire; + } + private JsonNode call(String op, ObjectNode body) { + return dispatch(op, body, false); + } + + private JsonNode dispatch(String op, ObjectNode body, boolean human) { + if (!op.matches("[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+")) { + throw new IllegalArgumentException("op must be a dotted operation name"); + } + try (SessionProtection.Observation observation = SessionProtection.begin(sessionProtection, human)) { + if (observation.bound() && (http.followRedirects() != HttpClient.Redirect.NEVER + || http.authenticator().isPresent() + || !("http".equals(baseUrl.getScheme()) || "https".equals(baseUrl.getScheme())) + || baseUrl.getHost() == null || baseUrl.getRawUserInfo() != null + || baseUrl.getRawQuery() != null || baseUrl.getRawFragment() != null)) { + throw new SessionProtection.Unavailable(); + } + return send(op, body, observation, human); + } + } + + private JsonNode send( + String op, ObjectNode body, SessionProtection.Observation observation, boolean human) { String requestId = UUID.randomUUID().toString(); HttpRequest.Builder req = HttpRequest.newBuilder(URI.create(baseUrl + "/v1/" + op)) @@ -252,10 +321,17 @@ private JsonNode call(String op, ObjectNode body) { if (token != null) { req.header("Authorization", "Bearer " + token); } + if (observation.bound()) { req.header("x-loom-session-protection", "v1"); } HttpResponse res; try { - req.POST(HttpRequest.BodyPublishers.ofString(JSON.writeValueAsString(body))); - res = http.send(req.build(), HttpResponse.BodyHandlers.ofString()); + String encoded = observation.bound() ? ProtectedBody.encode(JSON, body) : JSON.writeValueAsString(body); + req.POST(HttpRequest.BodyPublishers.ofString(encoded)); + observation.beforeSend(human); + if (observation.bound()) { + res = ProtectedBody.send(http, req.build(), timeout); + } else { + res = http.send(req.build(), HttpResponse.BodyHandlers.ofString()); + } } catch (HttpTimeoutException e) { throw noAnswer(op, "TIMEOUT", "timed out after " + timeout, requestId, e); } catch (IOException e) { @@ -265,6 +341,7 @@ private JsonNode call(String op, ObjectNode body) { throw noAnswer(op, "INTERRUPTED", "interrupted", requestId, e); } String echoed = res.headers().firstValue("X-Request-Id").orElse(requestId); + if (observation.bound()) { observation.observe(res.body()); } JsonNode parsed = parse(res.body()); if (res.statusCode() / 100 != 2) { Double retryAfter = @@ -328,6 +405,7 @@ public static final class Builder { private String agent; private Duration timeout = Duration.ofSeconds(30); private HttpClient httpClient; + private SessionProtection sessionProtection; private Builder() {} @@ -370,6 +448,12 @@ public Builder httpClient(HttpClient httpClient) { return this; } + /** Bind the same application-owned authority on every client for a conversation. */ + public Builder sessionProtection(SessionProtection family) { + this.sessionProtection = Objects.requireNonNull(family, "family"); + return this; + } + public LoomClient build() { return new LoomClient(this); } diff --git a/sdk/java/src/main/java/com/clickhouse/loom/ProtectedBody.java b/sdk/java/src/main/java/com/clickhouse/loom/ProtectedBody.java new file mode 100644 index 0000000000..47f2e83c14 --- /dev/null +++ b/sdk/java/src/main/java/com/clickhouse/loom/ProtectedBody.java @@ -0,0 +1,122 @@ +package com.clickhouse.loom; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.HttpTimeoutException; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.List; +import java.util.Locale; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Flow; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** Bounded owned subscription: no response bytes escape before envelope observation. */ +final class ProtectedBody implements HttpResponse.BodySubscriber { + static final int MAX_BYTES = 4 * 1024 * 1024; + private final CompletableFuture body = new CompletableFuture<>(); + private final ByteArrayOutputStream bytes = new ByteArrayOutputStream(); + private Flow.Subscription subscription; + private boolean stopped; + + static String encode(com.fasterxml.jackson.databind.ObjectMapper json, + com.fasterxml.jackson.databind.node.ObjectNode input) { + BoundedOutput output = new BoundedOutput(); + try { json.writeValue(output, input); } + catch (IOException e) { throw new SessionProtection.Unavailable(e); } + return output.toString(StandardCharsets.UTF_8); + } + + private static final class BoundedOutput extends ByteArrayOutputStream { + @Override public synchronized void write(byte[] value, int offset, int length) { + if (length > MAX_BYTES - count) { throw new SessionProtection.Unavailable(); } + super.write(value, offset, length); + } + @Override public synchronized void write(int value) { + if (count == MAX_BYTES) { throw new SessionProtection.Unavailable(); } + super.write(value); + } + } + + static HttpResponse send(HttpClient http, HttpRequest request, Duration timeout) + throws IOException, InterruptedException { + ProtectedBody subscriber = new ProtectedBody(); + CompletableFuture> response = http.sendAsync(request, info -> { + String type = info.headers().firstValue("Content-Type").orElse("") + .split(";", 2)[0].trim().toLowerCase(Locale.ROOT); + if (!type.equals("application/json") && !type.endsWith("+json")) { + subscriber.cancel(new SessionProtection.Unavailable()); + } + if (info.headers().firstValueAsLong("Content-Length").orElse(0) > MAX_BYTES) { + subscriber.cancel(new SessionProtection.Unavailable()); + } + return subscriber; + }); + try { + return response.get(timeout.toNanos(), TimeUnit.NANOSECONDS); + } catch (TimeoutException e) { + throw new HttpTimeoutException("protected response deadline exceeded"); + } catch (ExecutionException e) { + if (e.getCause() instanceof RuntimeException runtime) { throw runtime; } + throw new IOException("protected response failed", e.getCause()); + } finally { + // Cancellation synchronizes with onNext and cancels the owned network subscription. + subscriber.cancel(new IOException("response closed")); + response.cancel(true); + } + } + + @Override public CompletionStage getBody() { return body; } + + @Override public synchronized void onSubscribe(Flow.Subscription value) { + if (subscription != null || stopped) { value.cancel(); return; } + subscription = value; + value.request(1); + } + + @Override public synchronized void onNext(List chunks) { + if (stopped) { return; } + for (ByteBuffer chunk : chunks) { + if (chunk.remaining() > MAX_BYTES - bytes.size()) { + cancel(new SessionProtection.Unavailable()); + return; + } + byte[] copy = new byte[chunk.remaining()]; + chunk.get(copy); + bytes.writeBytes(copy); + } + subscription.request(1); + } + + @Override public synchronized void onError(Throwable error) { cancel(error); } + + @Override public synchronized void onComplete() { + if (!stopped) { + try { + String decoded = StandardCharsets.UTF_8.newDecoder() + .onMalformedInput(java.nio.charset.CodingErrorAction.REPORT) + .onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes.toByteArray())).toString(); + stopped = true; + body.complete(decoded); + } catch (java.nio.charset.CharacterCodingException e) { + cancel(e); + } + } + } + + synchronized void cancel(Throwable error) { + if (!stopped) { + stopped = true; + if (subscription != null) { subscription.cancel(); } + body.completeExceptionally(error); + } + } +} diff --git a/sdk/java/src/main/java/com/clickhouse/loom/SessionProtection.java b/sdk/java/src/main/java/com/clickhouse/loom/SessionProtection.java new file mode 100644 index 0000000000..09c53fe4e8 --- /dev/null +++ b/sdk/java/src/main/java/com/clickhouse/loom/SessionProtection.java @@ -0,0 +1,344 @@ +package com.clickhouse.loom; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.IOException; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.nio.channels.FileLock; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.LinkOption; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; +import java.nio.file.attribute.BasicFileAttributes; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; + +/** Application-owned monotonic conversation authority. See SESSION_PROTECTION.md. */ +public final class SessionProtection { + private static final Object LOCK = new Object(); + private static final ThreadLocal ACTIVE = new ThreadLocal<>(); + private static final ObjectMapper JSON = new ObjectMapper( + com.fasterxml.jackson.core.JsonFactory.builder().enable( + com.fasterxml.jackson.core.StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) + .enable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + private static final int MAX_PENDING = 1024; + private final Pointer pointer; + + /** Persist independently from mutable client configuration in trusted application storage. */ + public record Pointer(Path directory, String identity, String directoryKey, String stateKey) { + public Pointer { + java.util.Objects.requireNonNull(directory, "directory"); + java.util.Objects.requireNonNull(identity, "identity"); + java.util.Objects.requireNonNull(directoryKey, "directoryKey"); + java.util.Objects.requireNonNull(stateKey, "stateKey"); + if (!identity.matches("[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}")) { + throw new Unavailable(); + } + } + } + + /** Lost or unverifiable proof is terminal until the application repairs its authority. */ + public static final class Unavailable extends IllegalStateException { + private static final long serialVersionUID = 1L; + Unavailable(Throwable cause) { super("session protection proof unavailable", cause); } + Unavailable() { this(null); } + } + + /** Automatic publication requires a separate human invocation after protection. */ + public static final class Protected extends IllegalStateException { + private static final long serialVersionUID = 1L; + Protected() { super("automatic operation refused by session protection"); } + } + + private SessionProtection(Pointer pointer) { + if (!"Linux".equals(System.getProperty("os.name"))) { throw new Unavailable(); } + this.pointer = pointer; + } + + /** Creates a new conversation only; never use as a resume fallback. Parent must exist. */ + public static SessionProtection create(Path directory) { + synchronized (LOCK) { + try { + if (!"Linux".equals(System.getProperty("os.name"))) { throw new Unavailable(); } + Path root = directory.toAbsolutePath().normalize(); + Files.createDirectory(root, PosixFilePermissions.asFileAttribute( + PosixFilePermissions.fromString("rwx------"))); + String id = UUID.randomUUID().toString(); + Path state = root.resolve("state"); + Files.createFile(state, PosixFilePermissions.asFileAttribute( + PosixFilePermissions.fromString("rw-------"))); + try (FileChannel channel = FileChannel.open(state, StandardOpenOption.WRITE)) { + write(channel, id + "\n0\n"); + } + sync(root); + sync(root.getParent()); + return open(new Pointer(root, id, key(root), key(state))); + } catch (IOException | UnsupportedOperationException e) { + throw new Unavailable(e); + } + } + } + + public static SessionProtection open(Pointer pointer) { + SessionProtection family = new SessionProtection(java.util.Objects.requireNonNull(pointer)); + family.access(false, false, null, null, null, true); + return family; + } + + public Pointer pointer() { return pointer; } + @Override public boolean equals(Object other) { + return other instanceof SessionProtection family && pointer.equals(family.pointer); + } + @Override public int hashCode() { return pointer.hashCode(); } + + public Capture capture() { + Capture current = ACTIVE.get(); + return current == null ? new Capture(List.of(this)) : current.contribute(this); + } + + /** Immutable contributor ownership; pass this object explicitly into queued tasks. */ + public static final class Capture { + private final List families; + private Capture(List families) { + if (families.isEmpty() || families.size() > 32) { throw new Unavailable(); } + this.families = List.copyOf(families); + } + public Capture contribute(SessionProtection family) { + Set all = new LinkedHashSet<>(families); + all.add(java.util.Objects.requireNonNull(family)); + return new Capture(new ArrayList<>(all)); + } + public T call(Callable work) throws Exception { + Capture previous = ACTIVE.get(); + Set union = new LinkedHashSet<>(families); + if (previous != null) { union.addAll(previous.families); } + ACTIVE.set(new Capture(new ArrayList<>(union))); + try { return work.call(); } + finally { if (previous == null) { ACTIVE.remove(); } else { ACTIVE.set(previous); } } + } + } + + static Observation begin(SessionProtection bound, boolean human) { + Set families = new LinkedHashSet<>(); + Capture capture = ACTIVE.get(); + if (capture != null) { families.addAll(capture.families); } + if (bound != null) { families.add(bound); } + Observation observation = new Observation(new ArrayList<>(families)); + try { + synchronized (LOCK) { + for (SessionProtection family : families) { family.access(!human, false, null); } + for (SessionProtection family : families) { + String marker = UUID.randomUUID() + ".pending"; + family.access(!human, false, marker); + observation.markers.add(marker); + } + } + return observation; + } catch (RuntimeException e) { + observation.close(); + throw e; + } + } + + static final class Observation implements AutoCloseable { + private final List families; + private final List markers = new ArrayList<>(); + private boolean complete; + Observation(List families) { + if (families.size() > 32) { throw new Unavailable(); } + this.families = families; + } + boolean bound() { return !families.isEmpty(); } + void beforeSend(boolean human) { + synchronized (LOCK) { + for (int i = 0; i < markers.size(); i++) { + families.get(i).access(!human, false, null, markers.get(i)); + } + } + } + void observe(String raw) { + JsonNode value; + try { value = JSON.readTree(raw); } + catch (IOException e) { throw new Unavailable(e); } + boolean marked; + try { marked = marked(value); } + catch (IOException | RuntimeException e) { throw new Unavailable(e); } + for (SessionProtection family : families) { family.access(false, marked, null); } + // Remove pending proof only after every contributor acknowledges observation. + for (int i = 0; i < markers.size(); i++) { families.get(i).finish(markers.get(i)); } + complete = true; + } + @Override public void close() { + if (!complete) { + for (int i = 0; i < markers.size(); i++) { + try { families.get(i).access(false, true, null); } + catch (RuntimeException ignored) { /* Durable pending proof remains on failure. */ } + } + } + } + } + + private static boolean marked(JsonNode root) throws IOException { + if (root == null || !root.isObject()) { throw new Unavailable(); } + ArrayDeque todo = new ArrayDeque<>(); + todo.add(root); + int remaining = 10000; + int textBudget = 4 * 1024 * 1024; + boolean protectedValue = false; + while (!todo.isEmpty()) { + if (--remaining < 0) { throw new Unavailable(); } + JsonNode node = todo.removeLast(); + if (!node.isObject()) { continue; } + JsonNode mirrored = node.get("mirrored"); + if (mirrored != null) { + if (!mirrored.isBoolean()) { throw new Unavailable(); } + protectedValue |= mirrored.booleanValue(); + } + for (String field : List.of("result", "structuredContent", "data", "error")) { + JsonNode child = node.get(field); + if (child != null && child.isObject()) { todo.add(child); } + } + for (String field : List.of("items", "content")) { + JsonNode children = node.get(field); + if (children == null || !children.isArray()) { continue; } + if (children.size() > remaining - todo.size()) { throw new Unavailable(); } + for (JsonNode child : children) { + todo.add(child); + if ("content".equals(field) && "text".equals(child.path("type").asText()) + && child.path("text").isTextual()) { + String text = child.get("text").textValue(); + textBudget -= text.getBytes(java.nio.charset.StandardCharsets.UTF_8).length; + if (textBudget < 0) { throw new Unavailable(); } + if (text.stripLeading().startsWith("{")) { todo.add(JSON.readTree(text)); } + } + } + } + } + return protectedValue; + } + + private void access(boolean automatic, boolean protect, String marker) { + access(automatic, protect, marker, null); + } + + private void access(boolean automatic, boolean protect, String marker, String ownMarker) { + access(automatic, protect, marker, ownMarker, null, false); + } + + private void access(boolean automatic, boolean protect, String marker, String ownMarker, + String removeMarker, boolean resume) { + synchronized (LOCK) { + try { + validate(); + try (FileChannel channel = FileChannel.open(pointer.directory().resolve("state"), + StandardOpenOption.READ, StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS); + FileLock fileLock = channel.tryLock()) { + if (fileLock == null || !fileLock.isValid()) { throw new Unavailable(); } + validate(); + ByteBuffer bytes = ByteBuffer.allocate(65537); + while (channel.read(bytes) > 0) { + if (!bytes.hasRemaining()) { throw new Unavailable(); } + } + bytes.flip(); + String stored = java.nio.charset.StandardCharsets.US_ASCII.decode(bytes).toString(); + if (stored.length() < 65 || !stored.endsWith("\n")) { throw new Unavailable(); } + String state = stored.substring(0, stored.length() - 65); + if (!stored.substring(stored.length() - 65, stored.length() - 1).equals(digest(state))) { + throw new Unavailable(); + } + String prefix = pointer.identity() + "\n"; + if (!state.startsWith(prefix)) { throw new Unavailable(); } + String rest = state.substring(prefix.length()); + if (!rest.startsWith("0\n") && !rest.startsWith("1\n")) { throw new Unavailable(); } + boolean latched = rest.charAt(0) == '1'; + String tokens = rest.substring(2); + Set pending = new java.util.TreeSet<>(); + if (!tokens.isEmpty()) { + if (!tokens.endsWith("\n")) { throw new Unavailable(); } + String[] entries = tokens.split("\n", -1); + for (int i = 0; i < entries.length - 1; i++) { + String token = entries[i]; + if (!token.matches("[0-9a-f-]{36}\\.pending") || !pending.add(token) + || pending.size() > MAX_PENDING) { throw new Unavailable(); } + } + } + if (ownMarker != null && !pending.contains(ownMarker)) { throw new Unavailable(); } + boolean otherPending = pending.stream().anyMatch(token -> !token.equals(ownMarker)); + if (automatic && (latched || otherPending)) { throw new Protected(); } + if (resume && !pending.isEmpty()) { protect = true; } + if (marker != null && (!pending.add(marker) || pending.size() > MAX_PENDING)) { + throw new Unavailable(); + } + if (removeMarker != null && !pending.remove(removeMarker)) { throw new Unavailable(); } + if (protect || marker != null || removeMarker != null) { + StringBuilder updated = new StringBuilder(prefix).append(latched || protect ? "1\n" : "0\n"); + for (String token : pending) { updated.append(token).append('\n'); } + write(channel, updated.toString()); + } + } + } catch (IOException | UnsupportedOperationException e) { throw new Unavailable(e); } + } + } + + private void finish(String marker) { access(false, false, null, null, marker, false); } + + private void validate() throws IOException { + Path root = pointer.directory(); + Path state = root.resolve("state"); + if (!root.isAbsolute() || !root.normalize().equals(root) + || !Files.isDirectory(root, LinkOption.NOFOLLOW_LINKS) + || !Files.isRegularFile(state, LinkOption.NOFOLLOW_LINKS) + || !key(root).equals(pointer.directoryKey()) || !key(state).equals(pointer.stateKey()) + || !Files.getPosixFilePermissions(root, LinkOption.NOFOLLOW_LINKS) + .equals(PosixFilePermissions.fromString("rwx------")) + || !Files.getPosixFilePermissions(state, LinkOption.NOFOLLOW_LINKS) + .equals(PosixFilePermissions.fromString("rw-------")) + || !Files.getOwner(root).equals(Files.getOwner(state)) + || Files.size(state) < 104 || Files.size(state) > 65536) { + throw new Unavailable(); + } + try (DirectoryStream entries = Files.newDirectoryStream(root)) { + for (Path entry : entries) { + if (!entry.getFileName().toString().equals("state")) { throw new Unavailable(); } + } + } + } + + private static String key(Path path) throws IOException { + Object key = Files.readAttributes(path, BasicFileAttributes.class, + LinkOption.NOFOLLOW_LINKS).fileKey(); + if (key == null) { throw new Unavailable(); } + return key.toString(); + } + + private static String digest(String value) { + try { + byte[] hash = java.security.MessageDigest.getInstance("SHA-256").digest( + value.getBytes(java.nio.charset.StandardCharsets.US_ASCII)); + return java.util.HexFormat.of().formatHex(hash); + } catch (java.security.NoSuchAlgorithmException e) { throw new Unavailable(e); } + } + + private static void write(FileChannel channel, String value) throws IOException { + String stored = value + digest(value) + "\n"; + ByteBuffer bytes = java.nio.charset.StandardCharsets.US_ASCII.encode(stored); + channel.position(0); + while (bytes.hasRemaining()) { channel.write(bytes); } + channel.truncate(stored.length()); + channel.force(true); + } + + private static void sync(Path root) throws IOException { + try (FileChannel directory = FileChannel.open(root, StandardOpenOption.READ)) { + directory.force(true); + } + } +} diff --git a/sdk/java/src/test/java/com/clickhouse/loom/SessionProtectionHttpTest.java b/sdk/java/src/test/java/com/clickhouse/loom/SessionProtectionHttpTest.java new file mode 100644 index 0000000000..7675eb3fd7 --- /dev/null +++ b/sdk/java/src/test/java/com/clickhouse/loom/SessionProtectionHttpTest.java @@ -0,0 +1,428 @@ +package com.clickhouse.loom; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.sun.net.httpserver.HttpExchange; +import com.sun.net.httpserver.HttpServer; +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.http.HttpClient; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.attribute.PosixFilePermissions; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledOnOs; +import org.junit.jupiter.api.condition.OS; +import org.junit.jupiter.api.io.TempDir; + +/** Hosted only: real JDK HTTP, owned loopback fixtures, no Loom service or providers. */ +@EnabledOnOs(OS.LINUX) +class SessionProtectionHttpTest { + private static final ObjectMapper JSON = new ObjectMapper(); + private static final String PRIVATE = "{\"result\":{\"mirrored\":true}}"; + @TempDir Path temporary; + + record Seen(String method, String path, Map> headers, JsonNode body) { + List header(String name) { + return headers.entrySet().stream().filter(e -> e.getKey().equalsIgnoreCase(name)) + .map(Map.Entry::getValue).findFirst().orElse(List.of()); + } + } + + @FunctionalInterface interface Answer { void send(HttpExchange exchange) throws IOException; } + + static final class Wire implements AutoCloseable { + final HttpServer server; + final ExecutorService executor = Executors.newFixedThreadPool(4); + final BlockingQueue seen = new LinkedBlockingQueue<>(); + final AtomicReference failure = new AtomicReference<>(); + volatile Answer answer = exchange -> json(exchange, 200, "{}"); + + Wire() throws IOException { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setExecutor(executor); + server.createContext("/", exchange -> { + try (exchange) { + byte[] input = exchange.getRequestBody().readNBytes(4 * 1024 * 1024 + 1); + if (input.length > 4 * 1024 * 1024) { throw new IOException("oversize request"); } + seen.add(new Seen(exchange.getRequestMethod(), exchange.getRequestURI().getPath(), + Map.copyOf(exchange.getRequestHeaders()), JSON.readTree(input))); + answer.send(exchange); + } catch (Throwable error) { + failure.compareAndSet(null, error); + } + }); + server.start(); + } + + String url() { return "http://127.0.0.1:" + server.getAddress().getPort(); } + Seen next() throws InterruptedException { + Seen request = seen.poll(5, TimeUnit.SECONDS); + assertNotNull(request, "wire request did not arrive"); + return request; + } + static void json(HttpExchange exchange, int status, String body) throws IOException { + byte[] bytes = body.getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(status, bytes.length); + exchange.getResponseBody().write(bytes); + } + @Override public void close() { + server.stop(0); + executor.shutdownNow(); + try { assertTrue(executor.awaitTermination(5, TimeUnit.SECONDS), "fixture worker leaked"); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new AssertionError(e); } + assertNull(failure.get(), "HTTP fixture failed"); + } + } + + private SessionProtection family(String name) { + return SessionProtection.create(temporary.resolve(name)); + } + + private LoomClient client(Wire wire, SessionProtection family, String namespace, String token) { + LoomClient.Builder builder = LoomClient.builder().baseUrl(wire.url()).org("test-org") + .namespace(namespace).agent("java-test").token(token).timeout(Duration.ofSeconds(3)); + if (family != null) { builder.sessionProtection(family); } + return builder.build(); + } + + private static void declared(Seen seen) { + assertEquals("POST", seen.method()); + assertEquals(List.of("v1"), seen.header("x-loom-session-protection")); + assertEquals(List.of("application/json"), seen.header("Content-Type")); + } + + @Test void successfulReadPersistsAcrossClientsTokensNamespacesOriginsAndResume() throws Exception { + SessionProtection family = family("conversation"); + SessionProtection.Capture capture = family.capture(); + try (Wire wire = new Wire(); Wire other = new Wire()) { + LoomClient reader = client(wire, family, "private", "reader"); + wire.answer = exchange -> Wire.json(exchange, 200, PRIVATE); + assertTrue(reader.sourceMcpRead(Map.of("name", "selected", "resource_id", "doc")) + .path("result").path("mirrored").asBoolean()); + Seen read = wire.next(); + declared(read); + assertEquals("/v1/knowledge.source.mcp_read", read.path()); + assertEquals("reader", read.header("Authorization").get(0).substring(7)); + assertEquals("selected", read.body().path("name").asText()); + assertEquals("doc", read.body().path("resource_id").asText()); + assertEquals("private", read.body().path("namespace").asText()); + assertEquals("test-org", read.body().path("org").asText()); + assertEquals(4, read.body().size()); + SessionProtection.Pointer pointer = family.pointer(); + SessionProtection reopened = SessionProtection.open(new SessionProtection.Pointer( + Path.of(pointer.directory().toString()), pointer.identity(), pointer.directoryKey(), pointer.stateKey())); + LoomClient rebuilt = client(other, reopened, "public", "writer"); + assertThrows(SessionProtection.Protected.class, () -> rebuilt.set("key", "value")); + LoomClient unbound = client(other, null, "public", "different"); + assertThrows(SessionProtection.Protected.class, + () -> unbound.callAutomatic(capture, "memory.set", Map.of("memory_key", "key", "value", 1))); + assertTrue(other.seen.isEmpty()); + rebuilt.callHuman("memory.set", Map.of("org", "test-org", "namespace", "public", + "agent", "java-test", "memory_key", "key", "value", "human")); + Seen human = other.next(); + declared(human); + assertEquals("/v1/memory.set", human.path()); + assertEquals("public", human.body().path("namespace").asText()); + assertEquals(List.of("Bearer writer"), human.header("Authorization")); + assertEquals("human", human.body().path("value").asText()); + assertThrows(SessionProtection.Protected.class, () -> rebuilt.set("again", "automatic")); + assertTrue(other.seen.isEmpty()); + } + } + + @Test void nonSuccessErrorAndTypedMethodsObserveBeforeReturning() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection errorFamily = family("error"); + LoomClient errorClient = client(wire, errorFamily, "private", "token"); + wire.answer = exchange -> Wire.json(exchange, 409, + "{\"error\":{\"code\":\"CONFLICT\",\"data\":{\"mirrored\":true}}}"); + assertThrows(LoomException.class, () -> errorClient.call("custom.read", Map.of())); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> errorClient.delete("key")); + SessionProtection decodeFamily = family("decode"); + LoomClient decode = client(wire, decodeFamily, "private", "token"); + wire.answer = exchange -> Wire.json(exchange, 200, "{\"items\":[{\"mirrored\":true}]}"); + // The raw observer precedes every typed method even if its result has unexpected fields. + decode.get("key"); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> decode.set("key", 1)); + assertTrue(wire.seen.isEmpty()); + } + } + + @Test void cleanResponsesAndOrdinaryUnboundRequestsKeepTheirBehavior() throws Exception { + try (Wire wire = new Wire()) { + LoomClient ordinary = client(wire, null, "ordinary", "token"); + wire.answer = exchange -> Wire.json(exchange, 200, PRIVATE); + ordinary.call("custom.read", Map.of()); + assertTrue(wire.next().header("x-loom-session-protection").isEmpty()); + wire.answer = exchange -> Wire.json(exchange, 200, "{}"); + ordinary.call("custom.write", Map.of()); + assertTrue(wire.next().header("x-loom-session-protection").isEmpty()); + SessionProtection clean = family("clean"); + LoomClient bound = client(wire, clean, "clean", "token"); + bound.call("custom.first", Map.of()); + declared(wire.next()); + bound.sourceMcpPause(Map.of("name", "selected")); + declared(wire.next()); + SessionProtection.open(clean.pointer()); + bound.call("custom.next", Map.of()); + declared(wire.next()); + } + } + + @Test void boundProtectedBIsCheckedWhenRetainedAIsClean() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection cleanA = family("a"); + SessionProtection protectedB = family("b"); + LoomClient clientB = client(wire, protectedB, "private", "token"); + wire.answer = exchange -> Wire.json(exchange, 200, PRIVATE); + clientB.call("custom.read", Map.of()); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> clientB.callAutomatic(cleanA.capture(), + "memory.set", Map.of("memory_key", "key", "value", 1))); + assertTrue(wire.seen.isEmpty()); + wire.answer = exchange -> Wire.json(exchange, 200, "{}"); + client(wire, cleanA, "ordinary", "token").call("custom.write", Map.of()); + declared(wire.next()); + } + } + + @Test void captureRetainsUnionThroughTasksExceptionsAndPerInvocationHumanCalls() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection a = family("capture-a"); + SessionProtection b = family("capture-b"); + LoomClient boundB = client(wire, b, "private", "token"); + wire.answer = exchange -> Wire.json(exchange, 200, PRIVATE); + SessionProtection.Capture retained = a.capture(); + retained.call(() -> boundB.call("custom.read", Map.of())); + declared(wire.next()); + LoomClient newClient = client(wire, null, "destination", "new-token"); + ExecutorService task = Executors.newSingleThreadExecutor(); + try { + Future result = task.submit(() -> { + assertThrows(SessionProtection.Protected.class, + () -> newClient.callAutomatic(retained, "custom.write", Map.of())); + assertThrows(IOException.class, () -> retained.call(() -> { throw new IOException("callback"); })); + newClient.call("custom.ordinary", Map.of()); + return true; + }); + assertTrue(result.get(5, TimeUnit.SECONDS)); + assertTrue(wire.next().header("x-loom-session-protection").isEmpty()); + } finally { + task.shutdownNow(); + assertTrue(task.awaitTermination(5, TimeUnit.SECONDS)); + } + wire.answer = exchange -> Wire.json(exchange, 200, "{}"); + retained.call(() -> newClient.callHuman("custom.write", Map.of())); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, + () -> newClient.callAutomatic(retained, "custom.write", Map.of())); + assertTrue(wire.seen.isEmpty()); + } + } + + @Test void missingReplacedCorruptAndPendingProofNeverCreateACleanResume() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection missing = family("missing"); + Files.delete(missing.pointer().directory().resolve("state")); + assertThrows(SessionProtection.Unavailable.class, () -> SessionProtection.open(missing.pointer())); + assertThrows(SessionProtection.Unavailable.class, + () -> client(wire, missing, "n", "t").callHuman("custom.write", Map.of())); + SessionProtection replaced = family("replaced"); + Path original = replaced.pointer().directory().resolve("state"); + Path saved = temporary.resolve("saved-authority"); + Files.move(original, saved); + Files.copy(saved, original); + Files.setPosixFilePermissions(original, PosixFilePermissions.fromString("rw-------")); + assertThrows(SessionProtection.Unavailable.class, () -> SessionProtection.open(replaced.pointer())); + SessionProtection corrupt = family("corrupt"); + Files.writeString(corrupt.pointer().directory().resolve("state"), "corrupt"); + assertThrows(SessionProtection.Unavailable.class, () -> SessionProtection.open(corrupt.pointer())); + SessionProtection pending = family("pending"); + try (SessionProtection.Observation inFlight = SessionProtection.begin(pending, false)) { + assertTrue(inFlight.bound()); + SessionProtection resumed = SessionProtection.open(pending.pointer()); + assertThrows(SessionProtection.Protected.class, + () -> client(wire, resumed, "n", "t").call("custom.write", Map.of())); + } + assertTrue(wire.seen.isEmpty()); + } + } + + @Test void malformedMetadataNestedJsonAndOversizeResponsesFailClosed() throws Exception { + List invalid = List.of("not json", "{} {}", "{\"mirrored\":\"true\"}", + "{\"mirrored\":true,\"mirrored\":false}", + "{\"content\":[{\"type\":\"text\",\"text\":\"{invalid\"}]}", + "{\"payload\":\"" + "x".repeat(4 * 1024 * 1024) + "\"}"); + try (Wire wire = new Wire()) { + int index = 0; + for (String body : invalid) { + SessionProtection family = family("invalid-" + index++); + LoomClient client = client(wire, family, "n", "t"); + // Chunked bodies exercise the subscriber's byte bound without relying on Content-Length. + wire.answer = exchange -> { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, 0); + try { exchange.getResponseBody().write(body.getBytes(StandardCharsets.UTF_8)); } + catch (IOException cancelled) { /* The bounded client may close before the final chunk. */ } + }; + assertThrows(RuntimeException.class, () -> client.call("custom.read", Map.of())); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> client.call("custom.write", Map.of())); + assertTrue(wire.seen.isEmpty()); + } + } + } + + @Test void nestedTextProtectionAndRetainedNestedContributorsReachTheWireObserver() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection a = family("nested-a"); + SessionProtection b = family("nested-b"); + SessionProtection.Capture retained = a.capture().call(b::capture); + LoomClient reader = client(wire, null, "n", "t"); + String inner = JSON.writeValueAsString(Map.of("mirrored", true)); + String envelope = JSON.writeValueAsString(Map.of("structuredContent", Map.of( + "content", List.of(Map.of("type", "text", "text", inner))))); + wire.answer = exchange -> Wire.json(exchange, 200, envelope); + reader.callAutomatic(retained, "custom.read", Map.of()); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, + () -> client(wire, a, "other", "new").call("custom.write", Map.of())); + assertThrows(SessionProtection.Protected.class, + () -> client(wire, b, "other", "new").call("custom.write", Map.of())); + assertTrue(wire.seen.isEmpty()); + } + } + + @Test void oversizeRequestAndInvalidUtf8RefuseBeforeAnyPublication() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection requestFamily = family("request-limit"); + LoomClient requestClient = client(wire, requestFamily, "n", "t"); + assertThrows(SessionProtection.Unavailable.class, () -> requestClient.call("custom.write", + Map.of("value", "x".repeat(4 * 1024 * 1024)))); + assertTrue(wire.seen.isEmpty()); + assertThrows(SessionProtection.Protected.class, + () -> requestClient.call("custom.next", Map.of())); + SessionProtection utf8Family = family("utf8"); + LoomClient utf8Client = client(wire, utf8Family, "n", "t"); + wire.answer = exchange -> { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + byte[] bytes = new byte[] {'{', '"', 'x', '"', ':', '"', (byte) 0xc3, '"', '}'}; + exchange.sendResponseHeaders(200, bytes.length); + exchange.getResponseBody().write(bytes); + }; + assertThrows(RuntimeException.class, () -> utf8Client.call("custom.read", Map.of())); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> utf8Client.call("custom.write", Map.of())); + assertTrue(wire.seen.isEmpty()); + } + } + + @Test void pendingResponseBlocksNewAutomaticSendsAndCancellationRetainsProof() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection family = family("cancel"); + LoomClient client = client(wire, family, "n", "t"); + CountDownLatch started = new CountDownLatch(1); + CountDownLatch cancelled = new CountDownLatch(1); + wire.answer = exchange -> { + exchange.getResponseHeaders().set("Content-Type", "application/json"); + exchange.sendResponseHeaders(200, 0); + exchange.getResponseBody().write("{".getBytes(StandardCharsets.UTF_8)); + exchange.getResponseBody().flush(); + started.countDown(); + try { + byte[] chunk = new byte[4096]; + for (int i = 0; i < 2048; i++) { + exchange.getResponseBody().write(chunk); + exchange.getResponseBody().flush(); + try { TimeUnit.MILLISECONDS.sleep(5); } + catch (InterruptedException e) { Thread.currentThread().interrupt(); break; } + } + } catch (IOException closed) { cancelled.countDown(); } + }; + AtomicReference outcome = new AtomicReference<>(); + Thread request = new Thread(() -> { + try { client.call("custom.read", Map.of()); } + catch (Throwable error) { outcome.set(error); } + }); + request.start(); + try { + assertTrue(started.await(5, TimeUnit.SECONDS)); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> client.call("custom.write", Map.of())); + request.interrupt(); + request.join(5000); + assertFalse(request.isAlive(), "cancelled request did not join"); + assertNotNull(outcome.get()); + assertTrue(cancelled.await(5, TimeUnit.SECONDS), "response connection did not close"); + SessionProtection resumed = SessionProtection.open(family.pointer()); + assertThrows(SessionProtection.Protected.class, + () -> client(wire, resumed, "new", "new").call("custom.write", Map.of())); + assertTrue(wire.seen.isEmpty()); + } finally { + request.interrupt(); + request.join(5000); + assertFalse(request.isAlive()); + } + } + } + + @Test void unsupportedStreamRefusesBeforePublicationAndTruncatedJsonRetainsProof() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection stream = family("stream"); + LoomClient client = client(wire, stream, "n", "t"); + wire.answer = exchange -> { + exchange.getResponseHeaders().set("Content-Type", "text/event-stream"); + exchange.sendResponseHeaders(200, 0); + try { exchange.getResponseBody().write("data: {}\n\n".getBytes(StandardCharsets.UTF_8)); } + catch (IOException closed) { /* Media refusal cancels the response subscription. */ } + }; + assertThrows(RuntimeException.class, () -> client.call("custom.read", Map.of())); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> client.call("custom.write", Map.of())); + SessionProtection truncated = family("truncated"); + LoomClient other = client(wire, truncated, "n", "t"); + wire.answer = exchange -> Wire.json(exchange, 200, "{\"result\":"); + assertThrows(SessionProtection.Unavailable.class, () -> other.call("custom.read", Map.of())); + declared(wire.next()); + assertThrows(SessionProtection.Protected.class, () -> other.call("custom.write", Map.of())); + assertTrue(wire.seen.isEmpty()); + } + } + + @Test void redirectsAndCustomRoutesCannotBypassTheObservedBoundary() throws Exception { + try (Wire wire = new Wire()) { + SessionProtection family = family("redirect"); + LoomClient client = LoomClient.builder().baseUrl(wire.url()).org("test-org") + .namespace("n").agent("java-test").sessionProtection(family) + .httpClient(HttpClient.newBuilder().followRedirects(HttpClient.Redirect.ALWAYS).build()).build(); + assertThrows(SessionProtection.Unavailable.class, () -> client.call("custom.read", Map.of())); + LoomClient guarded = client(wire, family("route"), "n", "t"); + assertThrows(IllegalArgumentException.class, + () -> guarded.call("../custom", Map.of())); + assertTrue(wire.seen.isEmpty()); + } + } +} From 8f4ab133f512a93dcc5dd13bab5fd51cc5a23c36 Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 06:58:17 +0000 Subject: [PATCH 28/30] Protect Go source requests across retained client contexts Bind durable application-owned proof to the shared HTTP boundary, retain contributing families across tasks and process resume, and add owned HTTP fixtures for hosted race qualification. Native execution remains pending. Signed-off-by: zlareb1 --- sdk/go/README.md | 47 +- sdk/go/SESSION_PROTECTION.md | 134 ++++++ sdk/go/client.go | 52 +- sdk/go/operations.go | 64 +++ sdk/go/session_envelope.go | 158 +++++++ sdk/go/session_http.go | 176 +++++++ sdk/go/session_protection.go | 428 +++++++++++++++++ sdk/go/session_protection_http_test.go | 626 +++++++++++++++++++++++++ sdk/go/session_request.go | 83 ++++ sdk/go/session_store_unix.go | 47 ++ sdk/go/session_store_unsupported.go | 14 + 11 files changed, 1819 insertions(+), 10 deletions(-) create mode 100644 sdk/go/SESSION_PROTECTION.md create mode 100644 sdk/go/operations.go create mode 100644 sdk/go/session_envelope.go create mode 100644 sdk/go/session_http.go create mode 100644 sdk/go/session_protection.go create mode 100644 sdk/go/session_protection_http_test.go create mode 100644 sdk/go/session_request.go create mode 100644 sdk/go/session_store_unix.go create mode 100644 sdk/go/session_store_unsupported.go diff --git a/sdk/go/README.md b/sdk/go/README.md index 75a5bf2164..46fdc8a7a2 100644 --- a/sdk/go/README.md +++ b/sdk/go/README.md @@ -1,14 +1,15 @@ # Loom Go client -A minimal Go client for [ClickHouse Loom](https://clickhouse.github.io/loom/)'s memory -operations: `memory.set`, `memory.get`, `memory.search` and `memory.delete`. It depends -on the standard library only (`net/http`), and every call takes a `context.Context`. +A Go client for [ClickHouse Loom](https://clickhouse.github.io/loom/) with typed +`memory.set`, `memory.get`, `memory.search` and `memory.delete` methods and generic +operation calls. It depends on the standard library only (`net/http`), and every +call takes a `context.Context`. ```bash go get github.com/ClickHouse/loom/sdk/go ``` -The full surface (every operation, typed from the server's registry) is in the +Generated types for the full operation surface are in the [Python](https://github.com/ClickHouse/loom/tree/main/sdk/python) and [TypeScript](https://github.com/ClickHouse/loom/tree/main/sdk/typescript) SDKs. @@ -54,9 +55,36 @@ org, namespace and agent in its body. | `APIKey` | `LOOM_API_KEY`; with neither, no `Authorization` header | | `Org`, `Namespace`, `Agent` | Left out of the body when blank, so the server's defaults apply | | `HTTPClient` | `http.DefaultClient` | - -The client sends one request per call and never retries. It does not follow redirects, so a -memory body and token never go to another origin: a 3xx answer comes back as a `*loom.Error`. +| `SessionProtection` | Unbound; ordinary requests send no protection declaration | + +The client sends one request per call and never retries. Redirects are refused by +default; ordinary clients can supply a redirect policy in `HTTPClient`. Protected +clients always refuse redirects and hidden transport retries. + +## Generic source and connection operations + +`Call(ctx, operation, arguments, &output)` uses the same HTTP boundary as the typed +methods. It copies arguments and fills absent `org`, `namespace` and `agent` from +the client. Output may be a typed value, a map or `json.RawMessage`. Use the current +server schema for each operation; Go has no generated source declarations. + +| Operation | Arguments in addition to identity | +| --- | --- | +| `knowledge.connection.mcp_browse` | `slot`, `mode` (`resources` or `search`); optional `query`, `limit` | +| `knowledge.connection.mcp_disconnect` | `slot` | +| `knowledge.source.mcp_list` | Optional `cursor`, `limit`, `include_retired` | +| `knowledge.source.mcp_read` | `name`, `resource_id` | +| `knowledge.source.mcp_pause` | `name` | +| `knowledge.source.mcp_resume` | `name` | +| `knowledge.source.mcp_refresh` | `name` | + +Protected source reads require an application-owned durable family through +`Config.SessionProtection`. Bound calls are automatic by default. After protected +content or while a response is pending, automatic calls refuse. There are no +generated read-only exemptions in Go, so this also refuses automatic reads. +`CallHuman` records explicit user intent for one invocation and still observes +the response. See [session protection](SESSION_PROTECTION.md) for storage, +restoration and deferred-task ownership. ## Errors @@ -82,4 +110,7 @@ do about each are in the cd sdk/go && go test ./... ``` -The tests run against a local fake server and need no running Loom. +The tests use owned loopback HTTP servers and need no running Loom. Protection +tests include response errors, chunking, cancellation, restoration and a child +process. Native compilation, formatting and these cases require hosted execution; +this change has no native pass receipt or real-service qualification. diff --git a/sdk/go/SESSION_PROTECTION.md b/sdk/go/SESSION_PROTECTION.md new file mode 100644 index 0000000000..babb594851 --- /dev/null +++ b/sdk/go/SESSION_PROTECTION.md @@ -0,0 +1,134 @@ +# Protected source sessions + +The application owns one durable family per conversation and binds it through +`Config.SessionProtection`. The SDK sends exactly one +`x-loom-session-protection: v1` declaration only after durable admission, with its +raw response observer installed. An unbound ordinary client sends no declaration. + +## Provision and restore + +Provision a new family once under an application-owned private directory: + +```go +family, err := loom.CreateSessionProtection(conversationStorageDirectory) +if err != nil { + return err +} +pointer := family.Pointer() +// Persist every pointer field in the application's trusted conversation record. +client := loom.New(loom.Config{ + BaseURL: serverURL, APIKey: token, Org: org, Namespace: namespace, + SessionProtection: family, +}) +``` + +Restoring a conversation uses its existing trusted pointer: + +```go +family, err := loom.OpenSessionProtection(pointer) +if err != nil { + return err +} +``` + +Do not provision a replacement when restore fails. Storage is independent of user +configuration, client identity, origin and credentials. Changing any of those or +copying a client must retain the same family. A new pointer belongs to a new +conversation; it cannot clear protected history in an existing one. + +The built-in store uses a new private directory, a random identity, stable file +identities, an in-place monotonic state byte, a cross-process lock and durable +pending records. It stores no source bytes, credentials or messages. Missing, +replaced, corrupt, symlinked or inaccessible authority refuses, including explicit +human calls. Interrupted observations retain pending proof; reopening pending +proof marks the family protected. There is no SDK reset or pending-clear API. +Store scans cap at 10,000 entries; overflow refuses further dispatch. + +The host and trusted application storage must prevent rollback of the pointer +and store together, unauthorized writes and deletion. File identities detect +replacement; they are not a secure hardware counter or protection against a +compromised host. Keep the store and its parent private to the application user, +on a local filesystem supporting durable file/directory sync and POSIX locks. +Lock waits are bounded; blocking kernel storage operations require a healthy +host filesystem. Network filesystems and cross-host authority are unsupported. + +The store is selected on Linux, macOS, FreeBSD, NetBSD, OpenBSD and DragonFly build +targets. Other targets refuse protected provisioning and restore; ordinary +unbound clients remain available. Platform compilation and behavior require +hosted qualification. + +## Calls and retained work + +Bound typed methods and `Call` are automatic. Every invocation rechecks the +durable latch and pending responses immediately before HTTP dispatch. Protected +content and incomplete concurrent responses refuse new automatic operations, +including unknown operations and calls addressed to another namespace. Go has no +generated read-only operation metadata, so it conservatively applies this guard +to reads too. + +Use the actual source-read arguments: + +```go +capture := loom.CaptureSession(ctx, family) +readContext := capture.Context(ctx) +var result map[string]any +err := client.Call(readContext, "knowledge.source.mcp_read", map[string]any{ + "name": sourceName, + "resource_id": resourceID, +}, &result) +``` + +Retain `capture` with callbacks and queued tasks, then call +`capture.Context(taskContext)` when they run. The context can cross goroutines and +HTTP clients. `CaptureSession` and `Context` union existing contributors; dispatch +also includes the client's currently bound family. A clean retained family cannot +hide a protected bound family. Responses observe every contributing family before +returning. At most 64 contributors are accepted. Invalid or empty captures refuse. +The application must retain all contributors when scheduling work; the SDK does +not track arbitrary tasks or infer their provenance. + +After obtaining explicit intent from the application user for a specific +operation, invoke `CallHuman` once: + +```go +err := client.CallHuman(readContext, "memory.set", map[string]any{ + "memory_key": chosenKey, + "value": userSelectedValue, +}, &result) +``` + +This authorizes only that invocation. It validates proof, observes the response +and keeps the latch. It does not place authority in a context, client facade, +callback or task. Every later explicit operation requires new human intent; +automatic work keeps using guarded `Call` or the typed methods. + +## HTTP and storage limits + +Protected calls use the standard `http.Transport`; custom `RoundTripper` wrappers +refuse because they can conceal resends or publish unobserved responses. Configure +the transport before use and keep it immutable. Application dial/proxy callbacks +must honor context cancellation. Redirects and internal body replays refuse. +The SDK has no retry, pacing, streaming or download API. Caller retry loops must +make a new guarded invocation after every wait. + +The observer examines JSON at every HTTP status before API errors, typed +conversion or body publication. It follows `mirrored`, `result`, +`structuredContent`, `items`, JSON text content blocks and `error.data`. Invalid +metadata, duplicate keys, malformed JSON, truncated bodies and unsupported media +retain protection and refuse publication. SSE and binary responses refuse before +any bytes reach the caller. Empty 204/304 responses acknowledge observation; the +typed API can still report an invalid empty JSON result. + +Requests and response bodies are capped at 4 MiB. Request validation bounds +encoding work to 10,000 nodes and 64 nesting levels and conservatively budgets +escaped strings. Protected requests reject custom JSON/text marshalers; pass +plain JSON data. Response parsing shares a 10,000-node budget across nested text +documents and limits each JSON nesting depth to 64. HTTP work has a 30-second +context deadline, shortened by caller/client deadlines. Each lock wait has a +two-second deadline. Cancellation closes the owned response and completes bounded +proof cleanup before returning; failed cleanup leaves pending records. + +The authored native tests use owned loopback HTTP fixtures. Compilation, +formatting, tests and platform behavior are unrun in this authoring environment. +Actual service authorization, source ingestion and vendor compatibility require +separate hosted qualification. No compatibility claim follows from these fixtures. diff --git a/sdk/go/client.go b/sdk/go/client.go index e460212c04..f2fd683a9e 100644 --- a/sdk/go/client.go +++ b/sdk/go/client.go @@ -39,6 +39,10 @@ type Config struct { // uses a copy that answers a redirect with an *Error instead of following // it, unless this client sets its own CheckRedirect. HTTPClient *http.Client + + // SessionProtection binds the application's durable conversation family. + // Bound calls are automatic unless made through CallHuman. + SessionProtection *SessionProtection } // Client calls the memory operations as one org, namespace and agent. @@ -48,6 +52,7 @@ type Client struct { apiKey string identity identity http *http.Client + protection *SessionProtection } type identity struct { @@ -75,6 +80,7 @@ func New(cfg Config) *Client { apiKey: firstNonBlank(cfg.APIKey, os.Getenv("LOOM_API_KEY")), identity: identity{Org: cfg.Org, Namespace: cfg.Namespace, Agent: cfg.Agent}, http: &client, + protection: cfg.SessionProtection, } } @@ -89,10 +95,34 @@ func firstNonBlank(values ...string) string { // call posts in to /v1/ and decodes a 2xx answer into out. func (c *Client) call(ctx context.Context, op string, in, out any) error { + return c.dispatch(ctx, op, in, out, false) +} + +func (c *Client) dispatch(ctx context.Context, op string, in, out any, human bool) error { + if !validOperation(op) { + return fmt.Errorf("invalid operation name") + } + families, err := requestFamilies(ctx, c.protection) + if err != nil { + return err + } + httpClient := c.http + if len(families) != 0 { + httpClient, err = protectedHTTPClient(c.http) + if err != nil || validateProtectedInput(in) != nil { + return ErrSessionProtectionUnavailable + } + var cancel context.CancelFunc + ctx, cancel = protectedDeadline(ctx) + defer cancel() + } body, err := json.Marshal(in) if err != nil { return fmt.Errorf("%s: encode request: %w", op, err) } + if len(families) != 0 && len(body) > maxProtectedBody { + return ErrSessionProtectionUnavailable + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+"/v1/"+op, bytes.NewReader(body)) if err != nil { return fmt.Errorf("%s: %w", op, err) @@ -105,12 +135,30 @@ func (c *Client) call(ctx context.Context, op string, in, out any) error { req.Header.Set("Authorization", "Bearer "+c.apiKey) } - resp, err := c.http.Do(req) + observation, err := beginObservation(ctx, families, human) if err != nil { + return err + } + defer observation.abort() + if observation != nil { + req.Header.Set("X-Loom-Session-Protection", "v1") + // A replay inside net/http would bypass durable admission. + req.GetBody = nil + } + resp, err := httpClient.Do(req) + if err != nil { + if resp != nil && resp.Body != nil { + resp.Body.Close() + } return fmt.Errorf("%s: %w", op, err) } defer resp.Body.Close() - raw, err := io.ReadAll(resp.Body) + var raw []byte + if observation != nil { + raw, err = observation.readResponse(resp) + } else { + raw, err = io.ReadAll(resp.Body) + } if err != nil { return fmt.Errorf("%s: read response: %w", op, err) } diff --git a/sdk/go/operations.go b/sdk/go/operations.go new file mode 100644 index 0000000000..565c362fce --- /dev/null +++ b/sdk/go/operations.go @@ -0,0 +1,64 @@ +package loom + +import ( + "context" + "fmt" +) + +// Call invokes an existing operation with its wire-schema arguments. Bound and +// retained families guard automatic calls, including calls through other clients. +// It does not retry. Unknown operations have no read-only exemption. +func (c *Client) Call(ctx context.Context, op string, arguments map[string]any, out any) error { + in, err := c.operationArguments(arguments) + if err != nil { + return err + } + return c.call(ctx, op, in, out) +} + +// CallHuman records explicit human intent for this invocation only. The caller +// must obtain that intent from the application user for each call. It still +// validates durable proof and observes responses. No authority enters ctx. +func (c *Client) CallHuman(ctx context.Context, op string, arguments map[string]any, out any) error { + in, err := c.operationArguments(arguments) + if err != nil { + return err + } + return c.dispatch(ctx, op, in, out, true) +} + +func (c *Client) operationArguments(arguments map[string]any) (map[string]any, error) { + if len(arguments) > 10000 { + return nil, fmt.Errorf("too many operation arguments") + } + in := make(map[string]any, len(arguments)+3) + for key, value := range arguments { + in[key] = value + } + for key, value := range map[string]string{"org": c.identity.Org, "namespace": c.identity.Namespace, "agent": c.identity.Agent} { + if _, supplied := in[key]; !supplied && value != "" { + in[key] = value + } + } + return in, nil +} + +func validOperation(op string) bool { + if len(op) == 0 || len(op) > 160 { + return false + } + for _, ch := range op { + if ch != '.' && ch != '_' && (ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') { + return false + } + } + if op[0] == '.' || op[len(op)-1] == '.' { + return false + } + for i := 1; i < len(op); i++ { + if op[i] == '.' && op[i-1] == '.' { + return false + } + } + return true +} diff --git a/sdk/go/session_envelope.go b/sdk/go/session_envelope.go new file mode 100644 index 0000000000..3a04bfa3df --- /dev/null +++ b/sdk/go/session_envelope.go @@ -0,0 +1,158 @@ +package loom + +import ( + "encoding/json" + "io" + "strings" + "unicode/utf8" +) + +// A shared budget also bounds JSON documents embedded in MCP text blocks. +type sessionJSONBudget struct { nodes, text int } + +func protectedEnvelope(raw []byte) (bool, error) { + budget := &sessionJSONBudget{nodes: 10000, text: maxProtectedBody} + value, err := budget.decode(string(raw)) + if err != nil { + return false, err + } + root, ok := value.(map[string]any) + if !ok { + return false, ErrSessionProtectionUnavailable + } + pending := []map[string]any{root} + protected := false + for len(pending) != 0 { + if len(pending) > 10000 { + return false, ErrSessionProtectionUnavailable + } + item := pending[len(pending)-1] + pending = pending[:len(pending)-1] + if mirrored, exists := item["mirrored"]; exists { + flag, ok := mirrored.(bool) + if !ok { + return false, ErrSessionProtectionUnavailable + } + protected = protected || flag + } + for _, key := range []string{"result", "structuredContent"} { + if child, ok := item[key].(map[string]any); ok { + pending = append(pending, child) + } + } + if fault, ok := item["error"].(map[string]any); ok { + if data, ok := fault["data"].(map[string]any); ok { + pending = append(pending, data) + } + } + if items, ok := item["items"].([]any); ok { + for _, child := range items { + if child, ok := child.(map[string]any); ok { + pending = append(pending, child) + } + } + } + if content, ok := item["content"].([]any); ok { + for _, block := range content { + block, ok := block.(map[string]any) + if !ok || block["type"] != "text" { + continue + } + text, ok := block["text"].(string) + if !ok { + return false, ErrSessionProtectionUnavailable + } + budget.text -= len(text) + if budget.text < 0 { + return false, ErrSessionProtectionUnavailable + } + if strings.HasPrefix(strings.TrimSpace(text), "{") { + decoded, err := budget.decode(text) + if err != nil { + return false, err + } + child, ok := decoded.(map[string]any) + if !ok { + return false, ErrSessionProtectionUnavailable + } + pending = append(pending, child) + } + } + } + } + return protected, nil +} + +func (budget *sessionJSONBudget) decode(text string) (any, error) { + if !utf8.ValidString(text) || len(text) > maxProtectedBody { + return nil, ErrSessionProtectionUnavailable + } + decoder := json.NewDecoder(strings.NewReader(text)) + decoder.UseNumber() + value, err := budget.value(decoder, 0) + if err != nil { + return nil, err + } + if _, err := decoder.Token(); err != io.EOF { + return nil, ErrSessionProtectionUnavailable + } + return value, nil +} + +func (budget *sessionJSONBudget) value(decoder *json.Decoder, depth int) (any, error) { + budget.nodes-- + if budget.nodes < 0 || depth > 64 { + return nil, ErrSessionProtectionUnavailable + } + token, err := decoder.Token() + if err != nil { + return nil, ErrSessionProtectionUnavailable + } + delim, compound := token.(json.Delim) + if !compound { + return token, nil + } + switch delim { + case '{': + object := make(map[string]any) + for decoder.More() { + key, err := decoder.Token() + if err != nil { + return nil, ErrSessionProtectionUnavailable + } + name, ok := key.(string) + if !ok { + return nil, ErrSessionProtectionUnavailable + } + if _, duplicate := object[name]; duplicate { + return nil, ErrSessionProtectionUnavailable + } + child, err := budget.value(decoder, depth+1) + if err != nil { + return nil, err + } + object[name] = child + } + closing, err := decoder.Token() + if err != nil || closing != json.Delim('}') { + return nil, ErrSessionProtectionUnavailable + } + return object, nil + case '[': + var array []any + for decoder.More() { + child, err := budget.value(decoder, depth+1) + if err != nil { + return nil, err + } + array = append(array, child) + } + closing, err := decoder.Token() + if err != nil || closing != json.Delim(']') { + return nil, ErrSessionProtectionUnavailable + } + return array, nil + default: + return nil, ErrSessionProtectionUnavailable + } +} diff --git a/sdk/go/session_http.go b/sdk/go/session_http.go new file mode 100644 index 0000000000..3821092951 --- /dev/null +++ b/sdk/go/session_http.go @@ -0,0 +1,176 @@ +package loom + +import ( + "context" + "io" + "mime" + "net/http" + "os" + "path/filepath" + "strings" + "time" +) + +const maxProtectedBody = 4 * 1024 * 1024 + +func protectedDeadline(ctx context.Context) (context.Context, context.CancelFunc) { + return context.WithTimeout(ctx, 30*time.Second) +} + +func protectedHTTPClient(client *http.Client) (*http.Client, error) { + copyClient := *client + if copyClient.Transport == nil { + copyClient.Transport = http.DefaultTransport + } + // Resolve the mutable default once; a wrapper could hide automatic sends. + if transport, ok := copyClient.Transport.(*http.Transport); !ok || transport == nil { + return nil, ErrSessionProtectionUnavailable + } + copyClient.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return ©Client, nil +} + +type sessionObservation struct { + families []*SessionProtection + pending map[string]string + complete bool +} + +func beginObservation(ctx context.Context, families []*SessionProtection, human bool) (*sessionObservation, error) { + if len(families) == 0 { + return nil, nil + } + id, err := sessionRandom(16) + if err != nil { + return nil, err + } + observation := &sessionObservation{families: families, pending: make(map[string]string)} + err = withSessionLocks(ctx, families, func() error { + for _, f := range families { + if err := f.validate(); err != nil { + return err + } + pending, err := f.pending("") + if err != nil { + return err + } + if !human && (f.latched.Load() || pending) { + return ErrAutomaticSessionProtected + } + } + for _, f := range families { + if _, exists := observation.pending[f.pointer.Path]; exists { + continue + } + name := "pending-"+id + observation.pending[f.pointer.Path] = name + if err := sessionCreateFile(filepath.Join(f.pointer.Path, name), "1"); err != nil { + return err + } + if err := sessionSync(f.pointer.Path); err != nil { + return f.reject() + } + } + // This is the final admission barrier, after all storage waits. No read + // exemptions exist without exact generated operation metadata. + for _, f := range families { + if err := f.validate(); err != nil { + return err + } + pending, err := f.pending(observation.pending[f.pointer.Path]) + if err != nil { + return err + } + if !human && (f.latched.Load() || pending) { + return ErrAutomaticSessionProtected + } + } + return ctx.Err() + }) + if err != nil { + if len(observation.pending) != 0 { + observation.abort() + } + return nil, err + } + return observation, nil +} + +func (observation *sessionObservation) abort() { + if observation == nil || observation.complete { + return + } + // Cancellation cannot discard owned cleanup. The independent lock deadline + // bounds this work; pending records survive even if storage cannot be marked. + err := withSessionLocks(context.Background(), observation.families, func() error { + var failed bool + for _, f := range observation.families { + failed = f.mark() != nil || failed + } + if failed { + return ErrSessionProtectionUnavailable + } + return nil + }) + for _, f := range observation.families { + f.latched.Store(true) + if err != nil { + f.failed.Store(true) + } + } +} + +func (observation *sessionObservation) readResponse(response *http.Response) ([]byte, error) { + media, _, err := mime.ParseMediaType(response.Header.Get("Content-Type")) + emptyAllowed := response.StatusCode == 204 || response.StatusCode == 304 + if err != nil || (media != "application/json" && !strings.HasSuffix(media, "+json")) { + if !emptyAllowed || response.Header.Get("Content-Type") != "" { + return nil, ErrSessionProtectionUnavailable + } + } + if response.ContentLength > maxProtectedBody { + return nil, ErrSessionProtectionUnavailable + } + raw, readErr := io.ReadAll(io.LimitReader(response.Body, maxProtectedBody+1)) + closeErr := response.Body.Close() + if readErr != nil || closeErr != nil || len(raw) > maxProtectedBody { + return nil, ErrSessionProtectionUnavailable + } + input := raw + if len(input) == 0 && emptyAllowed { + input = []byte("{}") + } + protected, err := protectedEnvelope(input) + if err != nil { + return nil, err + } + err = withSessionLocks(context.Background(), observation.families, func() error { + for _, f := range observation.families { + if err := f.validate(); err != nil { + return err + } + if _, err := f.pending(""); err != nil { + return err + } + if protected { + if err := f.mark(); err != nil { + return err + } + } + } + for path, name := range observation.pending { + if err := os.Remove(filepath.Join(path, name)); err != nil { + return ErrSessionProtectionUnavailable + } + if err := sessionSync(path); err != nil { + return err + } + } + return nil + }) + if err != nil { + return nil, ErrSessionProtectionUnavailable + } + observation.complete = true + return raw, nil +} diff --git a/sdk/go/session_protection.go b/sdk/go/session_protection.go new file mode 100644 index 0000000000..34f148c5a6 --- /dev/null +++ b/sdk/go/session_protection.go @@ -0,0 +1,428 @@ +package loom + +import ( + "context" + "crypto/rand" + "encoding/hex" + "errors" + "io" + "os" + "path/filepath" + "sort" + "strings" + "sync/atomic" + "time" +) + +var ( + // ErrSessionProtectionUnavailable means the durable authority cannot be proved. + ErrSessionProtectionUnavailable = errors.New("session protection proof is unavailable") + // ErrAutomaticSessionProtected refuses an automatic operation after protected + // content, or while another request's observation is pending. + ErrAutomaticSessionProtected = errors.New("automatic operation refused by session protection") +) + +// SessionProtectionPointer belongs in trusted application conversation storage, +// independently of client configuration. Preserve every field on restore. +// Filesystem identities detect replacement; they do not prevent storage rollback. +type SessionProtectionPointer struct { + Path string `json:"path"` + ID string `json:"id"` + DirectoryIdentity string `json:"directory_identity"` + ManifestIdentity string `json:"manifest_identity"` + StateIdentity string `json:"state_identity"` + LockIdentity string `json:"lock_identity"` +} + +// SessionProtection is a monotonic, content-free application conversation family. +// Share its pointer across clients and retain captures across queued work. +type SessionProtection struct { + pointer SessionProtectionPointer + latched atomic.Bool + failed atomic.Bool +} + +// CreateSessionProtection provisions a new conversation in a new private +// directory under a trusted private parent. Never call it to restore a session. +func CreateSessionProtection(path string) (*SessionProtection, error) { + if !sessionPlatformSupported() { + return nil, ErrSessionProtectionUnavailable + } + absolute, err := filepath.Abs(path) + if err != nil { + return nil, ErrSessionProtectionUnavailable + } + parent, err := filepath.EvalSymlinks(filepath.Dir(absolute)) + if err != nil { + return nil, ErrSessionProtectionUnavailable + } + parentInfo, err := os.Lstat(parent) + if err != nil || !parentInfo.IsDir() || !sessionPrivate(parentInfo) { + return nil, ErrSessionProtectionUnavailable + } + absolute = filepath.Join(parent, filepath.Base(absolute)) + if err := os.Mkdir(absolute, 0700); err != nil { + return nil, ErrSessionProtectionUnavailable + } + id, err := sessionRandom(32) + if err != nil { + return nil, err + } + for _, item := range []struct{name, value string}{{"identity", id}, {"state", "0"}, {"lock", ""}} { + if err := sessionCreateFile(filepath.Join(absolute, item.name), item.value); err != nil { + return nil, err + } + } + if sessionSync(absolute) != nil || sessionSync(parent) != nil { + return nil, ErrSessionProtectionUnavailable + } + pointer := SessionProtectionPointer{Path: absolute, ID: id} + for name, target := range map[string]*string{"": &pointer.DirectoryIdentity, "identity": &pointer.ManifestIdentity, "state": &pointer.StateIdentity, "lock": &pointer.LockIdentity} { + info, err := os.Lstat(filepath.Join(absolute, name)) + if err != nil { + return nil, ErrSessionProtectionUnavailable + } + *target, err = sessionFileIdentity(info) + if err != nil { + return nil, err + } + } + return OpenSessionProtection(pointer) +} + +// OpenSessionProtection reopens exactly the trusted authority. Pending attempts +// remain protected; missing, replaced or corrupt proof never creates a family. +func OpenSessionProtection(pointer SessionProtectionPointer) (*SessionProtection, error) { + if !sessionPlatformSupported() || !filepath.IsAbs(pointer.Path) || !sessionHex(pointer.ID, 32) { + return nil, ErrSessionProtectionUnavailable + } + resolved, err := filepath.EvalSymlinks(pointer.Path) + if err != nil || resolved != pointer.Path { + return nil, ErrSessionProtectionUnavailable + } + f := &SessionProtection{pointer: pointer} + err = withSessionLocks(context.Background(), []*SessionProtection{f}, func() error { + if err := f.validate(); err != nil { + return err + } + pending, err := f.pending("") + if err != nil { + return err + } + if pending { + return f.mark() + } + return nil + }) + if err != nil { + return nil, err + } + return f, nil +} + +func (f *SessionProtection) Pointer() SessionProtectionPointer { return f.pointer } + +// Protected validates storage and reports the latch or an unacknowledged attempt. +func (f *SessionProtection) Protected(ctx context.Context) (bool, error) { + var protected bool + err := withSessionLocks(ctx, []*SessionProtection{f}, func() error { + if err := f.validate(); err != nil { + return err + } + pending, err := f.pending("") + protected = f.latched.Load() || pending + return err + }) + return protected, err +} + +// SessionCapture retains all families that contributed to deferred work. +// Values are immutable; pass Context's result to callbacks and goroutines. +type SessionCapture struct { families []*SessionProtection } +type sessionCaptureKey struct{} + +// CaptureSession unions the current retained capture with the supplied families. +func CaptureSession(ctx context.Context, families ...*SessionProtection) SessionCapture { + if len(families) > 64 { + return SessionCapture{families: []*SessionProtection{nil}} + } + var all []*SessionProtection + if current, ok := ctx.Value(sessionCaptureKey{}).(SessionCapture); ok { + if len(current.families) > 64 { + return SessionCapture{families: []*SessionProtection{nil}} + } + all = append(all, current.families...) + } + all = append(all, families...) + seen := make(map[*SessionProtection]bool) + unique := all[:0] + for _, family := range all { + if family == nil { + return SessionCapture{families: []*SessionProtection{nil}} + } + if !seen[family] { + seen[family] = true + unique = append(unique, family) + } + } + if len(unique) > 64 { + return SessionCapture{families: []*SessionProtection{nil}} + } + return SessionCapture{families: unique} +} + +// Context adds this capture to the context's existing contributors. It carries +// no human authority. An empty or invalid capture refuses protected dispatch. +func (capture SessionCapture) Context(ctx context.Context) context.Context { + merged := CaptureSession(ctx, capture.families...) + return context.WithValue(ctx, sessionCaptureKey{}, merged) +} + +func requestFamilies(ctx context.Context, bound *SessionProtection) ([]*SessionProtection, error) { + var families []*SessionProtection + if capture, ok := ctx.Value(sessionCaptureKey{}).(SessionCapture); ok { + if len(capture.families) == 0 { + return nil, ErrSessionProtectionUnavailable + } + families = append(families, capture.families...) + } + if bound != nil { + families = append(families, bound) + } + if len(families) > 64 { + return nil, ErrSessionProtectionUnavailable + } + seen := make(map[*SessionProtection]bool) + unique := families[:0] + for _, f := range families { + if f == nil { + return nil, ErrSessionProtectionUnavailable + } + if !seen[f] { + seen[f] = true + unique = append(unique, f) + } + } + sort.Slice(unique, func(i, j int) bool { return unique[i].pointer.Path < unique[j].pointer.Path }) + return unique, nil +} + +func (f *SessionProtection) reject() error { + f.failed.Store(true) + return ErrSessionProtectionUnavailable +} + +func (f *SessionProtection) file(name, identity string, size int64) (*os.File, error) { + path := filepath.Join(f.pointer.Path, name) + info, err := os.Lstat(path) + if err != nil || !info.Mode().IsRegular() || !sessionPrivate(info) || info.Size() != size { + return nil, f.reject() + } + actual, err := sessionFileIdentity(info) + if err != nil || actual != identity || identity == "" { + return nil, f.reject() + } + file, err := os.OpenFile(path, os.O_RDWR, 0) + if err != nil { + return nil, f.reject() + } + opened, err := file.Stat() + if err != nil || !os.SameFile(info, opened) { + file.Close() + return nil, f.reject() + } + return file, nil +} + +func (f *SessionProtection) validate() error { + if f == nil || f.failed.Load() { + return ErrSessionProtectionUnavailable + } + info, err := os.Lstat(f.pointer.Path) + if err != nil || !info.IsDir() || !sessionPrivate(info) { + return f.reject() + } + id, err := sessionFileIdentity(info) + if err != nil || id != f.pointer.DirectoryIdentity || id == "" { + return f.reject() + } + manifest, err := f.file("identity", f.pointer.ManifestIdentity, 64) + if err != nil { + return err + } + value, err := io.ReadAll(io.LimitReader(manifest, 65)) + closeErr := manifest.Close() + if err != nil || closeErr != nil || string(value) != f.pointer.ID { + return f.reject() + } + state, err := f.file("state", f.pointer.StateIdentity, 1) + if err != nil { + return err + } + value, err = io.ReadAll(io.LimitReader(state, 2)) + closeErr = state.Close() + if err != nil || closeErr != nil { + return f.reject() + } + switch string(value) { + case "1": + f.latched.Store(true) + case "0": + if f.latched.Load() { + return f.reject() + } + default: + return f.reject() + } + return nil +} + +// mark runs with the family's storage lock held. The local latch precedes I/O. +func (f *SessionProtection) mark() error { + f.latched.Store(true) + file, err := f.file("state", f.pointer.StateIdentity, 1) + if err != nil { + return err + } + _, writeErr := file.WriteAt([]byte("1"), 0) + syncErr := file.Sync() + closeErr := file.Close() + if writeErr != nil || syncErr != nil || closeErr != nil { + return f.reject() + } + return nil +} + +func (f *SessionProtection) pending(own string) (bool, error) { + directory, err := os.Open(f.pointer.Path) + if err != nil { + return false, f.reject() + } + entries, readErr := directory.ReadDir(10001) + closeErr := directory.Close() + if (readErr != nil && readErr != io.EOF) || closeErr != nil || len(entries) > 10000 { + return false, f.reject() + } + found := false + for _, entry := range entries { + name := entry.Name() + if name == "identity" || name == "state" || name == "lock" { + continue + } + if !strings.HasPrefix(name, "pending-") || !sessionHex(strings.TrimPrefix(name, "pending-"), 16) { + return false, f.reject() + } + info, err := os.Lstat(filepath.Join(f.pointer.Path, name)) + if err != nil || !info.Mode().IsRegular() || !sessionPrivate(info) || info.Size() != 1 { + return false, f.reject() + } + id, err := sessionFileIdentity(info) + if err != nil { + return false, f.reject() + } + file, err := f.file(name, id, 1) + if err != nil { + return false, err + } + value, readErr := io.ReadAll(io.LimitReader(file, 2)) + closeErr := file.Close() + if readErr != nil || closeErr != nil || string(value) != "1" { + return false, f.reject() + } + found = found || name != own + } + return found, nil +} + +func withSessionLocks(ctx context.Context, families []*SessionProtection, work func() error) error { + ctx, cancel := context.WithTimeout(ctx, 2*time.Second) + defer cancel() + locks := make([]*os.File, 0, len(families)) + defer func() { + for i := len(locks)-1; i >= 0; i-- { + sessionUnlock(locks[i]) + locks[i].Close() + } + }() + paths := make(map[string]SessionProtectionPointer) + for _, f := range families { + if f == nil || f.failed.Load() { + return ErrSessionProtectionUnavailable + } + if !sessionPlatformSupported() || !filepath.IsAbs(f.pointer.Path) || !sessionHex(f.pointer.ID, 32) { + return f.reject() + } + if old, exists := paths[f.pointer.Path]; exists { + if old != f.pointer { + return f.reject() + } + continue + } + paths[f.pointer.Path] = f.pointer + file, err := f.file("lock", f.pointer.LockIdentity, 0) + if err != nil { + return err + } + if err := sessionLock(ctx, file); err != nil { + file.Close() + return err + } + locks = append(locks, file) + // A path replacement while waiting cannot install a different lock. + if err := f.validate(); err != nil { + return err + } + check, err := f.file("lock", f.pointer.LockIdentity, 0) + if err != nil { + return err + } + check.Close() + } + if err := ctx.Err(); err != nil { + return err + } + return work() +} + +func sessionCreateFile(path, value string) error { + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) + if err != nil { + return ErrSessionProtectionUnavailable + } + _, writeErr := io.WriteString(file, value) + syncErr := file.Sync() + closeErr := file.Close() + if writeErr != nil || syncErr != nil || closeErr != nil { + return ErrSessionProtectionUnavailable + } + return nil +} + +func sessionSync(path string) error { + file, err := os.Open(path) + if err != nil { + return ErrSessionProtectionUnavailable + } + syncErr := file.Sync() + closeErr := file.Close() + if syncErr != nil || closeErr != nil { + return ErrSessionProtectionUnavailable + } + return nil +} + +func sessionRandom(size int) (string, error) { + value := make([]byte, size) + if _, err := rand.Read(value); err != nil { + return "", ErrSessionProtectionUnavailable + } + return hex.EncodeToString(value), nil +} + +func sessionHex(value string, size int) bool { + if len(value) != size*2 { + return false + } + _, err := hex.DecodeString(value) + return err == nil +} diff --git a/sdk/go/session_protection_http_test.go b/sdk/go/session_protection_http_test.go new file mode 100644 index 0000000000..b31ab2ef2f --- /dev/null +++ b/sdk/go/session_protection_http_test.go @@ -0,0 +1,626 @@ +package loom + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" +) + +// These tests own real loopback servers. They require hosted native execution. +type protectionRequest struct { + method, path string + header http.Header + body map[string]any +} + +type protectionWire struct { + server *httptest.Server + requests chan protectionRequest + count atomic.Int64 +} + +func newProtectionWire(t *testing.T, respond http.HandlerFunc) *protectionWire { + t.Helper() + wire := &protectionWire{requests: make(chan protectionRequest, 32)} + wire.server = httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + wire.count.Add(1) + raw, err := io.ReadAll(io.LimitReader(r.Body, maxProtectedBody+1)) + r.Body.Close() + if err != nil || len(raw) > maxProtectedBody { + t.Error("fixture request body exceeded its bound or could not be read") + http.Error(w, "invalid fixture request", http.StatusBadRequest) + return + } + var body map[string]any + if err := json.Unmarshal(raw, &body); err != nil { + t.Error("fixture request was not a JSON object") + http.Error(w, "invalid fixture request", http.StatusBadRequest) + return + } + select { + case wire.requests <- protectionRequest{r.Method, r.URL.Path, r.Header.Clone(), body}: + case <-r.Context().Done(): + return + case <-time.After(2*time.Second): + t.Error("fixture request queue did not drain") + return + } + respond(w, r) + })) + wire.server.Config.ReadHeaderTimeout = 2*time.Second + wire.server.Config.ReadTimeout = 3*time.Second + wire.server.Config.WriteTimeout = 4*time.Second + wire.server.Config.IdleTimeout = time.Second + wire.server.Start() + t.Cleanup(func() { + wire.server.CloseClientConnections() + wire.server.Close() + }) + return wire +} + +func protectionJSON(status int, body string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, body) + } +} + +func protectionReadArguments() map[string]any { + return map[string]any{"name":"documents", "resource_id":"resource:example"} +} + +func protectionMutationArguments() map[string]any { + return map[string]any{"memory_key":"publication", "value":"automatic"} +} + +func newGoProtection(t *testing.T) *SessionProtection { + t.Helper() + if !sessionPlatformSupported() { + t.Skip("durable session store requires a supported POSIX platform") + } + family, err := CreateSessionProtection(filepath.Join(t.TempDir(), "conversation")) + if err != nil { + t.Fatal(err) + } + return family +} + +func protectionClient(wire *protectionWire, family *SessionProtection, namespace, token string) *Client { + return New(Config{ + BaseURL: wire.server.URL, APIKey: token, Org: "example", Namespace: namespace, Agent: "assistant", + HTTPClient: &http.Client{Timeout: 3*time.Second}, SessionProtection: family, + }) +} + +func protectionContext(t *testing.T) context.Context { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + t.Cleanup(cancel) + return ctx +} + +func protectionNext(t *testing.T, wire *protectionWire) protectionRequest { + t.Helper() + select { + case request := <-wire.requests: + return request + case <-time.After(2*time.Second): + t.Fatal("HTTP fixture did not receive the expected request") + return protectionRequest{} + } +} + +func protectionAssertWire(t *testing.T, request protectionRequest, path, namespace, token string, body map[string]any, declared bool) { + t.Helper() + if request.method != http.MethodPost || request.path != path { + t.Fatalf("request method/path = %s %s", request.method, request.path) + } + want := map[string]any{"org": "example", "namespace": namespace, "agent": "assistant"} + for key, value := range body { + want[key] = value + } + if !reflect.DeepEqual(request.body, want) { + t.Fatalf("wire body = %#v; want %#v", request.body, want) + } + if request.header.Get("Authorization") != "Bearer "+token || request.header.Get("Content-Type") != "application/json" || request.header.Get("Accept") != "application/json" { + t.Fatal("wire credentials or JSON headers differ") + } + declarations := request.header.Values("X-Loom-Session-Protection") + if declared { + if !reflect.DeepEqual(declarations, []string{"v1"}) { + t.Fatalf("declarations = %#v", declarations) + } + } else if len(declarations) != 0 { + t.Fatalf("ordinary client declared protection: %#v", declarations) + } +} + +func protectionAssertLatched(t *testing.T, family *SessionProtection) { + t.Helper() + protected, err := family.Protected(protectionContext(t)) + if err != nil || !protected { + t.Fatalf("protected = %v, error = %v", protected, err) + } +} + +type protectionDecodeCallback struct { + run func() error + invoked bool + result error +} + +func (callback *protectionDecodeCallback) UnmarshalJSON([]byte) error { + callback.invoked = true + callback.result = callback.run() + return nil +} + +func TestGoProtectedSourceWireAndHumanInvocation(t *testing.T) { + family := newGoProtection(t) + wire := newProtectionWire(t, protectionJSON(200, `{"result":{"structuredContent":{"mirrored":true,"text":"synthetic private text"}}}`)) + client := protectionClient(wire, family, "documents", "source-token") + ctx := protectionContext(t) + args := map[string]any{"name": "documents", "resource_id": "resource:example"} + var out map[string]any + if err := client.Call(ctx, "knowledge.source.mcp_read", args, &out); err != nil { + t.Fatal(err) + } + protectionAssertWire(t, protectionNext(t, wire), "/v1/knowledge.source.mcp_read", "documents", "source-token", args, true) + protectionAssertLatched(t, family) + if args["namespace"] != nil { + t.Fatal("generic Call modified caller arguments") + } + resumed, err := OpenSessionProtection(family.Pointer()) + if err != nil { + t.Fatal(err) + } + protectionAssertLatched(t, resumed) + if _, err := client.Set(ctx, "publication", "automatic", nil); !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("typed automatic mutation = %v", err) + } + clone := *client + if err := clone.Call(ctx, "memory.set", protectionMutationArguments(), &out); !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("clone mutation = %v", err) + } + otherWire := newProtectionWire(t, protectionJSON(200, `{"ok":true}`)) + other := protectionClient(otherWire, resumed, "published", "replacement-token") + if err := other.Call(ctx, "memory.set", protectionMutationArguments(), &out); !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("new origin/token/namespace mutation = %v", err) + } + retained := CaptureSession(ctx, family).Context(ctx) + unbound := protectionClient(otherWire, nil, "published", "replacement-token") + if err := unbound.Call(retained, "memory.set", protectionMutationArguments(), &out); !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("retained capture mutation = %v", err) + } + if wire.count.Load() != 1 || otherWire.count.Load() != 0 { + t.Fatal("refused mutation reached a wire") + } + manual := map[string]any{"memory_key": "publication", "value": "human selected text"} + callback := &protectionDecodeCallback{run: func() error { return other.Call(retained,"memory.set",manual,&out) }} + if err := other.CallHuman(retained, "memory.set", manual, callback); err != nil { + t.Fatal(err) + } + if !callback.invoked || !errors.Is(callback.result,ErrAutomaticSessionProtected) { + t.Fatalf("decode callback inherited human authority: %v",callback.result) + } + protectionAssertWire(t, protectionNext(t, otherWire), "/v1/memory.set", "published", "replacement-token", manual, true) + if err := other.Call(retained, "custom.mutate", nil, &out); !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("human invocation escaped into retained work: %v", err) + } + if err := unbound.Call(ctx, "memory.set", manual, &out); err != nil { + t.Fatal(err) + } + protectionAssertWire(t, protectionNext(t, otherWire), "/v1/memory.set", "published", "replacement-token", manual, false) +} + +func TestGoProtectedErrorStatusObservedBeforeAPIError(t *testing.T) { + family := newGoProtection(t) + wire := newProtectionWire(t, protectionJSON(403, `{"error":{"code":"FORBIDDEN","message":"refused","data":{"content":[{"type":"text","text":"{\"mirrored\":true}"}]}}}`)) + client := protectionClient(wire, family, "documents", "synthetic-token") + ctx := protectionContext(t) + var out map[string]any + err := client.Call(ctx, "knowledge.source.mcp_read", map[string]any{"name":"documents", "resource_id":"resource:example"}, &out) + var apiError *Error + if !errors.As(err, &apiError) || apiError.Status != 403 { + t.Fatalf("HTTP status error = %v", err) + } + protectionAssertLatched(t, family) + if err := client.Call(ctx, "memory.delete", nil, &out); !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("post-error mutation = %v", err) + } + if wire.count.Load() != 1 { + t.Fatal("post-error mutation was sent") + } +} + +func TestGoGenericSourceControlsUseSharedWireBoundary(t *testing.T) { + family := newGoProtection(t) + wire := newProtectionWire(t,protectionJSON(200,`{"ok":true}`)) + client := protectionClient(wire,family,"documents","synthetic-token") + ctx := protectionContext(t) + for _, control := range []struct{op string; args map[string]any}{ + {"knowledge.connection.mcp_browse",map[string]any{"slot":"documents","mode":"resources"}}, + {"knowledge.source.mcp_list",map[string]any{}}, + {"knowledge.source.mcp_pause",map[string]any{"name":"documents"}}, + {"knowledge.source.mcp_resume",map[string]any{"name":"documents"}}, + {"knowledge.source.mcp_refresh",map[string]any{"name":"documents"}}, + {"knowledge.connection.mcp_disconnect",map[string]any{"slot":"documents"}}, + } { + var out map[string]any + if err := client.Call(ctx,control.op,control.args,&out); err!=nil { t.Fatal(err) } + protectionAssertWire(t,protectionNext(t,wire),"/v1/"+control.op,"documents","synthetic-token",control.args,true) + } + protected,err := family.Protected(ctx) + if err!=nil || protected { t.Fatalf("clean controls did not acknowledge observation: %v, %v",protected,err) } + if wire.count.Load()!=6 { t.Fatal("control dispatch count differs") } +} + +func TestGoBoundFamilyAndRetainedFamilyAreBothEnforced(t *testing.T) { + ctx := protectionContext(t) + a, b := newGoProtection(t), newGoProtection(t) + wire := newProtectionWire(t, protectionJSON(200, `{"mirrored":true}`)) + client := protectionClient(wire, b, "documents", "synthetic-token") + var out map[string]any + if err := client.Call(ctx, "knowledge.source.mcp_read", map[string]any{"name":"documents", "resource_id":"resource:example"}, &out); err != nil { + t.Fatal(err) + } + retainedA := CaptureSession(ctx, a).Context(ctx) + if err := client.Call(retainedA, "memory.set", protectionMutationArguments(), &out); !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("clean retained A masked protected bound B: %v", err) + } + if wire.count.Load() != 1 { + t.Fatal("bound-family refusal did not stop dispatch") + } + protectedA, err := a.Protected(ctx) + if err != nil || protectedA { + t.Fatalf("unused A = %v, %v", protectedA, err) + } + c, d := newGoProtection(t), newGoProtection(t) + contributing := CaptureSession(ctx, c).Context(ctx) + clientD := protectionClient(wire, d, "documents", "synthetic-token") + if err := clientD.Call(contributing, "knowledge.source.mcp_read", map[string]any{"name":"documents", "resource_id":"resource:example"}, &out); err != nil { + t.Fatal(err) + } + protectionAssertLatched(t, c) + protectionAssertLatched(t, d) + nested := CaptureSession(contributing, a).Context(contributing) + result := make(chan error, 1) + go func() { result <- protectionClient(wire, nil, "other", "new-token").Call(nested, "custom.write", nil, &out) }() + select { + case err := <-result: + if !errors.Is(err, ErrAutomaticSessionProtected) { + t.Fatalf("deferred contributor union = %v", err) + } + case <-time.After(3*time.Second): + t.Fatal("retained task did not finish") + } +} + +func TestGoLostReplacedAndCorruptProofRefusesEvenHuman(t *testing.T) { + cases := []struct{name string; damage func(*testing.T, SessionProtectionPointer)}{ + {"lost-state", func(t *testing.T, p SessionProtectionPointer) { if err := os.Remove(filepath.Join(p.Path,"state")); err != nil { t.Fatal(err) } }}, + {"lost-manifest", func(t *testing.T, p SessionProtectionPointer) { if err := os.Remove(filepath.Join(p.Path,"identity")); err != nil { t.Fatal(err) } }}, + {"lost-lock", func(t *testing.T, p SessionProtectionPointer) { if err := os.Remove(filepath.Join(p.Path,"lock")); err != nil { t.Fatal(err) } }}, + {"corrupt-state", func(t *testing.T, p SessionProtectionPointer) { if err := os.WriteFile(filepath.Join(p.Path,"state"),[]byte("?"),0600); err != nil { t.Fatal(err) } }}, + {"replaced-identical-state", func(t *testing.T, p SessionProtectionPointer) { + path := filepath.Join(p.Path,"state") + if err := os.Rename(path,path+".old"); err != nil { t.Fatal(err) } + if err := os.WriteFile(path,[]byte("0"),0600); err != nil { t.Fatal(err) } + }}, + {"replaced-directory", func(t *testing.T, p SessionProtectionPointer) { + if err := os.Rename(p.Path,p.Path+".old"); err != nil { t.Fatal(err) } + if err := os.Mkdir(p.Path,0700); err != nil { t.Fatal(err) } + for _, item := range []struct{name,value string}{{"identity",p.ID},{"state","0"},{"lock",""}} { + if err := os.WriteFile(filepath.Join(p.Path,item.name),[]byte(item.value),0600); err != nil { t.Fatal(err) } + } + }}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + family := newGoProtection(t) + wire := newProtectionWire(t, protectionJSON(200, `{"ok":true}`)) + pointer := family.Pointer() + test.damage(t, pointer) + if _, err := OpenSessionProtection(pointer); !errors.Is(err, ErrSessionProtectionUnavailable) { + t.Fatalf("restore damaged proof = %v", err) + } + client := protectionClient(wire, family, "other", "new-token") + var out map[string]any + if err := client.CallHuman(protectionContext(t), "memory.set", protectionMutationArguments(), &out); !errors.Is(err, ErrSessionProtectionUnavailable) { + t.Fatalf("human call with damaged proof = %v", err) + } + if wire.count.Load() != 0 { + t.Fatal("damaged authority declared readiness") + } + }) + } +} + +func TestGoMalformedOrUnboundedResponsesDoNotPublish(t *testing.T) { + cases := []struct{name, media, body string}{ + {"invalid-json", "application/json", `{"private":`}, + {"invalid-metadata", "application/json", `{"mirrored":"private"}`}, + {"duplicate-metadata", "application/json", `{"mirrored":true,"mirrored":false}`}, + {"nested-duplicate", "application/json", `{"error":{"data":{"mirrored":true,"mirrored":false}}}`}, + {"non-object", "application/json", `[]`}, + {"large", "application/json", `{"text":"`+strings.Repeat("x",maxProtectedBody)+`"}`}, + {"deep", "application/json", strings.Repeat(`{"result":`,66)+`{}`+strings.Repeat(`}`,66)}, + {"unsupported", "application/octet-stream", "synthetic private bytes"}, + } + for _, test := range cases { + t.Run(test.name, func(t *testing.T) { + family := newGoProtection(t) + wire := newProtectionWire(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type",test.media) + w.WriteHeader(500) + _, _ = io.WriteString(w,test.body) + }) + out := map[string]any{"unchanged":true} + err := protectionClient(wire,family,"documents","synthetic-token").Call(protectionContext(t),"knowledge.source.mcp_read",protectionReadArguments(),&out) + if !errors.Is(err,ErrSessionProtectionUnavailable) || !reflect.DeepEqual(out,map[string]any{"unchanged":true}) { + t.Fatalf("response was published or failed open: %v",err) + } + protectionAssertLatched(t,family) + }) + } +} + +func protectionWait(t *testing.T, done <-chan struct{}, what string) { + t.Helper() + select { + case <-done: + case <-time.After(3*time.Second): + t.Fatalf("%s did not finish",what) + } +} + +func TestGoPendingChunkCancellationClosesAndRetainsProof(t *testing.T) { + family := newGoProtection(t) + opened, peerClosed := make(chan struct{}), make(chan struct{}) + wire := newProtectionWire(t,func(w http.ResponseWriter,r *http.Request) { + defer close(peerClosed) + w.Header().Set("Content-Type","application/json") + _, _ = io.WriteString(w,`{"result":`) + w.(http.Flusher).Flush() + close(opened) + select { + case <-r.Context().Done(): + case <-time.After(2*time.Second): + t.Error("cancelled response retained its peer connection") + } + }) + client := protectionClient(wire,family,"documents","synthetic-token") + ctx,cancel := context.WithCancel(protectionContext(t)) + defer cancel() + finished := make(chan error,1) + out := map[string]any{"unchanged":true} + go func() { finished <- client.Call(ctx,"knowledge.source.mcp_read",protectionReadArguments(),&out) }() + protectionWait(t,opened,"chunked response opening") + var next map[string]any + if err := client.Call(protectionContext(t),"memory.set",protectionMutationArguments(),&next); !errors.Is(err,ErrAutomaticSessionProtected) { + t.Fatalf("in-flight pending proof allowed a send: %v",err) + } + if wire.count.Load()!=1 { + t.Fatal("pending request did not refuse another send") + } + cancel() + select { + case err := <-finished: + if err==nil || !reflect.DeepEqual(out,map[string]any{"unchanged":true}) { + t.Fatalf("cancelled response published: %v",err) + } + case <-time.After(3*time.Second): + t.Fatal("cancelled call did not join response cleanup") + } + protectionWait(t,peerClosed,"cancelled peer") + protectionAssertLatched(t,family) + restored,err := OpenSessionProtection(family.Pointer()) + if err!=nil { t.Fatal(err) } + protectionAssertLatched(t,restored) +} + +func TestGoStreamRefusalAndInterruptedJSONCloseTheWire(t *testing.T) { + for _, stream := range []bool{true,false} { + t.Run(fmt.Sprint("stream=",stream),func(t *testing.T) { + family := newGoProtection(t) + peerClosed := make(chan struct{}) + wire := newProtectionWire(t,func(w http.ResponseWriter,r *http.Request) { + defer close(peerClosed) + if stream { + w.Header().Set("Content-Type","text/event-stream") + _, _ = io.WriteString(w,"data: {\"mirrored\":true}\n\n") + w.(http.Flusher).Flush() + select { + case <-r.Context().Done(): + case <-time.After(2*time.Second): t.Error("stream refusal did not close its peer") + } + } else { + w.Header().Set("Content-Type","application/json") + w.Header().Set("Content-Length","200") + _, _ = io.WriteString(w,`{"mirrored":`) + w.(http.Flusher).Flush() + } + }) + var out map[string]any + err := protectionClient(wire,family,"documents","synthetic-token").Call(protectionContext(t),"knowledge.source.mcp_read",protectionReadArguments(),&out) + if !errors.Is(err,ErrSessionProtectionUnavailable) || out!=nil { + t.Fatalf("incomplete/stream response = %#v, %v",out,err) + } + protectionWait(t,peerClosed,"stream or interrupted peer") + protectionAssertLatched(t,family) + }) + } +} + +func TestGoCallerRetryAfterPacingRechecksFamily(t *testing.T) { + family := newGoProtection(t) + var attempts atomic.Int64 + wire := newProtectionWire(t,func(w http.ResponseWriter,r *http.Request) { + if attempts.Add(1)==1 { + w.Header().Set("Retry-After","1") + protectionJSON(429,`{"error":{"code":"RATE_LIMITED","message":"later"}}`)(w,r) + } else { + protectionJSON(200,`{"mirrored":true}`)(w,r) + } + }) + client := protectionClient(wire,family,"documents","synthetic-token") + ctx := protectionContext(t) + var out map[string]any + err := client.Call(ctx,"memory.set",protectionMutationArguments(),&out) + var apiError *Error + if !errors.As(err,&apiError) || apiError.Status!=429 || apiError.RetryAfter!=time.Second { + t.Fatalf("pacing response = %v",err) + } + if wire.count.Load()!=1 { t.Fatal("Go SDK retried without its caller") } + // The caller's pacing wait admits an independently completed source read. + // The next invocation must recheck instead of reusing the first admission. + if err := client.Call(ctx,"knowledge.source.mcp_read",map[string]any{"name":"documents","resource_id":"resource:example"},&out); err!=nil { t.Fatal(err) } + if err := client.Call(ctx,"memory.set",protectionMutationArguments(),&out); !errors.Is(err,ErrAutomaticSessionProtected) { + t.Fatalf("retry after contributing read = %v",err) + } + if wire.count.Load()!=2 { t.Fatal("retry bypassed the family barrier") } +} + +func TestGoChunkedResponseObservesBeforeTypedConversion(t *testing.T) { + family := newGoProtection(t) + opened, release := make(chan struct{}), make(chan struct{}) + wire := newProtectionWire(t,func(w http.ResponseWriter,r *http.Request) { + w.Header().Set("Content-Type","application/json") + _, _ = io.WriteString(w,`{"result":`) + w.(http.Flusher).Flush() + close(opened) + select { + case <-release: + _, _ = io.WriteString(w,`{"mirrored":true}}`) + case <-r.Context().Done(): + case <-time.After(2*time.Second): t.Error("chunk fixture release did not arrive") + } + }) + client := protectionClient(wire,family,"documents","synthetic-token") + finished := make(chan error,1) + var typed int + ctx := protectionContext(t) + go func() { finished <- client.Call(ctx,"knowledge.source.mcp_read",protectionReadArguments(),&typed) }() + protectionWait(t,opened,"first response chunk") + select { + case err := <-finished: t.Fatalf("partial response escaped observation: %v",err) + default: + } + close(release) + select { + case err := <-finished: + var apiError *Error + if !errors.As(err,&apiError) || apiError.Code!=CodeInvalidResponse { + t.Fatalf("typed conversion failure = %v",err) + } + case <-time.After(3*time.Second): t.Fatal("chunked response did not join") + } + protectionAssertLatched(t,family) +} + +func TestGoProofLostDuringResponseRefusesPublication(t *testing.T) { + family := newGoProtection(t) + opened, release := make(chan struct{}), make(chan struct{}) + wire := newProtectionWire(t,func(w http.ResponseWriter,r *http.Request) { + w.Header().Set("Content-Type","application/json") + _, _ = io.WriteString(w,`{"result":`) + w.(http.Flusher).Flush() + close(opened) + select { + case <-release: _, _ = io.WriteString(w,`{"mirrored":true}}`) + case <-r.Context().Done(): + case <-time.After(2*time.Second): t.Error("proof-loss fixture release did not arrive") + } + }) + client := protectionClient(wire,family,"documents","synthetic-token") + finished := make(chan error,1) + out := map[string]any{"unchanged":true} + ctx := protectionContext(t) + go func() { finished <- client.Call(ctx,"knowledge.source.mcp_read",protectionReadArguments(),&out) }() + protectionWait(t,opened,"proof-loss response") + if err := os.Remove(filepath.Join(family.Pointer().Path,"state")); err!=nil { t.Fatal(err) } + close(release) + select { + case err := <-finished: + if !errors.Is(err,ErrSessionProtectionUnavailable) || !reflect.DeepEqual(out,map[string]any{"unchanged":true}) { + t.Fatalf("lost proof published a response: %v",err) + } + case <-time.After(3*time.Second): t.Fatal("lost-proof call did not join") + } + if _,err := OpenSessionProtection(family.Pointer()); !errors.Is(err,ErrSessionProtectionUnavailable) { + t.Fatalf("lost-proof restore = %v",err) + } + if wire.count.Load()!=1 { t.Fatal("unexpected proof-loss request count") } +} + +type protectionCustomEncoder struct { calls *atomic.Int64 } + +func (encoder protectionCustomEncoder) MarshalJSON() ([]byte,error) { + encoder.calls.Add(1) + return []byte(`{"encoded":true}`),nil +} + +func TestGoProtectedRequestBoundBeforeCustomEncodingOrSend(t *testing.T) { + family := newGoProtection(t) + wire := newProtectionWire(t,protectionJSON(200,`{"ok":true}`)) + client := protectionClient(wire,family,"documents","synthetic-token") + ctx := protectionContext(t) + var out map[string]any + var encodes atomic.Int64 + for _, args := range []map[string]any{ + {"value":strings.Repeat("x",maxProtectedBody)}, + {"value":protectionCustomEncoder{calls:&encodes}}, + } { + if err := client.Call(ctx,"memory.set",args,&out); !errors.Is(err,ErrSessionProtectionUnavailable) { + t.Fatalf("unbounded/custom request = %v",err) + } + } + if encodes.Load()!=0 || wire.count.Load()!=0 { t.Fatal("bounded admission invoked a custom encoder or sent bytes") } + ordinary := protectionClient(wire,nil,"documents","synthetic-token") + if err := ordinary.Call(ctx,"memory.set",map[string]any{"value":protectionCustomEncoder{calls:&encodes}},&out); err!=nil { t.Fatal(err) } + if encodes.Load()!=1 { t.Fatal("ordinary custom encoder behavior changed") } + request := protectionNext(t,wire) + if len(request.header.Values("X-Loom-Session-Protection"))!=0 { t.Fatal("ordinary custom encoder declared protection") } +} + +func TestGoProtectionResumeInAnotherProcess(t *testing.T) { + const probe = "LOOM_GO_PROTECTION_RESUME_PROBE" + if encoded := os.Getenv(probe); encoded!="" { + var pointer SessionProtectionPointer + if err := json.Unmarshal([]byte(encoded),&pointer); err!=nil { t.Fatal(err) } + family,err := OpenSessionProtection(pointer) + if err!=nil { t.Fatal(err) } + client := New(Config{BaseURL:os.Getenv("LOOM_GO_PROTECTION_RESUME_URL"),SessionProtection:family,Namespace:"changed",APIKey:"changed"}) + var out map[string]any + ctx,cancel := context.WithTimeout(context.Background(),3*time.Second) + defer cancel() + if err := client.Call(ctx,"memory.set",protectionMutationArguments(),&out); !errors.Is(err,ErrAutomaticSessionProtected) { t.Fatalf("resumed process mutation = %v",err) } + return + } + family := newGoProtection(t) + wire := newProtectionWire(t,protectionJSON(200,`{"mirrored":true}`)) + var out map[string]any + if err := protectionClient(wire,family,"documents","synthetic-token").Call(protectionContext(t),"knowledge.source.mcp_read",protectionReadArguments(),&out); err!=nil { t.Fatal(err) } + encoded,err := json.Marshal(family.Pointer()) + if err!=nil { t.Fatal(err) } + ctx,cancel := context.WithTimeout(context.Background(),5*time.Second) + defer cancel() + child := exec.CommandContext(ctx,os.Args[0],"-test.run=^TestGoProtectionResumeInAnotherProcess$") + child.Env = append(os.Environ(),probe+"="+string(encoded),"LOOM_GO_PROTECTION_RESUME_URL="+wire.server.URL) + if output,err := child.CombinedOutput(); err!=nil { t.Fatalf("resume probe: %v\n%s",err,output) } + if wire.count.Load()!=1 { t.Fatal("resumed process sent an automatic mutation") } +} diff --git a/sdk/go/session_request.go b/sdk/go/session_request.go new file mode 100644 index 0000000000..bc54cb2548 --- /dev/null +++ b/sdk/go/session_request.go @@ -0,0 +1,83 @@ +package loom + +import ( + "encoding" + "encoding/json" + "reflect" +) + +// Protected requests accept bounded JSON data, not custom encoders with +// unbounded work or side effects. Unbound serialization keeps its existing API. +func validateProtectedInput(input any) error { + nodes, bytes := 10000, maxProtectedBody + return protectedInputValue(reflect.ValueOf(input), 0, &nodes, &bytes) +} + +func protectedInputValue(value reflect.Value, depth int, nodes, bytes *int) error { + *nodes -= 1 + *bytes -= 8 + if depth > 64 || *nodes < 0 || *bytes < 0 { + return ErrSessionProtectionUnavailable + } + if !value.IsValid() { + return nil + } + for _, encoder := range []reflect.Type{reflect.TypeOf((*json.Marshaler)(nil)).Elem(), reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()} { + if value.Type().Implements(encoder) || reflect.PointerTo(value.Type()).Implements(encoder) { + return ErrSessionProtectionUnavailable + } + } + switch value.Kind() { + case reflect.Interface, reflect.Pointer: + if !value.IsNil() { + return protectedInputValue(value.Elem(), depth+1, nodes, bytes) + } + case reflect.Map: + if value.Type().Key().Kind() != reflect.String || value.Len() > *nodes { + return ErrSessionProtectionUnavailable + } + iterator := value.MapRange() + for iterator.Next() { + *bytes -= 6*len(iterator.Key().String()) + 4 + if err := protectedInputValue(iterator.Value(), depth+1, nodes, bytes); err != nil { + return err + } + } + case reflect.Struct: + for i := 0; i < value.NumField(); i++ { + field := value.Type().Field(i) + if (field.PkgPath != "" && !field.Anonymous) || field.Tag.Get("json") == "-" { + continue + } + *bytes -= 6*(len(field.Name)+len(field.Tag.Get("json"))) + 4 + if err := protectedInputValue(value.Field(i), depth+1, nodes, bytes); err != nil { + return err + } + } + case reflect.Slice, reflect.Array: + if value.Len() > *nodes { + return ErrSessionProtectionUnavailable + } + for i := 0; i < value.Len(); i++ { + if err := protectedInputValue(value.Index(i), depth+1, nodes, bytes); err != nil { + return err + } + } + case reflect.String: + // Six bytes cover the longest JSON escape of one input byte. + if value.Len() > *bytes/6 { + return ErrSessionProtectionUnavailable + } + *bytes -= 6*value.Len() + case reflect.Bool, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, + reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, + reflect.Float32, reflect.Float64: + *bytes -= 32 + default: + return ErrSessionProtectionUnavailable + } + if *bytes < 0 { + return ErrSessionProtectionUnavailable + } + return nil +} diff --git a/sdk/go/session_store_unix.go b/sdk/go/session_store_unix.go new file mode 100644 index 0000000000..7075bc9d82 --- /dev/null +++ b/sdk/go/session_store_unix.go @@ -0,0 +1,47 @@ +//go:build linux || darwin || freebsd || netbsd || openbsd || dragonfly + +package loom + +import ( + "context" + "fmt" + "os" + "syscall" + "time" +) + +func sessionPlatformSupported() bool { return true } + +func sessionFileIdentity(info os.FileInfo) (string, error) { + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return "", ErrSessionProtectionUnavailable + } + return fmt.Sprintf("%d:%d", stat.Dev, stat.Ino), nil +} + +func sessionPrivate(info os.FileInfo) bool { + stat, ok := info.Sys().(*syscall.Stat_t) + return ok && stat.Uid == uint32(os.Geteuid()) && info.Mode()&os.ModeSymlink == 0 && info.Mode().Perm()&0077 == 0 +} + +func sessionLock(ctx context.Context, file *os.File) error { + ticker := time.NewTicker(10*time.Millisecond) + defer ticker.Stop() + for { + err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX|syscall.LOCK_NB) + if err == nil { + return nil + } + if err != syscall.EWOULDBLOCK && err != syscall.EAGAIN && err != syscall.EINTR { + return ErrSessionProtectionUnavailable + } + select { + case <-ctx.Done(): + return ErrSessionProtectionUnavailable + case <-ticker.C: + } + } +} + +func sessionUnlock(file *os.File) { _ = syscall.Flock(int(file.Fd()), syscall.LOCK_UN) } diff --git a/sdk/go/session_store_unsupported.go b/sdk/go/session_store_unsupported.go new file mode 100644 index 0000000000..f7bfbd01e9 --- /dev/null +++ b/sdk/go/session_store_unsupported.go @@ -0,0 +1,14 @@ +//go:build !linux && !darwin && !freebsd && !netbsd && !openbsd && !dragonfly + +package loom + +import ( + "context" + "os" +) + +func sessionPlatformSupported() bool { return false } +func sessionFileIdentity(os.FileInfo) (string, error) { return "", ErrSessionProtectionUnavailable } +func sessionPrivate(os.FileInfo) bool { return false } +func sessionLock(context.Context, *os.File) error { return ErrSessionProtectionUnavailable } +func sessionUnlock(*os.File) {} From 3d9ac241d5de10e92666ca96252f50f184476a6f Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 07:03:02 +0000 Subject: [PATCH 29/30] Check source SDK contracts in hosted qualification Exercise native protected-client fixtures on declared toolchains and export actual generator candidates without replacing failed checks. Remove obsolete consent-link tests and keep explicit retired-command refusal coverage. Signed-off-by: zlareb1 --- .../workflows/mcp-source-qualification.yml | 206 ++++++++++++++++ docs/reference/cli.md | 1 - docs/reference/operations.md | 2 +- docs/reference/operations/knowledge.md | 2 +- sdk/python/loom/ops.py | 4 +- server/knowledge/api/models_sources.py | 2 +- server/knowledge/api/ops_sources.py | 3 +- tests/unit/test_sdk_cli_connect.py | 225 ++---------------- 8 files changed, 228 insertions(+), 217 deletions(-) diff --git a/.github/workflows/mcp-source-qualification.yml b/.github/workflows/mcp-source-qualification.yml index db04f028ad..a842584c57 100644 --- a/.github/workflows/mcp-source-qualification.yml +++ b/.github/workflows/mcp-source-qualification.yml @@ -23,6 +23,11 @@ on: - server/main.py - sdk/python/** - sdk/ruby/** + - sdk/typescript/** + - sdk/rust/** + - sdk/go/** + - sdk/java/** + - sdk/dotnet/** - schemas/** - dev/ci_start_clickhouse.sh - dev/ci_start_postgres.sh @@ -44,6 +49,207 @@ env: UV_VERSION: "0.12.19" jobs: + source-contracts: + name: MCP generated SDK contracts + runs-on: ubuntu-latest + timeout-minutes: 15 + env: + LOOM_ENV_FILE: "" + LOOM_LLM_PROVIDER: fake + LOOM_EMBEDDING_MODEL: fake-ngram-1024 + steps: + - name: Validate a dispatched commit + if: github.event_name == 'workflow_dispatch' + env: + REQUESTED_SHA: ${{ inputs.sha }} + run: '[[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout-cone-mode: false + sparse-checkout: | + /* + !/*/ + /server/ + /scripts/ + /sdk/ + /extractor/ + /schemas/ + /tests/ + !/tests/unit/test_term_leg.py + !/tests/integration/test_term_leg.py + !/tests/unit/test_session_proof_request_correlation.py + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + id: python + with: + python-version: ${{ env.PYTHON_VERSION }} + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: ${{ env.UV_VERSION }} + enable-cache: false + - name: Install the locked generator dependencies + id: install + run: | + uv sync --locked --python "${{ steps.python.outputs.python-path }}" --extra dev --extra code + echo "$PWD/.venv/bin" >> "$GITHUB_PATH" + - name: Check generated SDK contracts + id: contracts + run: | + python -m scripts.codegen.sdk_py_gen --check + python -m scripts.codegen.sdk_py_client_gen --check + python -m scripts.codegen.sdk_py_admin_gen --check + python -m scripts.codegen.sdk_rb_gen --check + python -m scripts.codegen.sdk_ts_gen --check + - name: Render actual candidates after a contract failure + if: failure() && steps.contracts.outcome == 'failure' + run: | + python -m scripts.codegen.sdk_py_gen + python -m scripts.codegen.sdk_py_client_gen + python -m scripts.codegen.sdk_py_admin_gen + python -m scripts.codegen.sdk_rb_gen + python -m scripts.codegen.sdk_ts_gen + - name: Export only generated SDK candidates + if: failure() && steps.contracts.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mcp-generated-sdk-candidates + path: | + sdk/python/loom/ops.py + sdk/python/loom/client.py + sdk/python/loom/admin_routes.py + sdk/ruby/lib/clickhouse/loom/generated/ + sdk/typescript/src/generated/ops.ts + if-no-files-found: error + retention-days: 7 + + - name: Install the built SDK for the public API contract + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + id: sdk-install + run: | + uv build --wheel sdk/python --out-dir "$RUNNER_TEMP/mcp-contract-sdk" + uv pip install --no-deps "$RUNNER_TEMP"/mcp-contract-sdk/*.whl + - name: Check the maintained SDK public API snapshot + if: ${{ !cancelled() && steps.sdk-install.outcome == 'success' }} + id: sdk-snapshot + run: python -m pytest -q tests/unit/test_sdk_surface_contract.py::test_public_api_matches_the_snapshot + - name: Render the actual SDK public API candidate + if: failure() && steps.sdk-snapshot.outcome == 'failure' + env: + LOOM_UPDATE_SNAPSHOT: "1" + run: python -m pytest -q tests/unit/test_sdk_surface_contract.py::test_public_api_matches_the_snapshot + - name: Export only the SDK public API candidate + if: failure() && steps.sdk-snapshot.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mcp-sdk-public-api-candidate + path: tests/unit/snapshots/sdk_public_api.json + if-no-files-found: error + retention-days: 7 + + go-client: + name: Go protected source client (${{ matrix.go }}) + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + go: ["1.22.x", "1.27.4"] + defaults: + run: + working-directory: sdk/go + steps: + - name: Validate a dispatched commit + if: github.event_name == 'workflow_dispatch' + working-directory: ${{ github.workspace }} + env: + REQUESTED_SHA: ${{ inputs.sha }} + run: '[[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout: /sdk/go/ + sparse-checkout-cone-mode: false + - uses: actions/setup-go@d8cbb8045d7f43706b9177cceb36c1f91a6644d5 # v7.1.0 + with: + go-version: ${{ matrix.go }} + cache: false + - name: Check Go formatting + id: go-format + run: test -z "$(gofmt -l *.go)" + - name: Render the actual Go format candidate + if: failure() && steps.go-format.outcome == 'failure' + run: | + gofmt -w *.go + git diff -- '*.go' > "$RUNNER_TEMP/go-format.patch" + - name: Export only the Go format candidate + if: failure() && steps.go-format.outcome == 'failure' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: mcp-go-format-${{ matrix.go }} + path: ${{ runner.temp }}/go-format.patch + if-no-files-found: error + retention-days: 7 + - name: Build, vet and exercise owned HTTP protection fixtures + run: | + go build ./... + go vet ./... + go test -race -count=1 -timeout=180s ./... + + java-client: + name: Java protected source client (17) + runs-on: ubuntu-latest + timeout-minutes: 15 + defaults: + run: + working-directory: sdk/java + steps: + - name: Validate a dispatched commit + if: github.event_name == 'workflow_dispatch' + working-directory: ${{ github.workspace }} + env: + REQUESTED_SHA: ${{ inputs.sha }} + run: '[[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout: /sdk/java/ + sparse-checkout-cone-mode: false + - uses: actions/setup-java@d1374f8ac74474200d16ef8ecee22c7ae7a51880 # v6.3.0 + with: + distribution: temurin + java-version: "17" + - name: Compile and exercise owned HTTP protection fixtures + run: mvn --batch-mode --no-transfer-progress -DfailIfNoTests=true verify + + dotnet-client: + name: .NET protected source client (8) + runs-on: ubuntu-latest + timeout-minutes: 15 + defaults: + run: + working-directory: sdk/dotnet + steps: + - name: Validate a dispatched commit + if: github.event_name == 'workflow_dispatch' + working-directory: ${{ github.workspace }} + env: + REQUESTED_SHA: ${{ inputs.sha }} + run: '[[ "$REQUESTED_SHA" =~ ^[0-9a-f]{40}$ ]]' + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ inputs.sha || github.event.pull_request.head.sha || github.sha }} + persist-credentials: false + sparse-checkout: /sdk/dotnet/ + sparse-checkout-cone-mode: false + - uses: actions/setup-dotnet@0f4a354dd5547a28c70b7853dbd95d5b67886e73 # v6.1.0 + with: + dotnet-version: "8.0.x" + - name: Compile and exercise owned HTTP protection fixtures + run: dotnet test ClickHouse.Loom.sln --configuration Release + ruby-client: name: Ruby protected source client runs-on: ubuntu-latest diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 268b686bf1..928aa4672b 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -393,7 +393,6 @@ python scripts/codegen/docs_reference.py | `loom whoami` | Show who the stored session signs you in as. | | | `loom call` | Call any operation or API route with the stored session (`loom call --help`). | | | `loom token` | Make, list and revoke your own tokens for CI and agents (`loom token --help`). | | -| `loom connect` | Print the dashboard link to connect your own Google, Notion or Linear account. | | diff --git a/docs/reference/operations.md b/docs/reference/operations.md index a4f23674f0..f24332321a 100644 --- a/docs/reference/operations.md +++ b/docs/reference/operations.md @@ -455,7 +455,7 @@ Fields for every `knowledge` op: [operations/knowledge.md](operations/knowledge. | [`knowledge.source.mcp_resume`](operations/knowledge.md#knowledgesourcemcp_resume) | | writer | write | no | yes | | [`knowledge.source.mcp_update`](operations/knowledge.md#knowledgesourcemcp_update) | | writer | write | no | yes | | [`knowledge.source.remove`](operations/knowledge.md#knowledgesourceremove) | Retire a registered document source: its registry row goes inactive and its credential is cleared. | writer | write | no | yes | -| [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate) | Replace a registered document source's credential. | admin | write | no | yes | +| [`knowledge.source.rotate`](operations/knowledge.md#knowledgesourcerotate) | Replace a shared recording source's credential. | admin | write | no | yes | | [`knowledge.source.sync_now`](operations/knowledge.md#knowledgesourcesync_now) | Record a request to sync one document source in its sync state: the sync worker starts its next pass with it. | writer | idempotent | no | yes | | [`knowledge.synthesize`](operations/knowledge.md#knowledgesynthesize) | Complete a task over WHOLE documents, not a search slice: every active chunk of the named documents is read in order, in windows that respect section boundaries, each window is noted once, and the… | viewer | idempotent | no | yes | | [`knowledge.update_metadata`](operations/knowledge.md#knowledgeupdate_metadata) | Edit doc-level metadata (title, description, tags). | writer | idempotent | no | yes | diff --git a/docs/reference/operations/knowledge.md b/docs/reference/operations/knowledge.md index 7fbc20e3d4..babdfba3bc 100644 --- a/docs/reference/operations/knowledge.md +++ b/docs/reference/operations/knowledge.md @@ -1045,7 +1045,7 @@ Retire a registered document source: its registry row goes inactive and its cred ## `knowledge.source.rotate` -Replace a registered document source's credential. +Replace a shared recording source's credential. `POST /v1/knowledge.source.rotate` · MCP `loom_knowledge_source_rotate` · role `admin` · write · audited · not listed under the MCP `all` toolset diff --git a/sdk/python/loom/ops.py b/sdk/python/loom/ops.py index 06e189a406..38a1932455 100644 --- a/sdk/python/loom/ops.py +++ b/sdk/python/loom/ops.py @@ -12433,7 +12433,7 @@ class KnowledgeSourceRemoveOutput(TypedDict, total=False): class KnowledgeSourceRotateInput(TypedDict, total=False): - "Replace a registered document source's credential. A namespace admin may;" + "Replace a shared recording source's credential. A namespace admin may;" org: Required[str] namespace: Required[str] @@ -12442,7 +12442,7 @@ class KnowledgeSourceRotateInput(TypedDict, total=False): class KnowledgeSourceRotateBody(TypedDict, total=False): - "Replace a registered document source's credential. A namespace admin may;" + "Replace a shared recording source's credential. A namespace admin may;" org: NotRequired[str] namespace: NotRequired[str] diff --git a/server/knowledge/api/models_sources.py b/server/knowledge/api/models_sources.py index 5e778ef670..793328f86b 100644 --- a/server/knowledge/api/models_sources.py +++ b/server/knowledge/api/models_sources.py @@ -232,7 +232,7 @@ class KnowledgeSourceCheckOutput(BaseModel): class KnowledgeSourceRotateInput(PrivateSourceInput): - """Replace a registered document source's credential. A namespace admin may; + """Replace a shared recording source's credential. A namespace admin may; the new credential is probed first, and a probe that fails stores nothing.""" org: str = Field(..., description="The org.") diff --git a/server/knowledge/api/ops_sources.py b/server/knowledge/api/ops_sources.py index 04f13cee3b..161b3c18c3 100644 --- a/server/knowledge/api/ops_sources.py +++ b/server/knowledge/api/ops_sources.py @@ -63,8 +63,7 @@ audit=True, audit_subject=source_add_audit_subject, ) -# No store request and nothing written: a reader may preview what links name. -# The owner may probe their connection; other callers need namespace administration. +# Shared recording probes require namespace administration inside the handler. knowledge_source_check = Operation( name="knowledge.source.check", maturity="experimental", diff --git a/tests/unit/test_sdk_cli_connect.py b/tests/unit/test_sdk_cli_connect.py index 9d6286f38b..93d4a35a83 100644 --- a/tests/unit/test_sdk_cli_connect.py +++ b/tests/unit/test_sdk_cli_connect.py @@ -1,224 +1,31 @@ -"""Provider consent stays in the browser; the CLI reads only the own-account link.""" +"""Retired native account commands cannot send requests or launch consent.""" from __future__ import annotations -import argparse -import asyncio -import json -from pathlib import Path from typing import Any import httpx import pytest from loom import cli -from loom.errors import AuthInsufficient -class _Wire: - def __init__(self) -> None: - self.status = 200 - self.body: Any = {"connections": []} - self.seen: list[httpx.Request] = [] - self.clients: list[httpx.AsyncClient] = [] - - def __call__(self, request: httpx.Request) -> httpx.Response: - assert request.method == "POST" and request.url.path == "/v1/connection.list" - self.seen.append(request) - return httpx.Response(self.status, json=self.body) - - -@pytest.fixture -def wire(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> _Wire: - for name in ("LOOM_PROFILE", "LOOM_BASE_URL", "LOOM_MENTOR_BRIEF", "LOOM_AUTO_RUN"): - monkeypatch.delenv(name, raising=False) - monkeypatch.setenv("LOOM_API_KEY", "private-cli-bearer") - monkeypatch.setattr("loom.credentials.CREDENTIALS_FILE", tmp_path / "credentials") - monkeypatch.setattr("loom.transport.TOKEN_FILE", tmp_path / "token") - monkeypatch.setattr("loom.credentials.signed_in_server", lambda *_a: "https://loom.test") - fake = _Wire() - real_client = httpx.AsyncClient - - def client(*args: Any, **kwargs: Any) -> httpx.AsyncClient: - kwargs["transport"] = httpx.MockTransport(fake) - kwargs.pop("http2", None) - made = real_client(*args, **kwargs) - fake.clients.append(made) - return made - - monkeypatch.setattr("loom.transport.httpx.AsyncClient", client) - - def no_browser(*_args: Any, **_kwargs: Any) -> bool: - raise AssertionError("the user starts consent in their browser") - - monkeypatch.setattr("webbrowser.open", no_browser) - return fake - - -@pytest.mark.parametrize( - "provider,kind", [("google", "gdrive"), ("notion", "notion"), ("linear", "linear")] -) -@pytest.mark.parametrize("connected", [False, True]) -def test_connect_reads_the_own_provider_link_and_closes_client( - wire, capsys, provider, kind, connected +@pytest.mark.parametrize("provider", ["google", "gdrive", "notion", "linear"]) +def test_native_connect_is_rejected_before_any_http_or_browser( + monkeypatch: pytest.MonkeyPatch, provider: str, capsys: pytest.CaptureFixture[str] ) -> None: - url = f"https://dashboard.test/settings/connected-accounts?kind={kind}" - wire.body = { - "connections": [ - {"kind": "other", "connect_url": "https://unrelated.test"}, - { - "kind": kind, - "connected": connected, - "connect_url": url, - "account_email": "private-account@example.test", - "scopes": ["private-scope"], - "credential": "private-response-secret", - }, - ] - } - assert cli.main(["connect", provider]) == 0 - captured = capsys.readouterr() - assert url in captured.out and "choose Connect or Reconnect" in captured.out - assert "connected" not in captured.out.replace("connected-accounts", "") - assert captured.err == "" - for private in ( - "private-cli-bearer", - "private-account", - "private-scope", - "private-response-secret", - ): - assert private not in captured.out - assert len(wire.seen) == 1 - request = wire.seen[0] - assert request.url.host == "loom.test" - assert request.headers["Authorization"] == "Bearer private-cli-bearer" - body = json.loads(request.content) - assert body["agent"] == "loom-cli" and body["org"] == "" - assert not {"kind", "subject", "credential", "return_to"} & body.keys() - assert wire.clients and all(client.is_closed for client in wire.clients) - - -def test_connect_uses_the_explicit_server_before_environment(wire, monkeypatch) -> None: - monkeypatch.setenv("LOOM_BASE_URL", "https://environment.test") - wire.body = { - "connections": [ - { - "kind": "gdrive", - "connect_url": "https://public.test/settings/connected-accounts?kind=gdrive", - } - ] - } - assert cli.main(["connect", "google", "--server", "https://explicit.test"]) == 0 - assert wire.seen[0].url.host == "explicit.test" - - -def test_connect_uses_the_normal_profile_credentials(wire, monkeypatch, capsys) -> None: - seen = [] - - class Login(httpx.Auth): - def __init__(self, profile: str, server: str) -> None: - self.profile = profile - seen.append((profile, server)) - - def auth_flow(self, request): - request.headers["Authorization"] = "Bearer private-profile-bearer" - yield request + def forbidden(*_args: Any, **_kwargs: Any) -> Any: + pytest.fail("Retired native account setup attempted external work") - monkeypatch.setattr("loom.agent.StoredLogin", Login) - monkeypatch.setattr("loom.agent.signed_in_server", lambda _profile: "https://profile.test") - wire.body = { - "connections": [ - { - "kind": "notion", - "connect_url": "https://public.test/settings/connected-accounts?kind=notion", - } - ] - } - assert cli.main(["connect", "notion", "--profile", "work"]) == 0 - assert seen == [("work", "https://profile.test")] - assert wire.seen[0].url.host == "profile.test" - assert wire.seen[0].headers["Authorization"] == "Bearer private-profile-bearer" - assert "private-" not in capsys.readouterr().out - - -def test_connect_preserves_typed_refusal_and_closes_client(wire) -> None: - wire.status = 403 - wire.body = {"detail": {"code": "AUTH_INSUFFICIENT", "message": "private-refusal"}} - args = argparse.Namespace(provider="google", server=None, profile=None) - with pytest.raises(AuthInsufficient): - asyncio.run(cli._connect(args)) - assert wire.clients and all(client.is_closed for client in wire.clients) - - -def test_connect_refusal_prints_no_server_secrets_or_consent_link(wire, capsys) -> None: - wire.status = 403 - wire.body = { - "detail": { - "code": "AUTH_INSUFFICIENT", - "message": "private-cli-bearer", - "errors": [{"msg": "private-code-and-state"}], - } - } - assert cli.main(["connect", "google"]) == 1 - captured = capsys.readouterr() - assert captured.out == "" and "loom login" in captured.err - assert "private-" not in captured.err - assert wire.clients and all(client.is_closed for client in wire.clients) - - -@pytest.mark.parametrize( - "url", - [ - "javascript:private-secret", - "https://user:private-secret@public.test/settings/connected-accounts?kind=gdrive", - "https://public.test/v1/connect/gdrive/callback?state=private-secret", - "https://public.test/settings/connected-accounts?kind=gdrive&code=private-secret", - "https://public.test/settings/connected-accounts?kind=notion", - "https://public.test/settings/connected-accounts?kind=gdrive#private-secret", - "https://public.test/settings/connected-accounts?kind=gdrive\nprivate-secret", - "https://public.test:bad/settings/connected-accounts?kind=gdrive", - ], -) -def test_connect_rejects_links_that_carry_other_material(wire, capsys, url) -> None: - wire.body = {"connections": [{"kind": "gdrive", "connect_url": url}]} - assert cli.main(["connect", "google"]) == 1 - captured = capsys.readouterr() - assert captured.out == "" and "private-secret" not in captured.err - assert wire.clients and all(client.is_closed for client in wire.clients) - - -@pytest.mark.parametrize( - "connections", - [None, [], [{"kind": "gdrive"}], ["gdrive"], [{"kind": "gdrive"}, {"kind": "gdrive"}]], -) -def test_connect_refuses_missing_or_ambiguous_provider_links(wire, capsys, connections) -> None: - wire.body = {"connections": connections} - assert cli.main(["connect", "google"]) == 1 - assert capsys.readouterr().out == "" - assert wire.clients and all(client.is_closed for client in wire.clients) - - -def test_connect_refuses_an_invalid_response_shape(wire, capsys) -> None: - wire.body = ["private-response-secret"] - assert cli.main(["connect", "google"]) == 1 - captured = capsys.readouterr() - assert captured.out == "" and "private-response-secret" not in captured.err - assert wire.clients and all(client.is_closed for client in wire.clients) - - -def test_server_cli_delegates_connect_before_loading_deployment_environment(monkeypatch) -> None: - from server.cli import app - - def no_dotenv() -> None: - raise AssertionError("connect uses the SDK session, not the deployment environment") + monkeypatch.setattr(httpx.AsyncClient, "send", forbidden) + monkeypatch.setattr("webbrowser.open", forbidden) + with pytest.raises(SystemExit) as error: + cli.main(["connect", provider]) + assert error.value.code == 2 + assert "invalid choice" in capsys.readouterr().err + assert "connect" not in cli.COMMANDS - seen = [] - monkeypatch.setattr(app, "_load_dotenv_like_the_container", no_dotenv) - monkeypatch.setattr(app, "run_sdk_command", lambda argv: seen.append(argv) or 0) - argv = ["connect", "linear", "--profile", "work"] - assert app.main(argv) == 0 and seen == [argv] +def test_server_cli_does_not_delegate_retired_native_connect() -> None: + from server.cli.login import SDK_COMMANDS -def test_unknown_provider_is_a_parser_error_before_any_request(wire) -> None: - with pytest.raises(SystemExit) as error: - cli.main(["connect", "unknown"]) - assert error.value.code == 2 and wire.seen == [] + assert "connect" not in SDK_COMMANDS From 1a1f49da77305ed3d2abd7a960158a28e0a8504c Mon Sep 17 00:00:00 2001 From: zlareb1 Date: Mon, 23 Nov 2026 07:04:23 +0000 Subject: [PATCH 30/30] Describe MCP source authority and retained native registrations Reconcile document-source, live-search and retained push-state architecture with selected MCP reads while preserving protected publication, recording, storage and erasure rules. Signed-off-by: zlareb1 --- docs/architecture/document-sources.md | 1570 ++++++----------------- docs/architecture/live-source-search.md | 138 +- docs/architecture/source-push.md | 167 +-- 3 files changed, 487 insertions(+), 1388 deletions(-) diff --git a/docs/architecture/document-sources.md b/docs/architecture/document-sources.md index 717e95a535..af451376e7 100644 --- a/docs/architecture/document-sources.md +++ b/docs/architecture/document-sources.md @@ -1,419 +1,120 @@ # Document sources -A document source pulls files from a document store (a shared-folder store, a page -store, a project tracker, a meeting store) into a namespace's documents and keeps them -in step, on any shared namespace or collection. This page is the design of sources of -many items given as pasted links, per-user connected accounts, an org-wide crawl, and -access that follows the store's own permissions. The caller's view of today's sources is -in [knowledge: document sources](../features/knowledge.md#document-sources); parsing is -in [document extraction](document-extraction.md). Optional provider notifications -request the same sync path; [source push](source-push.md) describes their setup, -authentication and lifecycle. - -## What changes - -| Today | With this design | -| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| A source holds 1 to 20 folders, projects, pages or databases, and no op changes its `config`. | A source holds up to 300 items of mixed types, given as links or ids, and `knowledge.source.update` adds and removes them ([items](#items-and-links)). | -| One shared credential per source, typed by an admin. | A shared credential, a person's own connected account, or a delegated service account that reads many people's drives ([credentials](#credentials)). | -| Every reader of the namespace reads every synced document. | A source's `access` is `namespace` or `mirrored`; a mirrored document is shown only to a reader the store says may read it ([access](#access-follows-the-source)). | -| A `linear` source reads project documents only. | Issues and comments are a later design of their own ([issues](#project-tracker-issues)). | -| A `recording` source reads meeting-store transcripts (`meet`) or cloud-recording transcripts (`zoom`). | Meeting notes and transcripts that the meeting store saves to the shared-folder store come in through a `gdrive` source; `recording` keeps `zoom` only ([meetings](#meetings-through-the-shared-folder-store)). | +Document sources read explicitly selected external resources through approved MCP +connections, or import recordings through the recording source path. This page +explains their namespace, protected-result, storage and erasure boundaries. The +[MCP document-source architecture](mcp-document-sources.md) owns remote approval, +connection binding and selected-resource execution. Follow the +[source setup guide](../guides/mcp-sources.md) and +[source CLI guide](../guides/mcp-source-cli.md) for enrollment and controls. +[Document extraction](document-extraction.md) describes parsing. ## Any namespace -A source can be registered on any active shared namespace or collection; who may -register which kind is in [credentials](#credentials). `add` on an inactive namespace -answers `NAMESPACE_INACTIVE`, and `add` and `update` answer `ERASURE_RUNNING` (409, -retryable) while an erasure that will still run names the namespace, so no source writes -into a mirror the erasure is clearing. A source on a repository's trunk code namespace -still tags each document `repo:`, so the repository's `code.context` and -`loom_search` legs read them as today; on any other namespace, a branch namespace -included, it does not. A person's own place (a `col-me-…` collection, a `personal-…` or -`u-…` namespace, a namespace claimed at sign-up) holds no source (`PERSONAL_NAMESPACE`): -a `user_id` erasure erases what the person wrote, and a source's documents are the sync -worker's. The sync skips a source whose namespace is inactive; the cleanup of a stopped -source runs whatever its namespace's state. - -A source ends with its namespace: `code.repo.remove`, `namespace.delete`, -`collection.delete` and a namespace erasure each retire the namespace's sources under -its source lease, clearing their credentials, as `code.repo.remove` does today, so no -source outlives its namespace with a sealed credential or writes back what an erasure -took. - -A source's sync state is keyed by its namespace and name, as today, and a mirrored -source's by its mirror and source id, so the namespace's erasure covers it and a later -source of the same name resumes none of an earlier one's listing. It lives where -[storage layout](storage-layout.md#cursors) places it (`loom.code_index_state` today, -Postgres `cursors` from wave 3). - -On the dashboard, the Library's Sources button opens the sources of the namespace or -collection in view; the repository card keeps its own. +A source destination is an active ordinary namespace or collection. A source +cannot target the automatic personal namespace: end-user erasure covers what that +person wrote, while source documents carry worker provenance. A private or team +collection remains subject to ordinary grants and inheritance. Registration does +not add destination grants or turn a private connection into a shared credential. + +Namespace retirement and erasure fence source work before deleting content, so a +worker cannot write back what an erasure took. Inactive namespaces receive no new +source writes; explicit cleanup can still run. Source state belongs to its +namespace and registration identity, following the configured +[storage layout](storage-layout.md#cursors). A replacement registration cannot +resume another registration's authority from its name or cursor. + +The Library's Sources entry opens source setup for the selected namespace or +collection; repository sources retain their repository entry. ## Items and links -A source's items are its things to read, of mixed types: - -| Kind | Item `type` | Fields | Reads | -| -------- | ------------------ | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -| `gdrive` | `folder` | `id`, `recursive` (default `false`) | the folder's files; with `recursive`, every subfolder's too, to a depth of 8 and at most 500 subfolders per source (both not settings) | -| `gdrive` | `file` | `id` | one file of a kind `include` names | -| `gdrive` | `shared_drive` | `id` | every file of a shared drive | -| `gdrive` | `filter` | any of `name_contains`, `kinds`, `modified_after` (a date), and optionally `in` (a folder id) | the files that match, as a query the server builds | -| `gdrive` | `meet_recordings` | none | the meeting store's recordings folder of each account a `connected` or `crawl` source reads ([meetings](#meetings-through-the-shared-folder-store)) | -| `notion` | `page`, `database` | `id` | as today's `page_ids` and `database_ids` | -| `linear` | `project` | `id` or `slug_id` | the project's documents, as today's `project_ids` | - -Every id keeps today's alphabet check, since an id goes into a store query or a request -path. A `filter` never takes a raw query string: each field has a pattern (a name -fragment of printable characters, an ISO date, `kinds` from the `include` table), quotes -and backslashes are escaped, and `server/clients/gdrive.py` builds the query, so a -caller cannot widen a listing past what the fields say. `include` stays the source-wide -file-kind filter. `meet_recordings` is refused on a `shared` source, whose service -account has no recordings folder of its own. - -A source holds at most 300 items (a wire contract, not a setting; a `linear` or `notion` -source keeps its 20 until its turn bounds what it lists), and at most -`LOOM_KNOWLEDGE_SOURCE_MAX_DOCUMENTS` documents (default 50,000). The bound counts the -source's stored documents plus the new ones a turn writes (at most 200,000, since the -paged read of the stored copies costs about the square of the bound over 10,000). A turn -over it (a listing grown past it, an item swap whose new files are listed before the old -copies retire, or a lowered setting) holds back new documents only: it finishes its -listing, rewrites changed lists, retires, and lands its listing row, so its copies drain -back under the bound and no list goes stale; `inspect` and `loom doctor` show -`too_many_documents` meanwhile, with the count, for a `namespace` source; for a mirrored -source, its connected owner sees the code without the count, and a platform admin sees -both (exception 4). The read of a source's stored copies goes in pages by `source_uri`, -so it never cuts one off. A listing asks the store about at most 50 parent folders per -query (not a setting), so a source of many folders lists in several queries; a recursive -folder's subfolders are walked on every listing, so a new file in a new subfolder -arrives with the next turn, and files moved in with it (a move keeps a file's change -time) with the next full listing; a walk the pass deadline cuts leaves the listing -incomplete, so the turn keeps its stamp. A walk cut at its depth or folder bound still -lets a full turn retire a file the store reports deleted or trashed, or one of a kind -`include` no longer names, but never one the listing merely lacks, since it may sit -below the cut. - -A probe checks a bounded sample: every item while there are at most 20, otherwise the 20 -items added last, and the answer says `sampled: true` with the number checked, which is -shown wherever the item count is. - -On a mirrored source, the probe and the status hold back what depends on what a person -can read: - -- A mirrored source's probe answers reachability, the number of items checked and codes, - never a count, a sample of titles or a summary that names a file, since it lists as - the owner or as crawled people; which items were checked goes only to a connected - source's owner and a platform admin. -- To anyone else, a mirrored source's probe, status and `sync_now` answer only - source-level codes, whether the credential and its scopes work and `owner_inactive`, - and depend only on source-level conditions, so a held-back code reads as a clean sync. - `rate_limited`, which grows with how much a source lists, an item refusal, a per-file - or per-item code (`item : http_404`, `meet_recordings: not found`, `too_large`, - `extraction_failed:`), the oldest listing start and every last-sync time go only - to the owner and a platform admin. -- A refused item of the sample refuses `add` or `update` only on a `namespace` source - and on a connected source probed by its owner; on any other mirrored probe, a platform - admin's included, items never refuse, and only the source-level codes do. The next - sync turn reports a refused item as `item : http_404`, to those who see per-item - codes, and goes on with the rest. - -### The link parser - -`server/knowledge/domain/source_links.py` turns a pasted link into an item, with no -request to the store: - -| Link | Item | -| ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | -| `https://drive.google.com/drive/folders/`, with or without `u//` or `mobile/` | `gdrive` `folder` | -| `https://drive.google.com/file/d//…` | `gdrive` `file` | -| `https://docs.google.com/document/d//…`, `…/presentation/d//…` | `gdrive` `file` | -| `https://www.notion.so/-<32 hex>`, `https://www.notion.so//<32 hex>`, `https://.notion.site/-<32 hex>` | `notion` `page` (`database` with `?v=`, unless `p=` names a page) | -| `https://linear.app//project/-` | `linear` `project` | - -A shared drive's own link has the folder form: a folder link names a folder, read -without its subfolders, even when it is a shared drive's root; a recursive folder at a -drive's root is turned into a `shared_drive` item by the probe. A link of another host, -with no id, or to something the sync does not read (a spreadsheet, a single issue) -answers `unreadable` with the reason, as does an `open?id=` link, which names a folder -or a file alike. The parser takes a list and answers each link, so a paste of fifty -links shows which three it could not read. It is `knowledge.source.parse_links` (viewer; -no store request, nothing written), which agents use to preview pasted links; `add` and -`update` take links directly. A page link that turns out to be a database is reported by -the probe. A project link carries the project's short id, which `add` and `update` -resolve to the UUID the store's API takes, in one lookup before the probe. +An MCP registration saves an exact set of UTF-8 resource identities. Browsing shows +one bounded metadata window, with truncation and capability limits. Manual exact +IDs support servers that cannot enumerate. A resource identity is not normalized +into a provider URL, expanded into children or interpreted as a native folder, +page or project query. Approved read and search mappings supply service-specific +fields; tool descriptions and model arguments grant no authority. + +Live mode reads on demand without importing. Snapshot reads the saved selection +once; selected refresh re-reads that selection through the source worker. None +claims complete enumeration, upstream ACL synchronization or deletion detection. +Partial pages, missing results and failed reads never authorize content deletion. ### Wire shape -`knowledge.source.add` takes `items`, or `links` it parses (an unreadable link refuses -the call naming the first 10 with their reasons and counting the rest, `BAD_LINK`), and -still takes `config`, which it turns into items (`folder_ids` into `folder` items, and -so on), so an N-1 client keeps working. `list` and `inspect` answer `items`, and -`config` in today's form when the items can be written in it, else `{}`; a mirrored -source answers `config` `{}` to everyone, and its audit rows carry every field of its -items and a crawl's `subjects` as keyed hashes only (below). A filter has no owner field: -it would keep a person's address in the registry, which outlives their erasure. Its -`name_contains` is an admin's text and, like the source's name, stays in the registry -and the audit log after an erasure. - -`knowledge.source.update` takes `add_items`, `remove_items` (each also as links) and a -new `include`, probes what it adds with the stored credential (the same sample rule), -and writes the source at its next version under the namespace's source lease. Its audit -row, and `add`'s, names the namespace, the name and the items added and removed, with a -crawl's `subjects` and every field of a mirrored source's items as keyed hashes (below). -Removing every item is refused (`BAD_CONFIG`); `remove` ends a source. Changing `access` -is a new source. For a `crawl`, `update` also takes `subjects` (the new list, probed -like added items) and `directory_subject`. Every `update` and `rotate` of a crawl needs -the same roles as `add`, since its credential reads every listed person's drive: a -namespace admin without an org-wide role cannot change whose drives it reads, what it -reads of them (items, `include`) or the key it reads with. +MCP setup and lifecycle use `knowledge.connection.mcp_*` and +`knowledge.source.mcp_*`. Preview binds the exact selection, destination and reader +policy; save requires its current authority and any explicit collection-copy +consent. Updates replace the selected set under a monotonic scope revision. +Selection changes, including returning to an earlier selection, invalidate old +successful-read authority. A changed audience requires a separate registration. + +The ordinary `knowledge.source.add` path accepts recording configuration. Native +document kinds, link parsing, native source updates and native OAuth enrollment +are outside the executable source contract. The old add input's removed fields +are reported through the transport's `ignored_args`; they do not configure an MCP +source. The source and OAuth cleanup is a breaking interface change. ### One document, one owner -In a namespace, one document per address, as today, owned by one source: the source -whose `source:` tag it carries, written by the sync worker (today's ownership -check). Only the owner rewrites the document when its file changes and retires it on -positive evidence (today's retirement rule), and a document another writer (a person, an -agent) wrote is never overwritten or retired by any source, as today. A mirrored -document also carries `source-id:`, the id of the source that wrote it, and in a -mirror that tag, not the name, decides ownership: a later source of the same name owns -none of an earlier one's documents, and the cleanup of a stopped mirrored source retires -by it. Only N writes a mirror, so every mirror document carries the tag. Inside a mirror -a document's `source_uri` is its address with the source id appended -(`
    #`; the address is the part before the last `#`, and citations and -answers use it), so each mirrored source writes its own copy with its own list under the -table's key, heads and document machinery as they are, and no source's write or -retirement touches another's copy. The legs answer the address itself, dropping -duplicates after the check ([below](#the-mirror)), and a `get` or `download` of an -address answers the namespace copy when the reader may see it, else the newest mirror -copy the reader may see. Only the owning source's turn writes a mirror document's list; -any other writer of a mirror row (a retention or tier move, a sweep, a reindex) writes a -tombstone or `unread`, never a list it carried. Only those writers and the erasure write -rows under a mirror's name; no request does. How a stopped source's documents and rows -are found and cleaned when several sources, builds or names meet is the implementing -pull request's to specify. - -In a namespace, a second source that lists a file at an address where a document is -counts it `skipped`, as today, and fetches no content. No source reads whether another -is live: an address is free exactly when no document is there. Once the owner's document -is retired (by today's [retirement rule](../features/knowledge.md#document-sources), its -`remove` with `delete_documents`), the next source that lists the file writes it as a -new file under its own tag at its next full listing -(`knowledge_source_sync_full_interval_seconds`). A kept document (one a `remove` without -`delete_documents` left) is skipped by every source until `knowledge.delete` removes it, -as today. - -So a file that two `namespace` sources reach is written once and read through one -document. Between the owner's retirement and the other source's next listing of the -file, the document is missing; that gap is the cost of keeping one owner per address -there. A mirror pays duplicate chunks for a file two mirrored sources reach instead. - -A mirrored predecessor never makes `add` of its name answer `SOURCE_DELETE_PENDING`, -since mirror ownership goes by source id, and it counts toward no source quota while it -waits; its pending retirement shows to a platform admin only. `remove` with -`delete_documents` retires the source's documents, as today, and without it they stay as -kept documents, which `add` of the same name refuses to take over -(`SOURCE_DOCUMENTS_KEPT`, as today). A mirrored source's documents are always retired -([below](#the-mirror)). +Only a document's owning source may rewrite its copy. A source never overwrites +or retires content another writer owns. Mirror ownership uses the immutable +`source-id:` tag, so a replacement registration with the same name owns none +of its predecessor's copies. Each mirrored source has its own address and access +proof under the existing document key; ordinary knowledge heads, revisions, +originals, chunks and indexing still apply. + +An MCP citation identifies the registration and the digest of the exact selected +identity. It is a local source-copy address, never an outbound fetch target or an +assertion of an upstream URL. An unchanged owned document receives updated +metadata and successful-read proof without rewriting its content revision, +original or chunks. Retained bytes confer no current read authority. + +Ordinary published namespace copies keep their existing ownership, namespace +access and writer-requested erasure rules. Retiring executable source support +does not silently delete them or convert them into protected copies. ## Credentials -A source has a `credential_mode`: - -| Mode | Credential | Registers it | Writes to | -| ----------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------- | -| `shared` | Today's: a service-account key, an integration token, an API key | an `admin` of the namespace | the namespace, or its mirror when `access: mirrored` | -| `connected` | The registering person's own connected account for the kind's store | a person with `writer` on the namespace; the source is theirs | that namespace's mirror | -| `crawl` | A service account with domain-wide delegation that reads, as each listed person, what that person can read | an `admin` of the namespace who also holds `org_admin` or `platform_admin` | the namespace's mirror | - -The gate of `add`, `update`, `check`, `sync_now` and `remove` drops from `admin` to -`writer`. The handler then requires `admin` for a `shared` or `crawl` source. On a -`connected` source only its owner adds items or changes `include`, since the items read -with the owner's account; its owner or an admin of the namespace may `check`, `sync_now` -and `remove` it, and only its owner, who sees them, removes its items. `rotate` stays -`admin` (for a crawl, also an org-wide role) and is refused for a `connected` source, -whose credential is its owner's connection. Owners are compared as canonical subjects -(`server/auth/aliases.py` `canonical_subject`), so a person's other spellings are the -same owner. - -`LOOM_KNOWLEDGE_SOURCES_MAX_PER_NAMESPACE` (default 8) bounds a namespace's `shared` and -`crawl` sources, as today. `LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_PERSON` (default 8) -bounds a person's `connected` sources in one namespace, and -`LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_NAMESPACE` (default 64) all of a namespace's, -so writers cannot fill an admin's quota or the sync's passes. A crawl's credential reads -every listed person's drive, which is why it needs an org-wide role; a turn stops a -crawl whose registrant no longer holds `admin` on the namespace and an org-wide role, as -the owner check below stops a connected source. +An operator approves the remote HTTPS Streamable HTTP endpoint, authentication +profile, operations, mappings and bounds. A connection uses anonymous access or +a preissued bearer for that exact origin and audience. Loom credentials never +authenticate to the remote server. No provider OAuth enrollment, refresh fallback, +local command execution or native execution shim supplies failed MCP reads. ### Connected accounts -A person connects their own account from the dashboard (Settings → Connected accounts) -or with `loom connect gdrive|notion|linear`. Connecting needs `LOOM_PUBLIC_BASE_URL`: -the redirect URI registered with the store is built from it, never from a request's -`Host`. - -- The flow is bound to the browser that starts it, as SSO account linking binds its - ticket (`_link_cookie` in `server/auth/oauth.py`). The dashboard's page calls - `POST /v1/connect//start` with its bearer token, which must carry a sign-in - session (`sid`), which a service-account token lacks; the cookie below, not the token, - is what ties the connection to one browser. The server keeps a single-use `state` in - Keeper for 10 minutes, bound to the subject and to a random binding it sets in that - browser as an HttpOnly, `SameSite=Lax` cookie, and answers the store's consent URL, - which the page opens. The store redirects to `GET /v1/connect//callback`, which - stores the connection only when the request carries the cookie whose binding the - `state` names; the subject is the one recorded at start. A consent URL sent to someone - else attaches nothing: their browser has no such cookie. `loom connect` opens the - dashboard's Connected accounts page for the kind, where the person signs in if they - have not. PKCE where the store takes it; `include_granted_scopes=false`, so an earlier - grant of the same client is not folded in. - After consent succeeds, a callback whose HTTP `Accept` header prefers HTML returns - a redirect to the fixed same-origin `/settings/connected-accounts` path. Other clients - receive `{"connected": true}` as JSON. Both responses disable caching, carry - `Referrer-Policy: no-referrer`, vary on `Accept`, and clear the browser binding cookie. - The dashboard URL carries no code, state, token or caller-supplied return address. -- Scopes, the narrowest each store has: - - `gdrive`: `https://www.googleapis.com/auth/drive.readonly`, `openid` and `email` - (which the token answer spells `https://www.googleapis.com/auth/userinfo.email`). - The Drive scope is a restricted one, so the operator registers an OAuth client that - the store treats as internal to the org's workspace; a public client needs the - store's verification first. `drive.file` with the store's file picker reads only - files picked in a Loom page, never a folder's later files or the recordings folder, - so it is not offered. The store's device grant does not issue Drive scopes. - - `notion`: the public-integration OAuth, where the person picks the pages to share on - the consent page. The operator registers read-content capability only, without - write, comment or user-information capabilities. The OAuth flow has no documented - scope parameter; token introspection can report an opaque scope, without a - documented mapping to capabilities. Neither that value nor its absence proves the - registration is read-only. The registration is the permission bound; a display - email is optional because reading it needs a separate user-information capability. - - `linear`: an OAuth application with the `read` scope and `actor=user`. -- `GET /v1/connect//callback` exchanges the code. Each granted scope is mapped to - its canonical name, and a granted scope outside the kind's set refuses the connection. - The callback stores in `loom.connected_accounts` the canonical subject, the kind, the - store account's id, optional display email, scopes and refresh token. The store id and - email describe the connected account; neither changes the person's Loom identity or - grants namespace access. A usable refresh token is required for ongoing sync, - including for `notion`; a missing token refuses the connection instead of falling - back to storing an access token. The refresh token is sealed under the purpose - `connected_accounts.credential`, which `loom secrets reseal` covers. An access token - is held in memory only. The optional display email is sealed separately under - `connected_accounts.email`; neither value is copied into a source row. -- Refresh for a source retains its account generation and source binding across provider - work. One reservation owns the account generation at a time. A successful rotation - is sealed only while the owner, account fence and reservation remain current; source - or requesting administrator loss then refuses delivery without discarding that rotation. - Disconnect, replacement, erasure or deactivation cannot be undone by an older refresh. A cancellation or lost response - does not prove the provider left its token unchanged, so a retry needs the provider's - documented recovery guarantee. Missing expiry metadata does not justify an invented - lifetime or permanent access-token fallback. -- Each native HTTP call receives an internal `CheckedAccess` checkout rather than an - ordinary credential string. It retains the owner, source id and connection generation, - rechecks standing after pacing and before dispatch, and rechecks after the bounded - response stream closes. Its deadline covers those waits and the body read. It cannot - be converted into a shared credential or serialized, and it forwards credentials only - to the provider's fixed native API paths, without redirects. A source changed during - the request discards the result. -- Provider token contracts differ: - - `gdrive` can omit a replacement refresh token. Retain the existing refresh token in - that case. Revoking a token affects the person's grant across the OAuth project's - clients. Use a project dedicated to document connections; unrelated applications - must not share that revocation boundary. Other affected connections stop when - refresh is refused. - - `notion` refresh replaces both access and refresh tokens. The authorization guide - requires the pair, while the response reference permits a null refresh token; a - reply without usable replacement material is unavailable. The documented REST flow - supplies no token lifetime, PKCE or lost-response recovery guarantee to assume. - - `linear` refresh replaces both tokens and renews the refresh token's 30-day lifetime. - Track access expiry from `expires_in`. The provider documents a 30-minute recovery - window for a lost successful refresh response, excluding revoked or replaced - credentials; this does not permit retrying another provider's rotation. - - These contracts follow the stores' authorization references: - [Drive](https://developers.google.com/identity/protocols/oauth2/web-server), - [page-store authorization](https://developers.notion.com/guides/authorization/overview), - [page-store refresh](https://developers.notion.com/reference/refresh-a-token), - [capabilities](https://developers.notion.com/reference/capabilities), - [token introspection](https://developers.notion.com/reference/introspect-token) and - [tracker authorization](https://linear.app/developers/oauth-2-0-authentication). - -- A connection belongs to the subject that made it, and only that subject's sources use - it. `connection.list` and `connection.disconnect` act on the caller's own; an erasure - of the person deletes its connections and retires their sources - ([erasure](#erasure-and-audit)). An org admin sees in admin Users which kinds each - person has connected, never a token or the store account's email. -- Connecting again with another store account replaces the connection and stops the - sources that used the old one, as a disconnect does: their items were chosen for the - old account. -- Every path that ends a connection (`connection.disconnect`, connecting again with - another store account, a SCIM deactivation for every subject it revokes, an erasure of - the person, a restore) ends it in one order: it unseals the credential into memory, - clears the sealed credential and marks every source that uses it inactive (the part - that fails closed), and only then revokes at the store with the token in memory, best - effort, under a short timeout and outside any lease or claim, as SCIM revokes tokens - past its leases; a revoke that hangs or fails leaves the credential cleared. Local - disconnection is complete independently of remote revocation. The page store's - [revocation reference](https://developers.notion.com/reference/revoke-token) documents - access-token revocation, without promising refresh-token or whole-grant revocation. - An access-token revoke therefore cannot be reported as invalidating its refresh - family. If only refresh material is available, bounded refresh solely to obtain an - access token for revocation may follow local inactivation; no replacement credential - is persisted. An unavailable or unproven remote revocation remains so, and the person - can remove the integration's grant at the store. The sync worker then retires those - sources' mirrored documents. A turn also checks the owner: a - source whose owner subject is revoked, deactivated, or no longer holds `writer` on the - source's namespace is stopped (written inactive under the source lease, - `status: owner_inactive`) and goes as a removed source does, so a missed hook fails - closed. - -A connected source reads the person's own files, the files and folders shared with them, -their recordings folder, and the pages and projects they can read. It reads no -directory, so it expands no group ([below](#who-may-read)). - -### Org-wide crawl - -A `crawl` source's credential is a service-account key whose client id the org's -workspace administrator granted domain-wide delegation for `drive.readonly`, -`admin.directory.group.member.readonly` and `admin.directory.user.readonly`. Its config -holds `directory_subject` (a workspace administrator the directory reads impersonate) -and `subjects`: people (emails) and groups (group emails), whose members the directory -read lists at each turn, at most 2000 people (not a setting). For each person the sync -exchanges the key for a token that impersonates them (the JWT bearer grant with `sub`) -and lists the source's items as them. A typical config is one `meet_recordings` item and -a `filter` with `kinds: [docs]`, over a group: every member's meeting notes, without -anyone connecting. Every list and members row the sync writes, a crawl's expansion -included, leaves out the people an erasure excluded ([erasure](#erasure-and-audit)). - -The probe checks that the delegation grants no write on what the crawl reads: it asks -for each of the three scopes, which must be granted, and for -`https://www.googleapis.com/auth/drive`, `admin.directory.user` and -`admin.directory.group`, which the store must refuse; a credential the store grants any -of them is refused (`CREDENTIAL_REFUSED`). It cannot prove the delegation grants nothing -else (a mail scope, say), and the page says so to the admin who registers it. The audit -rows of `add`, `update` and `rotate` record the configured subjects as keyed hashes (an -HMAC under the root secret, as SCIM's audit rows hash a subject, so a list of the org's -addresses does not reverse them). Audit rows also record the scopes granted and the -number of members resolved: the audit trail outlives erasure and keeps no crawled -person's address. +Each connection belongs to its canonical authenticated owner in one organization. +Its sealed binding retains the account slot, generation, endpoint, token audience +and approval digest. Source work checks current owner standing, destination +authority, revocation fences, approval and fleet readiness. Another reader's +namespace grant cannot borrow that connection. Remote identity is not verified +merely by a bearer, server title or returned account label. + +Pause and disconnect stop local reads and retain content and account history. +They do not assert upstream credential revocation. The owner revokes a bearer at +its issuer when required. Retained native credentials are not reused or migrated +automatically; fresh MCP setup requires owner authorization and exact selection. ## Access follows the source -A source's `access`: +MCP stored copies use the protected mirror for both reader policies. Owner-only +access requires the current canonical owner and destination access. Collection +copy is an intentional local publication, requiring operator approval, namespace +administrator authority, explicit server-issued consent for that selection and +current destination-reader authority. Neither policy claims upstream ACL +equivalence. The audience is immutable for a registration. -- `namespace`: every reader of the namespace reads every document, as today. The only - mode for a `shared` source of a store whose permissions the sync does not read - (`notion`, `recording`), and the default for `shared` `gdrive` and `linear` sources. -- `mirrored`: a document is shown only to a reader the store says may read it. Required - for every `crawl` and every `connected` source. +The protected-result model has four parts: documents live in a companion +namespace no grant opens; each copy carries its current source access proof; +every checked leg validates that proof; and publication revalidates retained +contributions before delivery. Unsupported sources, missing proof and stale proof +admit nobody. Retained native permission rows cannot authorize MCP access. -The model has four parts: mirrored documents live in a companion namespace no grant -opens; each document carries its permission list; every read through that namespace -checks the list and fails closed; and every complete listing reads the lists again. One -rule holds them together: nothing derived from a mirrored document (its address, title, -text, counts or existence) enters a Loom record outside the mirror or an answer to a caller. An op -that is not a checked leg (a source's probe, status or `remove`, an erasure's receipt) -therefore answers codes for what a mirror holds, never a count, title, file id or -address, and a code that depends on the mirror's rows (a residue failure) reads as the -same code for any cause. The exceptions are these: +Nothing derived from a mirrored document (its address, title, text, counts or +existence) enters a Loom record outside the mirror or an answer to a caller, +except through these boundaries: 1. A checked leg's answer to its reader, every field of which depends, of the mirror, only on the items that reader was admitted to, and otherwise only on the request and @@ -445,12 +146,10 @@ same code for any cause. The exceptions are these: only, and the error-rate and model metrics leave marked requests out. The stored argument map keeps only numeric statement/read/injection work fields. Result identifiers, document tags, argument digests and error prose are omitted. -3. A connected source's per-item and per-file codes and `too_many_documents`, to its - owner, and its listing age, to its owner as a code (fresh or stale). -4. A platform admin's view of a mirror's sources (every mirrored source's status, the - probe's sampled items and their codes, and the oldest listing start), its sync and - spend, and its erasure counts, as codes and counts, through `loom doctor`, - `knowledge.source.inspect` and the erasure ops. +3. Owner-visible selected-source controls may report their authorized selection + and read failures; they do not expose another owner's registration or content. +4. Privileged platform diagnostics and erasure recovery retain their existing + codes-and-counts boundary. Ordinary receipts cannot reveal mirror contents. The rule covers Loom's records, application logs, spans, metrics and caller-visible answers. Database-native query, error, mutation, text, profile and trace logs remain @@ -494,14 +193,14 @@ owner's erasure included, since the registry keeps every mirror it had. The migr that enables the refusal first looks for namespaces of the reserved form, registered or holding rows, and refuses to run, naming them, if it finds any. -A knowledge read taught the mirror adds a leg over the namespace's mirror, with the -check below, while the namespace's source list holds an active mirrored source (a fact -that list shows every viewer); a mirror with no active mirrored source in that list runs -no leg. Every other read path reads the namespace and finds nothing of the mirror. So a +A checked knowledge read adds a leg over the destination's mirror only through +current source discovery and authority checks. Retained rows alone do not make a +source eligible. Every other read path reads the namespace and finds nothing of +the mirror. So a new op, a context-pack leg or an export that nobody taught the check shows no mirrored -document; an N-1 replica has no mirror leg, and the rollback procedure keeps it off a -mirror that holds rows. A permission column on `loom.documents` read by every path would -make the opposite the default; [sharing](sharing.md#alternatives-not-taken) rejected +document; a build without supported source authority cannot admit its protected +copies. A permission column on `loom.documents` read by every path would make the +opposite the default; [sharing](sharing.md#alternatives-not-taken) rejected that for collections, since one missed path leaks. Search discovers chunk keys and scores without returning chunk text. Each leg checks @@ -510,9 +209,9 @@ denied candidates consume no pool position or fusion rank. Content reads bind th exact admitted namespace, address, chunk index, version and revision under the requested embedding model. A missing key is omitted without substituting a later version. Duplicate or unexpected rows discard all mirrored legs. Permissions are checked again -after content is fetched. Listing evidence and any group membership relied on must -still be fresh before the content leaves the checked leg. Independent email, owner, domain or public grants -can admit a document whose group evidence expired. +after content is fetched. The successful-read proof, source scope and connection +authority must still be current before content leaves the checked leg. A retained native ACL or +group row cannot substitute for supported source authority. A marked private-first search gathers both possible passes from its authorized namespace list and visibility settings before choosing which to return. It refreshes @@ -521,8 +220,8 @@ threshold. A provisional private hit that loses permission therefore cannot supp the public fallback. No reranking provider receives the provisional pools. - **Legs with the check:** `knowledge.search`, `get`, `outline`, `list`, `download`, - `synthesize`, `knowledge.inspect` (titles), `knowledge.source.inspect` (a mirrored - source's documents), the `search.query` knowledge and repository-docs legs, + `synthesize`, `knowledge.inspect` (titles), source-specific protected reads, the + `search.query` knowledge and repository-docs legs, `code.context`'s docs section, `context.pack`, `memory.stack`, `memory.ask` and the assistant (which calls the same handlers under its answer token, delegated from the caller's). A `get`, `outline` or `download` of a mirrored address the reader may not @@ -568,11 +267,10 @@ the public fallback. No reranking provider receives the provisional pools. its stream's first event or its response's first field) is marked and flagged, since its answer is model text written from tool results and need not carry the field the tools answered. A mirror leg answers nothing to a client that does not declare it - honours the flag. Loom's plugins and CLI declare it, and so do the dashboard, which - shows the document, and the assistant, whose answer token declares the flag only when - its caller's request did: a caller that does not declare gets no mirrored text through - the assistant, and the assistant writes nothing from that turn into anything it - shares. An SDK declares it only when the app built on it opts in. + honours the flag. A participating client declares it only with its durable + observer and automatic-capture guards installed. A header alone does not establish readiness. + The assistant delegates its caller's protection promise; it cannot manufacture + one. A caller without that promise receives no mirrored text through it. - **The session rule** keeps a session that saw a mirrored answer from sending it on ([the session rule](#the-session-rule)). - **The sync and the workers write nothing outside the mirror.** The mirrored sync's @@ -691,46 +389,32 @@ retain checked reads. Each entry gets fresh local state before routing or screen the enclosing HTTP request keeps a monotonic mark through later ordinary entries, streaming and cleanup. Middleware task boundaries do not clear that owner. -A mirrored source's documents are never kept past it: `remove` retires every one it owns -(`delete_documents` is implied), and so do a disconnect, a SCIM deactivation, the owner -check and every retirement of a namespace's sources. Each of them marks the source -inactive (in the request, or in the turn for the owner check) and leaves the deleting to -the sync worker, so no request's work depends on how much the mirror holds. The worker -retires a stopped source's documents by its `source-id:` tag outside the content bound, -with a per-pass bound of its own, so a large removal does not stall other sources' -content. In a mirror, ownership and every per-source document read go by the -`source-id:` tag, not by name. The retention overrides give each mirror its -namespace's `retention_days` and `warm_days`. - -Stopped-source deletion has a durable source-id queue in `code_index_state` under the -mirror, with keys `knowledge_source_retire:`. A queue row contains only the -original namespace, source name, kind and registration id. The request writes it under -the sources lease before inactivating the source. A replacement registration can reuse -the name while the old queue row and copies remain; cleanup uses the row's mirror and -source-id ownership, independently of the current mirror registry. - -The `knowledge_source_retire` worker runs even with authentication or syncing off. It -shares the sync cadence, with its own deadline, cursor and -`LOOM_KNOWLEDGE_SOURCE_RETIRE_DOCUMENTS_PER_PASS` bound. Its cursor contains registration -metadata only. A queued source still active under the same id is left alone, so a crash -between enqueue and inactivation deletes nothing. Completion requires both no live owned -documents and no pending or parked publication while holding the source's turn lease. -Clearing the queue writes an empty version row; erasure removes it with the mirror's -other state. Cleanup exports no document counts or cut flags. - -A namespace source and a mirrored source that reach the same file own two documents, one -in the namespace and one in its mirror. The namespace copy is readable by every reader, -because an admin registered a source that makes it so; every leg answers the address -once, dropping duplicates after the check. When both copies matched and the reader may -see the namespace copy, the hit is the namespace copy's, with its own chunks and scores -and no item flag. When only a mirror copy the reader is admitted to matched, the hit is -that copy's, with the item flag. Otherwise the mirror copy is dropped. +MCP pause, disconnect and unsupported source kinds make retained copies +unavailable without deleting their bytes. Source removal queues document retirement +only when explicitly requested by `delete_documents`; namespace or owner erasure +uses its own explicit erasure authority. Removal without copy erasure does not +preserve permission to read an unsupported or stopped protected source. + +Explicit source retirement uses a durable source-id queue under the mirror. +Cleanup retains immutable ownership independently of a later registration with the +same name. The retirement worker runs with its own deadline, cursor and +`LOOM_KNOWLEDGE_SOURCE_RETIRE_DOCUMENTS_PER_PASS` bound, including when ordinary +syncing is disabled. It deletes no still-active matching registration. Completion +requires no live owned documents and no pending publication under the source's +turn lease. Erasure removes retirement state with the mirror's other state. +Cleanup exports no private document counts or cut flags. + +A retained ordinary namespace copy and a protected mirror copy keep independent +ownership and access. Checked retrieval deduplicates only after access checks. +When an admitted ordinary copy wins, it supplies its own chunks and scores; +a mirror-only hit retains its protected classification. ### The session rule A session-content op records a session's text, or a figure derived from it, that a hook -or client sends without the agent choosing it; an op the agent calls with text it chose -is the reader's own write. Each op declares +or client sends automatically. Explicit reader writes retain their ordinary +authority checks; participating clients also guard automatic writes derived from +a protected contribution. Each op declares its class in the op registry (`server/operations/registry.py`), and an op both a hook and an agent call is session content. They include `conversation.append` (which the CLI's `ingest-transcript` calls), `conversation.save_message`, the `title` and @@ -748,9 +432,13 @@ session-derived inputs. The rule decides; the registry's classes and a test over what the shipped hooks send pin the full set. Once a session has seen the flag, no Loom hook sends any op from it, reads included, and -no client sends a session-content op on its own; the calls the agent makes go on, -dual-use ops (`code.search`, `context.pack`) included. A session is also flagged when a -subagent or a child process it started saw the flag: the child records it in the session +no client sends a session-content op on its own. Explicit reader requests remain +subject to their ordinary authority checks, including dual-use reads such as +`code.search` and `context.pack`. Participating applications guard later automatic +writes through every retained contributing family, across clients and namespaces; +missing or lost durable state refuses rather than starting a clean session. + +A session is also flagged when a subagent or a child process it started saw the flag: the child records it in the session state it shares with the parent, which the parent's hooks read, since the child's final text, reworded, need not carry `mirrored: true`. A session resumed, forked or compacted from a flagged one is flagged, and so is one started from a flagged session's process @@ -816,272 +504,81 @@ these rules. ### The permission list -Each mirrored document carries its permission list in an `access_json` column of its row -(`loom.documents`; under the Postgres authority it rides in the head's `row` jsonb, with -no Postgres migration), written by the turn of the source that owns the document: - -- `emails`: the people the store grants any role on the whole file, lower-cased, and, by - credential mode: - - `connected`: the owner, whose account listed the file in that turn, entered as the - source's `owner_subject` (an `owner` entry, never an email, and never the - connection's store email), since the owner chose the item and can open it. When the - store will not give the file's list, the list is the owner alone, not `unread`. - - `crawl`: a person the crawl listed the file as, only when they own it or the - permissions read as them name them, never from a read by an item or folder id or - from a shared-with-me entry, which the store also gives a link-only share someone - opened. An unreadable list holds the file's owner if a crawled person owns it, and - is otherwise `unread`. - - `shared`: nobody more; its service account is no reader, so its unreadable lists are - `unread`. -- `groups`: group emails, which a crawl's directory read expands into - `loom.knowledge_group_members` (one row per source and group, with its members and - `read_at`). A connected or `shared` mirrored source reads no directory and expands no - group, so a file shared with its readers only through a group shows only to the people - whose own account listed it. -- `domains` and `anyone`: a domain or public permission the store marks discoverable. A - link-only share (one the store marks not discoverable) is left out: it lets someone - who holds the link open the file, not find it. -- `unread`: no current list is known; such a list carries no `owner`, `emails`, - `groups`, `domains` or `anyone`, and admits nobody. - -For `gdrive` the list is the file's `permissions`, read with the listing, or with -`permissions.list` when the listing leaves it out; for `linear`, the active members of -every team the project belongs to, a member of unknown state admitting nobody; for a -connected `notion` source, the owner alone, so only the owner sees a page. The list -lives and dies with its document: a retirement's tombstone carries no list, and no read -op returns the column. +A mirror document's `access_json` is private access metadata, carried in the +ordinary document row and, under the Postgres authority, its head. For MCP +copies it binds the owning source, scope digest and server-observed successful +read time. The existing freshness bound applies to each document, including a +snapshot. A snapshot without explicit refresh eventually becomes unavailable. +No read returns the private access column as ordinary document content. + +A denied, oversized or unavailable selected resource loses its own read proof; +its bytes remain. An observed approved-mapping schema failure stops the exact +current connection under its lease, invalidating all source reads on that +binding. Restoring a schema does not reactivate that connection. A fresh +owner-approved binding is required. Missing upstream ACL information never adds +readers or changes owner-only content into a collection copy. ### Who may read -A reader sees a mirrored document when all of these hold: - -1. The reader holds `viewer` on the source's namespace (the ordinary gate). -2. The document's owning source (the registry row whose `source_id` matches its - `source-id` tag) is active and has a last complete listing that started within - `LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS` (default 3600) of now, read from its row in - `loom.knowledge_source_listings`. -3. The person the token reads as (below) is the list's `owner` entry, compared through - `canonical_subject`, or one of that person's verified emails is in the list's - `emails`, or in the members of one of its `groups` from a members row of the - document's owning source read within `LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS` (by - its `source-id` tag), or that email's domain is in its `domains`, or its `anyone` is - set. - -The reader's verified emails are its subject's directory emails that -`VERIFIED_EMAIL_SQL` admits (an SSO account's or a linked one's, -`server/core/grant_sql.py`), and nothing else: a subject that merely spells an address -is not one, and neither is a connection's store email. The predicate's passwordless -arm covers nonempty contacts from verified SSO provisioning or operator linking. -Password signup hashes the supplied password before storing its claimed address; -ordinary namespace registration cannot write a contact address or password hash. -The internal reader resolver retains the uncached canonical subject independently of -verified emails and reads actual active contact rows for email proof. - -Signed hosted-domain evidence lives in `sso_links.hosted_domain` and `issuer`, written -after the final SCIM check under the account ownership lock. A domain matches only -through a current linked row naming the active passwordless account's contact, with the -configured issuer and its signed hosted-domain claim. Empty defaults, missing claims, -issuer changes and generic link changes deny domain access. Neither a linked password -account's email nor a bare verified address proves domain membership. These identity -inputs alone expose no mirrored document. -A request keeps a monotonic mirror mark in its existing work bag, shared with child -legs. An unbound direct helper serves no mirrored content. Active registrations, mirror -bindings and listing starts are read in sequence before candidate permissions. A failed -unconditional read marks `mirror_unread`; a failed candidate read invalidates the whole -mirror plan without that marker. Checked adapters cover search, get, outline, download -and listing. Other readers, marked-request sinks and session protections remain -prerequisites to enabling mirrored sources. - -`documents.access_keys` and its bloom index select coarse candidates under the -ClickHouse authority. Owner and group buckets retain candidates needing identity -resolution; Unicode buckets retain matches whose database and Python normalization -can differ. Every candidate still needs the current strict permission check. Under -the Postgres authority these keys do not filter candidates: an unpublished head may -widen permission. Both chunk-frequency views exclude mirrors, and a lexical-statistics -rebuild refuses their names before reading or writing statistics. Mirrored lexical -scores use fixed corpus constants. - -The checked list projection reads title, description, tags, blob metadata and the -stored preview only at an admitted live document version and revision. Under Postgres, -the current head supplies these fields and computes only the first 220 content bytes -in the database, including for encoded text; no full body crosses into the list reader. -Chunk counts belong to that same storage copy and revision. They count distinct -embedding-model and section-index pairs, including sections awaiting embeddings. A -Postgres count also requires the head's recorded chunk version; a current revision -without recorded chunks counts zero. Permission and serving-state proofs must remain -current through the list's final read before any count or lookahead is returned. -Metadata discovery groups complete public address families before a public cursor or -limit. Postgres reads internal pages of 64 rows, releasing the connection before -permission checks; it reads every page without a candidate cutoff. Ordinary shadow -checks read bounded batches independently of public filters and cursors. They cover -the ordinary listing's published rows and its unpublished Postgres heads; requesting -superseded rows also lets an ordinary tombstone shadow a mirrored copy. Mirrored -candidates remain live-only. -Listing chooses the newest admitted complete copy of a public address, with a stable -storage-identity tie break, before applying public tags, URI prefixes or the cursor. -An ordinary copy wins its entire family before these filters. Selection retains only -one current family, bounded shadow batches and the requested page plus one lookahead. -After selected projections and counts are read, ordinary shadows, permissions, identity, -document versions and recorded chunk serving state are checked again for every retained -copy, including the lookahead. A lost proof drops the whole mirrored leg, so it cannot -leave a stale cursor or reveal a removed row through the page's continuation. - -A token reads as one person, for both the `owner` entry and the emails, or as nobody: - -- a person's own session token (a primary token whose own `sid` claim names a sign-in - session, with no `creator` claim) reads as that person; a token minted for a subject - without one reads as nobody; -- a token minted for one person alone that says so (a `reads_as_creator` claim, which - only the person's own primary first-party sign-in session can mint through - `POST /v1/me/personal_tokens.create`, for the dashboard's own-agent connection flow; - delegation never copies it) reads as its creator; -- the assistant's answer token, delegated from the caller's for that answer alone, - carries a reads-as claim that the bridge sets at delegation to the person the caller's - token reads as, or to nobody, and reads as that; the check never infers it from the - token's `jti` or consumer, and no token delegated from it reads as anyone; -- every other token (a service account made for tools, CI or a team, a bot, an end-user - token, whatever their `creator`) and a request sent on behalf of another person - (`X-Loom-On-Behalf-Of`) reads as nobody, so it sees only `anyone` documents. - -The check fails closed. A stale listing, an `unread` list, an unexpanded or stale group, -a link-only permission, a permission the store marks deleted (its address may now belong -to someone else), a grant to one view of the file only (`view`), and a permission type -or role the sync does not know admit nobody. A missing registry or listing row admits -nobody. A leg whose per-request reads (the statements it issues whatever matched, the -reader's canonical subject and verified emails among them) fail shows no mirrored -document and marks the answer `degraded: mirror_unread`; a read it issues only for -candidates (the lists, the members rows, the heads) that fails drops every mirrored -result without the marker, so the marker says nothing about what matched. Each leg reads -the registry row and the listing row first and then the members rows and the lists, -under `sequential_reads()`, so a lagging replica cannot pair a fresh listing row with an -older list. It computes the addresses the reader may see before its `LIMIT`, so a page -is never cut short by the check, and caches no admitted set. No score depends on a -document the reader may not see: a mirror's chunks add nothing to any corpus statistic -(the lexical leg's document counts, lengths and term frequencies), and a mirror leg -scores its lexical hits with fixed corpus constants, which depend on no document, so a -namespace fed only by mirrored sources still ranks by both legs. Under the Postgres -authority each leg judges the addresses it is about to answer by their heads, so a -narrowing or a retirement committed and not yet published already applies, and a missing -head drops the address; a leg that cannot read the heads shows no mirrored document. The -implementing pull request measures the leg on a mirror of a million documents under both -storage authorities and puts the figures here. - -### Every complete listing reads the lists again - -Every complete listing of a mirrored source reads every file, metadata only (id, -revision, permissions): the store does not change a file's modification time when its -sharing changes, so an incremental listing would miss a permission removed. A listing -that reads a list unlike the stored one rewrites the document's row with the same -content and the new list, as `knowledge.update_metadata` without `reindex` does, so no -chunk or embedding is rebuilt; an unchanged list costs no write. A stored copy behind -its file's revision (a fetch deferred, given up or over the size bound) takes only the -entries both its stored list and the new one hold, since its text was shared under that -list (entry by entry, so a person the stored list admitted only through a domain or -`anyone` is dropped, which fails closed); the content write that brings it up to date -carries the wider one. A behind copy that once reads `unread` stays so until that write. -A stored document the complete listing no longer has is rewritten `unread`, with every -entry cleared, then retired on positive evidence, as today. The listing row's start -lands only once every changed list and every such `unread` rewrite of that listing is -written, so a row is never newer than the lists it vouches for. These rewrites are -outside the pass's document cap; the permission reads they need stop at half of what is -left of the listings' share when a turn starts them, so the turn's new and changed files -still get time. Content is fetched only for a file whose revision changed, and a content -write carries the list of the latest listing that read the file, so a fetch the pass -bound deferred never writes an older list; a listing row lands only once every document -written during that listing carries a list it read. - -A pass runs the listings first, rotating across the mirrored sources, and gives them at -most a third of the time the pass starts work in (a quarter of -`knowledge_source_sync_max_pass_seconds`) and their own document bound, while the -namespace sources then have the rest of the pass under theirs. Mirrored files consume -none of the namespace sources' document bound. Their earlier work can reduce the time -left for namespace writes, so namespace progress can vary under the threat model's -timing exclusion. A listing that does not finish goes on from its cursor in the next -pass, and until it completes the source's listing row keeps its older start, so a large -source needs a stale bound longer than the time to list it all. `inspect` and `loom -doctor` report each source's oldest listing start, a mirrored source's to a platform -admin only (its connected owner sees fresh or stale). A stopped sync hides every -mirrored document once the stale bound passes. The implementing pull request measures -the writes of a crawl over 2000 people and puts the figures here. - -How lists from several accounts of one source, a person a crawl stops reading, a stopped -source's rows, and restores of either store are handled is the implementing pull -request's to specify against these four parts; each must leave no list or row that -admits someone the store no longer names. +Every checked leg requires a supported active source, current connection and +scope, fresh per-document proof and the selected reader policy. Destination +access alone is insufficient. An unbound machine reader cannot borrow an owner's +identity. Retained protected copies from unsupported sources remain unavailable; +old owner, email, group, domain or public entries do not repair missing current +authority. + +Checks apply to search, reads, originals, history, exports, diagnostics, caches +and derived publication. Source replacement is never silently substituted into a +retained read plan. A denied id-addressed read answers as for a missing document. +A missing registry, access proof or required head admits nobody. Under the +Postgres authority a narrowing or retirement already committed in the head +applies before asynchronous publication. + +Search checks permissions before filling the admitted pool or assigning fusion +rank. Denied candidates consume no rank, and admitted content is bound to its +exact address, chunk, version, revision and embedding model. Mirror chunks do not +contribute private corpus statistics to ordinary lexical ranking. A missing exact +content key cannot be replaced with a later version. Final publication retains +and revalidates only the proofs contributing to the selected response. ### Threat model -| Threat | Boundary | Enforced by | -| --------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| A connected person leaks a private file into a team namespace | Every connected source is mirrored; its documents live in the mirror, and a teammate sees one only when the store names them. `access` cannot change. | `add` and `update`; the mirror gate; `test_document_source_leakage.py` | -| A crawl's registrant reads crawled people's private files | No rule admits a source's registrant or owner as such; a registrant reads a file only when the store names them or their own connected account lists it. | the access check | -| An admin points someone's connected account at files they did not choose | Only a connected source's owner adds its items or changes `include`. | `update` | -| A link-only share becomes a search hit for everyone | A permission the store marks not discoverable admits nobody. | the access check | -| A person stops reading a file and Loom keeps showing it (stale ACL) | Every complete listing of a mirrored source reads every file's list and rewrites a changed one; a source whose last complete listing is older than the stale bound admits nobody. | the sync's mirrored listing; the access check | -| A person leaves a group and keeps reading through it (group churn) | Groups are read with every complete listing into a members row with its `read_at`; a stale or unread group admits nobody. | the access check | -| Auth is switched off after mirrors exist | The `acl-` refusal runs before the auth-off return; mirror legs answer nothing and the sync skips mirrored sources while auth is off. | `check_authorized`; the mirror legs | -| A person leaves the org and their connected sources keep syncing | SCIM deactivation and disconnect stop the sources and clear the credential, then revoke it at the store; each turn's owner check skips a source whose owner is revoked, deactivated or no longer a writer. | `server/auth/scim.py`; the sync's turn | -| A crawl reads more than its registrant meant, or can write | An org-wide role to register, update or rotate; the probe requires the store to refuse a write scope; subjects and scopes in the audit row. | the crawl probe; `loom.audit_log` | -| An id-addressed read confirms a mirrored document exists | `get`, `outline`, `download` and the inspects answer `found=false` or leave out an address the reader may not see. | the mirror legs | -| A viewer or admin learns what a mirror holds from an op that is not a checked leg | A source's probe, status and `remove`, and an erasure's receipt, answer codes for a mirror; its counts go to a platform admin only. | the source ops; the erasure handlers | -| A new read path shows mirrored documents to everyone | Mirrored documents live in a namespace no grant opens and no listing names; a path that does not read the mirror shows none, and no org-wide scope names an `acl-` namespace. | `check_authorized` (`acl-[0-9a-f]{24}`); the scope helpers ([the mirror](#the-mirror)) | -| An older build shows mirrored documents | N-1 has no mirror leg, but its org-wide reads return `acl-` rows and so hand out a mirror's name, and its gate admits a wildcard admin token that names it. So no N-1 may serve while a mirror holds rows: the new modes wait for N everywhere, the rollback procedure erases the mirrors with every replica stopped first, and N reports an N-1 heartbeat while a mirror holds rows. An N-1 replica started without that procedure (a bare `helm rollback`) exposes mirror text to an org admin; that residual rests on the procedure. | the rollback procedure; `loom doctor` | -| A mirrored document's text reaches every reader through a derived row | Decision mining and dataset extraction skip mirrored documents; a request that touches a mirror writes nothing derived from it outside the mirror. | the sync; the mark | -| A store account is linked into another person's Loom account, either way | The connection is stored only from the browser that started it, with that subject's own dashboard session and the `state` cookie. A connection's email is never a reader identity. | the connect routes | -| A caller injects store query syntax through a filter | Filters are fields with patterns, escaped and built by the server; no raw query is taken. | `server/clients/gdrive.py` | -| A stolen connected credential changes the store | Only read scopes are accepted; the credential is sealed and never returned. | the connect callback; `server/core/secrets_at_rest.py` | - -Out of scope: response timing, and when a pass reaches the namespace sources, which the -mirrored sources' turns before them delay; a resource limit (memory, rows read) that a -mirror's size can trip on a per-request statement, which like timing depends on how much -the mirror holds; how fast the shared pass gets to a connected owner's own source, which -its fresh or stale code and per-item status reflect; that a namespace erasure is still -retrying, which a namespace admin sees whatever its cause; a worker an orchestrating -agent starts outside a flagged session's process tree; a person who hands their own -`reads_as_creator` token to a team bot or a CI job, which then reads as them; a session -still open from before an operator lifted the refusal that saw mirrored text then; a -reader who already saw a document and kept its text in a record only they read, or one -their agent chose to write or sent in a call it chose (a follow-up `memory.search` whose -terms come from what it read, recorded in a trace log the namespace's viewers read), -which is that reader's write; that a person able to add a file where a mirrored source -lists can tell, by the file never appearing, that the source is over -`LOOM_KNOWLEDGE_SOURCE_MAX_DOCUMENTS`; the store itself reporting a wrong permission -list. +| Threat | Boundary | +| --- | --- | +| A shared destination exposes an owner's private selection | Both policies use protected storage; collection copy requires explicit publication authority and consent. | +| A caller borrows another owner's account | Connection binding and source controls require the current canonical owner. | +| A changed selection borrows old proof | A monotonic scope revision binds each successful read. | +| A stopped or unsupported source exposes retained bytes | Every read needs actual current supported authority. | +| A partial listing removes documents | Only explicit writer-authorized retirement or erasure deletes content. | +| A private result leaks through capture, caches or telemetry | Marked handling, durable session protection and the publication boundary cover the complete request. | +| A read path omits access checks | The mirror is inaccessible to ordinary token scope; a path without a mirror leg reads none of it. | + +These boundaries end at response delivery. Readers and remote hosts control their +own retained copies, requests and conversations. Response timing, resource-limit +side channels and inference from the allowed aggregate spend totals are outside +the noninterference claim. An application must preserve every contributing +session authority across callbacks, tasks, resume and compaction; a separately +started process does not acquire that authority merely by receiving text. ## Meetings through the shared-folder store -Meet transcripts and notes are documents in Drive. A `gdrive` source reads them as -files: a `meet_recordings` item finds the recordings folder in an account's own -Drive, and a `folder` item reads a supplied folder. Folder discovery uses the fixed -table of localized names. When no folder is found, the turn reports -`meet_recordings: not found` without naming an account; a `folder` item with the -folder's link reads it instead. Individual document links use the same source. - -A transcript Doc in the recognized English export layout is tagged -`ingested_format: transcript`. Its elapsed-time headings and speaker paragraphs -are retained unchanged; the document chunker uses those headings for timed -sections and citation context. The export supplies coarse elapsed points, rather -than a start and end time for each speaker turn. Loom does not infer missing -intervals or use the meeting-ended footer as an utterance endpoint. Edited, -untimed or unrecognized layouts, including meeting notes, remain ordinary Docs -with their content preserved. - -The source keeps its existing connected-account and mirrored-access checks. A -folder name, transcript shape or attendee paragraph does not grant access. - -The `recording` source accepts Zoom only. A stored Meet source remains listed and -inspectable, and keeps its configuration and documents. Its `check`, `rotate`, -`sync_now` and `update` operations refuse with `BAD_CONFIG` and direct the caller -to `gdrive`. Its worker turn records `provider_removed`, contributes no pass -failure and preserves the cursor, pending full request and file waits. Removing -the source deletes documents only when requested. No stored configuration is -rewritten to a sentinel, and no native Meet API fallback remains. +Meeting notes and exported transcripts can be selected as documents only when an +approved MCP server exposes a supported text read. A folder name, transcript +shape or attendee paragraph grants no access, and does not expand the selection. +The document extraction and chunking paths retain supported transcript structure; +missing timing intervals are not invented. + +The recording source path is separate. It accepts Zoom (`provider: "zoom"`) +and explicit recording IDs; MCP setup does not replace recording +credentials or make a document server a recording provider. Retained unsupported +recording configurations keep their bytes and history without native fallback. +Explicit removal deletes documents only when requested. ## Project-tracker issues -Feeding a project tracker's issues and comments into the tracker plane is a design of -its own, written in the pull request that builds it, after the items and access pull -requests. That design has to answer what this page found: +Feeding a project tracker's issues and comments into the tracker plane is a +separate design concern. MCP document import does not change its live record contract or create tracker tables. A tracker ingestion design must account +for these boundaries: - The tracker plane reads a team's records live and copies none ([tracker plane](../features/tracker/overview.md)); issues with no team database would be kept @@ -1094,542 +591,195 @@ requests. That design has to answer what this page found: repository; and tracker namespaces belong to `LOOM_TRACKER_ORG` alone. - An issue of a private team, or read through a person's connected account, is private (`is_private = 1`). The contract derives an item's id from `source_id`, which changes - when an issue moves to another team; the design changes the contract to take the - issue's own UUID, so a moved issue keeps its item. + when an issue moves to another team; stable tracker ingestion would need the + issue's own identity so a moved issue keeps its item. ## Surfaces -- **Ops.** `knowledge.source.add` takes `items` or `links`, `credential_mode` and, for - `crawl`, `directory_subject` and `subjects`; `update`, `parse_links`, - `connection.list` and `connection.disconnect` are new (a connection starts in the - dashboard, `POST /v1/connect//start`); `list` and `inspect` show items, modes - and, through the check, the documents each owns. A mirrored source shows its document - counts to nobody but a platform admin (exception 4), apart from what a checked leg - lists to an admitted reader, and a connected source's items only to its owner (an - admin can still remove the source). To a viewer who is neither the owner nor an admin, - a mirrored source shows its kind, its owner as "a connected account" for a connected - one, its item count and its last sync's status, not its items, `config` or - `created_by`; its error text carries codes only, for every viewer. Python and - TypeScript SDKs are regenerated. -- **CLI.** `loom knowledge source add|update|list --namespace --link ...` - (`--credential-file`, `--connected`), `loom connect gdrive|notion|linear`, - `loom connection list|disconnect`, `loom knowledge mirror erase --all` ([restores and - rollback](#rolling-upgrades)), and `loom doctor`'s line for the oldest listing start - of each mirrored source (for a platform admin; a connected owner sees fresh or stale). -- **Dashboard.** The Library's Sources section: paste many links, a preview of what each - resolves to and which could not be read, Check, Add, edit items, the access mode, and - each source's last sync (a mirrored source's status code only). Settings → Connected - accounts: connect, see, disconnect. The repository card keeps its own sources. -- **Agents.** Every op reaches an agent through `loom_op`. The mentor reference gains a - line: handed a store link and asked to bring it in, call `knowledge.source.update` - with `links` on the caller's connected source for that store, or `add` one; with no - connection, `connection.list` answers the dashboard link - `/settings/connected-accounts?kind=` to hand back. +The [setup guide](../guides/mcp-sources.md) describes dashboard selection, access +preview and lifecycle controls. The [CLI guide](../guides/mcp-source-cli.md) owns +exact command and operation mappings, secret-file inputs, trusted session pointers +and request-UUID reconciliation. SDKs use the same authenticated operations and +must implement durable protected-response observation and automatic-write guards. +Protocol compatibility and generated operation methods alone do not qualify a +client application. + +Live lookup reuses the common [live-source search](live-source-search.md) path. +It returns selected content without automatic import or memory save. +[Source push](source-push.md) describes retained registry data and local +maintenance; there is no native callback or renewal runtime. ## Data model -ClickHouse, additive migrations: - -| Table | Key | Holds | -| ---------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `loom.knowledge_sources` (columns) | `(org, namespace, name)` | `source_kind`, `credential_mode` (default `shared`), `access` (default `namespace`), `owner_subject`, `items_json`, `options_json` (a crawl's `directory_subject` and `subjects`), `secret_enc` | -| `loom.knowledge_mirrors` | `(org, namespace, mirror)` | `deleted` (written once a namespace erasure or the mirror-erase command has erased the mirror); at most one live mirror per namespace | -| `loom.knowledge_mirror_latch` | one row | `set_at`: the deployment once had the switch on; the mirror-erase command deletes it last. It stays in ClickHouse and holds no memory content. | -| `loom.documents` (column) | as today; in a mirror `source_uri` is `
    #` | `access_json`: a mirrored document's permission list (`emails`, `owner`, `groups`, `domains`, `anyone`, `unread`); empty elsewhere; under the Postgres authority it rides in the head's `row` jsonb, no migration | -| `loom.knowledge_source_listings` | `(org, namespace, source_id)` | `name`, `started_at` (the start of the source's last complete listing), `version`; `namespace` is the mirror | -| `loom.knowledge_group_members` | `(org, namespace, source_id, group)` | `name`, `members`, `read_at`, `deleted`, `version`; `namespace` is the mirror | -| `loom.connected_accounts` | `(org, subject, kind)` | `connection_id`, `account_id`, `workspace_id`, `account_email_enc`, `scopes`, `credential_enc`, `active`, `refresh_id`, `connected_at`, `disconnected_at`, `version` | - -This is an authentication control registry, keyed by canonical sign-in owner across -namespaces, like the sign-in and revocation registries. It is not a memory-content row: -`namespace`, `agent`, end-user `user_id` and `session_id` would falsely bind one provider -connection to one requesting session or namespace. Source registrations retain their -namespace and worker provenance; account changes use the authenticated actor in audit. -The explicit owner erasure axis covers sealed identity and credential history rather -than guessing a memory `user_id` from the sign-in subject. Auth invokes a required lifecycle -port; the HTTP and CLI composition roots bind its knowledge implementation before -accepting mutations. An unbound process refuses retirement rather than skipping it. - -The account registry seals its optional display email in `account_email_enc`. Its -`workspace_id` distinguishes provider workspaces, `connection_id` fences replacement -and disconnection, and `refresh_id` reserves one rotating refresh. Source rows retain -that exact connection id with their canonical `owner_subject`; `created_by` remains -audit attribution and supplies no credential authority. Indexed mirror discovery retains -an exact source and account generation for each connected source. Preparing and refreshing -a read plan revalidates the owner's standing without refreshing a provider token. The -existing document permission list still decides which readers may see each copy; a -verified reader need not own its source. A replacement source is not added to a retained -plan. Worker publication checks owner and source standing again after extraction and -embedding, before committing documents or a complete listing. - -The browser routes and account operations implement the connection backend. The dashboard -connection page, interactive CLI flow and crawl support require their own integration; -the backend does not implement those surfaces. Connect routes are excluded from HTTP -tracing before request attributes or headers can be captured. - -Account restore cleanup discovers raw account and connected-source history, including -replaced registrations and source-only orphan owners. It stops every proven random -Keeper key under its exact owner lease, queues every historical source id, clears only -matching current registrations, and physically deletes account and source history with -raw residue verification. Ordinary disconnect still refuses another live generation. -The cleanup runs before publication in `loom reconcile` for either restored store. For a -ClickHouse-only deployment, stop every serving process, restore its configured stores, -then run `python dev/restore_connected_accounts.py` and repeat with `--apply`. The script -accepts only the configured deployment and preserves its authority and cell checks; -it does not attach cleanup to the generic loader's arbitrary database or scratch target. -Recent worker activity refuses cleanup. Local completion precedes bounded best-effort -provider revocation outside leases, and revocation failure cannot restore credentials. -Complete the separate mirror-content restore cleanup before serving; account cleanup -alone does not prove every mirror document, chunk, head and original was erased. - -A source N-1 can operate on (`shared`, `access: namespace`, with items today's config -can express) keeps today's columns as they are: `kind`, its credential in -`credential_enc` and its items in `config_json`, which N writes alongside `items_json`. -Every other source (mirrored, `connected`, `crawl`, or with an item today's config -cannot express) is stored with `kind` empty and its kind in `source_kind`, its -credential in `secret_enc` (purpose `knowledge_sources.secret`, which -`loom secrets reseal` covers) and its items in `items_json`, with `credential_enc` empty -and `config_json` `{}`. N reads `source_kind` first and `kind` when it is empty, and -`items_json` first and `config_json` when it is empty ([rolling -upgrades](#rolling-upgrades)). The mirror's documents and chunks live in -`loom.documents` and `loom.chunks` under the mirror's namespace, so the document -machinery (heads under the Postgres authority, deliveries, originals, the blob sweep) -applies unchanged. Each new table is placed in [storage layout](storage-layout.md) by -its placement rule, in the pull request that adds it: `loom.knowledge_mirrors` and -`loom.connected_accounts` are registrations read by key, so they follow -`knowledge_sources` to Postgres in wave 3; the listing and members rows are read by the -mirror legs beside the lists in `loom.documents`, so they stay in ClickHouse. An -implementing pull request that needs another table (for a stopped source's cleanup, or a -crawl's exclusions) adds it with its placement and erasure classification. +MCP connections reuse connected-account storage, canonical-owner lifecycle, +leases and generation fences. Source registrations reuse `knowledge_sources`; +versioned configuration and selected scope remain opaque to builds without +support. Documents, chunks, originals, revisions and accounting use the ordinary +knowledge machinery and configured storage authority. + +The account registry is authentication control data, keyed by canonical owner +rather than a requesting session or destination namespace. Source rows retain +the identity tuple and worker provenance. The authenticated actor supplies audit +attribution; `created_by` is not credential authority. Owner erasure covers sealed +identity and credential history explicitly, rather than guessing a sign-in +subject from `user_id` or an email. Required lifecycle bindings refuse missing +composition instead of skipping cleanup. + +Mirror mappings live in `knowledge_mirrors`. Private access metadata lives with +the document and its authority head. Retained listing, group, push, account and +source history rows remain subject to their existing storage and erasure +classification; retaining a row does not activate native execution or establish +MCP permissions. The deployment's protection latch contains no document content +and is separate from tenant erasure. ## Erasure and audit -What every implementing pull request must hold; each specifies its steps, leases, -statements and census keys against these, and its tests pin each one: - -- Every new table is classified in `server/erasure/store/census.py`, and every table - that can hold a person's address or a document's text is covered by an erasure. -- A namespace erasure, `namespace.delete`, `collection.delete` and `code.repo.remove` - retire the namespace's sources first, clearing their credentials, so no turn writes - back what the erasure took. A `namespace` or `namespace_list` erasure covers each - named namespace's mirrors as more names of the same erasure: a scope that holds a - mirror is erased as a purge, in one pass over the named namespaces and their mirrors, - since no token reads or restores an `acl-` name, and the census counts it the same - way. The last Loom step, `knowledge_mirrors.forget`, writes the mirrors `deleted`, so - the name registered again gets a new mirror; the registry keeps them, so a resume or a - replay after a restore still reaches them. A `user_id` erasure touches no mirror row - (the sync writes them as `-`), and its census and export name none. -- Each namespace step resolves its mirrors once and persists `mirror_marked` in - `loom.erasure_requests` and, under the Postgres authority, `loom.erasure_ledger` - before counting or deleting that scope. Failure-tail verification does the same; - if marking fails it counts nothing. The mark only moves from false to true and - survives registry loss, resume, abandonment and restore replay. A restore promotion - preserves the receipt, checkpoint time and pending-replay fence. Marked checkpoints - use the high bit of their UInt64 version; they supersede stale unmarked writers - even after a merge, while timestamps order marked writes. -- Marked `erasure.request` replies carry codes only for every caller, since the - idempotent answer can be replayed after a role change. `erasure.status` and - `erasure.list` carry codes only unless the current caller is a flat platform admin; - namespace and org admins receive zero counts, empty residue, no census and no - verification timestamp. These placeholders never prove verified absence. Masking - the whole receipt prevents a caller subtracting its namespace's counts to discover - a mirror's size. Ordinary receipts keep their counts. Marked completion and - abandonment audit rows persist no counts. Failed marked receipts and audit rows - answer `ERASURE_FAILED` for every cause and withhold step progress, so a residue - failure reveals no special code or failed stage. Full internal evidence remains - available for recovery and authorized - platform-admin status reads. -- A person's connected accounts, the sources they own with every mirrored copy those - wrote, and their entries in every crawl are erased when an org admin asks; afterwards - no source row, list or members row names them, and a crawl reads them again only once - an org admin readmits them. The pull request that builds connected accounts and crawls - designs that erasure. -- Private canonical-owner cleanup uses the exact `(org, subject, kind)` key independently - of namespace and end-user erasure. Disconnect and deactivation fence the generation, - clear the current credential, queue every owned source for retirement, then physically - delete historical provider identity and credentials. They retain only an empty inactive - canonical-owner marker. SCIM deletion removes that marker too. The canonical-owner - census counts all historical rows, including sealed values; a failed delete, missing - census answer or residue refuses completion. The `user_id` erasure scope continues to - mean an end-user principal and never guesses a sign-in subject from an id or email. - Source retirement remains queued until the existing mirror retirement worker finishes; - account cleanup alone does not certify that every source copy or crawl entry is erased. -- `erasure.request` refuses an `acl-` scope for every caller but a platform admin with - auth on, and `erasure.export` refuses one for every caller (an export would read the - mirror's chunks with no permission check); with auth off both refuse it for everyone. -- Audit rows: `add`, `update`, `rotate`, `remove`, `sync_now` as today, plus `update`'s - item changes; `connect` and `disconnect` (subject, kind, scopes, never a credential); - a crawl's subjects (as keyed hashes), granted scopes and member count; a SCIM-driven - stop names the sources it stopped. +- Every table that can hold memory content, document identities or private + account material has an explicit erasure classification. MCP uses existing + knowledge, original, revision, index and accounting cleanup paths. +- Namespace retirement fences source writes before erasure. Namespace erasure + covers its mirrors as a purge. The mirror registry is marked deleted only after + content cleanup, so a replay or restore still reaches retained mirror names. + A later namespace registration gets a separate mirror. +- Each namespace step persists its monotonic `mirror_marked` receipt before + counting or deleting mirror scope. Failure to mark counts nothing. Registry + loss, resume and restore cannot downgrade that receipt. Restore promotion + preserves its checkpoint and replay fences. Marked checkpoints use the high bit + of their UInt64 version to supersede stale unmarked writers; timestamps order + marked writes. +- Marked erasure replies expose codes only unless the current caller has the + existing flat platform-admin diagnostic authority. Ordinary readers receive no + mirror count, residue, census or verification timestamp. Placeholder fields + never prove verified absence. Marked audit rows omit counts, and failed marked + receipts withhold stage details and private failure prose. +- End-user `user_id` erasure and canonical-owner cleanup are distinct axes. + Owner cleanup uses exact account identity and generation fences. Erasure must + verify historical identity and sealed credential residue; account cleanup + alone does not certify that every source copy or original is gone. +- No token reads or exports a mirror directly. `erasure.request` accepts a mirror + name only from a platform admin with authentication on; `erasure.export` + refuses it for every caller. +- Audit preserves authenticated actors and lifecycle decisions without credentials, + selected private identities or content. Source pause, disconnect, schema refusal + and upgrade are not erasure requests. Explicit remove with `delete_documents` + requests copy retirement; without it retained copies remain subject to current + access and ordinary retention policy. ## Rolling upgrades -- **Clients.** A client built before `mirrored: true` declares nothing, so a mirror leg - answers it nothing until it is upgraded, and [the refusal](#the-session-rule) refuses - its session-content ops; a third-party MCP client is refused the same way. Mirrored - sources stay off (`LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED`) until the operator has - rolled out the plugins, CLI, SDKs and hooks that honour the flag. -- **N-1 cannot operate on a source it must not.** N-1 reads `kind`, unseals - `credential_enc` and reads `config_json`, and knows none of the new columns. A source - stored with `kind` empty is one N-1 cannot use: its `check`, `rotate` and sync turn - fail before any request and retire nothing, and N-1 syncs only sources on a trunk - namespace. -- **The new modes wait for N everywhere.** `add` and `update` answer 503 `OVERLOADED` - (`retry_after_s`) for a source stored with `kind` empty while any live process of any - deployment on the ClickHouse service reports a schema version below the migration that - adds the columns, or no heartbeat has been read, as rule 24 does for namespace guides - ([rolling upgrades](rolling-upgrades.md)). -- **Rollback and restores.** N-1 has no mirror leg, but its gate admits a wildcard admin - token that names a mirror, its org-wide reads (insights, usage, cost, the analytics - export) include `acl-` rows, and nothing on N-1 ages the lists. N reports the - condition (`loom doctor`, and the schema heartbeat check above) when a process below - the mirror migration heartbeats while `loom.knowledge_mirrors` holds a live mirror - (one not written `deleted`), as a rolling rollback (a Helm rollback included) would - start one. So the rollback procedure ([upgrades](../operations/upgrades.md)) stops - every replica, stops every mirrored source and erases every mirror - (`loom knowledge mirror erase --all`) before any N-1 replica starts. A restore of - either store runs the same command before the deployment starts, since a restored copy - cannot be trusted to say who may read; owners connect and add their sources again. The - implementing pull request adds both steps and specifies the command. -- **Ownership.** In a namespace, one owner per address, found by its tag, is today's - model, so N-1 and N agree on whose a document is; N-1 has no mirror leg. -- **Lists.** N-1 never meets a list: the build that adds the column writes none and - carries none forward, and the first build that writes one runs beside it (rule 53). -- **`meet`.** N-1 still syncs a stored `meet` source on its turns; N skips it. -- **Erasure.** N-1's erasure misses the mirror and the new tables (rule 14): run again - with N every erasure completed while an N-1 replica served. - -Each implementing pull request adds its rule to [rolling upgrades](rolling-upgrades.md), -and pins this section's N-1 behaviour with a test that runs today's `check`, `rotate`, -`remove` and sync turn over a row N wrote with `kind` empty. +Lifecycle preparation adds version and slot fields without converting existing +registrations. The MCP admission migration establishes a fleet code floor without +changing stored data or schema objects. Admission and current connection checks +require the whole live fleet to advertise that floor; unreadable fleet state +refuses. Neither migration activates connections, approves profiles, transfers +consent or deletes upgrade data. See the +[MCP cutover contract](mcp-document-sources.md#rolling-upgrades-and-operator-cutover) +and [rolling upgrades](rolling-upgrades.md). + +Native document-source registrations remain retained and unavailable in this +build. Credentials, configuration, documents, originals, history, uploads and +checkpoints are not converted, reused or removed as upgrade cleanup. Existing +ordinary published copies keep namespace access and erasure rules. Retained +protected mirrors require actual current supported authority and stay unavailable +when their source is unsupported. Rollback does not translate MCP registrations +into native sources. + +Restore still requires the documented account-authority and mirror-content +reconciliation before serving. Explicit mirror cleanup uses +`loom knowledge mirror erase --all` under the stopped-fleet procedure; it refuses +while a live process reports mirrors enabled. It covers orphan reserved mirror +namespaces across the stores, then removes the deployment latch last. A restored access row alone is not trusted current +authority. The explicit mirror cleanup procedure and deployment protection remain +separate from routine upgrades; migration is never a request to erase mirrors. +Follow [backup and recovery](../operations/backup-and-recovery.md) and the +[upgrade procedure](../operations/upgrades.md) for the supported restore boundary. ## Breaks -- Mirrored sources need `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED`, which an operator - sets once every Loom client and hook honours `mirrored: true`. -- While [the refusal](#the-session-rule) holds, every session-content op, the hook-sent - reads included (`context.pack`, `code.search`, `code.impact`, `memory.for_file`, - `namespace.validate`), refuses a client that does not declare `mirrored: true` in - every org: an SDK app that has not opted in, and a third-party MCP client, which - cannot. -- `recording` sources lose the `meet` provider. -- The gate of `add`, `update`, `check`, `sync_now` and `remove` takes `writer`, with - `admin` checked by the handler for shared and crawl sources; `rotate` is refused for a - connected source. +Native document-source setup, execution, source update/link parsing, provider +OAuth routes and native settings are removed. There is no provider fallback or +legacy execution shim. Owners need an approved MCP endpoint, fresh account +binding, selection and access preview. Recording, model providers, tracker and +code integrations keep their separate contracts. + +Protected reads require actual participating clients. Session-content operations +continue to refuse clients without the durable protection protocol while the +[deployment refusal](#the-session-rule) applies. A sent header or generated SDK +method is insufficient evidence of application readiness. ## Settings -| Setting | Default | Meaning | -| ---------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------ | -| `LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS` | 3600 | a source's listing or group members row older than this admits nobody | -| `LOOM_KNOWLEDGE_SOURCE_MAX_DOCUMENTS` | 50000 | a source's stored documents plus the new ones a turn writes, at most 200,000; at it a turn tries no new file | -| `LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_PERSON` | 8 | a person's connected sources in one namespace | -| `LOOM_KNOWLEDGE_CONNECTED_SOURCES_MAX_PER_NAMESPACE` | 64 | a namespace's connected sources | -| `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED` | false | mirrored sources may be added; set once every Loom client and hook honours `mirrored: true` | -| `LOOM_KNOWLEDGE_SOURCE_MIRROR_DOCUMENTS_PER_PASS` | 40 | documents a pass fetches, writes and retires for mirrored sources, apart from the namespace sources' bound | -| `LOOM_CONNECT_GDRIVE_CLIENT_ID`, `_SECRET` | unset | the shared-folder store's OAuth client; unset, those connections are off | -| `LOOM_CONNECT_NOTION_CLIENT_ID`, `_SECRET` | unset | the page store's public integration | -| `LOOM_CONNECT_LINEAR_CLIENT_ID`, `_SECRET` | unset | the project tracker's OAuth application | - -The redirect URI to register with each store is -`/v1/connect//callback`. +Use the generated [configuration reference](../reference/configuration.md) for +available settings and defaults. MCP requires authentication and +`LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED`; enrollment also requires +`LOOM_KNOWLEDGE_SOURCE_SELF_SERVICE_ENABLED`. Stored-copy execution requires +`LOOM_KNOWLEDGE_SOURCE_SYNC_ENABLED`. The existing +`LOOM_KNOWLEDGE_SOURCE_ACL_STALE_SECONDS` bounds successful-read freshness; its +name does not imply MCP ACL synchronization. Approved profiles and bounded +scheduler configuration are described in the +[MCP architecture](mcp-document-sources.md). ## Rejected -- **Mirrored documents in the namespace itself, filtered by every read.** A missed path - would show the document to every reader. The list sits on the document only inside the - mirror, which no token opens. -- **A namespace per permission list.** A list changes with every share, which would move - the document, its chunks and embeddings on each change. -- **A mirror name derived from the namespace.** Anyone could compute it, and a known - name makes every error and refusal about it a probe. -- **A permission list per reading account within a source.** An account that read the - list before a reader was removed would keep admitting them until its row aged out. - Across sources each copy keeps its own list, bounded by the stale bound and dropped at - its own source's next listing. -- **Resolving the store's groups through Loom's SCIM groups.** They hold a service's end - users (`user:`), not people's emails. -- **A separate meeting-store path.** The meeting store already saves transcripts and - notes to the shared-folder store, with the participants' permissions. -- **`drive.file` with the picker.** It cannot read a folder's later files. -- **Incremental listings for mirrored sources.** A sharing change does not move a file's - modification time. +- Putting protected documents in the ordinary namespace would make one missed + read check disclose them. A separate mirror makes absence the default. +- Deriving mirror names from namespace names would turn predictable names into + probes. Mirrors use random reserved names. +- Inferring permissions from server descriptions, tool hints or missing ACLs + would grant authority without evidence. Approval, selection and reader policy + are explicit. +- Treating an incomplete catalog as deletion evidence would remove content the + writer never asked to delete. +- Reusing native credentials or translating registrations would transfer account + consent without an owner-approved MCP binding. ## Invariants -- A mirrored document is read only through a leg that applies the permission check; no - token reads or exports a mirror, and `erasure.request` takes a mirror's name only from - a platform admin, with auth on. -- Every `crawl` and `connected` source is mirrored. -- Every permission the sync cannot trust admits nobody, and so does an `unread` list - ([who may read](#who-may-read)). -- Every complete listing of a mirrored source reads every file's list again, and only a - complete listing's start vouches for the lists. -- No caller-supplied host or query string reaches a store. -- A connected source stops on every path that ends its connection or its owner's - standing ([connected accounts](#connected-accounts)), and its mirrored documents go - with it. -- Nothing derived from a mirrored document leaves the mirror except as the four - exceptions allow, and no mirrored source exists until - `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED` is set. -- N-1 never operates on a source it cannot honour: such a source is stored with `kind` - empty. +- Only checked legs read protected copies; no token scope opens a mirror. +- Every returned protected copy has current source, connection, scope and + per-document authority, rechecked at final publication. +- A shared destination does not publish private content without explicit copy + authority and consent. +- A source rewrites only its own copies. Replacement names confer no ownership. +- Nothing derived from protected content leaves its boundary except through the + checked answer and documented accounting/diagnostic exceptions. +- Live retrieval imports nothing and saves no memory automatically. +- Unsupported sources and stale proof refuse access while retaining bytes. +- Only writer-authorized retirement or erasure deletes content; migrations and + incomplete remote results authorize neither. ## Source entry points -- `server/knowledge/domain/sources.py`: kinds, configs, items. -- `server/knowledge/domain/source_links.py`: the link parser. -- `server/knowledge/app/sources.py`: the ops. -- `server/knowledge/app/source_sync.py` and its kind modules: the sync. -- `server/knowledge/app/source_access.py`: the permission check and the mirror legs. -- `server/knowledge/app/connection_routes.py`: the browser consent routes. -- `server/clients/gdrive.py`, `notion.py`, `linear.py`, `recording.py`: the stores. -- `server/clients/connected_oauth.py` (`OAuthClient`): fixed-provider consent, code - exchange, refresh, account metadata and revocation requests. Calls share the caller's - deadline, cap response bodies, refuse redirects and never retry. The caller consumes - browser-bound state before exchange, authorizes the Loom owner/source and commits - refresh generations; this HTTP helper neither supplies nor bypasses those checks. +- `server/knowledge/app/mcp_connections.py` and `mcp_source_sessions.py`: current + connection binding and observed schema refusal. +- `server/knowledge/app/mcp_sources.py` and `mcp_source_controls.py`: preview, + selected scope, lifecycle controls and reconciliation. +- `server/clients/mcp_source.py`: bounded official SDK protocol calls. +- `server/knowledge/app/source_sync_mcp.py`, `mcp_source_worker.py` and + `source_sync.py`: selected reads, scheduling and common knowledge writes. +- `server/knowledge/app/source_access.py`: current copy authority and mirror legs. +- `server/knowledge/app/sources.py`: recording and retained-source lifecycle. ## Tests -Each implementing pull request lists its own; these pin the model: - -- Unit: - - Items, links and the sources' ops: - - The link parser on every link form and every unreadable one. - - Item validation. - - The query builder escaping every field. - - A non-owner admin's `list` and `inspect` of a connected source showing `config` - `{}`. - - A connected source's items, and its document counts beyond those a checked leg - lists to that admin when admitted, hidden from an admin who is not its owner; a - non-owner admin's `check` of a connected source answering no item ids. - - A failed read of the reader's canonical subject or emails giving the same marker - whether or not a candidate exists. - - A mirrored source's probe (`check`, and the `add`, `update` and `rotate` probes, - by a non-owner admin and a crawl registrant), status, `remove` answer and a - namespace erasure's receipt carrying no count, title, file id or address of what - the mirror holds. - - A crawl `update` probe by any caller answering the same code whether or not the - file exists. - - A crawl's status carrying no `item ` code and no `meet_recordings: not found`. - - A non-owner admin's `remove` of mirrored sources of 10 and 10,000 documents - leaving the same request-side figures. - - `add` of a removed mirrored source's name answering as for a fresh name. - - A mirrored `add` during an open namespace erasure refused with `ERASURE_RUNNING`. - - The mixed-version refusal, and N-1's `check`, `rotate`, `remove` and sync turn - over a row N wrote with `kind` empty. - - A crawl `update` by an `admin` with an org-wide role who is not the registrant, - adding a `file` or `filter` item, accepted whether or not any crawled person can - read it. - - The mirror and its gate: - - The `acl-` gate in `check_authorized` and `CachedGate`, with auth on and off, and - for a platform admin on a read op. - - `namespace.register` and `namespace.restore` refusing the form. - - `erasure.request` and `erasure.export` refusing an `acl-` scope with auth on and - off. - - `row_reach` and `audit.list` refusing an `acl-` name with auth off. - - `row_reach`, `row_in_scope` and `namespace_for_id` opening nothing of a mirror - with auth off. - - `erasure.list` and `erasure.status` treating an `acl-`-scoped saga as not found - for an org admin. - - `erasure.status` and `erasure.list` by a viewer, and a saga that fails on mirror - residue, showing no mirror count. - - `resolve_org_scope` with auth off, `every_namespace_scope`, - `rollup_member_namespaces`, `sql_v1_agent_events` under a `*` grant and the - analytics export leaving out every `acl-` name. - - The insights agents and cost reads leaving `acl-` names out. - - `audit.list` after a connected `add`, by an admin who is not the owner, showing no - item id other than its keyed hash. - - `erasure.export` and a `user_id` erasure's census naming no `acl-` row. - - No row carrying a reader's `user_id` under an `acl-` name after an admitted - reader's `get`, `search` and `ask`. - - An erased namespace's name registered again with a new mirror. - - N reporting a below-schema heartbeat while a mirror holds rows. - - The list and who may read: - - The access check on fresh and stale listings, `unread`, group, stale group, - domain, link-only, anyone and unknown permissions, and for a delegated token, a - bot and an end-user token. - - An email-shaped subject with no verified directory email, and an inheriting - service account, seeing no `emails` document. - - A group matched only through the owning source's members row. - - A connected source's unreadable-list entry admitting the owner through the list's - `owner` entry, never an email or the connection's store email. - - A crawl `file` item of a link-only file admitting no crawled person. - - A verified email at a domain without the identity provider's domain claim refused - a `domains` document. - - A crawled person who opened a link-only file only through its link not admitted. - - A deactivated team member admitted by no `linear` list. - - Against an `emails` document: a person's own session token and a - `reads_as_creator` agent token admitted, a Settings-made service-account token - (with `creator`), a delegated child of a `reads_as_creator` token other than the - assistant's answer token, and a request on behalf of another person not. - - A permission the store marks deleted, whose address now belongs to another - verified user, admitting nobody. - - An answer token delegated from the listed person's session token admitted, an - answer token delegated from a `reads_as_creator` token admitted as its creator, - and a token delegated from an answer token refused. - - An assistant answer token delegated from a Settings-made service-account token - refused an `emails` document. - - A token with consumer `loom-assistant` and an `assistant-answer-` id but no - reads-as claim reading as nobody. - - A caller of `assistant.ask`, `loom_assistant_ask` or the chat route that does not - declare the flag getting no mirrored text; an `assistant.ask` and a chat-route - answer on a namespace with an active mirrored source and no admitted item - answering `mirrored: true`, the chat route in its stream's first event and, - unstreamed, in its response's first field; a plugin session flagged once its - `loom_assistant_ask` answer carries the flag; a marked `assistant.ask` and - chat-route row folded and masked like a marked tool-call row. - - A `knowledge.search`, `context.pack` and `memory.ask` on a namespace with an - active mirrored source and no admitted item answering `mirrored: true` as the - first field; the same reads after the last mirrored source is removed, and while - the only one listed is inactive (its owner gone, its cleanup pending), answering - no flag and running no mirror leg. - - A marked `memory.ask` whose candidates are all hidden making the same model and - embedding calls as one with no candidates. - - A caller admitted to nothing seeing the same `cost.budget_status` change over 10 - and over 10,000 hidden matching documents. - - A file another mirrored source holds, added by a second source, written as that - source's own copy with its own list, so the adder sees what they would with no - other source. - - A hidden mirrored chunk holding the query term leaving an admitted hit's - `lexical_score` and rank unchanged. - - A namespace whose documents are all mirrored ranking by both legs. - - The check fails closed: - - A leg that cannot read the listing row or the owning source's registry row showing - no mirrored document, marked `degraded: mirror_unread`, and one that cannot read - the lists, the members rows or the heads dropping mirrored results without the - marker. - - The same `degraded` marker for a query that matches a hidden document and one that - matches nothing while a mirror read fails. - - A failed list, members or heads read with one hidden candidate answering exactly - as a query with no candidate: no marker. - - A leg on a lagging replica that sees a fresh listing row and an older list - admitting nobody. - - A document missing from a complete listing admitting nobody once its listing row - lands. - - A stopped source's documents admitting nobody before their retirement. - - Every complete listing reads the lists again: - - A turn that finds a narrowed list rewriting the row without rebuilding a chunk, - and one that finds the same list writing nothing. - - A listing row landing only after its changed lists. - - A fetch the pass bound deferred writing no list older than the listing row that - lands after it. - - After a person's erasure, no source's next turn writing a list or members row that - names them. - - A namespace source's per-pass progress unchanged by a mirror's size. - - A large removal leaving another mirrored source's content fetches unchanged. - - A mirror's originals surviving a blob sweep and its chunks re-embedded after a - model change. - - The rule and its exceptions: - - Two readers of one namespace, one admitted to a mirrored document, through the - repository-docs listing cache and `memory.ask`'s precedent fast path: the other - gets none of it. - - A request a mirror leg answered keeping no argument or result-side field the leg - shaped in its `agent_events` row. - - A marked request's trace and exposure rows unchanged by a hidden mirrored hit. - - A follow-up query a mirror leg shaped leaving the embedding cache untouched. - - A generation over a mirrored chunk capturing no text. - - The sync's audit rows, status, pass notes and log lines naming no mirrored file id - or address. - - No reader but a platform admin reading the work figures on a marked row. - - A viewer's cost or insights read showing no per-request token spend of another - person's marked request. - - A viewer's `cost.summary` grouped by `user_id` and `operation` showing no single - marked request's tokens. - - `cost.budget_status` and `cost.summary` by a viewer reading the same before and - after a mirrored sync pass. - - A namespace-scoped SQL user reading `sql_v1_agent_events` and - `sql_v1_usage_daily`, and the analytics export's `usage` rows, after another - person's marked request, finding its spend and work only as the fold and the mask - allow. - - A mirrored source's document counts shown to nobody but a platform admin. - - `knowledge.reads` after an admitted reader's `knowledge.get` of a mirrored address - not naming it, nor a namespace document's address read in the same marked - request. - - The dashboard's `knowledge.get` and the assistant's `memory.ask` of an admitted - mirrored document answered with `mirrored: true`. - - A later turn of a session that saw `mirrored: true` not captured, and a client - that does not declare the flag answered nothing by a mirror leg. - - A capture hook recording no turn whose answer carries `mirrored: true`. - - A plugin session over a collection with an active mirrored source and no admitted - hit flagged all the same, its next turn not captured. - - `loom` CLI output holding an admitted mirrored item, and a subagent's mirror read, - not captured into the parent session. - - A `loom` CLI run through a shell and a prompt-recall injection carrying - `mirrored: true` stopping every hook of the session. - - The CLI's `ingest-transcript` refusing a transcript that carries the flag. - - A dashboard view of an answer carrying `mirrored: true`, with or without an - admitted item, sending no `ui.vitals`. - - A forked or resumed session not captured after its parent saw the flag. - - One test over every op the registry classifies as session content, each refusing a - client that does not declare the flag from the first time - `LOOM_KNOWLEDGE_MIRRORED_SOURCES_ENABLED` is set until it is off again and the - mirror-erase command has run, in every org, with the switch on and off; and a test - that collects every op the shipped hooks, their shared library and the CLI send - without the agent choosing the content and asserts each is classed as session - content. - - A session with clients holding tokens for two orgs, one reading a mirror, - capturing nothing into the other. - - The session-content refusal holding once the switch was set with no mirror yet, - when the deployment row cannot be read and on a replica whose view lags it, and - lifting only once the switch is off and the mirror-erase command has deleted the - row. - - A mirror-erase run with the switch still on refused, a restore that loses the - deployment row, and a mirrored `add` after either, with the refusal still holding. - - A viewer's `insights.query` over `analysis_agent_events` after another person's marked - request finding its tokens, cost, `model` and outcome fields only as the mask - allows, the caller's own rows included. - - A caller admitted to nothing seeing no work figure on its own marked row over a - mirror of 10 and of 10,000 hidden documents. - - A checked leg's every answer field unchanged by a hidden mirrored document. - - The mirror-erase command cut short after deleting mirrors but before the latch - row, with the refusal still holding. - - An assistant memory citation from a marked `memory.ask` returned `unchecked`. - - A viewer's `cost.budget_status` read before and after another person's marked - request differing only by that request's folded spend, as exception 2 accepts. - - The folded per-namespace-day row's `errors` count unchanged by a marked request - that fails in the model call. - - The session-content refusal of a hook-sent `context.pack` from a client that does - not declare the flag. - - An admitted mirrored item in `context.pack` writing no recall credit or exposure - row. - - A later `ingest-transcript` of a session flagged only by inheritance refused from - an unflagged shell. - - A session started from a flagged session's process (`claude -p` through its shell) - flagged through the inherited marker, and a hook's `code.search` and - `context.pack` sending nothing after the flag. - - The owner's `reads_as_creator` token admitted to the owner-only list of a - connected source; an on-behalf request for the owner and a token minted for the - owner's subject without `sid` refused. - - A `claude -p` child that read a mirror flagging its parent session, whose hooks - then send nothing. - - A namespace copy winning a dedupe carrying only its own chunks and scores; a - reader only the namespace copy admits keeping it; a reader whose query matches - only the mirror copy's revision getting that hit with `mirrored: true`. - - A restore that drops a `loom.knowledge_mirrors` row while `acl-` rows stay in the - documents, chunks, heads and bucket, then `loom knowledge mirror erase --all` - deleting every one of them before the latch. - - A non-owner admin's `sync_now` on a mirrored source with a refused item answering - as on a clean source. -- Integration: `tests/integration/test_document_source_leakage.py`, beside - `test_cross_principal_leakage.py`: for every leg with the check and every id-addressed - op, a reader the list leaves out sees no mirrored document, its title, its address, - its count or its existence, through the legs, `knowledge.reads`, `audit.list`, the - org-wide rollups or a source's status (an admin who is not the owner included), under - both storage authorities; a reader the list names sees it; a reader removed from the - store's list stops seeing it after the next listing of every source that holds a copy; - one mirrored source's retirement leaving another source's copy of the same address - readable; a `shared` mirrored source's status, read by a viewer no list names, showing - no per-file code. -- Integration: a `connected` source is mirrored wherever it writes; a SCIM deactivation - and a disconnect stop the person's sources and retire their mirrored documents; - `namespace.delete` and `collection.delete` retire the namespace's sources and clear - their credentials. +Generic protected-result checks cover mirror isolation, exact content versions, +current authority, private diagnostics, session inheritance, cancellation, +accounting-before-publication and erasure receipt masking. MCP qualification must +also exercise selected-resource reads, scope changes, stale proof, schema refusal, +immutable audiences and unavailable retained sources under each supported storage +authority. Authored cases alone establish no qualification result. + +The [qualification boundaries](mcp-document-sources.md#qualification-boundaries) +distinguish synthetic resource and mapped-tool tests from external server, +transport and client qualification. Exact-head hosted receipts are required for +actual results; no complete-listing, upstream-ACL or deletion guarantee follows +from protocol tests. ## Related -- [Knowledge: document sources](../features/knowledge.md#document-sources) +- [MCP document sources](mcp-document-sources.md) +- [Source setup](../guides/mcp-sources.md) +- [Source CLI](../guides/mcp-source-cli.md) - [Document extraction](document-extraction.md) - [Security](security.md) - [Sharing knowledge](sharing.md) diff --git a/docs/architecture/live-source-search.md b/docs/architecture/live-source-search.md index 3fb43230c0..68ede6e28f 100644 --- a/docs/architecture/live-source-search.md +++ b/docs/architecture/live-source-search.md @@ -1,73 +1,97 @@ # Live connected-source search -`search.query(live=true)` adds an ephemeral section from the asker's own connected -Drive and Notion registrations. The default is false. Indexed retrieval, ranking, -withholding and paging keep their existing paths; provider results join only the -final response. No provider result becomes an indexed hit or an ingestion request. +`search.query(live=true)` adds an ephemeral section from the asker's own approved +MCP source registrations in live mode. The default is false. The common +`live_search` path retains indexed retrieval, ranking, withholding and paging; +selected remote results join only the final response. Live retrieval never +imports a document or saves a memory automatically. ## Authority and publication -The leg requires authenticated operation, mirrored sources enabled, the caller's -existing session-protection promise, a bound request work bag and an active -required request tail. It marks the logical request and HTTP owner before private -account discovery. Account and provider work runs under private diagnostics. A -mark classifies the whole response, including an attempted read that times out; -it does not establish a client protection promise. - -The canonical requester selects only active connected registrations in the -search's authorized content namespaces. Shared ingestion credentials and another -person's registrations are excluded. The connected-account resolver checks the -selected source identifier and retains its account generation, owner, corpus and -requester. Provider authorization uses its checked access object, without exposing -credential material to response assembly. - -Each selected hit retains its original authority and native corpus membership. -Both are checked before assembly and through the existing request-tail publication -barrier after accounting. Revocation, source replacement, moved items or expired -evidence cannot authorize replacement results. A failed final publication check -refuses the response before its private bytes are sent. These are current read -checks, not an atomic lock on a remote document. +The leg requires authentication, mirrored sources enabled, the caller's supported +session-protection promise, a bound request work bag and an active required +request tail. It marks the logical request and HTTP owner before private account +discovery. Account and remote work runs under private diagnostics. A mark +classifies the whole response, including an attempted read that times out; it +does not establish client readiness. -## Work bounds and coverage +The canonical requester selects only active, owner-bound MCP registrations in +live mode within the search's authorized namespaces. Another person's connection +and retained unsupported native sources are excluded. Current account generation, +owner standing, approved profile, source scope and destination authority remain +required throughout the read. A destination grant does not borrow an owner's +connection. + +Each returned hit retains its exact selected resource identity and successful-read +receipt. Final checks rediscover the approved capability and re-read retained +resources, comparing their content digest and title. A changed source, connection, +selection or resource cannot authorize replacement text. The common request-tail +publication barrier retains these checks after required accounting and refuses +unchecked private bytes at delivery. These checks are current observations, not +an atomic lock on a remote document. -One five-second deadline covers account discovery, credential checkout, native -search and final assembly. The leg considers at most three eligible registrations -in namespace/name order and returns at most ten hits in total. Each provider -response is capped at the smaller of 256 KiB and the configured source response -limit. There are no retries or pagination. +An optional live contribution that fails before selection is omitted, leaving +indexed sections available. Once a selected response frame retains private +contributions, a failed final publication check refuses that frame before its +private bytes are sent. -The `knowledge_live_search_*` settings can reduce the deadline, registration and -hit counts, response bytes, Drive item count and Notion ancestor count. Their -defaults are these ceilings; configuration cannot increase them. +## Work bounds and coverage -Drive uses native full-text search constrained to registered folders, shared -drives or filters. At most four source items are searched. Folder searches cover -direct children even when a registration permits recursive ingestion; explicit -file items have no native file-id search predicate and do not widen the search. -Notion uses native title search and accepts pages only after checking registered -page or database membership, following at most three ancestors. Incomplete -coverage is not evidence that a document does not exist. +One common deadline covers discovery, connection admission, mapped search, +selected reads and assembly. The existing `knowledge_live_search_*` settings +bound the deadline, eligible registration count, hit count and response bytes. +Trusted MCP profile bounds also constrain protocol calls, pages, content bytes +and work. Configuration grants no wider selection or additional operation. + +A live search needs an approved declarative search mapping and a supported read +capability. It reads one bounded search page, intersects returned identities with +the saved selection, drops duplicates and reads each admitted resource before +returning content. A resource-only server can support direct selected reads +without offering mapped search. Browse and search windows are not complete +catalogs; there is no recursive expansion, inferred upstream ACL or deletion +claim. Missing hits never authorize content retirement. Live search runs only on the first page, without tags, for queries of at most -1,000 characters. It ignores memory retrieval recipes. An unavailable or timed-out -leg contributes no live section and leaves indexed sections unchanged. Cancellation -or failure of indexed search cancels and joins its owned live task. +1,000 characters. It ignores memory retrieval recipes. An unavailable or +timed-out optional leg contributes no live section. Cancellation or failure of +indexed search cancels and joins its owned live task. There is no native provider +execution or OAuth fallback. ## Content boundary -The separate `live` section contains bounded identifiers, titles, URLs, provider -names and optional excerpts, with `live=true` on the section and each hit. -`bodies=none` omits excerpts. HTTP, SDK and MCP responses retain the existing -server-owned mirrored classification and protected-client handling. +The separate `live` section contains bounded identifiers, titles, local source-copy +citations and optional excerpts, with `live=true` on the section and each hit. +Those citations identify the registration and exact selected resource; they are +not upstream URLs or fetch targets. `bodies=none` omits excerpts. HTTP, SDK and MCP +responses retain server-owned mirrored classification and protected-client +handling. -Provider data does not enter indexed rankers, search traces, page tokens, served +Remote data does not enter indexed rankers, search traces, page tokens, served memory keys, gap contributions, learnings, snapshots, offloads or model prompts. -A live answer suppresses the unanswered-query contribution explicitly. Existing -numeric private request accounting remains required; it contains no live result -identifier, URL, title or content. The operation remains a read, so response replay -storage is not enabled. This path creates no table, stored content or erasure -substrate. - -Connected-account authority and deployment protection follow -[document sources](document-sources.md). The user-visible response contract is in -[unified search](../features/unified-search.md). +A live answer suppresses the unanswered-query contribution explicitly. Required +numeric private request accounting contains no result identity, citation, title +or content. The operation remains a read without response replay storage. This +path creates no persistent live-result cache, stored content or erasure substrate. +Remote hosts and participating clients retain their own requests and conversations +under their respective policies. + +## Source entry points + +- `server/knowledge/app/live_search.py`: common selection, deadline and publication. +- `server/knowledge/app/mcp_live.py`: approved mapped search, selected reads and + retained resource checks. +- `server/knowledge/app/mcp_source_sessions.py`: checked connection sessions and + observed schema refusal. + +## Invariants + +A live hit belongs to the current saved selection and is read before publication. +No model argument widens approval, account or selection. Final protected +publication applies to the entire selected response frame. Live lookup creates no +import, automatic memory write or deletion evidence. + +Connection and deployment protection follow +[MCP document sources](mcp-document-sources.md) and the generic +[document-source boundary](document-sources.md). The user-visible response contract +is in [unified search](../features/unified-search.md). Synthetic protocol tests do +not qualify an external service or every client application. diff --git a/docs/architecture/source-push.md b/docs/architecture/source-push.md index 3114dcae55..28d0f8572a 100644 --- a/docs/architecture/source-push.md +++ b/docs/architecture/source-push.md @@ -1,130 +1,55 @@ -# Document source push notifications +# Retained document-source push state -Needs `LOOM_KNOWLEDGE_SOURCE_PUSH_ENABLED=true` to request document source syncs -from provider notifications. Notifications never write document content or change -the source's access policy. The normal 15-minute poll remains enabled and is the -recovery path for missed deliveries. Disabling push pauses setup, deliveries and -renewal without preventing secret resealing or setup retirement. - -## Source entry points - -- `server/knowledge/api/ops_source_push.py` (`OPERATIONS`) declares admin setup, - confirmation and status operations. -- `server/knowledge/app/source_push_routes.py` (`notification`) bounds callback - bodies and dispatches provider deliveries. -- `server/knowledge/app/source_push.py` (`receive`, `_fresh`, `_put`, `renew_drive`, - `reseal_registry`) authenticates hints and coordinates registry lifecycle writes. -- `server/knowledge/domain/source_push.py` (`fingerprint`, `verify_drive`, - `verify_notion`, `verify_linear`) binds setup and verifies provider proof; - `server/knowledge/store/source_push.py` (`get`, `put`) persists registry versions. -- `server/knowledge/app/sources.py` (`sources_lease`, `deactivate_namespace_sources`) - coordinates source lifecycle changes; - `server/erasure/store/steps_ledgers.py` (`delete_source_push_by_namespace`) settles - registry erasure. - -## Invariants - -- Authenticated deliveries request sync through the existing source path. Provider - payloads cannot write content or widen source access. -- A delivery must match the current source ID, setup generation and credential, - item and configuration fingerprint. The source lease and sequential reads fence - source replacement, retirement and late provider responses. -- Push secrets use purpose-bound sealing. Only an admin can reveal a pending - challenge; ordinary reads, audit subjects and idempotency replay omit it. -- Registry writes and namespace erasure share a fenced writer lease. Erasure - removes every stored version, and setup publication requires verified fleet - support for that erasure step. - -## Registration and authentication - -The push registry is separate from the source registry and sync cursors. A row -binds an org, namespace, source ID, provider and random setup generation to a -fingerprint of the source's credential and items. Configuration is an admin -operation. An explicitly configured HTTPS public base URL is required. - -The callback URL puts the namespace, source ID and setup generation in the path -and the exact organization in the required `org` query parameter. Query encoding -preserves organization names that contain slashes or reserved URL characters. -A callback re-reads the registry and current source under the namespace's source lease -before recording a sync request. A removed or replaced source, changed -credential, changed item set, inactive namespace or retired generation refuses -the delivery. Callback payloads and headers are not stored or logged. - -- Drive channels use independent random channel IDs and sealed channel tokens. - A delivery must match the active channel ID, token and resource ID before its - expiration. This is channel-token verification: Drive does not sign these - deliveries. Early `sync` notifications are acknowledged without requesting - work. Watch responses are activated only after rechecking the setup generation. -- Notion setup captures one bounded, sealed verification challenge for a fresh - generation. Only an admin can reveal it while setup is pending. After verifying - the subscription in the provider's UI, the admin confirms that exact generation - and challenge fingerprint. An unsigned challenge cannot activate a subscription - or request sync. Active deliveries require the raw-body HMAC and the configured - workspace identity. -- Linear setup first exposes a pending notification address. The admin creates - its webhook there, then confirms the same generation with its signing secret. - Deliveries require the raw-body HMAC, the signed body's millisecond timestamp - within one minute and the configured organization identity. - -Provider identity is read using the source's existing credential during setup. -Notification bodies have a fixed size limit. Duplicate valid notifications -coalesce with the existing pending sync request; a waiting full sync is preserved. -Successful callbacks answer HTTP 200 within a four-second handler budget. - -## Drive coverage and renewal - -A Drive user change channel does not cover every shared-drive change. Setup -therefore creates channels for the user corpus and every shared drive the account -belongs to, up to 19 drives. A complete, bounded membership listing avoids mistaking -a directly shared file's drive ID for membership: a nonmember's directly shared -items use the user log. Setup refuses an incomplete or over-limit corpus set -rather than claiming complete push coverage. Moving a file -to a new corpus may require setup again; polling still discovers the change. - -A bounded, default-off worker renews channels before expiration. It creates a -new unique channel, validates the response and source generation, then swaps it -under the source lease. It stops the old channel best effort. A failed renewal -leaves polling available and exposes the expired channel in setup status. - -The configuration catalog controls the provider-work, per-channel stop, total -cleanup and worker-pass deadlines. Their defaults are 40, two, five and 120 -seconds. A pass stops starting renewals with enough time for one provider attempt -and two cleanup windows. Configuration refuses provider work plus cleanup that -could outlive the 48-second work window within the 120-second renewal lease, or a -pass budget that leaves no time to start a renewal. The channel stop deadline -cannot exceed the total cleanup window. +Document-source push registrations are retained maintenance data. Native push +setup, callbacks, delivery handling and renewal execution are removed. Retained +rows do not request sync or activate an MCP source. MCP selected refresh uses the +bounded source worker described in [MCP document sources](mcp-document-sources.md). ## Lifecycle and storage -The registry is ordered by org, namespace and source ID, so namespace reads -prune their physical key range. Maintenance scans advance in that same order. -The registry stores the full identity tuple, server-stamped actor and derived -provenance. Secrets use purpose-bound sealing and participate in resealing. -Ordinary source reads and audit subjects never include tokens or challenges. -The admin setup read bypasses idempotency replay storage, so a revealed pending -challenge cannot be replayed from an ordinary cache after activation. +The push registry remains separate from source configuration and sync cursors. +Existing configuration, credentials, push rows and history are retained without +upgrade deletion or automatic migration. Unsupported native document sources are +unavailable, and their credentials are never reused for MCP enrollment. + +Explicit local source retirement may retire its retained push binding under the +existing source lifecycle. Retirement writes a retired registry version and +clears that current binding's sealed secret; it does not claim upstream channel +revocation or delete all historical rows. The account owner must revoke remote +credentials or registrations at their issuer when required. No callback, native +stop request or provider OAuth fallback runs here. + +Offline secret resealing preserves retained registrations, including rows without +an executable source. It rotates only the purpose-bound sealed secret and keeps +the existing identity, status and configuration. Unreadable secrets are reported +for operator resolution rather than discarded as cleanup. Resealing does not +activate a source or perform provider work. + +The registry keeps its identity tuple, server-stamped actor and provenance. +Writes use the existing fenced writer lease; resealing also holds the namespace's +source lease and refuses active erasure. Namespace erasure removes stored registry +versions through the existing settled erasure machinery. Source retirement, +namespace erasure and secret resealing remain distinct authorized actions. -Source removal, credential rotation, item updates and namespace retirement -retire push setup under the same source lease. Late external watch responses -cannot revive retired setup. Namespace erasure removes every registry version -through the existing settled erasure machinery. Configuration writes require a -fleet that understands the registry's erasure step; an unreadable fleet refuses. -Before rolling back to a build without this registry, disable push, erase the -registry rows with the current build and verify the namespace erasures complete. -Provider channels that cannot be stopped expire; retired callbacks refuse them. +## Source entry points -## Alternatives +- `server/knowledge/app/source_push.py` (`retire`, `reseal_registry`) performs + explicit local retirement and offline secret rotation. +- `server/knowledge/store/source_push.py` persists retained registry versions and + supplies bounded sealed-row scans. +- `server/knowledge/app/sources.py` coordinates source lifecycle under its lease. +- `server/erasure/store/steps_ledgers.py` (`delete_source_push_by_namespace`) + participates in namespace erasure. -Putting push state in the source row would make every delivery contend with -credential writes and risk carrying an old credential forward. Putting it in -sync detail would mix sealed setup secrets with ordinary inspection output. -Both are avoided by the separate registry. Notifications are hints, so a durable -event queue, provider payload archive and a second ingestion path are unnecessary. +## Invariants -## Provider contracts +Retained state is not an executable notification registration. Upgrade and +resealing delete no history and activate no work. Only an explicit authorized +lifecycle action retires a local binding, and only writer-requested erasure +removes its stored history. Local retirement makes no remote revocation promise. -- [Drive push notifications](https://developers.google.com/workspace/drive/api/guides/push) -- [Drive user and shared-drive logs](https://developers.google.com/workspace/drive/api/guides/about-changes) -- [Notion webhook verification](https://developers.notion.com/reference/webhooks) -- [Notion event delivery](https://developers.notion.com/reference/webhooks-events-delivery) -- [Linear webhook verification](https://linear.app/developers/webhooks) +Protected copies continue to require actual current source authority. Existing +ordinary published copies retain their namespace access and erasure rules; +unsupported protected mirrors stay unavailable. See +[document-source erasure](document-sources.md#erasure-and-audit) and +[operator cutover](mcp-document-sources.md#rolling-upgrades-and-operator-cutover).