# mcp-data-platform > MCP server for AI-assisted data exploration. Its own data catalog in PostgreSQL is the semantic layer, with optional Trino and S3. Cross-enrichment automatically enriches query results with business context: descriptions, owners, tags, glossary terms, open incidents. Implements fail-closed security with OIDC/API key authentication and TLS for HTTP transport. For the security architecture rationale, see: https://imti.co/mcp-defense/ **Document version: v1.120.0, revised 2026-08-29.** This project releases often. If your copy of this page is older than the current release on https://github.com/txn2/mcp-data-platform/releases/latest, re-fetch it before grounding an assessment on it; earlier revisions described a narrower system. **How the documentation site is organized.** Three sections: `home`, `docs` (everything written about the platform -- install, the End User and Administrator references, the API reference, the Go library, evaluation, examples and support), and `portal` (a guided tour of every screen the built-in web portal serves, split into Your Work and Administration). The portal tour lives under /portal/; it replaced the two single-page guides that used to sit at /server/portal-user/ and /server/admin-portal/. --- # Overview Your AI assistant can run SQL. But it doesn't know that `cust_id` contains PII, that the table has an open data-quality incident, or who to ask when something breaks. mcp-data-platform fixes that. It connects AI assistants to your data infrastructure and adds business context from its own data catalog. Query a table and get its meaning, owners, tags, and open incidents in the same response. Cross-enrichment works from the platform catalog, kept in PostgreSQL: every Trino, API and GraphQL connection is scanned into it, and people (in the portal) and agents (through apply_knowledge) curate it. Add Trino (https://trino.io/) for SQL queries and S3 for object storage when you're ready. Both are optional: with neither configured the server starts normally and the database-backed surfaces (catalog, API and MCP gateways, knowledge, memory, portal, search/fetch) run on PostgreSQL alone. See "Deployment Shapes" below. ## Key Features - **Semantic-First**: The platform catalog is the foundation of cross-enrichment. Query a table, get its business context automatically: description, owners, tags, glossary terms, open incidents. No separate lookups. - **Cross-Enrichment**: Trino results include the catalog's curation. A dataset fetched from the catalog says whether and where it is queryable. Context flows between services automatically. - **Enterprise Security**: Fail-closed authentication model, TLS enforcement for HTTP transport, and read-only mode enforcement. - **Built for Customization**: Add custom toolkits, providers, and middleware. The Go library exposes everything. Build the data platform your organization needs. - **Personas**: Define who can use which tools and, deny-by-default, which connections. The connection is the authorization boundary rather than the end user: one connection per credential and permission level, several of which may front the same downstream system. Map from your identity provider's roles. - **Resource Templates**: Browse platform data as parameterized MCP resources using RFC 6570 URI templates. Three built-in templates: table schemas (`schema://catalog.schema/table`), glossary terms (`glossary://term`), and data availability (`availability://catalog.schema/table`). - **Managed Resources**: Human-uploaded reference material (data, samples, playbooks, templates, references) surfaced directly to AI assistants via MCP `resources/list` and `resources/read`. Three visibility scopes: global, persona, and user. PostgreSQL metadata with S3 blob storage. REST API for CRUD, Admin Portal page for management. Auto-enabled when a database is available. - **Progress Notifications**: Long-running Trino queries send granular progress updates (executing, formatting, complete) to clients that provide `_meta.progressToken`. Zero overhead when the client doesn't send a token. Enabled by default; set `progress.enabled: false` to opt out. - **Client Logging**: Server-to-client log messages for platform decisions (enrichment, timing) via MCP `logging/setLevel` protocol. Zero overhead if the client hasn't opted in. Enabled by default; set `client_logging.enabled: false` to opt out. - **Elicitation**: User confirmation prompts before a query returning many rows (EXPLAIN IO output estimate, off by default) or PII access (sensitive column detection). Requires client-side elicitation support; gracefully degrades when unavailable. Enabled by default with `pii_consent`; `cost_estimation` is off unless `enabled: true` (#2586). Set `enabled: false` at any level to opt out. - **Icons**: Visual metadata for tools, resources, and prompts. Upstream toolkits provide default icons; deployers can override via configuration. Enabled by default; set `icons.enabled: false` to opt out. - **Dynamic Prompts**: Three-tier prompt system: auto-registered `platform-overview` built from description and enabled toolkits, operator-configured prompts with `{placeholder}` argument substitution, and conditional workflow prompts (explore-available-data, create-interactive-dashboard, create-a-report, trace-data-lineage) registered when required toolkits are present. `server.builtin_prompts` is a per-prompt switch (map of prompt name to bool) suppressing a built-in workflow prompt; a name absent from the map registers as usual. Toolkits implement `PromptDescriber` to advertise their own prompts. Operator prompts override auto-registered ones by name. `platform_info` does not list the prompt library. It once did, carrying every prompt with its full body, which made the mandatory first call of a session grow with the library (#1586); and a prompt is now reached by handle: `manage_prompt` command `use` resolves a stored name, display name, `mcp:prompt:` reference or free text, command `list` browses, the portal's Prompts page opens the library for a person, and `fetch` on `mcp:prompt:` returns one in full. --- # Ecosystem mcp-data-platform is the orchestration layer for a broader suite of open-source MCP servers designed to work together as a composable data platform. Each component can run standalone or be combined through mcp-data-platform for unified access with cross-enrichment, authentication, and personas. ## mcp-s3 (https://github.com/txn2/mcp-s3/) An MCP server for Amazon S3, providing AI assistants with direct access to object storage. List buckets, browse prefixes, read objects, and generate presigned URLs. Supports multi-server configurations for accessing storage across accounts and regions. ## mcp-trino (https://github.com/txn2/mcp-trino/) An MCP server for Trino, the distributed SQL query engine. Run read-only SQL queries across any data source Trino connects to, including data lakes, warehouses, and relational databases. List catalogs and schemas, describe tables, explain query plans, and execute analytical queries with configurable timeouts and row limits. --- # The Data Stack: Catalog + Trino + S3 Modern data platforms need three things: meaning (what does the data represent?), access (how do I query it?), and storage (where does it live?). mcp-data-platform keeps its own catalog for meaning, uses Trino for access, and S3 for storage. Trino and S3 are components the platform composes, not prerequisites an adopting organization must already run. A deployment can attach either, both or neither (see Deployment Shapes). ## The Platform Catalog: The Semantic Layer The platform catalog lives in the platform's PostgreSQL. It records the datasets every connection can see, their columns, the glossary, tags, domains and data products, and the curation written on each: descriptions, owners, tags, glossary terms, properties, curated queries, incidents and context documents, versioned and reversible, with lineage recorded as data moves. **Problem it solves**: Data exists everywhere, but understanding what it means requires tribal knowledge. Column `cid` in one system is `customer_id` in another, and PII columns are not labeled. **Why built in**: scanned from the connections without an ingestion job, curated where the work happens (portal and apply_knowledge), every change versioned with rollback, connection-scoped so persona connection rules govern who reads it, and no extra service to run. **For AI**: Without a catalog, an AI sees columns and types. With it, it sees what the data means, who owns it, and whether it has an open incident. ## Trino: Universal SQL Access Trino (https://trino.io/, formerly PrestoSQL from Facebook) is a distributed SQL query engine. It runs SQL against data where it lives, without moving it first. **Trino connects to everything**: PostgreSQL, MySQL, Oracle, Snowflake, BigQuery, Elasticsearch, MongoDB, S3, HDFS, Delta Lake, Iceberg, Kafka, and more. **One SQL dialect**: Query across PostgreSQL, Elasticsearch, and S3 in one statement. The AI doesn't need to know where data lives. It's all SQL. **Why Trino**: Battle-tested at Meta, Netflix, Uber, LinkedIn. Cost-based optimizer, standard ANSI SQL, federated queries without data movement. ## S3: The Universal Data Lake S3 (Amazon S3, SeaweedFS, or any S3-compatible service) is object storage for any data: files, Parquet, JSON, logs, ML models. **Problem it solves**: Not all data is structured or in databases. Data platforms must handle structured (tables), semi-structured (JSON, Parquet), and unstructured (PDFs, images) data. **Why S3**: Infinite scale at low cost, any file format, direct querying via Trino, object versioning, S3-compatible (AWS, SeaweedFS, Ceph). ## Cross-enrichment fills the gaps | Component | Answers | Limitation Alone | |-----------|---------|------------------| | Catalog | "What does this mean?" | Can't query the data | | Trino | "What's in this table?" | Doesn't know business context | | S3 | "What files exist?" | Just storage, no meaning | Cross-enrichment wires them together: - Trino to catalog: Query a table → Get schema + description + owners + tags + glossary terms + open incidents - Catalog to Trino: Fetch a dataset → See whether it is queryable, on which connection, and its estimated rows This stack is built for OLAP: S3 stores petabytes at low cost, Trino runs analytical queries across that data, the catalog adds business context. --- ## What's Included | Toolkit | Tools | Required | |---------|-------|----------| | Trino | 7 tools | No | | S3 | 6-9 tools | No | | Knowledge | 1-2 tools | No | | Memory | 2 tools | No | --- # Content Model: Resources, Assets, Knowledge, Memory Four places content lands, distinguished by who authored it and what the agent should do with it, not by file format. The canonical statement, held byte-identical in instructions.ResourcePositioning (Go), ui/src/lib/positioning.ts (portal), and the concepts page, and enforced by TestResourcePositioningIsVerbatim: "Resources are human-uploaded inputs an agent uses as-is: report templates, brand files, data dictionaries, sample payloads, and reference documents. Assets are AI-generated outputs. Knowledge pages are curated facts to search and synthesize. Memory is per-user recall. If it existed before the conversation and the agent should use it verbatim, it is a resource." | Layer | Holds | Authored by | Agent reaches it via | Portal | |-------|-------|-------------|----------------------|--------| | Resources | Files used as-is: templates, brand assets, data dictionaries, sample payloads, runbooks | A person, before the conversation | search then fetch, the resources/read protocol method, or a prompt attachment | Resources | | Assets | Dashboards, reports, visualizations, documents produced during a session | The agent, during the conversation | save_asset / manage_asset, and search | Assets | | Knowledge pages | Curated business and domain facts, cross-linked and citable | A person or a promoted insight, reviewed | search then fetch, apply_knowledge | Knowledge | | Memory | Per-user recall: preferences, corrections, working context | The agent on the user's behalf | memory_capture / memory_manage, and search | Knowledge | Choosing: existed before the conversation and should be reproduced rather than rewritten -> resource. Made by the agent in a session and worth keeping -> asset. A fact to be found, cited, and synthesized -> knowledge page. About how one person works -> memory. A resource is filed under a folder path inside its library, and the suggested first-level folders carry the distinction one level down: data are records to read as fact rather than as an example (rosters, mappings, rate tables), templates are layouts a deliverable must be produced in, playbooks are procedures to follow rather than summarize, samples are examples to pattern-match against, references are documents to consult. data and samples are the pair most easily confused: the same CSV is a sample when the agent should copy its shape and data when it should read its rows. The upload dialog states each meaning as the folder is chosen. They are suggestions and not a closed set: a path nests as deep as a library needs. Some knowledge pages ship with the platform itself: built-in pages documenting the features whose purpose is not readable from tool schemas (managed-script authoring and the Starlark dialect's gotchas, script output identity, the semi-dynamic dashboard pattern, asset references and the refresh loop, provenance and the capture loop, the media type every stored file carries, writing a document that fits the reader's screen). Each page states its mechanism as a mermaid diagram as well as in prose, which the portal renders and an agent reading the page through fetch receives as a labeled graph. They are embedded in the binary and reconciled into the store at startup, so a release that changes them updates every deployment on its next start; unchanged content touches nothing, and a changed page is re-embedded through the ordinary write trigger. They are badged Built-in and read-only where people edit (the portal and apply_knowledge refuse to modify them); a deployment hides one by deleting it — the reconcile respects the tombstone rather than resurrecting it, and a restore action brings hidden pages back refreshed to the running release — and can write its own page on the topic, including under the same slug, which the reconcile also leaves alone. A page a release stops shipping is retired (its tombstone releases the slug), so re-shipping it later resurrects it, unlike an operator hide. The managed-script authoring page derives its dialect section from the same constant `manage_script help` returns, so the two cannot drift. The pages cite one another by slug, outside code spans (#2200): every page ends with a Related pages list of its neighbours and the index, and `platform-index` ("What the platform documents about itself") lists every page with its summary, generated from the shipped set. A citation by slug is stored in knowledge_page_entity_refs as the cited page's id on the deployment (an mcp:knowledge_page: key resolves to the row with that id, else the live page with that slug, in reference validation and in every reference write, so a deployment's own page citing a built-in by slug is stored too), and the built-in pages' inline references are derived in a second pass after every page is written, on every start, so an upgraded deployment gains them with no page changed; the portal resolves a slug citation as a live link. `make builtin-pages-check` (in make verify) warns when a diff changes a source path internal/platform/knowledgebuiltin/covers.txt lists for a page and leaves the page alone. Search ranking is not their only discovery path: the instruction baseline names the index in its page list's heading, the baseline's scripts bullet and `manage_script help`'s see_also list name them by slug, and fetch takes a page's slug in place of its id, because a built-in page's row id is generated per deployment at reconcile time and only the slug is stable across deployments. ## Agent steering When a deployment has managed resources, platform_info appends a resources section to the agent instructions carrying the positioning statement plus the operating rule: - Before formatting a deliverable, search for an applicable template or reference resource and follow it rather than inventing a layout. - When the user names a company file ("our template", "the checklist", "the brand header"), resolve it with search and read it in full with fetch rather than asking them to paste it. - Material attached to a prompt is authoritative: use it as given. The section names a tool only when the caller's persona can reach it: a persona denied search is pointed at the resources/list protocol method, which is persona-filtered but is not a tool and is therefore always available. A deployment with no managed resources gets no section. This is steering, not enforcement. ## Making an approved template mandatory The operator surface for a stricter rule is server.agent_instructions, composed beneath the platform baseline in platform_info. It is set in YAML or edited at runtime from the admin portal's Agent Instructions page, which writes the server.agent_instructions config key to the database. ```yaml server: name: mcp-data-platform agent_instructions: | Reporting standard: every report, summary, or briefing you produce must use the approved template for that deliverable. Before writing one, search for a resource in the `templates` category matching the deliverable's name. If one exists, fetch it and produce your output in its structure, section order, and headings. Do not restructure it, and do not substitute your own layout. If no approved template exists, say so in one line before the output so the gap is visible. ``` Scoping the rule to one audience is a persona suffix appended to the same layer: ```yaml personas: analyst: display_name: "Data Analyst" roles: ["analyst"] context: agent_instructions_suffix: | Client-facing deliverables additionally require the brand header resource. Fetch it and place it before the first section. ``` GET /api/v1/admin/config/agent-instructions-baseline renders the platform baseline for this deployment's registered tools, so an operator can see what is already covered before writing their own. Two baseline lines teach an order rather than a capability, and one runtime note says which tools take which connections. With `trino_query` reachable, the SQL line reads: read a table's columns before SQL names one, with `trino_describe_table` (or `fetch` of its `mcp:dataset` reference, when `fetch` is reachable); `SELECT *` and `count(*)` need none; join a short key list inline, and register a longer one as a table (#2810). With `memory_manage` reachable, a line says that a memory relied on that proved wrong or outdated is fixed with `update` or retired with `forget` (#2814). The runtime note in `platform_info`'s composed instructions names, for each connection kind the deployment has connections of, the tools of that kind the caller may call, plus `platform.query in a managed script` for an application database (#2812): `Each connection is served by the tools of its kind; send a connection only to them:` followed by one line per kind (`- Trino: trino_browse, trino_describe_table, ...`). A kind the deployment has no connection of is not listed, a kind with neither a tool the caller may call nor a script route is left out, and with no such kind there is no note. --- # Authorization Model: the connection is the boundary The unit of access in mcp-data-platform is the connection, not the end user. This is the authorization design, not a filter layered on top of one and not a missing per-user passthrough. An operator configures one connection per credential and permission level, and grants each persona the subset of connections it may reach. A caller's identity selects a persona; the persona selects connections; the connection carries the credential that talks to the downstream system. ## The shape A connection is a named, operator-authored binding to one downstream system under one credential: a Trino cluster as one service account, an S3 account, an upstream MCP server, an HTTP API. Several connections may point at the same system under different credentials, and that is the intended shape rather than a workaround. A read-only Trino account and a write-capable one on the same cluster become two connections; a persona granted the first cannot do what the second can, because the permission level a caller gets is the permission level of the credential bound to the connection they were granted. The HTTP API gateway uses the same split heavily, with api_routes narrowing further by method and path. ## Why the connection and not the end user Three reasons. First, the downstream systems are heterogeneous: the platform federates Trino, S3, arbitrary upstream MCP servers, and arbitrary REST APIs. Trino has session users and can sit behind a system that enforces row policies; a third-party MCP server and a vendor REST API typically have neither and expose no token-exchange endpoint to impersonate a caller through. An identity model that works for one of five backends is a special case, not an authorization model. The one construct all of them share is a credential and an endpoint. Second, a credential the operator wrote is auditable ahead of time: an operator can read a connection's service account in the downstream system, see exactly what it reaches, and reason about blast radius before any tool call happens, rather than deferring that reasoning to whatever the identity provider asserted at request time for each user. Third, the distinctions organizations actually draw for AI agents (read the warehouse, read and write the sandbox, read the customer API, write the customer API) are coarse and fit a handful of connections, which keeps each grant explicit and greppable. ## What the boundary enforces Deny-by-default on both axes, checked on the same call. Connections are deny-by-default: a persona reaches a connection only when a connections.allow glob matches its name, an omitted connections block or an empty allow grants no connections, and deny patterns win over allow (pkg/persona/filter.go, IsConnectionAllowed); a caller whose roles match no persona is denied everything by the built-in deny-all persona the role mapper returns (pkg/persona/mapper.go). Both checks run on every tool call: Authorizer.IsAuthorized refuses unless the tool pattern and the connection both pass. Discovery is bound by the same predicate: search, fetch, list_connections, and the portal search consult one shared scope that delegates to IsConnectionAllowed rather than reimplementing the glob rules, so a caller cannot find an entity behind a connection it was not granted (internal/platform/connscope), and argument completion applies the same predicate directly. search and list_connections report a withheld count and a notice naming the persona rather than silently shortening results. The scope is deliberately permissive in one direction: a catalog dataset whose URN maps to no configured connection is unattributable and stays visible (pkg/knowledge/connscope.go), and a deployment with no persona registry has no scope to apply so discovery is unfiltered there. API routes narrow within a connection: for kind=api connections, api_routes constrains (connection, method, path), and when no rule matches the connection the route check is a no-op so the connection-level grant is the sole gate. A rule's path globs are matched against both the path a call reaches ("/v1/orders/42") and the catalog path its operation declares ("/v1/orders/{id}"), so naming the declared path governs that one operation and every call it serves; wildcards do not cross a "/" and there is no recursive form. Rules are written in the config file under a persona's api_routes, or in the portal at Settings > Personas > Permissions > API endpoints, which lists each api-kind connection and the operations its catalog declares with the persona's decision on each one, and compiles a selection to that operation's own method and declared path so a portal-written rule and a file-written one are the same rule; a hand-written glob is displayed as the glob it was typed as and is not rewritten on save. POST /api/v1/admin/personas/{name}/test-access answers a (connection, method, path) question with the decision and the matched rule. The credential is the enforcement and the toolkit adds what it can: the S3 toolkit's read_only flag is per connection and refuses the writing actions of s3_object, an upload link (presign with method PUT) among them (pkg/toolkits/s3/tools.go), and Trino's read_only is per connection too — several Trino instances fold into one multi-connection toolkit whose query interceptor rejects write SQL on the connection each call names, or on the default connection when the call names none, leaving the other connections of the same toolkit untouched (pkg/toolkits/trino/readonly.go); a read/write split across two connections on one cluster is enforced by the toolkit as well as by the downstream service account. Tools belonging to no connection (platform_info, search, and the other platform-level tools) carry an empty connection name, so the connection check admits them and the tool patterns are the gate; the middleware does take the connection from a "connection" argument when the toolkit resolved none (pkg/middleware/mcp.go), so a caller that sends one to a platform-level tool has it recorded and checked like any other. ## What the boundary does not enforce Every caller granted a connection acts as that connection's credential downstream. The platform performs no per-user token exchange, no impersonation, and no session-user propagation; nothing in the tree swaps a caller's identity for a downstream one. (It does run outbound OAuth per connection, obtaining and refreshing that connection's own credential against upstream MCP servers and APIs via pkg/connoauth/exchange.go; the identity that flow yields belongs to the connection, not to the caller.) Two analysts granted the same connection are indistinguishable to the downstream system. Row-level policies and column masking that key off the end user therefore do not follow a caller through the platform: if a warehouse masks a column for one person and not another and both reach it through one connection, both see whatever that connection's service account sees. Per-person policy means one connection per distinct policy outcome, which is workable when those outcomes are few and unpleasant when they are many. Per-user attribution comes from the audit trail, not from distinct downstream identities: with audit enabled, each tool call writes a row carrying user_id, user_email, persona, tool_name, timing, the connection when the call targets one, and the call arguments subject to redact_keys (pkg/audit/logger.go for the schema, pkg/middleware/mcp_audit.go for the redaction and the write), so the platform can answer who ran what, as which persona, through which connection, even though the downstream system sees only the service account. That makes the audit trail load-bearing and it is not unconditional: audit requires a database, so a deployment with no database.dsn or with audit.enabled: false gets a no-op logger and no rows (pkg/platform/platform.go), log_tool_calls: false keeps audit on but drops per-call rows, log_parameters: false keeps the row without arguments, and async delivery is best-effort under a sustained store outage. A deployment that leans on connection-scoping for authorization should not also run without audit. ## More connections, not more roles The lever for tightening access is usually a new connection, not a new role. A role divides people; a connection divides reach. Adding a role to split two groups that both land on the same connection changes nothing about what either group can do downstream. Reach for another connection when a group needs a different permission level in the same system (bind the narrower downstream account to a second connection and grant it separately), when a group needs a different blast radius (a connection is the unit a compromised credential is bounded by), or when an API needs a subset of its endpoints exposed (two connections, or one plus api_routes). Reach for another role when the same reach should carry different tools, different agent instructions, or different portal visibility. ## Compared with a warehouse-native MCP server A server that lives inside one warehouse inherits that warehouse's per-user authorization: row policies, column masks, and grants apply to the calling person because the calling person is the session user. That is a real advantage inside that warehouse and the right choice for a single-warehouse deployment that needs per-person data policy. It does not extend past the warehouse. This platform's premise is a caller reaching a warehouse, a catalog, object storage, third-party MCP servers, and REST APIs through one authenticated, audited, persona-governed endpoint, and the connection is the boundary that spans all of them uniformly. The trade is explicit: uniform enforcement and pre-auditable credentials across heterogeneous backends, in exchange for per-person downstream policy that has to be expressed as connections rather than inherited. --- # Deployment Shapes A deployment's shape is the set of backends it attaches. Shape is independent of operating mode, which is determined solely by whether database.dsn is set. Three shapes: | Shape | Backends | Core capability | |-------|----------|-----------------| | Semantic stack | PostgreSQL and Trino, optionally S3 | Cross-enrichment: every data response carries business context from the platform catalog | | API and knowledge | PostgreSQL | Gateways, knowledge, memory, portal, universal search | | Combined | Both | Cross-enrichment plus the database-backed surfaces | ## Semantic stack The shape the platform was built for. The platform catalog, kept in PostgreSQL, supplies meaning, Trino supplies SQL access, S3 supplies object storage, and cross-enrichment wires them together. The database is what cross-enrichment requires; every Trino connection is scanned into the catalog. ## API and knowledge A deployment with no data warehouse and no catalog. PostgreSQL is the one infrastructure requirement, because connections, catalogs, knowledge, memory, and portal assets are all database-backed. It provides the API and MCP gateways (portal-authored connections with encrypted credentials and OAuth grants), API catalogs, the knowledge layer (capture, review, promotion to canonical knowledge pages), the memory layer, the portal (assets, collections, prompts, feedback threads, sharing), search/fetch federating over those sources, and the full auth/persona/audit/observability envelope. Minimal configuration: ```yaml server: name: mcp-data-platform transport: http address: ":8080" database: dsn: ${DATABASE_URL} auth: api_keys: enabled: true keys: - key: ${API_KEY_ADMIN} name: admin roles: ["admin"] admin: enabled: true persona: admin # API connections are authored in the admin portal and stored in the # database; enabling the toolkit is all the YAML needs to say. toolkits: api: enabled: true personas: admin: display_name: "Administrator" roles: ["admin"] tools: allow: ["*"] ``` There is no query: block. Omitting it selects the noop query provider, a supported configuration rather than an error; the platform catalog is the semantic provider and holds the API connections' operations. From that configuration and an empty database, tools/list returns seventeen tools: api_discover, api_invoke_endpoint, apply_knowledge, fetch, list_connections, manage_asset, manage_feedback, manage_prompt, manage_resource, manage_script, manage_table, memory_capture, memory_manage, platform_info, run_script, save_asset, search. What this shape does not have: - Cross-enrichment. With no warehouse there is no query result to enrich. - Trino and S3 tools. No trino_* or s3_* tools are registered. - Warehouse tables in the catalog. The catalog holds the API and GraphQL operations, which search and fetch read; there are no tables. - Writing knowledge back to the catalog. apply_knowledge writes the platform catalog, which a database-backed deployment has whether or not it sets a semantic: block; with semantic.provider: noop catalog changes are refused rather than reported as written; use sink: knowledge_page instead. Object storage is optional here too: without an s3_connection, portal assets are stored in the database and managed-resource blob storage is disabled; the platform logs the fallback and starts normally. ## Combined Attaching a warehouse and catalog to an API-and-knowledge deployment, or API connections to a semantic-stack deployment, yields both sets of surfaces. Neither addition is a migration: providers are selected by the semantic: and query: blocks, and API connections are database rows. ## Replicas A database-backed deployment of any shape can run several replicas over one database behind a load balancer. State in the database is shared and state in a replica's memory is not, so set sessions.store: database for an MCP session to continue on whichever replica serves its next request. Every HTTP response carries X-Platform-Instance, the hostname and listen port of the process that served it (the hostname separates pods, the port separates two processes on one machine), so two replicas answering one read differently can be told apart. An answer to a signed-in portal caller the access gate admits also carries X-Platform-Build, the serving build's version and commit, and that reader's index.html names the build it loads (meta mcp-platform-build); a page that hears of a build it has not run loads the next page it moves to in full, or, with unsaved changes or a dialog open, shows "The portal has been updated. Save your changes, then reload to use the new version." with Reload, at most once per new build and never back to an older one (#2727). An anonymous caller, a site's visitors, an endpoint's callers and a share's readers are not told the build. A connection exists because the connection store holds a row for it, committed before the admin API's save returns; a replica also keeps a live object for each connection it serves (an HTTP client, a parsed spec set, a compiled GraphQL schema, a Trino pool), which it builds for itself. Both questions are answered from the rows: what connections exist (list_connections, the portal's connection pickers, GET /api/v1/apis) is the store unioned with what this replica serves, so a connection saved a moment ago on another replica is named at once with its description, catalog and operation count -- facts about the connection, not about the replica -- and with no health until this replica has called it; a call naming a connection this replica does not serve takes it on from the store and then answers as the saving replica answers. A connection is therefore never listed on one replica and missing on another, never refused as non-existent on one while working on another, and a deleted connection leaves every listing as soon as its row is gone. The startup merge of stored connections into toolkit configuration and the save announcement over the database's notification channel make this cheaper, not correct: a deployment is correct without either. The local dev stack runs this shape. make dev starts two platform processes over one PostgreSQL (replica A on DEV_API_PORT, replica B on DEV_API_PORT + 1) and an nginx proxy (dev/lb/platform-lb.conf.template, DEV_API_PORT + 2) that round-robins them with no session affinity, so a request and the next are served by different processes. The proxy also replaces the body of any origin 502 or 504 with "error code: " as text/plain, as the CDN in front of a deployment does. make acceptance connects to the proxy by default (MCP_BASE_URL overrides); forEachReplica and connectReplicaPair in test/acceptance discover the replicas from the header and open a session on each directly. The portal's Vite server stays on replica A. DEV_REPLICAS=1 make dev runs one process and no proxy; criteria about two replicas then fail. The stack runs with no embedder unless DEV_EMBEDDING_PROVIDER=ollama (#2637): memory.embedding.provider in dev/platform.yaml is noop, no Ollama container starts, search ranks lexically and the index queue never starts, so an acceptance run embeds nothing it creates; DEV_EMBEDDING_PROVIDER=ollama make dev starts the CPU-only Ollama container (compose profile embeddings), pulls nomic-embed-text and embeds, and the criteria that read real vectors run in the embeddings acceptance environment, which sets it. A criterion that needs a stack this lane does not make (the script worker off, the ClickStack bundle beside it) is named with its environment in test/acceptance/environments.txt: make acceptance leaves it out and says so, ACCEPTANCE_ENV= bash scripts/release-acceptance.sh starts that environment's stack and runs its criteria, and the E2E Nightly runs every environment each night except one marked manual: slack, whose criteria post to the Slack workspace named in dev/.slack-env and run by hand. A pull request that changes dev/, the Makefile, scripts/acceptance*, scripts/release-acceptance.sh, a harness file under test/acceptance/ (not a ticket's issue__test.go) or the acceptance workflows runs the worker-off environment in CI with make dev-smoke first (ACCEPTANCE_SMOKE=1), through .github/workflows/acceptance-run.yml, the workflow the nightly's acceptance jobs call (#2274). ## Shape versus operating mode | | Standalone (no database) | Database-backed | |---|---|---| | Semantic stack | Trino and S3 tools without cross-enrichment: the catalog lives in the database. No knowledge, memory, portal, or gateways. | Everything. | | API and knowledge | Not available: every surface in this shape is database-backed. | The shape described above. | --- # Installation ## Prerequisites - Go 1.27+ (for building from source) - An MCP-compatible client (Claude Desktop, Claude Code, or custom) - Access to the Trino and/or S3 services you want to connect, and PostgreSQL for the catalog ## Installation Methods ### Go Install ```bash go install github.com/txn2/mcp-data-platform/cmd/mcp-data-platform@latest ``` Note: `go install` and plain `go build` do not embed the web portal UI. The portal SPA is compiled in via `//go:embed` from `internal/ui/dist/`, which is populated only by the release build or `make frontend-build` and is empty in a plain source checkout. Such a binary has a working MCP server and admin REST API but no portal. For the full product use the released binaries, Homebrew, the Docker images, or run `make frontend-build` (requires Node.js 22) before `go build`. ### Homebrew (macOS) ```bash brew install txn2/tap/mcp-data-platform ``` ### Docker ```bash docker pull ghcr.io/txn2/mcp-data-platform:latest docker run -v /path/to/platform.yaml:/etc/mcp/platform.yaml ghcr.io/txn2/mcp-data-platform:latest --config /etc/mcp/platform.yaml ``` ## Client Setup ### Claude Code ```bash claude mcp add mcp-data-platform -- mcp-data-platform --config /path/to/platform.yaml ``` ### Claude Desktop Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS): ```json { "mcpServers": { "mcp-data-platform": { "command": "mcp-data-platform", "args": ["--config", "/path/to/platform.yaml"], "env": { "DATABASE_URL": "postgres://platform:secret@localhost:5432/platform" } } } } ``` ## Command Line Options | Option | Description | Default | |--------|-------------|---------| | `--config` | Path to YAML configuration file | None | | `--transport` | Transport protocol: `stdio` or `http` | `stdio` | | `--address` | Listen address for HTTP transports | `:8080` | --- # Configuration Configuration uses YAML with environment variable expansion (`${VAR_NAME}`). By default, unrecognized config keys are logged as a `WARN` and ignored so older configs keep loading. Detection applies at every level that maps to a defined field (a stray key under `server:`, `auth.oidc:`, or inside a persona definition is flagged, not just stray top-level keys). Set `config.strict: true` to reject unknown keys with a hard startup error instead (recommended: turns typos and stale keys into an immediate failure rather than a silent no-op). Free-form maps are exempt because they accept arbitrary keys by design: the `toolkits` tree, each toolkit's `config:` map, and the persona *names* under `personas:` (the fields within a persona definition are still validated). A future release will make strict rejection the default, opt-out via `config.strict: false`. Separately, after parsing the server validates the config and refuses to start on a recognized key whose value cannot work: `personas.default_persona` (removed), a missing `auth.oidc.issuer` under enabled OIDC, the `auth.browser_session` requirements (OIDC enabled, `signing_key`, a valid `same_site`, and `secure: true` under `same_site: none`), the `oauth` issuer/upstream fields and `oauth.signing_key` on an HTTP transport without `allow_ephemeral_signing_key`, `database.dsn` and a `LISTEN`-legal `sessions.broadcast_channel` under `sessions.store: database`, and `audit.delivery`. All problems are reported in one error. These checks are newly enforced: they were written alongside the settings they guard, but nothing called them, so a deployment may be running on a config that is refused after upgrading - notably `browser_session.enabled: true` under disabled OIDC (previously started with portal login silently off) and an HTTP-transport OAuth server with no `oauth.signing_key` (previously minted a per-process key that peers reject). ## Config Versioning Every configuration file should include an `apiVersion` field as the first key. This enables safe schema evolution with deprecation warnings and migration tooling. ```yaml apiVersion: v1 server: name: mcp-data-platform ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `apiVersion` | string | `v1` | Config schema version. Omitting defaults to `v1` for backward compatibility. | **Supported versions**: `v1` (current) ### Migration Tool Migrate config files to the latest version: ```bash # From file to stdout mcp-data-platform migrate-config --config platform.yaml # From stdin to file cat platform.yaml | mcp-data-platform migrate-config --output migrated.yaml # Specify target version mcp-data-platform migrate-config --config platform.yaml --target-version v1 ``` The migration tool preserves comments and `${VAR}` environment variable references. ### Version Lifecycle - **current**: Actively supported, no warnings - **deprecated**: Still works, emits a warning at startup with migration guidance - **removed**: Rejected at startup with an error pointing to the migration tool ## Minimal Configuration ```yaml server: name: mcp-data-platform transport: stdio database: dsn: ${DATABASE_URL} # holds the platform catalog cross-enrichment reads toolkits: trino: enabled: true instances: primary: host: trino.example.com port: 443 user: ${TRINO_USER} password: ${TRINO_PASSWORD} ssl: true catalog: hive default: primary enrichment: trino_semantic_enrichment: true unwrap_json: true # Auto-unwrap single-row VARCHAR-of-JSON (default: true) column_context_filtering: true # Only enrich columns referenced in SQL (default: true) estimate_row_counts: false # Run COUNT(*) for availability enrichment (default: false) semantic_fallback: false # Fallback to similarity search on a lookup miss (default: false, issue #444) semantic_fallback_top_k: 1 # Suggested matches per miss (default: 1, max: 10) memory_limit: 5 # Max memory records recalled per tool call (default: 5, issue #761) memory_context_budget_bytes: 1500 # Byte budget for rendered summaries; over-budget records become fetchable stubs; 0 disables (default: 1500) memory_summary_bytes: 280 # Per-record summary excerpt cap; 0 = full content (default: 280) ``` ## Server Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `server.name` | string | `mcp-data-platform` | Platform identity (e.g., "ACME Corp Data Platform") - helps agents identify which business this MCP serves | | `server.description` | string | - | Explains when to use this MCP - what business, products, or domains it covers. Agents use this to route questions to the right MCP server. | | `server.tags` | array | `[]` | Keywords for discovery: company names, product names, business domains. Agents match these against user questions. | | `server.agent_instructions` | string | - | Business/deployment context (data conventions, which backends hold what, domain rules), layered BENEATH the platform-owned instruction baseline (#646). The baseline is an index rather than a manual (#1586): one line per capability naming its entry-point tool and the judgment made before reaching for it (search-first / topology discovery, capture proactively), plus an index of the built-in knowledge pages that carry the depth, fetched when needed rather than carried in every session's first response. It is versioned with the release, names only tools the caller's persona can reach and only pages that caller can read, and is always present (a persona `agent_instructions_override` replaces this admin layer only). The agent receives the baseline as part of the composed `agent_instructions` in the `platform_info` response; the baseline on its own is at `GET /api/v1/admin/config/agent-instructions-baseline` (used by the portal's read-only Agent Instructions panel, which also draws its size meter from the `limit_bytes` and `advisory_bytes` that endpoint reports). This customized layer is BYTE-BOUNDED (#1607) because it is composed into every session's first response: past 12,288 bytes a write succeeds and carries a notice, and past 32,768 bytes it is refused, naming knowledge pages as the home for the overflow. Both writers enforce it -- `PUT /api/v1/admin/config/entries/server.agent_instructions` (400) and the `apply_knowledge` `agent_instructions` sink. | | `server.prompts` | array | `[]` | Platform-level MCP prompts registered via `prompts/list`. Support `{arg_name}` placeholder substitution. Operator-defined prompts override auto-registered workflow prompts with the same name. | | `server.prompts[].arguments` | array | `[]` | Typed arguments: name, description, required. Substituted into content as `{name}` placeholders. | | `server.prompts[].display_name` | string | - | Human-readable title served as the MCP prompt `title` (falls back to the name) | | `server.transport` | string | `stdio` | Transport: `stdio` or `http` (`sse` accepted for backward compatibility) | | `server.address` | string | `:8080` | Listen address for HTTP transports | | `server.streamable.session_timeout` | duration | `30m` | How long an idle Streamable HTTP session persists before cleanup | | `server.streamable.stateless` | bool | `false` | Disable session tracking (no `Mcp-Session-Id` validation) | | `server.reference_scheme` | string | `mcp` | The scheme every platform reference is written out under (#2776), read under it and under `mcp:`, stored canonical as `mcp:`. The platform's own wording about the reference form (`mcp::`, "an mcp:dataset reference", "an mcp: reference") is rewritten too in `tools/list`, the initialize instructions, every refusal and the `platform_info` result (#2818); a tool's data keeps the whole-reference rewrite only. A managed script's session receives results canonical and manage_script's code fields (source, edits, find, pattern, replace, text, before, after, diff, lines) are never rewritten, and what a script reports through manage_script and run_script (log, result, state, checkpoint, state_discarded, error, failure, tests) is shown canonical as the script produced it; an endpoint's JSON answer and every delivered notification's title and body are written under the scheme, and an endpoint's path, query and JSON body are read canonical (#2788). | The MCP SDK caps each Streamable HTTP request body at 4 MiB and rejects a larger one with `413 Request Entity Too Large` (`request body exceeds 4194304 bytes`). It bounds inbound JSON-RPC bodies, so it bounds tool-call arguments; tool results, managed-resource uploads, and asset exports travel other paths with their own limits. ## Database Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `database.dsn` | string | - | PostgreSQL connection string | | `database.max_open_conns` | int | 25 | Maximum open database connections; at least 4, refused at startup below that (#2169). Every background try-lock (the locked loops, connlimit slots, the connoauth refresher) is held on one session per process, internal/advisorylock | Setting `dsn` enables audit logging, knowledge capture, session externalization, and OAuth persistence. Without it, these features degrade to in-memory or noop implementations. PostgreSQL 16 and 17 are the supported majors, with the `pgvector` extension available. Both are covered by the migration gate on every change (`make migrate-check` applies the full set to each, and CI runs a service per major), because the majors disagree about what SQL a migration may legally contain: since 17, maintenance operations including `CREATE INDEX` run with `search_path` restricted to `pg_catalog` and `pg_temp`, so an index expression whose function body calls a platform-defined function builds on 16 and fails on 17. Upgrading between the two majors needs nothing from this platform beyond the usual PostgreSQL upgrade procedure. ## Config Store When a database is available (`database.dsn` is set), individual config entries in the `config_entries` table override file defaults for whitelisted keys. The store is the authority: every read resolves the key from it and falls back to the file value when no row exists, so a change via the admin API is in force on every replica as soon as it commits, without restart. Deleting a database entry restores the file default everywhere on the next read. If the store cannot be read, the file-config value is used. **Whitelisted keys (phase 1):** `server.description`, `server.agent_instructions` `server.agent_instructions` is byte-bounded on both of its writers (#1607): 12,288 bytes is a soft advisory carried on the response, 32,768 bytes is a hard refusal. The value is composed into the first response of every session on the deployment, so its size is paid for by every caller; the refusal names the size, the limit, the overage, and the knowledge-page alternative. `apply_knowledge action=apply sink=agent_instructions` is the other writer and enforces the same bound. The config store is selected automatically by database presence: no `database.dsn` means read-only file config; setting it makes config database-backed and mutable. ## Tool Visibility Configuration Reduce LLM token usage by hiding tools from `tools/list` responses. This is a visibility optimization, not a security boundary — persona-level tool filtering continues to gate `tools/call`. ```yaml tools: allow: - "trino_*" - "search" - "fetch" deny: - "*_delete_*" description_overrides: trino_query: "Custom description for trino_query..." ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `tools.allow` | array | `[]` | Tool name patterns to include in `tools/list` | | `tools.deny` | array | `[]` | Tool name patterns to exclude from `tools/list` | | `tools.description_overrides` | map | `{}` | Override tool descriptions in `tools/list` responses. Config overrides take precedence over built-in defaults. | | `tools.result_budget.max_bytes` | int | `32768` | The context budget: the most of a rendered tool result a model client over MCP is handed. | | `tools.result_budget.per_tool` | map | `{}` | Per-tool overrides of `max_bytes` (tool name to bytes). | No patterns configured means all tools are visible. When both are set, allow is evaluated first, then deny removes from the result. Patterns use `filepath.Match` syntax (`*` matches any sequence of characters). ### Built-in Description Overrides The platform ships with built-in description overrides for `trino_query` and `trino_execute` that instruct agents to call `search` first for business context. These are always active and require no configuration. Use `tools.description_overrides` to customize or add more overrides; config entries take precedence over built-in defaults. #### Tool result context budget A model reads a tool result into its context, and a client refuses or spills a result past what it accepts (a 64,213-character result was measured refused). `tools.result_budget` is that budget, set once for the platform: ```yaml tools: result_budget: max_bytes: 32768 # default per_tool: trino_query: 65536 ``` It is enforced in one place, on the MCP response to a model, and only on a result the model can recover the rest of. Three tools qualify, because each has an export equivalent that returns the whole result without a context cost; each cuts in its own shape and says so. What is measured is the text the client receives, the platform's own additions (the call reference, enrichment) included. A result within the budget is untouched. | Tool | Past the budget | |------|-----------------| | `api_invoke_endpoint` | Re-encoded compactly first; if that is not enough a list body is cut on whole items, `body_truncated` is set, `body_items` reports how many are shown of how many, `next_arguments` is the call that reads on when the operation declares paging parameters, and `export_arguments` carries the `api_export` call that streams the whole response into an asset. A body with no list to cut is cut to a prefix, flagged, and steered to `api_export` | | `graphql_query` | Re-encoded compactly first; if that is not enough the list in `data` is cut on whole items, `data_truncated` is set, `data_items` reports how many are shown of how many, and `export_arguments` carries the `graphql_export` call. An answer with no list to cut has its `data` withheld whole (a JSON document cut in half cannot be parsed) | | `trino_query` | The most whole rows that fit are kept, in the format asked for; `result_truncated` and `rows_shown` say how many of `row_count`, and `export_arguments` carries the `trino_export` call | Every other result reaches the model whole, whatever its size: a knowledge page, `manage_script` help, a prompt, `platform_info`, an uploaded document read through `fetch`, an `s3_object` read, a proxied MCP tool's output. None of these has a way back to the rest, and a model reasoning from half a manual does worse than one whose client spills an oversized result to a file it can still read. The same holds when one of the three tools cannot cut a result recoverably (an answer whose `errors` alone are past the budget): it is returned whole. A fitted result's structured content is the fitted value too, so the message a client receives carries the cut result twice rather than the whole one. Only a model's call over MCP is held to the budget. A REST gateway call (`POST /api/v1/gateway/{connection}/invoke`), a managed script's run and an admin call are never fitted: a program that parses a response cannot read a cut one. Those callers meet only the real resource limits, a connection's `max_response_bytes` and the gateway's in-flight memory budget, and a response past `max_response_bytes` fails with an explicit error (`413` on the REST route) instead of arriving cut. The budget replaced `max_inline_bytes`, which was set per `api` and `graphql` connection. A connection that still carries it loads normally, the value has no effect, and a warning naming `tools.result_budget` is logged when the connection is read. ## Search-First Gate Configuration A hard gate that refuses query tools until the agent calls `search`. When a query tool (`trino_query`, `trino_execute`) is called before any discovery tool, the tool handler does not run; a `SEARCH_REQUIRED` error result is returned instructing the agent to call `search` first. Once `search` has been called at least once, every subsequent query tool call by the same authenticated user proceeds normally for as long as the platform session lasts: the search is remembered for the lifetime of the session handle `platform_info` mints (`sessions.handles.ttl`, 8 hours by default, extended while in use), or the Streamable HTTP session timeout when that is longer. Discovery is tracked per authenticated user (not per raw MCP session), so the gate is not falsely re-triggered by clients that open a new session for every tool call (for example claude.ai's web connector); it falls back to the session ID for unauthenticated callers. Enabled by default; set `require_search: false` to disable gating (and hinting) entirely. ```yaml workflow: require_search: false # Default: true (gate on). false disables it entirely. # discovery_tools: [] # Tools that satisfy the gate (defaults to search and fetch) # query_tools: [] # Tools that are gated (defaults to trino_query, trino_execute) ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `workflow.require_search` | bool | `true` | Enable the search-first hard gate. `false` disables gating with no block and no hint. | | `workflow.discovery_tools` | array | `search`, `fetch` | Tool names that satisfy the gate. `search` is the front door agents are steered toward, and `fetch` also counts: reading a dataset with its curation and lineage, or browsing a connection's catalog, discovers what a query needs. | | `workflow.query_tools` | array | `trino_query`, `trino_execute` | Tool names gated by discovery | `require_search` replaces the former `workflow.require_discovery_before_query` and its warn-after-execution behavior (breaking rename, not aliased). It is a hard gate: a deployment that never touched workflow gating will begin refusing `trino_query`/`trino_execute` until `search` is called once per session. ## Schema Gate Configuration A hard gate on the SQL tools (`trino_query`, `trino_execute`, `trino_export`) that refuses a statement against a table whose columns the agent has not read. A search hit names a table and describes it but does not list its columns, so an agent that goes from a search hit straight to SQL writes the column names it expects. A wrong guess fails; a guess that happens to name a real column (filtering on `id` when the record id is `p_id`) returns rows that look right and are wrong, and nothing reports it. - The first statement against an unread table is refused with a `SCHEMA_REQUIRED` error before it runs. The refusal lists every such table's columns and types, with the column comments and the catalog's column descriptions and glossary terms, so the agent can correct the statement without another call. Delivering the schema counts as reading it: the same statement sent again runs. The refusal's hint says how to avoid it next time: read a table's columns before the first SQL on it, with `trino_describe_table` or by fetching its `mcp:dataset` reference (#2810). - A table's schema has been read after `trino_describe_table` of the table, `fetch` of its `mcp:dataset` reference, a `DESCRIBE` or `SHOW COLUMNS` statement, a successful `SELECT *` of it, or a refusal or failure that delivered its columns. - A statement that names no column of the one table it reads runs without the table having been read (#2810): `SELECT *` or `SELECT count(*)` from one table, with at most an alias and `OFFSET`, `LIMIT` or `FETCH FIRST|NEXT n ROWS ONLY` after it. A successful `SELECT *` counts as the read, since its result names every column; `count(*)` names none and does not, so the next statement on the table that names a column is refused as before. Either shape with a `WHERE`, a join, a grouping, an ordering or a second table is an ordinary statement. - A statement other than those two shapes that fails because Trino has no catalog of the name it used (`Catalog '' not found` or `does not exist`), where `` is the name of a connection whose catalog is called something else, comes back with a sentence naming the catalog that connection reads and telling the agent to put the catalog in the SQL and the connection in the `connection` argument (#2812). - A statement that fails because a column or a type is wrong (Trino's `COLUMN_NOT_FOUND`, `TYPE_MISMATCH`, `AMBIGUOUS_NAME`, `MISSING_COLUMN_NAME`, `INVALID_COLUMN_REFERENCE` or `FUNCTION_NOT_FOUND`) comes back with the columns of each table it names. A timeout, an access denial or an outage comes back unchanged. This holds with `require_schema: false` too. - Never refused: a statement naming no table the platform can pick out, `information_schema` and `system` tables, a table whose schema cannot be read (Trino's own error for it stands), a managed script's run, a portal or REST shim run, and every tool other than the three SQL tools. - Reads are kept per caller under the same scope as the search-first gate, in the same store (shared across replicas when there is a database), for as long as a search is remembered. ```yaml workflow: require_schema: false # Default: true (gate on). false turns the refusal off. ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `workflow.require_schema` | bool | `true` | Refuse a SQL statement against a table whose columns the session has not read, returning the table's schema. Independent of `require_search`. | ## Session Gate Configuration A hard gate that refuses every non-exempt tool until the agent calls the session-initialization tool (`platform_info` by default) once in the session. Before the init tool runs, any other tool call is short-circuited before its handler executes and a `SETUP_REQUIRED` error result is returned (error category `setup_required`) telling the agent to call the init tool first, then retry. Once the init tool has been called, subsequent tool calls proceed until the session TTL expires. Unlike the default-on `*bool` sections, this gate is off by default: `enabled` is a plain bool, so an absent `session_gate` block means disabled. ```yaml session_gate: enabled: true # Default: false. true activates the gate. init_tool: platform_info # Tool that initializes the session (default: platform_info) exempt_tools: # Tools that bypass the gate entirely - list_connections ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `session_gate.enabled` | bool | `false` | Activate the session-initialization gate. | | `session_gate.init_tool` | string | `platform_info` | Tool that initializes a session; always exempt from the gate. | | `session_gate.exempt_tools` | array | (empty) | Tool names that bypass the gate and may be called before the init tool. | The gate's session-initialized memory expires after the session TTL, derived from `sessions.ttl` (falling back to the Streamable HTTP session timeout), not from a field on this block. The session gate is distinct from the search-first gate: the session gate requires an init tool (`platform_info`) before any tool; the search-first gate requires a discovery tool (`search`) before query tools. When explicit session handles (`sessions.handles`) are enabled, the session gate is skipped and handle resolution enforces initialization instead, carrying the gate's `exempt_tools` into the handle resolver. ## Purpose Configuration The one sentence an agent states about WHY a data-access call was made (top-level `purpose:` block, issue #1317). Audit records what a call did and, without this, never why. The platform advertises a `purpose` string property on the input schema of each gated tool via a tools/list decorator, takes the argument off the request in `MCPToolCallMiddleware` before the handler or a gateway-proxied upstream server can see it, and records it on the audit event's own `purpose` column (never in `parameters`, so the parameter redaction policy does not apply to it; the admin events search matches it). Named `purpose`, not `intent`, because `search.intent` is the query text and keeps that meaning. Enabled and required by default. ```yaml purpose: enabled: true # Default: true. false removes the argument entirely. require: true # Default: true. false records when present, never refuses. tools: # Override the gated set; empty means the default below. - search - trino_query - "s3_*" - "kind:mcp" ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `purpose.enabled` | bool | `true` | Advertise, strip, and record the `purpose` argument. | | `purpose.require` | bool | `true` | Refuse a gated call that states none with `PURPOSE_REQUIRED` (error category `purpose_required`). | | `purpose.tools` | array | see below | Gated set: tool-name globs (`filepath.Match`) plus `kind:` entries. | Default gated set: `search`, `fetch`, `trino_query`, `trino_execute`, `trino_export`, `trino_describe_table`, `api_invoke_endpoint`, `api_export`, `s3_object`, `s3_list`, `save_asset`, `manage_asset`, and `kind:mcp` (every tool an MCP gateway connection proxies, whose names are chosen upstream and cannot be written as a glob). The two asset tools are in the set because an asset is the one output a person opens weeks later, often someone who was not there when it was made, and the first question they ask is what it was for (#1695); `manage_asset` is named whole, so its reads state a purpose alongside its writes, since the gate decides from a tool name and one name covers both halves. `apply_knowledge` stays outside on its own reasoning -- what an apply_knowledge call applies is itself the explanation, while an asset is the output and not the reason for it. The rest of the orientation and platform-management surface (`platform_info`, `list_connections`, `memory_*`, the other `manage_*` tools) is deliberately outside it: their purpose is their name. One predicate (`middleware.PurposeResolver.Gates`, deciding from tool name plus toolkit kind) drives both the advertisement and the enforcement, so what the platform asks for and what it enforces cannot drift, and both are replica-stable without either request remembering the other. `require: true` refuses ONLY a caller that threaded an explicit `session_id` handle on the same call, which is the platform's only proof that a caller can thread a platform-injected argument. That single condition subsumes every exemption: an MCP App's sandboxed call is session-adopted from its authenticated identity and threads nothing (#1040); the gateway REST shim, the admin tool runner, and a managed script drive a fresh in-memory session per request and thread nothing (#811); an isolated `dpp_`/`dpx_` run has its session minted server-side (#859). Consequently `sessions.handles.enabled: false` also stops purpose from ever being required, though it is still advertised and recorded. A stated purpose is trimmed and bounded to 1000 runes before it reaches the audit row. The agent instructions name the gated set rather than a category (#1640): the tools the configured set NAMES and the caller can reach, listed, plus a clause per `kind:` entry it gates wholesale ("every tool served by a connection of kind `mcp`"). The kind is named rather than expanded because one MCP gateway connection can proxy more tools than the platform's own data-access surface has, under names the platform did not choose and that change when the upstream does. `middleware.PurposeResolver.GatesByName` is the split, so the description and the enforcement still come off one resolver. What the gate decides is where the argument is advertised and where a MISSING one refuses the call, not whether a stated one is understood. A `purpose` stated on an UNGATED tool is taken off the request and recorded on the audit row exactly as a gated one is (#1640): tool input schemas are closed to unknown properties (#1057), so leaving it in place refused the call with `invalid_arguments` for stating what the platform's own instructions asked the model to state, and the corrective hint then told the agent to drop a property those instructions required. The argument is taken on every tool the platform DEFINES, gated or not; a tool proxied from an upstream MCP server (`registry.ToolkitMatch.Kind == "mcp"`) is the one place the platform did not choose the parameter names, so when such a tool is outside the gated set its `purpose` is recorded and still delivered to the upstream — which is what makes dropping `kind:mcp` from `purpose.tools` the remedy for an upstream server that defines its own `purpose` parameter. ## Tool Annotations Every tool the platform registers advertises MCP tool annotations on `tools/list` (issue #1692). `readOnlyHint` is `true` when no call to the tool modifies state; `destructiveHint` is stated on every write (`true` when some action removes or overwrites, `false` when every action only adds, because the specification's default for an absent one is `true`); `idempotentHint` is `true` on a read. The specification tells a client to assume a tool is NOT read-only when `readOnlyHint` is absent, and clients that act on that ask the user to confirm every unannotated call, so the mandatory opening sequence `platform_info` then `search` then `fetch` arrived as three write confirmations before any data. The hint describes the tool rather than the call: `manage_asset`, `manage_table`, `manage_resource`, `manage_prompt`, `manage_script`, `memory_manage` and `s3_object` expose reads alongside writes and each advertises the most it can do. Read-only: `platform_info`, `search`, `fetch`, `list_connections`, `api_discover`, `graphql_discover`, `s3_list`, plus the upstream reads `trino_query`, `trino_browse`, `trino_describe_table`. `toolkit.ReadOnlyAnnotations()` and `toolkit.WriteAnnotations(destructive)` are the two shared constructors a registration states its classification with. `internal/toolwrite.ReadOnly` is the platform's other per-tool statement about whether a tool writes — it is what a managed script's draft run consults — and a structural gate (`TestAnnotationsAgreeWithToolwrite`) fails the build when the two disagree, so a tool cannot be advertised read-only and refused inside a draft. A second gate (`TestEveryToolLiteralIsAnnotated`) fails when a registration sets no `Annotations` or no `Title`. A tool proxied from an upstream MCP server carries the upstream's annotations unchanged, including none; the trino and s3 toolkits take theirs from the upstream libraries, overridable per deployment under a toolkit's `annotations:` key. The admin API returns the same object (#1706): `GET /api/v1/admin/tools/schemas` carries `annotations` on each tool and `GET /api/v1/admin/tools/{name}` carries it on the detail, both read from the server's own `tools/list` after any override, with the MCP keys unchanged (`readOnlyHint`, `destructiveHint`, `idempotentHint`, `openWorldHint`) and the key absent for a tool that states none, `destructiveHint` and `openWorldHint` kept absent rather than false when unstated. The portal's Tools page shows them as badges on the tool header: read-only, additive (a write stating `destructiveHint: false`), destructive (any other write, since an unstated `destructiveHint` defaults to true), idempotent, and "no hints" for a tool advertising none, which is where an operator checks that an `annotations:` override took effect. ## Tool-Call Rate Limiting A per-identity safety net on authenticated `tools/call` requests (top-level `rate_limit:` block). It bounds a runaway agent loop or a compromised account before it can saturate the audit pipeline, the shared database pool, or an upstream (Trino, S3, a proxied MCP server); it is not a throughput throttle: the default limit is generous enough that ordinary interactive and agent use never touches it. Over-limit calls are short-circuited before the handler runs and outer to the audit/enrichment middleware, so a refused call consumes no handler, audit, or upstream work; the caller receives a `RATE_LIMITED` in-band error result (error code and category `rate_limited`) with a retry hint so an agent backs off rather than seeing a transport failure, and the structured envelope carries the interval as `retry_after_seconds` beside `code`, `category`, `message` and `hint`. A platform run of a managed script is queued, not refused: its calls cross the limiter as the script principal (`AuthType` `script`), and when the bucket is empty the limiter holds the call until the sustained rate refills a token and admits it, so a run's throughput is governed by the sustained rate and its calls never see `RATE_LIMITED`; a queued call does not count in `mcp_rate_limited_total` or log a warning but counts in `mcp_rate_limit_queued_total` and logs at Info under the run id, and a run canceled or reaching its deadline while a call is held ends then. A draft run carries its author's own identity and is refused as any interactive call is; there the script host waits `retry_after_seconds`, bounded by the run's deadline, and issues the call again, so the script sees only the admitted call's result and the wait is recorded in the run's log (a run whose deadline arrives while waiting fails as a timeout and is not re-queued). `platform_info` is always exempt so a throttled agent can re-read platform guidance. The limit is keyed on the authenticated user (not the client IP: a multi-user connector delivers all traffic from one egress, so per-IP limiting would be useless and would let one user starve the rest); shared/anonymous identities (auth disabled) fall back to a per-session key, and a call with no attributable identity is not limited (fail-open, since it has already passed auth). The token bucket is in-memory per replica, so behind a load balancer the effective ceiling is N times the configured limit (intentional for a backstop, since distributed coordination on the hot tool path is not warranted). Each refusal increments `mcp_rate_limited_total`; each call a script principal was held for increments `mcp_rate_limit_queued_total`. Enabled by default; set `rate_limit.enabled: false` to remove the limiter from the chain, for scripts as for everyone. This is unrelated to `oauth.rate_limit`, the per-IP limiter on the unauthenticated `/token` and `/register` endpoints. ```yaml rate_limit: enabled: true # Default: true. false removes the limiter. requests_per_minute: 240 # Default: 240. Sustained per-user tools/call rate (4/second). burst: 60 # Default: 60. Largest instantaneous per-user burst. exempt_tools: # Never limited (platform_info is always exempt) - search ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `rate_limit.enabled` | bool | `true` | Enable the per-user tool-call limiter. `false` removes the middleware from the chain. | | `rate_limit.requests_per_minute` | int | `240` | Sustained per-user `tools/call` rate (token refill). | | `rate_limit.burst` | int | `60` | Token-bucket depth: largest burst a single user may issue before the sustained rate governs. | | `rate_limit.exempt_tools` | array | (empty) | Tool names never rate limited, in addition to the always-exempt `platform_info`. | ## Portal Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `portal.enabled` | bool | `false` | Enable portal toolkit and save_asset/manage_asset/manage_feedback tools | | `portal.s3_connection` | string | - | Name of the S3 toolkit instance for asset storage | | `portal.s3_bucket` | string | `portal-assets` | S3 bucket for asset content | | `portal.s3_prefix` | string | `artifacts/` | Key prefix every asset object is written under: content and versions from the portal, the admin console, the asset tools, the exports and script outputs, and collection mosaics (`collections//thumbnail.png`), all through `portaldomain.AssetContentKey` and `portaldomain.CollectionThumbnailKey` (#1903). Releases before that wrote portal and admin edits and mosaics under a fixed `portal/`; those objects keep the key their row recorded and stay where they are, and a mosaic moves under the prefix the next time it is drawn | | `portal.deleted_retention_days` | int | `30` | How long a soft-deleted asset, collection, feedback thread or knowledge page is kept before it is hard-purged with every version object, tile and mosaic it names, and its shares, collection places and threads (#1904). `0` = default, negative keeps them. A hidden built-in knowledge page is never purged. An asset whose object will not delete keeps its row for the next day's sweep | | `portal.orphaned_producer_retention_days` | int | `90` | How long a `content_producers` row outlives its asset or resource (#1904). `0` = default, negative keeps them | | `portal.public_base_url` | string | `""` | Base URL for portal links in save_asset responses | | `portal.max_content_size` | int | `10485760` | Maximum asset size in bytes (10 MB) | | `portal.max_versions` | int | `100` | Versions an asset keeps when it carries no override of its own. A version pushed past the cap is deleted along with its stored content and thumbnails; the current version is never pruned. `0` keeps every version, and a negative value is refused at startup. Applied at the write, so an asset already over the cap is trimmed the next time it is written. An asset's owner (or an admin) can override it, from the portal metadata form, `manage_asset` action `update` with `max_versions`, or the admin asset route | | `portal.implementor.name` | string | `""` | Implementor display name shown in the left zone of the public viewer, the public collection viewer, the guest share landing page, and the access-denied page. Independent of `portal.implementor.logo`: either one alone renders the implementor block | | `portal.implementor.logo` | string | `""` | URL to the implementor logo in any image format. The viewer and share pages link it with an `` element; its origin is added to the `img-src` of the pages whose policy would otherwise block it. Renders with or without `portal.implementor.name` | | `portal.implementor.url` | string | `""` | Clickable link wrapping the implementor name and logo | | `portal.terms_url` | string | `""` | Terms-of-service link rendered in notification email footers | | `portal.privacy_url` | string | `""` | Privacy-policy link rendered in notification email footers | | `portal.export.enabled` | bool | auto | Enable trino_export tool (auto-enabled when portal + trino configured) | | `portal.export.max_rows` | int | `100000` | Hard row cap for exports | | `portal.export.max_bytes` | int | `104857600` | Hard byte cap for formatted output (100 MB) | | `portal.export.default_timeout` | string | `"5m"` | Default query timeout for exports | | `portal.export.max_timeout` | string | `"10m"` | Maximum allowed query timeout for exports | The asset reference route (`/portal/refs/`) has a limiter of its own sized at `assetrefs.MaxRefs` (20) times the `portal.rate_limit` values after their defaults are applied, so a deployment with no `portal.rate_limit` block gets 1,200/min and a burst of 200 per client rather than the unscaled 60/10 (#1791); the thumbnail renderer's in-process requests to it are not counted. Portal requires `database.dsn` for metadata storage and at least one S3 toolkit instance for asset content. ## Admin API Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `admin.enabled` | bool | `true` | Enable admin REST API. Set `false` to disable. Routes still require admin-role auth to use. | | `admin.persona` | string | `admin` | Persona required for admin access | | `admin.path_prefix` | string | `/api/v1/admin` | URL prefix for admin endpoints | Branding fields have moved to the `portal:` section: | Field | Type | Default | Description | |-------|------|---------|-------------| | `portal.enabled` | bool | `false` | Enable portal SPA frontend and asset API | | `portal.brand_name` | string | mcpapps `brand_name` | Deployment brand; composes the portal title as ` Portal` and names the public viewer header, branded denial pages, and built-in MCP Apps. Falls back to `brand_name` in `mcpapps.apps.platform-info.config` when MCP Apps are enabled | | `portal.brand_url` | string | mcpapps `brand_url` | Brand home page; the sidebar brand mark (logo and name) links to it in a new tab. Unset leaves the mark inert. Falls back to `brand_url` in `mcpapps.apps.platform-info.config` when MCP Apps are enabled | | `portal.version_url` | string | `""` | Link target for the version number in the portal header (release notes or changelog). Unset leaves the version as plain text. Served on the unauthenticated branding endpoint | | `portal.title` | string | ` Portal`, else `MCP Data Platform` | Sidebar/branding title text; composed from `brand_name` when unset. A brand already ending in "Portal" is not doubled. Only a `brand_name` set in the `portal` block composes the title, so an mcpapps-inherited brand leaves an existing deployment's title unchanged | | `portal.tagline` | string | `Sign in to access the platform.` | Login-screen subtitle text | | `portal.oidc_button_label` | string | `Sign in with OIDC` | Login-screen SSO button text (e.g. "Sign in with ACME Keycloak") | | `portal.feedback.standalone_recipients` | list | `[]` | Seeds who hears about a General feedback post (#2603) until an administrator saves Admin > Settings > General feedback (`general_feedback` section, `GET`/`PUT /api/v1/admin/settings/general-feedback`): entries are an address, `persona:` or `channel:`; empty seeds the administrator persona. The list's people (persona members from the user directory plus addresses) are told of a new General post and every reply, its channels of the new post, the email links to `/portal/feedback#thread-`, and acknowledge_author sends the poster a "Your feedback was received" email naming nobody, only when someone was told; a post reaching nobody is logged; `GET /api/v1/portal/feedback/general` answers reaches_someone only. A thread on an item whose owner cannot be found falls back to the list under the item's access. | | `portal.login_redirect` | bool | `false` | Send a signed-out portal visitor straight to the identity provider (`/portal/auth/login` with the page opened as `return_to`) instead of the login screen. In force only with `auth.oidc.enabled` and `auth.browser_session.enabled`; otherwise logged as `login_redirect_ignored` and ignored. An error back from the provider (`/portal/?error=access_denied`) is shown with a Try again button and is not redirected again. The public branding endpoint reports `login_redirect` | | `portal.allow_api_key_login` | bool | `true` | With `login_redirect` on, whether `/portal/?login=api_key` shows the login screen with the API key form; `false` sends that address to the identity provider too. Portal login screen only: API keys keep working on the MCP endpoint and the REST API. Reported by the public branding endpoint | | `portal.logo` | string | `""` | Logo URL (fallback for both themes) | | `portal.logo_light` | string | `""` | Logo URL for light theme | | `portal.logo_dark` | string | `""` | Logo URL for dark theme | | `portal.logo_email` | string | `""` | Raster PNG logo URL for notification emails (fetched at startup, max 1 MB) | | `portal.implementor.name` | string | `""` | Implementor display name (left zone of the public viewer, the collection viewer, and the share pages); renders with or without a logo | | `portal.implementor.logo` | string | `""` | URL to the implementor logo in any image format, linked by the viewer and the share pages; renders with or without a name | | `portal.implementor.url` | string | `""` | Clickable link wrapping implementor name and logo | | `portal.terms_url` | string | `""` | Terms-of-service link rendered in notification email footers | | `portal.privacy_url` | string | `""` | Privacy-policy link rendered in notification email footers | When `portal.enabled: true`, an interactive web dashboard is served at `/portal/`. It provides audit log exploration, tool execution testing, and system monitoring. The sidebar displays a configurable logo and title. Theme-specific logos are resolved as: light theme uses `logo_light` → `logo` → built-in default; dark theme uses `logo_dark` → `logo` → built-in default. The resolved logo is also used as the browser favicon, and `/favicon.ico` answers without a session (#2460): a redirect to `logo_light`, else `logo`, else the built-in icon, named as the icon by the portal shell and the public share pages. Shared asset links (`/portal/view/{token}`) display a two-zone header: the right zone shows the platform brand, and the optional left zone shows the implementor brand configured via `portal.implementor`. Both logos may be any image format, and the pages link them with an `` element at the configured URL rather than embedding them; the guest share pages and the branded denial page add that URL's origin to their `img-src`, and a deployment with no logo configured keeps a policy that loads no remote image. The exception is a built-in MCP App, which runs in a sandboxed iframe that blocks external loads: its config carries the logo inline, fetched once at startup — an SVG as its own markup, any other format as a `data:` URI — and a logo that is unreachable, larger than 1 MB, or not an image logs one warning naming the URL and the reason. Notification emails cannot reuse these logos because mail clients strip inline SVG; set `portal.logo_email` to a raster PNG URL, which is fetched once at startup and attached to each message as an inline part so it renders without remote-image loading. It is additive to the brand wordmark, which also serves as the image's alt text, and leaving it unset renders the wordmark alone. The public viewer supports light/dark mode (system default with toggle, persisted to localStorage), an expiration countdown notice showing relative time until share expiry, and a configurable per-share notice text. The `notice_text` field defaults to "Proprietary & Confidential. Only share with authorized viewers." — set it to a custom string for different text, or to `""` (empty string) to hide the notice entirely. Only a public link is created with an expiry, so the countdown is driven by the share's own `expires_at` rather than by its access mode — shares created before that rule keep the expiry they were given. Set `hide_expiration: true` to hide the countdown from the viewer. Every share carries an `access_mode` deciding who its token opens for: `restricted` (only the named recipient and the share's creator), `authenticated` (any signed-in platform user), or `public` (anyone with the link, without signing in). A create-share request that names a recipient and no mode is `restricted`; one that names neither is `authenticated`. `public` is never implied and must be requested; `restricted` without a recipient is rejected with 400. Enforcement is a single gate (`publicShareGate`, `pkg/portal/share_access.go`, deciding via `pkg/portal/shareaccess`) wrapping every route under `/portal/view/` (the page, `/content`, `/thumbnail`, `/collection-thumbnail`, and the three `/items/{assetId}/...` routes), so no route can serve bytes the mode refuses. A caller who is not admitted receives 403 with the reason; revoked and expired tokens still return 410. The gate also writes the response's cache policy, so a per-caller verdict cannot be cached under a per-URL key: `Vary: Cookie` everywhere, `Cache-Control: private` for every mode but `public`, `no-store` on refusals, and `public` only on a fully public share's thumbnail, with `max-age` clamped to the smaller of an hour and the share's remaining life so no stored copy outlives the token (revocation is the residual: a copy a shared cache already holds is served until it goes stale). Migration 000083 backfills existing rows: recipient present becomes `restricted`, recipient absent becomes `authenticated`, so previously distributed links stop resolving anonymously. Who may act on a portal item is resolved by one seam per authority rather than by an ownership comparison repeated at each route (`internal/portal/access`). `CanManage(ownerID, user)` is owner-or-admin and gates deleting an asset or collection, creating a share, reading a share list, and revoking one; `CanManageEmail` is its form for prompts, whose ownership is an address. `CanEditCollection` is owner-or-admin-or-Editor and gates the four operations that shape a collection as a document — name and description, display config, sections, thumbnail — so an Editor share on a collection means something about the collection and not only about the assets inside it. The split is deliberate: an Editor edits, but destruction and re-granting access stay owner authority, which is why delete, share, and share-list remain on `CanManage`. The admin arm never grants more than an admin already holds, since the admin API reads, edits, and deletes any asset outright; withholding the weaker right to share one was an artifact of the gate, not a policy, and it stranded content owned by a non-human principal (an API-key session owns its assets as `@apikey.local`, an identity nobody can sign in as). `GET /portal/collections/{id}` reports the resolved `can_edit` and `can_manage` beside `is_owner`, so the page offers exactly the actions that will succeed instead of rendering a form the server refuses on submit. View gates are unchanged: an admin still reaches another principal's collection through the admin surface, not through the portal's own read routes. ## Resource Templates Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `resources.enabled` | bool | `true` | Serve the MCP resource templates. Read-only, so default on; set `false` to disable | When enabled, three RFC 6570 URI templates are registered: - `schema://{catalog}.{schema_name}/{table}` — Table schema with semantic context - `glossary://{term}` — Glossary term definition and related assets - `availability://{catalog}.{schema_name}/{table}` — Data availability status and row count ## Argument Autocompletion (completion/complete) The platform serves the MCP `completion/complete` request so completion-capable clients suggest valid values as a user types. The capability is advertised automatically whenever prompts or resource templates are available (no configuration). Prompt arguments are routed by name across built-in and database prompts: `dataset` gives dataset names from the semantic index; `topic` gives domains, data products, and glossary terms; `connection` gives configured connection names. Resource-template variables complete from the query engine: `schema://`/`availability://` `catalog`/`schema_name`/`table` (each variable completes once its predecessors are chosen), and `glossary://` `term` from the glossary index. Completions are persona-filtered like `tools/list` and `search` (dataset/topic/glossary require `search`; catalog/schema/table require `trino_browse`; connections require `list_connections` and are further filtered by persona connection rules); unauthenticated sessions get nothing, and each lookup runs under a short latency budget that degrades to an empty list on upstream failure. A response carries at most 100 values; `hasMore` is set from the catalog's own match count (never inferred from the number of rows a page returned, which a catalog may clamp below what was requested) and `total` only when the returned set is provably complete — a catalog that cannot count leaves both omitted. ## Custom Resources Configuration Custom resources expose arbitrary static content as named MCP resources. Registered whenever `resources.custom` is non-empty, independent of `resources.enabled`. Content can be inline (`content`) or read from a file on every request (`content_file`, supports hot-reload). | Field | Type | Default | Description | |-------|------|---------|-------------| | `resources.custom[].uri` | string | — | Unique resource URI, e.g. `brand://theme` (required) | | `resources.custom[].name` | string | — | Display name shown in `resources/list` (required) | | `resources.custom[].description` | string | `""` | Optional description for MCP clients | | `resources.custom[].mime_type` | string | — | MIME type, e.g. `application/json`, `image/svg+xml` (required) | | `resources.custom[].content` | string | — | Inline text/JSON/SVG content; mutually exclusive with `content_file` | | `resources.custom[].content_file` | string | — | Absolute file path; read on every `resources/read` request | Example — inline JSON brand theme and file-backed SVG logo: ```yaml resources: custom: - uri: "brand://theme" name: "Brand Theme" mime_type: "application/json" content: '{"colors":{"primary":"#FF6B35"},"url":"https://example.com"}' - uri: "brand://logo" name: "Brand Logo" mime_type: "image/svg+xml" content_file: "/etc/platform/logo.svg" ``` Invalid entries (missing URI, name, or mime_type; both or neither content fields) are skipped with a warning; valid entries in the same list are still registered. ## Managed Resources Configuration Managed resources are human-uploaded reference files (data, samples, playbooks, templates, references) stored in S3 with metadata in PostgreSQL. They are surfaced to AI assistants via the standard MCP `resources/list` and `resources/read` protocol, and managed through a REST API and the Admin Portal. | Field | Type | Default | Description | |-------|------|---------|-------------| | `resources.managed.enabled` | bool* | auto | Enable managed resources. nil = auto (enabled when database is available) | | `resources.managed.uri_scheme` | string | `"mcp"` | URI scheme prefix for resource URIs | | `resources.managed.s3_connection` | string | `""` | Name of the S3 toolkit instance used for blob storage | | `resources.managed.s3_bucket` | string | `managed-resources` | S3 bucket for resource file blobs | | `resources.managed.max_versions` | int | `10` | Content revisions kept per resource, counting the current one. A revision past the cap deletes the oldest version's blob; the live content is never pruned. Non-positive selects the default; below 2 is raised to 2 | | `resources.managed.extract.max_member_bytes` / `max_total_bytes` / `max_members` / `max_ratio` | int64 / int64 / int / int64 | 2 GiB / 4 GiB / 100000 / 500 | Limits on `manage_resource extract` (#1879); see "Archive extraction limits" below. Independent of `max_upload_bytes` | | `resources.managed.max_upload_bytes` | int64 | `1073741824` (1 GiB) | Largest file `POST /api/v1/resources` and `POST /api/v1/resources/{id}/content` accept. Non-positive selects the default, 1 GiB since #2069. The refusal names this deployment's number, and the portal's file chooser reads it from `GET /api/v1/portal/me` rather than holding a second copy. It bounds bytes streamed rather than bytes held: the upload path streams into the multipart uploader (see below). A CSV or JSON-lines table registration reads by `table_registration_max_bytes` instead: unset, this number when it is set (#1634), else 100 MB (#2069) | Example: ```yaml resources: managed: enabled: true uri_scheme: "mcp" s3_connection: "primary" s3_bucket: "platform-resources" max_versions: 10 max_upload_bytes: 104857600 extract: max_member_bytes: 2147483648 max_total_bytes: 4294967296 max_members: 100000 max_ratio: 500 ``` #### Archive extraction limits (`resources.managed.extract`) `manage_resource action=extract` (#1879) writes the members of a stored zip, gzip or gzipped tar out as managed resources, and `resources.managed.extract` bounds it. `max_member_bytes` (default 2 GiB) is the largest one member may be uncompressed; `max_total_bytes` (default 4 GiB) is the most the selected members may add up to; `max_members` (default 100000, raised from 10000 by #2593 so one archive carries a site's media folder) is how many entries an archive may hold, directories included, and since a zip's directory is read whole to open it (`archive/zip.NewReader`), it is checked against the count the end-of-directory record declares, zip64 locator followed, before the directory is parsed; `max_ratio` (default 500) is the furthest a member may expand past its compressed size, checked once a member passes 1 MiB. Each field takes its default when absent, zero or negative. The struct is `unarchive.Limits` (`internal/unarchive`), used directly as the config section, so the key a `LimitError` names is the key an operator sets. The limits are apart from `max_upload_bytes` on purpose: an archive is delivered by an upstream rather than picked at an upload form, and the file inside a monthly delivery is routinely several times the upload ceiling, so the extractor lands each member with an unbounded lander ceiling (`Lander.landPlanned` with ceiling 0) and enforces its own limits in the archive reader. `manage_resource action=upload_link` (#2639, #2844), or Upload > Upload link... on the Resources page (Upload link here... on empty space), makes a link on the platform's own origin (`portal.public_base_url`) that files are PUT to from an agent's shell or by an external service: given the folder (`path`, `scope`), `content_type`, `size_bytes` (the most each file may be, at most the upload limit), `max_files` (1 to 100, default 1), optional `filename` (only for one file) and `ttl_seconds` (900, at most 86400), it answers `id`, `upload_url`, `method` PUT, `expires_at`, `max_bytes`, `max_files`, `name_in_url` and an example curl. A link with a filename takes `PUT /api/v1/resources/uploads/{token}`; one without takes `PUT /api/v1/resources/uploads/{token}/{filename}`, a plain file name (no session or key: the link is the credential). Each file is filed in the folder as the link's maker through the writer manage_resource uses, with the upload limit, denied types and if_exists, answering 201 with the reference and `files_remaining`; a place is taken by one atomic statement, and a PUT that files nothing (413 past the size, 422 a refused type) gives it back so the service can retry; a full, revoked, expired or unknown link answers 404 alike. Only the token's SHA-256 is stored (`resource_upload_links`, migrations 000252 and 000272: max_files, files_used, resource_ids, revoked_at; a link used before 000272 counts as full); links swept 7 days after expiry. The Resources page's Upload > Upload links lists the caller's open links (folder, type, files filed, expiry; never the token) and revokes one (`GET|POST /api/v1/resources/upload-links`, `POST /api/v1/resources/upload-links/{id}/revoke`; an administrator revokes anyone's). A saved script's run may ask for a link to hand a service; its recording keeps the link and is read only by the script's owner and administrators. The sites-from-source page names upload links as the way to load a source tree or media set from the agent's machine. `manage_resource action=download_link` (#2847), or Copy link on a file (its menu, or beside Copy URI in the preview pane), gives a URL on the platform's public address, ending in the file's name, that anybody holding it downloads the file from with no session or key, for a connection or service that takes a file by URL. `expires` is `single_download` (default: ends after the first full GET, or an hour; a HEAD or a byte-range read does not count) or `6h`. The file is served as a download (attachment, nosniff). The link is the asset content URL's signed token (`internal/portal/contenturl`) under its own key derived from the browser-session signing key, with a per-link id for a single download whose use is recorded in `resource_download_uses` (migration 000273) so every replica refuses a second; an expired, used or altered link answers 403, a deleted file or another name 404. Without `auth.browser_session.signing_key` or `portal.public_base_url` no link is made. Routes: `GET /api/v1/resources/{id}/download-link?expires=`, `GET /api/v1/resources/downloads/{token}/{filename}`. Extraction streams both ways: the archive is read by range (`GetObjectRange`) through a two-block cache of 8 MiB blocks, and each member is streamed into `PutObjectStream`. A zip declares every member's name, size, flags and method up front, and a gzipped tar is read through once before its members are written, so for both every refusal (unsafe name, encryption, method, limit, empty selection) comes before the first write; a plain gzip's single member has no declared size, so its limits are enforced as it streams, and a gzip past one leaves nothing stored because its one multipart upload is abandoned. #### What raising `max_upload_bytes` costs The upload path streams (#1631). A request walks the multipart form part by part (`r.MultipartReader`, `pkg/resource/handler.go`) and hands the `file` part to the multipart uploader as a reader (`S3Client.PutObjectStream`, `pkg/resource/store.go`), so the object is never assembled: not in one `[]byte`, and not in a temporary file. What a request holds is the uploader's part buffers plus `contenttype.StructuredSniffLen` (8 KiB) for content detection, whatever the ceiling is. Two consequences, both of which were true the other way before: the upload path needs no writable temporary directory, which is what the published `FROM scratch` image has; and blob storage is written through multipart, so a backend that bounds a single `PutObject` — MinIO refuses one above 16 MiB under the `aws-chunked` encoding the AWS SDK uses over HTTPS — takes a file of any size the ceiling allows. The READ path has not changed shape: `GetObject` returns a `[]byte`, so serving a large managed resource still holds it. Every other object write goes the same way since #1863: the portal's blob adapter sends a buffered `PutObject` through the multipart uploader (8 MiB parts, a body under one part still one request), which covers `platform.export` to the portal, `trino_export` and portal content edits, and `s3_object action=put`, which a script's bucket destination delivers through, streams when the connection's client has the uploader. `manage_script help` states the per-output ceiling as `limits.output_max_bytes` (100 MiB). The ceiling is enforced on the bytes streamed, since a streamed part declares no length: the read that passes it fails, the uploader aborts the incomplete multipart upload, and the route answers 400 naming this deployment's number. The request body is separately bounded at the ceiling plus 64 KiB of multipart framing headroom as a backstop against a body with no end, so a file of exactly the ceiling is still accepted. A table registration reads by this same ceiling (`registrationMaxBytes`, `internal/httpserver/tablemounts.go`, feeding `tableregister.Deps.MaxBytes`). It was a compiled-in `DefaultMaxBytes` of 100 MB, written to track the upload cap back when that cap was also compiled in; #1628 made the cap configurable and the constant did not follow, so a deployment that raised its ceiling stored CSVs no registration would read (#1634). The registration read holds the whole object, unlike the upload, because the header row and the line-shape check need the bytes (#1441). Both write routes read the form IN ORDER and stop at the `file` part, because that part is handed to the uploader where it is found. Every other field (`scope`, `scope_id`, `path`, `display_name`, `description`, `tags`) has to arrive before it; a form that puts a part behind the file is refused with `the file part must be the last part of the form`, and because the refusal happens while the file is being read, no object and no record survive it. The portal appends its file last (`draftForm`, `ui/src/pages/resources/modals/UploadModal.tsx`). Two things a raised ceiling does not change: content indexing still stops at `MaxContentReadBytes` (8 MiB), so a file above that is indexed on its metadata alone whatever the ceiling is; and an ingress or proxy in front of the platform enforces its own body limit, which has to be raised too or a request the platform would accept never reaches it. ### Scope Model Resources are assigned one of three visibility scopes: | Scope | Visibility | scope_id | Example URI | |-------|-----------|----------|-------------| | `global` | All authenticated users | (empty) | `mcp://global/templates/query-patterns.sql` | | `persona` | Users operating under the named persona | persona name | `mcp://persona/analyst/playbooks/data-quality-checklist.md` | | `user` | Only the owning user | user subject ID | `mcp://user/abc123/references/my-notes.txt` | ### URI Scheme Resource URIs follow the pattern: `{scheme}://{scope}/{scope_id?}/{path}/{filename}`, where `path` is the slash-separated folder path the resource is filed under - Global: `mcp://global/{category}/{filename}` - Persona: `mcp://persona/{persona_name}/{category}/{filename}` - User: `mcp://user/{user_sub}/{category}/{filename}` ### Categories Resources must be assigned a folder path (#1529): slash-separated, each segment lowercase alphanumeric with hyphens starting with a letter or digit (#1886; the webhook compactor files windows under dated folders) and at most 31 chars, at most 8 segments and 200 characters overall, no empty segment, no leading or trailing slash, no `.` or `..`. `ValidatePath` (`pkg/resource/path.go`) names the rule a refusal broke rather than restating the grammar, and it refuses depth before length because removing folders is what fixes a path that breaks both. Every segment keeps the rule the flat `category` column carried, widened to a leading digit, so every pre-tree row is a legal one-segment path, migration 000130 rewrites no rows and no existing URI changes. Folders are STORED (#1872, migration 000160 `resource_folders`, one row per folder, NULL `scope_id` for global like `resources`, unique on `(scope, COALESCE(scope_id,''), path)`): a folder exists once it is created (`POST /api/v1/resources/folders`, the authority an upload into that library takes) or a resource is filed under it, and it stays when its last file leaves. Every insert and move records the folder chain in the same transaction, the migration recorded every folder in use, and `Store.Folders` is the union of the stored rows and the paths in use, so a writer that skips the chain hides nothing. The file manager's Delete dialog opens at once for a selection holding a folder and counts the files inside it itself, showing "Counting files..." with its confirm disabled until the count is in, and showing a failed count inside the dialog with Retry; a second Delete while a dialog is open starts nothing (#1887; before, the dialog rendered nothing until the folder's listing returned, and a read that took 12-30 s on the reference install looked like a dead button). `DELETE /api/v1/resources/folders` removes a folder and the stored folders beneath it and answers 409 while any resource is filed there; a folder move rewrites the stored folders beneath it in the same transaction as the resources (`FolderStore.MoveFolderTree`) and moves a folder that holds only empty folders. The portal suggests six first-level names (`data`, `visual`, `samples`, `playbooks`, `templates`, `references`, in `SEED_FOLDERS`, `ui/src/pages/resources/parts/PathField.tsx`) as completions rather than as a closed set; the server validates the shape of a path and not its membership. The library is browsed as a TREE of folders (#1530). `folderView` (`ui/src/pages/resources/parts/tree.ts`) divides whatever is loaded into the folders and files at one location; a folder's count is everything beneath it at every depth, and while further pages remain it is written `12+`, because it is how many have arrived and not how many the folder holds. The location is in the ROUTE, not the query string: `/resources/lib//` and `/admin/resources/lib//`, always at least two segments after the section so it can never be confused with `/resources/{id}`, which is exactly one -- `readPath()` drops the query string, so a location kept there is one the page cannot see on a nav-link push (#1470). Each level is a distinct address, so a reload returns to it, a link opens it, and Back steps out one folder. Filters (q, tag, sort) stay in the query and are written with replace. Search spans the WHOLE library rather than the folder in view -- the path filter is dropped while a query runs -- and each hit carries the path it was found at with a Reveal control that walks the tree to it. A folder whose resources are all images renders as a grid of tiles instead of rows -- decided by the content, not by the folder name, so a photograph filed under `references` is shown as a photograph and a written note filed under `visual` is shown as a row; on the administrator's page a tile also carries the scope badge and never-read flag its table columns carry. A resource has no stored thumbnail, so a tile is the original object: tiles load lazily, and one past the 2 MB tile cutoff renders a placeholder carrying its name and size and requests no content until the resource itself is opened. Because a tile is a real read of the bytes, it is audited as one, under the `portal_preview` surface the content route accepts as `?preview=1` -- the only surface that does not stamp `last_read_at`, so browsing a library of photographs cannot clear the never-read flag on every image in it or reorder the recently-read sort. A tag filter sits beside the search box, populated from the tags the resources in view carry plus whichever tag is selected, and sets the `tag` query parameter the list endpoint has always supported; tags are orthogonal to the tree. Rows are multi-selectable, and one Move, Tag or Delete covers the selection: each file is its own PATCH or DELETE, so the report names what happened to each and a refused file stays where it was with the server's reason beside it. A file can be dragged onto a folder and a folder onto another folder; both open the same confirmation the menu action does, because dragging is easy to do by accident and either rewrites an address. ### Permission Model | Action | Global | Persona | User | |--------|--------|---------|------| | **Read** | All authenticated users | Users with matching persona | Owner only | | **Write (create)** | Platform admins | Platform admins or persona admins (`persona-admin:{name}`) | Any authenticated user (own scope) | | **Modify/Delete** | Original uploader or platform admin | Original uploader, platform admin, or persona admin | Original uploader or platform admin | Platform admin roles: `admin`, `platform-admin`. ### REST API Endpoints All endpoints are mounted at `/api/v1/resources` and require authentication (Bearer token or browser session). | Method | Path | Description | |--------|------|-------------| | `POST` | `/api/v1/resources` | Upload a new resource (multipart form) | | `GET` | `/api/v1/resources` | List resources visible to the caller | | `GET` | `/api/v1/resources/{id}` | Get resource metadata by ID | | `GET` | `/api/v1/resources/{id}/content` | Download resource file content | | `PATCH` | `/api/v1/resources/{id}` | Update resource metadata (display_name, description, tags), refile it in another folder (`path`), and/or move it to another library (`scope`, `scope_id`) | | `POST` | `/api/v1/resources/folders/move` | Rename a folder, or nest it under another, by rewriting the path prefix of every resource beneath it in one transaction | | `DELETE` | `/api/v1/resources/{id}` | Delete resource (metadata and S3 blob) | List supports query parameters: `scope`, `scope_id`, `path` (a folder and everything beneath it), `tag`, `q` (text search), `offset`. Upload (POST) accepts multipart form fields: `file` (required), `scope`, `scope_id`, `path`, `display_name`, `description`, `tags`. Maximum upload size: 100 MB. Executable file extensions and MIME types are blocked. ### MCP Protocol Integration When managed resources are enabled, the `MCPManagedResourceMiddleware` intercepts MCP `resources/list` and `resources/read` requests: - **resources/list**: Appends managed resources (filtered by caller's visible scopes) to the SDK's static resource list. - **resources/read**: For URIs matching the configured scheme (default: `mcp://`), looks up the resource in the database, checks read permission, and returns the file content from S3. Text types under 1 MB are returned inline; larger or binary content is returned as a blob. Falls through to the SDK handler for non-matching URIs. MCP resource capabilities are advertised whenever resource templates, custom resources, or managed resources are enabled. ### Portal UI A batch of files is loaded through the same create route (#1862). `POST /api/v1/resources` takes an optional `if_exists` form field ahead of the file part: `fail` (the default) answers 409 for an address that already holds a resource, and `skip_unchanged` compares the upload with that resource by SHA-256: identical bytes answer 200 with `outcome: unchanged` and write nothing (the blob written for the comparison is removed), and different bytes are recorded as its next version (200, `outcome: revised`) with its id, URI, name, description and tags kept. Every create answers `outcome` (`created` on 201). The hash is taken as the upload streams to storage and recorded on each version as `content_sha256` (migration 000158); a version written before that has none, so its first re-upload is recorded as a version. The portal's Upload many dialog sends files, a folder, or a `.zip` unpacked in the browser, four at a time, at most 5,000 per batch, each within `max_upload_bytes`, with shared library, folder, tags and a `{name}` description template, and marks the files a document can reference directly as an image. The Admin Portal includes a Resources page for uploading, browsing, editing, and deleting managed resources. Users browse the folder tree, filter by scope and tags, search the whole library by name or description, upload files, and edit metadata inline. One resource opens at a route of its own: `/resources/{id}` in the reader's portal, `/admin/resources/{id}` in the administrator's, both registered in the shell's route table so an id that names nothing gets the section's not-found rather than a blank page. Clicking a row navigates there. The page takes the same chrome a portal asset takes, through one shared `ViewerLayout`: the content at the full width of the page with the page area as its only scroll region, and the metadata, tags, canonical URI, read-activity rollup, version history, table registration panel and attaching prompts in a sidebar beside it. Download, Edit and Delete sit in the page header under the same authority the API applies — the uploader or an administrator. Editing, deleting and uploading stay dialogs, being bounded forms. The library's LOCATION -- which library, which folder -- is carried in the route (`/resources/lib/global/data/media-manager`) and its filters in the query string, so Back from a resource returns to the folder it was left in and any level of the tree can be linked to. The viewer's subtitle renders the same `FolderBreadcrumbs` component the library's header does, so the folder trail on a resource's own page is clickable back into the library it lives in. ## Thumbnails Configuration The platform draws a thumbnail of every portal asset, managed resource and collection itself, in a headless Chrome (`chromedp/headless-shell`, pinned by digest) that runs as a second container in the platform's pod with no Service or port (#1787). Enabled by default; nothing needs to be set when the renderer runs beside the platform. A raster image (PNG, JPEG, GIF, WebP, BMP) larger than a tile is decoded and reduced to the tile's size by the platform before the renderer draws it, at most 96 MiB decoded and one image at a time per replica, so Chrome never decodes a photograph at its natural size; an image whose header declares more is recorded as not drawable with its size named. With the worker drawing one document at a time (the default), a document whose render takes the renderer down is recorded as not drawable on that attempt rather than retried (#2697). ```yaml thumbnails: enabled: false # only needed to opt out; defaults to true renderer_url: "http://127.0.0.1:9222" # the renderer's DevTools address; this is the default concurrency: 1 # documents one replica draws at once render_timeout: 45s # one variant of one document batch: 1 # rows of each kind one pass claims; defaults to concurrency lease: 4m10s # default worked out from batch, concurrency and render_timeout poll: 5s # first idle wait; doubles to 1m while idle, woken by new work max_attempts: 5 # tries before a document that never finishes is recorded retry_backoff: 1m # hold after the first unfinished try; x4 each try, at most 1h max_source_bytes: 1048576 # largest document a tile is drawn from (1 MB) large_source_bytes: 33554432 # the bound for PDF, CSV and TSV (32 MB) ``` The platform dials the renderer and answers every request a page makes itself, so the renderer is never given an address to call and a document reaches no network through it. With no renderer answering, the platform serves normally, files keep their content-type icons, and it logs once that no renderer answers and once when one does. A document that cannot be drawn within `render_timeout`, an image no browser decodes, or an artifact whose linked files did not load is recorded with the reason, shown on the file's Thumbnail panel, and not tried again until the file changes or its owner asks. Every claim charges the row an attempt (`thumbnail_attempts`, migration 000159, on assets, resources and collections); an attempt that does not finish -- the renderer stops answering or closes the page while the document is loaded, the stored file cannot be read, a file the document references is answered by the platform with an error or not in time (#2218), the tile cannot be written -- holds the row back for `retry_backoff`, four times longer each time, and at `max_attempts` records it as not drawable with the last reason, so one document cannot hold the renderer or the queue (#1868). The worker asks the renderer before each document and hands the untried rows back with their attempt returned when it does not answer. A collection mosaic that cannot be composed is recorded against its source (`thumbnail_failure`, `thumbnail_failed_source`) and owed again when the source changes. Pages are loaded with `prefers-reduced-motion: reduce` and their animation timeline stopped in every frame, and just before the capture an animation that ends is shown ended and an infinite one removed. A lease shorter than drawing the batch, or a negative value, is refused at startup. `max_source_bytes` (default 1 MB) and `large_source_bytes` (default 32 MB, for PDF, CSV and TSV) bound the document a tile is drawn from. A file larger than its bound is never offered to the renderer and keeps its content-type icon. Every asset and resource read says so (#2072): the portal API, `manage_asset get`/`list` and `manage_resource` report `thumbnail_skipped: "over_source_limit"` and `thumbnail_source_limit` (the bound, in bytes), and the file's Thumbnail panel says the file is too large for a thumbnail, with both sizes. Without them a skipped file reads the same as one not drawn yet. Raising `max_source_bytes` is the fix for a scripted dashboard that carries its data inline; the renderer holds the whole document while it draws, so give it memory to match. Every file a page drawn by the renderer loads (a tile of any kind, a site tile, or a PDF export) is answered through a bound on memory (#2721): one file up to 16 MiB (`headless.MaxFileBytes`); a larger one of the platform's own is answered 413 and the page is drawn without it, a larger public one fails, and an open-ended range (how a video asks) is cut to 16 MiB from its start. The files every render in a replica is answering at once are held to 64 MiB together, and a page's other requests wait for room. In-process reads (`internal/inproc`, the site tile page) stop at the bound rather than buffering a whole object, and a file is sent to the renderer with one base64 copy. Before this, a replica redrawing every site tile after an upgrade held about 3 GB for a site of large images and was killed for its memory. ## Progress Notifications Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `progress.enabled` | `*bool` | `true` (nil = enabled) | Enable progress notifications for Trino queries | Enabled by default; set `enabled: false` to opt out. When enabled, Trino query tools send three progress notifications per query: before execution, after query returns, and after formatting. Clients must include `_meta.progressToken` in their tool call to receive notifications. ## Client Logging Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `client_logging.enabled` | `*bool` | `true` (nil = enabled) | Enable server-to-client log messages | Enabled by default; set `enabled: false` to opt out. When enabled, the platform sends log notifications to clients after enrichment is applied (tool name, duration). Uses MCP `logging/setLevel` protocol, with zero overhead if the client hasn't called `setLevel`. ## Elicitation Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `elicitation.enabled` | `*bool` | `true` (nil = enabled) | Enable user confirmation prompts | | `elicitation.cost_estimation.enabled` | `*bool` | `false` (nil = off, #2586) | Prompt when a query is estimated to return more rows than the threshold | | `elicitation.cost_estimation.row_threshold` | int | `1000000` | Compared with the rows a query is estimated to return, capped by the row limit the call runs with | | `elicitation.pii_consent.enabled` | `*bool` | `true` (nil = enabled) | Prompt when a query reads a PII-tagged column, or a PII-tagged table | Elicitation and `pii_consent` are on by default; `cost_estimation` is off by default (#2586), since `trino_query`'s row limit and `tools.result_budget` already bound what a query returns. Set `enabled: false` at any level to opt out. Elicitation requires client-side support (MCP `elicitation/create` capability). When the client doesn't support it, elicitation gracefully degrades to a no-op. If a user declines the confirmation, the tool returns an informational message instead of executing the query. How a prompt reaches the client depends on the protocol revision it speaks (#2052). A client on 2026-07-28 is answered with the prompts as input requests on the `trino_query` result (`resultType: "input_required"`) and retries the call with its answers; one cost prompt and one PII prompt owed by the same statement come in one round. An older client is asked in band while the call waits, which needs a deployment that keeps sessions in process: with a database session store the platform serves MCP stateless, a stateless server can send no request to the client, and an older client is not prompted (the query runs as it would for a client without elicitation). Either way a prompt that does not come back accepted ends the call, and nothing is sent to Trino past the estimate: declined is a `user_declined` error, and no answer (the client canceled or gave up waiting) is a `prompt_unanswered` error saying the person was not reached and a resend only asks again (#2586). The call that issued the prompt is audited with the `input_required` category, not as a success, and is never a provenance source or a call catalog record. The prompts are a layer of the platform's `tools/call` chain, inside authorization, the session and search-first gates and the rate limiter, so a call that may not run is never estimated or prompted for. Each Trino connection carries its own settings: the platform's apply to every connection in `toolkits.trino.instances` that sets no `elicitation` block of its own, and a connection added through the admin API with none takes the default connection's (the admin API drops an `elicitation` key from a stored connection, so a per-connection block is file configuration only). The estimate's `EXPLAIN (TYPE IO)` runs on the connection the query names and is measured as one: `trino_queries_total{query_kind="explain"}` and a `trino.explain` span under the tool call's. The cost prompt compares the plan's own output estimate (top-level `estimate.outputRowCount`), capped by the call's row limit, never a table's scan; an unknown estimate asks nothing (#2586). The PII prompt fires for a column the catalog tags PII that the statement reads (named outside strings and comments, or under `*` / `t.*`) and for a table it tags PII (a tag whose name contains "pii"), since a catalog commonly tags the dataset holding personal data rather than each column. Before #2052 neither prompt ran on any deployment: the middleware was built only by a single-connection constructor the platform never used. Behavior change: PII-consent prompts fire out of the box; the cost prompt does not since #2586. A deployment that wants it sets `elicitation.cost_estimation.enabled: true`, and its `row_threshold` is compared with the rows a query returns (capped by its row limit), so a threshold above the connection's `max_limit` never prompts. ## Icons Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `icons.enabled` | `*bool` | `true` (nil = enabled) | Enable icon enrichment middleware | | `icons.tools..src` | string | - | Icon URI for a tool | | `icons.tools..mime_type` | string | - | Icon MIME type | | `icons.resources..src` | string | - | Icon URI for a resource template | | `icons.prompts..src` | string | - | Icon URI for a prompt | Enabled by default; set `enabled: false` to opt out. Upstream toolkits (Trino, S3) provide default icons on all tools. This configuration overrides or adds icons for tools, resource templates, and prompts in list responses. ## Audit Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `audit.enabled` | bool | `true` (when a database is available) | Enable audit logging. Set `false` to disable. | | `audit.log_tool_calls` | bool | `true` | Log MCP tool call events. Set `false` to keep audit on but skip per-tool-call rows. | | `audit.log_parameters` | bool | `true` | Capture tool-call arguments on each event. Set `false` to drop them; `parameters` then holds only a `result` a tool reports about the call's outcome, or null. | | `audit.redact_keys` | list of strings | `[]` | Top-level argument keys whose values are replaced with `[REDACTED]` before the event leaves the request path. Case-insensitive; top-level only. | | `audit.delivery` | string | `async` | Store-write path: `async` (best-effort, never blocks the tool call) or `sync` (writes on the request goroutine for backpressure and zero queue drops). | | `audit.retention_days` | int | 90 | Days to retain audit events | Requires `database.dsn`. With a database available and no `audit:` block, both audit and per-tool-call logging are on by default. `enabled: false` disables audit entirely; `log_tool_calls: false` keeps audit on but stops recording per-tool-call events. Delivery semantics and data captured. Each event records identifiers (`id`, `request_id`, `session_id`, `user_id`, `user_email`, `persona`), the call target (`tool_name`, `toolkit_kind`, `toolkit_name`, `connection`, `event_kind`), the agent's stated reason for the call (`purpose`, see Purpose Configuration), the raw tool-call arguments (`parameters`), the outcome (`success`, `error_message`, `error_category`, `authorized`), timing and size (`timestamp`, `duration_ms`, `request_chars`, `response_chars`, `content_blocks`), transport (`transport`, `source`), and enrichment accounting (`enrichment_applied`, `enrichment_tokens_full`, `enrichment_tokens_dedup`, `enrichment_mode`, `enrichment_match_kind`). The `parameters` field stores arguments verbatim (including full SQL); use `redact_keys` or `log_parameters: false` for sensitive values. Async delivery is best-effort: under sustained backpressure or a crash, queued events are dropped and counted by the `audit_events_dropped_total` metric (which also covers writes that fail or exceed the per-write timeout). Sync delivery writes on the request goroutine with a per-write timeout (5s), trading latency for zero queue-overflow drops; a failed write is still logged, counted, and never fails the tool call. Under a stalled store, sync mode blocks each tool call up to the timeout and draws from the same connection pool as OAuth/sessions/portal (the async writer's single drain goroutine avoids both); graceful shutdown cancels in-flight sync writes. ## Session Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `sessions.store` | string | `memory` | Backend: `memory` or `database` | | `sessions.ttl` | duration | streamable session_timeout | Session lifetime | | `sessions.cleanup_interval` | duration | `1m` | Cleanup routine interval | | `sessions.handles.enabled` | bool | `true` | Explicit session handles (#792): platform_info mints a session_id the model threads on every subsequent tool call. Set false for legacy transport-session behavior. | | `sessions.handles.ttl` | duration | `8h` | Handle lifetime, refreshed on use | | `sessions.handles.require` | bool | `true` | Refuse any gated call without a valid platform_info-minted handle (SESSION_REQUIRED); a transport Mcp-Session-Id/stdio sentinel is NOT a fallback (issue #800). `false` falls back to the transport session | The `database` store requires `database.dsn`. Database-backed sessions survive restarts and support multi-replica deployments. Explicit session handles (`sessions.handles`, issue #792) adopt the pattern the MCP 2026-07-28 release candidate recommends after removing the `Mcp-Session-Id` header (SEP-2567): `platform_info` mints a `session_id`, every tool advertises it as an input argument (except `platform_info`), and `MCPToolCallMiddleware` validates it against the session store (must exist, be unexpired, and belong to the same authenticated identity), adopts it onto `PlatformContext.SessionID`, and strips it before the handler runs. This makes `platform_info` structurally unskippable and gives audit and provenance a deliberate session key. Unknown/expired/cross-identity handles are refused with `SESSION_EXPIRED (reason: unknown|expired|other_identity)` (#2816); on `expired` or `unknown` an authenticated caller is issued a new `session_id` for their own identity in the same refusal (message and `structuredContent.session_id`) to resend the call with, and `other_identity` gets none; a missing handle on a gated tool with `require: true` is refused with `SESSION_REQUIRED`. A transport-level session (`Mcp-Session-Id` or the stdio sentinel) is not accepted as a fallback for the requirement (issue #800): it is the churning per-call value the handle exists to replace, so `platform_info` mints and threads a handle on every transport with no stdio carve-out. When `require: false`, a handle-less call falls back to the transport session. The `mcp_session_resolution_total{source}` metric tracks how much traffic still relies on a transport session. ## Toolkit Configuration ### Trino | Field | Type | Default | Description | |-------|------|---------|-------------| | `host` | string | required | Trino coordinator hostname | | `port` | int | 8080/443 | Trino coordinator port | | `user` | string | required | Trino username | | `password` | string | - | Trino password. Sent only over TLS: a connection with a password needs `ssl: true` (the Trino client refuses it otherwise, mcp-trino v1.6.0). Startup checks every Trino connection the way the client will (a connection inherits unset values from the default one) and refuses the configuration before any database migration runs, naming each connection and the fix (#2014). The admin API refuses to save such a connection (toolkit.ConnectionValidator, asked through connreconcile before the store write), and one already saved in the database is dropped from the start-up merge with an error log naming it (toolkitcfg.MergeStored with registry.RefusedConnections) rather than failing every Trino connection after the migration | | `catalog` | string | - | Default catalog | | `schema` | string | - | Default schema | | `ssl` | bool | false on the default connection, auto-detected on the others | Enable SSL/TLS. Omitting it on a non-default connection leaves the choice to the host: anything that is not `localhost` or `127.0.0.1` is assumed HTTPS on 443. Write `ssl: false` for plain HTTP (#1436) | | `ssl_verify` | bool | true on the default connection, inherited on the others | Verify SSL certificates; a non-default connection that omits it takes the default connection's setting | | `timeout` | duration | 120s | Query timeout | | `default_limit` | int | 1000 | Default row limit | | `max_limit` | int | 10000 | Maximum row limit | | `read_only` | bool | false | Reject write SQL on this connection; set per instance, so the other instances of the same toolkit are unaffected and a call that omits `connection` is judged by the default instance's setting | `read_only` became per connection in #1269. Before that it was read from the default instance alone and applied to the whole Trino toolkit, which cut both ways: `read_only: true` on the default instance refused write SQL on every Trino connection, and `read_only: true` on any other instance did nothing. A deployment relying on the default instance's `read_only` to cover its other Trino connections must now set `read_only: true` on each connection it wants refused. Connections stored in the database (Admin > Connections) carry the same key, with a Read Only toggle in the Trino connection form; a connection the toolkit holds no setting for - one just added, or a name that is not configured - refuses write SQL until its setting is recorded. | `scratch.catalog` | string | - | Catalog a registered table is created in on this connection; unset (or set without `schema`) means table registration is unavailable here | | `scratch.schema` | string | - | Schema a registered table is created in; required alongside `catalog`, and a block naming only one is ignored with a warning | | `scratch.statement_timeout` | duration | the connection's `timeout` | How long each statement that creates, drops or fills a table in the scratch target may run (registration, follow, webhook tables and partitions); a value that does not parse refuses the connection (#2131) | | `descriptions` | map | {} | Override tool descriptions (key: tool name, value: description text) | `scratch:` names a TARGET, not a boundary. Nothing in the toolkit restricts a catalog or a schema, and `catalog`/`schema` on a connection are session defaults: every query on the connection runs with them as the Trino session catalog and schema (sent since mcp-trino v1.6.0, #1998), so `SELECT * FROM webhook_` resolves on the source's scratch connection and `CREATE TABLE t` lands in `..t`; what keeps a registration off the warehouse is the Trino identity the connection authenticates as. A read-only warehouse connection beside a write-capable scratch one on the SAME cluster is the worked example, and the difference that matters between them is the Trino account, not the platform flag: `read_only` admits only the statement kinds that read (SELECT, WITH, VALUES, TABLE, SHOW, DESCRIBE, EXPLAIN without ANALYZE) evaluated per connection name, so a scratch connection authenticating as the warehouse's user can write `INSERT INTO warehouse...`. Adding a catalog allow-list to the toolkit is deliberately not done, because parsing SQL is the wrong layer for a boundary the engine already enforces on its own identities. Separately, a SHORT external list of keys needs no table at all: a few hundred join inline with `JOIN (VALUES ('a'),('b')) AS t(id)` or `WHERE id IN (...)` through `trino_query` on a read-only connection, and the platform's instruction baseline says so wherever `trino_query` is accessible, so a handful of pasted keys is joined rather than refused or turned into a request for a table. ### S3 | Field | Type | Default | Description | |-------|------|---------|-------------| | `region` | string | us-east-1 | AWS region | | `endpoint` | string | - | Custom S3 endpoint for data operations (for MinIO, SeaweedFS) | | `public_endpoint` | string | - | Public endpoint used only to sign presigned URLs (`s3_object` `presign`); set it to an externally resolvable address. Empty falls back to `endpoint`. | | `access_key_id` | string | - | AWS access key ID | | `secret_access_key` | string | - | AWS secret access key | | `read_only` | bool | false | Restrict to read operations | ## Cross-Enrichment Configuration | Field | Type | Default | Description | |-------|------|---------|-------------| | `trino_semantic_enrichment` | bool | true | Add the platform catalog's curation to Trino results (default on; set false to disable) | | `unwrap_json` | bool | true | Auto-unwrap single-row VARCHAR-of-JSON results (e.g. from raw_query) | | `column_context_filtering` | bool | true | Limit column enrichment to SQL-referenced columns | | `estimate_row_counts` | bool | false | Run `SELECT COUNT(*)` when reporting table availability so a fetched catalog dataset's `query_availability` carries an estimated row count, and so the insight review path can state a row count beside a pending claim (and flag one that disagrees). Off by default: `COUNT(*)` can trigger a full table scan and make search enrichment very slow | | `semantic_fallback` | bool | false | When a Trino-table lookup misses in the catalog, fall back to a similarity search and surface the top-K hits as SUGGESTED matches annotated with `match_kind: semantic`. Default off; operators opt in. Issue #444. | | `semantic_fallback_top_k` | int | 1 | Number of similarity-search hits surfaced per miss when `semantic_fallback` is on. Clamped to [1, 10]. | | `memory_limit` | int | 5 | Max memory records recalled and rendered into `memory_context` per tool call. Issue #761. | | `memory_context_budget_bytes` | int | 1500 | Byte budget for the rendered memory summaries; records beyond it are listed as compact `id`+`reference` stubs in `memory_context_omitted` (still fetchable, at least one always rendered). `0` disables the budget. | | `memory_summary_bytes` | int | 280 | Per-record summary-first excerpt cap; the full record is fetchable via its `mcp:memory:` reference. `0` renders full content. | When `semantic_fallback` fires, the appended content carries `semantic_fallback.match_kind: semantic`, a human-readable note, the queried table identifier, and a list of suggested matches (urn, name, platform, description, tags, domain). The audit row's `enrichment_match_kind` column records `semantic` for these calls and `urn` for exact lookups, so operators can compute the false-positive rate of similarity-based suggestions with a SQL aggregate. The fallback fires only on the single-table enrichment path (e.g. `trino_describe_table`); multi-table SQL queries fall through with no suggestions until a follow-up extends the same hook to `enrichTrinoQueryResult`. --- # Authentication & Security mcp-data-platform implements a **fail-closed** security model. Missing or invalid credentials deny access, never bypass. For the security architecture rationale, see: https://imti.co/mcp-defense/ ## A broker, not an identity provider **mcp-data-platform is an OAuth 2.1 broker, not an identity provider.** No person authenticates to it: there is no login form, no user password to verify, and no MFA. A human's identity comes from an existing IdP (Keycloak, Auth0, Okta, Azure AD) over OIDC; `/authorize` redirects the browser there and refuses the flow outright when no upstream IdP is configured, and the roles and email that person is authorized against are the ones the IdP asserts. Service accounts authenticate with API keys instead, and their roles come from local configuration. It stores no human passwords, and no migration in the tree defines a password column. The secrets it does hold are machine credentials: API keys and the client secrets Dynamic Client Registration issues to MCP client software are bcrypt hashes, the authorization codes and tokens the platform itself issues are SHA-256 digests, and refresh tokens for upstream services are encrypted at rest (AES-256-GCM when `ENCRYPTION_KEY` is set; the server warns loudly at startup when it is not). The platform presents an authorization server toward MCP clients because the MCP specification requires a discoverable authorization server supporting Dynamic Client Registration, which upstream IdPs generally do not expose. The broker shape is what the spec requires, not a decision to reimplement identity. | Concern | Implementation | |---|---| | `redirect_uri` matching | Exact match for non-loopback; RFC 8252 section 7.3 handling for loopback (`pkg/oauth/storage.go`) | | DCR abuse | Plain HTTP to non-loopback hosts refused regardless of configuration; private-use schemes excluded from `AllowAllRedirectURIs` (`pkg/oauth/dcr.go`) | | Brute force and registration flood | Per-IP token-bucket limits on `/token` and `/register`, applied before the bcrypt work they would otherwise burn (`pkg/oauth/ratelimit.go`) | | Authorization | Deny-before-allow, default deny, fail-closed on unresolved persona (`pkg/persona/filter.go`) | | Prompt injection carried in catalog metadata | Untrusted descriptions, tags, and owner notes sanitized before reaching the model; detected attempts logged (`pkg/semantic/sanitize.go`, `pkg/semantic/injection_logger.go`) | ## Engineering posture More than 1.25 lines of test code per line of production Go, with the security-critical packages carrying the highest ratios in the tree: `pkg/oauth` and `pkg/middleware` are both above 2:1. Fuzz targets cover `pkg/oauth`, `pkg/auth`, `pkg/platform` and `pkg/middleware`, and every parser of untrusted input under `internal/`: `internal/pglex`, `internal/pgtext`, `internal/sqltables`, `internal/webhook/jsonpath`, `internal/webhook/whevent`, `internal/webhook/whauth`, `internal/hmacsig`, `internal/unarchive`, `internal/pmtiles`, `internal/imapmail`, `internal/mailtrust`, `internal/untrusted`, `internal/gqlschema`, `internal/swagger2`, `internal/pathtemplate`, `internal/tableparquet`, `internal/scriptprintf`, `internal/scriptre` and `internal/totp`. A daily workflow fuzzes each one, and a failing input is committed so `go test` replays it. Every PR passes race-detector tests, `golangci-lint`, `gosec`, and Semgrep and CodeQL SAST, under a coverage floor enforced in CI. Release artifacts are Cosign-signed with GitHub build-provenance attestations, and supply-chain posture is tracked by OpenSSF Scorecard. These ratios are kept true mechanically: `make posture-check` recomputes them and fails when the tree crosses a stated line. ## Transport Security | Transport | Authentication | TLS | Why | |-----------|---------------|-----|-----| | stdio | Not needed | N/A | Local execution with your own credentials | | HTTP | **Required** | Recommended | Shared server needs to identify users | ## Security Model - **Required JWT Claims**: Tokens must include `sub` (subject) and `exp` (expiration) - **OIDC Audience**: a bearer token is accepted only when it was issued for this platform: its `aud` names `auth.oidc.audience` when that is set, and otherwise its `aud` names `auth.oidc.client_id` or `client_id` is its authorized party (`azp`). A token the identity provider issued to another of its clients is refused, and OIDC refuses to start with neither `client_id` nor `audience`. - **Self-Healing JWKS Cache**: OIDC signing keys are fetched at startup and cached for one hour. The key-lookup path refreshes on demand (during that request's validation, honoring the request's deadline) when the cache expires or a token bears an unknown key ID (IdP key rotation), so validation survives rotation without a restart. Concurrent requests collapse into a single fetch that runs independently, so a slow issuer cannot pin request goroutines. Refreshes are throttled by the last fetch's outcome: at most once per minute after a success (anti-hammer), and a short recovery window after a failure so a brief issuer outage heals within seconds. A failed refresh on an expired cache rejects the token rather than accepting it unverified. - **Default-Deny Personas**: Users without explicit persona have no tool access, and connection rules are deny-by-default on the same call, so access is scoped at the connection rather than the end user (see the Authorization Model section) - **Read-Only Enforcement**: Trino `read_only: true` runs only reads, per connection: a statement is a read when `internal/sqltables.IsRead` lists its kind (SELECT, WITH, VALUES, TABLE, SHOW, DESCRIBE, EXPLAIN without ANALYZE) and anything else is refused; the interceptor resolves the connection the call names (the default when it names none) and refuses only when that connection sets it. `trino_query` and `trino_export` hold to the same read list on every connection, so writing is `trino_execute`'s alone - **Cryptographic Request IDs**: Secure random identifiers for audit trails ## stdio Transport (Local) No MCP authentication required. The server runs on your machine using credentials you configured. ## HTTP Transport (Remote/Shared) Authentication identifies who is making requests. Anonymous access is disabled by default. - **OIDC**: Human users via Keycloak, Auth0, Okta - **API Keys**: Service accounts, automation - **OAuth 2.1 (inbound)**: Claude Desktop authentication via upstream IdP — see "OAuth 2.1 for Claude Desktop" below - **OAuth 2.1 (outbound)**: Gateway connections to upstream MCPs — `client_credentials` (M2M) and `authorization_code` + PKCE (browser sign-in). Encrypted refresh tokens persist across restarts. See "OAuth to Upstream MCPs" later in this document. ### OAuth 2.1 for Claude Desktop For Claude Desktop connecting to a remote MCP server, the built-in OAuth 2.1 server bridges authentication to any OIDC-compliant upstream identity provider (Keycloak shown): 1. Claude Desktop calls `/oauth/authorize` 2. MCP server redirects to the upstream IdP's discovered authorization endpoint 3. User logs in to the upstream IdP 4. Upstream IdP redirects back to MCP server's `/oauth/callback` 5. MCP server exchanges code at the upstream IdP's discovered token endpoint, extracts user info 6. MCP server issues its own token to Claude Desktop Configuration: ```yaml oauth: enabled: true issuer: "https://mcp.example.com" signing_key: "${OAUTH_SIGNING_KEY}" # Required on http transport: openssl rand -base64 32 previous_signing_keys: # Optional: verify-only keys retained across a rotation - "${OAUTH_SIGNING_KEY_OLD}" clients: - id: "claude-desktop" secret: "${CLAUDE_CLIENT_SECRET}" redirect_uris: - "http://localhost" - "http://127.0.0.1" upstream: issuer: "https://keycloak.example.com/realms/your-realm" client_id: "mcp-data-platform" client_secret: "${KEYCLOAK_CLIENT_SECRET}" redirect_uri: "https://mcp.example.com/oauth/callback" # Optional overrides; empty = discover from the issuer's well-known document. # authorization_endpoint: "https://idp.example.com/authorize" # token_endpoint: "https://idp.example.com/token" ``` The broker resolves the upstream authorization and token endpoints via OIDC discovery: on first use it fetches `/.well-known/openid-configuration` and reads `authorization_endpoint` and `token_endpoint`, so the brokered flow works with any OIDC-compliant IdP rather than assuming Keycloak's URL shape. Resolved endpoints are cached for the process lifetime; a discovery failure is not cached, so `/oauth/authorize` returns a retryable `server_error` and retries on the next request rather than falling back to a fixed path. Set `upstream.authorization_endpoint` and `upstream.token_endpoint` to bypass discovery for an IdP with a broken discovery document; discovery is skipped entirely only when both are set. Access tokens are signed JWTs whose `aud` claim is the issuer URL (the platform is both authorization server and resource server); the requesting client is carried in the `client_id` claim, and the authenticator rejects tokens minted for any other audience. Access tokens are HS256-signed and carry a `kid` header derived from the signing key, so verifiers select the right key after a rotation. `oauth.signing_key` is **required** when OAuth is enabled on `server.transport: http`/`sse` (startup fails otherwise, naming the key) because an auto-generated per-process key makes each replica reject its peers' tokens; set `oauth.allow_ephemeral_signing_key: true` to override for a single-replica dev setup. On `stdio` the key is auto-generated when omitted. Rotate in two phases so every replica can verify the new key before any replica signs with it (a single-phase swap causes intermittent 401s during the rolling restart): (1) add the new key to `oauth.previous_signing_keys` as verify-only while `signing_key` stays the old key, roll-restart; (2) promote by setting `signing_key` to the new key and moving the old key into `previous_signing_keys`, roll-restart; then drop the old key after the access-token TTL (1h) elapses. Tokens minted before `kid` support carry no header and fall back to current-then-previous key verification, so an in-place upgrade preserves live sessions. Dynamic Client Registration (`oauth.dcr`) is off by default. Enabling it requires `allowed_redirect_patterns` (regex list): the registration endpoint is unauthenticated, so registration is denied when no patterns are configured (a startup warning flags the misconfiguration). `allow_all_redirect_uris: true` explicitly opts out of pattern matching. Plain HTTP redirect URIs are rejected for non-loopback hosts regardless of configuration; private-use schemes (RFC 8252 native apps) are accepted only through an explicit pattern. Each pattern matches the whole redirect URI (anchored at both ends) and must write the host exactly: the platform re-tests each match with the host replaced by hosts nobody controls (another host, a label or letter appended, a letter before the registrable domain) and does not use a pattern that still matches; a subdomain wildcard under a named domain is accepted, and a loopback URI only needs to match. A redirect URI must be absolute with no user info, fragment, backslash, whitespace, control character or escaped host. The authorization endpoint re-applies the policy to a dynamically registered client's redirect URI on every sign-in; with DCR off, such a client cannot sign in. Consent: before an authorization code is sent to a dynamically registered client, the person signing in sees a platform page (branded with `portal.title` and the portal logos) naming who is signed in, the redirect URI and its host, and the client's self-chosen name marked unchecked, with Deny and Allow. Allow sends the code; Deny sends `error=access_denied` with the client's state. It is asked on every sign-in, cannot be framed, loads nothing from other hosts but the logos, and is answered once, within 10 minutes, only by the browser it was served to (a SameSite=Strict HttpOnly cookie whose SHA-256 the state store keeps); a late, repeated or foreign answer gets an ended page. The pending request holds the person's ID and claims, never an upstream token. Clients configured under `oauth.clients` are not asked. The answer posts to `POST /oauth/consent`. The unauthenticated `/token` and `/register` endpoints are rate limited by default (`oauth.rate_limit`, disable with `enabled: false`). `/token` runs a bcrypt compare per attempt and `/register` a bcrypt hash plus a DB insert per request, so both are CPU/storage amplification levers. Each endpoint has a per-client-IP token bucket (`/token` 60 rpm / burst 10, `/register` 10 rpm / burst 3) plus a global backstop bucket sized at ten times the per-IP rate that bounds total throughput even when per-IP attribution is defeated or collapses behind a proxy. Client attribution is trusted-proxy-aware: `X-Forwarded-For` is consulted only when the direct peer is in `rate_limit.trusted_proxies` (a CIDR list), taking the rightmost untrusted hop; with no trusted proxies configured the header is ignored and the direct peer address is used (the spoof-safe default). On limit the endpoint returns HTTP 429 with `Retry-After` and `{"error":"slow_down"}`. Separately, DCR-registered clients never issued a token are reaped 24h after registration by the OAuth store's cleanup loop (a `dcr` column marks them; pre-registered config-file clients are exempt), bounding `oauth_clients` growth. The per-IP token-bucket implementation lives in the shared `pkg/ratelimit` package, reused by the public portal viewer, which composes the same trusted-proxy-aware resolver and global backstop (per-IP 60 rpm / burst 10 by default) and reads its trusted-proxy CIDRs from `portal.rate_limit.trusted_proxies` (empty trusts none: the direct peer address is used and `X-Forwarded-For` is ignored). When a database is configured, in-flight authorization state (linking `/oauth/authorize` to the upstream IdP callback) is stored in PostgreSQL so multi-replica deployments work behind a load balancer: the callback can land on a different replica than the one that started the flow. Refresh tokens and authorization codes are stored only as hex-encoded SHA-256 digests (in both the PostgreSQL and in-memory stores); the server hashes the presented value on lookup, so a database read, backup, or replica never yields a usable bearer credential. Migration 000078 converts pre-existing plaintext rows in place so live sessions survive the upgrade; rolling it back deletes all outstanding refresh tokens and authorization codes, forcing interactive re-authorization. ## Browser Sessions (OIDC Login for Portal UI) When `auth.oidc` and `auth.browser_session` are both enabled, the portal UI offers SSO login. The flow uses OIDC authorization code with PKCE. Sessions are stored as HMAC-SHA256 signed JWT cookies (stateless, no server-side store). ```yaml auth: oidc: enabled: true issuer: "https://auth.example.com/realms/platform" client_id: "mcp-data-platform" client_secret: "${OIDC_CLIENT_SECRET}" scopes: [openid, profile, email] browser_session: enabled: true signing_key: "${SESSION_SIGNING_KEY}" # openssl rand -base64 32 ttl: 8h secure: true same_site: lax # lax (default), strict, or none ``` Endpoints: `/portal/auth/login` (initiate; accepts optional `return_to` site-relative path), `/portal/auth/callback` (process; redirects to `return_to` when set, otherwise `PostLoginRedirect`), `/portal/auth/logout` (clear). API key fallback always available. MCP clients unaffected. Limitations: no individual session revocation, no key rotation support (rotating invalidates all sessions), no session refresh (re-auth required after TTL). CSRF protection: cookie-authenticated state-changing requests (POST/PUT/PATCH/DELETE) to the portal, admin, and managed-resources APIs require an `X-CSRF-Token` header; missing/invalid tokens are rejected with 403. The token is stateless (an HMAC over the session subject under the signing key), returned by `GET /api/v1/portal/me` as `csrf_token` and echoed by the SPA on every mutation. Read-only requests and API-key/Bearer-authenticated requests are exempt (those credentials are not attached automatically by the browser). `SameSite=Lax` is kept as defense-in-depth; `same_site: none` disables that browser defense (requires `secure: true`) and logs a startup warning. Cross-origin reads: the platform answers a cross-origin request from any origin (a browser-based MCP client calls with a bearer token or API key), and allows credentials (`Access-Control-Allow-Credentials: true`) only for its own origin: the host the request arrived on, or the origin of `portal.public_base_url`. A page on any other origin, a sibling host on the same domain included, cannot read an answer its cookie-bearing request unlocked. Behind a proxy that does not pass the original `Host`, set `portal.public_base_url` (#2526). ## Threat Model The threat model states the security model as a whole (reviewed at v1.101.x): trust boundaries, the attackers each mechanism is designed to stop, and what is explicitly out of scope. Every mitigation claim carries a package or config citation a reviewer can verify. Trust boundaries fall into four groups. Inbound surfaces: MCP over stdio (local-process trust, no MCP-layer auth) versus HTTP (streamable + SSE, bearer/API-key gate that returns 401 with `WWW-Authenticate` and fails closed on an invalid token); the OAuth 2.1 endpoints; the admin REST API (admin persona required, CSRF on the cookie path); the portal API and its share-token viewer (rate-limited, access-mode gated, 403 for a caller the mode does not admit, 410 on revoked/expired; refused browser navigations get a branded landing page, and email-share recipients can request single-use guest view links: uniform response, per-share issue cap, hashed 15-minute tokens claimed atomically, view-only guest cookie scoped to one share under a key domain-separated from the browser-session signing key); the no-login notification unsubscribe endpoint (HMAC token bound to the recipient address, can only opt that address out); the gateway REST shim (runs through an in-memory MCP session so persona and audit apply); the observability PromQL proxy (`observability:read` capability, admin-only); unauthenticated health endpoints (liveness/readiness only); and managed resource upload/download (per-request auth plus scope checks). Identity mechanisms: OIDC bearer validation with a self-healing JWKS cache; API keys (constant-time compare for config keys; DB keys found by a SHA-256 lookup digest of their 32 random bytes, `api_keys.key_digest`, with a bcrypt hash kept beside it and bcrypt comparison only for a key stored before digests existed, bounded to half the CPUs at once and recording the digest when it matches); the built-in OAuth 2.1 server (HS256 with a `kid` key ring); browser cookie sessions (HttpOnly, Secure, SameSite, HS256-signed); and persona default-deny authorization. Outbound dependencies: Trino and S3 with per-connection operator-authored credentials; upstream MCP servers and HTTP APIs; outbound OAuth (one shared upstream identity per connection, #374); and the embedding provider. At rest: Postgres holding SHA-256-hashed OAuth tokens (single-use via atomic `DELETE ... RETURNING`), bcrypt-hashed client secrets, AES-256-GCM-encrypted connection secrets (single symmetric key from `ENCRYPTION_KEY`, not a DEK/KEK envelope), and audit rows subject to `redact_keys` and the `log_parameters` opt-out. Identity-provider outage is a recorded decision rather than an emergent property. Validation has three outcomes: valid, definitively invalid, and undetermined (the IdP is unreachable, so signing keys cannot be fetched — the `ErrValidationUnavailable` sentinel, wrapped only on a JWKS fetch failure with an expired cache). On the third, the HTTP edge passes the request through instead of answering 401, because a 401 asserts a bad credential and would drive every valid user into a re-auth flow that cannot complete during the outage; the protocol layer then refuses each tool call with `feature_unavailable` and a retryable hint, so no tool handler runs. Access is never granted on an unvalidated credential; the cost is depth, since an unauthenticated request reaches the protocol layer before refusal. A client sees successful transport, an established MCP session, and in-band retryable errors on every tool call, with nothing signaling re-auth. Both halves are one control, pinned end to end by `TestStreamableHTTP_ValidationUnavailable_EdgePassesThroughProtocolRefuses` (`internal/httpserver/validation_outage_test.go`) with `TestStreamableHTTP_DefinitiveRejection_EdgeFailsClosed` holding the boundary. Attacker analysis covers six personas: an unauthenticated network attacker (rate-limited OAuth endpoints with a global backstop, trusted-proxy-aware client-IP resolution that ignores spoofed `X-Forwarded-For`, access-mode-gated share viewer, anonymous only for shares explicitly created public); an authenticated low-privilege persona (default-deny on tools, connections, and API routes; admin and observability surfaces gated separately; Trino cost/PII elicitation consent); a malicious or compromised upstream (tool descriptions and responses flow through without content sanitization, mitigated operationally by per-connection encrypted credentials and audit, not by neutralizing adversarial content); malicious data in query results (prompt-injection content reaches the client; the platform reduces blast radius via read-only mode, persona allowlists, the search-first gate, and audit, but does not scrub content); a database reader (hashed tokens and encrypted secrets yield no usable credentials, but audit content and metadata remain readable, and connection secrets are plaintext if `ENCRYPTION_KEY` is unset); and a compromised downstream credential (blast radius bounded by the downstream service account's own privileges, which least-privilege scoping is a deployment responsibility). Explicit non-goals and residual risks: stdio transport trusts the invoking process with no in-process sandboxing; the platform does not defend against a malicious admin (who can hold `ENCRYPTION_KEY`); audit delivery is best-effort async by default with a documented loss model; downstream identity is per connection rather than per user, which is the authorization design rather than an unmitigated gap (no token exchange, no impersonation, no session-user propagation to Trino, S3, upstream MCP servers, or HTTP APIs, because the construct all of those backends share is a credential and an endpoint, not a caller identity to pass through; the cost, stated without softening, is that all callers granted a connection are indistinguishable downstream and warehouse row policies or column masks keyed off the end user do not follow a caller through, so per-person policy is expressed as one connection per distinct outcome and per-user attribution comes from the audit trail); content sanitization is partial (catalog curation is sanitized on the enrichment path; raw query row values and gateway-upstream tool descriptions/responses are not); and TLS termination, network segmentation, Postgres transport security, and S3 blob-at-rest are deployment responsibilities. Full document with the mitigations table and citations: https://mcp-data-platform.txn2.com/security/threat-model/ --- # Audit Logging Every tool call flows through the audit logging middleware, which records who called what, when, how long it took, and whether it succeeded. Audit logs are stored in PostgreSQL and automatically cleaned up based on a configurable retention period. ## Prerequisites Audit logging requires: 1. A PostgreSQL database (version 13+) 2. The `database.dsn` configuration set With a database available, both `audit.enabled` and `audit.log_tool_calls` default to on, so no `audit:` block is needed to record tool calls. Set either to `false` to opt out. ## Configuration ```yaml database: dsn: "${DATABASE_DSN}" audit: enabled: true log_tool_calls: true log_parameters: true redact_keys: ["password", "token"] delivery: async # async (default) | sync retention_days: 90 ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `database.dsn` | string | - | PostgreSQL connection string. Required for audit logging. | | `audit.enabled` | bool | `true` (when a database is available) | Master switch for audit logging. Set `false` to disable. | | `audit.log_tool_calls` | bool | `true` | Log every `tools/call` request. Set `false` to keep audit on but skip per-tool-call rows. | | `audit.log_parameters` | bool | `true` | Capture tool-call arguments. Set `false` to drop them; `parameters` then holds only a `result` a tool reports about the call's outcome, or null. | | `audit.redact_keys` | list of strings | `[]` | Top-level argument keys whose values become `[REDACTED]` before the event leaves the request path. Case-insensitive; top-level only. | | `audit.delivery` | string | `async` | Store-write path: `async` (best-effort, never blocks the tool call) or `sync` (writes on the request goroutine for backpressure and zero queue drops). | | `audit.retention_days` | int | `90` | Days to keep audit logs before automatic cleanup. | ## What Gets Logged Every tool call produces one row in `audit_logs` with these fields: | Field | Type | Description | |-------|------|-------------| | `id` | VARCHAR(32) | Cryptographically random event ID (base64url, 16 bytes). | | `timestamp` | TIMESTAMPTZ | When the tool call started. | | `duration_ms` | INTEGER | Wall-clock time in milliseconds. | | `request_id` | VARCHAR(255) | Request ID from auth middleware. | | `user_id` | VARCHAR(255) | The principal that made the call: an OIDC subject for a person, `apikey:` for a key, `script:` for a managed-script run. | | `user_email` | VARCHAR(255) | The address the principal acts for (the script owner's on a run). Not an identity: an owner's every script writes the same address, so `user_id` is what separates two rows, and `GET /api/v1/admin/audit/events/filters` returns both the distinct ids and a `user_labels` map between them. | | `persona` | VARCHAR(100) | Resolved persona name. | | `tool_name` | VARCHAR(255) | MCP tool name. | | `toolkit_kind` | VARCHAR(100) | Toolkit type: `trino`, `s3`, `search`, `knowledge`, or `mcp`. | | `toolkit_name` | VARCHAR(100) | Toolkit instance name from config. | | `connection` | VARCHAR(100) | Connection name from toolkit config. | | `parameters` | JSONB | Tool call arguments with sensitive values redacted. | | `success` | BOOLEAN | `true` if tool handler succeeded. | | `error_message` | TEXT | Error description if `success` is `false`. | | `error_category` | VARCHAR(64) | The bounded class of a failed call: a platform error category (`authentication_failed`, `authorization_denied`, `search_required`, `rate_limited`, `user_declined`, `client_input`, ...) or an upstream outcome (`upstream_4xx`, ...). Empty on a success, `NULL` before the column existed. A refused call is audited and this names the refusal (#1892). | | `event_kind` | VARCHAR(64) | High-level category: `mcp_tool_call` and `apigateway_invoke` for tool calls, plus `prompt_serve`, `resource_read`, `resource_move`, `script_run` and `admin`. See [Event kind](#event-kind). | | `created_date` | DATE | Partition key derived from `timestamp`. | ## Sessions read back from the log Every audit row carries the `session_id` of the call that wrote it, so grouped by that id the log is a record of sessions. Sessions are DERIVED, never stored: the platform's own session rows are working state with a TTL that the store deletes on expiry, while audit rows persist for the retention window, so there is no new table, no second write path, and nothing to backfill. A session's kind comes from its id prefix, the only classification available since isolated runs' ids are never persisted: `dps_` agent handle, `dpp_` portal run, `dpx_` managed-script run, and bare hex for a transport session or a call recorded before handles existed. A summary carries the caller and persona of the session's first event, its first and last call, call and failure counts, the distinct tools and connections it touched, and what it produced — with one exception: while the live session record still exists, the persona the handle was MINTED under outranks the per-call persona, because that is what the session was authorized as. Output is read from the two places the platform records it: `portal_assets` rows whose `session_id` matches (deleted ones excluded), and knowledge-dimension `memory_records` whose metadata carries the capturing session (migration 000031 folded `knowledge_insights` into `memory_records`). Opened, a session reads as its summary, those outputs, and the ordered record of its calls, each with the purpose the agent stated, the connection it reached, its outcome, and its duration — the reading order the flat event list cannot give. Served by `GET /api/v1/admin/sessions` (filters: user, kind, time range, has_assets, has_failures) and `GET /api/v1/admin/sessions/{id}` (summary, assets, insights, paged timeline), with `session_id` accepted on `GET /api/v1/admin/audit/events`; in the portal under Admin > Sessions. Migration 000106 adds the two supporting indexes (`idx_portal_assets_session_id` on live assets, `idx_memory_records_session_id` on the metadata expression); `audit_logs` was already indexed on `session_id`. ## Parameter Sanitization A built-in baseline replaces with `[REDACTED]`, at any depth of the arguments (#2356), every key that names a secret: one containing `password`, `secret`, `token`, `api_key`, `apikey`, `credential`, `private_key`, `authorization`, `cookie`, `_pem`, `service_account_json` or `dsn`, or ending in `_key`, and every value under `static_headers` and `session_login_headers` (case-insensitive, `-` read as `_`, so `X-API-Key`, `previous_secret` and `Ocp-Apim-Subscription-Key` match); a key ending in `_path`, `_header`, `_name`, `_names`, `_set`, `_url`, `_encoding`, `_until`, `_at`, `_count`, `_type`, `_placement`, `_id` or `_ids` is kept (`token_path`, `secret_name`). A string argument holding a JSON object or array (an `api_invoke_endpoint` body sent as text), or written as a query with no whitespace (a form-encoded body, a path carrying `?api_key=`), is read and redacted the same way, and a call whose `path` is under `/admin/secrets` has its body's `value` replaced, so a stored secret created through `platform-admin` never reaches `audit_logs`. A string holding SQL that gives a role, user or group a password (`manage_schema`'s `up` and `down`, a statement a script executes) has each literal after the `PASSWORD` replaced by `'[REDACTED]'`, by the rule the migration review refuses the statement by (#2475), including a statement inside a dollar-quoted body (a `DO` block, a function's body), which is read the same way; SQL that sets no password is stored as sent. A call whose `topic` argument is `platform` (a `manage_feedback` platform feedback post) has its `trying_to`, `blocked_by`, `suggestion`, `observed`, `proposal` and `benefit` replaced with `[REDACTED]` (#2820, #2885): a platform feedback post is kept in its own table once it passes the content secret check, and a refused one leaves nothing behind. For your own keys, set `audit.redact_keys`, a case-insensitive list of top-level argument keys whose values are masked in the middleware, before the event ever leaves the request path (top-level only; the baseline covers nested secrets). To drop arguments entirely, for tools whose inputs cannot be made safe to retain even with redaction, set `audit.log_parameters: false`. A `result` key a tool reports about the call's outcome (an API gateway page walk records `pages_fetched`, `items_merged`, and `stopped_by` there) is not an argument value and is recorded either way; with arguments dropped it is all `parameters` holds. ## Middleware Chain The middleware sits in a layered execution chain: ``` ResultType → Icons → DescOverrides → Visibility → OutputSchema → Apps Metadata → Auth/Authz → Audit → Rules → Client Logging → Enrichment → Tool Handler ``` Blocks the chain appends — enrichment context, the proven queries a describe carries, the `call_reference` stamped on a data call — are added as JSON text content and merged into `structuredContent`, but only into a structured result the tool's own handler set, and only when it is a JSON object. A handler that returned none keeps its response as written: a structured result synthesized from the appended blocks alone is not context added to the tool's output, it is the tool's output replaced by the platform's additions. `trino_export` is the case this protects, its asset metadata (`asset_id`, `portal_url`, `row_count`, `size_bytes`) being a text block and nothing else; the same holds for a gateway-proxied tool whose upstream answered in text. For `tools/call` requests: Auth creates the `PlatformContext` (user identity, persona, toolkit metadata) and records tool calls for workflow tracking. Audit reads it to build the audit event. Rules checks session workflow state and prepends warnings when needed. Enrichment adds cross-service context and optional discovery notes. Unauthorized requests are rejected before reaching audit, so only authenticated tool calls appear in audit logs. ResultType, the outermost layer, types every `tools/call`, `prompts/get` and `resources/read` result with the `resultType` the negotiated protocol revision (`2026-07-28` and later) requires: the SDK stamps only the result its own handler returns, so a gate's refusal, the error contract's rebuild of a bare error, and a managed resource read, all built by the layers below, are typed here; an older client receives the field unset, as the SDK leaves it. For `tools/list` responses: Icons, DescOverrides, and Visibility modify tool metadata and filter the tool list, and OutputSchema opens the top level of every advertised output schema (`additionalProperties` allowed, nothing required, the error envelope documented under `error`) so a client validating a result against the schema it was advertised accepts the keys the chain adds to `structuredContent` — the error envelope, `call_reference`, enrichment. Every nested object is advertised open as well (#1945), so a key a later release adds to a nested type (platform_info's `notices`) validates against a schema a client cached before the upgrade; nested `required` lists are kept. A toolkit registering typed handlers without an explicit schema (mcp-trino before v1.4.0) otherwise advertises the closed schema the SDK infers from its struct; the server still validates the handler's own output against that inferred schema before any middleware runs. Audit delivery is configurable (`audit.delivery`). In the default **async** mode, events are enqueued on a bounded writer drained by a single background goroutine, so store latency never blocks a tool response, and a graceful shutdown drains that queue (bounded by a 10s deadline) before the store and database are closed; under sustained backpressure or a crash, queued events are dropped and counted by the `audit_events_dropped_total` metric. In **sync** mode, the event is written on the request goroutine with a per-write timeout, trading latency for backpressure and zero queue-overflow drops. In either mode, a write that fails is logged via `slog.Error` but the tool call still succeeds. ### Error contract Every failed `tools/call` returns a uniform, self-describing error so an agent consumer can tell a correctable mistake from a platform problem instead of guessing (and falsely concluding the platform is down). A failure sets `isError: true`, a self-describing text message (` (code: ) Hint: `), and a machine-readable `structuredContent.error` object `{code, category, message, hint}`. `code` is a stable identifier (`missing_required_parameter`, `invalid_arguments`, `not_found`, `unauthenticated`, `unauthorized`, `setup_required`, `feature_unavailable`, `internal_error`, `tool_error`); `category` is the broad class an agent branches on (`client_input`, `not_found`, `authentication_failed`, `authorization_denied`, `user_declined`, `setup_required`, `feature_unavailable`, `internal`, `tool_error`). A central normalization middleware (`MCPErrorContractMiddleware`, registered inner to Audit/Metrics) guarantees the envelope is present even when a tool returns only a bare message, recovers a panicking handler into a categorized `internal_error` result rather than a dropped connection, and leaves source-categorized results (auth/authz, missing-parameter, not-found, feature-unavailable, setup-required) untouched. The `category` continues to feed the audit log (`error_category`) and metrics (`status_category`). It is built by extending the existing `PlatformError` / `CategorizedError` rather than a parallel type, and covers every toolkit (including the proxied trino/s3 tools) at the shared chain, so no upstream-library change is required. The platform's own tools publish input schemas closed to unknown top-level arguments (`"additionalProperties": false`), so a misnamed argument is refused at the boundary before the handler runs, with `code: invalid_arguments`, `category: client_input`, and a message naming the offending property; nested maps that carry a foreign namespace (`query_params`, `headers`, `body` on the `api_*` tools) stay open, and gateway-proxied tools keep the upstream server's own schema. The `invalid_arguments` refusal says what the call got wrong and what the tool accepts (#2811, `internal/toolhelp`), read from the input schema the server advertises in `tools/list` (`internal/toolschema`, cached a minute, so injected `session_id` and `purpose` are listed): each undeclared property as ` does not take ""; did you mean ""?` (the declared name within a small edit distance, else the one required property the call left out, else no suggestion), each enum miss with the valid values, each JSON type mismatch, then ` accepts: (, required), ...`. Code and category are unchanged; no tool takes an alias (`search` takes `intent`, never `query`). A refused call naming a connection of another kind gains `"" is a/an connection, which this tool does not serve: use [, or platform.query in a managed script]` (#2812, `internal/platform/connroute`), its code kept; a read sent to `trino_execute` runs and its result gains a note naming `trino_query` as the read tool. Every tool choosing its operation by a `command` or `action` enum answers `help` from its schema (#2815): each command with the parameters whose description names it, opening it (`publish: ...`) or after "for"/"required for" anywhere in it (`(required for get, update)`, #2826), `required` per command (the schema's, for a parameter naming no other command, or a "required for" clause naming that command), `common_parameters` (a "required for" clause naming no command assigns none), and an example call per command with every parameter required for it as a typed placeholder; `manage_script`, whose enum lists `help`, answers its own. A managed script's draft treats `help` as a read on every action tool (#2827, `toolwrite.HelpVerb`, pinned by `TestEveryHelpAnswerIsARead`). The second refusal with the same code of one session's call to one tool gains a sentence pointing at `manage_feedback action=create target_type=standalone topic=platform` (#2820; per replica, 10,000 keys; not for `manage_feedback` or a session-less call). A recovered handler panic is logged with the tool, the request id, the sanitized panic value and the stack (#2817). ## Caller class via `source` Tools on this platform are reachable through three entry points; the audit row's `source` field records which one was used: | `source` | Caller | |----------|--------| | `mcp` | Real MCP transport (stdio or HTTP/SSE). Agents. | | `rest` | Gateway REST shim at `POST /api/v1/gateway/{connection}/invoke`. Apache NiFi, cronjobs, integrations, anything HTTP that wraps the platform. | | `admin` | Admin REST API at `POST /api/v1/admin/tools/call`. Portal-driven tool runs. | Both REST entry points open an in-memory MCP session against the assembled server and tag the context (`middleware.WithSource`) before the call so the existing audit middleware records the originating class. Filter via `GET /api/v1/admin/audit/events?source=...` or the **All Sources** dropdown in the portal. Portal-driven runs (`source=admin`) get a distinct portal session ID (`dpp_…` prefix), minted per request by the tool-call middleware, so they are attributable and their search-first gate, provenance, and dedup state are isolated from the operating admin's own agent session. Both stateless shims (`admin`, `rest`) are exempt from the search-first and `SESSION_REQUIRED` gates, so a portal "test this tool" / replay run of a query tool always executes. ## Event kind The `event_kind` field separates the classes of audited activity that share the row shape. A tool call's kind is derived at write time from the toolkit kind — `apigateway_invoke` when the toolkit kind is `api`, `mcp_tool_call` otherwise — so the split does not rely on tool-name matching, and it lets the MCP Activity view exclude high-volume gateway traffic by default while a dedicated gateway view includes it. The other kinds are stamped by the surface that writes them. These seven are the complete set the column holds and the set the filter accepts. | `event_kind` | Meaning | |--------------|---------| | `mcp_tool_call` | Tool routed through the trino, s3, search, or MCP gateway toolkits. | | `apigateway_invoke` | HTTP API call through the apigateway toolkit (`api_*` tools). | | `prompt_serve` | A database prompt served to an agent (`prompts/get`, or a resolved `manage_prompt use`). | | `resource_read` | A managed resource's content served through one of four doors, named by `surface`: `mcp_read`, `fetch`, `rest_download`, or `portal_preview`. | | `resource_move` | A managed resource refiled in another library; carries the scope, scope id and URI on both sides. | | `script_run` | One execution of an approved managed script, written by the run worker when the run finishes; carries the run id as its `session_id`. | | `admin` | An administrative act against somebody else's object; today, an administrator transferring a managed script to another owner. | Accepted on the event list, stats, and all metrics endpoints (timeseries, breakdown, overview, performance, enrichment, discovery): `GET /api/v1/admin/audit/events?event_kind=apigateway_invoke`. A timeseries (admin `/api/v1/admin/audit/metrics/timeseries`, portal `/api/v1/portal/activity/timeseries`) answers with every bucket of its range, so a range is held to 10,000 buckets at its resolution (`audit.MaxTimeseriesBuckets`, checked by the store before it queries): a week by the minute or a range across centuries answers 400 naming the bound, as does an end_time before start_time. Calls held for a person (#2819): a call answered with input requests (`error_category` `input_required`) is recorded `success: false` and is not a failure; `hold_count` is reported on the metrics overview, each breakdown entry and each timeseries bucket, `success_rate` leaves holds out of both sides, `error_count` leaves them out, the breakdown takes `group_by=event_kind`, and the admin tool detail's `activity` counts only `mcp_tool_call` rows and reports `hold_count`. These are computed at read time, so they cover earlier rows too. Failures by category, source and persona (#2795): the breakdown takes `group_by=error_category` and `group_by=source` and a `success` filter (`true`/`false`); with `success=false` it counts the failed calls of a window by refusal or error category (schema_required, search_required, purpose_required, invalid_arguments, ...), by source (mcp, script, portal, endpoint) or by persona, exactly, never capped (the event list's total stops at 10,000), and Admin > Audit > Overview shows them under Failures. An audit row a tool writes itself takes its `source` from the call (`mcpcontext.CallSource`, `mcp` when none recorded): a managed script's table registration (`table_register`) is now `script`; rows written before keep `mcp`, so a `source` filter or breakdown still counts a script's earlier registrations under `mcp`. `GET /api/v1/admin/audit/events/filters` returns the kinds actually present in the data, which is narrower on a deployment that has not used every surface; a filter naming a kind with no rows returns `200` with an empty result rather than an error. The events view reads a bounded amount of audit_logs however large it grows (#2272): `GET /api/v1/admin/audit/events`'s `total` counts no further than 10,000 and adds `total_capped: true` when it stopped there (the portal shows "of 10,000+"); each filter dropdown of `GET /api/v1/admin/audit/events/filters` with no time range is a loose index scan (one index probe per distinct value) over indexes migration 000223 adds on toolkit_kind, source and event_kind (user_id and tool_name were indexed), the user labels one row per user the same way, and NULL is never a value. On 20 million rows opening the view went from 10.2 s to 39 ms and a searched total from 15.2 s to 391 ms; page 150 of the list read 2 ms against page 1's 1 ms before and after. The migration took 27 s on that table, with audit writes waiting. ## Retention and partition rotation A maintenance routine runs every 24 hours and performs three ordered steps: 1. **Ensure upcoming partitions**: `CREATE TABLE IF NOT EXISTS audit_logs_YYYY_MM PARTITION OF audit_logs FOR VALUES FROM (...) TO (...)` for the next two months. The current month is intentionally skipped on brownfield deployments so existing rows in `audit_logs_default` do not block the new named partition. Idempotent. 2. **Delete expired rows**: `DELETE FROM audit_logs WHERE timestamp < NOW() - INTERVAL ' days'`. PostgreSQL prunes to overlapping partitions. 3. **Drop fully expired partitions**: `DROP TABLE IF EXISTS audit_logs_YYYY_MM` for any monthly partition whose entire date range ends at or before the retention cutoff. Constant-time reclamation versus row-level DELETE. Step failures are logged and isolated; a partition operation that errors does not skip the retention DELETE on the same tick. The eager pre-tick `EnsureMonthlyPartitions` also runs once at startup. This pattern keeps audit_logs bounded even at high write volume (e.g. Apache NiFi calling the gateway REST shim at order-of-magnitude-per-second). In multi-replica deployments, the entire maintenance tick (including the eager startup ensure) is guarded by `pg_try_advisory_lock` on a stable key. Every replica still ticks every 24h, but only the pod that wins the lock runs the work; the rest exit silently and retry next tick. This makes the DELETE scan, partition CREATE, and partition DROP run exactly once per tick across the cluster, regardless of replica count. --- # Observability (Prometheus metrics, distributed tracing, correlated logs) Audit answers "who did what." Metrics answer "how is the system performing." Phase 1 of the OpenTelemetry instrumentation in mcp-data-platform exposes Prometheus-format metrics on a dedicated `/metrics` HTTP listener, separate from the main MCP/HTTP listener so scrape traffic and tool traffic do not share an auth path. ## Configuration Metrics are enabled by default. Configuration is environment-only for Phase 1 to keep the surface small. The full surface lands in subsequent phases: | Variable | Default | Purpose | |---|---|---| | `OTEL_METRICS_ENABLED` | `true` | Master switch. Set to `false` to skip MeterProvider construction and not start the listener. | | `OTEL_METRICS_ADDR` | `:9090` | Bind address for the `/metrics` listener. | ## Exposed metrics | Name | Type | Labels | |---|---|---| | `mcp_tool_calls_total` | counter | `tool`, `toolkit_kind`, `persona`, `status_category`, `source` | | `mcp_tool_call_duration_seconds` | histogram | `tool`, `toolkit_kind`, `persona`, `status_category` | | `mcp_inflight_tool_calls` | gauge | (none) | | `mcp_enrichment_bytes_total` | counter | `tool`, `toolkit_kind`, `persona` | | `apigateway_outbound_total` | counter | `connection`, `http_status_class`, `status_category`, `persona` | | `apigateway_outbound_duration_seconds` | histogram | `connection`, `http_status_class`, `status_category` | | `apigateway_inbound_requests_total` | counter | `connection`, `operation_id`, `method`, `status_class`, `identity` | | `apigateway_inbound_duration_seconds` | histogram | `connection`, `operation_id`, `method`, `status_class` | | `http_server_request_duration_seconds` | histogram | `route`, `method`, `status_class` | | `http_rate_limited_total` | counter | `limiter` | | `mcp_requests_total` | counter | `method`, `status` | | `mcp_request_duration_seconds` | histogram | `method`, `status` | | `db_pool_max_open_connections` | gauge | `pool` | | `http_client_requests_total` | counter | `kind`, `connection`, `status_class` | | `http_client_request_duration_seconds` | histogram | `kind`, `connection`, `status_class` | | `egress_blocked_total` | counter | `reason` | | `upstream_retries_total` | counter | `kind` | | `upstream_retries_exhausted_total` | counter | `kind` | | `embedding_calls_total` | counter | `model`, `status` | | `embedding_call_duration_seconds` | histogram | `model` | | `embedding_fallbacks_total` | counter | `model` | | `gateway_upstream_calls_total` | counter | `connection`, `outcome` | | `gateway_upstream_call_duration_seconds` | histogram | `connection` | | `gateway_session_redials_total` | counter | `connection`, `result` | | `background_loop_iterations_total` | counter | `loop`, `result` (`ok`, `error`, `skipped`) | | `background_loop_duration_seconds` | histogram | `loop` | | `background_loop_last_success_timestamp_seconds` | gauge | `loop` | | `retention_rows_purged_total` | counter | `loop` | | `background_queue_items` | gauge | `loop`, `kind`, `state` (`pending`, `running`, `waiting`) | | `background_queue_oldest_age_seconds` | gauge | `loop`, `kind` | | `script_run_failures_total` | counter | `cause` | | `script_runs_shed_total` | counter | (none) | | `script_worker_load_ratio` | gauge | `reason` (`memory`, `cpu`) | | `notification_delivery_attempts_total` | counter | `kind`, `result` (`delivered`, `retry`, `failed`) | | `connection_oauth_refresh_total` | counter | `kind`, `result` (`ok`, `failed`, `revoked`) | | `connection_oauth_credentials` | gauge | `kind`, `state` (`ok`, `expiring`, `revoked`, `missing`) | | `thumbnail_renderer_up` | gauge | (none) | | `thumbnail_render_duration_seconds` | histogram | `kind` | | `thumbnail_render_failures_total` | counter | `kind`, `reason` (`document`, `renderer`, `storage`, `subresource`, `undrawable`) | | `audit_writer_queue_depth` | gauge | (none) | | `audit_write_duration_seconds` | histogram | `result` (`ok`, `error`, `timeout`) | | `pg_listen_connected` | gauge | `loop` | | `pg_listen_reconnects_total` | counter | `loop` | | `pg_listen_last_notification_age_seconds` | gauge | `loop` | Plus the free Go runtime + process metrics (`go_*`, `process_*`). Every background loop runs through `internal/bgloop` (#1897): `background_loop_iterations_total{loop,result}` (`ok`, `error`, `skipped` for a lock held by another replica), `background_loop_duration_seconds{loop}` and `background_loop_last_success_timestamp_seconds{loop}`; each periodic iteration is a root span `loop {name}` whose context its log records carry, a queue worker opens a root span per claimed unit, and a managed script run is one trace (the `loop script_run` span parents every `tools/call` the run makes, through `params._meta`). `retention_rows_purged_total{loop}` counts each sweep's deletions. Queues are read on each scrape (in parallel, cached 10s, the thumbnail backlog 1m; read with max) as `background_queue_items{loop,kind,state}` (`pending`, `running`, `waiting`) and `background_queue_oldest_age_seconds{loop,kind}` for `script_worker`, `script_scheduler` (due schedules not materialized, reported even where the worker is off), `notification_worker` (`email`, `channel`), `webhook_compactor` and `thumbnail_worker` (`asset`, `resource`, `collection`, `script`). Scripts add `script_run_failures_total{cause}`, `script_runs_shed_total`, `script_worker_load_ratio{reason}`; notifications `notification_delivery_attempts_total{kind,result}`; the connection OAuth refresher `connection_oauth_refresh_total{kind,result}` and `connection_oauth_credentials{kind,state}` (`ok`, `expiring`, `revoked`, `missing`; a revoked credential's connection stays `revoked` after its row is deleted, until it is authenticated again or deleted, and a kind with none left reads 0); thumbnails `thumbnail_renderer_up`, `thumbnail_render_duration_seconds{kind}`, `thumbnail_render_failures_total{kind,reason}`; the four LISTEN adapters `pg_listen_connected{loop}`, `pg_listen_reconnects_total{loop}`, `pg_listen_last_notification_age_seconds{loop}` (no ping: `pq.Listener.Ping` holds the listener lock; the age starts at the first connect and only a notification resets it, never a reconnect). A Semgrep rule refuses `time.NewTicker`, `time.Tick` and an infinite loop around a `select` outside the helper. Every HTTP request the platform sends goes through one transport chain (`internal/outbound`, #1895): the platform's User-Agent, a client span named `{kind} {method}` under the calling span, the W3C `traceparent` carried to the upstream, and `http_client_requests_total{kind,connection,status_class}` with its duration histogram. `kind` is `api`, `graphql`, `mcp`, `util`, `oauth`, `oidc`, `embedding`, `notification`, `spec_fetch`, `promql`, `renderer`, `branding`, `maps`, `storage`, `import`, `bot_check` or `standalone`; a transport failure is `status_class="other"`. The span's `url.full` and the URL a transport failure's error names carry no credential (#2358, outbound.ScrubURL/ScrubError): no userinfo, every query value `REDACTED` with the names kept, and a stored secret filled into the path replaced by its name; the connection test and a notification channel's `last_error` show the scrubbed URL. `apigateway_outbound_*` stays as the API-kind view with `persona` and the body-level GraphQL verdict. `trace_propagation: false` on an `api`, `graphql` or `mcp` connection leaves the trace headers off its requests. An egress-guard refusal and a catalog spec fetch whose host the preflight refuses increment `egress_blocked_total{reason}` (`loopback`, `private`, `link_local`, `multicast`, `unspecified`, `cgnat`, `embedded_ipv4`, `internal_hostname`) and log `egress blocked` with the host sanitized. `upstream_retries_total{kind}` / `upstream_retries_exhausted_total{kind}` count a page walk's (`api`) and a script host's (`script`) retries. `embedding_calls_total{model,status}`, `embedding_call_duration_seconds{model}` and `embedding_fallbacks_total{model}` measure every embedding call and the searches that fell back to lexical ranking. `gateway_upstream_calls_total{connection,outcome}` (`ok`, `tool_error`, `transport_error`, `timeout`), `gateway_upstream_call_duration_seconds{connection}` and `gateway_session_redials_total{connection,result}` measure the MCP gateway's forwarded calls and re-dials. A Semgrep rule refuses an `http.Client` built outside the chain. Every inbound HTTP request is measured once, outside every handler, under the route TEMPLATE it matched (#1889): `http_server_request_duration_seconds{route="GET /api/v1/resources",method,status_class}`, never the path, so the series set is the size of the route table. The admin, portal, resources, REST gateway and PromQL proxy routes sit on nested muxes behind an authentication layer that clones the request; each nested mux resolves its template on arrival, so a refused request still reports the template rather than the mount prefix. An unmatched request (404, 405, CORS preflight, CONNECT) is `route="unmatched"`; the webhook receiver's own listener reports `/hooks/`. The MCP transport at `/` is split by `method` so the long-lived `GET` stream sits beside the `POST` messages. Each request carries a server span named `{method} {route}` (`http.request.method`, `http.route`, `http.response.status_code`) that continues the caller's `traceparent` and parents the `tools/call` span. Every 429 a platform rate limiter answers is counted by `http_rate_limited_total{limiter}` (`oauth_token`, `oauth_register`, `portal_viewer`, `portal_content`, `portal_refs`, `observability_proxy`, `pdf_export`, `standalone_export`, `webhook`, `endpoint`, `unknown`). A request slower than `server.slow_request_threshold` (default `5s`) logs `slow HTTP request` at WARN with route, method, status and `duration_ms`; an event stream is never slow. MCP methods other than `tools/call` are counted and timed by `mcp_requests_total{method,status}` / `mcp_request_duration_seconds` (`status`: `ok`, `client_err`, `internal_err`) and each carries a server span named by the method with `mcp.method.name`, `mcp.session.id`, `mcp.protocol.version`; `initialize` is answered by the SDK before any middleware. `db_pool_max_open_connections{pool}` is the pool's ceiling (`database.max_open_conns`). ### Authentication, configuration and platform state (#1898) `auth_attempts_total{method,result,reason}` counts every credential validation the authenticator chain makes and every browser sign-in at the OIDC callback; `method` is `oidc`, `oauth`, `api_key`, `browser` or `unknown` (no credential), attributed to the authenticator that owns the credential (a JWT by its issuer, anything else to API keys), and `reason` is a class (`none`, `expired`, `revoked`, `bad_signature`, `unknown_key`, `idp_unavailable` (no answer or a 5xx), `invalid_claims`, `code_rejected` (a browser sign-in code the identity provider refused with a 4xx), `malformed`), never the error text. Each request is counted once: an MCP request over HTTP is counted at the HTTP gate, and the tool-call middleware's re-validation of it is not counted again. The HTTP gate's fail-open when the identity provider is unreachable logs `auth gate: identity provider unavailable` and increments `auth_fail_open_total`. JWKS fetches are `oidc_jwks_fetches_total{result}`, `oidc_jwks_fetch_duration_seconds`, `oidc_jwks_last_success_timestamp_seconds`; dynamic client registration is `oauth_client_registrations_total{result}`; a grant the OAuth server does not implement is `oauth_token_issuance_total{grant_type="unsupported"}`. Refused tool calls are `mcp_tool_call_denials_total{persona,reason}` (`tool_denied`, `connection_denied`, `no_persona`). `mcp_platform_config_info{toolkit_kinds,auth_methods,tracing,metrics_exporter,sampler_ratio} 1` names what the process runs with and never carries an address or a secret. `config_validation_warnings_total{code}` counts every configuration warning, at boot and when a persona written through the admin API raises one: `persona_tool_unregistered` (a `tools.allow` entry without a wildcard naming a tool the deployment does not register), `persona_incoherent`, `unused_connection`, `agent_instructions_unknown_tool`, `unrecognized_keys`, `deprecated_api_version`, `deprecated_key`, `placeholder_unexpanded`, `ephemeral_oauth_signing_key`, `portal_no_object_storage`, `resources_no_object_storage`, `memory_no_embedding`, `exclude_persona_unknown`, `deployment_id_unset`, `script_destination_outside_prefix`, `site_reserved_label` (a two-character site's `--` addresses, #2611), `site_environment_renamed` (before migration 000239 renames a site's `dev` environment that has a domain, #2608), `site_public_without_domain` (before migration 000245: a public site environment with no domain, #2619), `s3_connection_reaches_platform_bucket` and `s3_connection_reaches_backup_bucket` (a granted S3 connection's credentials list one of the platform's buckets, or a bucket named for backups, #2616). Initialization logs one `platform initialized` line with the version and each `phase__ms`, and writes a `platform.startup` span with a child per phase. `dependency_up{dependency}` (`database`, `semantic`, `query`, `object_storage`, `idp`, `renderer`) is 1 when the dependency answered its last ping; `/readyz` does not read it, so an upstream outage never takes every replica out of a load balancer. The replica's own pool is the exception: every connection in use with none handed out within 500ms for 30s answers `/readyz` 503 `database_pool_starved` (#2169). The pings re-run at most once per `server.state_probe_interval` (default `1m`), only when scraped, and never hold a scrape. `mcp_platform_connections{kind,state}` counts connections by the state the last call through each one found it in, and sends nothing to find out: `healthy` (the upstream answered), `unreachable` (no answer, or 502/503/504), `auth_failed` (HTTP 401/407 from an API, GraphQL, MCP or Trino upstream; an S3 key or signature refused), `configured` (no call has used it on this replica); read with `max by (kind, state)`. The connection test records a state only from an answer that says something about the credential (#2443): an API connection's `probe_path` or a read its catalog declares (401 or 403 is `auth_failed`), or a 401 or 502/503/504 at its base; a 403 or 200 at the base records nothing and leaves what real calls found. A connection's state is dropped on every replica when it is deleted or its configuration changes (#2444). A recorded state stands for `MCP_PLATFORM_CONNECTION_STATE_MAX_AGE` (default `15m`) with no later call and then reads `configured` again (#2442). `mcp_platform_connection_state{connection,kind,state}` is 1 for each connection's current state and `mcp_platform_connection_state_observed_timestamp_seconds{connection,kind}` when a call last recorded it. Each move into a failure logs WARN `connection state changed`, each move out INFO `connection recovered`, with `connection`, `kind`, `from_state`, `to_state` and `reason` (`http_401`, `http_407`, `http_502`-`http_504`, a status class, `timeout`, `transport_error`, `credential_refused`, `network_error`, `answered`; never an address, an answer or an error's text). `mcp_platform_personas` counts the registered personas, `search_index_last_indexed_age_seconds{kind}` how long ago each search source last finished indexing. `domain_operations_total{operation,result}` and `domain_operation_duration_seconds{operation}` count the platform's own operations, each with a span of its name under the calling `tools/call`: `knowledge.apply`, `memory.capture`, `memory.manage`, `search.query`, `search.fetch`, `calls.record`, `calls.reuse`, `calls.promote`, `calls.sweep`, `configstore.read`, `configstore.write`, `resource.upload`, `resource.extract`, `table.register`, `prompt.serve`. `knowledge_changes_total{sink,result}` counts what `apply_knowledge` changed (`catalog`, `knowledge_page`, `agent_instructions`: `applied`/`failed`; `insight`: `created`/`approved`/`rejected`); `search_results_returned_total` sums the hits search returned; archive extraction counts `archive_members_extracted_total`, `archive_extracted_bytes_total` and `archive_refusals_total{reason}`. Every `tools/call` is counted, traced and audited, a call the platform refuses included (#1892): a failed authentication, a persona denial, a session-gate or search-first refusal, a missing session handle or purpose, and a rate-limit refusal each produce one `mcp_tool_calls_total` increment under their `status_category`, one `tool_call` span and one audit row naming the refusal. The tracing, metrics and audit middlewares sit outer to auth and the gates for this; before #1892 they sat inner and a refused call left one log line. `source` on the call counter is how the call arrived (`mcp`, `admin`, `rest`, `script`), the audit event's source. The `tool` label is the registered name; a call naming a tool no toolkit registers records `tool="unregistered"` so a caller cannot mint a series per invented name (the name is on the audit row). The `apigateway_inbound_*` pair measures inbound requests to the REST shim (`POST /api/v1/gateway/{connection}/invoke`, the NiFi-class ETL path), as opposed to `apigateway_outbound_*` which measures the platform's calls to the upstream API. `operation_id` is the OpenAPI operationId resolved from the connection's catalog via path-template matching (`unknown` for no-catalog or no-match). `identity` is the API key's name for key auth, `oidc` for a signed-in person and `unknown` when unauthenticated (bounded by the operator's key list, never by the number of people, and never an address or subject; before #1892 it was the person's email or subject, one series each), recorded on the counter only (never the histogram) to bound bucket cardinality. `apigateway_outbound_total` carries `persona`, the persona the call was authorized under, which separates an automated principal's traffic from an analyst's on a shared connection; it is bounded by the deployment's persona definitions, records `unknown` for a call the platform could not attribute (the same value `mcp_tool_calls_total` uses for that case), and is on the counter and not the duration histogram -- a scope decision, not the cardinality one that keeps `identity` off the inbound histogram, since persona is bounded and `mcp_tool_call_duration_seconds` carries it. Upgrading: a call that never reached persona resolution used to record an empty `persona`, which Prometheus drops; it now records `persona="unknown"` on `mcp_tool_calls_total`, `mcp_tool_call_duration_seconds` and `mcp_enrichment_bytes_total` too, so a rule matching the label's absence must match `persona="unknown"` instead. ### Capacity and integrity (#1899) `db_table_size_bytes{table}` and `db_table_rows_estimate{table}` report each growing platform table's on-disk size (indexes and TOAST, `audit_logs` summed over its partitions) and the planner's row estimate (`pg_class.reltuples`, never a `COUNT(*)`); `db_vector_index_size_bytes{index}` each HNSW index; `db_transaction_id_age` is `age(datfrozenxid)`. Each replica samples the catalog every `MCP_PLATFORM_CAPACITY_INTERVAL` (15m). `storage_bucket_bytes{bucket,purpose,backend}` and `storage_bucket_objects{...}` are what the platform holds in each bucket it owns, kept in shared `storage_usage` rows: a full listing (every `MCP_PLATFORM_STORAGE_SCAN_INTERVAL`, 6h, on one replica under an advisory lock) sets them to what it found plus what each row gained while it ran (objects modified after it began, on the store's clock read from the marker `_mcp_platform_capacity/listing-start` it writes first, are left to the write that made them), skips when another replica listed within the interval, and removes rows of buckets no longer configured; every put and delete the platform makes through its object adapters moves them in between (each replica adds its writes every ten seconds; tiles, redrawn in place, are left to the listing), so an upload shows without waiting for the listing; a delete takes its object off the count but not its bytes, which the listing corrects. The same listing counts `storage_orphaned_objects{purpose}` (an object under a platform prefix no row records, older than `MCP_PLATFORM_STORAGE_ORPHAN_GRACE`, 15m) and `storage_dangling_references{purpose}` (a row whose object is gone, and still names it after the listing ends: a row removed with its object while the listing ran is re-read and not counted, #2663); a site environment's tile (`site_tiles.tile_key`) is a reference like any other key column, and a test derives every object key column from the migrations and fails when no reference query reads one (#2701); a site tile whose object is gone is drawn again on the next request for it, and every site tile is drawn once more on upgrade (generation 4, #2747, draws each as the site's owner: /_viewer answers the owner, the page's GET and HEAD to /endpoints/ run as them marked tile_draw, any other method answers 405, and an owner the directory no longer holds draws for nobody); a tile beside a referenced object belongs to it, `maps/uploads/` is the operator's, and webhook segments are not reconciled. The listing reclaims orphans (#2470): with `MCP_PLATFORM_STORAGE_RECLAIM` at its default, `delete` (`report` logs what it would delete, `off` only counts), an orphan older than `MCP_PLATFORM_STORAGE_RECLAIM_AGE` (24h, apart from the grace because a multipart upload's last-modified time is when it began) is deleted after every reference is read again, counted in `storage_reclaimed_objects{purpose}` and no longer counted as orphaned; at most 10,000 a pass, none under a purpose where more than 100 orphans are more than half of what the listing met (a deployment reading another's bucket), never a tile beside a referenced object, `maps/uploads/`, a webhook segment or a soft-deleted item's object, and no key is logged. `storage_scan_duration_seconds` and `storage_scan_objects` describe the last listing. A purpose is read from the key: `resources/`, `webhooks/` and `maps/` in the managed-resources bucket; under the portal prefix, tile names are `thumbnails`, a script's run outputs `script_outputs`, GraphQL and API exports `exports`, and everything else (Trino exports included) `portal_assets`. `storage_bucket_budget_bytes{bucket}` comes from `MCP_PLATFORM_STORAGE_BUDGETS` (`bucket=size,...`). `mcp_platform_storage_backend_info{backend}` is 1 per store kind (`seaweedfs`, `s3`, `gcs`, `other`), read per bucket from its own S3 connection (`MCP_PLATFORM_STORAGE_BACKEND` overrides). Every replica reports the same values: read them with max. The Go runtime and process series (`go_*`, `process_*`) are pushed over OTLP too, under their Prometheus names, from a registry of their own (#1901). ## Chokepoints Phase 1 instruments two points that cover every tool call through the platform: 1. **`MCPToolCallMiddleware`** — every tool call (MCP transport, SSE, Streamable HTTP, REST gateway shim, admin tools/call) passes through here. One histogram + one counter + one gauge here covers every toolkit at once. 2. **apigateway transport** — every outbound HTTP call from `api_invoke_endpoint`, `api_export`, and the REST gateway shim is recorded at the `http.RoundTripper` level, so adding a new apigateway code path picks up metrics automatically. The calling persona reaches it on the request context, stamped by `MCPToolCallMiddleware` once the authorizer resolves it. Phase 2 adds OTLP tracing on the same chokepoints. Phase 3 extends to toolkit adapters (Trino, S3, OAuth refresh, audit, enrichment). ## Cardinality budget `status_category` is a closed set: `ok`, `auth_err`, `authz_err`, `gate_err` (a refusal by the session gate, the search-first gate, a missing session handle or purpose, or the rate limit; the specific gate is the audit row's `error_category`), `declined` (the user said no to an elicitation), `validation_err`, `upstream_err`, `internal_err`. The OAuth server's `oauth_token_issuance_total` and `oauth_token_refresh_total` carry `status` `ok`, `client_err` (an expired or reused code, a mismatched client_id, a bad verifier, an invalid refresh token) or `server_err` (the token store or signer failed). `TestLabelKeysAreApproved` in `pkg/observability` refuses an instrument whose label key is outside the approved bounded set. `http_status_class` is `2xx` / `3xx` / `4xx` / `5xx` / `other`. High-cardinality fields (user id, email, request id, session id, raw upstream URLs, raw error messages, free-text tool arguments) are NOT recorded as Prometheus labels — they belong on trace spans (Phase 2) and on audit log rows. Worst-case counter cardinality for `mcp_tool_calls_total` with ~40 tools × 8 toolkit_kinds × 5 personas × 8 status_categories × 4 sources = 51,200 series (the duration histogram carries no `source`, 12,800 series times its buckets); for `apigateway_outbound_total` with ~10 connections × 5 status_classes × 6 status_categories × ~5 personas = 1,500 series (the persona dimension is on the counter only, so the duration histogram keeps its 300-series bound). Both well within typical Prometheus and managed-observability backend per-metric series budgets. ## Toolkit, provider, and DB-pool metrics Beyond the MCP and apigateway chokepoints, the toolkit and provider call paths are instrumented so the cross-enrichment fan-out and dependency health are visible: - **Trino** (every statement and metadata call the platform sends, #1896: the `trino_*` tools, the platform's own statements such as table registration DDL, the connection test and the prompt sources' queries, and the query provider's cross-enrichment reads; a statement the read-only check refuses never reached Trino and is not counted): `trino_queries_total{status, query_kind}` and `trino_query_duration_seconds{query_kind}`. `query_kind` is the statement's leading keyword (`select`, `show`, `insert`, `create`, ...), `explain`, or the metadata call (`list_catalogs`, `list_schemas`, `list_tables`, `describe_table`); an unknown keyword maps to `other`; never the SQL text. Each call is a `trino.` client span under the tool call with `db.system.name=trino`, `db.operation.name`, `db.query.summary` (keyword plus the tables read, no literals) and `trino.connection`. (No `trino_bytes_scanned_total` and no queued/running time: the mcp-trino client exposes neither.) - **Platform object storage** (#1896): `storage_operations_total{purpose, operation, result, reason}`, `storage_operation_duration_seconds{purpose, operation}` and `storage_bytes_written_total{purpose}` for every put, get, get_range, list and delete on a bucket the platform owns. `purpose` ∈ `portal_assets`, `resources`, `thumbnails`, `script_outputs`, `exports`, `webhooks`, `maps`; `result` is `ok` or `error`; a failure carries `reason` ∈ `access_denied`, `bucket_missing`, `quota_exceeded`, `not_found`, `other`, read from the store's error code. Spans are `storage.` with `storage.purpose`, `storage.bucket` and `storage.failure_reason`. - **PostgreSQL statements** (#1896): the pool is opened through `otelsql`. `db_client_operation_duration_seconds{operation}` (operation is the statement keyword, `vector_search` for a pgvector ranking, or `begin`/`commit`/`rollback`/`prepare`/`connect`/`ping`) and `db_client_slow_statements_total{operation}` for statements at or over `MCP_PLATFORM_DB_SLOW_STATEMENT_THRESHOLD` (default `1s`, `0` off), which also log `slow database statement` at WARN. Inside a traced request each statement is a `postgres.` span with `db.operation.name` and `db.query.summary`; the SQL text is added only with `OTEL_TRACES_INCLUDE_DB_STATEMENT=true`; a statement outside any trace opens no span. - **S3** (S3 toolkit): `s3_operations_total{operation, status}` and `s3_operation_duration_seconds{operation}`, recorded by an mcp-s3 `ToolMiddleware` installed before tool registration. `operation` is the S3 tool name (`list_buckets`, `get_object`, ...). - **OAuth** (authorization server): `oauth_token_issuance_total{grant_type, status}`, `oauth_token_refresh_total{status}`, and `oauth_token_refresh_duration_seconds`. - **Audit** (async writer): `audit_events_dropped_total{reason}` counts audit events lost by the audit writer: queue-full drops (`queue_full`), writes that failed (`write_failed`) and writes abandoned at the per-write timeout or at shutdown (`timeout`); `audit_writer_queue_depth` and `audit_write_duration_seconds{result}` show the backlog and the store latency (#1897). Audit writes run through a single background goroutine with a per-write timeout, so a stalled database sheds audit load instead of blocking tool calls or leaking goroutines; a growing counter means rows are being lost by design (best-effort delivery). - **Background indexing** (`pkg/indexjobs`, #1837), recorded as each job settles so the figures cover a backlog of any size: `indexjob_jobs_total{kind, trigger, outcome}` (every registered kind's series started at zero for each trigger and outcome when the queue starts, so increase() sees a replica's first job, #2218; outcome `succeeded`, `retried`, `failed`, `source_gone`, `lease_lost`, `store_error`), `indexjob_duration_seconds{kind, outcome}` (claim to settling write, buckets to 3600s), `indexjob_running{kind}` (per replica; sum), `indexjob_enqueued_total{kind, trigger, result}` (`created` or `folded` into an open job), `indexjob_items_total{kind, result}` (`embedded` or `reused`), `indexjob_embed_calls_total{kind, status}` (`ok`, `timeout`, `error`), `indexjob_embed_texts_total{kind}`, `indexjob_embed_call_duration_seconds{kind}`, `indexjob_leases_released_total`, `indexjob_units_deferred_total{kind}` (parked units a reconciler sweep skipped). Read from the database at scrape time (one statement over the open rows plus each kind's coverage, cached 30s; every replica reports the same value, so read with `max by (kind)`): `indexjob_queue_jobs{kind, state}` (`pending`, `running`, `retrying`), `indexjob_failed_units{kind}`, `indexjob_oldest_runnable_wait_seconds{kind}` (a worker claims what a write or an operator asked for ahead of the reconciler's backfill, and kinds take turns, so one kind's backlog holds another kind's job behind one job, #2218), `indexjob_vectors_indexed{kind}`, `indexjob_vectors_expected{kind}` (only for a kind with a known denominator). The admin Indexing dashboard draws Throughput and Embed latency from these. A worker claims the jobs a write or an operator asked for ahead of the reconciler's backfill, longest-waiting first within each (#2218). - **DB pool** (`database/sql`): `db_pool_open_connections`, `db_pool_in_use`, `db_pool_idle`, `db_pool_wait_count_total`, and `db_pool_wait_duration_seconds_total`, all labeled `pool`. These are OTel observable instruments read from `(*sql.DB).Stats()` at scrape time via a single callback registered once at startup; `RegisterDBPool(*sql.DB, name)` adds a handle to the observed set (the platform registers its shared pool as `pool="platform"`). `status` on these metrics reuses the platform's bounded status taxonomy (`ok` for success, `upstream_err` for a failed external call). Per-operation/query_kind label sets are bounded by the closed tool/operation lists. ## Deployment manifests `deployments/observability/clickstack/` is a self-hosted backend (#1900, #1901): a compose profile with the upstream ClickStack all-in-one image by digest (evaluation only; the image runs MongoDB, which is SSPL, and upstream documents it as not for production), Kubernetes manifests applied with `kubectl apply -k`, a per-deployment edge collector (`collector-edge.yaml`: deployment identity, a second pass of the privacy defaults, tail sampling, OTLP export with an auth header), substrate receivers (`collector-substrate.yaml`: PostgreSQL with a pg_monitor role and SQL queries for transaction id age, vacuum lag, the longest transaction and lock waits, the host filesystem, SeaweedFS, ClickHouse's own disk, parts and rejected inserts), a node collector for pod logs and volume capacity, an optional central gateway with the load-balancing exporter documented, per-signal retention (traces 7 days, logs 14, metrics 30), and `seed/seed.py`, which applies eight dashboards, six saved searches and the alerts through HyperDX's `/api/v2` idempotently by name, removes what it created and no longer defines, and with `--render` prints every query as ClickHouse SQL. Every dashboard carries Deployment, Environment and Version filters. Alerts are sent to a generic webhook (`HYPERDX_ALERT_WEBHOOK_URL`). Plain Kubernetes manifests (no Helm, no Operator CRDs) ship in `deployments/observability/`: `pod-annotations.yaml` (enable the listener + `prometheus.io/*` scrape annotations), `recording-rules.yaml` and `alert-rules.yaml` (ConfigMaps with starter rules in the `level:metric:operations` convention — `mcp:tool_call_duration:p95_5m`, `apigateway:inbound_error_rate:5m`, a DB-pool saturation alert, an `up{job="mcp-data-platform"} == 0` alert, etc.), and a README covering how to mount the rules and confirm scraping. The full metric reference is `docs/server/observability.md`. ## What metrics do NOT replace - **Audit logs** remain the source of truth for "who called what entity, with what result" — compliance and user-level analytics. - **Application logs** (stderr / structured slog) remain the source of truth for free-text diagnostic detail and stack traces. Metrics answer "how is the system performing" — they complement, they do not replace. ## Startup heap profiles A replica whose startup work outgrows its memory limit is killed within seconds, before anyone can pull a profile from the `PPROF_ADDR` listener. Setting `MCP_PLATFORM_STARTUP_HEAP_PROFILE_DIR` to a directory makes a starting process write its own (#2721): one heap profile each time the live heap doubles from 256 MiB, during its first 10 minutes, named `heap---MiB.pb.gz` and read with `go tool pprof`. Each write logs `startup heap profile written` with its path. Unset (the default) writes nothing. A heap profile holds stack traces, function names and allocation sizes, never the contents of memory. On Kubernetes, mount an `emptyDir` at the directory: it keeps the files across the container restart an OOM kill causes, and `kubectl cp` reads them out. ## PromQL query proxy The portal reads the scraped metrics back through an authenticated proxy rather than talking to Prometheus directly (which would require CORS, a separate auth path, and exposing an internal service). The platform serves `GET /api/v1/observability/query` and `GET /api/v1/observability/query_range`, forwarding to the configured Prometheus `/api/v1/query` and `/api/v1/query_range` and returning the upstream response body unchanged. Configured under `observability.prometheus` in platform.yaml (`url`, `timeout`, `basic_auth.{username,password}`, `rate_limit_per_second`). An empty `url` leaves the proxy unconfigured: endpoints return 503 with `observability backend not configured` so the portal renders a clean empty state. Access is gated by the `observability:read` persona capability, checked through the same persona tool-allow filter that gates tools (operators grant it by adding `observability:read` to a persona's tools.allow; default-deny). A per-persona rate limit (default 10 queries/second) returns 429 when exceeded. Proxy queries are not audited: the dashboards poll these endpoints on a refresh interval, so auditing each one flooded the audit trail and tool-usage analytics with dashboard-internal reads that are not MCP tool calls. Responses are not cached on the platform; Prometheus is the cache and the portal applies React Query stale-time. ## Distributed Tracing (Phase 2) Where metrics answer "how is the system performing" in aggregate, traces answer "why was THIS call slow" by capturing one MCP request as a single span tree. The platform exports OpenTelemetry spans over OTLP/gRPC to a collector (Tempo, Jaeger, or any OTLP backend). Tracing is OFF by default and independent of metrics: unlike the always-available `/metrics` scrape endpoint, traces need a collector to receive them, so enabling without one is pointless. When off, every span call site is a single span-context check; the tool-call tracing middleware benchmarks at ~0.3 ns/op disabled and ~1.8 µs/op when it samples a span, negligible against millisecond-scale tool calls. ## Load testing and measured limits A Go load harness lives in `test/load` (a separate module, kept out of the root coverage/test/lint gates). It drives named workloads against a running platform over the MCP streamable-HTTP protocol and the REST surfaces, scrapes the platform's own Prometheus metrics before/during/after each run, optionally captures pprof profiles, and writes a self-contained JSON report. It is written in Go against the official MCP SDK because the hot path is the MCP protocol (initialize handshake, session, `tools/call`), which generic HTTP load tools cannot exercise. Like mutation testing, it is deliberately NOT part of `make verify`; run it via the `load-up` / `load-run` / `load-down` Makefile targets. Scenarios: `mcp-tool-call` (the primary hot path: `search` then `trino_query`), `mcp-session-churn` (session-store create/destroy), `oauth-token` (the bcrypt-bound, rate-limited OAuth DCR path), `portal-read` (portal REST reads plus the public viewer), `audit-burst` (sized past the async audit queue to observe `audit_events_dropped_total`), and `soak` (a long fixed-rate run asserting flat memory and goroutines). An opt-in pprof listener supports the harness: setting the `PPROF_ADDR` environment variable starts a dedicated `net/http/pprof` server on a private mux (off by default, never mounted on a client-facing listener, since it exposes process internals). Published single-replica throughput and latency ceilings, the saturation narrative (the async audit writer sheds first; CPU saturates on OAuth bcrypt, not the data path), and copy-pasteable reproduction commands are in `docs/reference/tuning-and-scaling.md` under "Measured limits". ## Agent-effectiveness benchmark A second measurement harness lives in `bench/` (also a separate Go module): the agent-effectiveness benchmark (issue #930). Where the load harness answers "how much" (throughput, latency, memory), the benchmark answers "how well": it holds the model, prompt scaffold, seed data, and task set constant and ablates only the platform configuration (arms as config profiles: `a0` raw toolkit tools vs `a2` the full semantic-first platform), measuring answer accuracy, pass^k reliability, and tool-call efficiency. Ground truth is generated from a fixed-seed dataset (Trino tables, platform catalog curation seeded by `make bench-seed-catalog`, knowledge pages) with the disambiguating facts for its knowledge-trap tasks (units-in-cents, gross-vs-net revenue policy) living only in the metadata and knowledge layers. Efficiency metrics are read back from the platform's own admin audit API (`audit.delivery: sync`), and a run fails loudly when a session's audit rows are incomplete. A deterministic scripted adapter validates the whole pipeline against a live stack with no model API key (`make bench-up`, `make bench-smoke`, `make bench-down`); real runs use a pinned Anthropic model. Like load testing, it is deliberately NOT part of `make verify`. `bench/README.md` is the index to the report series (each study's published page, DOI, protocol, toolchain, and run data); the method for this study is `bench/docs/knowledge-layer-protocol.md` and the sibling knowledge-use study's is `bench/docs/knowledge-use-protocol.md`; every archived run family under `bench/results/` carries a README stating what it does and does not establish, indexed by `bench/results/README.md`. The published reports cite these protocol documents by section name, and `TestHarnessCitationsResolve` fails the build when a cited section stops existing. The S5 suite adds multi-episode memory-insight-knowledge lifecycle protocols (`make bench-lifecycle`, on the `a3` arm): each protocol teaches a novel definition in one session and, across fresh sessions, measures personal recall, cross-identity transfer after the reviewer promotes the insight via `apply_knowledge` (to an entity description or a knowledge page), recall-first supersede when the fact is later corrected, and abstention on facts never taught -- every lifecycle state transition verified through the admin insights and changesets APIs, not inferred from transcripts. A cold-start knowledge-growth suite (`make bench-cold-start`, issue #963) closes the loop between the two halves: it boots the `a3` arm against an empty enrichment layer (undocumented catalog datasets via `make bench-seed-catalog-empty`, no knowledge pages via `BENCH_SEED_PAGES=0`), teaches a six-lesson curriculum (one fact per S3 trap class, promoted to the same catalog descriptions and knowledge pages the A2 seed pre-loads), and re-runs the fixed S3 trap suite with a fresh, never-taught evaluator identity after each promotion -- producing a learning curve of accuracy, per-trap-class resistance, and enrichment coverage as a function of accumulated promoted knowledge (the ceiling is the fully-documented A2 level, so the capture-and-propagation half visibly populates what the surfacing half delivers). The canonical, citable results live in `docs/reference/benchmark-report.md`, recomputed from committed run JSON under `bench/results/`; `docs/reference/benchmarks.md` is the product-framed introduction that names the measured surface (the knowledge layer, not the whole platform) and points to the report. The benchmark measures one knowledge system from two coupled angles: a surfacing half (cross-enrichment and search deliver curated knowledge from its sinks) and a capture-and-propagation half (memory -> insight -> apply_knowledge promotes facts into those sinks -- catalog entity/column descriptions or knowledge pages); the lifecycle populates what enrichment and search deliver, so they are two ends of one pipe, not independent features. Surfacing half, validated by S1-S3 (four arms a0/a1/a2/a3, claude-sonnet-5, k=3, 261 graded attempts per arm, zero harness failures): S3 knowledge-trap accuracy climbs 42.7% (raw tools) -> 57.3% (enrichment) -> 98.7% (full platform), a +56-point gain for the platform over bare tools (95% CI +44 to +67), while S1 discovery and S2 analytical accuracy are near ceiling for every arm; median knowledge-trap tool calls drop 16 -> 10. Arm a3 (platform + memory lifecycle) ties a2 (platform) on S1-S3 because these single-session tasks exercise only the surfacing half, NOT because capture lacks value; capture-and-propagation is what produces the sink contents S1-S3 shows are effective once present, and it is measured separately by S5. Capture-and-propagation half (S5 lifecycle protocols, a3, k=3, 15 multi-session protocols): a capture/personal-recall/unprompted-surface/cross-identity-transfer/update-correctness/duplicate/abstention scorecard plus full-lifecycle pass^3, measuring whether the teach-once-answer-forever mechanism works reliably across fresh sessions rather than an accuracy delta over a (trivially-zero) no-memory baseline, with every state transition verified through the admin insights and changesets APIs. The S5 lifecycle is reported as three runs: a shared-store run (45 attempts, one accumulating knowledge store, k-repeats coupled) and two isolated replicates (each three independent k=1 passes with a full clean platform reset between passes, merged to k=3). The two isolated replicates, identical in configuration, disagree materially (duplicate rate 0% vs 42.9%, pass^3 26.7% vs 20.0%, capture/recall a few points each), which shows most metric-by-metric differences at this scale (15 protocols, small supersede denominators) are run-to-run sampling noise rather than the shared-store confound; the apparent isolation "lift" seen in the first replicate is not reproduced by the second. What is stable across all three runs and is read as the firm result: unprompted surface 100%, update correctness 100%, abstention 96-100%, and cross-identity transfer stuck at ~42-47% (the clearest reproducible reliability ceiling). Because S1-S3 already validates surfacing, the transfer gap is a capture/propagation limit upstream (the apply_knowledge promotion landing in an aspect enrichment reads -- mcp-datahub GetEntity fully populates only datasets/dashboards -- or the second identity surfacing the fact but not using it), not a delivery failure. All three runs recorded zero harness failures and zero episode errors, so transient Claude API outages (which surface as excluded harness failures, never mis-graded answers) did not affect the data. Spend is published as token counts (not dollars), computed from committed per-attempt records: ~158.6M tokens total across all runs (25,182 fresh input, 2,664,630 output, 147,183,943 cache-read, 8,676,898 cache-write), of which cache reads are ~93% -- apply current claude-sonnet-5 per-token pricing to these counts for a cost. S1-S3 and the shared-store S5 run used development build v1.102.0-9-gadfb9d90-dirty; the isolated runs used v1.102.0-10-g32d61254-dirty (platform code byte-identical between the two build commits, verified by diff; only benchmark-harness commits differ); each is pinned in its manifest. A `benchrun -baseline ` regression gate exits nonzero when a fresh run falls below a committed baseline beyond per-suite thresholds; an earlier phase-1 pilot and phase-3 S5 pilot remain under `bench/results/`. Two derived, peer-reviewable deliverables read from the committed run data. `docs/reference/benchmark-report.md` is a neutral evaluation report: it recomputes every statistic from the raw `results.json` files and presents two complementary sub-studies that are never mixed (they used different client paths, the Anthropic API for the ablation and `claude-cli` for the cold-start, which the harness itself refuses to compare on absolute accuracy). Ablation headline: the knowledge layer lifts S3 knowledge-trap accuracy 42.7% -> 98.7% (+56 points, 95% bootstrap CI +44 to +67) and is statistically neutral on S1 discovery and S2 numeric tasks where no business context is needed. Cold-start headline: from a reproducible empty-layer floor (five baseline replicates: 44.0/44.0/47.8/48.0/52.0 percent, mean 47.2%), teaching and promoting six facts lifts trap accuracy to 90.7% at K=3 and 100% at K=1, and the per-trap-class trajectories show each fact's gain arriving at its own promotion checkpoint (the two knowledge-page traps that start at the 0% floor unlock cleanly at their checkpoints). An S5 lifecycle scorecard, replaced in report v2.0 by a k=5 re-run over 30 protocols (149 runs) on platform v1.118.0, reports capture 91.9%, personal recall 95.3%, unprompted surface 100%, cross-identity transfer 98.9% CI [96.8-100.0], abstention 92.6%, and supersede metrics as point estimates with intervals (update correctness 41/41, duplicate rate 22.0% CI [9.8-34.1]) rather than the v1.1 ranges on 7 runs; Section 5 is measured on a later build than Sections 3 and 4, so its differences from v1.1 are across-code (#1129, #1141), not sample-size effects. The report carries a mandatory threats-to-validity section (single model, non-comparable client paths, build provenance, small seed dataset, bootstrap scope, one capture miss, one excluded transient API 500, the distinctive-needle caveat) and a data-availability table. It is written to be cited: an author line (Craig Johnston), a publication date, a Report v2.0 version tied to the platform build, commit, and release tag, and a How-to-cite section with a ready-to-paste citation and a BibTeX entry pointing at a tagged/permalinked artifact; the repo ships `CITATION.cff` and `.zenodo.json` recording the Zenodo concept DOI 10.5281/zenodo.21438044 (published, resolves to the latest version; v2.0.1 is version DOI 10.5281/zenodo.21751635 and the v1.0 snapshot is 10.5281/zenodo.21438045). It also carries a related-work section and a references list (BIRD for the execution-match grading, tau-bench for pass^k, and LOCOMO/LongMemEval/Mem0/Zep for the long-term-memory framing) crediting the methods it borrows without drawing any cross-study comparison. `bench/reports/knowledge-layer/report.ipynb` is the reproducible supplement: a Python/pandas/matplotlib notebook that loads only the committed JSON (no API key, no running platform, no network), recomputes every number, and regenerates the four figures under `bench/reports/knowledge-layer/figures/`; dependencies in `bench/reports/knowledge-layer/requirements.txt`. The follow-up roadmap the report motivates is tracked as a GitHub issue rather than committed documentation (the report stays neutral and makes no recommendations; all direction lives in the issue, which references the report): Track A benchmark improvements (vary teaching order, adversarial/conflicting curricula, multi-model climb, capture-rate as a first-class metric, forgetting/decay after supersede, the channel-ablation experiment that teaches the same fact three ways across three discovery modes to resolve the sink-delivery confound the report was careful not to over-claim, and larger-protocol lifecycle scale) and Track B product improvements each citing the report finding that motivates it (give DataHub-resident facts topic-discoverability at search time, make promoted insights searchable cross-identity to close the ~47% transfer gap, and harden teach-time capture as the loop's rate-limiter). An Errata subsection records post-publication corrections; the 2026-08-02 entry documents that every run executed with fetch (and list_connections) absent from the arm personas' allow-lists (19 fetch attempts across all 4,173 archived transcripts, 19 denials, #1176): the arms measured search-only, single-hop delivery rather than the shipped search-then-fetch surface, uniformly across arms, so the contrasts stand and no statistic changed; the bench configs now grant both tools, guarded by a config test. A second report, `docs/reference/benchmark-report-knowledge-use.md` (version 1.0, 2026-07-26; headline tables replicated on a v1.116.0 tag build), asks when agents USE stored knowledge at all. It grew from a pre-registered study (bench/docs/perishable-knowledge-study-design.md, issue #1054) whose primary hypothesis - that agents under-verify perishable stored beliefs and epistemic metadata would fix it - was falsified at first empirical contact, so everything in it is exploratory with per-rate Wilson intervals and the pre-registered confirmatory matrix never ran. Apparatus: a deterministic social-analytics-shaped fixture behind the API gateway (bench/apisvc -surface perishable) with a between-session world-change control plane, a committed world registry whose workspace scoping makes the cost of re-establishing state a controlled variable (1 to 11 calls), frozen minimal-pair beliefs planted through the real memory_capture tool as the identity later queried, cells whose correct behavior (answer/refuse/verify-then-answer/verify-then-refuse/probe-then-refuse) is derived from computed answerability and belief truth rather than hand-labels, and deterministic grading with a pre-analysis definition of verification (direct state observations only; state-presupposing calls are a separate sensitivity measure). Findings: (1) Sonnet 5 re-derives every checkable delivered belief - verification at ceiling across an elevenfold cost sweep, both belief directions, and matched no-knowledge controls showing a zero-call median effort delta - so delivered world-state observations are redundant for the strong tier; (2) the derivability bridge (an authored reporting convention no endpoint states: positive coverage = sentiment_score >= 70) shows the same model relying on non-derivable testimony 8/8 and, without it, fabricating a plausible threshold in most control attempts - so the knowledge layer's value concentrates in conventions/definitions/policies, consistent with report 1's +56 trap lift; (3) Haiku 4.5 inverts the derivable result (trusts delivered state 29/32), making weak-tier deployments staleness-exposed where strong-tier ones are staleness-immune; (4) neither headline is a client artifact - the tier flip happens within one claude-cli version and the sonnet results replicate exactly (48/48 verified, 0 trusted) on a raw Messages API in-process loop with no agent client; (5) a companion lifecycle probe found supersede at ceiling conditional on capture but strict capture at 33%, decomposed into deterministic mis-filing against the semantically nearest entity and silent non-capture - the measured loss stages of the knowledge lifecycle and a candidate mechanism for report 1's 46.7% transfer. Retired platform features (with evidence): volatility/valid-until schema fields, freshness/recheck-cost enrichment, capture steering toward dated observations (capture already writes dated self-refreshing notes - the archived capture corpus shows it). Every table recomputes offline via bench/reports/knowledge-use/pk_tables.py from bench/results/knowledge-use/; run manifests pin commit, model, driver, client version, seed-set hash, and k. A 2026-08-02 threats-to-validity entry records that every run executed with fetch denied by the pk arm persona, so every rate is a rate under search-only, single-hop delivery; the denial was uniform across cells, the contrasts stand, and the configs now grant fetch (#1176). A third report, `docs/reference/benchmark-report-knowledge-pollution.md` (version 1.0, 2026-08-07; DOI 10.5281/zenodo.21834813), prices the failure mode the first two left open: what a wrong claim costs once the platform's own curation gate has admitted it. Pre-registered (bench/docs/knowledge-pollution-study-design.md, issue #1166) with hypotheses, decision rules, and falsifiers fixed before the confirmatory data; grading is fully deterministic (exact discriminant values computed from the fixture, no judge); the framing is organic error, not adversarial. Design: a wrong claim planted through the real capture-approve-apply path into the shared applied tier beside a co-present correct source, crossed over derivability class (convention: a fiscal boundary nothing in the fixture refutes; checkable: an order count one query settles) x arm (absent/correct/wrong) x tier (Haiku 4.5 / Sonnet 5 / Opus 5), 24 episodes per cell, 432 confirmatory episodes plus pre-registered follow-ups. Headline, inverting the study's own primary hypothesis: the only claim adopted anywhere was the CHECKABLE one - 16/24 on the weak tier, 0/24 on both strong tiers, while the convention was adopted nowhere on the agent client. Mechanism, exact in 120 episodes with no exception: every episode that observed the refuting count answered correctly, every episode that did not adopted, and with nothing planted the weak tier runs the query 24/24 - the claim does not out-argue the world, it removes the impulse to consult it (verification displacement). The effect is unchanged at three directive strengths (a bare statement adopts like an imperative, so it is adoption, not compliance), at least as strong with the claim on a knowledge page as on the catalog entity (search delivery alone carries it; the applied sink is not the load-bearing channel), replicates on a second fixture (24/24 vs 0/24 controls, capability split intact), and replicates on the raw Messages API with no agent client. Two narrowings: the convention's immunity is client-scaffold-bound (raw-API weak tier adopted it 4/8), and the plant's reviewer note disclosed the plant to any episode that fetched the insight - provenance inspection proved capability-graded (convention cells: haiku 9/24, sonnet 18/24, opus 24/24), the strongest tier's convention null is confounded by that disclosure, and the weak tier adopted straight through it. Design consequences: derivability-aware promotion (the claims worth guarding are the ones the platform could verify itself), capability-aware delivery for weak tiers, and provenance-on-fetch as a load-bearing surface. Retraction (RQ3) never ran and the report says so. Every table recomputes offline via bench/reports/knowledge-pollution/pollution_tables.py and every figure via figures.py beside it (both runnable from bench/reports/knowledge-pollution/report.ipynb) from bench/results/knowledge-pollution/, and make bench-report-check (part of make verify and CI's harness job) pins the published headline numbers to the archives; builds are commit-pinned to the v1.118.0-v1.119.0 lineage with every manifest carrying its exact commit. A fourth report, `docs/reference/benchmark-report-graph-completion.md` (version 1.0, 2026-08-10; DOI 10.5281/zenodo.21881798), asks what the structure BETWEEN knowledge pages is for: when a completion task's constraints are spread across a page graph, do authored cross-references deliver what retrieval structurally cannot - constraints search cannot rank (semantic discontinuity) and a decidable notion of done (a graph closure terminates; a ranked list never certifies coverage)? Pre-registered as a stage-3 separation design (bench/docs/graph-completion-study-design.md, issue #1250; confirmatory matrix under #1251 running only what the design froze), after a premise probe (#1241) validated the instruments. Apparatus: a deterministic generated corpus - a fixed 27-page hand-authored core, byte-identical at every scale, inside generated operations-wiki filler at 50/500/5000 total pages (Seed 1250, EdgeDensity 3), graded by minted signatures that structurally cannot occur off their source pages - planted through the platform's knowledge-page surface in two arms holding page meaning constant: graph (authored references as real edges, verified exact) vs stripped (each reference rendered as its meaning-preserving prose fallback, reference table verified empty). Two discontinuity constraints per cell were certified unreachable twice per scale before any episode: offline embedding rank outside the exclusion horizon for every task phrasing, and a live sweep gate requiring absence from every hit list. 99 episodes, one agent configuration, commit-pinned build, every manifest carrying the generator spec and corpus fingerprint. Headline - the pre-registered instrument kill fired, and it is the finding: stripped-arm episodes grounded the certified-unreachable constraints at 1.00 (500 pages) and 0.93 (5000 pages) by reading the prose fallback on an ordinary page and re-searching in the named institution's own vocabulary, which ranks the "unreachable" page instantly. The certifications proved unreachability for task-derived queries; the defeating queries are read-derived - the agent spontaneously runs the classical pseudo-relevance-feedback loop, traversing in query space. Consequence for benchmark design, recorded as the series' instrument rule: "unreachable by search" must hold against read-derived queries, and a meaning-constant stripped arm can never provide that, because meaning-preserving prose names what it points at. What the archives affirmatively show: discovery is not enumeration (grounded coverage at ceiling in every cell of the matrix; roughly eleven fetches - 0.2 percent of the corpus - ground every constraint against 5000 pages; scale moved cost, not coverage); authored edges buy cost and robustness, not coverage (searches per grounded constraint 0.59/0.67/0.63 graph vs 0.73/1.02/1.44 stripped across two orders of magnitude - flat vs roughly doubling - with the matrix's only failed episode and only sub-ceiling cell in stripped/5000, and the share of graph-arm fetches dereferencing a page-learned edge rising 0.09/0.28/0.34 with scale); with search removed entirely the graph arm walked every closure at full depth (1.00 grounded, zero searches, 9 fetches per episode), scale-invariant with the pilot's no-search floors (graph 0.96/0.42 across two reading budgets, stripped 0.00 - no edges and no search means no route at all); and the elicited completeness claim was uniformly conservative (0 of 98 surviving episodes claimed complete, 91 declared open items), so the overclaim channel is unmeasured, not null, and the report says so. The completeness-delivery framing for authored edges is retired with the discontinuity construct; the evidence supports writing cross-references for economy and resilience, not reach. Every table recomputes offline via bench/reports/graph-completion/graph_tables.py and every figure via figures.py beside it (both runnable from bench/reports/graph-completion/report.ipynb) from bench/results/graph-completion-confirmatory/ and bench/results/graph-completion-probe/, and make bench-report-check (part of make verify and CI's harness job) pins the published headline numbers to the archives, including the instrument kill's presence and the archived analyzer's deliberate non-zero exit. Environment-only configuration: `OTEL_TRACES_ENABLED` (default false), `OTEL_EXPORTER_OTLP_ENDPOINT` (OTLP/gRPC `host:port` or a URL, default `localhost:4317`), `OTEL_EXPORTER_OTLP_INSECURE` (unset: plaintext for host:port, the scheme for a URL; set, it decides), `OTEL_TRACES_SAMPLER_ARG` (head-based sampling ratio in [0,1] applied to root spans, default 0.1; a deployment that tail-samples in its collector sets 1.0), `OTEL_SERVICE_NAME` (service.name resource attribute, default `mcp-data-platform`), and `OTEL_TRACES_INCLUDE_USER_EMAIL` (default false: the caller's address goes on the span only when a deployment opts in; the user id is always there). The OTLP exporter connects lazily: an unreachable or unconfigured collector never blocks or fails startup; spans are batched and dropped if undeliverable. Each tool call produces one trace. The ROOT span is named as the MCP semantic conventions say, `tools/call {tool}` with the bounded tool name (the registered name, `unregistered`, or `unknown`), and is opened by the tracing middleware outer to auth and the gates, so a refused call has its span too; it reads the identity auth resolved after the call returns. It carries the convention keys (`mcp.method.name`, `gen_ai.operation.name=execute_tool`, `gen_ai.tool.name`, `mcp.session.id`, `mcp.protocol.version`, `error.type` on failure), the bounded attributes that mirror the metric labels (`mcp.toolkit_kind`, `mcp.persona`, `status_category`), and the high-cardinality fields kept off Prometheus labels (`mcp.user_id`, `mcp.request_id`, `mcp.connection`, `mcp.transport`, `mcp.source`, the enrichment summary); `mcp.tool` and `mcp.session_id` stay one release beside their convention keys. The caller's email address is on the span only when `OTEL_TRACES_INCLUDE_USER_EMAIL=true`. Child spans nest under the root via context propagation: the cross-service `enrichment` fan-out and one span per upstream call to Trino (`trino.`) and S3 (`s3.`), and `postgres.` for the catalog's reads. Span status is Error for any non-ok `status_category`, with the category as the description and the error recorded redacted as a span event. A `tools/call` that arrives with W3C trace context continues the caller's trace (#1893): `params._meta.traceparent`/`tracestate`, where the MCP semantic conventions carry it, winning over the request's HTTP headers; a sampled parent keeps the whole trace through the ParentBased sampler. Every signal, a metric, a span or a log record, carries one resource (#1893): `service.name` (`OTEL_SERVICE_NAME`, default `mcp-data-platform`), `service.version` and `vcs.ref.head.revision` from the build, `service.instance.id` (the hostname, else a UUID minted at boot), and `deployment.environment.name` and `mcp_platform.deployment.id` from `MCP_PLATFORM_DEPLOYMENT_ENVIRONMENT` and `MCP_PLATFORM_DEPLOYMENT_ID`, merged over `OTEL_RESOURCE_ATTRIBUTES` so an operator's own keys ride along and the platform's variables win. On `/metrics` the resource is `target_info`, and the build is `mcp_platform_build_info{version,commit,go_version} 1`. Startup warns when an OTLP exporter is on and nothing names the deployment. `OTEL_METRICS_EXPORTER=prometheus|otlp|both` (default `prometheus`) adds an OTLP push (a second reader on the same MeterProvider, every `OTEL_METRIC_EXPORT_INTERVAL` ms) beside or instead of the scrape; `otlp` alone starts no listener. `OTEL_EXPORTER_OTLP_ENDPOINT` is parsed once for the trace, metric and log exporters in either form the specification defines: `host:port` (plaintext unless `OTEL_EXPORTER_OTLP_INSECURE=false`) or a URL whose scheme chooses TLS unless `OTEL_EXPORTER_OTLP_INSECURE` is set. Logs (#1894): the platform logs JSON to stderr at `LOG_LEVEL`, and every record written on a tool call's path carries `trace_id` and `span_id`, the ids of the span the call's context carries, so a line and its span are joined by one id. `OTEL_LOGS_EXPORTER=otlp` (default `none`) exports every record the stderr handler accepts to the collector as well, through the OpenTelemetry slog bridge (`contrib/bridges/otelslog`, v0.21, pre-v1; the logs SDK is stable at v1.47), carrying the resource and the trace and span ids as OTLP fields; stderr stays the primary sink. Where the export is off the collector reads stderr where the runtime put it: the `filelog` receiver with the `container` parser on Kubernetes, the `json-file` driver's files in Compose. Every `slog` call in a function that has a `context.Context` uses the `Context` form; the rule in `.semgrep/go-slog-context.yml` (run by `make semgrep` and CI over `pkg/middleware`, `pkg/platform`, `internal/platform`, `internal/httpserver`, `internal/admin`, `pkg/portal`, `pkg/admin`, `pkg/oauth` and `pkg/auth`) refuses a context-less call in such a function, inside its closures too. Head-based sampling is in-app via a ParentBased ratio sampler (a sampled caller's whole trace is always kept); the decision is made when the root span starts, before its outcome is known, so at the default 0.1 about 90% of the platform's own traces are never exported, errors and slow calls among them. Tail-based sampling in the collector keeps every error and slow trace it receives and down-samples the rest, and can be tuned without redeploying, but it can only keep what arrives: a deployment that tail-samples sets `OTEL_TRACES_SAMPLER_ARG=1.0` and lets the collector drop. An example collector pipeline (OTLP receiver, `tail_sampling` keeping ERROR and >2s traces, OTLP export to Tempo) ships in `deployments/observability/otel-collector.yaml`; the `AuthFailureSpike` alert in `alert-rules.yaml` has promtool unit tests (`alert-rules.test.yaml`, `make alert-rules-test`), one of them the deployment without an OAuth server where two of its three series are absent. Full reference, the span-tree diagram, and example Tempo/Jaeger queries are in [docs/server/observability.md](https://github.com/txn2/mcp-data-platform/blob/main/docs/server/observability.md). --- # Evaluating This Project Source: https://mcp-data-platform.txn2.com/reference/evaluating/ Reviews of an open source project, by people and by AI agents, usually start from contributor count, stars and forks, release frequency, review comments on pull requests, and whether someone could take over if the maintainer left. Those signals stand in for how well the code is tested, whether changes are reviewed, whether what the project knows is written down, and whether it will last. This project measures those directly; every claim on the page links to the file, gate, test or third-party report that shows it, figures that change carry the date they were read, and `make posture-check` (https://github.com/txn2/mcp-data-platform/blob/main/scripts/posture-check.sh) checks the README's and the page's figures against the tree (in `make verify` and CI's Test job, #2887). How the usual signals apply: one maintainer, with agents doing most implementation, and the engineering knowledge in the repository (gates as code, every rule in CLAUDE.md with the incident behind it, tests named by issue, Development Rules classifying each rule with `TestEveryRuleIsClassified`); few GitHub review comments because review happens before a commit (a correctness review, then a separate security review, then `make verify`, then a human reviews every line); frequent releases are small changes through the full gate set; many contributors are not a measure of testing (SQLite is maintained by a few developers with no outside contributions). - Test coverage: line coverage on `main` was 94.16% on 2026-12-02 (Codecov); CI fails a full run under 82% and a change whose changed lines are under 80% covered (`COVERAGE_MIN`, `PATCH_COVERAGE_MIN`), the Makefile, CI and Codecov thresholds held together by `TestGateFiguresAgree`; more than 1.25 lines of test code per line of production Go (1.32 on 2026-12-02: 736,178 test lines, 557,674 production lines). - Behavior gates: every unit test under the race detector; changed tests again at `-race -cpu=1,2 -count=5` (schedule lane); every `*RealDB*` test on a real PostgreSQL with pgvector and every SQL statement parsed and planned by PostgreSQL (`internal/sqlgate`); migrations on PostgreSQL 16 and 17; mutation testing weekly over `./pkg/...` and `./internal/...` and on every pull request's changed lines, a survivor in a security package failing the job; more than 40 fuzz targets fuzzed daily, with `TestEveryUntrustedParserHasAFuzzTarget`; a nightly end-to-end suite every pull request runs whole before merging; a weekly load test; every scheduled workflow opening or updating an issue when it fails; the timing criteria ten times on a CPU-saturated runner on request; allocation counts of hot paths held on every pull request (`make bench-allocs`). - Acceptance tests: more than 600 files in `test/acceptance` calling the platform through a real MCP client against a running server; a change is blocked unless every changed acceptance test has a recorded passing run (missing, skipped and failed are one verdict); every tool a change registers needs a criterion calling it, and the server refuses to start listing a tool it cannot serve; each test sends every JSON form a parameter's schema admits. - Security process: a threat model before code for changes touching untrusted input, secrets, authorization, encryption or what is stored, logged or served; every place a secret must never reach becomes an acceptance test searching it, as written and encoded; no tag while an issue labeled `security` is open (`scripts/release-tag.py check`); the audit sanitizer held to the keys encrypted at rest (`TestSanitizeParametersCoversEveryEncryptedKey`); gosec, govulncheck against a written allow list, osv-scanner and Semgrep on every pull request, CodeQL in its own workflow; `make verify` refuses to run when local gosec or golangci-lint differs from CI's; release artifacts signed with Cosign with build-provenance attestations; an OpenSSF Best Practices badge (https://www.bestpractices.dev/projects/13548) and OpenSSF Scorecard. - Review: a correctness review and a separate security review before `make verify`, which runs CI's gates cheapest first (`TestVerifyRunsTheCheapestStepFirst`); a human approves every line before it is committed (CLAUDE.md rule 7). - Releases: v0.1.0 on 2026-01-21, 420 release tags by 2026-12-02; a final tag is refused while the latest E2E Nightly on `main` failed unless its annotation gives a `release-without-nightly:` reason (10 of 420 did); `make verify-release` runs `make verify`, CodeQL, mutation testing, osv-scanner over every advisory and the acceptance release check; of 316 `bug` issues closed as completed between 2026-04-26 and 2026-12-01, half closed within 7.5 hours, three quarters within 13, nine in ten within 24. - Documentation: more than 110 pages and more than 400,000 words (118 pages, 438,278 words on 2026-12-03); the docs state where the design stops (Authorization, API Stability, Deployment Shapes), `TestPublicSurfacePolicy` holds the public Go API to the stability promise, the benchmarks publish their method with Zenodo DOIs and recompute every figure from committed raw data, and CLAUDE.md, llms.txt and llms-full.txt orient people and agents from the repository alone. - Stewardship: security reports are handled as SECURITY.md (https://github.com/txn2/mcp-data-platform/blob/main/SECURITY.md) describes. --- # Development Rules CLAUDE.md states the rules every change to this repository is held to. docs/reference/development-rules.md lists each numbered rule and CRITICAL section with its status: enforced (a Makefile target, a Go test or a CI job fails a change that breaks it, named in the row) or human (a step only a person or the agent doing the work can take, such as a threat model, a review or the choice of an integration test). There is no third class: a rule with no gate gains one or is marked a human step. TestEveryRuleIsClassified (test/gates/claude_rules_test.go) fails when CLAUDE.md gains a rule the table does not list, when the table lists one CLAUDE.md no longer states, when a row names a gate that does not exist, and on any other status. Gates added with the table (#2550): - No tag while a security finding is open: an issue reporting a secret reaching a sink, an authorization bypass or a decryption oracle carries the `security` label, and scripts/release-tag.py check refuses every tag, candidate or final, while one is open, in the release workflow and in `make release-tag-check`. - Pinned Dependencies: TestDependenciesArePinnedByDigest fails on a GitHub Action not pinned to a commit, or a Dockerfile base image (other than scratch) or compose image not pinned to a digest. - Diagrams: TestDocsDrawDiagramsInMermaid fails on a box drawn in characters in a tracked Markdown file; a directory tree passes. Human steps named as such: the Factual Integrity rules, the threat model and the attacker's review, integration tests for cross-component behavior, human review, tautological tests, dependency-first verification, coverage of each new function on top of the patch-coverage gate, and reading the dead-code report `make verify` prints. --- # Platform Catalog The platform keeps its own data catalog in PostgreSQL. It records the datasets every connection can see, their columns, the glossary, tags, domains and data products, and the curation written on each. It is the semantic layer wherever the platform has a database: table enrichment, `search` over catalog datasets, glossary lookups and lineage all read from it. No external catalog or ingestion job is involved. ## What is cataloged A **dataset** belongs to the connection that sees it. The same table reached through two connections is two datasets, and a persona sees a dataset only if its connection rules allow that connection. | Connection kind | Datasets | Columns | |-----------------|----------|---------| | `trino` | every table and view, read from each catalog's `information_schema` | each column with its type and whether it allows nulls | | `api` | every stored OpenAPI operation | none | | `graphql` | every query and mutation in the stored schema | each argument, with its type | | registered and webhook tables | recorded when the registration is made, before the call returns | the columns the registration declares | The `system` catalog and every catalog's `information_schema` describe the query engine rather than data, and are never cataloged. ## References A catalog entity is cited and fetched with an `mcp:` reference: | Reference | Names | |-----------|-------| | `mcp:dataset:(kind,connection,path)` | a dataset. The connection is its instance name; the path is the dotted name the connection uses: `catalog.schema.table` for Trino, the operation id for an API, `query.` or `mutation.` for GraphQL. | | `mcp:column:(kind,connection,path,column)` | one column of a dataset | | `mcp:schema_document:(kind,connection,filename)` | an API or GraphQL connection's schema document | | `mcp:glossary_term:`, `mcp:glossary_node:`, `mcp:domain:`, `mcp:data_product:` | a definition, by the id it is stored under. The slug works in place of the id when reading, and renaming a definition changes no reference to it. | | `mcp:tag:` | a tag | A part of a dataset or column reference that contains `.`, `,`, `(`, `)` or `"` is double-quoted the way SQL quotes an identifier, with an inner `"` doubled: `mcp:dataset:(trino,warehouse,hive.sales."orders.v2")`. `fetch` dereferences every form. A dataset comes back with its type, the schema document it was read from when it has one, its columns in order with each column's curation, every aspect written on it, and the lineage edges within three hops `upstream` and `downstream` of it. ## Curation Curation is stored as aspects, each written, versioned and rolled back on its own: - on a dataset or a column: description, tags, glossary terms, owners, domain, custom properties, structured properties, documentation links - on a dataset only: curated queries, incidents, context documents - on a glossary term, glossary node, domain, data product or tag: description, owners, custom properties, documentation links Every write records who made it, when, and the value it replaced. Rolling back a change restores that value and is recorded as a change of its own. A scan never touches curation: redeclaring a dataset keeps the curation of every column that is still declared. Curation is written with `apply_knowledge` (its default sink, `catalog`): the changes of one apply are written in one transaction, recorded as a changeset, and a rollback restores every aspect the apply wrote, refused when one of them has been written again since. An apply that finds an aspect it read written by someone else before its own write lands reads and plans again, so two applies to one entity at once both land. See [Governance](../knowledge/governance.md). A promoted call record becomes a curated query on every dataset its statement read. A knowledge page cites a catalog entity by its `mcp:` reference, in its references or its body, and the citation is checked against the catalog when it is written. ## Schema documents An API connection's OpenAPI spec and a GraphQL connection's schema (as SDL) are kept in the catalog, one per connection, addressed as `mcp:schema_document:(kind,connection,filename)`, for example `mcp:schema_document:(api,billing,"openapi.json")`. Each operation's dataset names the document it was read from: `fetch` on the dataset lists it as a reference, and its `schema_document` field holds it. A scan records a new version only when the document's content or media type changed, so an unchanged spec stays at its version. A document belongs to its connection. `fetch` returns it only to a caller whose persona may reach that connection, the rule its datasets are read under, and answers not found to anyone else. Its text is the body, up to the 1 MiB every fetched file is held to; a longer one is cut at a character boundary with a note saying how much was shown. An administrator lists every document on **Admin > Catalog > Documents**, or with `GET /api/v1/admin/catalog/documents`, and downloads one from there. A knowledge page may cite one. A page's citation of a schema document, a dataset or a column is listed, by `fetch` and on the portal, only to a reader whose persona may reach its connection; another reader's `fetch` counts it in `references_withheld`. ## Scans Every connection is scanned every 6 hours by default, and once when the platform starts if it has never been scanned. A scan writes what the connection sees and marks every dataset it no longer sees as removed. A removed dataset's curation stays readable, and a later scan that sees it again clears the mark. A Trino catalog that cannot be read, for example because its connector is broken, does not fail the connection's scan. The scan writes the catalogs it could read and reconciles them as usual, records the unreadable catalog as unread with the reason, and marks nothing in it removed: what it did not read is not evidence that it is gone. A scan that cannot list the connection at all, or cannot write to the catalog, fails and marks nothing removed. Replicas take turns: one advisory lock guards the scan, and the time of the last scan any replica started decides when the next one is due. ### Admin > Catalog ![Catalog scans](../images/screenshots/light/admin-admin-catalog-light.webp#only-light)![Catalog scans](../images/screenshots/dark/admin-admin-catalog-dark.webp#only-dark) The **Scans** tab lists each connection's last scan: when it finished, how many datasets it wrote, how many it marked removed, the problem when it failed, and each part it could not read ("Not read: legacy", with the reason on hover). The API reports those parts as `unread`, a list of `{path, error}` that is `[]` when every part was read. **Scan now** requests a scan of every connection without waiting for the interval. The request is recorded, so whichever replica next takes the scan lock runs it, even when another replica is scanning at that moment. ![Catalog settings](../images/screenshots/light/admin-admin-catalog-settings-light.webp#only-light)![Catalog settings](../images/screenshots/dark/admin-admin-catalog-settings-dark.webp#only-dark) The **Settings** tab holds the two settings, stored in the database: - **Scan every**: a duration such as `6h` or `90m`, at least `5m`. - **Exclusions**: for a connection, the prefixes it leaves out of the catalog, separated by commas. For Trino a prefix is a catalog (`hive`), a schema (`hive.tmp`) or a table (`hive.tmp.scratch`); for GraphQL, `mutation` leaves out every mutation. The next scan leaves the excluded datasets out and marks any it cataloged before as removed. The same settings and scans are served at `/api/v1/admin/catalog/settings` and `/api/v1/admin/catalog/scans`, and the schema documents at `/api/v1/admin/catalog/documents`; see the [Admin API](admin-api.md). ## Search `search` ranks catalog datasets through the platform's `catalog-datasets` index, built from this catalog. A dataset declared or curated since the index last read the catalog is re-read on the index queue's next check (`knowledge.index_reconcile_interval`, five minutes by default), and the index re-reads the whole catalog at least every `knowledge.catalog_index.sync_interval`. A `knowledge.catalog_index.max_entries` lowered since the last read applies on the next start: a mirror holding more datasets than the cap is re-read down to it then (#2429). ## Lineage Lineage edges are recorded when the platform moves data: - **SQL**: a statement run through `trino_execute` that writes a table from what it reads (`CREATE TABLE ... AS`, `INSERT INTO ... SELECT`, `MERGE INTO`, `CREATE VIEW ... AS`) records an edge from each table it read to the table it wrote. An unqualified name resolves in the connection's default catalog and schema. The statement is read from the audited call, so a deployment with `audit.log_parameters: false` records no SQL lineage. - **Managed scripts**: a run that succeeds records an edge from every table its queries read to every file it exported (a managed resource or a portal asset). - **Registrations**: registering a table over a file records an edge from the file (`mcp:resource:` or `mcp:asset:`) to the table. A table registered over a script's export is therefore reached, walking upstream, from the tables the script read. Each edge records what wrote it: the audited call, the script, or the registration. The semantic layer's lineage walk reads them. ## The portal catalog The portal's Knowledge > Catalog section is where people read and curate the catalog: Tables, Glossary, Tags, Domains and Data products, each tab addressed in the URL hash and an open entity in the `ref` query parameter (`/portal/knowledge/catalog?ref=mcp%3Atag%3Apii#tags`), which is what a catalog reference links to anywhere in the portal. Tables searches the datasets of every connection the reader's persona reaches (text in name, path or description; one connection optionally) and opens a dataset page: description, tags, glossary terms, owners, domain and properties; columns in table order, each with Edit for its own description, tags and glossary terms; context documents (markdown notes with title and category); lineage within three hops, each dataset a link; the schema document an API or GraphQL operation was read from; the knowledge pages that cite it; and history (every change with who, when, what it holds and what it replaced, each with Roll back, recorded as a change of its own; a change the aspect was written over since is refused, naming the newer write). Glossary lists the top of the glossary (terms and nodes filed under no node, nodes with entry counts) or every entry matching a filter; a node's page lists and adds entries under it, a term's page lists the datasets and columns carrying it, with those on unreached connections counted, not named. Tags, Domains and Data products list, describe, create and delete their definitions. A definition still in use is not deleted (a node with entries, a term/tag/domain something carries): 409 naming what uses it. Reading takes the persona's fetch grant and editing its apply_knowledge grant; the Catalog tab is shown only to a reader who may read; a dataset, its columns and schema document are read and written only on connections the persona reaches; an administrator reaches everything; every write is audited as an apply_knowledge call with source portal. apply_knowledge holds its curation writes to the same boundary: an apply or rollback on a dataset or column of an unreached connection is refused, and so is a bulk_untag of a tag one carries. A portal edit carries the value it was made from and is refused when another writer changed it since. Routes under /api/v1/portal/catalog: GET connections (reached connections, whether the caller may edit), GET datasets (q, connection_kind, connection, tag repeatable, limit default 50 max 200, offset), GET browse (connection_kind, connection, path: one level), GET dataset?ref= (columns, curation, lineage within three hops, names of referenced terms and domain), GET schema-document?ref=, GET history?ref= (newest first; aspect narrows), PUT aspect ({reference, aspect, value, expect}; null clears; expect, the value the edit was made from, refuses a write made since with 409), POST rollback ({reference, aspect, change_id}; 409 when the aspect was written over since), GET definitions (kind repeatable, parent, roots, q, limit, offset), POST definitions ({kind, name, parent, description}; 409 naming an existing definition of the same slug), GET definition?ref= (entries under a node, up to 100 carriers, more_uses when more carry it), DELETE definition?ref= (409 while in use). ## Moving from DataHub The platform no longer reads or writes DataHub, apart from importing it once. A configuration that still names DataHub starts: the platform reads the DataHub `toolkits.datahub` names (the instance `semantic.instance` chose, else the kind's `default`, else the first by name; its `url` or `endpoint` and its `token`) and imports it into the catalog after its first catalog scan, and after each later scan until an import against that address finishes without error; a restart after that imports nothing, and one import runs at a time across replicas. Nothing else of DataHub runs: no datahub_* tools, no DataHub enrichment, and `semantic.provider: datahub` is read as the platform catalog. `semantic.provider: datahub`, `toolkits.datahub`, `semantic.instance`, `semantic.urn_mapping`, `semantic.lineage`, `query.urn_mapping`, the `storage:` block, `enrichment.datahub_query_enrichment`, `enrichment.datahub_storage_enrichment`, `enrichment.s3_semantic_enrichment`, `enrichment.search_schema_preview`, `enrichment.schema_preview_max_columns` and `knowledge.apply.datahub_connection` are accepted for this release, strict parsing included, and logged once as `deprecated_key`; the next release refuses them. Lineage inheritance carries over without its settings (#2130): a column with no description or no glossary terms of its own shows the same-named column's from the nearest upstream dataset (up to two hops along the catalog's own lineage, which the import carries over) that the caller's persona reaches, never its tags, marked inherited_from {source_dataset, source_column, hops, match_method: name_exact} in a Trino result's column_context with inheritance_sources beside it; never written to the downstream column; on by default, `enrichment.lineage_inheritance: false` turns it off, and the `semantic.lineage` settings are not read. Admin > Catalog > Import shows the configured DataHub, imports it again (`POST /api/v1/admin/catalog/imports` with an empty body), imports another DataHub given its address and a token used for that run, and lists each run with its report (`GET`, which also returns `configured`). The import reads every dataset including the records DataHub marked removed (a live record's curation first, a removed record's filling what it lacks), each dataset's description, tags, glossary terms, owners, domain, documentation links, custom and structured properties, curated queries, incidents and context documents and each top-level column's description, tags and terms, every glossary node and term, tag, domain and data product, and lineage between cataloged datasets. A Trino dataset is matched by name with `semantic.urn_mapping.catalog_mapping` read backwards and `semantic.urn_mapping.platform` naming the platform when it is not `trino`. An aspect the platform wrote since is kept, and importing again writes only what changed. It then rewrites the DataHub URNs in memories, insights, changesets, call records, knowledge pages (citations become catalog citations) and the dataset search index into catalog references, listing what it could not map. A catalog entity is referenced only by its `mcp:` reference: an apply_knowledge target, a knowledge page citation and a semantic lookup given a `urn:li:` URN are refused. A changeset applied to DataHub before the catalog replaced it cannot be rolled back; a new apply restores the state wanted. The datahub_* tools are gone, not aliased: search finds datasets and definitions, fetch reads a dataset (columns, curation, curated queries, context documents, lineage), a definition (a node with what is under it, a term/tag/domain with its carriers) or a connection (the top of its catalog), a partial dataset path browses, apply_knowledge and the portal curate, and list_connections lists connections. ## The semantic provider With a database, the platform catalog is the semantic provider; no `semantic:` block is needed. `semantic.provider: noop` turns the semantic layer off. Lookups read the catalog directly, so `semantic.cache` has no effect on them; `semantic.cache.ttl` remains the default for `enrichment.session_dedup.entry_ttl`. A dataset is keyed by its connection's own catalog names, so no name mapping applies. # Cross-Enrichment When you query a Trino table, you get the platform catalog's context in the response. When you fetch a dataset from the catalog, you see whether and where it is queryable. No extra calls. ## The Problem It Solves Without cross-enrichment: 1. Query a table 2. Search the catalog for that table 3. Read its owners, tags and incidents Several calls to understand one table. With cross-enrichment, step 1 gives you everything. ## What Gets Injected | When you use | You also get | |--------------|--------------| | Trino | Catalog curation (description, owners, tags, glossary terms, open incidents, column context) | | fetch of a catalog dataset | Whether it is queryable in Trino, on which connection, estimated rows | | S3 | Catalog datasets matching the bucket and prefix | ## Semantic Context (added to Trino results) ```json { "semantic_context": { "urn": "mcp:dataset:(trino,production,hive.sales.orders)", "description": "Customer orders with line items and payment info", "owners": [{"urn": "data-team@example.com", "type": "user", "name": "data-team@example.com", "email": "data-team@example.com"}], "tags": ["pii", "financial"], "domain": {"urn": "mcp:domain:4f1c", "name": "Sales"}, "active_incidents": 1 } } ``` ## Query Availability (on a fetched catalog dataset) ```json { "query_availability": { "available": true, "query_table": "hive.sales.orders", "connection": "production", "estimated_rows": 1500000 } } ``` A table the query engine cannot reach comes back with `available: false` and the reason in `error`. API and GraphQL operations carry none. ### Knowledge Pages (entity to knowledge) When a tool result names entities, the response also carries the canonical knowledge pages that document those entities, so an agent sees the business and domain knowledge about what it just fetched. Entity URNs are read from the result, the reverse lookup finds the pages that reference them, and a bounded `knowledge_pages` block is appended (capped so a widely documented entity does not balloon the response): ```json { "urn": "mcp:dataset:(trino,production,iceberg.retail.daily_sales)", "knowledge_pages": [ {"id": "kp_5cdde7bb", "slug": "retail-sales-vocabulary", "title": "Retail Sales Vocabulary"} ] } ``` The same reverse lookup surfaces in two more agent-facing places: `search(entity_urns=[...])` returns the knowledge pages that reference each entity (datasets and connections) merged with the text-relevance results, and `list_connections` carries per connection a `knowledge_page_count`, and for one connection asked for by name a bounded sample of the pages that document it. `list_connections` answers in two forms (#2813): with no arguments the summary (`form: summary`), each description cut to its first sentence and at most 200 characters, the page sample dropped while `knowledge_page_count` and `health` stay, `kind_tools` at the top level naming the tools that take each kind listed, and a `note`; with `connection: ""` that one connection in full (`form: detail`: whole description, page sample, health, its `call_limits` entry, `kind_tools` for its kind). A name the caller cannot see is refused with `no connection "" is visible to you; the connections are: `. ## Session Metadata Deduplication When Trino enrichment is enabled, every tool call targeting a table receives ~2KB of semantic metadata. In a typical session querying the same table multiple times, this wastes LLM context tokens with repeated information. Session dedup tracks which tables have been enriched per client session. First call gets full metadata; repeat calls within the TTL get reduced content based on the configured mode. ### Configuration ```yaml enrichment: trino_semantic_enrichment: true column_context_filtering: true # Only include SQL-referenced columns (default) session_dedup: enabled: true # Default: true mode: reference # reference (default), summary, none entry_ttl: 5m # Defaults to semantic.cache.ttl session_timeout: 30m # Defaults to server.streamable.session_timeout ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `enabled` | bool | `true` | Whether session dedup is active | | `mode` | string | `reference` | What to send for repeat queries | | `entry_ttl` | duration | semantic cache TTL | How long a table stays "already sent" | | `session_timeout` | duration | streamable session timeout | Idle session cleanup | ### Modes - **`reference`** (default): Repeat calls return `{"metadata_reference": {"tables": [...], "note": "Full semantic metadata was provided earlier..."}}`. Minimal tokens, LLM can refer back. - **`summary`**: Repeat calls return table-level `semantic_context` without column details. LLM gets a reminder of ownership and tags. - **`none`**: Repeat calls return raw tool results with no enrichment. Maximum token savings. ### Behavior - Enabled by default when `trino_semantic_enrichment: true` - Trino-only (the tool calls enrichment adds context to) - In-memory state by default; persisted to database session store if `sessions.store: database` - Each client session has independent dedup state - SQL parsing tracks multiple tables independently (`JOIN` queries) ## Session Externalization Externalize MCP session state to PostgreSQL for zero-downtime restarts and horizontal scaling. ### Configuration ```yaml database: dsn: "${DATABASE_URL}" sessions: store: database # "memory" (default) or "database" ttl: 30m # session lifetime cleanup_interval: 1m # cleanup routine frequency ``` When `store: database`: - Platform forces `server.streamable.stateless: true` on the SDK - Sessions are managed in PostgreSQL via `SessionAwareHandler` - On shutdown, enrichment dedup state is flushed to the session store - On startup, dedup state is restored from persisted sessions - Multiple replicas share the same session store Every MCP protocol revision over HTTP, with either store (#2008): the memory store also runs the SDK's streamable handler stateless behind `SessionAwareHandler`, keeping its sessions in the process, so a client asking for 2026-07-28 (the sessionless revision) gets it and a 2025-11-25 or earlier client is served as before. `platform_info` reports the revision the calling session speaks as `protocol_version` (the `Mcp-Protocol-Version` header, or the revision the session initialized with; `mcpcontext.ProtocolVersion`). Session hijack prevention: each session stores a SHA-256 hash of the creation token. Requests with a different token get HTTP 403. Session termination is served by `SessionAwareHandler` itself: `DELETE /` with an `Mcp-Session-Id` removes the row and answers `204 No Content`; a `DELETE` without the header answers `400`. The request is not forwarded to the SDK, whose stateless handler serves `POST` only (SEP-2575, go-sdk v1.7.0) and would answer `405 Method Not Allowed` for a termination that had already succeeded. ### Server-pushed notifications (`tools`/`prompts`/`resources` `list_changed`) In stateless streamable HTTP mode (the production shape when `sessions.store: database`), the SDK refuses GET requests for SSE streaming and closes each session at end-of-request. Without intervention this means downstream agents (Claude.ai, Claude Desktop) never receive `notifications/tools/list_changed` — when a gateway upstream re-authenticates, agents still show the old tool list until they disconnect and reconnect. The platform handles this with a session broadcaster: - `pkg/session.Broadcaster` is the abstract fan-out interface; the AwareHandler subscribes per-session. - In-memory implementation for single-replica or no-DB deployments. - Postgres `LISTEN/NOTIFY` implementation (channel `mcp_notifications`) for multi-replica. Each replica `LISTEN`s once at startup; every replica re-publishes received events to its local SSE subscribers. - The `AwareHandler.ServeHTTP` GET branch opens a long-lived `text/event-stream` response, subscribes to the broadcaster bound to the request's session ID, and streams every event as a JSON-RPC 2.0 notification (`data: {"jsonrpc":"2.0","method":"notifications/tools/list_changed","params":{}}\n\n`). A 25-second comment-frame heartbeat keeps the stream alive through proxy idle timeouts. - The gateway toolkit publishes `tools/list_changed` (debounced 50 ms — a longer window than the MCP SDK's own 10 ms internal debounce, chosen to absorb the postgres LISTEN/NOTIFY round-trip cost across replicas) after every aggregate tool-inventory change that registers or removes at least one tool: a connection coming up after re-auth, a connection being removed, the SetTokenStore retry promoting a placeholder. Zero-tool changes (placeholder upstreams, removals on connections with no live tools) are silently skipped. - The same broadcaster carries `prompts/list_changed` and `resources/list_changed` (also debounced 50 ms). `notifications/prompts/list_changed` fires on every prompt store write (create, update, delete, approve, scope promotion) across all write paths (`manage_prompt`, admin/portal REST, knowledge `add_prompt`), emitted from a notifying wrapper over the shared prompt store so no write path can change the prompt set without notifying; the advertised `prompts.listChanged` capability is honest. `notifications/resources/list_changed` fires when a managed resource is created or deleted through the admin REST API (startup registration of existing resources does not notify). `resources/subscribe` (per-resource `notifications/resources/updated`) is intentionally not implemented: no current client watches individual managed resources, and the coarse list_changed signal already prompts a re-list, so the capability flag is left unset to keep the contract honest. Broadcaster lifecycle is owned by the platform: `initSessions` builds it (postgres if a DSN is configured, in-memory otherwise) and `Close` shuts it down before the database connection closes. `WireGatewayBroadcaster` plugs it into every gateway toolkit, mirroring `WireGatewayTokenStore`; the prompt and managed-resource notifiers are bound during `finalizeSetup` and stopped via the platform lifecycle. If the postgres broadcaster fails at startup (e.g. role missing `LISTEN` privilege), the platform falls back to in-memory and continues: `tools/list_changed`, `prompts/list_changed`, and `resources/list_changed` propagation degrades to single-replica scope rather than failing platform startup. A session resumed on another build (#1946): each session records in its stored state (`tools_build`) the build whose tool list it was last told about (`HandlerConfig.Build`, internal/buildinfo.Version); a new session records the build it was created on. A request, or the session's reopened event stream, arriving on a process whose build differs sends `notifications/tools/list_changed` to that session alone, once, and records the running build; a session holding no build (created before builds were recorded, or revived after its row expired) is told once too. An announcement made from a request leaves `tools_pending` set, and the session's stream sends it again when it next opens. `session.Event.SessionID` addresses an event to one session (carried as `session_id` in the `mcp_notifications` payload); only that session's stream writes it. During a rolling update a session moving between builds is told on each move. Clients on protocol revision 2026-07-28 (#1967): such a client opens no GET stream; it sends one `subscriptions/listen` request when it registers a list-changed handler, and that request's response is the stream its notifications arrive on, held by the replica that received it. `internal/platform/listenbridge` records each listen stream a replica holds from the SDK's `notifications/subscriptions/acknowledged` (a sending middleware on the MCP server, wired in `internal/httpserver` beside the AwareHandler), drops it when the listen request ends, and writes every broadcaster event to the streams that agreed to its type, stamped with the subscription id (`_meta` `io.modelcontextprotocol/subscriptionId`), honoring `Event.SessionID`. `prompts/list_changed` and `resources/list_changed` from any replica therefore reach every listening client. An unaddressed `tools/list_changed` is not written to listen streams: every replica applies a gateway connection change to its own MCP server (directly, or through the reload bus), and the SDK tells that replica's listen streams itself. A session-addressed `tools/list_changed` (the build notice) is written, at most once per listen; `AwareHandler.AnnounceOnListen` sends it when a listen opens with a `Mcp-Session-Id` whose recorded build is not the running one (the go-sdk client resends the id it was given on `server/discover`; a new connection gets a new session on the running build). A listen stream ends when its replica stops, and the go-sdk client (v1.8.0) does not reopen it, since a 2026-07-28 listen carries no event ids to resume from; such a client is told nothing further until it connects again. A client on 2025-11-25 or earlier opens no listen and is served on its GET stream as before. --- # Tools API Reference Cache scope (#2794): under revision 2026-07-28 every tools/list, prompts/list, resources/list and resources/read result carries `cacheScope: "private"` (each is filtered by caller, or answers within the caller's scope), and resources/templates/list and server/discover carry `"public"`; go-sdk's default is public everywhere. The table is internal/cachescope, applied in MCPResultTypeMiddleware so a result a middleware built is decided too; TestEveryCacheableMethodHasAScope fails on a go-sdk cacheable result it does not set and on a file naming a public method it does not list. Empty lists (#1832): a list with nothing in it is `[]` in every tool result and REST response, never `null`. Every response is encoded by internal/wirejson (encoding/json semantics through the v2 module github.com/go-json-experiment/json with v1 options, plus a nil slice written as []): REST responders, tool result text (pkg/toolkit.JSONResult/MarshalResultJSON), a typed tool's output (pkg/toolkit.AddTool, which every platform tool is registered through in place of mcp.AddTool), and structured content a layer left as a Go value (encoded in MCPResultTypeMiddleware, the outermost layer). A nil map stays null; a nil []byte is "". test/structure TestResponsesAreEncodedByWirejson fails on a function that takes an http.ResponseWriter, returns a *mcp.CallToolResult or builds an mcp.TextContent and calls encoding/json Marshal, MarshalIndent or NewEncoder, and on mcp.AddTool outside pkg/toolkit. `manage_asset action=get_collection` returns `"items": []` for an empty section and `"sections": []` for none. Tools registered by the mcp-trino and mcp-s3 libraries encode their own results. ## Trino Tools ### trino_query Execute a read-only SQL query against Trino. Write operations are rejected. Annotated with `ReadOnlyHint: true`. A query plan is read through it: send `EXPLAIN (TYPE LOGICAL|DISTRIBUTED|IO|VALIDATE) ` and the plan comes back as the result; `EXPLAIN ANALYZE` runs the statement it explains and is refused. A failed query (and a failed `trino_execute`) carries `structuredContent.error` classifying it (#2032): `code` `trino_query_failed`, `category` (`upstream_unavailable`, `client_input`, `internal`), `retryable`, `message`, and `trino` (`error_type`, `error_name`, `error_code`, `sql_state`, `http_status`) or, when Trino never answered, `transport` (`kind`, `http_status`, `detail`). A managed script run ended by a retryable failure is recorded with cause `upstream`, a read Trino itself failed for a temporary reason is re-issued by the host at most three times (opt out with `retry = False`; a read that never reached Trino is not, the client having already retried the connection), a statement is never re-issued, and `on_error = "return"` on `platform.query`, `platform.execute` and `platform.call` hands the script `{"error": {...}}` instead of ending the run. A statement the coordinator accepted and then stopped at its timeout (mcp-trino v1.7.1) is `client_input`, not retryable, with `statement_timeout` (`elapsed_ms`, `cancel_requested`, `cancel_confirmed`) and `query_id`; a timeout before the coordinator accepted it stays a retryable `transport` timeout. In a managed script (#2073) such a run is cause `script`, its error naming the limit, the elapsed time, the query id and whether the cancel was confirmed, and the envelope a script asks for also carries `limit_ms` and `limit_source`. `platform.query` and `platform.execute` take `timeout_seconds` (default 120), as does a `platform.call` to `trino_query` or `trino_execute`: a value above `scripts.sql.max_timeout_seconds` (300, which is also the most it may be set to; lower to tighten) is refused by name, never cut (a version saved before the ceiling was enforced, #2085, runs it at the ceiling with a `WARN statement timeout:` log line and `limit_source` `clamped`), and the host gives a statement no more than the run's remaining time less five seconds. `get_run` and `run_draft` report `slowest_statement` (`tool`, `elapsed_ms`, `limit_ms`, `limit_source`, `share_of_limit`, `timed_out`, `query_id`), `manage_script help` reports `statement_default_timeout_seconds` and `statement_max_timeout_seconds`, and `platform_info`'s `limits.query` reports `script_max_timeout_seconds`. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `query` | string | Yes | - | SQL query to execute (read-only) | | `limit` | integer | No | 1000 | Maximum rows to return | | `connection` | string | No | the kind's `default:` | Trino connection name | **No statement points a table, a schema or a partition at one of the platform's own buckets (#2616).** A catalog that registers tables over managed resources holds credentials that reach the resource bucket by design, so `trino_query` and `trino_execute` (and a script's `platform.query` and `platform.execute`) refuse, on every connection and for every persona, administrators included, a statement holding a location in the portal bucket or the managed-resource bucket (`external_location` or `location` on `CREATE TABLE`/`CREATE SCHEMA`, `SET PROPERTIES`, `CALL ... register_partition`/`register_table`, `EXECUTE add_files`, the same through `EXECUTE IMMEDIATE`), and a location it cannot read before the statement runs (assembled from parts, a procedure argument that is not a literal, `LIKE ... INCLUDING PROPERTIES`). The platform's own registrations run apart from the tools; `manage_table` puts a table over a stored file. An external table over a platform bucket created before this release keeps reading until it is dropped. ### trino_execute Execute any SQL against Trino including write operations (INSERT, UPDATE, DELETE, CREATE, DROP). Annotated with `DestructiveHint: true`. `read_only` is set per instance and the block applies to the connection the call names, or to the default connection when it names none: a call routed to an instance with `read_only: true` is refused while the other instances of the same toolkit still accept writes. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `query` | string | Yes | - | SQL query to execute | | `limit` | integer | No | 1000 | Maximum rows to return | | `connection` | string | No | the kind's `default:` | Trino connection name | ### trino_browse Browse the Trino catalog hierarchy. Omit all parameters to list catalogs. Provide `catalog` to list schemas. Provide `catalog` and `schema` to list tables (with optional `pattern` filter). Parameters: `catalog`, `schema`, `pattern`, `connection` (all optional). ### trino_describe_table Get table schema and metadata. The advertised description (#2814) tells a caller to send `catalog`, `schema` and `table` as three separate arguments, `table` the bare name; it replaces the upstream description until txn2/mcp-trino#122 accepts a dotted name. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `catalog` | string | Yes | - | The catalog containing the table | | `schema` | string | Yes | - | The schema containing the table | | `table` | string | Yes | - | The bare table name, never a dotted `catalog.schema.table` | | `include_sample` | boolean | No | false | Include a 5-row sample of data | | `connection` | string | No | the kind's `default:` | Trino connection name | ### trino_export Export query results directly to a portal asset (CSV, JSON, Markdown, text), bypassing the LLM token budget. Use after validating the query shape with `trino_query`. Only metadata is returned to the agent. Requires portal + trino configured. SQL runs through the read-only interceptor. CSV cells hold each value exactly as the query returned it, including one starting with `=`, `+`, `-` or `@`. Sensitivity tags inherited from source datasets. The response is one JSON object, returned as the tool's structured result and as a single text block; the platform's `call_reference` is merged into that object, so a client reading only the structured result sees `asset_id`, `portal_url`, `row_count`, `size_bytes` and `call_reference` together, as it does for `api_export`. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `sql` | string | Yes | - | SQL query (read-only enforced) | | `format` | string | Yes | - | csv, json, markdown, or text | | `name` | string | Yes | - | Display name for the asset | | `connection` | string | No | default | Trino connection name | | `description` | string | No | - | Asset description | | `tags` | array | No | [] | Lowercase kebab-case tags (max 50 chars, max 20; `_sys-` reserved) | | `limit` | integer | No | deployment max | Row limit. A value over `portal.export.max_rows` is refused; the tool description states this deployment's cap. A result your `limit` cuts is written and flagged | | `on_truncation` | string | No | see below | `fail` or `warn`: what a result cut at a row limit does. Default `warn` when your `limit` cut it, `fail` when the deployment cap did (see "Exports Cut at a Limit") | | `expect_rows` | integer | No | - | The exact row count the export must write; any other count fails, or is flagged under `on_truncation: "warn"` | | `expect_min_rows` | integer | No | - | The fewest rows the export may write. Mutually exclusive with `expect_rows` | | `idempotency_key` | string | No | - | Dedup key to prevent duplicate assets on retry | | `timeout_seconds` | integer | No | deployment default | Query execution timeout | | `create_public_link` | boolean | No | false | Generate a public share link for automation | | `resource` | object | No | - | Land the result in the managed resource at `{path, filename}` instead of a new asset, create-or-replace by path (#1663). Mutually exclusive with `idempotency_key` and `create_public_link`. `api_export` and `graphql_export` take the same block; see "Landing a response in a managed resource". | Configuration: `portal.export.enabled` (auto), `portal.export.max_rows` (100000), `portal.export.max_bytes` (100MB), `portal.export.default_timeout` (5m), `portal.export.max_timeout` (10m). ### Exports Cut at a Limit Every export runs under a bound (#2057): `trino_export` under the caller's `limit` or the deployment's `portal.export.max_rows` (default 100,000), and `api_export`/`graphql_export` with `paginate` under the caller's `paginate.max_pages` or the tool's default (100 pages for api, 10 for graphql). A cut is detected from the engine's own signal, never a second `count(*)`: `trino_export` reads one row past the limit (mcp-trino `Stats.Truncated`), and a walk stops at its bound only when the last page named another; a result ending exactly at the bound is complete. A cut the caller set the bound for is written and flagged by default; a cut at the deployment cap or the default page bound is refused and writes nothing, the error naming the bound, its key, the evidence and the alternatives. `on_truncation` (`fail`/`warn`) overrides either default. `api_export` and `graphql_export` refuse a result over `portal.export.max_bytes` whole, so only a walk can be cut. Every `trino_export` response, and every export response that walked, carries `truncated`, `limit_applied`, `limit_source` (`request`/`deployment`), `limit_unit` (`rows`/`pages`); `arbitrary_subset` when a cut `trino_export` result's SQL has no top-level `ORDER BY`; `expect_mismatch` under warn; and the message says "This file is incomplete." An idempotency hit on a cut export's asset reports the same fields. Marking: an asset carries the reserved tag `_sys-truncated` while its current version is a cut export, and the version's metadata records `truncated`, `limit_applied`, `limit_source`, `limit_unit`; the portal version store adds the tag with such a version and strips the tag and keys with any other (a portal upload included), and a revert carries the reverted version's cut. The asset list shows an Incomplete badge, the asset page "Incomplete: truncated at 100,000 rows", and version history each cut version. A managed resource records the cut on the landed version (migration 000181, `resource_versions.metadata`), shown on the resource page and its history; a resource is not tagged since a replacement leaves its tags alone; a restore carries the restored version's cut. A managed script's `platform.call` of an export that is refused fails the run (unless `on_error="return"`); under warn the run's output records `truncated`, `limit_applied`, `limit_source`, `limit_unit` and its page marks it Incomplete. `expect_rows`/`expect_min_rows` refuse (or flag under warn) a count outside them; for api/graphql the count is the items a walk merged, and an expectation without `paginate` is refused. `platform_info` reports `limits`: `export` (max_rows + max_rows_key when trino_export is reachable, max_bytes + key, default/max timeout seconds + max_timeout_key), `query` (trino_query default_rows, max_rows, timeout_seconds), `page_walk` (`api`/`graphql`: default_max_pages, max_pages), each part only when the caller's persona reaches a tool it bounds. The shared judgment is `internal/exporttrunc`; the top-level ORDER BY check is `sqltables.HasTopLevelOrderBy`. ### trino_list_connections List configured Trino connections. No parameters. ## Catalog Reads and Writes The platform's own catalog is read with `search` and `fetch` and curated with `apply_knowledge`; no catalog toolkit is registered, and the datahub_* tools are gone, not aliased. Find datasets and definitions with `search` (sources `catalog` and `governance`). `fetch mcp:dataset:(kind,connection,path)` reads a dataset: columns and their curation, curated queries, context documents, lineage within three hops `upstream` and `downstream`, the schema document, and for a table or view `query_availability`. `fetch` on a glossary term, node, tag, domain or data product reads the definition; a node lists the entries under it and a term, tag or domain the datasets and columns carrying it. `fetch mcp:connection:(kind,name)` lists the top of the connection's catalog, and a dataset reference whose path stops above a dataset (`mcp:dataset:(trino,,)`) lists what is under it. Curation is written with `apply_knowledge` (`sink=catalog`) and in the portal's Catalog section; connections are listed with `list_connections`. ## S3 Tools Two tools (#1591): `s3_list` lists the buckets of a connection when no bucket is named, or the objects in one bucket when one is; `s3_object` performs one action over a `(bucket, key)`. Both are registered on every S3 connection. `put`, `copy`, `delete` and `presign` with `method: PUT` (an upload link) on a connection configured `read_only: true` are refused with an error naming the connection; `get`, `metadata` and a `GET` presign still work there. `read_only` is enforced by the toolkit only; for defence in depth, give a read-only connection upstream credentials that can only read and list, so no path writes even if a handler missed the check. A connection that sets `bucket_prefix` serves only the buckets whose name starts with it (#2584): `s3_list` with any other `bucket`, and every `s3_object` action on one or a copy whose `dest_bucket` is one, is refused naming the connection and the prefix, compared exactly; a script destination outside it is warned about at startup as `script_destination_outside_prefix`. `s3_object`'s description names where the files of the platform's own buckets are read instead: an asset or an export's output with `fetch` or `manage_asset`, a managed resource with `fetch` or `manage_resource`, a site with `manage_site` (#2814). The platform's own buckets (the portal bucket and the managed-resource bucket) are refused on every connection, for every persona, administrators included (#2616): every `s3_object` action and `s3_list` naming one, either side of a copy, and a bucket source (`manage_resource extract from_bucket`, `manage_site publish from_bucket`) are refused before any request reaches the store, naming the surface that reads it instead (`fetch` or `manage_resource`, `platform.read_resource` from a script, `fetch` or `manage_asset`, `manage_site`), and a bucket listing leaves them out; the name is compared case-insensitively, trimmed, and an ARN by its last segment. At startup the platform logs `s3_connection_reaches_platform_bucket` or `s3_connection_reaches_backup_bucket` for a granted connection whose credentials list one. ### s3_list List buckets, or the objects in one bucket. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `bucket` | string | No | - | Bucket to list objects in; omit to list the connection's buckets (filtered by its `bucket_prefix`); a bucket outside that prefix is refused | | `prefix` | string | No | - | Key prefix filter | | `delimiter` | string | No | - | Groups keys at this character (`/` lists one folder level) into `common_prefixes` | | `max_keys` | integer | No | 1000 | Objects per page (1-1000) | | `continuation_token` | string | No | - | The previous page's `next_continuation_token` | | `connection` | string | No | first configured | S3 connection name | ### s3_object One action over an object. Parameters: `action` (`get`, `metadata`, `put`, `copy`, `delete`, `presign`), `bucket`, `key` (required), `connection`; for `put`: `content` (text, or base64 with `is_base64: true`), `content_type`, `metadata`; for `copy`: `dest_key` (required), `dest_bucket` (default: the same bucket), `metadata`; for `presign`: `method` (`GET` default, or `PUT`), `expires_in` (seconds, default 3600, maximum 604800). `get` is bounded by the connection's `max_get_size` and returns binary content as base64; `put` is bounded by `max_put_size`; `presign` signs against `public_endpoint` when the connection sets one. ## Knowledge Tools ### memory_capture The one way to record knowledge, in the memory toolkit. The `type` (sink-class) drives routing: `personal_preference` and `episodic_event` write live to memory; `business_knowledge`, `schema_entity`, and `operational_rule` write a knowledge-dimension record carrying a pending insight overlay (`insight_status=pending`) that `apply_knowledge` can promote. Capture never waits on the embedder (#1987): the record is inserted with no vector and marked `recall_check=pending` in its metadata, its embedding is enqueued through the memory kind's write-path producer (source_kind `memory`), and the tool returns. The memory index consumer's sink calls `Toolkit.SettleRecall` after it writes the vector, and that runs the recall-first check over the caller's memory (superseded rows excluded so a dead predecessor never absorbs the supersede; stale rows stay matchable, since a restatement corrects them). Of two records at or above the supersede threshold (0.9 cosine) the NEWER supersedes the older, whichever is embedded first, so a newer capture supersedes every record it restates (all of them, consolidating an already-duplicated set). Matches in the 0.75-0.9 band are written to the record's metadata as `similar_existing` (id + score) so the owner can consolidate (`memory_manage` update/consolidate). The check runs once per capture and sets `recall_check=done`. When the capture carries `entity_urns`, only records sharing an entity URN can match. The response's `recall_check` is `pending`, or `unavailable` when there is no embedding provider (captures then append). `memory_manage update` writes changed content at once and enqueues the re-embed the same way. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `type` | string | Yes | - | personal_preference, episodic_event (live); business_knowledge, schema_entity, operational_rule (reviewed) | | `content` | string | Yes | - | Knowledge to record (10-4000 chars) | | `entity_urns` | array | No | [] | Related catalog references (`mcp:dataset:(kind,connection,path)`, schema_entity); max 10 | | `suggested_actions` | array | No | [] | Proposed catalog changes for apply_knowledge (schema_entity) | | `confidence` | string | No | medium | high, medium, low | | `source` | string | No | user | user, agent_discovery, enrichment_gap | | `thread_ids` | array | No | [] | Feedback threads this capture resolves | Captures are owned by the user's email (`memory_records.created_by`), the same key `memory_manage`, search, and the portal use, so a person's knowledge and memory appear together under their **My Knowledge** view. The sink-class is stored on `memory_records.sink_class` (derived from the record's dimension when absent). ### search The universal, topology-free discovery entry point (renamed from `knowledge_search` in #645; corpus widened to API endpoints and connections). Call it FIRST. One query fans across every searchable source the caller can access and returns results grouped by source with a coverage summary, so the agent sees the shape of the answer space instead of tunneling into the first tool that comes to mind. Walking the catalog is `fetch` on a connection, a partial dataset path or a glossary node; the scoped API drill-down stays in `api_discover`. Registered whenever at least one source is available. Corpus (everything the persona can access): the platform catalog's datasets, its governance vocabulary (glossary terms and nodes, tags, domains and data products as first-class entities, #1160), canonical knowledge pages (the internal-knowledge home for business/domain ontology, stored as markdown in the portal database and searched over their full content), the caller's personal memory (non-knowledge dimensions; captured/remembered knowledge surfaces via the insights provider, so a record is never double-listed), captured insights, the caller's feedback threads (lexical, since threads carry no embedding), saved assets, managed resources (human-uploaded reference material, indexed over their metadata AND a bounded text prefix extracted from the uploaded file, so a data dictionary is found by a column name that appears only inside it; #1012), prompts, managed scripts (found by name, description, tags, and typed parameter contract, never by their source code; #1302), the caller's own recorded calls (each hit carrying its derived outcome and its reuse count, so a proven statement outranks a guess; #1321), the caller's own sessions (matched against the purposes their calls stated and the names of the assets they saved, ranked lexically because a session is derived from the audit log and so has no row to carry an embedding; the two arms use the indexes that do exist — the audit purpose full-text index added by migration 000108, and portal_asset_fts; #1322), API endpoints (aggregated across every API gateway connection, reusing `api_discover`'s per-connection semantic/hybrid ranking, each gateway applying its own route policy fail-closed), and connections. API endpoints and connections are in the default corpus, not behind an opt-in. Memory, insights, feedback, and assets are per-user, scoped server-side to the caller (memory and insights by email `created_by`/`captured_by`, feedback by author email, assets by `owner_id`) and fail closed when their scope key is absent; the catalog, the governance vocabulary, knowledge pages, prompts, endpoints, and connections are shared. Managed scripts are per-user: a script is its owner's, so an unidentified caller reaches none. Managed resources are visibility-scoped rather than per-user: the provider derives the caller's visible (scope, scope_id) set exactly as the `resources/list` middleware does (global to everyone, persona to its members, user to its owner) and passes it into the SQL, so a resource the caller could not list is never ranked. A managed script is scoped the same way from `script.Script.VisibleTo` — global to everyone, persona to a caller BELONGING to it, personal to its owner — applied as a store predicate rather than a filter over the answer, and the ranking additionally skips dead ends (disabled, deprecated, superseded), which is a ranking rule and not an access rule: a caller holding an `mcp:script:` reference to a retired script still fetches its contract, which states plainly that nothing will run it. Persona visibility keys on MEMBERSHIP — `knowledge.Caller.Personas`, resolved from roles by the same resolver the resources middleware uses and bound via `search.Toolkit.SetPersonasForRoles` — never on `Caller.Persona`, the persona the request resolved to: resolution substitutes the configured default persona when a caller's roles match none, so using it would hand every unmatched caller the default persona's material. With no resolver bound the set is empty and the caller sees only global plus their own user-scoped material (fail closed). A resource hit additionally carries an MCP `resource_link` content block with the canonical `mcp://` URI so a client with native resource support can attach the file itself. Knowledge pages are org-shared and editable by personas with `apply_knowledge` access; everyone can read them, and anyone can add feedback (threads). A search never surfaces another user's private records or a route a persona could not invoke; an anonymous caller still sees shared sources but no per-user data. The three topology sources (catalog, connections, endpoints) are additionally narrowed by the caller's persona `connections.allow` rules through the same predicate that authorizes a tool call (#1108), so discovery and authorization cannot drift: a catalog dataset belongs to the connection its reference names and is hidden when the persona does not reach it. `fetch` applies the identical boundary, returning not-found for a denied dataset or connection reference so a citation cannot read around what search omitted, and `list_connections` enumerates only granted connections. Tools are a source too (`tools`, #2809): `search` ranks the platform's own registered tools against the intent, by the tools index's embedding similarity (lexically when no embedder or index is available) and filtered by the persona predicate `tools/list` applies, so "publish a static site" returns `manage_site` and "assets shared with me" returns `manage_asset`. Each hit gives the tool's first sentence and one example call fitting the intent: for a tool that chooses its operation by `command` or `action`, the value whose words best match the intent with the parameters it requires, plus any enum parameter whose value the intent names (`{"action":"list","scope":"shared"}`). `search` itself is never a hit. A query may be text (`intent`), entity-keyed (`entity_urns`), or both. The entity path unions every source linked to those catalog references (the catalog entity, URN-linked insights, and the caller's URN-linked memory), expanded along lineage; per-user scope and the catalog's access rules still apply to each source. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `intent` | string | Conditional | - | Natural-language description of what is sought; provide intent, entity_urns, or both | | `context` | string | No | - | Optional surrounding context, folded into the intent to sharpen relevance | | `entity_urns` | array | Conditional | - | Exact entity-keyed lookup: everything linked to these catalog references (catalog entity, linked insights, the caller's linked memory), lineage-expanded | | `status` | string | No | - | Optional filter by insight review status (pending, approved, rejected, applied, superseded) | | `sources` | array | No | - | Narrow to named sources (catalog, governance, context_documents, knowledge_pages, memory, insights, feedback, assets, resources, prompts, scripts, calls, sessions, endpoints, connections); only narrows, never opts past scope; an unrecognized name is echoed back in `unknown_sources` rather than silently ignored | | `limit` | integer | No | 10 | Total results to display across all sources (max 50). Also the per-source ranking depth when it exceeds 25, so a search narrowed to one source returns up to `limit` from it | The display set is balanced rather than a flat relevance list: a total budget with a per-source floor (every matching source stays visible), a per-source ceiling (none runs away), and redistribution of unused budget to sources with more relevant hits. Ranking is hybrid (semantic vector + lexical) when an embedding provider is configured, falling back to lexical-only otherwise; an entity-only query reports ranking `entity`. A hybrid lexical arm matches records holding every word of the intent; a lexical ranking (no embedder, or one that did not answer in time) matches records holding ANY word and ranks those holding more first (#2838, `internal/ftsquery`, every lexical-only search on the platform), and its response carries `ranking_note` saying why it is lexical and that each result matches at least one of the intent's words. The response carries `ranking`, `count` (total shown), a `groups` array (`{source, hits[]}` where each hit pairs the matched `text` with its `source`, a `ref` (record id within that source), a relevance `score`, a canonical `reference` (the citation `fetch` dereferences), and where present `status`, `entity_urns`, and `dimension`), and a `coverage` array (`{source, matched, shown, matched_capped, withheld}`) reporting how many matched beyond what is displayed (the anti-tunnel signal) and how many the persona connection boundary removed. Each source ranks up to `limit` candidates (25 when `limit` is smaller) and `matched` counts within that bound; a source with more matching records than the bound carries `matched_capped: true`, making its `matched` a floor rather than a total (#1585). Without it a source that matched exactly the bound and one that matched thousands both read as `matched: 25, shown: 25`, which tells the agent it has seen everything at the moment it has not; raise `limit` to rank further into one source, or browse it for a true `total`. A count the persona connection boundary shortened is exact for what it says and is not flagged. `withheld` is present only when something was hidden, is accompanied by a top-level `withheld_notice` naming the persona and the remedy, and a source filtered down to nothing still reports its withheld count -- so an agent reads "present, but not yours to see" instead of concluding the data does not exist and re-deriving it. The catalog source ranks two ways (#1131). The platform keeps its own index of every catalog dataset's text (name, description, tags, domain) in `catalog_datasets` and ranks the query against it first (hybrid vector + full-text); the catalog's word search over names, paths and descriptions follows as the recall tail, and a dataset both return is emitted once at the index's rank. This is what gives a fact written into a dataset description — by `apply_knowledge` with sink `catalog`, or by a person in the portal's Catalog section — a search-time route that does not require a tool result to already name its entity, closing the asymmetry with knowledge-page sinks, which always rode the platform's own search. The corpus is refreshed by the `catalog-datasets` indexjobs consumer (internal/platform/datasetindex): its Source enumerates the catalog, materializes the mirror, and the Sink's atomic replace prunes datasets the catalog no longer returns, so a deleted dataset cannot linger as a hit. Scheduling needs no goroutine — `FindGaps` reports the corpus stale once `knowledge.catalog_index.sync_interval` (default 30m) has passed since the last enumeration, and the queue's own claim/lease makes the sweep single-flight across replicas. `knowledge.catalog_index.max_entries` (default 5000) caps the mirror: when it binds the index keeps every Trino table, then GraphQL operations, then API operations (#2381), logs the truncation, and its coverage on the Indexing page is held to the catalog's own count, so it reads degraded while datasets are left out. The built-in `platform-admin` connection's operations are never indexed; they stay in the catalog and are found through `api_discover`. Every hit is still dereferenced against the catalog by reference, the persona connection boundary applies to index hits exactly as to word-search ones, and an index failure degrades to the word search rather than blanking the catalog source. A dataset declared or curated since the index last read it is re-read on the index queue's next check. Without an embedding provider the index ranks lexically. The `governance` source (#1160) makes the catalog's glossary terms and nodes, tags, domains and data products searchable and fetchable as entities in their own right rather than as attributes of a dataset. It is a sibling of `catalog`, not an arm of it -- the two answer different questions ("what does X mean here" versus "which datasets are about X"), and the allocator balances the display budget per source, so a definition is never crowded out by a broad dataset match. It is text-only: a definition reference handed to `search` is a reference, and `fetch` is the verb that dereferences one. Definitions are ranked by the words a natural-language intent shares with each one's name, slug and description, the same lexical token-overlap rule the `connections` source uses, so "what does net revenue mean here" reaches a term it does not name exactly. Each hit carries the definition in its text so a term match needs no follow-up `fetch`. Connection boundary: a definition belongs to no connection, so it is visible to every caller who may search; the datasets and columns a `fetch` lists under it are filtered by the caller's boundary, with the removed count and reason carried on the fetched entity. A fetched entity fills `content` with `{reference, kind, name, description, parent?, owners?, custom_properties?, documentation_links?, children?, carriers?, more_carriers?, carriers_withheld?, notice?}`; a node's `children` lists up to 200 entries, the carrier list is capped at 25 and `more_carriers` reports that more carry it than are listed, so a bounded list never reads as the whole membership. Browse mode (#695) is `search`'s exhaustive counterpart: relevance ranking with per-source flooring/capping cannot list a source in full, so browse pages the complete set of one source with a total count and NO relevance threshold, for auditing, deduping, governing, or migrating a corpus an agent must first obtain whole. It is the same `search` tool. A call enters browse mode when it carries exactly one `sources` entry, no `intent`, and no `entity_urns`; `offset`/`limit` page it (limit default 50, max 100). The browsable source is `knowledge_pages`; the catalog is walked with `fetch` instead; browsing zero or several sources, an unknown source, or a non-browsable one is a tool error that names what can be browsed. The response is a flat, unranked page `{source, total, offset, limit, count, items[]}`: `total` is the source's full member count (how many pages remain) and each item carries the same `reference` that `fetch` reads in full. Scope mirrors `search`: knowledge pages are org-global so any caller may enumerate them, and a per-user source is never browsable for an anonymous caller. ### fetch The companion read verb to `search` (#694). `search` returns navigational pointers with truncated snippets; `fetch` dereferences one pointer's `reference` back to its complete content, so an agent can read in full what it found. It is the single consumer of the `reference` every search hit already carries, and it collapses the previously fragmented scoped readers (the catalog's by-reference reads, `manage_asset` get, `manage_prompt` get) into one verb. Registered alongside `search` (same toolkit) whenever search exists. Every reference is in the `mcp:` scheme. `fetch` routes each well-formed reference by its form to the owning source: knowledge pages (`mcp:knowledge_page:` -> the full markdown body and its declared references, a cited asset, collection, prompt or managed resource the caller cannot open left out and counted in `references_withheld`, #2028; the page's slug is accepted in place of the id, with the id resolved first so a slug can never shadow a page asked for by id), saved assets (`mcp:asset:` -> the asset's metadata record; the blob bytes stay in S3, reached with `s3_object` `get` or `presign`; readable by its owner, a person it is shared with directly or through a collection, and an administrator, as the portal opens it, while a script run reaches its author's own assets and its script's outputs, #2027), prompts (`mcp:prompt:` -> the full prompt), connections (`mcp:connection:(kind,name)` -> the connection descriptor with the top level of its catalog), the platform's own catalog (#1917: `mcp:dataset:(kind,connection,path)` -> the dataset with its type, the schema document it was read from, ordered columns and every aspect of curation, lineage within three hops, and for a table or view `query_availability`, readable only by a caller whose persona may reach the connection; a dataset reference whose path stops above a dataset lists the path groups and datasets under it; `mcp:column:(kind,connection,path,column)` -> one column with its curation; `mcp:schema_document:(kind,connection,filename)` -> an API connection's OpenAPI spec or a GraphQL connection's SDL as text up to 1 MiB, under the same connection rule (#1918); `mcp:glossary_term:`, `mcp:glossary_node:`, `mcp:domain:`, `mcp:data_product:` -> the definition, a node with the entries under it and a term or domain with its carriers, the slug accepted in place of the id; `mcp:tag:` -> the tag and its carriers), the caller's captured insights (`mcp:insight:` -> the full insight, scoped to the caller), the caller's personal memory (`mcp:memory:` -> the full memory record, scoped to the caller; fetch-only, not citable on a page) (#699), and managed resources (`mcp:resource:` -> the metadata record plus the file itself, in whichever form the file admits: a text file's contents inline, a PDF's extracted text, the XML parts of an Office document (`.docx`, `.xlsx`, `.pptx`, `.odt`, `.ods`, `.odp`, and any zip) each under a banner naming the part and its size followed by an inventory of what was not rendered, an image as an MCP `image` content block a model looks at directly, and any other family as an MCP `resource` content block carrying the bytes for the client's own tools to open. Only a file above the 1 MB inline threshold the MCP read path uses returns metadata alone, with the canonical `mcp://` URI, MIME type, and size, which `resources/read` reads the whole file by with no limit. Until #1657 every non-textual family returned that metadata row, and an agent handed a PDF's size and media type reported that the platform was refusing it the file. PDF text is read by PDFium compiled to WebAssembly and run under wazero, cgo-free, with its module compiled on the first PDF a deployment reads rather than at startup; the same reader feeds the content index, so a PDF and a presentation are found by words that appear only inside them. Fetch-only, not citable on a page since a scoped resource would be a broken citation outside its scope) (#1012, #1657), and managed scripts (`mcp:script:` -> the script's CONTRACT: name, description, owner, typed parameter contract, whether a run requested now would be admitted (and the run gate's own refusal when it would not), schedule cadence, and the last successful run with what it produced, each output naming its shape — a portal asset the platform still serves, or an object delivered to a configured bucket destination that it wrote and does not hold — for the owner and administrators only, then the files it produced that the caller can open, with a count of the rest over its 50 most recent outputs, and its current source, all for every signed-in caller (#2027); citable on a knowledge page, where it resolves for every reader (#1855), and resolved by ID so renaming a script never breaks a stored reference) (#1302), recorded calls (`mcp:call:` -> the cataloged call: the statement or request that ran, the purpose stated for it, what came of it, and how many later sessions re-ran it; reading one is what makes the caller's own re-run of it creditable as reuse) (#1321), and sessions (`mcp:session:` -> the caller's own session: its summary, the assets and insights it produced as references to follow, and its call timeline in order, each call carrying the purpose stated for it and, where the catalog recorded one, its kind, its outcome, and the `mcp:call:` reference that reads the record in full; a call with no record stays on the timeline and simply carries nothing to fetch) (#1322). The usual source of a reference is a `search` result's `reference` field, but `fetch` is not limited to references `search` produced: a well-formed reference held from another tool works too (for example a lineage edge's `source` or `target` from a fetched dataset). Feedback threads and API endpoints emit no reference and are not fetch targets. The per-user sources (assets, memory, insights, recorded calls, sessions) are read only for the identity that owns the record, so a non-owner gets a structured not-found, exactly as search would never have surfaced the record. A session id is guessable, being the handle the agent threads, so the scoping is a predicate on the audit rows themselves: another caller's session groups to no rows and is indistinguishable from one that never ran. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `reference` | string | Yes | An `mcp:` reference; usually a `search` result's `reference` field passed verbatim, but any well-formed reference held from another tool works | A catalog or governance reference the catalog does not hold is one of those not-founds. Whether the record is documented has no bearing on it, so a dataset with no description and a root glossary term with no definition resolve like any other. The same read backs search by entity_urns, so a reference that names nothing reports no match rather than a hit whose reference then fails to fetch (#1605, #1610). ### apply_knowledge The sink router (#633, #1607). Review, synthesize, and promote captured insights to their canonical home. Admin-only. Requires `knowledge.apply.enabled: true`. The `apply` action's `sink` selects the target: `catalog` (default, #1920) writes `changes` to a platform catalog entity (`entity_urn` an mcp: catalog reference; any other form is refused), all changes of one apply in one transaction, every change type undone by rollback through the catalog's history (refused when an aspect was written again since, when the changeset created a prompt, or when it was written before the platform catalog held its entities); `knowledge_page` promotes the insight(s) to a canonical portal knowledge page, found-or-created by `page.slug`; `agent_instructions` promotes an operating rule into the deployment's own customized agent instructions, found-or-created by `instructions.section`. The destination is chosen at apply, suggested by whether the insight is entity-anchored (carries entity_urns) rather than frozen at capture: the capture-time sink-class is a non-binding hint, and any insight can be applied to either sink. Both record a changeset (page promotions target `kp:`) reversible via rollback (a page rollback soft-deletes a new page or restores a prior version, refused if the page was edited since). A promotion that wrote a page reports `portal_url`, the address that page is read at, in the payload and in the message (#1696): the response carried the page's id and slug and no address at all, so an agent handing someone a link composed one, and the one it composed opened nothing. The address is `/portal/knowledge/pages/`, composed in one place for both sinks that write a page, and omitted on a deployment that declared no public address. `GET /api/v1/portal/knowledge-pages/{id}` resolves an id then a slug, the order `pkg/knowledge` resolves an `mcp:knowledge_page:` reference in, so a slug-shaped address opens too; the portal's page view keys the panels beside the body on the id the read returned rather than on the key the address carried, since their own routes take an id. operational_rule is stored as a page like business_knowledge; active rules-engine enforcement is a separate follow-up. To cite an entity on a page, pass it in `page.references` or write it in the body as plain text or a markdown link (not in backticks or a code block, which are treated as examples and ignored). Each entry in `page.references` is existence-checked before the page is written: a missing internal (mcp:) entity rejects the apply, and a reference in any other form is refused. References in `page.references` and those carried from source insights attach with the promotion, so a rollback undoes them; a stale insight-carried reference is skipped rather than blocking. Inline body references are also filtered to those that exist, so a stale mcp: token in prose is skipped rather than blocking the page. A dropped insight-carried or inline-body reference is reported on the apply response: references_dropped lists the references that did not land (a deleted target, or an insight-carried reference not citable on a shared page such as mcp:memory:/mcp:insight:) and references_attached always carries the count of references that landed, so an agent can reconcile what it cited against what was attached (#696). Page creation is dedup-gated (#705): on a slug miss, the backend ranks existing pages by pure embedding cosine similarity against the candidate's content (embedded over the same title+body+tags composition the stored page vectors use), and a near-duplicate (cosine at or above a configurable threshold, default 0.85, active only when a real embedding provider is configured) is rejected with the candidate pages returned (id, slug, title, score) rather than created; the agent then re-applies against a candidate's slug to update it, or sets page.force_new to create a distinct page (a deliberate, auditable act separate from confirm). The identical gate runs on the portal REST create path (POST returns 409 with the candidates), so the two write surfaces cannot drift. A slug hit is always an update and is never gated. An oversized page (body bytes or markdown-heading count past a configurable threshold) returns a non-blocking split_suggestion on the apply response, nudging the agent to split it into focused, cross-linked sub-pages linked from a thin index page; the write still succeeds. The guidance steers toward many focused, cross-linked pages (progressive revelation) over one sprawling page. On a deployment with no platform catalog (no database, or semantic.provider: noop) catalog changes are refused with an error naming sink: knowledge_page. The add_prompt change type creates a platform prompt rather than a catalog write and still applies. bulk_untag removes a tag from every dataset and column carrying it, up to 500 per call, in one changeset rollback undoes; delete_tag does the same for the tag entity_urn names. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `action` | string | Yes | bulk_review, review, synthesize, apply, approve, reject, rollback, list_changesets, bulk_untag | | `sink` | string | No | apply target: catalog (default), knowledge_page, or agent_instructions | | `entity_urn` | string | Conditional | Required for review, synthesize, list_changesets, and apply with sink=catalog | | `tag_urn` | string | Conditional | Required for bulk_untag; the tag (name or mcp:tag:) to remove from every entity that carries it | | `page` | object | Conditional | {slug, title, body, summary?, tags?, references?} for apply with sink=knowledge_page. references is a list of serialized reference strings (mcp::) attached to the page independent of body text. The per-user forms, personal memory (mcp:memory:) and captured insight (mcp:insight:), are fetchable but NOT citable on a shared page (they are private to their owner, so a citation would resolve for no one else) and are rejected; promote an insight to the catalog and cite the resulting mcp: catalog reference instead (#699). A managed script (mcp:script:, #1855) IS citable: existence-checked like every internal reference, stored with a foreign key that removes the citation when the script is deleted, and resolved per reader, so the script's owner and administrators see the reference and any other reader reads the page without it (fetch answers them found=false) | | `insight_ids` | array | Conditional | Source insights; required for approve, reject. On apply, pass the promoted insights so they are marked applied and the changeset is linked to them (closes the review loop; the queue then reflects what is live). Sink-class is a non-binding hint; any insight can be applied to either sink | | `instructions` | object | Conditional | {section, body, slug?, title?, summary?, tags?, references?} for apply with sink=agent_instructions (#1607). section is the find-or-create key: a second promotion of the same section rewrites that section and leaves every other section byte-identical (the edit runs through pkg/textpatch, the same anchored-edit engine behind manage_asset patch). Recorded as a changeset with target ai:
, listed by list_changesets and reverted by rollback, which restores the previous text byte for byte and is refused when the layer was written again after the promotion. Refused when the rule names a tool this deployment does not register, naming the tool: the recognized prefixes are derived from the deployment's own registered inventory plus a floor list, so a retired api_/manage_/memory_/save_ name is caught as readily as a trino_ one. A body over 1,500 bytes is written to a knowledge page instead (slug and title defaulted from the section) and the section keeps one mcp:knowledge_page: index entry pointing at it, in the same form the platform baseline's page index uses; both halves are one changeset, so one rollback undoes both. Refused before any write when the layer would pass its 32,768-byte limit, and carries a size_notice past the 12,288-byte advisory. Needs a database-backed config store; without one the promotion is refused with sink=knowledge_page named as the alternative. Route domain knowledge to knowledge_page: this layer should carry at most a pointer to it | | `changes` | array | Conditional | Required for apply with sink=catalog | | `changeset_id` | string | Conditional | Required for rollback | | `confirm` | bool | No | Required when `require_confirmation` is true (apply and rollback) | | `review_notes` | string | No | Notes for approve/reject actions | | `itemize` | bool | No | With bulk_review, also return the pending insights themselves (full insight_text body, captured_by, sink_class, created_at, suggested_actions_count, ...; full suggested_actions omitted, fetch for it), paginated by offset/limit. The response is bounded so it stays under the output limit: page_size_capped:true flags a short insights page (continue with next_offset) and by_entity_truncated:true flags a capped by_entity | | `limit` | int | No | Page size for itemized bulk_review (default 20, max 100) | | `offset` | int | No | Page start for itemized bulk_review; pass the previous next_offset to continue | The `rollback` action restores, in one transaction, every catalog aspect a changeset wrote to the value it replaced (#1920), returns the source insights to the review queue as `pending` (`insights_returned_to_review`), and marks the changeset rolled back. It undoes every change type. It is refused, and reverts nothing, if the changeset is already rolled back, if an aspect it wrote has been written again since (the refusal names the aspect, the entity, who wrote it and when), if it created a prompt, or if it was written before the platform catalog held its entities (an apply from a release that wrote to DataHub). The `list_changesets` action lists an entity's changesets for discovering rollback targets. The apply response and each `list_changesets` entry carry a `revertible` boolean plus `unrevertible_change_types` when false. The `bulk_untag` action removes a tag (tag_urn) from every dataset and column carrying it, up to 500 per call in one transaction, recording one changeset that rollback undoes; it requires confirm. ## Memory Tools Persistent memory for agent and analyst sessions. Requires `memory.enabled: true`. Tools are opt-in per persona (`memory_*` in `tools.allow`). ### memory_manage Lifecycle operations for existing memory records; create new records with `memory_capture`. Its description, and a baseline instruction line when the caller may call it, say that a memory relied on that proved wrong or outdated is corrected with `update` or retired with `forget`, so the next session is not misled by it (#2814). Commands: `update`, `forget` (soft-delete), `list` (persona-scoped), `review_stale` (stale memories: every one for an administrator, otherwise the caller's own in their persona, and none for a caller with no email; update, forget and consolidate are the creator's by email, refused for a caller with no email; the staleness watcher checks only records carrying at least one entity URN, so `last_verified` is null on a record no catalog can be asked about rather than reading as a check nothing performed, and verification never moves `updated_at`, which stays the last content change), `review_duplicates` (list the caller's own active pairs at or above 0.75 cosine similarity, the backstop for near-duplicates the capture-time recall gate missed; requires the database-backed store with vector search), `consolidate` (supersede a duplicate by the record kept: `id` = keep, `duplicate_id` = supersede; both must belong to the caller, the record kept must be active, and the correction chain is preserved via `metadata.superseded_by`). `review_duplicates` is summary-first and byte-bounded: each pair returns ids, `score`, `status`, timestamps, owner, and a bounded `content_preview` (first ~200 characters per side), not the two full records, so its listing never overruns the MCP output budget. It is not offset-paginated: the candidate set is score-ordered and shrinks from the top as pairs are consolidated, so offset paging would skip pairs; instead it returns the current highest-similarity pairs (at most `limit`, default 20) and sets `more_pairs: true` when the byte budget or the page limit hid lower-scored pairs. The pagination is the review loop itself: consolidate the surfaced pairs and re-run to surface the rest. Read a record in full with `fetch mcp:memory:` or `memory_manage list` before consolidating. | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `command` | string | No | update, forget, list, review_stale, review_duplicates, consolidate (create with memory_capture) | | `id` | string | For update/forget/consolidate | Memory record ID (for consolidate: the record to keep) | | `duplicate_id` | string | For consolidate | The duplicate record the kept record supersedes | | `dimension` | string | No | LOCOMO: knowledge, event, entity, relationship, preference | | `category` | string | No | correction, business_context, data_quality, usage_guidance, relationship, enhancement, general | | `confidence` | string | No | high, medium, low | | `entity_urns` | array | No | Catalog references (max 10) | | `metadata` | object | No | Arbitrary metadata | | `limit` | integer | No | Page size for list (default 20, max 100); also caps review_duplicates pairs (which may hold fewer when the byte budget hits, more_pairs=true) | | `offset` | integer | No | Pagination offset for list (not used by review_duplicates) | ### Reading memory back Reading memory back moved to the universal `search` tool (see Knowledge Tools): relevance ranking, entity-keyed lookup, and catalog lineage/graph traversal are all served there. The memory toolkit retains `memory_manage` for the write path. The ranking it uses fuses embedding cosine similarity with a lexical full-text match signal (over `fts_name_words(content)`, which reads `-`, `_`, `.`, `/` and `:` as word breaks beside the text as written, #2230; the names, paths, file names, tags and titles of resources, assets, collections, prompts, knowledge pages, scripts and catalog datasets are read the same way, and a row or API/GraphQL operation not yet embedded is blended at a cosine of zero, so its lexical match outranks every non-match), blended as `0.6 * semantic + 0.4 * lexical`, which improves recall on identifier-heavy content (entity URNs, column names, error codes) over pure vector search. The vector arm uses an `hnsw` ANN index on `memory_records.embedding`; the lexical arm a GIN index on `to_tsvector('english', content)`. When no embedding provider is available it degrades to lexical-only instead of erroring, which also surfaces rows whose embedding is NULL (saved during an outage). STORED SEARCH TEXT (#2292, migration 000220): every lexical arm (resources, resource_folders, portal_assets, portal_collections, prompts, portal_knowledge_pages, scripts, catalog_datasets, memory_records, call_records) matches and ranks on a stored generated column search_fts tsvector with a GIN index, rather than on resource_fts(...) and its siblings recomputed per matching row: a GIN index on an expression answers @@ and holds no vector to rank from, so a word in 15,000 of 30,000 files with 32 KiB of content took 20.7 s against the provider's 5 s bound, and 0.1 s on the stored column. The migration rewrites each table once (about 3 minutes for 30,000 files carrying 26 KiB of content each). The session search's ranking runs over the caller's own sessions and needed no change. Memory registers as a consumer of the shared index-jobs framework (`source_kind = memory`). The synchronous embed-on-write is preserved so a just-saved memory stays immediately recallable; a periodic reconciler backfills embeddings that were missed during an embedder outage (`embedding IS NULL`) or invalidated by a provider model swap (`embedding_model` differs from the current model), and the `memory` kind appears on the admin Indexing dashboard with an indexed/expected coverage ratio. Migration `000054_memory_hybrid_search` adds the `embedding_model` and `embedding_text_hash` breadcrumb columns plus the hnsw and GIN indexes. ## Portal Tools The portal toolkit persists AI-generated assets (JSX dashboards, HTML reports, SVG charts) to S3 with PostgreSQL metadata. Requires `portal.enabled: true`. ### save_asset Save AI-generated content to the asset portal as a versioned asset. Captures the calls the asset was built from: by default every data-access call the session made since its last save or export, or exactly the calls named in `sources`. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `name` | string | Yes | - | Display name (max 255 chars) | | `content` | string | Yes | - | Artifact content | | `content_type` | string | Yes | - | MIME type the asset is stored under. One of `application/json`, `application/octet-stream`, `application/sql`, `application/x-ndjson`, `application/xml`, `application/yaml`, `image/svg+xml`, `text/css`, `text/csv`, `text/html`, `text/javascript`, `text/jsx`, `text/markdown`, `text/plain`, `text/tab-separated-values`, `text/x-python`; anything else is refused | | `description` | string | No | "" | Description (max 2000 chars) | | `tags` | array | No | [] | Tags for categorization (max 20 tags, each max 100 chars) | | `sources` | array | No | session window | The calls this asset was built from, as the `call_id` (or `mcp:call:` reference) each query and API invocation returns in its own result. Replaces the default window; only the caller's own calls resolve (max 100) | It is how every document is produced, in the words a user asks for it (#1995): a PowerPoint, deck or slides is an HTML presentation on the served slide runtime, which its page exports to PDF; a report, one pager, memo or markdown report is text/markdown or text/html; a spreadsheet is text/csv. The tool description, the platform_info baseline and the presentations knowledge page say so, and that there is no local file to build, software to install, or bucket to write; a format the platform does not produce (a .pptx) is named, and what is made instead said. Response includes asset_id, portal_url (if public_base_url configured), provenance_captured status, and calls_recorded count. Content stored at `{s3_prefix}{user_id}/{asset_id}/content.{ext}`. Save-time hints (#2508): the response also carries, when there are any, `existing_tags` (tags on the assets the caller can open that are a case or spelling variant of a given tag: equal without case, equal without spaces and punctuation, or one letter apart from four letters and two from eight; each with `asset_count` and `close_to`) and `similar_assets` (up to three assets the caller can open, other than the new one, whose stored embedding is within `assetsimilar.NearDuplicate`, cosine 0.93 in `internal/portal/assetsimilar`, of the new asset's name, description and tags; each with `asset_id`, `name`, `owner_email`, `similarity`), and the message says what to do with them. Both are read after the save is stored, within two seconds; neither refuses or holds a save, and an asset the caller cannot open is never returned or counted. The same constant decides the portal's Possible duplicates (#2509). ### manage_asset List, retrieve, update, delete, share, or relevance-search saved assets (and manage collections). Ownership is enforced for changes: users can only modify or share their own assets; list and search cover what the caller can open (#2500). Human feedback on assets is handled by the separate `manage_feedback` tool. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `action` | string | Yes | - | list, get, update, delete, search, patch, locate, get_content, outline, stats, diff, share, list_shares, revoke_share | | `asset_id` | string | Conditional | - | Required for get, update, delete, share, list_shares, and every content action | | `asset_ids` | array | No | - | Several assets in place of `asset_id` for update, delete and share (#2507; at most 500): each acted on as its own call would be, with its own permission check; the result lists `applied` and `skipped` with each `reason`, `not found or no access` for an asset the caller cannot open or that does not exist. A bulk update never changes content; a bulk share sends no email. A JSON string is refused | | `add_tags` / `remove_tags` | array | No | - | Change tags on update without replacing them, compared without case; with `asset_ids`, on every asset | | `content` | string | No | - | New content (for update — replaces S3 object) | | `name` | string | No | - | New name (for update) | | `description` | string | No | - | New description (for update) | | `tags` | array | No | - | New tags (for update), or for list and search the tags an asset must carry, every one | | `scope` | string | No | search: `all`, list: `mine` | Which assets list and search cover: `mine`, `shared` (shared by a person, the caller's address or persona, directly or through a shared collection) or `all` | | `owners` | array | No | - | For list and search: only assets owned by one of these email addresses | | `offset` | integer | No | 0 | Rows to skip in list and search; a search pages at most 1,000 results deep | | `max_versions` | integer \| null | No | - | How many versions this asset keeps (update). Omit to leave the setting alone, `null` to go back to the deployment's `portal.max_versions`, `0` to keep every version, `N` to keep the newest N. Negative is refused | | `content_type` | string | No | - | New content type (for update, only when replacing content) | | `sources` | array | No | session window | The calls behind a content edit (update and patch), as `call_id` values or `mcp:call:` references. Recorded as a new capture beside the ones earlier versions carry | | `query` | string | Conditional | - | Free-text relevance query (required for search) | | `limit` | integer | No | 50 | Max results for list (max 200); ranked search defaults to 20 (max 100) | | `recipient` | string | No | - | Who to share with (share): an email address, or a name resolved against the known-users directory. Omit for a link share | | `permission` | string | No | viewer | `viewer` or `editor` (share). A link share is always viewer | | `access_mode` | string | No | authenticated | Who a link share admits (share, no recipient): `authenticated` or `public` | | `expires_in` | string | Conditional | - | Duration bounding a public link (`24h`). Required for `access_mode: public`, refused for every other share | | `share_id` | string | Conditional | - | Share to end (required for revoke_share) | The `search` action ranks the assets the caller can open (#2500) by relevance to `query`: `scope` `all` by default (owned, on either identifier the row records, or named by an active share to the caller's id, address or resolved persona, on the asset or on a collection holding it), narrowed by `owners`, `tags` and `content_type` before ranking. Every asset whose text matches is a result, and so is one whose blended semantic score reaches `opranking.ScoreFloor` (the owner and producer searches rank the same way); the candidate set is materialized and scored by exact distance (an HNSW scan filters after its nearest-neighbor step, which drops most of a narrow reach), `total` counts every result and `offset` pages them up to 1,000 deep. It returns each match with a `score` plus a `ranking` field (`hybrid` or `lexical`). The reach condition is the per-asset access rule in SQL (`internal/portal/reachstore`), the ranked statement over any candidate set is `internal/sqlrank`, and the routes are `internal/portal/reachapi`, held to `access.CanViewAsset` by `TestReach_RealDB_ListingIsTheAccessRule`; an administrator's reach is their own. A managed-script run's search keeps its producer scope. The Portal exposes the same over HTTP: `GET /api/v1/portal/assets`, `GET /api/v1/portal/assets/search` and the collection equivalents take `scope` (default `mine`) and `owner` (repeated or comma-separated), the asset routes also `tag` and `content_type`; each page carries `permissions`, the caller's permission on each row they do not own, and `share_summaries` only for rows they own. `GET /api/v1/portal/assets/facets` lists the tags and authors on the assets the scope and other filters cover with counts (the tag facet ignores the tag filter, the author facet the owner filter), and `GET /api/v1/portal/collections/facets` the collection authors; an asset or collection the caller cannot open contributes nothing to either. The portal's Assets and Collections tabs read only these: every scope, search and filter runs on the server, with Tag and Author pickers. ### Version retention (max_versions) Every write to an asset records a version, and the version trail was the one history on the platform with no bound: `portal_asset_versions` had INSERT and SELECT and nothing else, no sweeper, and an asset delete that is a soft delete, so the `ON DELETE CASCADE` never fired. A managed script refreshing one dashboard hourly writes 24 versions a day, each with its own stored object, indefinitely. An asset keeps its newest `portal.max_versions` versions (100 unless configured; `0` keeps every version, and a negative default is refused at startup by `portalcfg.MaxVersionsError`), and may override that with its own `max_versions`: NULL inherits the deployment value, `0` keeps every version, `N` keeps the newest N. Three surfaces write the same column — the portal's asset metadata form, `manage_asset action=update`, and `PUT /api/v1/admin/assets/{id}` — and all three refuse a negative value where it was entered; the column carries a non-negative CHECK behind them. Retention is owner-or-admin on every surface. The portal's asset update route otherwise admits an editor-share recipient, and this one field is excluded from that grant: lowering the cap deletes the owner's history and its stored content at the next write, which is not a decision an edit grant carries. The portal form omits the field entirely from an update that did not move it, so an editor saving a rename never sends it. The prune runs inside the transaction `portalversions.CreateVersion` already takes the asset row lock in, which is the single door every asset write passes through (portal handlers, admin routes, the asset toolkit, managed-script output, and both export adapters), so the cap converges at the write and needs no schedule. It is skipped entirely when the asset's history has not reached the cap, which is the common case on every write. A pruned version's stored object is deleted with its row, along with the thumbnails derived beside it — no row records a thumbnail, so a prune that removed only the content would cap the table while the bucket kept growing. The object deletes happen after the commit and are best-effort: the version the caller asked for has already committed, and an object that could not be removed is logged rather than turned into a failed save. **A version's key is not private to it, and the cleanup must not assume it is.** `scriptexec` keys a managed script's output object by RUN (`internal/platform/scriptexec/export.go`), so a run that exports a document and then publishes data into the same asset writes two version rows at one key, and every version of such an asset shares one directory — which is also where its thumbnails are derived. The cleanup therefore reads the keys the surviving versions still own (`survivingObjectKeys`, inside the same transaction, after the delete) and skips every one of them. It reads the asset row's own thumbnail pointers into the same set, because since #1431 a capture outlives the version it was taken from: the image an asset is serving can sit in a directory this prune is deleting, and no surviving row derives its key. Deleting by key shape alone would take the live content object or the current thumbnail with the pruned row. The prune also never deletes the key the asset row points at. Version 1 of an asset created before it had a second version carries the flat content key the asset itself still names, so the DELETE joins `portal_assets` and excludes `v.s3_key = a.s3_key`, exactly as `resource.PruneVersions` does. Retention applies at the next write, not on a migration: an asset already carrying more history than the cap is untouched until it is written again, then trimmed. Knowledge page versions (`portal_knowledge_page_versions`) are the same shape and are not yet bounded. ### Sharing an asset from the session (share, list_shares, revoke_share) "Share this with John" is one call rather than a trip to the portal. `manage_asset action=share` takes the same three decisions the portal's share dialog takes — who, what they may do, how it ends — and builds the share row through the same constructor the REST share routes use (`portaldomain.BuildShare`), so a share created from a session is indistinguishable from one created in the UI. `recipient` accepts an email address or a person's name. A name is resolved against the known-users directory (the same directory the portal's share picker reads), matching case-insensitively against email, first name and last name; a full name is resolved by querying the most selective word and narrowing to the entries every word appears in. The lookup refuses to guess: a name that matches nobody, or more than one person, comes back as an error naming the candidates, and no share is created. An email address is taken as written, so a person who has never signed in can still be shared with; a deployment without a database has no directory, and a name there is refused with a pointer to give an address instead. A share addressed to a person is `restricted` — it opens only for the named recipient and its creator, whoever else holds the URL — is `viewer` unless `permission: editor` is asked for, never expires (it ends when it is revoked), and sends the recipient the same "shared with you" email the portal sends, subject to their own notification preferences. The response reports `notified`, so an agent claims someone was emailed only when one was actually sent. Omitting `recipient` mints a link. `access_mode: authenticated` (the default) opens for any signed-in platform user and lasts until revoked; `access_mode: public` opens for anyone holding the URL without signing in and therefore requires `expires_in`, which is refused for every other shape (#1279). A link is always `viewer`: it admits an audience the creator never enumerated, so it can never carry write access. `list_shares` returns the shares that currently grant access to an asset — a revoked or expired share is not one of them, decided by the same liveness rule the public viewer gate applies — each with its recipient, permission, access mode, view URL, expiry and access count. `revoke_share` ends one by `share_id`, and its token stops opening the asset immediately. All three are owner authority (an editor share never carries the right to hand access on), an unauthenticated caller is refused outright rather than matched against the shared "anonymous" owner sentinel, and an admin is unrestricted as everywhere else. ### Editing content in place (patch, locate, get_content, outline, stats, diff) Regenerating a whole document to change one sentence costs output tokens proportional to the size of the document rather than the size of the change, and every regeneration is a chance to silently drop an unrelated paragraph. `manage_asset` and `manage_prompt` therefore share one content-editing grammar, implemented once in `pkg/textpatch` (pure text in, text out, with no knowledge of assets, prompts, S3, or MCP) and rendered to the protocol by `pkg/textpatch/patchmcp`. Both tools splice the identical JSON Schema fragment, so the grammar an agent reads on one tool is literally the grammar it reads on the other. Verbs: `outline` (heading tree with levels, line numbers, per-section byte size, plus `landmarks` on an HTML/JSX/SVG asset), `get_content` (whole body, one `section` or `selector`-addressed element, or a `line_start`/`line_end` range), `stats` (size, line count, current version, content type, sha256 body hash, no body), `locate` (literal `find` or regex `pattern` matches with count, line, byte offset, enclosing section, and a copyable context window), `patch` (an ordered list of anchored edits), and `diff` (two stored versions, or a pending prompt draft against the approved snapshot). The intended loop for a large document is outline or locate to decide where, then patch that place; the body crosses the wire in neither direction. Patch operations, each an entry in the `edits` array: `replace` (the default; literal `find` swapped for `replace`, an empty `replace` deletes), `insert_before` / `insert_after` (`text` positioned relative to the anchor, anchor kept), `replace_section` (a region, either a heading through the next heading of the same or higher level or a `selector`-addressed element's balanced subtree, replaced by `text`), `replace_content` (a `selector`-addressed element's interior replaced by `text`, its own tags kept byte for byte — the data-island operation; selector-only, and a void or self-closing element is refused because it has no interior), `move_section` (relocate a region `before` or `after` another heading, or with `position` set to `start` or `end`), and `append` / `prepend` (no anchor). `section` and `selector` also scope the anchor search on the anchored operations, which is how a repeated phrase becomes unambiguous without quoting a long anchor; a `Report > Methodology` path disambiguates repeated headings. The payload key is REQUIRED and is the only one: an edit writes from `replace` on `op: replace` and from `text` on every other writing op, and an edit that omits the key its op reads is refused with `PATCH_BAD_EDIT` naming its index, as is one carrying a key the grammar does not declare, which is named along with the accepted set. Deleting is therefore always asked for -- `"replace": ""` written out. Omission used to be read as an empty replacement, so an edit whose text rode on a misspelled key (`text` on a replace, `replacement`, `with`) had its payload ignored, replaced the anchor with NOTHING, saved a new version and reported success; the damage was a deletion nobody asked for in a source that usually still parsed, so `validate` passed too and a scheduled run was the first thing to notice (#1804). Every tool that adopts the grammar splices the same schema fragment from `pkg/textpatch`, so its edit items declare exactly these keys and are closed to the rest and an unknown key is refused by the argument validator before the handler runs; `manage_script` published a hand-written paraphrase whose edit items were a bare `{"type": "object"}`, which is how the keys inside an edit came to be validated nowhere, and `TestPatchGrammarIsNeverHandCopied` now fails any package outside `pkg/textpatch` that declares the property itself. Naming a region is syntax-aware, derived from the content type through `pkg/contenttype` (never guessed from the bytes). Markdown (`text/markdown`, `text/plain`) names regions by ATX heading. HTML, JSX, SVG and XML (`text/html`, `text/jsx`, `image/svg+xml`, `application/xml`) name them by `

`..`

` heading (resolved as markdown resolves `#`) or by CSS `selector`, whose region is the addressed element's balanced subtree, running from its start tag through its matching end tag, so a structural edit can never cut a tag in half. The element tree is built from a tokenizer with byte offsets recorded per node; markup that cannot be resolved into a balanced tree is refused with `PATCH_UNRESOLVED_MARKUP` rather than guessed at. Supported selector forms: type (`section`, `Card`), `#id`, `.class` (also matches a JSX `className`), `[attr]`, `[attr=value]`, joined by descendant (space) or child (`>`) combinators; HTML/SVG tags match case-insensitively while a JSX component name is case-sensitive. `selector` on a markdown document, or `section`/`selector` on a structureless one (JSON, CSV, SQL), is refused with a message naming the right alternative (`PATCH_NO_STRUCTURE` for the structureless case). On a headingless dashboard, `outline` returns `landmarks`: every element carrying an `id` or `data-*` marker, each with tag, a copyable selector, line, and byte size, so an agent finds where to patch without reading the body. Matching rules: an anchor or `selector` must resolve to exactly one span. Zero and more than one are both errors that report the count; `occurrence` (`first`, `last`, `all` for text anchors, or a 1-based integer) is the explicit opt-in, and an `occurrence: "all"` edit reports how many spans it changed. A region is a single element, so a `selector` uses `first`/`last`/index, not `all`. Matching is exact first, with exactly one retry that normalizes CRLF to LF and ignores trailing whitespace per line (reported as `normalized: true`); there is no fuzzy, similarity, or semantic matching, because a plausible-but-wrong edit applied silently is worse than a rejection the agent can correct. `pattern` is the regex alternative on both `locate` and `patch`, with `$1`-style capture expansion in `replace`; Go's RE2 gives linear match time so a pathological pattern cannot hang the server, and a pattern-length cap, a match cap, and the all-or-nothing failure rule still apply. Edits apply in order against the evolving body, so a later edit can anchor on text an earlier edit introduced. Atomicity: every edit resolves against an in-memory copy and the first failure aborts the whole call, writing nothing; the error names the failing edit by index. `base_version` is optional and checked when supplied, refusing a stale patch with the current version in the error. The response never echoes the new body: it returns the new version, the new size and line count, a per-edit report (operation, normalized flag, spans touched, landing line), and a unified diff of the changed hunks only. Unified diff is deliberately an output format and never an input format: as input it would make correctness depend on line numbers and context lines the model must reproduce exactly. `dry_run: true` returns exactly that report without writing. Line numbers are read output only and are never accepted as an edit anchor. Integration: an asset patch goes through the same version write path as a full content update, so it produces an ordinary new version and `revert` still works, and the version's change summary is the caller's `change_summary` or a generated one ("3 edits via patch") instead of a fixed constant. A prompt patch goes through `prompt.ApplyEdit`, so patching an approved global or persona prompt produces a pending draft version and the approved snapshot keeps being served. Ownership, persona authorization, and audit are untouched; the read-only asset verbs additionally accept a share grant (owner, direct share, or collection share), while `patch` remains owner-only like `update`. Every verb is text-only: a PDF, image, or other binary target is refused with `PATCH_NOT_TEXT` via `contenttype.IsTextual`, the platform's single detection seam. Error codes, all carrying the standard `{code, category, message, hint}` envelope: `PATCH_NO_MATCH`, `PATCH_AMBIGUOUS`, `PATCH_STALE_BASE`, `PATCH_NOT_TEXT`, `PATCH_TOO_LARGE`, `PATCH_SECTION_NOT_FOUND`, `PATCH_BAD_PATTERN`, `PATCH_BAD_EDIT`, `PATCH_BAD_SELECTOR` (the selector does not parse), `PATCH_NO_STRUCTURE` (the content type has no addressable structure), and `PATCH_UNRESOLVED_MARKUP` (the markup could not be resolved into a reliable element tree). ### manage_resource (create, replace_content, get, list, delete, extract) Manages a file in the managed resource library. A managed resource is the only kind of file an asset can reference, and creating and revising one was reachable only from the portal UI and the REST surface behind it, both of which need a person with a browser. That left the data half of a referencing asset unrefreshable by the platform: an agent could rewrite a report on a schedule and could not rewrite the CSV the report reads. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `action` | string | Yes | - | `create`, `replace_content`, `get`, `list`, `delete` or `extract` | | `reference` | string | Conditional | - | `mcp:resource:`, the reference a search hit, a fetch document, or a create carries. Required for `replace_content`, and for `extract`, where it names the archive; for `get` and `delete` it is the alternative to naming the address | | `if_exists` | string | No | `fail` | What a `create`, an `extract` or a PUT to an `upload_link` does when an address already holds a file: `fail` refuses it, `replace` records the next version of what is there. For `upload_link` it is chosen when the link is issued | | `members` | string | No | every file | For `extract`: a glob. A pattern with no slash (`*.csv`) matches a member's file name wherever it is filed; one with a slash matches the member's whole cleaned path | | `force` | boolean | No | false | Delete a file even though something still points at it | | `limit`, `offset` | integer | No | 100, 0 | Page a `list`; 100 is also the largest page | | `content` | string | Conditional | - | The file as text | | `content_base64` | string | Conditional | - | The file as base64-encoded bytes, for a binary file. Exactly one of the two | | `content_type` | string | Conditional | - | Media type the bytes are (required for `create`). Not detected: SVG, HTML, JSX and Markdown all read as plain text to a byte sniffer. `replace_content` keeps the type the resource already carries when it is omitted; a file stored under a generic type is re-detected from its bytes | | `filename` | string | Conditional | - | Name of the file (required for `create`), normalized to lowercase; ignored by `replace_content` | | `display_name`, `category`, `description` | string | Conditional | - | Required for `create` | | `tags` | array | No | [] | Tags for filtering in the library | | `scope`, `scope_id` | string | No | the caller's own user scope | `user`, `persona`, or `global` | | `change_summary` | string | No | generated | Why the content changed, shown in the version history beside the revision | Content arrives in one of two fields rather than one field with an encoding flag, so a caller cannot declare an encoding the bytes are not in. Both are capped at `portal.max_content_size` (10 MB by default), the same cap `save_asset` applies: one number governs everything an agent writes through a tool call, and a file larger than that goes through the portal's upload form. `create` reports the resource's `mcp://` URI (which is what `save_asset`'s `references` argument takes) and its `mcp:resource:` reference (which is what every other tool takes). It reports no `version`: version 1 is recorded only where the deployment keeps a version trail, and a number the history may not hold is worse than none. `replace_content` reports the `version` the content was recorded as and, when a table is registered over the file, `tables`: one sentence per table saying it followed onto the new version or is pinned and now behind it, appended to the message as well (#1536); a scheduled script that replaces a followed resource needs no second call, and the sentences reach its run log. A replacement goes through `resource.ReviseContent`, the same call the portal's replace-content route makes, so the resource keeps its id, its canonical `mcp://` URI and its filename — which is what keeps every `mcp:resource:` citation, every prompt attachment and every asset reference pointing at it resolving across the write, with no asset re-saved — the new bytes land on a fresh per-revision key so the prior version stays independently readable and restorable, the revision is recorded with its author and change summary, and the resource is re-registered so `resources/list_changed` reaches clients that would otherwise keep serving the bytes it moved off. Creating is scope authority, checked with the same `resource.CanWriteScope` the REST surface applies: the caller's own user scope (the default, and the one place every signed-in caller may write), a persona they administer, or the global scope as a platform administrator. The refusal names the SCOPE and not the file, because where it was filed is what the caller has to change. Replacing is `resource.CanModifyResource` — the uploader, or an administrator of the scope — and a resource the caller cannot see is answered as absent rather than as forbidden, so a caller who should not learn it exists cannot tell the two apart. An unauthenticated session is refused outright: a resource records who uploaded it and decides its scope on that. A deployment with no managed-resource layer (no database, or no S3 connection for resource storage) refuses the call with that reason and says nothing was saved, rather than reporting a write that did not happen; a store with no version trail still creates and refuses only `replace_content`, naming the missing history. The seam is `internal/platform/resourcewrite`, built by the platform because the re-registration callback is the platform's, and bound onto the toolkit through `portalstore.BindResourceWriter`; the create path itself is `resource.CreateResource`, exported for the same reason `ReviseContent` was — creating a managed resource is not the browser's alone — and the REST upload route goes through it too, so both surfaces write one record shape and one version-1 row. The lifecycle around those two writes is #1665. `get` resolves an address (`scope` + `path` + `filename`) or a reference to the record a `fetch` returns without the bytes, `list` reports a folder and everything beneath it, and `delete` removes a file and its version trail. Without them a caller had to remember the id of everything it wrote: `create` refuses an occupied address, `replace_content` needs a reference, and `search` is relevance-ranked and capped, so a file it does not return is not a file that is not there -- a script whose state was cleared could never reach its own rolling file again, and a file a draft run or a test made was permanent from the agent's side. `Writer.Locate` is the one address resolution the lander already performed, reached by both: it validates through the managed-resource layer's own `ValidateScope`/`ValidatePath`/`SanitizeFilename`, composes the canonical URI with `BuildURI`, follows the alias trail a move left behind, and answers "nothing is filed there" as a value rather than an error, which is what lets one lookup serve a `create` deciding whether to revise and a `get` reporting an empty address; a read that FAILED stays an error, because creating on it would file a second file at an occupied address. The reference branch answers the same way (#1690): `Writer.Get` folds absent and forbidden into `resource.ErrNoSuchResource` -- the sentinel lives in the domain package so the tool surface can read it without importing the writer -- and `handleGetResource` renders that one error as `found: false` beside the `reference` it looked up, the shape `fetch` already answers a dangling reference in, while any other error stays a tool error. Before this, a script holding a reference in its state read a deleted file as a failed call. `create` with `if_exists=replace` routes into the same `replaceResourceContent` an explicit `replace_content` reaches, so the two cannot disagree about what a revision does to the file's type, its history or the tables over it, and `toolkit.ResourceAddress` sits beside `ResourceDestination` in `pkg/toolkit` so an export's destination and a tool's lookup are one definition of where a file is. A delete is `resource.DeleteResource`, extracted from the REST route's handler so both doors remove the blobs (head first, then every superseded version's, best-effort past the head) and then the record, and `Writer.Delete` adds the `Unregistered` callback that takes the file out of the MCP resource list. Authority is `CanModifyResource`, the same rule a replacement meets: deleting is not stronger than overwriting, since a replacement already leaves nothing of the previous content beyond the trail the delete takes. What still points at the file is gathered BEFORE the delete by `internal/platform/resourceholds`, two reverse lookups behind one call -- `assetrefs.Store.ListByTarget` for assets whose content references it and `prompt.AttachmentStore.ListByResource` for prompts that attach it -- plus `TableRegistrar.Tables` for query-engine tables. A knowledge page is deliberately NOT a third: `ParseCitableRef` refuses an `mcp:resource:` citation on a shared page, because a resource is visibility-scoped and the citation would be broken for every reader outside that scope, and every writer of `knowledge_page_entity_refs` (the manual picker, `ScanBodyRefs`, and promotion through `parsePageReferences`/`promotedRefsFromURNs`) goes through it, so a page cannot hold a resource row and a lookup for one would be a count that is always zero. Neither of the two IS a foreign key: migration 000088 states the rule for attachments, and deleting the file must leave the row so the prompt reports the material as missing rather than erasing the evidence that the procedure is now incomplete. Nothing in the database therefore stops the delete, which is exactly why the tool does, and why a failed lookup refuses rather than counting zero -- an empty count reads as "nothing depends on this file", the one wrong answer somebody about to delete must not act on. The counts are counts and not names because each of those records carries an audience of its own (an asset has shares, a prompt has a scope) and the caller is not necessarily in it; the portal's used-by panel resolves those audiences and names what its reader may open. A table IS named, since `manage_table` already names it to the same caller. `force=true` deletes anyway, records what it broke, and calls `DropResourceTables`, the resource-kind sibling of `DropAssetTables` -- the REST route reaches the same `UnregisterAllForSource` through the store's delete hook, and a tool call does not cross that route. `resourceholds` returns its own `Holds` type and the composition root adapts it in `portalstore.holdReader`, so the checker depends on no toolkit and the toolkit depends on no reverse lookup. `extract` (#1879) writes the members of a stored archive out as managed resources: the only way a delivery like a monthly `.zip` holding one large CSV becomes a file a table can be registered over, since `manage_table register` reads CSV, JSON lines and Parquet and Starlark has no decompression and could not hold a multi-hundred-MB member anyway. `internal/unarchive` opens the archive (format by magic bytes: `PK` for zip; `1f 8b` for gzip, read as a tar when the decompressed head carries the `ustar` magic at offset 257) and answers which members are selected, whether each name is safe, and whether the archive is inside `resources.managed.extract`; `resourcewrite.Extractor` plans every selected member's address -- the member's directories become folders beneath `path` through `resource.FolderSegment`, the Go twin of the bulk uploader's `folderSegment` (`Q3 2026` files as `q3-2026`, and `2026` keeps its name since #1886), or with `filename` the one selected member lands at `/` -- and checks each through `Lander.plan` (scope authority, the authority to replace what is there, `if_exists`) before the first write, then streams each member through `Lander.landPlanned`, so a member is created, or recorded as the next version with the tables over it followed, exactly as an export landing at that address would be. Refused before anything is written: a name that is absolute, carries a drive letter or has a `..` segment (anywhere in the archive, selected or not; a backslash is read as a separator), an encrypted member (flag bit 0, or WinZip AES method 99), a zip method other than stored or deflate, a selection matching nothing (the refusal lists what the archive holds), `filename` with several members selected, two members at one address, an occupied address without `if_exists=replace`, a folder name with no usable characters, a folder chain past 8 levels, a denied extension, and any limit. Links and devices are skipped and listed as `skipped`. A failure while a member streams (CRC mismatch, truncated stream, a gzip past a limit) abandons that member's multipart upload and returns the members written before it alongside the error, which the tool names with each reference and version. The result is `{archive, format, members: [{member, resource_id, reference, uri, path, filename, content_type, size_bytes, version, created, table_changes}], skipped, message}`. The toolkit holds a `ResourceExtractor` interface over its own request and result types; `portalstore.BindResourceWrites` assembles the writer, the export lander and the extractor over the managed-resource layer in one place (moved out of `pkg/platform`), builds the extractor only when the blob client implements `resourcewrite.RangeReader`, and binds it through an adapter that carries the fields across, so the toolkit depends on no writer. A tar's global PAX header, which `git archive` writes first, is metadata and is neither extracted nor listed as skipped. `extract` is classified as a write in `internal/toolwrite`, so a script draft reaches it only with `allow_writes`. A managed script reaches the tool through `platform.call` like any other, under its version author's permissions, which is what makes a scheduled refresh of a referenced file possible with nobody in the loop. A run authenticates as `script:`, a principal that owns no file and is in nobody's library, so the resource rules read the address it acts for the same way the asset toolkit's ownership check does (#1419). `resource.Claims.OnBehalfOf`, built by `BuildClaimsFor` and empty for every human caller, is read by four rules: `VisibleScopes` adds the library of the person acted for, `CanWriteScope` admits that person's user scope, `CanAccessResource` admits a file they uploaded INTO THEIR OWN LIBRARY, and `CanModifyResource` matches the address the resource records as its uploader wherever the file now sits. Those two are deliberately different predicates (#1576): a move rewrites a resource's library, folder and `mcp://` address and never its uploader columns, so the person who uploaded a file keeps modify authority over the row after somebody files it elsewhere, and a run acting for them has to keep it with them -- holding the run to the library instead meant a person who moved a CSV into a persona they merely BELONG to (which `canMoveToLibrary` deliberately permits) silently broke the schedule refreshing it, with nothing warning at the move and whether it broke at all turning on whether the author happened to be a platform administrator. The modify arm is ONE rule for the person and for what acts for them (`uploadedByCaller`) rather than a person's rule beside a stand-in written for the run: a stand-in diverges, and this one would have -- a resource a RUN filed records the principal as its subject and the author as its address, so the person's own subject does not match it, and once such a file leaves their library every OTHER script that person writes could have rewritten what the person cannot touch. That rule reads the recorded ADDRESS for an unattended caller and the recorded SUBJECT only for a caller acting as themselves, because `script:` is unique only within an owner (`idx_scripts_name_owner`, migration 000119) and two people's same-named scripts would otherwise share one identity. Visibility is unchanged: `CanAccessResource` keeps the scope-bound arm, and the libraries a move can reach are readable on their own terms (a persona by its members, the global one by everyone) -- though "may change" is a wider set than "may see", so a surface authorizing on `CanModifyResource` alone (registering a resource as a Trino table) grants the run that wider set exactly as it grants the person. The decay the uploader arm is known for now falls on the person and their script identically rather than on one of them: an administrator who uploaded into somebody else's scope and later lost the role keeps modify authority over that row, and so does their script -- one grant, one holder. Without it a run could neither read nor replace a file its author uploaded through the portal — which files a person's own resources under their SUBJECT, an identifier a run does not have — and a create with no scope named would land under `{user, script:}`: visible to the run and absent from the author's Resources page, which is where the person who scheduled it looks. The create default is the address the run acts for, not the principal. A scope id is compared EXACTLY, because VisibleScopes emits it verbatim and the store's listing predicate is built from that -- folding case in the write check alone would make a resource modifiable and deletable by somebody it never appears in a listing for; the uploader address IS folded, since it is read off the row rather than listed by and so has no predicate to disagree with. An author whose address changes in the identity provider loses their scripts' reach over resources uploaded under the old one (the uploader address is frozen on the row, the run carries the current one), and the run is answered as for a deleted file, because telling the two apart would disclose that a file the caller may not see exists. Both sides of every identity comparison must be non-empty, so an absent address never matches an absent owner or an absent scope id; the same tightening now applies to the plain subject arm of `CanWriteScope` and `CanModifyResource`, which previously let an empty subject match an empty scope id (unreachable through the handlers, since `ValidateScope` refuses an empty user scope id, but not a rule worth leaving written the other way beside its new sibling). --- # Personas Personas control which tools a user can access. Map OIDC roles to personas for role-based access control. ## Configuration ```yaml personas: analyst: display_name: "Data Analyst" roles: ["analyst", "data_engineer"] tools: allow: ["*"] deny: ["*_delete_*"] admin: display_name: "Administrator" roles: ["admin"] tools: allow: ["*"] ``` A caller whose roles match no persona is unmapped and reaches nothing: MCP tool calls resolve to the built-in deny-all persona and are refused, the portal answers 403 with a branded page naming the refused account, and the managed-resources API refuses the request. There is no fallback persona - granting access means granting a role one of the personas lists. A deployment with auth.allow_anonymous, or with no authenticators configured, gives its callers the role "anonymous", so open access is something a persona opts into by listing that role. personas.default_persona was removed and a config that still sets it is refused at startup. ## Tool Filtering Patterns support wildcards: - `*` matches any sequence of characters - `trino_*` matches all Trino tools - `*_delete_*` matches any delete tool Evaluation order: deny patterns are checked first, then allow patterns. Prefer `allow: ["*"]` with a targeted `deny`. An enumerated allow-list has to name every tool the persona will ever hold, so it silently loses each tool a later upgrade adds; the persona keeps working with less of the platform than the operator thinks it has. ## Hiding Automations A persona's `portal` block (file config, the `persona_definitions.portal` column from migration 000212, the persona editor's Portal tab) sets what its people may do in the portal, one setting per area (#2225): `assets` (`shared` reads what is shared and creates nothing, `own` creates too), `resources` (`none`; `shared` reads the own folder, persona folder and Global and uploads nothing; `own` uploads to the own folder and opens no persona folder; `persona` as before), `knowledge` and `catalog` (`none`, `read`, `write`), `apis` (`none`, `browse`), and the switches `feedback`, `prompts`, `automations`, `search`, `memory`, `download`. The navigation hides what a persona lacks and the persona gate (`internal/portal/portalperm`) answers every route of the area with 403 and the area named; resources levels are applied to the resources API's claims. An unset area resolves to the persona's pre-#2225 reach: assets own, resources persona, apis browse, every switch on, knowledge write with apply_knowledge else read, catalog write with apply_knowledge and fetch, read with fetch, none without. Knowledge-page writes and the portal catalog read and write follow the levels rather than the tools. `GET /api/v1/portal/me` reports `portal` resolved; administrators have every area. Migration 000212 folds `hide_automations` into `portal.automations` and drops the column; a file persona's `hide_automations: true` still reads as `automations: false`. The MCP tools stay governed by `tools:`. `allow_sharing: false` on a persona (file config, `persona_definitions.allow_sharing` from migration 000211, default true, the "Sharing" checkbox on the persona editor's Portal tab) withholds sharing (#2241): no Share action on assets, collections and prompts; 403 "sharing is not available to your persona" from `POST .../shares`, `POST /api/v1/portal/assets/{id}/channel-shares` and `GET /api/v1/portal/channels`; and the same refusal from `manage_asset action=share`, an export's `create_public_link`, and `notify action=publish` with access signed_in or public. `GET /api/v1/portal/me` reports `sharing`; administrators always can. A persona marked `external: true` (file config, the `persona_definitions.external` column from migration 000213, the "External people" account type in the persona editor's Identity section) is for people outside the organization (#2290): an identity-provider account given a role that resolves to it, typically one external persona per client organization. It is denied every MCP tool (search and fetch included), opens what is shared with its people or with the persona as a viewer only, reads its people's own folders and no persona folder or Global (resourcelevel drops the persona claims), has knowledge, catalog, APIs, scratch tables and external_files at `none` and search, prompts, automations and memory off whatever its `portal` block says (feedback, download, history and uploads stay as set), cannot share, has no API keys, people directory or mentions, reaches no admin route and no authenticated endpoint, and under /api/v1/portal/ reaches only me, assets, collections, shared-with-me, shared-collections, threads, worklist, feedback, notification-prefs and notifications (portalperm.externalAllowed; every other segment, a later one included, answers 403). A person is external when the roles the directory recorded at their last sign-in resolve to an external persona (personashare.External, persona.Registry.IsExternalRoles), which is what mentions, thread notifications and the guest-link path ask. `GET /api/v1/portal/users` marks each person `external`, `GET /api/v1/portal/share-personas` each persona, and `GET /api/v1/admin/users` reports each person's `persona` and `external`; the share dialog, Admin > Users and the audit drawer show an External badge, and the persona access summary lists the persona's people (`references.people`). The emailed-link accounts of #2092 are removed (migration 000219 drops external_accounts and external_signin_links). The administrator persona is never external: the admin API refuses saving it so (400), a file persona marked so is refused at startup, and one written to the store directly administers nothing, because every surface asks the registry's AdminRule/IsAdminName rather than comparing a persona name. A persona's `portal.history` (default false, the editor's "Earlier versions") decides whether its people read the earlier versions of an asset shared with them as viewer; off, `GET /api/v1/portal/assets/{id}/versions`, an earlier version's content and content-url, and `manage_asset` list_versions and diff answer a viewer 403. The owner, an editor (by a direct share or a collection's) and administrators always read them; a person of an external persona is held to viewer, so the setting alone decides for them (#2226, #2290). `portal.external_files` (`none` default, `view`, `manage`; administrators manage, external personas none) reaches every external person's own folder: `GET /api/v1/resources/external-folders` lists them (scope_id, email, name, persona, persona_display_name, manage), the Resources page shows them under "External files" named "Name (Persona)", view opens their files and manage renames, versions, moves, deletes, shares and uploads into them (resource.Claims.ExternalFolder/ManageExternalFiles). `portal.uploads` is a switch (default false): an external persona's people upload to their own folder and nothing is shared on arrival; migration 000219 reads a stored #2258 recipient list as true, and a file config still naming share_personas/share_emails is read the same way, logged as deprecated_key naming the persona (#2744). The persona editor offers it as the third choice of an external persona's Resources row (None, Read their own folder, Read and upload to their own folder); a person whose own folder takes no upload sees "Uploads are not turned on for you. An administrator turns them on in your persona." where Upload would be, and POST /api/v1/resources answers 403 naming the persona and the setting. A share can be addressed to a persona (#2089, `portal_shares.shared_with_persona` from migration 000215): `shared_with_persona` in place of `shared_with_email` on `POST .../shares` (both is refused). Everyone who resolves to the persona when they open the item opens it, so membership changes take effect with no change to the share; anyone who can share may name any persona (#2290; `GET /api/v1/portal/share-personas` lists them, each marked external when it is), every current member is notified by their own preferences, and shared-with-me reports `via_persona`. SHARE DIALOG (#2291): one dialog answers who can open an item. The Share view: an Add people or groups box (a combobox listing matching groups, each persona with member_count from GET /api/v1/portal/share-personas, counted as its members are notified, and people from the directory; a full address not in the directory is offered as a Guest), People with access (the owner, then each grant oldest first, each with a Can view / Can edit / Remove access menu applied at once through PATCH /api/v1/portal/shares/{id} {permission}, or PATCH /api/v1/resources/{id}/shares/{shareID} for a file; Undo for 5 s re-creates a removed grant with notify false), General access (assets and collections: Only people added, Anyone who can sign in = authenticated, Anyone with the link = public), Posted to channels, and a footer of Copy link, Post to a channel, Done. An item has ONE general link: PUT /api/v1/portal/{assets|collections}/{id}/link {access_mode, expires_in, notice_text, hide_expiration} creates it or changes the newest unaddressed, unposted link in place keeping its token (internal/portal/sharelink, portaldomain.GeneralLink/ApplyLinkSpec), DELETE on the same path revokes it; older general links are listed as Other link with Remove. An address the directory does not hold (a guest) can only view: an editor grant to one is refused at creation and on PATCH (portaldomain.GuestCheck, portal.Deps.HasAccount). Adding people: a chip per recipient, one permission for all, Send an email (notify) and a 500-character message; Share creates one share per chip and a refused chip stays with the server's reason. A feedback thread is `internal` (the default for an internal author) or `shared` (#2227, `threads.visibility` from migration 000214). An external person never sees an internal thread: not in lists, counts, sign-off or by id (404), and mentions and notifications of an internal thread skip external addresses. A thread an external person opens is always shared; the item's owner, an editor or an administrator changes it with `PATCH /api/v1/portal/threads/{id}` `{"visibility"}`, recorded on the timeline, and an external person is refused (403). A signed-in person who cannot open an asset, collection or prompt can ask its owner for access (#2090, table `access_requests` from migration 000216): `GET /api/v1/portal/{assets|collections|prompts}/{id}/access-request` (has_access, owner_email, the item's name only when the `access_requests` setting reveal_names is on, their pending request), `POST .../{id}/access-requests` with an optional `{"message"}` (201; a second while one waits answers 200 with it and notifies nobody; 409 for a person who already opens it; 429 after three in a day), `GET /api/v1/portal/access-requests` (the owner's waiting requests, every one for an administrator, or one item's with target_type and target_id), `POST /api/v1/portal/access-requests/{id}/approve` with `{"permission": "viewer"|"editor"}` (creates a person share with origin access_request) and `/decline`. The owner is notified by their preferences and the requester of either answer by email; a request expires after `expire_days` (default 14), set at `/api/v1/admin/settings/access-requests` (Admin > Settings > Access requests). The portal shows the request page in place of an item's not-found state, and the waiting requests at the top of the Inbox and in the item's share dialog. Persona resolution is one rule on every surface (#2228): the MCP tools, the portal, the admin API and managed resources resolve a role in `personas.role_mapping.oidc_to_persona` first, then the highest-priority matching persona, with a tie going to the name that sorts first. An administrator is a user whose roles resolve to `admin.persona`; a user whose roles also match a higher-priority persona is not an administrator anywhere, and a role literally named `admin` or `platform-admin` grants nothing on its own. ## Some tools are a unit A few tools produce work that only another tool can consume, so granting one without the other is a configuration error rather than a tightening: `search` needs `fetch` (search returns navigational pointers carrying a `reference` and fetch is the only tool that dereferences one, so without it the persona discovers that an answer exists and can never read it, and cannot follow a knowledge page's outbound references); `memory_capture` needs `search` (search is the retrieval front door for captured memory, so without it the persona writes knowledge nobody, including itself, can retrieve); `apply_knowledge` needs `search` (the review workflow's documented first step is discovery). The platform evaluates these pairs against the tools it actually registered — at startup for every persona, and again on each persona write through the admin API — and logs a warning naming the persona, the granted tool, the missing tool, why the pair matters, and the fix (`persona.CheckCoherence`, `pkg/persona/coherence.go`). It is advisory, never a gate: a restricted persona may be intended, and a deployment that never registered the missing tool is never warned about it. The warning exists because the loss is otherwise silent — the instruction baseline names a tool only when the caller can reach it, so a persona missing `fetch` is simply never told that reading a result in full is possible, and the only other symptom is an `unauthorized` audit row if an agent guesses the tool name unprompted. Relatedly, the search-first gate refuses `trino_query` and `trino_execute` until `search` has been called in the session, so a persona granted query tools but not `search` cannot open that gate and is refused permanently. ## Connection Access Control Personas can restrict which toolkit connections a user may access. A tool call must pass both the tool pattern check and the connection check, and the discovery surfaces show only the connections a persona is granted. The connection is the platform's authorization boundary rather than the end user, and connection rules are the load-bearing half of a persona. Several connections may front the same downstream system under different credentials at different permission levels (a read-only Trino account and a write-capable one on the same cluster are two connections), so the permission level a caller gets is the permission level of the credential bound to the connection they were granted. Tighten access by adding a connection with a narrower downstream account, not by adding a role that lands on the same connection. The platform does not impersonate the caller downstream, so warehouse row policies and column masks that key off the end user do not follow a caller through, and per-user attribution comes from the audit trail (user_id, user_email, persona, connection on every call). Full rationale, trade-offs, and boundaries: the Authorization Model section above. ```yaml personas: analyst: connections: allow: ["prod-*"] deny: ["prod-admin-*"] ``` Connections are deny-by-default: if the `connections` block is omitted or `allow` is empty, the persona reaches no connection at all. Connection patterns use the same wildcard syntax as tool patterns. A pattern matches the name a call binds the connection by, which `list_connections` reports as `connection`: the `instances:` key of the toolkit instance, or the `connection_name` an S3 instance sets in its place. A `connection_name` on a Trino instance has no effect (the server warns about it at startup): Trino routes by the `instances:` key, so that key is its connection's name everywhere. Before #1396 an unqualified Trino call bound the `connection_name` instead, so a persona that lists one must be changed to list the `instances:` key. Discovery applies the same rules through the same predicate, so what a caller can find and what a caller can call never disagree. `search` omits catalog datasets, connections, and API endpoints belonging to connections the persona is not granted; `fetch` returns `found: false` for such a reference, so a citation cannot read around what search omitted; `list_connections` enumerates only the granted connections; the portal search shares the router and behaves identically. A catalog dataset belongs to the connection its reference names and is shown only when the persona reaches that connection. Nothing is dropped silently: `search` coverage carries a per-source `withheld` count plus a `withheld_notice` naming the persona and the remedy, and `list_connections` returns `withheld` and `notice`. This is a metadata boundary — it hides names, descriptions, and inventory; the data behind them was already gated at the tool call. ## API Endpoint Rules A persona that reaches an `api` connection can call every operation it exposes. `api_routes` narrows that to specific methods and paths, which is how one API is split into read-only and read-write access without two connections and two credentials. ```yaml personas: analyst: connections: allow: ["crm-*"] api_routes: - connection: "crm-*" methods: ["GET", "HEAD"] - connection: "crm-*" methods: ["DELETE"] paths: ["/v1/orders/{id}"] action: deny ``` `connection` is a glob and is required. `methods` and `paths` are glob lists where empty means any. `action` is `allow` (the default) or `deny`. Evaluation against one `(connection, method, path)`: entries whose connection glob does not match are skipped; among the rest a matching deny refuses the call; otherwise a matching allow is required; and if no entry names the connection at all the check is a no-op, so adding a rule for one connection does not close the others and a persona written before `api_routes` existed behaves as it did. A path glob is matched against the path the call reaches (`/v1/orders/42`) and the catalog path the operation declares (`/v1/orders/{id}`). Naming the declared path is the precise way to govern one operation; a glob such as `/v1/orders/*` is a different rule that also covers the sibling operations at that depth. Wildcards do not cross a `/` and there is no recursive form — `**` is two stars and stops at a separator like one does. Rules are authored in the config file or in the portal at Settings > Personas > Permissions > API endpoints, which lists each api-kind connection and the operations its catalog declares with the persona's decision on each one and the rule that produced it. Selecting an operation writes that operation's own method and declared path, so a portal-written rule and a file-written rule are the same rule; a hand-written glob is displayed as the glob it was typed as and is not rewritten on save. `POST /api/v1/admin/personas/{name}/test-access` answers a `(connection, method, path)` question with the decision and the matched rule. `api_routes` does not make an API connection deny-by-default. A connection no rule names stays fully reachable by any persona granted it. ## People: several personas, assigned personas, No access, addresses By default a person whose roles match several personas gets the highest-priority one. `personas.combine: all` (or Admin > Settings > Personas, which wins once saved; `PUT /api/v1/admin/settings/personas`, with a preview of who changes at `GET .../preview?combine=all`) gives them every persona their roles grant. A tool call is allowed only when one held persona allows the tool, the connection and the API route together; `tools/list`, visible connections, portal levels, shares and grants are the union. A person whose roles grant an external persona holds it alone. A caller is a service account when any held persona is. Agent context joins every held persona's prefix and instructions in priority order. Audit rows record `allowed_by` (the persona that allowed the call) and `personas` (all held); `persona` keeps the highest-priority one. Persona names may not contain `+`. An administrator can assign a person's personas in the platform (Admin > Users, `PUT /api/v1/admin/people/{email}/personas`); from the next request they hold exactly those, whatever the identity provider's roles say, and assigned personas always combine. `DELETE .../personas` returns them to identity provider roles. People can be added before their first sign-in (`POST /api/v1/admin/people`). External personas cannot be assigned. A change that would leave nobody reaching the administrator persona is refused. Addresses match only with `email_verified: true`. A role starting `platform-persona:` from an identity provider is ignored. Assignments are database-only. No access (`PUT /api/v1/admin/people/{email}/no-access`) refuses every request the person makes from the next one: portal, agents, admin API, keys bound to them, runs of automations they own or authored, and their endpoints (`503 this endpoint is not available`). Nothing is deleted. Addresses (`POST /api/v1/admin/people/{email}/addresses`) sign in as the person; only an address the platform has never seen can be added, and the person is emailed at their primary. Make primary (`PUT .../primary`) changes the address shown and emailed; records stay under the first address. A person picks where their notifications go (`PUT /api/v1/portal/me/notify-to`). Audit rows keep the address that signed in (`signed_in_email`). Each replica reloads who is assigned, refused and aliased on a PostgreSQL notification (`people_changed`) and once a minute; before the first load every person has no roles, and an API key bound to nobody keeps its own. A person's effective access, with the persona granting each tool and connection, is at `GET /api/v1/admin/people/{email}/access`; who holds a persona at `GET /api/v1/admin/personas/{name}/people`. --- # Go Library Import the platform as a library for custom MCP servers. ## When to Use Use the library when you need to: - Add tools - Your domain-specific operations - Swap providers - Different semantic layer, different query engine - Write middleware - Custom auth, logging, rate limiting - Embed it - MCP inside a larger application ## Packages | Package | What it does | |---------|--------------| | `pkg/platform` | Main entry point, orchestration | | `pkg/toolkits/*` | Trino, S3, search, knowledge and gateway toolkits | | `pkg/semantic` | Semantic provider interface | | `pkg/query` | Query provider interface | | `pkg/middleware` | Request/response processing | | `pkg/mcpcontext` | MCP session/progress context helpers | | `pkg/persona` | Role-based tool filtering | | `pkg/auth` | OIDC and API key validation | | `pkg/admin` | Admin REST API for knowledge management | ## Minimal Example ```go package main import ( "context" "log" "github.com/txn2/mcp-data-platform/pkg/platform" ) func main() { cfg, err := platform.LoadConfig("platform.yaml") if err != nil { log.Fatal(err) } p, err := platform.New(platform.WithConfig(cfg)) if err != nil { log.Fatal(err) } defer p.Close() if err := p.Start(context.Background()); err != nil { log.Fatal(err) } // p.MCPServer() is the *mcp.Server to serve over the transport you choose. } ``` ## API Stability The module is `github.com/txn2/mcp-data-platform` at major version 1 with no `/vN` suffix. This is the promise the project keeps across minor releases. Supported import surface (breaking changes only in a major release): | Package | What you import it for | |---------|------------------------| | `pkg/platform` | The facade: construct, configure, run (options and lifecycle) | | `pkg/toolkit` | Shared types every toolkit implements | | `pkg/registry` | Register and manage toolkits | | `pkg/semantic` | Semantic provider interface | | `pkg/query` | Query execution provider interface | | `pkg/middleware` | Request/response middleware contracts | | `pkg/toolkits/*` | Toolkit adapters' exported config types | Other exported packages under `pkg/` are importable but are implementation packages, not a committed integration surface; their API may change in a minor release with a release-note callout. The set is bounded by a build gate (`TestPublicSurfacePolicy`, `pkg_stability_policy_test.go`) that fails when a package is added under `pkg/` outside the supported table with a single first-party importer, since that shape is an implementation seam and belongs under `internal/`; the remaining exemptions are the reference store and provider implementations a consumer passes to `platform.WithSessionStore`/`WithQueryProvider`/`WithStorageProvider` and their siblings, plus `pkg/admin` (a mountable router) and `pkg/database/migrate` (the embedded schema migrations). Facade-internal seams live under `internal/platform/`, the HTTP adapters the server mounts under `internal/httpserver/`, and the portal's own seams under `internal/portal/` (its domain types and store contracts, PostgreSQL and no-database stores, authorization core, feedback surface, public-viewer templates, rate limiter and share cache — every moved name aliased back so `portal.Asset`, `portal.Collection`, `portal.User` and the store constructors are spelled as before); all are unimportable from outside the module by Go's internal rule and were never a supported surface. What a connection kind does to reach an HTTP upstream is one of these seams too: `internal/upstreamauth` holds the outbound authenticator and every auth mode (`none`, `bearer`, `api_key`, `basic`, `oauth`, `mtls`), the operator-owned static headers and the header names a model may not claim, the connect/call timeouts, the response read cap and the TLS material, shared by the HTTP-based kinds rather than copied into each; `internal/cfgmap` holds the typed readers over a stored connection's `map[string]any`. `apigateway.Authenticator`, `apigateway.NewAuthenticator`, `apigateway.ErrNeedsReauth` and the `AuthMode*`, `CredentialPlacement*` and `OAuth2AuthStyle*` constants are aliased back, so the toolkit's API, its configuration keys and its error messages are unchanged. Configuration-file compatibility is handled more conservatively: additive keys ship in minor releases, and breaking renames or removals are called out in that version's release notes with an admonition (old key, new key, runtime effect). Precedent: `workflow.require_search` replaced the former `workflow.require_discovery_before_query` as a hard, non-aliased rename documented in the release notes. Set `config.strict: true` to turn an unaccounted-for rename into a hard startup error instead of a silent no-op. --- # Knowledge Capture Domain knowledge shared during AI sessions -- column meanings, data quality issues, business rules -- is captured, reviewed through a governance workflow, and written to the platform catalog with changeset tracking and rollback. ## The Problem Every organization has tribal knowledge about its data that lives in the heads of experienced team members. AI-assisted data exploration surfaces this knowledge in conversations, but without capture, it's lost when the session ends. Knowledge capture persists these insights for admin review and catalog write-back. ## How It Works The system has four MCP tools and an Admin REST API: - `search`: The universal, topology-free discovery entry point, fanning one query (text and/or entity_urns) across the technical catalog, its context documents, knowledge pages, the caller's memory, captured insights, the caller's feedback, saved assets, uploaded reference material (managed resources, indexed over their file contents), prompts, managed scripts, the caller's own recorded calls, the caller's own sessions, API endpoints, and connections, returning a balanced, grouped-by-source, per-user-scoped result set with a coverage summary. - `fetch`: The companion read verb to `search`. Dereferences any `reference` a search hit carries (knowledge page, context document, catalog dataset, saved asset, prompt, or connection) back to its full content, honoring the same per-user scope so it never reads what search could not surface. A stale or out-of-scope reference returns a structured not-found, not an error. Fetching a knowledge page also returns its outbound `references` (the pages and entities it links to, each a citable reference plus its type), so an agent can deep-crawl a graph of focused, cross-linked pages deliberately (fetch the index, follow into the relevant branch) instead of re-parsing links from the markdown body (#705). - `memory_capture`: The one way to record knowledge (memory toolkit). Routed by sink-class; reviewed classes create insights with status `pending`. (To read knowledge back, use `search`.) - `apply_knowledge`: Admin-only sink router for reviewing, approving, synthesizing, applying, and rolling back insights. `apply` promotes by `sink`: `catalog` (schema_entity → the platform catalog) or `knowledge_page` (business_knowledge/operational_rule → a canonical portal knowledge page, found-or-created by slug). Both record reversible changesets. Actions: `bulk_review`, `review`, `synthesize`, `apply`, `approve`, `reject`, `rollback`, `list_changesets`, `bulk_untag` (remove a tag from every entity carrying it). - Admin REST API: HTTP endpoints for managing insights and changesets outside the MCP protocol. ## Reflexive Capture Reflexive capture removes the operator from the loop for the highest-signal case: a query error the same session later fixes. When a `trino_query`/`trino_execute` call fails with a data-model misunderstanding (unknown column/table, ambiguous reference, type mismatch, `GROUP BY` mistake) and a later related query on the same connection succeeds in the same session, the platform auto-mints one "misconception + fix" correction memory with no tool call by the agent and without blocking the tool response (the mint is asynchronous). The record carries `source: automation` and `category: correction`, and is a reviewed sink-class (`schema_entity`) so it enters review as a `pending` insight rather than mutating catalog state. Pairing is conservative: the error must match an allowlist of misconception signatures (infra, policy, timeout, and permission errors are ignored), and the success must run on the same connection and be a near-variant of the failing query (scored on shared identifiers, and requiring a novel corrected identifier) so an unrelated query on the same table, or an identical retry, is not treated as a fix. The correction is best-effort entity-keyed to the successful query's catalog dataset references, and the whole path is gated by the caller persona's `memory_capture` grant. Enabled by default when the memory subsystem is available; disable with `knowledge.reflexive_capture.enabled: false` (#635). ## Configuration ```yaml knowledge: enabled: true apply: enabled: true require_confirmation: true reflexive_capture: enabled: true ``` | Field | Type | Default | Description | |-------|------|---------|-------------| | `knowledge.enabled` | bool | `true` (when a database is available) | Enable the knowledge review and write-back toolkit (`apply_knowledge`). Knowledge capture lives in the memory toolkit (`memory_capture`) and is enabled with the memory layer, not this flag | | `knowledge.apply.enabled` | bool | `true` (when a database is available) | Enable the `apply_knowledge` tool for admin review and catalog write-back. Set `false` to disable. | | `knowledge.apply.require_confirmation` | bool | `false` | When true, the `apply` action requires `confirm: true` in the request | | `knowledge.pages.dedup_threshold` | float | `0.85` | Cosine similarity in `[0,1]` at or above which creating a knowledge page is blocked as a near-duplicate. Acts only when a real embedding provider is configured. A non-positive value selects the default | | `knowledge.pages.dedup_disabled` | bool | `false` | Turn the duplicate gate off entirely, so "no gate" is never confused with "left at default" | | `knowledge.pages.oversize_bytes` | int | `16384` | Body size in bytes at or above which a page write returns a non-blocking split suggestion. Negative disables this arm. An editorial nudge, not a bound on search reach: page content is embedded as chunks sized to the provider input budget, so a page of any size is semantically searchable end to end (#1242) | | `knowledge.pages.oversize_sections` | int | `12` | Markdown heading count at or above which the split suggestion fires. Negative disables this arm | | `knowledge.reflexive_capture.enabled` | bool | `true` | Auto-capture a "misconception + fix" correction (source `automation`, reviewed sink-class) when a Trino query errors and a later same-session query over the same table(s) succeeds (#635). Default-on when the memory subsystem is available; set `false` to disable | | `knowledge.verifiable_insights` | bool | `true` | Deliver a `verifiable` block ({urn, query_table, connection}) on an insight whose linked catalog entity resolves through the query provider to an available table, on every delivery surface: `search` insight hits, the record `fetch` returns for `mcp:insight:`, and the insight entries of the `memory_context` enrichment block (#1220). Additive and absent whenever nothing resolves, so a deployment with no query provider is unchanged. Set `false` to deliver insights with no marker | | `knowledge.search_provider_timeout` | duration | `5s` | Per-provider deadline for the `search` fan-out arms, so one slow knowledge source drops out as a collected error rather than stalling the whole search. Set a negative duration to disable the bound. | | `knowledge.search_embed_timeout` | duration | `5s` | Deadline for the serial intent-embedding step in `search`, independent of `search_provider_timeout`. A slow or unreachable embedder degrades to lexical ranking rather than stalling the search; this knob lets you give a slow (cold or CPU-only) embedder headroom to preserve `hybrid` ranking without loosening the fan-out bound. While the index worker of any replica has a call at a shared embedder (one with no `interactive_url`), the deadline grows by the time that call's largest input is expected to take, at most 20 seconds (#2846): a CPU embedder finishes the input it has begun even when the gate preempts the call, a chunk near the input budget takes seconds, and a search that gave up first was ranked by words alone though the embedder was about to answer. Each replica's worker measures the time a byte of input takes and publishes the input it has at the server in `embed_background`; a search reads the sum of the live marks. Set a negative duration to disable the bound. | Prerequisites: `database.dsn` must be configured. The `apply_knowledge` tool requires the admin persona. ## How much of a knowledge page is searchable All of it, at any size. A page's content (title, body, tags) is embedded as a SET of chunks rather than one vector, each chunk sized to the embedding provider's per-text input budget (`memory.embedding.ollama.max_input_bytes`, default 6,000 bytes) and split on the page's own markdown section boundaries where it has them, falling back to paragraph and then rune-boundary cuts. Every chunk is composed through the same title+body+tags composition a query is embedded over, so each carries the page's identity. Both vector readers -- the hybrid search arm and the create-time near-duplicate gate -- rank chunks and score each page by its best-matching chunk, so results stay page-granular while a fact at the end of a long runbook ranks its page exactly as one in the opening paragraph would, and a large candidate page is compared for duplication in full rather than by its head. Before #1242 a page carried one vector over text trimmed at the provider cap, so anything past roughly 6 KB reached the lexical arm only. The byte cap is a proxy for the model's token budget and cannot be an exact one (token density varies by close to an order of magnitude between prose and dense content such as CSV, JSON, or source), so when the model refuses an input anyway the provider halves what it sends and retries down to a 256-byte floor; that is what keeps a dense document from failing identically on every attempt forever (#1350). The refusal is recognized by the wording of the response body whatever status carries it, because the same Ollama answers the condition with a 400 from its batch endpoint and a 500 from its single-input endpoint, body identical; a status-gated match classified the batch refusal and missed the per-input one that follows it, so the bound was never reduced (#1385). The converged vector covers a prefix of that chunk rather than all of it (the lexical arm still matches the whole text), and the shrink is logged with the model and the refused size, because a model that cannot hold the configured cap for ordinary content is a misconfiguration to correct at `max_input_bytes` rather than something to absorb silently. The bound is deliberately not remembered between calls: density is a property of the text, not the model, so one dense document learning a small bound would truncate every prose document with it. Vectors live in `portal_knowledge_page_embedding_chunks`, replaced atomically by the indexjobs consumer; a content edit deletes the page's chunks in the same transaction as the write, so no vector outlives the text it was computed from, and the same write enqueues the page's own index job (trigger `write`, #1256) so the new content enters ranked search within one embed rather than on the next reconciler sweep. ## Insight Categories | Category | Description | Example | |----------|-------------|---------| | `correction` | Fixes wrong metadata | "The amount column is gross margin, not revenue" | | `business_context` | Business meaning not in metadata | "MRR counts active subscriptions only, not trials" | | `data_quality` | Quality issues or limitations | "Timestamps before March 2024 are UTC; after that, America/Chicago" | | `usage_guidance` | Tips for querying correctly | "Always filter status='active' to avoid soft-delete duplicates" | | `relationship` | Dataset connections not in lineage | "customer_id in orders joins to the legacy CRM export" | | `enhancement` | Suggested metadata improvements | "Tag sales_daily with its 6 AM CT refresh schedule" | ## memory_capture Tool Records domain knowledge shared during a session (memory toolkit). Its description says what is worth capturing (a definition, a convention, an official figure's method, who owns a dataset, a trap that cost a retry) and what is not (a column name just corrected in one's own query, or anything the table's schema already says) (#2814). **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | `type` | string | Yes | Sink-class. Live: `personal_preference`, `episodic_event`. Reviewed (creates a pending insight): `business_knowledge`, `schema_entity`, `operational_rule` | | `content` | string | Yes | The knowledge to record (10-4000 characters) | | `confidence` | string | No | `high`, `medium` (default), or `low` | | `source` | string | No | `user` (default), `agent_discovery`, or `enrichment_gap` | | `entity_urns` | array | No | Catalog references this knowledge relates to (max 10) | | `related_columns` | array | No | Columns related to this knowledge (max 20) | | `suggested_actions` | array | No | Proposed catalog changes (max 5) | | `thread_ids` | array | No | Feedback thread IDs this insight resolves; each is linked (insight_id set, `insight_linked` event, status `resolved`) | **Suggested action types:** `update_description`, `add_tag`, `remove_tag`, `add_glossary_term`, `flag_quality_issue`, `add_documentation`, `add_curated_query`, `set_structured_property`, `remove_structured_property`, `raise_incident`, `resolve_incident`, `add_context_document`, `update_context_document`, `remove_context_document`, `delete_tag`, `set_custom_property`, `remove_custom_property` **Target field:** Use `column:` (e.g., `column:location_type_id`) for column-level descriptions. For `add_documentation`, the target is the URL. For other types, leave empty or omit. **Detail field:** Description text, tag name or reference (e.g., `pii` or `mcp:tag:pii`), glossary term name or reference, quality issue description, link description, or query name (for `add_curated_query`). Short tag/term names are auto-normalized to full URNs. `flag_quality_issue` adds a fixed `QualityIssue` tag and, with a detail, opens an incident on the dataset. `add_curated_query` adds a curated query to the target dataset's curation. Requires `query_sql` (the SQL statement) and optionally `query_description`. The `detail` field serves as the query name. **Response:** ```json { "insight_id": "a1b2c3d4e5f67890a1b2c3d4e5f67890", "status": "pending", "message": "Insight captured. It will be reviewed by a data catalog administrator." } ``` When `thread_ids` is supplied, the response also includes `linked_thread_count` and `unlinked_thread_ids` (the IDs that matched no open thread, or that the caller is not authorized to resolve); both are omitted when `thread_ids` is absent. Linking is gated by the same owns-or-edit check as `manage_feedback resolve` (it is not a back door around the access model), is best-effort, and never fails the capture. The tool also registers an MCP prompt `knowledge_capture_guidance` that provides AI agents with guidance on when to capture insights. ## Feedback Bridge Human feedback threads on portal assets connect to the knowledge loop: an agent resolves a thread by capturing the insight it represents, and the chain stays visible end to end (**thread → insight → changeset → `target_urn`**). - **`memory_capture` `thread_ids`** links threads to the captured insight (see above). - **`manage_feedback` tool** (the dedicated, discoverable home for agent feedback): `list`, `create`, `get`, `reply`, `resolve`, `request_validation`, `respond_validation`, `edit`, `delete`. `edit` (thread_id, event_id, body) replaces the text of a message the caller wrote and `delete` (thread_id, event_id) removes one, the caller's own or any on a target they own or edit or as an administrator (#2514); both are served by the portal's `PATCH`/`DELETE /api/v1/portal/threads/{id}/events/{eventID}` in process as the caller. Only `comment` events change (the opening message of a comment, question, correction or suggestion thread, and every reply); approval, rejection, rating, status_change, resolution, validation_request, validation_result, insight_linked, changeset_linked and visibility_changed are refused with 409, so an edit never moves a sign-off. An edit keeps the previous text in portal_thread_event_revisions, stamps edited_at, and notifies only the people the new text newly mentions; a delete stamps deleted_at, every read returns the event with no body and no metadata (thread events, the thread list's first_message, search, the mentions inbox, manage_feedback get), the notification rows it produced lose their snippet and unsent ones are dropped, and an opening message nothing else followed takes the thread with it. A portal change is audited as a manage_feedback call with source portal, naming the thread and event and never the text. `create` (#2371) opens a thread with `body` as its first comment on exactly one of `asset_id`, `collection_id`, `prompt_id`, `knowledge_page_id` or `target_type=standalone`, through the portal's own `POST /api/v1/portal/threads` served in process as the caller (internal/selfcall), so the portal's persona gate, view-access target check, external-visibility rule, mentions and notifications apply unchanged and the caller is the author; `kind` is comment (default), question, correction, rating, approval, rejection or suggestion, `visibility` internal (default) or shared, `anchor` an object or a string holding one; a thread takes no title (#2513), so `title` is refused as an unknown argument, and every list row (the tool's `list`, the asset's thread list, the activity feed, the worklists) carries `first_message`, the first line of the thread's first message that is not deleted, which the portal lists it by with its author and target (a thread stored with a title before #2513 keeps it as its heading); a refusal carries the portal's words and status, and `reply` without `thread_id` names `action=create`. A thread's author also gets and replies to it when the portal lets them read it. **`list` with no target is the cross-target entry point**: it returns the caller's pending feedback across the assets and collections they own or can edit AND the shared general channel (unresolved threads they did not author, plus any awaiting their validation), so an agent can "review and act on any pending feedback" in one call; `list` with an `asset_id`/`collection_id`/`prompt_id` or `target_type=standalone` scopes to one target (filter by status, `requires_resolution`, `validation_state`). Scoped to the assets and collections the caller owns or can edit; admins see all; standalone/general threads are readable by any authenticated caller and resolved by the thread author or an admin. (These six actions previously lived on `manage_asset`; they were moved to `manage_feedback` so agents discover feedback by tool name.) - **Platform feedback (#2820, #2885)**: `manage_feedback action=create target_type=standalone topic=platform` reports to whoever runs the platform, not as a General thread: `kind=blocked` (default) with `trying_to` and `blocked_by` (required), `tool`, `suggestion`, what it could not do; `kind=improvement` with `observed`, `proposal` and `benefit` (required), `benefit_kind` (`possible`, `fewer_steps`, `fewer_calls`, `fewer_tokens`), `tool`, a specific change that would have saved calls, tokens or a workaround; both take `calls` (`mcp:call:` references only, at most 20). With the topic on and the persona allowed (and its tool rules reaching `manage_feedback`): `platform_info`'s agent instructions end with one note naming both loops (data lessons to `memory_capture`, platform lessons here; post blocked the first time, keep working, tell the user; at least one improvement before substantial work ends); an `invalid_arguments` refusal or a call to an unknown tool carries the reporting sentence the first time, any other refusal once the session was refused before, a `manage_script` save the gate refused or over the size limit carries it once per session as `platform_feedback`; a session's calls showing six similar calls, three truncated results, six draft cycles of one script or a workaround after a refusal add one platform note asking for an improvement (once per pattern per session, naming up to five `mcp:call:` references), and a query corrected after a failure a knowledge note pointing at `memory_capture` (every persona). Which prompt a result carried is `audit_logs.feedback_prompt` (`refusal`, `missing`, `gate`, `pattern:`); `GET /api/v1/admin/platform-feedback/prompts?days=7|30|90` counts them per persona against posts, leaving out `pattern:query_corrected`. A repeat of a done or declined post is refused (`platform_feedback_shipped` naming the release, `platform_feedback_declined` naming the reason); `PUT /{id}/status` takes `release` (required for done) and `reason` (required for declined); the list takes `kind` and `rank=true` (reports, distinct personas, sessions, benefit kind) and reports `personas`, `sessions`, `improvements_open`, `prompts_this_week`. A deployment's own `server.agent_instructions` section on this should be removed (migration 000279). Off by default; settings are the `platform_feedback` section (`GET`/`PUT /api/v1/admin/settings/platform-feedback`: `enabled` false, `channels`, `personas` empty = every persona except service accounts, `session_limit` 5, `persona_daily_limit` 50 per 24 hours). Refusal codes `platform_feedback_off`, `_persona`, `_invalid`, `_secret`, `_limit`, each naming a field and never its content. Every field passes a credential check (`internal/secretscan`: credential shapes, and the deployment's stored secrets and sealed connection values as written and base64, hex, URL- and JSON-escaped); a refusal stores only its reason and persona. A post matching one of the 500 most recent open posts by its words or by embedding at `assetsimilar.NearDuplicate` is counted on it (`folded: true`, `report_count`) and not resent; a post waits at most 5 seconds for its embedding (`DefaultEmbedTimeout`, #2829), then is stored and sent folded only by its words, with a warning logged. A new post is queued to each channel as document type `platform.feedback` with its fields as `data` (`id`, `kind`, `tool`, `suggestion`, `calls`, `persona`, and the kind's own fields only). Admin routes: `GET /api/v1/admin/platform-feedback` (status, tool, q, limit, offset; `stats`), `GET /{id}` (reports, deliveries), `PUT /{id}/status` (open, planned, done, declined), `POST /{id}/resend` (`{channel}`). Tables `platform_feedback`, `platform_feedback_reports`, `platform_feedback_refusals` (migration 000267). A session's prompt record (calls as tool, hashes and call reference, never argument values, and the prompts given) is `feedback_prompt_calls` and `feedback_prompt_given` (migration 000282), shared by every replica, swept after a day by the `feedback_prompts` retention sweep (advisory lock 4713210113); in memory without a database. Portal: Admin > Platform feedback has Blocked, Improvements (Most reported or Last reported) and Prompts and posts (7/30/90 days per persona); Change status takes Shipped with its release or Declined with its reason. Audit rows of a `topic=platform` call redact `trying_to`, `blocked_by`, `suggestion`, `observed`, `proposal`, `benefit`. - **Markdown bodies (#2214)**: a thread event body renders as Markdown in the timeline (GFM, single newlines kept as breaks, raw HTML dropped, script links not followed, delivered mentions still chips read from `metadata.mentions`, a mention inside code left as written); the composer has Write and Preview; a comment, feedback or mention email renders the message through the same goldmark renderer channel bodies use, with each `@local(domain)` mention written as its address. List views show thread titles only, so no body excerpt is involved. - **@-mentions (#627)**: a thread comment body may address people with `@local(domain)` tokens (for example `@marcus.johnson(example.com)`). The parenthesized domain terminates the token, so a mention written before sentence punctuation is not swallowed by it, and the stored form is an address rather than a display name. On write (portal REST and `manage_feedback reply` alike) the named addresses are filtered to the people who can open the target, decided by internal/portal/threadreach with the portal's authorization core (#2512): each address is judged as the person it belongs to, with the roles the known-users directory last recorded and the persona they resolve to, so ownership, an email share, a persona share, a collection share and administration all admit; an address the directory does not hold is admitted only by a grant addressed to it, and a target open to every signed-in person (knowledge page, standalone channel, a prompt that is not personal) admits only known people. A thread event's comment fan-out reaches the owner, the grantees and the thread's participants (authors of its live messages and the people they mention), each filtered by the same decision at enqueue time. Eligible mentions are recorded on the event as `metadata.mentions` (a lower-cased address array, GIN-indexed) and notified in the `mention` category, which has its own per-user preference so muting comment activity still leaves a person reachable by name. A name outside the audience -- and the author's own address -- is kept as plain text: nothing is recorded, the timeline renders it unchipped (the client chips only what `metadata.mentions` records), and nothing is delivered, so a comment can never mail an item's title and an excerpt to someone who cannot open it. A share that names its recipient only by user id grants access but records no address anywhere, so such a person is outside the audience by construction. `GET /api/v1/portal/mention-candidates?target_type=&target_id=&q=` lists the audience for the composer's type-ahead (the caller must belong to it, or be an admin); `GET /api/v1/portal/worklist/mentions` is the caller's mentions inbox, re-checked against present-day access so a revoked share stops surfacing the item's threads. - **`GET /api/v1/portal/threads/{id}/chain`** returns a thread's resolved chain: its `insight_id` and the changesets that insight produced (each with `target_urn`, `change_type`, rollback state). The portal feedback panel renders this as a "Knowledge chain" section. - **Capture as insight in the portal (#2546)**: `POST /api/v1/portal/threads/{id}/insight` builds the text from the thread when no `content` is sent, and holds it to the 4,000-byte limit. When the default is over the limit the panel shows it in an editable field with a byte count and the reviewer shortens it; nothing is truncated. A refusal shows the server's message and is logged with the thread id and reason, never the text. ### Validation & sign-off (Phase 3) - **Validation response**: after `request_validation` routes a request to the feedback author, that author confirms or disputes it via `manage_feedback action=respond_validation` (`validation_result` = `validated`|`disputed`, optional `validation_reason`) or `POST /api/v1/portal/threads/{id}/validation`. Both append a `validation_result` event and set `validation_state`; **disputing re-opens the thread**. Only the author (or an admin) may respond. - **Worklists**: `GET /api/v1/portal/worklist/practitioner` (open resolution-required threads across assets and collections the caller owns/can edit), `GET /api/v1/portal/worklist/sme` (threads awaiting the caller's validation), and `GET /api/v1/portal/worklist/mentions` (threads where a comment @-mentioned the caller). - **Activity feed**: `GET /api/v1/portal/feedback/activity` returns every feedback thread across the assets, collections, and prompts the caller can view (owned or shared, any permission), most recent activity first, each row enriched with the target's display label (`target_label`) so the client links straight back to the item; the practitioner and validation worklists carry the same label (#2513). It is scoped server-side to the caller's reachable set and never discloses feedback on items they cannot see; global-prompt threads the caller did not author are excluded so the feed stays personal. With no push-notification system, this feed (plus a sidebar badge counting the caller's open worklist) is how a user discovers new feedback. - **Sign-off**: `GET /api/v1/portal/assets/{id}/signoff` and `.../collections/{id}/signoff` return `signed_off` of `stakeholders` (N = distinct approvers; M = owner + active share grantees), rendered as "signed off by N of M". ## apply_knowledge Tool Admin-only tool for reviewing and applying captured insights. Requires the `admin` persona. ### Actions **bulk_review**: Counts of all pending insights (total_pending, by_entity, by_category, by_confidence) plus a review-queue staleness rollup (oldest_pending_at, oldest_pending_age_days, pending_over_30d, omitted when the queue is empty) so aging review debt is visible; the same rollup appears in platform_info under features.knowledge_apply.review_queue. An hourly operator alert emails a digest of the same rollup when the queue crosses an admin-configured threshold (see Review queue alerts). Pass itemize:true to enumerate the queue itself, paginated by offset/limit, each insight carrying its full insight_text body, captured_by (author), sink_class and suggested_actions_count (full suggested_actions omitted, fetch for it); the relevance-ranked search tool cannot list it completely. The response is bounded so it stays under the output limit: page_size_capped:true flags a short insights page (continue with next_offset) and by_entity_truncated:true flags a capped by_entity. ```json {"action": "bulk_review"} ``` **review**: Insights for a specific entity with its current catalog curation. ```json {"action": "review", "entity_urn": "mcp:dataset:(trino,warehouse,hive.sales.orders)"} ``` **approve/reject**: Transition insight status with optional review notes. ```json { "action": "approve", "insight_ids": ["a1b2c3d4e5f67890", "f6e5d4c3b2a10987"], "review_notes": "Verified with data engineering team" } ``` **synthesize**: Structured change proposals from approved insights. ```json {"action": "synthesize", "entity_urn": "mcp:dataset:(trino,warehouse,hive.sales.orders)"} ``` **apply**: Write changes to the platform catalog in one transaction, recorded as a changeset. ```json { "action": "apply", "entity_urn": "mcp:dataset:(trino,warehouse,hive.sales.orders)", "changes": [ {"change_type": "update_description", "target": "", "detail": "Order records with gross margin amounts (before returns)"}, {"change_type": "add_tag", "target": "", "detail": "gross-margin"}, {"change_type": "remove_tag", "target": "", "detail": "outdated"} ], "insight_ids": ["a1b2c3d4e5f67890"], "confirm": true } ``` ## Insight Lifecycle ``` pending -> approved -> applied pending -> rejected pending -> superseded applied -> pending (changeset rolled back) ``` | Status | Description | |--------|-------------| | `pending` | Newly captured, awaiting review | | `approved` | Reviewed and approved for application | | `rejected` | Reviewed and rejected | | `applied` | Changes written to the canonical sink (the platform catalog, a knowledge page, or the agent instructions); also the point the insight becomes organization-wide | | `superseded` | Replaced by newer insights for the same entity | A changeset rollback returns its source insights to `pending` rather than to a terminal state, so the review queue surfaces them again; they keep `applied_by`, `applied_at` and `changeset_ref`, and their `review_notes` names the rolled-back changeset. `reject` remains the way to discard an insight. ## Insight Visibility Applying an insight is what turns one person's capture into knowledge the organization holds, so `applied` is also the visibility boundary. | Status | Who can find it with `search` and read it with `fetch` | |--------|--------------------------------------------------------| | `pending`, `approved` | Only the capturer | | `applied` | Every identified caller, attributed through the hit's `captured_by` | | `rejected`, `superseded` | Only the capturer, and only under an explicit status query | No insight is public: reaching applied insights requires an identified caller, so an anonymous visitor to a shared portal link never sees them. Discovery also does not depend on the sink, so a fact applied to the catalog is findable by search even when no tool result names the dataset it hangs off. ## Checkable Delivered Insights An insight is a claim, and a delivered claim removes the consumer's reason to check it. When the platform can query the subject of a claim for itself it says so (#1220): an insight whose linked catalog entity resolves through the query provider to an available table is delivered carrying `verifiable: {urn, query_table, connection}` -- the table one query would settle the claim against, and the connection it lives on. Default on (`knowledge.verifiable_insights`, nil = enabled). The marker rides the payload on every surface that delivers an insight, because the platform cannot detect what model is consuming it: `search` insight hits, the record `fetch` returns for `mcp:insight:`, and the insight entries of the `memory_context` enrichment block pushed onto tool results. It asserts that the claim's subject is one query away, NOT that the claim was checked or that it is true; an insight linked to several entities names the first one that resolves, since a claim needing more than one table to settle is not the checkable shape the marker is for. It is additive: an insight linked to no entity, an entity the query provider cannot see, a noop query provider, and the operator opt-out all deliver exactly the payload they always did -- absent, never an empty block. A plain memory record never carries it, since a note is not a claim about the warehouse. The block is topology, so it honors the persona connection boundary (#1108): an insight about a dataset on a connection the caller's persona may not reach is still delivered -- an insight is not connection-scoped -- but carries no `verifiable` block, and that connection is never probed on the caller's behalf. The hit itself is not counted as withheld, since nothing about the record was hidden. Cost: each delivery surface resolves through a bounded TTL cache (`internal/tableavail`, the same implementation behind the review path's observed-entity block), so a page of insights about the same entity costs one lookup rather than one per hit, and concurrent sessions asking about the same cold entity share a single in-flight lookup. Delivery resolves through `query.LocationResolver` (where an entity is queryable) rather than `GetTableAvailability` (which also runs `COUNT(*)` when `enrichment.estimate_row_counts` is on), so the marker never costs a full scan. The pass is bounded at 2s, so a slow warehouse costs a delivery its marker rather than the record or the search arm's budget. A negative answer is remembered for 30s rather than the positive 5 minutes, because a query adapter reports a transiently failed describe and a genuinely absent table in exactly the same shape; an answer computed after the budget expired is not remembered at all. The `memory_context` block's insight entries carry `mcp:insight:` as their reference rather than `mcp:memory:`, which `fetch` always declined for a knowledge-dimension record. Because that push path is persona-scoped rather than caller-scoped, only an APPLIED insight is given a reference: fetch serves an insight to its capturer or, once applied, to everyone, and the push path cannot know which case it is in, so anything else is delivered with no reference rather than one that answers not-found. ## Governance Workflow 1. User shares domain knowledge during an AI session 2. AI calls `memory_capture` to record it (status: pending) 3. Admin uses `bulk_review` to see pending insights 4. Admin reviews and approves/rejects via `approve`/`reject` 5. Admin calls `synthesize` to generate change proposals from approved insights 6. Admin calls `apply` to write changes to the platform catalog with changeset tracking 7. Source insights are marked as applied with a changeset reference 8. Changeset stores previous values for rollback if needed This is a human-in-the-loop metadata curation workflow. Every change to the catalog goes through admin review and is tracked for auditability. ## Changeset Tracking Every `apply` action creates a changeset record: | Field | Description | |-------|-------------| | `id` | Unique changeset identifier | | `target_urn` | The catalog reference of the entity the apply named | | `change_type` | Summary of change types applied | | `previous_value` | Entity metadata before changes (for rollback) | | `new_value` | Changes that were applied | | `source_insight_ids` | Insights that produced this changeset | | `applied_by` | User who applied the changes | | `rolled_back` | Whether this changeset has been reverted | The `apply` response also returns `resulting_state`, a fresh read of the entity's `description`, `tags`, `glossary_terms`, and `owners` (the same shape stored as the changeset's `previous_value`), `catalog_changes` (the aspects written), and `created_ids` (the incidents and context documents it opened and the glossary terms it created). ## Persona Integration Control access through persona tool filtering: ```yaml personas: analyst: tools: allow: ["search", "fetch", "trino_*", "memory_capture"] deny: ["apply_knowledge"] admin: tools: allow: ["*"] etl_service: # "search" is required so this query-capable persona can satisfy the # search-first gate (on by default); otherwise trino_* calls are refused. tools: allow: ["search", "trino_*"] deny: ["memory_capture", "apply_knowledge"] ``` ## Admin REST API HTTP endpoints for managing insights and changesets. All endpoints require admin authentication via API key (X-API-Key or Authorization: Bearer header) with the admin role. ### Insight Endpoints | Method | Path | Description | |--------|------|-------------| | GET | `/api/v1/admin/knowledge/insights` | List insights with filtering and pagination | | GET | `/api/v1/admin/knowledge/insights/{id}` | Get a single insight by ID | | PUT | `/api/v1/admin/knowledge/insights/{id}` | Update insight text, category, or confidence | | PUT | `/api/v1/admin/knowledge/insights/{id}/status` | Approve or reject an insight | | GET | `/api/v1/admin/knowledge/insights/stats` | Get insight statistics | **Query parameters for listing:** | Parameter | Type | Description | |-----------|------|-------------| | `status` | string | Filter by status (pending, approved, rejected, applied, superseded) | | `category` | string | Filter by category | | `entity_urn` | string | Filter by entity URN | | `captured_by` | string | Filter by user who captured | | `confidence` | string | Filter by confidence level | | `source` | string | Filter by source (user, agent_discovery, enrichment_gap) | | `since` | RFC3339 | Filter by creation time (after) | | `until` | RFC3339 | Filter by creation time (before) | | `page` | integer | Page number (1-based) | | `per_page` | integer | Results per page (default 20, max 100) | **Observed warehouse state:** a pending insight whose entity URN resolves through the configured query provider to an available table carries `observed_entities` on both the list and detail payloads: one entry per resolved URN with `urn`, `query_table`, `connection`, `estimated_rows` (only when `enrichment.estimate_row_counts` is on), and an advisory `conflict` (`claimed_rows`, `observed_rows`, `message`) when the claim text states an integer the table disagrees with. When a claim states several numbers, the one nearest the estimate is compared. The marker never blocks promotion — approve and reject are unchanged. The field is omitted entirely, leaving the payload byte-identical to before, for a decided insight, an unresolvable URN, an unavailable table, a lookup that outran the read path's budget, and a deployment with no (or a noop) query provider. ### Changeset Endpoints | Method | Path | Description | |--------|------|-------------| | GET | `/api/v1/admin/knowledge/changesets` | List changesets with filtering and pagination | | GET | `/api/v1/admin/knowledge/changesets/{id}` | Get a single changeset by ID | | POST | `/api/v1/admin/knowledge/changesets/{id}/rollback` | Rollback a changeset (restores previous metadata) | **Query parameters for listing changesets:** | Parameter | Type | Description | |-----------|------|-------------| | `entity_urn` | string | Filter by target entity URN | | `applied_by` | string | Filter by user who applied | | `rolled_back` | boolean | Filter by rollback status | | `since` | RFC3339 | Filter by creation time (after) | | `until` | RFC3339 | Filter by creation time (before) | | `page` | integer | Page number (1-based) | | `per_page` | integer | Results per page (default 20, max 100) | ### Memory Record Endpoints | Method | Path | Description | |--------|------|-------------| | GET | `/api/v1/admin/memory/records` | List every user's memory records: `created_by`, `dimension`, `sink_class`, `category`, `status`, `source` filters, `limit`/`offset` paging (the portal route lists only the caller's own) | ## Database Schema Knowledge capture uses two PostgreSQL tables (migrations 000006, 000007, 000008). **knowledge_insights:** | Column | Type | Description | |--------|------|-------------| | `id` | TEXT | Primary key (cryptographic random hex) | | `created_at` | TIMESTAMPTZ | When the insight was captured | | `session_id` | TEXT | MCP session that produced it | | `captured_by` | TEXT | User who shared the knowledge | | `persona` | TEXT | Active persona at capture time | | `source` | TEXT | Where the knowledge came from: `user`, `agent_discovery`, `enrichment_gap` | | `category` | TEXT | Insight category | | `insight_text` | TEXT | The domain knowledge | | `confidence` | TEXT | Confidence level | | `entity_urns` | JSONB | Related catalog references | | `related_columns` | JSONB | Related columns | | `suggested_actions` | JSONB | Proposed catalog changes | | `status` | TEXT | Current lifecycle status | | `reviewed_by` | TEXT | Who reviewed the insight | | `reviewed_at` | TIMESTAMPTZ | When it was reviewed | | `review_notes` | TEXT | Reviewer comments | | `applied_by` | TEXT | Who applied the insight | | `applied_at` | TIMESTAMPTZ | When it was applied | | `changeset_ref` | TEXT | Link to the changeset | **knowledge_changesets:** | Column | Type | Description | |--------|------|-------------| | `id` | TEXT | Primary key (cryptographic random hex) | | `created_at` | TIMESTAMPTZ | When changes were applied | | `target_urn` | TEXT | Catalog entity that was modified | | `change_type` | TEXT | Type of changes applied | | `previous_value` | JSONB | Metadata before changes | | `new_value` | JSONB | Changes applied | | `source_insight_ids` | JSONB | Insights that produced this | | `approved_by` | TEXT | Who approved the changes | | `applied_by` | TEXT | Who applied the changes | | `rolled_back` | BOOLEAN | Whether changes were reverted | | `rolled_back_by` | TEXT | Who reverted the changes | | `rolled_back_at` | TIMESTAMPTZ | When changes were reverted | --- # Portal: Your Work The user portal is the day-to-day interface for analysts, engineers, and data consumers. On the site it is the `portal` rail section's Your Work group, one page per surface, in the order the portal's sidebar lists them: Assets (https://mcp-data-platform.txn2.com/portal/assets/), Collections (https://mcp-data-platform.txn2.com/portal/collections/), Shared With Me (https://mcp-data-platform.txn2.com/portal/shared/), Resources (https://mcp-data-platform.txn2.com/portal/resources/), Activity (https://mcp-data-platform.txn2.com/portal/activity/), APIs (https://mcp-data-platform.txn2.com/portal/apis/), Automations (https://mcp-data-platform.txn2.com/portal/scripts/), Inbox (https://mcp-data-platform.txn2.com/portal/feedback/), Knowledge and Memory (https://mcp-data-platform.txn2.com/portal/knowledge/), Prompts (https://mcp-data-platform.txn2.com/portal/prompts/), Scratch Tables (https://mcp-data-platform.txn2.com/portal/scratch-tables/) and Settings (https://mcp-data-platform.txn2.com/portal/settings/). The sidebar opens with Assets and Resources, set apart from the other sections, which follow in alphabetical order; Collections and Shared With Me are reached from Assets. The tour's entry page is https://mcp-data-platform.txn2.com/portal/, which also covers enabling and branding the portal. Every page is addressable. Path recognition is one table (`ui/src/lib/portalRoutes.ts`) rather than a final `else` in the shell's switch, because the switch is spread across five section components that each own their own matching and none can see whether another matched: a retired or guessed name (`/assets`, `/shared`, `/knowledge-pages`) redirects to the surface it meant, a trailing slash is dropped when what is left is a real route, and a path with no page renders a not-found page naming the address and offering the way back. The old behaviour was the failure mode the platform refuses everywhere else — the shell rendered its chrome, a section title, and an empty content area, having requested nothing, which is indistinguishable from being told you own none of what you asked for (#1359). A drift gate reads the route literals and detail patterns back out of the shell and the section components and asserts the table knows each one, so a route added to the shell cannot silently become a refusal. ## Section intros Every reader-facing section opens with a description of itself: a compact row carrying the section's own nav icon and one sentence, and a disclosure holding the fuller paragraph (`ui/src/components/patterns/SectionIntro.tsx`, copy in `sectionIntros.tsx`). Both fields describe the section; neither instructs the reader, who is finding out what they are looking at rather than being told where to file something. It is composed once in the shell (`AppShell`) over the section a route belongs to, so it heads a section's listing surfaces and no detail page beneath them, and a test fails when a nav entry has no intro. A reader who has never opened a section sees it expanded; closing it leaves the one-line summary and is remembered per section in `localStorage`, wrapped in try/catch so a private window still renders. Knowledge draws its compact row rather than writing it -- the Memory to Insight to Knowledge pipeline is its summary -- and keeps the storage key its former standalone header used, so a reader who had already closed it does not get it back. Settings has no intro: it is controls, not a place things live. This is what a person is told; `instructions.ResourcePositioning` is what the agent is told, still rendered verbatim in the resources empty state and the upload dialog. The two agree because both are drawn from the content model, not because one renders the other (#1570). ## Activity Three tabs at `/activity`, `/activity/sessions`, and `/activity/calls`. Overview: personal tool usage analytics with configurable time ranges (1h, 6h, 24h, 7d). Summary cards (total calls, avg duration, tools used), activity timeseries chart, and top tools bar chart. My Sessions: the caller's own sessions, listed and openable, over `GET /api/v1/portal/sessions` and `GET /api/v1/portal/sessions/{id}`. Same audit-derived read model the admin Sessions surface reads (`internal/platform/sessionview`), scoped to the caller: the scope is a predicate inside the rollup over `audit_logs`, so another user's session id groups to no rows and is answered 404 — indistinguishable from an id that was never used. There is no `user_id` parameter (one sent is overwritten with the authenticated caller) and no user column or facet. Facets: time window (24h/7d/30d/all, default 7d, a visible control because the rollup reads every event in range), session kind (agent/portal/script/transport), has-failures, has-assets. The detail carries the summary, the assets and insights the session produced, and a page of its call timeline with the purpose stated for each call; the timeline is scoped to the caller too, so it cannot carry calls they did not make. Rows are plain rather than clickable: the admin event drawer is the only surface that opens a single audit event. Addressable at `/activity/sessions/{id}`. The same read model is what an agent recalls through `search` (the `sessions` source) and `fetch mcp:session:` (#1322), under the same predicate, so what an agent recalls and what its owner opens are one session. My Calls: the caller's own recorded data-access calls, over `GET /api/v1/portal/calls` and `GET /api/v1/portal/calls/{id}`, with `POST .../promote` and `POST .../reject`. Same catalog the admin Calls surface reads (`internal/platform/callrecord`), scoped the way My Sessions is: the caller is a predicate inside the query, so another user's record id is 404 and there is no user facet or column. A record is one query (`trino_query`, `trino_execute`, `trino_export`) or one API invocation (`api_invoke_endpoint`, `api_export`), written by an audit-store decorator on the audit writer's own goroutine, carrying the statement or request line, the targets (dataset URNs parsed from the SQL; the endpoint identity for API), the stated purpose, the session, the duration and the response size. Outcome is DERIVED on read, never stored: `failed` (the call errored), `satisfied` (an asset's provenance or a capture's `sources` names it), `superseded` (a later successful call in the same session over the same connection and targets, with nothing built from this one), else `ran`. Reuse counts later sessions that fetched the record and then ran what it holds; a session re-running its own query, or an identical query written without reading the record, counts for nothing. Facets: kind, connection, outcome, target, session, free text over purpose and statement, and `queue=promotable` (satisfied, undecided, ordered by reuse). `search` ranks the caller's successful calls on the curve the other sources use, `0.6 * (cosine+1)/2 + 0.4 * lexical` (lexical 1 when the full-text index matches), each match's own cosine read in the lexical arm and a record not yet embedded scored at cosine 0, so an exact word only a fresh record holds outranks every semantic neighbour that matches none of the query (#2251; it was `0.5 * ts_rank_cd` beside the raw cosine). Promotion writes a SQL record as a curated query on every catalog dataset it reads (the curated-query write `apply_knowledge` uses) and an API record as a saved example on its endpoint; a rejection is recorded so the queue stops offering it. Retention (`calls.retention_days`, default 90) sweeps by what a record came to rather than by age: a record cited by an asset or a capture, promoted, declined, or re-run by another session is never swept; a query that came to nothing ages out. `calls.exclude_personas` names the personas that are machinery -- an automated system driving ingestion through the same tools people use writes a record per fetch that nobody re-runs, and every one is embedded -- and a call made under one of them is audited exactly as before and never cataloged, so no surface can return it and the indexer has no unit to embed; the records such a persona wrote before it was named are swept whatever their age, with the evidence clauses standing, and a name matching no known persona is warned about at startup. A persona can carry the same mark itself: `service_account: true` in its file definition, or the "Service account" checkbox on the portal persona editor's AI Assistant Behavior tab ("Its calls are audited but not added to Calls.") for a database persona (column `persona_definitions.service_account`, migration 000171). The mark is read from the live persona registry on every call and every sweep, so a persona saved in the portal takes effect on the next call on every replica; both forms apply, and an API key is covered through the persona its roles map to. Saving a persona as a service account through the admin API starts a sweep at once. The sweep deletes in batches of 5,000 records, each its own statement and transaction, and deletes each removed record's `index_jobs` units of kind `calls` (pending, running or finished) in the same statement, so the calls index total falls by the count removed. The admin Indexing page shows a Top callers list under the `calls` kind (`GET /api/v1/admin/calls/top-callers`): the ten callers (a principal under one persona) and ten personas with the largest share of records, each with its count, share, `service_account` and `excluded_by_config`, and a link to the persona editor; the counts are cached for five minutes and taken again after a sweep removes records, and the flags are read at the request. A managed script run's calls are excluded the same way and take no setting: the platform's own scheduler is the automated system, a run is by construction the re-run, and a run presents the persona of the person who wrote the script, so `exclude_personas` could never name it -- the rule reads the audit event's `source` instead, the sweep clears the rows written under a `script:` principal before this existed, and a person's call in the same persona is cataloged exactly as before. The audit row, its retention and the API gateway metrics are untouched; what is also withheld is the `mcp:call:` reference a data call normally comes back with, since an id the catalog declined to record resolves to nothing and citing it would store a citation that can never be satisfied. The sweep runs at startup and then daily under a PostgreSQL advisory lock so replicas delete once. Addressable at `/activity/calls/{id}`. The asset viewer walks the other way: the metadata sidebar's Session row and the provenance panel's Open session action both open the session that produced the asset (`/activity/sessions/{id}` for an owner, `/admin/sessions/{id}` for an operator). Both are omitted for a reader who is neither, since the session would answer them 404. ## Home Home is the portal's landing page at `/` (#2504); the Assets gallery is at `/assets`. It shows Recent (the assets and collections the reader opened in the portal, newest first), Favorites (what they starred; the same list sits at the bottom of the sidebar and of the phone menu drawer), My drafts (their assets with status Draft) and Waiting on you (the practitioner and SME worklists), each with an empty state. Under each name in Recent and Favorites a line says whose the item is and when it last changed (#2734): `Shared by ` or `Yours`, then `Changed` with the time (relative within a day, a date after it, the year when not this one), `Collection` first for a collection; the reads return each item's `updated_at` beside its `owner_email`. Opening an asset or collection page records the open (`POST /api/v1/portal/recents` with `{kind, id}`; a second open within 30 seconds is not counted again); the star (the round button on an asset card, Star in the viewer's action row and a collection's header) is `PUT`/`DELETE /api/v1/portal/favorites/{kind}/{id}`. Both are stored per person (`portal_favorites`, `portal_opens`, migration 000262) and grant nothing: `GET /recents` and `GET /favorites` join each entry to its asset or collection under the reach rule (`internal/portal/reachstore`), so an item the reader can no longer open (share revoked, deleted) is absent with no placeholder or count, and an item they cannot open cannot be starred or recorded (404, the answer for a missing item). Unused, Possible duplicates and Trash are tabs beside Assets and Collections (#2509) at `/unused`, `/duplicates` and `/trash`, each listing only the caller's own assets; an administrator may pass `everyone=true` (the Everyone's switch, adding an Owner column) and anyone else asking is refused with 403. Unused (`GET /api/v1/portal/unused?days=30|90|180`, default 90) lists assets nobody opened in the portal since the cutoff, never opened first, with status, all-time open count and last open, never who opened; opening an asset removes it; Deprecate and Delete act on a selection. Opens count from this release. Possible duplicates (`GET /api/v1/portal/duplicates`) groups one owner's assets whose stored embeddings are at least `assetsimilar.NearDuplicate` alike, the closeness `save_asset`'s `similar_assets` uses, over the newest 2,000 embedded assets; Keep marks the one to keep, Deprecate sets status Deprecated with the note "Duplicate of ", Delete sends to the trash, and Dismiss (`POST /api/v1/portal/duplicates/dismissals` with the group's digest, a sha256 over its members and the version each is at) hides the group from that person until a member gets a new version or the group changes membership (`DELETE .../dismissals/{digest}` undoes). Trash (`GET /api/v1/portal/trash`) lists deleted assets and collections, most recent first, each with `purge_at` = deletion + `portal.deleted_retention_days` (default 30) and the retention in `retention_days`; Restore (`POST /api/v1/portal/trash/{kind}/{id}/restore`) clears the deletion, so versions, shares and collection memberships come back; Delete permanently (`DELETE /api/v1/portal/trash/{kind}/{id}`) removes the item now with its objects, shares, threads and collection places (`portalpurge.PurgeAsset`/`PurgeCollection`, objects first; 503 when a stored file would not delete, keeping the row). Restore and purge are the owner's or an administrator's; to anyone else the item answers 404. The retention sweep repeats the deletion and cutoff in its final statement, so an item restored after its batch was listed keeps its row. `manage_asset` reads the same library: `list_recents` (`limit`), `list_favorites`, `list_trash` (with `retention_days`) and `restore` (`asset_id` or `collection_id`, the owner's or an administrator's; anything else reads as not found). The draft write barrier classifies the three lists as reads and `restore` as a write. ## Assets Download of an HTML or JSX asset (#2530) is one self-contained HTML file named for the asset that opens from disk with the network off and renders as in the portal, from the asset page, its fallbacks and the share viewer (signed in and public). The platform builds it at `.../standalone` beside the content route, reading the asset through that route with the reader's own request: the runtimes under `/portal/vendor/` (reveal.js, MapLibre) inlined as scripts and styles, declared images and fonts as `data:` URIs, and files on other hosts (Google Fonts, images, CDN scripts) fetched through an egress guard that refuses private, loopback, link-local and metadata addresses, bounded per file, in total, in count and in time. A JSX asset is compiled (esbuild) and bundled with React, Recharts and lucide-react as the UI build pins them (`/portal/vendor/jsx/`) and any module it imports by `https` URL, keeping only what it uses. A file not fetched is left as its URL and named in the `X-Standalone-Notices` header, shown with the download. An asset that reads platform data while it renders (a declared data file it fetches, an embedded form, the basemap archive) answers 409 and the portal shows a dialog with Cancel and Download source, which saves the asset as stored (`?source=stored` on the content route: references as written, no form viewer token). A `publish_data` data region is inline and downloads standalone. Other types download as before; public share downloads are limited per client address. Asset status (#2502): Draft, Published or Deprecated (with an optional note a deprecated asset shows readers in a banner), set by the owner and editors from the viewer's Status menu, `save_asset` (`status`, `status_note`) and `manage_asset update` (`status`, `none` clears); informational, no access effect, no status by default; badge on card, row and viewer; the Status filter (Any, No status, Draft, Published, Deprecated) in every scope; every change in the Status history (who, when, from, to). Routes: `PUT`/`DELETE /api/v1/portal/assets/{id}/status` (403 for a viewer), `GET .../status/history`, `status=` on the listing and search. Verified (#2503): administrators and personas with `portal.verify_assets` ("Can verify assets") verify an asset they can open with a note and optional expiry, recording the version; a newer version reads changed_since_verified; the badge is removed at its expiry after one reminder to the verifier and owner a week before; search ranks verified above unverified at equal relevance; `manage_asset verify` (`note`, `expires_at` date or RFC 3339) and `unverify`; `PUT`/`DELETE /api/v1/portal/assets/{id}/verification`; `verified=true` filter; no update field forges it. Published version (#2510): the owner or an editor publishes one version (`published_version`) that readers (viewer shares, persona shares, a collection's viewer shares, share links) are served from every content route (content, share link content, a signed content URL minted without a version, the tile, a copy, `manage_asset get_content`/`outline`/`locate`/`stats`), while the owner, administrators and editors read the newest and `manage_asset get` tells them `newer_than_published`; a reader's `get`, provenance and row in every listing, search and view run describe the published version (number, size, type, provenance up to it, no `published_version`) and the tile is drawn from it; a later version by number is 403 to a reader, and a reader's history (`list_versions`, `diff`, the versions route) stops at the published version; publishing an asset with no status or a Draft marks it Published, never a Deprecated one, and stopping changes no status; each change is a `published` entry in the asset's history; retention never prunes the published version; an asset in a released application is served its release's version (#2411) and publishing it is refused (409); `manage_asset publish_version` (`version`, the newest when omitted) and `unpublish`; `PUT /api/v1/portal/assets/{id}/published-version` `{"version": n}`, `POST .../published-version/latest`, `DELETE .../published-version`; in the viewer the Published version menu (Publish version N, Publish latest, Stop pinning), a note above the content while a newer version exists, and the published version marked in the version picker and Versions panel, for editors only. Links between assets (#2432): `mcp:asset:` as a link target (``, Markdown link) is a link, not a reference: saved without checks, grants nothing, opens the target's portal page for each reader with their own access (request-access page otherwise), followed from an HTML frame only for an id the stored body links; a managed resource as a link target is still refused; `GET /api/v1/portal/assets/{id}/links` returns `links` and `linked_from` (only assets the caller can open, no count of the rest). Bulk actions (#2507): tick boxes on cards or table rows, shift-click a range, the table header selects the page, and Select all N matching takes every asset the scope, search and filters cover, up to 500. The toolbar offers Add tags, Remove tags, Add to collection, Set status (or clear), Share (a person by address or a persona, viewer or editor, no email) and Delete (to the trash); on a phone it docks at the bottom as Tags, Status and More. `POST /api/v1/portal/assets/bulk` (`action`, `asset_ids` at most 500, the action's arguments) acts on each asset through that asset's own single route served in process with the caller's identity (`internal/portal/assetbulk`), so each is authorized by its own rule and nothing changes on an asset the caller may not act on; the result lists applied and skipped with the reason, `not found or no access` for an asset the caller cannot open or that does not exist. Tag suggestions (#2508): the metadata tag field suggests tags on the assets the reader can open by prefix without case, with counts, ending with "Add 'X' as a new tag"; `GET /api/v1/portal/tags?prefix=`. Download progress (#2614): the asset page's Download, a managed resource's Download (its page and the file browser's preview pane) and the standalone download read the file into the page before the browser's own download bar appears, so the control shows the download running: disabled and spinning, **Preparing…** while a standalone file is built, then **Downloading 42%** with a bar along its bottom edge when the size is declared (Content-Length on an uncompressed body), or **Downloading 12.4 MB** with a moving bar when it is not; hover names the bytes. A second click starts nothing. On a phone a status line at the foot of the screen shows the progress until the download ends. A failure names the status (*Download failed: the platform answered 500.*) or that the platform could not be reached, in a five-second toast with Try again; on a phone it stays until dismissed or tried again. AI-generated dashboards, reports, and visualizations saved via `save_asset`. Grid/table view with search, content type filter (HTML, JSX, SVG, Markdown, CSV), and tag filter. Ordering is a control, not a constant: a column select (updated, created, name, size) plus a direction toggle, mirrored by the sortable table headers, sent to the server as `sort` and `dir` on `GET /api/v1/portal/assets`. It defaults to `updated_at DESC` so the most recently revised work is first, resolves the column against an allowlist before it reaches an ORDER BY, and appends `id` in the same direction so LIMIT/OFFSET pagination cannot repeat or drop a row that ties. The date each card and row displays is the one the list is ordered by. Asset viewer renders each type natively: HTML/JSX as interactive components, SVG as vector graphics, Markdown with GFM+mermaid, CSV as sortable tables. Preview/Source toggle, Delete/Download/Share actions. The version picker beside the toggle lists every version the asset keeps with the time it was written, since a number alone does not identify a version of an asset written on a schedule; the trigger shows the version alone. The picker and the history are the owner's, an editor's and an administrator's (#2226): a reader whose access is viewer (direct or through a collection) sees the current version only, and `GET .../versions`, an earlier version's content and a signed content URL naming an earlier version answer them 403, as do `manage_asset` `list_versions` and `diff` (list_versions had no access check before and now requires read access too). A feedback thread raised against an older version still opens. The knowledge pages that reference the asset are a Referenced by button to the right of the version picker, carrying their count and opening a modal that lists them, each opening its page; it replaced a full-width card above the toolbar that pushed the document down to name one page (#1792). The metadata sidebar's References panel is the person's end of the asset reference mechanism (#1475, #1488), over `GET/POST /api/v1/portal/assets/{id}/references` and `DELETE .../{kind}/{targetID}`: each reference's name and type, a scope for a managed resource and an owner for a referenced asset, a thumbnail where it is an image (loaded through the reference's own /portal/refs URL rather than the target's own route, so it renders for a reader who was only ever shown the asset), a link to the target where the reader could open it themselves, and the reference string with a copy control -- adding a reference never touches the content, so the markup still has to name it. The owner, a shared editor and an administrator add through a picker with a tab per kind (the resources they can read, the assets they can open) and remove; the picker names what the reference gives away and the asset's CURRENT audience before it is confirmed, a removal whose reference the stored content still writes warns with those line numbers first, a reference whose target was deleted is flagged rather than dropped, and a reader without edit authority gets the list and no controls. The reverse edge is on both ends (`GET /api/v1/portal/resources/{id}/used-by` and `GET /api/v1/portal/assets/{id}/used-by`): a Used by section on the resource beside the prompts one and on the asset viewer's own sidebar, flagging any referencing asset that carries a public link and counting without naming the ones the reader cannot open, and the resource delete dialog carries the same list. A presentation is an HTML asset built on the slide runtime the platform serves (reveal.js, pinned in the portal build and answered at `/portal/vendor/reveal/` by the same origin as the page, so a deck renders on a network that admits only this deployment and inside the share viewer's existing script policy). The HTML frame is an `srcdoc` document rather than a blob: URL, so a root-relative path in the artifact resolves against the page. Every HTML asset carries, on the row that holds the Preview/Source toggle and the version picker, a Present control that fullscreens the frame and moves the keyboard into it (arrow keys and space advance, Esc returns) and an Export PDF control that downloads the document printed by the platform's renderer (#1983): GET .../pdf beside the content routes of a portal asset and its versions, an admin asset and its versions, a managed resource and its versions, a share (/portal/view/{token}/pdf) and a shared collection item (/portal/view/{token}/items/{assetId}/pdf) reads the document through its content route with the caller's own request, so the same access applies and that route's refusal status is returned with its Retry-After, WWW-Authenticate and Location headers under a plain-text body of the route's own, then prints it in the headless renderer with printBackground, at the page size the document's @page declares, in its own colors; a deck on the served runtime is printed in its print view with pdfSeparateFragments off, one page per slide at its last build step, laid out as on screen: the print step repeats the document's own `.slides > section` rules for the slide inside the print view's page wrapper and sets each slide's screen padding back on it (#2343). 415 for a non-HTML document and 413 past 32 MiB, neither held in memory; 503 with the reason when no renderer answers, the document does not settle within 90 seconds, or the print fails; two prints at a time per replica; the share routes admit six prints a minute per client (burst three, 429 with Retry-After). The viewer exports the version on screen and offers no export while the source has unsaved edits. Nothing is printed in the browser. A document on the served runtime also carries Overview, the runtime's grid of every slide, asked for by message. The frame fills the page under that row, ending at the page's padding. The share viewer carries the same three controls in its header and fills the space under its notices, and the thumbnail is the title slide. An agent asked for a presentation, a deck or slides is pointed at `mcp:knowledge_page:platform-presentations`, which carries the served paths, the skeleton, what the controls do, and what the sandboxed frame does not allow: the runtime's speaker view, a second window (#1767, #1769). A chart, flow, mind map, roadmap, network, graph or animation in an HTML asset, a JSX asset or on a slide is drawn by a library the document loads from a public CDN at a pinned version; an agent is pointed at `mcp:knowledge_page:platform-visual-libraries` by the instruction baseline and by save_asset's description, which names Vega-Lite, Mermaid, Markmap, D3 with d3-sankey, Frappe Gantt, Cytoscape.js, Graphviz, Rough.js and dotLottie, each with a skeleton that follows light and dark, fits the frame and shows an animation's last frame under reduced motion, plus what changes on a slide and the JSX form through esm.sh. Graphviz and dotLottie are built on WebAssembly, which the share viewer's policy compiles and a JSX asset's frame does not (#2373). Agents are told to save output here rather than in their client's own artifact or canvas feature, with the reasons on the built-in page `mcp:knowledge_page:platform-why-assets-live-in-the-platform`, and that an HTML, JSX or SVG asset must fit a 375-pixel phone screen; every whole worked example on the visual pages is opened at that width by an acceptance criterion (#2463). Every portal page fits a phone too: on a phone the tab strips scroll sideways in their own row, the main lists stack as cards, the admin and data tables scroll inside their own box with the first column pinned, and the page itself never scrolls sideways, which `npm run test:phone` (the phone-width pass over the screenshot route manifest, signed in as an administrator and as a non-admin, in make verify's frontend-e2e and CI's Portal phone width job) fails on. **What gets a tile.** If the viewer renders it as a document, it gets a tile: the drawable set is derived from the renderer registry (`ui/src/components/renderers/registry.ts`) rather than restated beside it, which is how YAML, XML, SQL, Python, JavaScript, CSS and TSV -- every one of them laid out by the viewer -- kept a content-type icon forever (#1754). The bridge is a table over the registry's own renderer kinds, exhaustive by type, in which the families the viewer renders and the tile page deliberately does not draw (PDF, audio, video) carry the reason they do not; a test derives the expectation from it for every content type the registry names, and the Go/browser parity test holds the two languages to each other. A type is matched whole -- its canonical media type with parameters removed and aliases settled, or a `+json`/`+xml` structured suffix, with any other `text/` type drawn as plain text -- rather than as a fragment found anywhere in the type (#1882): every Office Open XML type contains "xml", so an Excel workbook, a Word document and a presentation were offered as XML and drawn as the text of their zip bytes. They, OpenDocument files and archives keep their content-type icon, and migration 000162 cleared the tiles already drawn for a type nothing draws. **Thumbnails and how they stay current.** The platform draws every tile itself (#1787), in a headless Chrome (`chromedp/headless-shell`, pinned by digest) that runs as a second container in the platform's pod and is reached over the DevTools protocol at `thumbnails.renderer_url` (default `http://127.0.0.1:9222`). A worker in every replica claims owed rows with a lease (`FOR UPDATE SKIP LOCKED`, `thumbnail_claimed_until`), opens a tile page -- the content-viewer bundle's second entry, `ui/src/tile-entry.tsx`, carrying the document as JSON -- and screenshots it once the page reports itself drawn: HTML and JSX in the viewer's own frame at 1280x960, painted at full size and reduced to 800x600 with a Catmull-Rom filter (a browser asked for the small picture paints body text a few pixels tall, #1789), everything else laid out at 400x300 and painted at twice the density, scrollbars hidden. A PDF's tile is rasterized rather than borrowed from the viewer's frame (#1794): the tile page rasterizes page one with pdf.js onto a canvas sized in device pixels and scaled to cover, in a chunk loaded by a PDF tile and nothing else (the worker file is served from the viewer's own chunk directory, which is why `.mjs` is servable there). A PDF reaches the page by URL like a raster image rather than through the page's JSON payload (`isBinary`) and is drawn once for both schemes. It is one of the families past the 1 MB source bound: `thumbtypes.LargeSourceLimit` holds a PDF, a CSV and a TSV to 32 MB, because each is drawn from part of the file rather than all of it -- page one of a PDF, and for a table the head of the file, which the worker cuts at a record boundary (`headFor`, 64 records or 256 KiB) before the tile page is built, since the tile is the header row and ten rows and the rest used to be parsed and discarded (#1802). Both stores ask the bound as a CASE over the content type (`thumbtypes.SourceLimitExpr`) so the raise reaches those families alone, and `thumbtypes.LargeSourceFamilies` and `HeadDrawnFamilies` are the one Go statement of which they are, held to the browser's copy by a parity test. A document that is password-protected, damaged or not a PDF settles with its reason and keeps its icon. Every family except SVG, PDF and raster images is drawn once per colour scheme with `prefers-color-scheme` emulated: the families laid out on the portal's surface take the scheme's background, and HTML and JSX answer it through their own stylesheets as they do in the viewer's frame (#1789). Raising the renderer generation (`thumbnail_renderer`) redraws every stored tile once in the background, and the old tile serves until its replacement lands; the generation is on the asset, resource and collection-item JSON (`thumbnail_renderer`, `asset_thumbnail_renderer`) and the portal puts it in the tile URL (`&r=`) beside the version, because a redraw keeps the version and the thumbnail route is cacheable for an hour. A collection's mosaic is composed twice, light from its members' light tiles and dark from their dark tiles, the dark one stored beside the light one at `portal/collections//thumbnail_dark.png` and served by `GET /api/v1/portal/collections/{id}/thumbnail?variant=dark` (the light mosaic when a collection has no dark one yet); the mosaic's source signature carries each member's dark version, so a member's new dark tile recomposes it. The portal root sets `color-scheme` from its resolved theme (`:root { color-scheme: light }`, `:root.dark { color-scheme: dark }` in `ui/src/theme.css`, shared by the portal and the public share viewer), which every document frame inherits and which a framed document's `prefers-color-scheme` resolves against, so an HTML or JSX asset follows the reader's theme choice rather than the operating system (#1789). The browser paints it, so the tile is what the viewer shows; it replaced html2canvas 1.4.1, a JavaScript reimplementation of CSS painting that could not draw a CSS transform (a reveal.js deck became a sliver in the corner, #1784) and painted an inset box-shadow as a solid fill (#1787). The renderer never reaches the network: every page runs in its own browser context behind a dead proxy, every request of the page, its frames and its workers is intercepted and answered by the platform (its own routes in-process, a public URL fetched through `internal/egressguard`), and the socket constructors are removed before any script runs. A row is owed a tile when it has none, has one of an older version (an asset's `thumbnail_version`, a resource's `thumbnail_captured_at` against `updated_at`), one drawn by an older renderer generation (`thumbnail_renderer`), or one under a legacy filename; a version write leaves the stored tile serving until the new one lands. A document that cannot be drawn is recorded (`thumbnail_failure`, and the version or file time it was tried at) and not tried again until it changes or its owner clears the tile; the reason is on the file's Thumbnail panel, where Recapture (`DELETE .../thumbnail`) discards the tile and the failure and the panel polls the row until the new tile arrives; the control is disabled while the row says a tile is owed, since the draw it would ask for is already under way, and presses never queue work (a clear resets columns on the row, the worker leases the row, and the clear does not touch the lease). The light variant is drawn and stored first, so a failure can stand beside a stored tile, and the panel names the part that failed from the tile's own stamp: a light tile of the current version means only the dark tile failed, a light tile of an earlier version means this version could not be drawn and the reader is looking at the previous one, no tile means the file has none (#1791). The worker's in-process requests to the platform's own routes carry `viewerlimit.InProcess` on their context and are admitted by the public viewer's rate limiter without being counted: every one presents the loopback address, so counted they shared one bucket and a document drawn after it ran dry was recorded as not drawable although every file it names exists (#1791). A collection's mosaic of its first four drawn members is composed by the same renderer and redrawn when that signature (`thumbnail_source`) changes. The browser capture routes (`PUT` asset, admin asset, collection and resource thumbnail, and both `thumbnails/pending` lists) and the in-tab capture queue are gone. A JSX frame's policy grants the reference route to `font-src` as well as `img-src` and `connect-src`, so an `@font-face` rule naming a managed-resource font loads in the viewer and in the tile frame (#2062); a font the frame still could not load does not withhold the tile, since the page drew completely in its fallback face, while a failed image or data reference does. Migration 000182 clears the `file(s) this document links to could not be loaded` failures recorded before, on assets and resources, so those documents are drawn again. A document frame reports itself ready only once its styles are in (#2122): every stylesheet it names, including one a script added after load, has loaded or failed, its fonts have settled, and neither its styles nor its layout has changed for 400 ms, bounded at 6 s, which is what catches CSS written at run time such as the Tailwind Play CDN's. A JSX frame waits for its module to run, which is when every esm.sh module it imports has arrived, instead of a fixed two seconds. A public stylesheet or script the platform could not fetch for a reason that may pass (the network, a 429 or a 5xx) makes the attempt one that did not finish, counted as `thumbnail_render_failures_total{reason="subresource"}` and retried with backoff up to `max_attempts`, rather than a stored picture of unstyled text; one its server answers 404 is the document's own and is drawn without. The renderer keeps each public 200 answer it fetched for ten minutes (64 MB, oldest first, never one marked `no-store` or `private`), so a library of documents on one CDN does not fetch the same files for every tile. `thumbnails.allow_private_cidrs` names private prefixes a drawn document may load files from (an internal CDN); every other private, loopback, link-local and metadata address stays refused, and a prefix that does not parse stops the platform at start. The worker reads only due rows (#2084): `thumbnail_due_at` on resources, portal_assets and portal_collections is set by a trigger on every write the renderer did not make (and on a collection when a section, an item or a member's tile changes, migration 000189), a partial index holds only due rows, a pass takes rows owed nothing out of the due set a thousand at a time and claims from the rest, and a claim or hold writes its end time there. An idle claim over 500,000 rows reads one index page and no table row (about 2 ms). A changed owed rule (renderer generation, source bounds, drawable types) marks every row due once, 2,000 per statement under an advisory lock, recorded in `thumbnail_sweeps` (`internal/thumbdue`). A row becoming due notifies `thumbnail_due`, which wakes every replica's worker over LISTEN; an idle worker's wait doubles from `poll` to a minute. **On a phone (#2390).** Below 768px an asset's header actions are one row: Share (the owner's, when the persona allows sharing) stays a button and Download, Add to collection, Save to My Assets and Delete are in a More menu. Expand, on the row above the content, shows the content edge to edge inside the safe area with one bar (the asset's name and Close); it adds a history entry so the back gesture closes it, Esc closes it, the document's frame is not reloaded, and the address carries `?view=full`, so a link with it opens the asset expanded at any width. The share viewer (`/portal/view/{token}`) offers the same Expand in its header on a phone. The portal shell is sized in dvh with `viewport-fit=cover` and side safe-area insets. ## Collections Curated groups of assets organized into ordered sections with markdown descriptions. Grid/table list view with search, and the same ordering control as Assets minus size, which a collection does not have (`sort`, `dir` on `GET /api/v1/portal/collections`; same `updated_at DESC` default and same id tie-breaker). Collection viewer renders sections with markdown, asset cards with thumbnails, each in the reader's color mode: a collection item carries both capture keys and both capture versions out of the same join that populates its name and content type, so a tile asks for `variant=dark` exactly when a dark capture exists and carries the capture's version as its cache key, the same as an assets-grid card (#1468). The admin asset thumbnail route accepts the same `variant` parameter, since an administrator reading a collection someone else owns gets its tiles from there (#1292). The public share viewer's tiles are still light-only. Configurable thumbnail sizes (Large/Medium/Small/None). The knowledge pages that reference a collection are a Referenced by button to the left of Feedback in its header, with their count and a modal listing them (#1792); the prompt viewer, knowledge page detail, and glossary, domain and tag views keep the card. Sharing via links (token-based, time-limited, opening for signed-in users or, by explicit choice, for anyone) and user shares (email, Viewer/Editor permission, restricted to that recipient). Collection API endpoints: - CRUD: POST/GET/PUT/DELETE `/api/v1/portal/collections[/{id}]` - Sections: PUT `/api/v1/portal/collections/{id}/sections` (full replace) - Add one asset: POST `/api/v1/portal/collections/{id}/items` with `asset_id` and optional `section_id` (appends at the end of that section, or the last section, or a new untitled one; 409 for a duplicate, a full section or a stale section id), and POST `/api/v1/portal/collections` with `asset_id` for a new collection holding it (#2260) - Add-to-collection picker: GET `/api/v1/portal/assets/{id}/collection-targets` lists the collections the caller can edit, newest first, each with its sections and whether the asset is in each (`search` narrows); the asset viewer's **Add to collection** action reads it - Collection item sweep (#2752): with the retention sweeps, under its own advisory lock, every collection item its owner cannot open now is removed (an administrator's collection keeps everything); a grant through another collection's share counts only while that collection's own item stays, so two collections opening an asset only to each other lose it. The asset is untouched, the other items keep their order, and each removal is recorded in `portal_collection_item_removals` (collection, asset, time; no content). It runs in each process's first retention pass, as soon as it is added after the loop has started, so a replica restarted more often than `retention.every` still runs it (#2757). - Config: PUT `/api/v1/portal/collections/{id}/config` - Sharing: POST/GET `/api/v1/portal/collections/{id}/shares` - Shared with me: GET `/api/v1/portal/shared-collections` - Public view: GET `/portal/view/{token}` (branches on collection vs asset) Database tables: portal_collections, portal_collection_sections, portal_collection_items. portal_shares extended with collection_id (CHECK constraint: exactly one of asset_id/collection_id set). ## Views A view is a named set of filters over assets that keeps itself current (#2505): it stores the filters, not the assets, so an asset saved after the view was made appears in it without anyone editing it. Filters: scope (`mine`, `shared`, `all`, the default), query (ranked as asset search ranks), tags (every one), authors, status (`draft`, `published`, `deprecated`, `none`), verified, content types, collection (matching only when the person opening the view can open that collection), created and updated ranges (from inclusive, to exclusive), and built from: the connection and the table, API operation or path, or GraphQL field an asset's provenance names, read from `portal_asset_sources`, recorded as an asset is saved and as captures are appended and filled in for older assets by the `asset_sources` retention sweep (advisory lock 4713210112); a table matches as written or by its trailing dotted parts. A view also keeps a sort (`updated_at`, `created_at`, `name` or `size_bytes`, `:asc` or `:desc`, default `updated_at:desc`) and a layout (`grid`, `table`, `board_status`, `board_tag`). The further filters are also parameters on `GET /api/v1/portal/assets`, `/assets/search` and `/assets/facets`: `content_types`, `collection`, `created_from`, `created_to`, `updated_from`, `updated_to`, `source_connection`, `source_target`. A view is run for the person opening it under the listing's reach rule (`internal/portal/reachstore`), never with its owner's access: sharing it shares the definition (visible to its audience, filter values included) and grants nothing else, so each person sees the matching assets they can open and every count and board column counts only those. The owner or an administrator shares a view with a person (user id or address), a persona, or everyone signed in, which leaves out people whose persona is external (a guest gets a view only through a share to their persona or address, as a viewer, and creates none), as viewer (read and run) or editor (also change name, description, filters, sort and layout); sharing the same audience again replaces its permission; only the owner or an administrator lists shares, stops one or deletes the view; a persona withholding sharing shares no views. Routes: `GET`/`POST /api/v1/portal/views` (an owner's rows carry their active `shares`), `GET`/`PATCH`/`DELETE /api/v1/portal/views/{id}`, `GET /api/v1/portal/views/{id}/run` (`limit` default 50, at most 200, `offset`; rows as the listing returns them with `groups.statuses` and `groups.tags`), `GET`/`POST /api/v1/portal/views/{id}/shares` and `DELETE /api/v1/portal/views/{id}/shares/{shareId}`. A view can be starred (`PUT /api/v1/portal/favorites/view/{id}`) and recorded in Recent, and drops out of both when it is no longer shared with the person. `manage_asset list_views` lists the caller's views and `run_view` (`view_id`, `limit`, `offset`) returns the rows and counts the portal shows that person; the draft write barrier classifies both as reads. Portal: the Views tab beside Assets and Collections (Mine, Shared with me, New view; Save as view on the Assets tab), a view in grid, table or a board by status or tag, Edit filters for an owner or editor, read-only filters and Duplicate for a viewer, and Share. ## Resources Human-uploaded reference materials (SQL templates, runbooks, checklists) accessible to AI via MCP resources/read. FILE MANAGER SEARCH (#2293): the Search box searches every library the caller can read (no scope sent; GET /api/v1/resources?q= with no scope does the same, an administrator's spanning every library), unless This folder only (within=1 in the address) keeps it in the open folder and beneath it; q matches display_name, description, path, filename and tags (buildScopeWhere), and each hit shows its library and folder with Show in folder. FILE SHARES (#2258): a file is shared like an asset, through portal_shares.resource_id (migration 000217, one target per share, cascading on delete): Share on a file's page names a person by address or a persona as viewer or editor (an editor renames, edits details, writes new versions and may register a table over it through tablesource.ResourceSubjectShared; moving and deleting stay CanModifyResource's), an external person opens any share as viewer, sharing needs CanModifyResource and a persona that allows sharing (an external person may share their own upload only with someone who shared with them), a grant's permission changes in place through PATCH /api/v1/resources/{id}/shares/{shareID} (#2291), Post to a channel posts the file's page link through the notify tool's send action with access authenticated (a link share any signed-in internal person opens, origin channel_post, withdrawn if the post fails) or existing (no share), Upload and share uploads to the caller's own folder and opens the share dialog, Shared with me is a top-level folder listing GET /api/v1/resources/shared-with-me, and Request access on a file one cannot open asks its uploader (access_requests target_type resource). The resources API's claims carry Claims.Shared, the caller's share lookup. An external persona's `portal.uploads` lets its people upload to their own folder, each upload shared on arrival with the personas and addresses named. A person of an external persona has no Global folder (Claims.NoGlobal). GLOBAL FOLDER WRITE GRANTS (#2684): an administrator grants a person (by address) or a persona write on a Global folder and every folder beneath it by segment (resource.PathUnder; its SQL form resource.UnderSQL), stored as a folder share (portal_shares.folder_path, migration 000256, editor only). Every write check reads resource.CanWriteFolder (CanWriteScope or a grant covering the path; the upload route, manage_resource, an upload link and a script export), CanModifyResource reads it at the file's folder, a new, deleted or moved folder needs write at its parent folder (so the granted folder itself is an administrator's, and an empty stored folder is no longer renamable by any reader), a move inside Global needs a grant at the destination, and a script run reads its author's grants. Grants are read lazily once per request (Claims.WithFolderGrants from the source internal/httpserver/foldergrantwire installs), matched against every persona the caller's roles reach, read again when an upload link's file arrives (the link keeps NoGlobal), ignored for NoGlobal and for any external persona, never override the persona's Resources level, follow the folder through MoveFolderTree and go with DeleteFolder in the same transaction. Admin routes GET|POST /api/v1/admin/resources/folder-grants (folder; email or persona; refuses an external person or persona, a missing folder and a duplicate) and DELETE .../{id}, audited folder_grant_add and folder_grant_remove; GET /api/v1/resources/folder-grants/mine is the caller's own folders. A refusal names the folders the caller can write. The page is a FILE MANAGER (#1872): a folder tree on the left whose top-level folders are My Resources, Shared with me, Global and each persona the caller can read (a platform administrator adds People, one folder per person from `GET /api/v1/resources/people`), a path bar with Back/Forward/Up and clickable segments that take a drop, one listing of the folder in view (folders first, then files; Name/Modified/Size sort on the server through `sort=name|name_desc|updated|updated_asc|size|size_desc`; rows or tiles), a preview pane (one file: thumbnail, description, location as `/Global/data/weekly`, size, modified, uploader, URI, tags, with Open/Download/Copy URI; several: count, total size, bulk actions; nothing: the folder), and a status line. A folder opens on click and a file is selected and previewed, opening on double-click or Enter (the stated exception to the portal's row-click rule). Click, Shift-click, Cmd/Ctrl-click, Cmd/Ctrl-A and Escape select; the selection bar offers Move to, Tag and Delete, each reporting per file; rows dragged onto a folder row, a tree node or a path segment move there with Undo on the toast; files dropped from the desktop upload there; right-click offers Open, Rename, Move to, Tag, Copy URI, Delete, and New folder and Upload here on empty space; F2 renames inline; the tree follows the WAI-ARIA tree pattern. The page never says "library". A file's tile is a PNG the platform's renderer drew and stored beside it, in the reader's own colour scheme where the family carries two; a type nothing draws keeps its content-type icon. A file's own page carries a Thumbnail panel showing that tile, or the reason the renderer gave for not drawing it, with a Recapture control, for whoever may change the file. The scope tab in view is the upload's destination, and the dialog states it before a file is chosen (#1444). `ui/src/pages/resources/scopes.ts` mirrors `resource.CanWriteScope` in the browser — own user scope always, persona scope with a `persona-admin:{name}` role (the name cut out of the role, so any identity-provider prefix works) — and the page renders Upload, in the filter bar and in the empty state, only on a tab that check passes. Where it does not, a note in the control's place names who publishes that library. On All, both upload dialogs name the persona library the caller belongs to and cannot upload into (`withheldUploadPersonas`), the `persona-admin:{name}` role that grants it, and the move (Edit details > Library) that membership does allow (#1866). A persona admin therefore adds to their persona's library from the user page, not only from the admin page, which keeps its scope picker and its persona and per-user fan-out. The platform-admin override is the identity's, not a section's (#1527). `canWriteScope`, `moveTargets` and `libraryOptions` read the caller and nothing else: a platform admin is offered Upload on every scope tab and every move target — their own library, every persona, Global, and a named person's library — on the portal Resources page and in Admin > Resources alike, which is what `CanWriteScope` and `canMoveToLibrary` have always granted the same caller whatever route the request arrived on. The `Surface = "portal" | "admin"` parameter those three took, and the `adminReachNote` sentence that pointed an administrator at Admin > Resources in the withheld control's place, are removed rather than defaulted: a parameter whose only remaining value is `"admin"` is a seam the behavior grows back on. The portal enables the `usePersonas` fetch for a platform administrator so the picker offers the deployment's personas and not only the ones their own claims name; everyone else's personas stay claims-derived, and `moveTargets` offers a non-admin nothing out of a list it is handed. `ResourceViewerPage` reads Edit and Delete the same way — `CanModifyResource`'s two arms, the uploader and `canWriteScope` over the library the file is in — instead of the section it was mounted in, which had left an administrator on the portal with no Edit button on a file they did not upload. A blob store that refuses the write now answers 503 with what happened and that nothing was saved, rather than the fragment "storing file" that `writeError`'s colon truncation left of the internal chain — a storage outage read, to the person who hit it, as a refusal of permission. Resources are also discoverable through the universal `search` (#1012). An indexjobs consumer (`internal/platform/resourceindex`, source_kind `resources`) embeds each resource's metadata plus a bounded text prefix (32 KiB) read from its S3 blob for text-family MIME types (classified by `pkg/contenttype`), for a resource under the `full` index policy; under `metadata` the vector is built from the metadata alone and no content is read or kept, and under `none` there is no index job at all (#2111, below); the vector, the model/text-hash breadcrumbs, and the extracted `content_text` live inline on the `resources` row (migration 000091), so a DELETE removes the index entry with the resource. The request-path metadata Update clears the vector and enqueues the row's own index job (trigger `write`, #1256), as do the create and content-revision paths, so a just-uploaded or just-edited resource is re-indexed within one embed rather than on the next sweep; the reconciler stays the backstop for what a write could not produce. `content_indexed_at` is a second, independent gap signal: the consumer stamps it only once it has extracted the text or established there is nothing to extract, so a transient blob failure (which still yields a valid metadata-only embedding) leaves the row in `FindGaps` and the next sweep retries, instead of the job succeeding and the file's contents never being indexed while coverage read 100%. Coverage counts a resource indexed only when both signals are settled. Content extraction needs the index queue (database + configured embedding provider); an object over 8 MB is indexed on metadata alone, since the blob API has no range read and the whole object would be held in memory to keep 32 KiB of it. A transient blob failure keeps the previously extracted text; a confirmed missing object clears it and indexes metadata only (the row is pruned only by the read path's orphan self-heal). The by-id REST handlers (get, content, patch, delete) gate on `resource.CanAccessResource` (visible scopes OR current write authority over the scope — deliberately not `CanModifyResource`, whose uploader clause would outlive the role that authorized the upload), so a platform admin can manage a persona resource they uploaded rather than being 404'd on material `CanWriteScope` let them create; ENUMERATION stays membership-scoped via `CanReadResource` (a listing and the ranked search hand a caller material they did not name), while a file the caller NAMES is answered on `CanAccessResource` wherever it is named -- the by-id routes, an asset reference declaration, and `fetch` on an `mcp:resource:` reference (#1584). `resources/read` remains membership-scoped. Search hits carry `mcp:resource:` plus an MCP resource link with the canonical `mcp://` URI; `fetch` on that reference returns text contents inline (at or under the 1 MB threshold shared with the MCP read path) or metadata with the URI, MIME type, and size. SEARCH INDEXING POLICY (#2111). Every managed resource carries `index_policy` (`full`, `metadata`, `none`) and `index_policy_explicit` (a writer chose it) on its row (migration 000193, which also set every existing CSV/TSV/NDJSON resource to `metadata` (the text such a row still keeps is cleared by a reclassification) and added `description`, `summary_text` and an embedding to `resource_folders`). The writer decides first: `manage_resource` `index` (create, replace_content, update, extract), the upload form and REST create/replace `index` field, `PATCH /api/v1/resources/{id}` `index`, `platform.export(..., index=)` for a "resources" output, a resource destination's `index`, and a webhook source's `config.index`. A writer that says nothing gets the default the operator's `resources.index` section gives the file (internal/indexpolicy): `default` (full unless set) and ordered `rules`, each matching on `path` (slash glob, `**` any depth), `mime` (exact or `type/*`), `size_over` (`1MiB`, `500KB`, bytes), `scope` (global, persona, user) and `origin` (upload, agent, script, export, webhook), every set matcher holding; the first matching rule with `index` decides the default and the first matching rule with `max` caps what a writer may ask for. Built-in rules follow the operator's: CSV, TSV and JSON-lines default to `metadata`. Being written by a script decides nothing by itself; `origin` is only a matcher. `none` means no index job, no blob read, no kept text and no vector; the file is still listed, fetched, versioned and referenced, and lexical/semantic search excludes it. A folder holding files that are not indexed one by one is indexed as one entry (index kind `resource_folders`, key scope/scope_id/path): its path, file count, media types, date range, a few file names and its description, written by `PUT /api/v1/resources/folders/description` (GET reads it), the file manager's Describe... action, or `manage_resource` `update` with `path` and `description` and no reference; writing a description empties the stored summary so the reconciler re-embeds the entry within one sweep even when the enqueue met a running job; folder search unions a vector arm and a lexical arm over path, description and summary, as file search does; search and the knowledge read path return folder hits. Rules apply when a file is written; `POST /api/v1/admin/resources/index/reclassify` (202, 409 while running) applies them again to every resource no writer chose for, in batches of 500 under an advisory lock, dropping the vector and kept text of each that changed and clearing the text of any no longer under `full`; `GET /api/v1/admin/resources/index` reports counts per policy, `explicit`, `content_bytes`, `folders` and the last run, which every replica reports alike (table `resource_reclassify_runs`; a start is refused with 409 while one runs on any replica, and a run unfinished after an hour is taken to have stopped). The admin Indexing page shows them under Resource search with a Reclassify button; the portal shows the setting as a field named Search with options Default, Contents, Details only and Not indexed. A RESOURCE'S SOURCE IS EDITABLE IN THE PORTAL (#1775). A text family the viewer can show as source carries a Preview/Source switch and a Save above its content for a reader who may change the file -- `ViewModeToggle`, `SaveControls` and `SourceEditor` imported from the asset viewer rather than rewritten, so the two surfaces cannot drift. A save posts the edited text through the SAME `POST /api/v1/resources/{id}/content` route the file picker uses, so it records a version, keeps the id, URI and filename, and carries the server-side validation; it sends `change_summary: "edited in the portal"`, which that route now reads (it had the field on `RevisionUpload` for the correction a table registration saves and sent an empty one whatever the caller passed), so Version history tells an edit from a file picked off disk. The switch is withheld from a reader who may not change the file, from a family that is not text, and from a file past the inline preview limit. Until this a resource was VIEW-ONLY in the portal and the only control named Edit opened the metadata dialog, so somebody looking at their own CSV pressed it and could not touch the contents; that button is now named Edit details. A resource's content is revisable in place (#1014). `POST /api/v1/resources/{id}/content` uploads a replacement that keeps the resource's id, canonical URI, and filename — so every `mcp:resource:` citation and prompt attachment keeps resolving, which delete-plus-re-upload breaks by minting a new id — and the uploaded file's own name is therefore ignored. Each revision writes a `resource_versions` row (version number assigned inside the insert transaction, uploader, timestamp, size, MIME type, and its own per-revision S3 key) and moves the head in the same transaction, so the trail and the live content can never disagree; migration 000092 backfills every existing resource as version 1 pointing at its current blob, copying nothing. `GET .../versions` lists the trail with the version the head serves, `GET .../versions/{n}/content` downloads one, and `POST .../versions/{n}/restore` re-promotes a prior version's exact bytes as a NEW head revision (recorded with `restored_from`) rather than rewinding, so history stays append-only. A revision written on the uploader's behalf records why (`change_summary`, migration 000123, #1450) and the version panel renders it beneath the row -- the same thing `portal_asset_versions.change_summary` has carried since 000022, so a corrected managed resource and a corrected portal asset say the same thing in their histories rather than the resource's correction reading as an upload. Retention is bounded by `resources.managed.max_versions` (default 10): a revision past the cap deletes the oldest version rows and their S3 objects, never the key the head points at. A revision clears `content_text`, `content_indexed_at`, and the embedding and enqueues the resource's index job so the new bytes are re-indexed within one embed rather than on the next sweep, and fires `resources/list_changed`. Deleting a resource removes every version's blob (the rows cascade). Reads are audited (#1014). Content served through any of the four doors — MCP `resources/read` (`mcp_read`), a `search` fetch of an `mcp:resource:` reference (`fetch`), a REST content download (`rest_download`), or the portal drawing an image tile in the resource library (`portal_preview`) — writes one `resource_read` audit event (`resource_id`, `resource_uri`, `surface`, and `version` when a specific revision was named) through one shared recorder (`internal/platform/resourceaudit`), gated by `audit.enabled`; listing is not a read, and a read that could not be served records nothing. The same recorder stamps `resources.last_read_at`, which is what `GET /api/v1/resources?sort=last_read` orders on (`DESC NULLS LAST`, so never-read material sorts last) and what outlives the audit retention window. `GET /api/v1/resources/{id}` carries a `usage` object aggregated from those events by the audit store (`ResourceUsage`, backed by a partial expression index on `(parameters->>'resource_id') WHERE event_kind = 'resource_read'`): reads over 30 and 90 days, a per-surface 30-day breakdown, and the last read the rollup saw. The portal detail view renders version history (with download and restore), the usage panel, and the prompts attaching the resource; the admin table adds a Last read column, a Recently read sort, and a flag on anything never read since it was uploaded over 30 days ago. A resource can be MOVED to another library after it is uploaded (#1502). The library was chosen once on the upload form and never again, so the only route from a personal library to a shared one was to upload the file a second time -- a second id, a second URI, a second blob, two separate version trails, and every asset and prompt still referencing the first. `Library` on the Edit dialog rewrites `scope`, `scope_id` and `uri` on the row instead; the S3 key is a stored column that nothing recomputes on read, so the blob stays where it is and the version trail, table registration and read history are untouched. `resource.canMoveToLibrary` is the destination check and is looser than `CanWriteScope` on exactly ONE arm: a persona you BELONG to accepts a file you already own, while uploading into it still takes `persona-admin:{name}`. Widening `CanWriteScope` itself would have been the smaller diff and the wrong one -- it is what the upload route checks and what the Resources page derives its Upload control and scope tabs from, so every member of every persona would have gained an upload door nobody asked to open. Global and another person's library stay `CanWriteScope`'s, so an administrator reaches every target and nobody else reaches those two. The move travels on the update route (`PATCH /api/v1/resources/{id}` carrying `scope`/`scope_id`) because the permission check it needs -- `CanModifyResource` on the resource itself -- is the one that route already runs, and it runs BEFORE any metadata edit in the same request so a refused move cannot leave half of it committed. A move to the library the file is already in writes nothing and audits nothing, so an idempotent PATCH neither fails nor reads as a refile. THE URI FOLLOWS THE FILE, AND THE ADDRESS IT LEAVES KEEPS RESOLVING. `RelocatedURI` composes the target library's prefix, the target folder path and the filename off the stored URI, so a rewrite that changes one half leaves the other exactly as it was; a URI that will not parse falls back to the row's own filename. A folder edit takes the same path as a library move (#1528): `Update.Path` is not metadata, `buildUpdate` writes no `path` column, and `applyMove` in the handler resolves whichever halves the request named against the row's current values into ONE `Destination`, so a library and a folder changed in the same PATCH produce one URI carrying both, one alias for the one address vacated, and one audit event. The no-op test compares the composed URI as well as the two columns, so a row whose stored URI disagreed with its folder -- which every category edit before #1528 produced -- is repaired by saving the folder it already shows. `resource_uri_aliases` (migration 000129, `uri` PRIMARY KEY, `resource_id` ON DELETE CASCADE) records every address a resource has vacated, written in the SAME transaction as the row -- the new address and the alias for the old one are one fact stated twice, and a commit carrying only the first leaves every citation dangling. `GetByURI` tries the live column first and the alias table second, so an alias can never shadow whichever resource occupies that address NOW: a person who moves a file out and uploads another under the same name reaches the new one by its own URI. The move also DELETES any alias equal to the address it is taking, so moving a file back where it came from leaves no row claiming its own current URI. The collision pre-check tells a live occupant from an alias by comparing the hit's own `URI` against the address asked for, and names the occupant in the refusal (the mover cannot see the other library, so "that address is taken" alone is an error they can do nothing about); the store additionally maps a UNIQUE violation, at exec or at commit, to `ErrURIConflict`, since the pre-check and the write are not atomic. Reference and attachment rows are NOT touched: `portal_asset_resource_refs` and `prompt_resource_attachments` key on `resource_id`, and the serve-time rewrite matches the URI string recorded on the reference row -- which is what the author wrote and stays what they wrote -- so a declaring asset and an attaching prompt both keep serving the file, proven end to end over the real PATCH route, the real reference-serving route and the real attachment resolver rather than by asserting a store call. The MCP registry IS keyed on the URI, so a move withdraws the old one and registers the new. Each move writes a `resource_move` audit event (`resource_id`, `display_name`, and `from_scope`/`from_scope_id`/`from_path`/`from_uri`/`to_scope`/`to_scope_id`/`to_path`/`to_uri`) through the same `internal/platform/resourceaudit` recorder reads go through; the "from" side is snapshotted BEFORE the write, since a store is free to hand back the same `*Resource` it then mutates. `ui/src/pages/resources/scopes.ts` mirrors the rule in the browser through `moveTargets`/`libraryOptions`, withholding the platform-admin override on the portal surface exactly as `canWriteScope` does, and offering the current library even when the caller could not move it there, because leaving the file where it is has to be expressible; the field is absent entirely when there is nowhere else to put it. There is no MCP action: `manage_resource` creates and replaces content, and deciding that a file becomes a persona's or the platform's is a human act. A FOLDER VIEW LISTS ITS OWN LEVEL (#1837). The listing for a folder used to be the folder and everything beneath it, paged in the view's sort order, with the page then filtering to the files whose path is exactly this folder; the footer reported the fetched row count and the subtree total. A `brand` folder whose four subfolders held 2,528 files showed four folder tiles, no files, a Load more, and `Showing 146 of 2541 resources`: 146 poster rows fetched, none on screen, and Load more fetching more rows to hide. `GET /api/v1/resources?path=&direct=true` (`Filter.Direct`, a single `path = $n` equality in place of the `path = $n OR path LIKE $n+1` subtree arm) lists only the files filed at that path, and the portal's folder view always asks for it (`listingFor` in `useResourceLibrary.ts`), so the page, its total and Load more all describe the files on screen; the subfolders and their counts come from the facets as before. A search and a tag at a library root still list flat across the library. Without `direct` the route answers the subtree, which is what a folder move plans over. RENAMING A FOLDER IS ONE TRANSACTION OVER THE WHOLE SUBTREE (#1529). `Store.Move` takes a BATCH of relocations rather than one, because a half-renamed folder is not a state anyone should be able to observe; `MoveFolder` (`pkg/resource/folder.go`) lists every resource beneath the prefix, refuses the whole move if the caller may not modify one of them (403) or if a destination address is occupied (409, naming the occupant) or if the target is inside the folder being moved, and hands the store one batch. A multi-row batch VACATES every address before taking any: renaming `a/b` to `a` hands one resource an address another in the same batch still holds, and the UNIQUE constraint on `uri` is not deferrable, so the rows are parked on a sentinel derived from their own primary key first and the statement order stops mattering. One rename covers at most `MaxFolderMoveResources` (500) resources and is REFUSED with its true count past that rather than moving part of the subtree. `POST /api/v1/resources/folders/move` is the route; the MCP registry is keyed on the URI, so every vacated address is withdrawn and every new one registered from the row as stored. The folder path is part of `IndexText`, so `applyMove` drops the embedding only for a row whose path actually changed -- compared by the database against the stored value, since a library-only move changes no indexed text. `scopeLabel` now takes the reader, because a user library is only "My Resources" to the person it belongs to and the admin section lists every library at once -- a library keyed by address is named by that address, one keyed by a subject identifier is described rather than printed. ## Shared With Me Items shared by other users appear in the corresponding pages, filtered by ownership scope: the Assets and Collections pages each have a Mine / Shared / All scope control (shared items show sharer email and permission level), and the Prompts page has a Shared tab (shared prompts are runnable over MCP as shared-). ## Share landing page and guest links (#1001) A refused `/portal/view/{token}` browser navigation renders a branded landing page instead of bare text: sign-in with a return path for account holders; for a signed-in caller who is not the recipient, a page naming the signed-in account with a sign-out-and-switch action; a branded 410 for revoked/expired. When the share names an email address, the landing page also offers "Email me a one-time view link" for recipients with no platform account: POST `/portal/view/{token}/request-link` (uniform response regardless of share state, per-IP rate limit plus a per-share hourly cap) emails a single-use link only to the stored `shared_with_email`. The link (GET `/portal/view/{token}/guest?otk=...`) is claimed atomically (SHA-256 hash at rest in `portal_share_guest_links`, 15-minute expiry, dead after first use, so forwarding transfers nothing) and opens a view-only guest session: an HMAC-signed browser-session cookie scoped to that one share (key domain-separated from the browser-session signing key), rendered in the public viewer with a "Viewing as guest" indicator, download allowed, no editing even on Editor shares, no auto-promotion, no portal or API access. Revoking the share refuses existing guest sessions immediately. Same flow covers collection shares and their item routes. Subresource and API-style refusals stay plain-status. (`pkg/portal/shareguest`) ## Feedback Structured feedback from reviewers (including non-agent subject-matter experts and stakeholders) on shared work, replacing email round-trips. An item's feedback panel sits beside the item, or under it below 1024px, with nothing over the item: a document scrolls and a deck pages while feedback is written, and the arrow keys page a deck unless the cursor is in a text box (#2583). Built on a generic thread substrate (`portal_threads` + `portal_thread_events`) where a comment is one event type among many, so later thread kinds slot in with no schema churn. A thread targets one asset, collection, prompt, or knowledge page (mirroring the `portal_shares` 1-of-N polymorphism, enforced by a CHECK constraint) or lives on a standalone channel; it carries a kind (comment, question, correction, rating, approval, rejection, suggestion), a status (open, answered, resolved, wont_fix, acknowledged), an optional requires_resolution flag, an optional inline anchor (JSONB, e.g. a W3C-style text-quote or a collection section) plus the target_version it was raised against, and a typed event timeline (comment, status_change, resolution, rating, approval, rejection, and the Phase 2 knowledge-link events). A status change records a timeline event in the same transaction so the timeline never shows a status with no event. Standalone threads are visible to any authenticated user; object threads follow the target's existing view access; knowledge pages are org-shared, so any authenticated user can read and add feedback on them. Moderation (status change, delete) is allowed for the thread author, the target owner/editor (for knowledge pages, an apply_knowledge holder), or an admin. When an anonymous viewer opens a public share link, they see a "Sign in to leave feedback" prompt; signing in, when they have no prior share for the item, auto-creates a viewer share (`origin=public_link_login`) so the item appears in their portal, and never downgrades an existing editor. A signed-in platform user who can open the target in the portal (its owner, a holder of an active share, or one the derived share just granted) AND whom the portal application would actually serve (the deployment carries a frontend build and the shell gate admits their roles, both answered by the composition root through one seam so the redirect and the page it lands on cannot disagree) is sent there instead of being shown the public page, carrying the token so the portal viewer offers a Shared page action back to the page its recipient sees; a promotion that failed, an account no persona claims, a deployment serving no portal application, a guest holding a one-time link, and an anonymous reader all get the public page unchanged. REST under `/api/v1/portal/threads` (GET list scoped to one target, POST create, GET/PATCH/DELETE by id, GET/POST `/events`) plus `GET /api/v1/portal/threads/counts` for list-page open-thread badges, owner-scoped for assets/collections (a non-admin receives counts only for objects they own) but open to all for org-shared knowledge pages, and `POST /api/v1/portal/threads/{id}/insight` to capture a correction/suggestion thread as a pending, knowledge-dimension insight (requires apply_knowledge) that enters the review queue and links/resolves the source thread via the existing insight bridge. List rows carry timeline aggregates (event_count, last_event_at, last_event_type) so the panel renders activity without an N+1 fan-out. Humans author and triage feedback through a portal panel: a non-modal slide-out drawer mounted in the asset, collection, prompt, and knowledge-page viewers, plus a full-width Inbox page in the sidebar (named Feedback until #1798). The drawer lists threads with kind/status/activity, supports a new-thread form (kind, requires_resolution, rating, optional text-quote anchor captured from a markdown/plain-text selection), threaded replies, and owner/editor/admin status changes and deletion. The Inbox has four views: Recent (the cross-target activity feed, each row linking to its item and opening the thread in a right slide-over with a "Go to item" link), Worklist (the practitioner, SME and mentions worklists, selected by chips rather than a second tab strip), General (the standalone channel), and Notifications (the history of what the platform has emailed the caller, read from `GET /api/v1/portal/notifications`, which used to be a card on /settings beside the preferences that decide what gets sent; the preferences stay there). The page returns flowing content with no scroll region of its own -- `main` is the one scroll container, as on every other portal page (#1798). The sidebar's Inbox item carries a badge of the caller's open worklist count as a stand-in for push notifications. My Assets and Collections show an owner-scoped open-thread badge per item. On a phone the panel is a sheet under the item (#2705): 60% of the screen by default and full screen below the top bar from its handle or header arrow, the size kept between threads; an open thread's row replaces the panel header with visibility and Delete thread under More; the thread scrolls as one surface with Capture as insight after the comments, and the reply box is one Reply… row until tapped, keeping the reply, its buttons and the last lines of the answered comment on screen with the keyboard open. ## Knowledge The single home for the Memory to Insight to Knowledge lifecycle (formerly the separate Knowledge Pages, Knowledge & Memory, and admin Knowledge & Memory routes, which now redirect here). A header teaches the model: everything learned is a Memory; a memory others would benefit from becomes an Insight (a proposal awaiting review); whoever holds the `apply_knowledge` capability promotes good insights into Knowledge (business/domain facts become knowledge pages, technical/entity facts go to the catalog). Three tabs, with review/promote affordances gated on the `apply_knowledge` tool (a capability, not an admin role). Knowledge (default): unified search across every accessible source grouped by source with a coverage summary (the same federation as the `search` tool, over `GET /api/v1/portal/search`); with an empty query, browse of canonical knowledge pages (create/edit/remove for `apply_knowledge` holders; the platform's own built-in pages sit in the same corpus — reconciled from the binary at startup, badged Built-in, read-only where people edit, hidable per deployment with the hide respected across upgrades and reversible via the Knowledge list's Restore built-in / POST /api/v1/portal/knowledge-pages/restore-builtin) in either of two layouts, a card list or an interactive graph of the corpus (#1162) where every page and every entity a page references is a typed node and every stored reference is a directed edge. The graph is exploratory rather than a whole-corpus hairball: it opens on the corpus's strongest bridge and its neighborhood, with a hops control to widen it and a whole-corpus overview on demand. It is analysed, not merely drawn - Louvain community detection partitions the corpus into clusters (tinted as regions in the overview, with a clustering force separating them, and reported with the partition's modularity) and betweenness centrality scores each node for how much of the graph it bridges, which sets node size and is reported per node with its percentile. Clicking a node opens a side inspector (references in each direction, bridge score and rank, cluster, the reference's URN, selectable neighbor lists) rather than navigating away; its actions are focus, expand, shortest-path tracing between any two nodes, and open. Selecting a catalog node resolves it against the platform catalog and reports what is there (description, domain, owners, tags), or states plainly that the cited dataset is not in that catalog - a page citing a dataset the catalog does not have is surfaced as the gap it is. Which of the two it is comes from the read itself, a 404 for a reference the catalog does not hold (#1610), so a dataset the catalog holds and nobody has documented reads as held rather than as missing. Catalog entities are URL-addressable at /knowledge/catalog?ref=..., which is where a catalog reference links from anywhere in the portal. Plus hover neighborhood highlighting, node drag with pinning, pan/zoom, type and tag filters, and search-as-focus; the graph read is `GET /api/v1/portal/knowledge-pages/graph`, access-filtered so an entity the viewer cannot see has neither node nor edge, and explicitly reporting any node/page cap instead of truncating silently; and for `apply_knowledge` holders the changesets (the record of insights promoted into knowledge, with rollback) since a changeset is created only at apply time and belongs with the promoted knowledge, not the unpromoted insights. Insights: the review pipeline only (insights are the one memory type that crosses between users, and they cross when applied) - your captured insights with status and relevance search, plus for `apply_knowledge` holders the full review queue (approve/reject); a pending-review count is badged on the sidebar Knowledge item and the Insights tab. Memory: personal, scoped to your own records (the cross-user unit is the insight), classified by lifecycle class (`sink_class`: Preference, Event, Business knowledge, Operational rule, Schema/entity). The Knowledge tab also has a Catalog sub-tab (#1194, #1921), a first-class route at `/knowledge/catalog` over the platform catalog, shown to a reader whose persona grants `fetch` (editing takes `apply_knowledge`). Its inner tabs are Tables, Glossary, Tags, Domains and Data products, the inner tab in the URL hash and an open entity in `?ref=` (a catalog reference links to the tab that manages its kind; each tab claims only its own kinds, and going back or switching tab drops the `?ref=`). Tables searches the datasets of every connection the persona reaches and opens the dataset page (description, tags, glossary terms, owners, domain, properties, editable columns, context documents, lineage, schema document, citing knowledge pages, history with Roll back); Glossary lists the top of the glossary or every entry matching a filter, a node's page listing and adding entries and a term's page listing its carriers; Tags, Domains and Data products list, describe, create and delete their definitions, a definition still in use refused with what uses it. Tags, glossary terms and domains are picked by name; a tag may be a new name. The routes are under `/api/v1/portal/catalog` (see Platform Catalog). The knowledge-page manual-reference picker searches glossary terms, tags and domains by name from the catalog and stores the definition's reference, offered only to a reader who may read the catalog; a stored reference renders with the name the catalog reports. Each dataset and definition page lists the knowledge pages that reference it, through the existing `GET /api/v1/portal/knowledge-pages/backlinks?urn=` reverse lookup. ## Prompts The organization's prompt library, presented as two buckets (#1010, #1124): My Prompts (every prompt the caller owns at any scope — shared scopes carry a scope badge — plus prompts shared with them, each attributed to its sharer; never another owner's personal prompt) and Library (the approved shared prompts visible to the caller). Both buckets are browsed grouped by collection, each group headed by the collection name, its prompt count, and the collection description beneath it; only search results are flat, holding their relevance order. The scope taxonomy (global/persona/personal) appears only inside the promote and admin flows, never in the user-facing library. Collections are named groups organizing the library by team, domain, or workflow (`prompt_collections` table; a prompt belongs to at most one via `prompts.collection_id`, released to the default General group when its collection is deleted). Any user creates collections; renaming/deleting is creator-or-admin; assignment follows the prompt's own mutation rule (owner for personal, admin for shared) and is organizational metadata: it never versions or triggers review. REST: `GET/POST /api/v1/portal/prompt-collections`, `PUT/DELETE /api/v1/portal/prompt-collections/{id}`, `PUT /api/v1/portal/prompts/{id}/collection` (admin-prefixed equivalents exist); agents assign with `manage_prompt` `collection_id` on create/update (an id from the `collections` array list returns; empty string clears; collections themselves are created in the portal). Facets narrow by collection, tag, status (My Prompts), owner (Library), and usage; rows show run count and last-run age with sorts by name, runs, and last run, and dead prompts carry a badge naming the exact usage condition ("never run" or "unused 60d+"; a prompt created within the last week carries no flag). Search ranks prompts by relevance to a phrase (semantic vector similarity when an embedding provider is configured, keyword fallback otherwise) across the caller's full visibility, best-first; browse mode keeps sortable columns. The same ranking backs the MCP tool `manage_prompt list query=...`. Every enabled prompt is embedded off the request path by the shared index-jobs framework (source_kind `prompts`) regardless of lifecycle status, since visibility is decided at query time; editing a prompt's title, description, body, or tags clears its vector so it re-embeds against the new text. Visibility is applied before ranking, so a prompt you cannot read is never returned, and it is the same rule browsing applies (#1124), so a prompt visible in a list is findable by search: an admin ranks across everything (any owner, any status); a non-admin ranks over approved global prompts, approved matching-persona prompts, and every prompt they own at any scope and status — the publication gate applies to other people's shared prompts, never to your own work. Sortable columns, expandable rows with full content and copy button. Scope badges: Personal, Global, Persona, System. Lifecycle status badge (draft, approved, deprecated, superseded) and comma-separated tags on create/edit. An admin creating a global or persona prompt is its approver: the prompt lands approved with the stamp set (#1124), on both the admin REST API and `manage_prompt`; personal creates stay draft and publish through the promotion flow. Request Promotion on a personal prompt asks an admin to promote it to a chosen persona or to global; the prompt stays personal with a "Promotion requested" badge until an admin approves or rejects it. Share sends a personal prompt directly to another user by email (owner-initiated, no approval): the recipient gets a real runnable prompt, not a markdown snapshot, and it appears in the Prompts page's My Prompts bucket with a shared-by attribution. Personal prompt names are unique per owner; when served over MCP, names carry a scope prefix computed at serve time: `personal-`, `-` (one per persona), `global-`, or `shared-` for prompts shared with the caller, keeping the surface collision-free by construction; every descriptor carries a `title` from display_name. Users never need machine names: agents resolve any handle (stored name, display name, `mcp:prompt:`, or free text) to a ready-to-run prompt with the `manage_prompt` `use` command, which returns rendered content, argument specs, and provenance (including version, approver, and approval time), or ranked candidates when ambiguous. Every database prompt is versioned (#1009): each mutation of content, display name, description, arguments, or tags snapshots an immutable `prompt_versions` row with its author, and approval stamps bind to the specific version approved (approving v5 never alters v4's recorded approval). Editing the content or arguments of an approved global or persona prompt does not change what is served: the edit lands as a pending draft version (manage_prompt update returns status pending_approval; a gated content edit cannot be combined with scope/status changes in one call) and the approved snapshot keeps serving until an admin approves the draft via `POST /api/v1/admin/prompts/{id}/versions/{version}/approve` (reject with `.../reject`; full history with author and content via `GET /api/v1/admin/prompts/{id}/versions`; `GET /api/v1/portal/prompts/{id}/versions` serves history to any caller who can view the prompt (own personal prompts and enabled shared prompts), since history is the library's verification surface; non-admin viewers of a shared prompt get the served history only: applied snapshots in full, the pending draft as a content-redacted stub, and rejected/superseded drafts omitted). The portal prompt page renders this history with per-version approval provenance, flags a pending draft (readers keep being served the approved version), and diffs any version against the current content as a line diff; it also shows point-of-use invocation help (a copyable natural-language invocation built from the stable name and required arguments, resolved by agents via `manage_prompt use`). Metadata-only edits (tags, category, description, display name) apply directly; personal prompts version silently. Served prompts carry provenance: `prompts/get` stamps `prompt_version` / `prompt_approved_by` / `prompt_approved_at` / `prompt_reference` into `_meta`. Usage stats are aggregated from `prompt_serve` audit events (emitted on every database-prompt `prompts/get` and resolved `use`, within the audit retention window): `manage_prompt get` and `list` report `run_count` and `last_run_at` per prompt (`list` also includes the shared `collections` list when the store supports collections, so MCP clients see the same organization model as the portal), and `GET /api/v1/admin/prompts/usage` / `GET /api/v1/portal/prompts/usage` return the per-prompt rollup (portal scoped to the caller's visible prompts, including prompts shared person-to-person with them) for library curation and dead-prompt detection. A prompt also carries the reference material its procedure depends on (#1013): attachments are ordered links from `prompt_resource_attachments` to managed resources, stored by resource id so editing the uploaded file updates every prompt that attaches it, and deliberately without a foreign key so deleting a resource leaves the link visible as broken rather than silently erasing the evidence that the SOP is incomplete. A resolved prompt delivers them after the prompt text: textual material at or below a 64 KiB threshold as an MCP `EmbeddedResource` carrying the contents, anything binary or larger as a `ResourceLink` the client reads on demand, with a framing message stating the material is authoritative (fill an attached template, follow an attached checklist); `manage_prompt use` additionally lists them in an `attachments` array (uri, media type, size, availability, and inline content for embedded items) so the agent can state what it received. An attachment must be at least as widely visible as the prompt that carries it: global resources attach anywhere, a persona resource to personal prompts and to persona prompts scoped to exactly that persona, and a user-scoped resource only to its owner's own personal prompts. The rule is enforced at attach time (`POST /api/v1/portal/prompts/{id}/attachments`, admin-prefixed equivalent exists; `PUT` reorders, `DELETE .../{resourceId}` detaches, `GET /api/v1/portal/resources/{id}/prompts` answers what depends on a resource) and again on every prompt write through the shared store wrapper, so a scope edit or promotion request that would strand an attachment is refused with a message naming the resource, whichever surface it arrives from. At serve time it is re-checked per caller with `resource.CanReadResource`: an unreadable or deleted attachment is reported only as an aggregate count of undelivered materials, never by name and never by contents, and the prompt still serves. A prompt also references the managed scripts its procedure depends on (#1289): ordered links in `prompt_script_attachments` storing the canonical `mcp:script:` reference rather than a bare id, because that reference is the platform's one way to name a script from outside `pkg/script` (the same string `search` emits and `fetch` dereferences), and again deliberately without a foreign key so deleting a script leaves the reference visible as broken. `manage_prompt attach_script` / `detach_script` take `script` as either that reference or a bare script id and normalize to the reference. Serving a prompt delivers each referenced script's contract plus the instruction to call `run_script` for fresh output, and `manage_prompt use` lists them in a `scripts` array; serving NEVER executes a script, because a prompt read is a read path and running code from it would blur audit attribution and turn every read into a potential asset write. A reference resolves for the script's owner and for nobody else; referencing is allowed from any prompt and the response names who it will resolve for when the prompt serves anybody else, and only a script the caller can see may be referenced, with the per-caller check applied again at serve time, where an unreadable or deleted reference is reported only as an aggregate count with the prompt still serving. The rule itself is one implementation for both kinds (`prompt.CheckAttachScope` over an `AttachmentScope` carrying a SET of audience ids), because a script may serve several personas where a resource serves exactly one, and a single id cannot answer whether the prompt's audience is contained in the material's. A person browses the library on the portal's Prompts page. `manage_prompt` carries no app and renders nothing, and its JSON results stand alone in non-app clients. ## Automations The portal's view of automations, for the people who own them and the people they run for (#1290, #1307, #1994). It opens on every automation, with Mine narrowing to the reader's own; every reader sees each script's schedule and its run history as status, timing, cause and error, and what a run was given, printed and wrote stays with the owner, administrators and whoever requested that run. An automation is work that runs on a schedule or when someone asks; an agent builds one as a managed script, and every automation is a script today (#1912). The section lives at /portal/automations (the administrator's at /portal/admin/automations); the old /portal/scripts paths, including a run link mailed with a failed run before the rename, redirect to the same page with the rest of the path, query and hash intact. The detail page of one script is titled Script and backs out to Automations. The listing's first column is Automation and a Kind column states each row's kind as Script. A Grid/Table control switches the listing to a grid (#1909), remembered per browser and opening on the table: each card's tile is the script's flow diagram, drawn light and dark by the thumbnail worker (internal/platform/thumbworker, a scripts kind over internal/platform/scripttiles and the script_tiles table, migration 000164) whenever a new version is saved, recorded as not drawable with the parse error when the latest version does not parse, and removed with a deleted script; served at GET /api/v1/portal/scripts/{id}/thumbnail (?variant=dark) to everyone who can read the script. The failed-run email reads "A scheduled automation failed". The section is three tabs: Automations, Schedules (#1891) and Runs (#1405). The Schedules tab draws when every visible schedule fires, one row per schedule (a script with several schedules has a row for each, carrying `schedule_id`, #2434) with a mark at each fire, on one of three axes chosen by how often it fires over four weeks: Intraday (the viewer's today, more than 28 fires), Multi-day (the viewer's Monday-to-Sunday week, at least four) and Long-term (three months from the first of the viewer's month, fewer); a row is colored by its rhythm (the median gap between fires: minutes, hours, days, weeks, months) from the --chart-1..5 theme tokens, a paused row is muted and keeps its marks, a row over 100 fires draws 1.3px ticks and one with at most 12 irregular fires draws dots, hover or focus states a fire in the viewer's and the schedule's zones, and a click opens the script; with nothing scheduled the tab shows an empty state that returns to the Scripts tab. Every fire is expanded server-side by GET /api/v1/portal/scripts/fires?tz= (internal/httpserver/scripthttp/fireshttp over script.Cron.FiresBetween, the scheduler's own robfig/cron parse), never in the browser. The listing shows every script the caller may see with, per row, what the script is called (with a badge beside the name where it will execute nothing — disabled, or its lifecycle status — because the exception is what a listing is scanned for, while the version a run executes is true of every healthy script and belongs on the script's own page (#1407)), the cadence and next fire of its schedule, stated in words ALWAYS (#1405) — the sentence the schedule editor states, plus the step cadences an agent writes that the builder has no control for ("Every 30 minutes, UTC"), and a named custom cadence for what is left — because this is the column an owner scans to answer what is running and when; a cron expression appears only in the schedule editor, where somebody is editing one, and both the listing and the editor read what the schedule is doing off one `scheduleState` so neither can call a paused schedule due (a paused schedule says so rather than showing a fire that will not happen; a script without one runs on demand) (#1358), and the state of its most recent run. Above the table is ONE health line (#1795): the total, the scheduled count and the failed-last-run count, of which only the last is a control (pressing it filters to those scripts, `aria-pressed` while it does) because it is the one number a person opens the page for. The total and the scheduled count are the SERVER'S, counted over the predicate with no limit (`Store.Count`, `Store.CountScheduled`), and the line says "showing N" beside the total when the cap truncated the page; the failed count is the page's, and is the one that cannot be otherwise, since a run is attached per page and only for rows the caller owns. They replaced three bordered tiles that counted the ROWS ALREADY LOADED while the chips beside them counted the platform, so past the 200-row cap the two disagreed and nothing said the page was truncated (`total` was `len(rows)`). Under the line is ONE filter bar in the shape the assets browser established: Mine/All scope tabs (a non-admin's; an administrator's listing is every script by construction), free text, and a `FilterSelect` each for author, category, tag, status and type (Filter by type: Endpoint, Form, Schedule, Webhook or None, `type=` repeatable on `GET /api/v1/portal/scripts`, which refuses the removed `endpoint=` with 400; each row carries `handler_types`, `schedules` and `endpoints`, `[]` when empty, and a type badge per handler type beside the name, #2435) — tag being a select rather than a chip cloud because it is the least discriminating axis and the only one with no bound on its vocabulary, its options ordered by count exactly as the chips were. Every axis is a SERVER predicate (`GET /api/v1/portal/scripts?search=&category=&tag=&owner=&status=&enabled=&scope=`, over `script.ListFilter`) so the narrowing covers every script the caller can see rather than the capped page the listing holds. ORDERING is the server's too: `sort` and `dir` carry a whitelisted column (`script.SortColumn`: name, display_name, owner_email, created_at, updated_at) into `ORDER BY` ahead of `LIMIT`, with an id tie-breaker, and an unrecognised column falls back to updated_at DESC rather than erroring, because the caller of a listing is a page of a portal and a typo in a query string is not worth a blank screen. The Script, Author and Updated headers sort through `SortableHead`; LAST RUN does not and carries no affordance, because it is attached per page after the query and an ordering over it would be an ordering over the page. A script is VISIBLE to everyone and READABLE as before: a non-admin's `scope=all` lists every script, with `reportableScript` blanking the source of a row the caller does not own, `attachLastRuns` filling runs only for owned rows, and no action offered on one; `scope=mine` is the default and is what the listing did unconditionally before. The same widening reaches `manage_script command=list`, deliberately — an agent asked to write a weekly report should be able to see that one already exists — and the tool's projection carries no source and must keep not carrying it. The second tab is every run across the caller's own scripts, newest first (`GET /api/v1/portal/scripts/runs`, bound to the caller's owned script ids through `script.RunFilter.ScriptIDs` — an empty, non-nil set for a caller who owns nothing, so a listing across every run on the platform is unreachable; an administrator reads every run, the same reach their script listing has): what triggered each run, how it ended, how long it took, and the reason a failure failed, wrapped in the row rather than behind it, with the row linking to the run and the script's name linking to the script. A run has an address of its own, `/scripts/{id}/runs/{runID}`, which opens that run in its script's history rather than in a page of its own. Opening a script shows its Details — owner, the version that runs, the schedules, next fire, lifecycle status, and the typed parameters a run binds against, read in that one section rather than in a card apart from it (#1406) — which is the SAME document `search`, `fetch` on an `mcp:script:` reference, and a prompt that references the script serve, so the page and an agent describe a script identically; where the run gate would refuse a run requested now, the page carries the gate's own refusal (`script.RefuseRun`) rather than re-deriving runnability from a status and an enabled flag. The page is ordered for the person debugging a script (#1406): Details, the Handlers section, About (the description as the markdown document it is), the Source, and the run history directly beneath the Source, because an error in the history is answered by the text above it. The code is one card with three tabs, Flow, Source and Tests, and Flow opens first for owners and readers alike (#1906). Flow draws the script three ways, chosen by a view switch above it (Structure, Calls, Timeline; kept per viewer in browser storage and in the address as ?view=) beside a Full screen control that gives the diagram and its panel the whole window until pressed again or Escape (#1972). Structure is the default: the script in the order it runs, top to bottom and acyclic, derived from the parse tree (internal/platform/scriptflow structure.go, the graph route's `structure`): one Start, one End, a Stops node for each fail() with its message, a Returns early node for each return from main() before its end, an If decision for each if whose arms draw anything with yes and no edges that join where the script goes on, a dashed Repeats box around each loop (and comprehension) whose body makes a call, a grey box for each helper expansion that draws anything (captioned with its comment, foldable, opening folded past eight steps, a one-call helper folded into its card), and a card per platform call naming the Calls view's card for the same call site; run.state is read at the top and saved at the bottom rather than drawn as an edge back. Selecting a card lights the cards it takes data from and feeds; the version's stored test report marks each step its tests do not reach with a diamond. Calls is the value graph described next. Calls is a diagram the platform derives from the saved version's source (internal/platform/scriptflow, served by GET /api/v1/portal/scripts/{id}/versions/{version}/graph under the source's read rule and GET /api/v1/admin/scripts/{id}/versions/{version}/graph; no MCP tool carries it, an agent reads the code): every platform.* call except platform.progress is a card, colored by role (input, reads, writes, output); edges follow values, a value carrying the set of steps and run.state it was computed from, with the pure functions it passed through named on the edge, and an edge a longer path implies removed; a user function is expanded at each call site (except inside its own expansion: the interpreter refuses a recursive call when it is made), a function holding steps is one box per enclosing box captioned with its author's comment, and a function whose only effect is one platform call is folded into its step as a chip; module constants are shown by value and string building rendered with each computed part as {its source}, and a connection, destination, tool, table or target the source computes marks its card dashed and is never guessed; parameters are listed beside the diagram with the steps whose arguments their value reaches, and a parameter a condition reads is marked as deciding which steps run; run.state is an input node and platform.save_state draws a dashed edge back to it. Selecting a card fills a side panel (what it reaches, what feeds it, what it feeds, the loop, the helper and its call site, a source excerpt); double-clicking it opens Source with its lines marked, and lines selected in Source light the cards they produce. For the owner and administrators the Flow tab opens on the latest run drawn on the diagram (#1907), with a Run menu choosing one of the newest 25 runs or none: each card states its calls and their duration, the rows it exported, or that it ran; a card the run never reached is dimmed; the card a failed run stopped at is drawn in the error color with the run's cause and error in the side panel (when the run failed in the script's own code just after a call failed, such as fail() on the line after a call answered 500, the card that made that call from the same function is the one marked, #1933); a card's run chip counts its failed calls and shows the failed call's message on hover; a call that failed in a run that went on counts on its card as a failed call without marking the card failed; and the panel counts the run's calls, those on cards, and those no card made, grouped by tool with failures first and each failure message counted ("api_invoke_endpoint: 54 succeeded, 144 failed (Not Found 132, Forbidden 12), median 76 ms"), each group opening to its calls. On the Structure view a failed run marks its structure_failed node (the card of the call it failed at, the Stops of the fail() it ended in, or the helper box whose own code failed, from the backtrace's call site), what it did not reach is lighter (End when it did not succeed), and a loop box counts the most calls any call inside it made (×N); which arm of a decision a run took is not recorded. A run whose calls carry no call site (made before call sites were recorded) answers unplaced: true, and the page says so and dims nothing. With a run drawn, the Timeline view is a flame chart of its calls from the overlay's timeline (each audited call's start_ms after the run started, duration_ms, tool, outcome, response size and call_site, and run_ms): main() on top, each helper frame a row, the call the bottom bar, gaps the script's own work. The Run menu lists the newest 25 runs, narrowed by a status filter the server applies, with no paging (#1990; the Runs tab pages the whole history), each run labelled by when and how it ran, then its outcome and version ("Sep 28, 10:57 PM · manual · failed · v10"), over GET /api/v1/portal/scripts/{id}/runs?per_page=&page=&status=, whose total counts every run the filter matches (Store.CountRuns). The Tests tab lists the version's test_* functions with how each did at the save and the coverage (statements reached, the percentage, the lines no test reaches, each opening in Source), read from the report the save kept on the version (script_versions.tests, migration 000170; a version written without running the tests over the same source, such as an owner transfer, keeps the report of the one before); a version saved before reports were kept says so, and its owner can run the tests there. Script tiles draw the Structure view and have their own renderer generation (thumbworker.ScriptRenderer), so the change redraws them and nothing else. A run of an older version is drawn on that version's diagram. The attribution is exact rather than guessed: the script host records the call site of every host call (internal/scriptcallsite: the line:col of each script frame on the Starlark stack, outermost first, at the call's opening parenthesis), sends it on the in-process MCP request's _meta under mcp-data-platform/call_site, and the audit middleware stores it in audit_logs.call_site (migration 000163) for calls whose source is script; the output writer stores it on each run output, and a failed run's backtrace names the site it stopped at. The graph records the same positions on each card, so a helper called from two places is two cards with their own calls. Served at GET /api/v1/portal/scripts/{id}/runs/{runID}/flow to the owner and administrators, reading at most 10,000 of the run's calls and answering calls_truncated past that. Each version older than the running one has a Compare with button (#1908) that opens the pair as a diagram and a text diff: the running version's graph marked against the older one (?compare= on the graph route), a step matched by what it reads, writes or produces rather than by its line, so a card is added, changed (carrying what it was) or removed (the older version's card, dashed, with its edges), and moved code is not a change. A version that no longer parses answers ok false with its findings and empty lists; a script with no platform calls answers nodes, edges, groups and params as [] rather than null; the graph is cached per distinct source. The same constant resolution now feeds manage_script validate: a name the module binds once to a literal, or string building over literals and such names, is read as its value into connections, tools, destinations and refresh_targets without setting the matching dynamic_ flag. The Handlers section (#2435) lists what starts the script, one row per handler with its type badge (Endpoint, Form, Schedule, Webhook), what it answers to (a schedule in words such as "Every weekday at 7:00 AM, America/Los_Angeles", an endpoint's path, "Each event of" a webhook source) and On or Off, a row opening onto that kind's controls (the schedule builder with Pause and Resume, the endpoint settings, the webhook switch with its event-run summary) and Delete, and Add handler offering each kind with the reason beside one the viewer may not add; with none it says nothing starts the script but someone running it. About starts OPEN, because what a script is for is what a reader came for, and folds to the first line of prose in its document when the description has grown into one. Details states each cadence in the same words the listing and the schedule's handler row do rather than as the expression the platform stores, so the page carries a cron expression in exactly one place: the schedule builder. For a script the caller owns, Run and Dry run sit side by side above the editor over ONE parameter form they both bind — Run executes the saved version, a dry run executes the text on screen — and a script the run gate would refuse carries no Run control at all rather than a button that fails when pressed; the version history folds into that same section behind a collapsed reveal, each version with its author and the roles that author held at the save, which are the roles a run of that version presents, and nothing opens by default because the version that runs is the text in the editor directly above it. The run history carries each run with its trigger, the version it executed, its duration, its outputs, its failure reason where it failed, and, opened in place, its bound parameters, its cost in steps and queries and exports, its outputs, and the bounded log it printed. The run rows are composed rather than laid out flat: how a run ended and when it ran are one fact and are set as one, while the trigger (a short enumeration) and the version (the same number down the whole column) qualify it from underneath rather than each holding a column open, which is what lets the history fit the width the page has instead of scrolling sideways (#1362); a failure message wraps to as many lines as it needs, because a table cell does not wrap by default and a Starlark traceback on one line put the page's own reason for existing off the edge of it (#1406). A `skipped_overlap` row is shown as a distinct state, neither success nor failure: it names a fire that never executed because the previous run was still going, which is exactly what a report that stopped producing has to be able to show. An output written to the portal links to the asset version it produced — a recurring script writes new versions of ONE asset keyed `script::`, so that asset's version history is the script's refresh history — while an object delivered to a configured bucket destination names its bucket and key and is deliberately not a link, because the platform wrote those bytes and does not hold them. Visibility rules, shared with every other surface: a script's definition -- its contract, its source and its version history -- to everyone signed in (#1866), on the portal and through search, fetch, prompt references, knowledge-page citations and the knowledge graph alike (#2027), because a script is how a resource or an asset was produced, with the roles each version's author held withheld from all but the owner and administrators (`manage_script` `get`, `get_content`, `outline`, `stats`, `locate`, `diff` and `versions` address another person's script with `owner_email`; `get` leaves out `live_runs`); the run history, the produced list, the state and every action to that owner and to administrators, because a log is free text the script printed while presenting its author's captured roles and may echo rows the reader has no access to of their own; and one particular run additionally to whoever requested it, since the result was handed to them when they asked for it. A command that acts on another person's script is refused naming that rule. The pages write six things and none of them is an authority beyond the author's own (#1307, #1363, #1364, #1369, #1575). The handlers: on a script they own, at any scope, a caller adds a schedule (the cron expression, the timezone it is read in, and the values every fire binds), replaces or deletes one that never fired a run, and pauses or resumes it, adds a webhook handler for a source they may name, and, on a form they own, its endpoint — over `GET`/`POST /api/v1/portal/scripts/{id}/handlers`, `GET`/`PUT`/`DELETE /api/v1/portal/handlers/{id}` and the enable/disable pair (#2441), inside the portal's own authentication and CSRF handling, restricted to the owner and to administrators. Pausing is its own route rather than a field of the schedule, because re-sending the schedule to turn it off would re-base the fire it resumes on. A schedule saved against a disabled or retired script saves and stays inert, and the page says so in the gate's own words. The schedule is asked for in the terms a person has it in — hourly, daily, weekdays, chosen days of the week, a day of the month, a time, a timezone — and the cron expression is DERIVED and shown rather than asked for, because cron is a precise notation for people who already know it and the owner of a report is not required to be one of them; a Custom field keeps every expression reachable, and an expression an agent wrote through manage_script opens there as itself rather than being rewritten into something near it. The SOURCE: the code is editable in the portal's own editor with Starlark highlighted as the Python dialect it is, and the edit crosses `script.ApplyEdit` — the one gate every mutation surface crosses — landing on the live row as the version that runs and recording the roles its editor held, which is what a run of it presents; the source is parsed before anything is stored. A RUN of the latest saved version (`POST /api/v1/portal/scripts/{id}/runs`), which queues exactly what `run_script` queues under the same gate, worker and principal and records `portal` as the trigger. A DRAFT run of an edit, executed as the caller with the draft limits, persisting nothing it produced and refusing every write it reaches through `platform.call` (#1664) — a "Write for real" control beside the Dry run button lifts that for one run, and the report then lists what the run persisted. And what the script SAYS about itself — display name, markdown description, category, tags — which is not an input to any decision the platform makes and is still captured as a version. And the DELETE (#1575), at the bottom of a script the caller owns and of every script for an administrator: `DELETE /api/v1/portal/scripts/{id}`, authorized the way the tool's delete is — the owner, or an administrator over any script, with a caller who may not see the script answered as one who named a script that does not exist — and calling the same `Store.Delete` `manage_script command=delete` calls, so the cascade cannot come out differently depending on which surface asked. The confirmation names what goes with the script rather than asking whether the reader is sure: every saved version, its handlers with each schedule stated in words, the whole run history, and the state it carried, with the schedules and the state named only where the script has them. It names what stays for the opposite reason — the assets and resources the script wrote remain, owned by whoever owns them, and the producer records naming it as their writer remain with them (#1569) — because "delete the script" reads to a lot of people as "delete the reports it wrote". The delete is recorded in the audit log as a `script_delete` event of kind `admin` naming the script and the owner who lost it, whether the removal succeeded or failed at the write, the way the owner transfer is; a caller the route refuses is answered before the script is read and no event is written, which is what every other portal script route does, and a delete made through the tool is already in the log as the `manage_script` call it was, refusals included. After it lands the reader is back at the script listing. An agent reads scripts and runs as data through `manage_script` (`list`, `get`, `runs`, `get_run`), or `search` and `fetch` on a script reference, and none of those calls renders UI. RENAMING A SCRIPT (#2875). Rename beside the script's name in Details (its owner and administrators), `manage_script update name= rename_to=` sent with `owner_email` and `reason` only, or `PUT /api/v1/portal/scripts/{id}/name`. It keeps the id, versions, run history, state, grants, release pins, handlers (endpoint names and addresses are the handler's) and output files, which the next run adds versions to; runs are recorded as `script:` from then on. `GET /api/v1/portal/scripts/{id}/rename?to=` says first what stays and what changes. A name any other script holds, whoever owns it, is refused (two scripts of one name would be one principal); a script with a run running is renamed once it ends; a library is not renamed while a version that can still run loads it (the latest saved, a release's pin, an approved version, a queued or running run's), and the refusal lists each. An agent's rename of a part of a released application waits on a person (Approvals purpose `script_rename`). Each rename is audited with the old name and the new. --- # Registered Tables A file already in object storage -- a CSV somebody uploaded as a managed resource, or one `trino_export` wrote as a portal asset -- is made readable as a Trino table by pointing an external table at the directory the file already sits in (#1327). Nothing is copied and nothing is ingested: a `CREATE TABLE ... WITH (external_location = 's3://.../', format = 'CSV', skip_header_line_count = 1)` over the object's own directory, so the table reads whatever the object holds now and a vendor drop that overwrites its file changes the query result on the next run with no further action. The join was always the easy part; loading was the gap, because Trino has no client-side upload and an agent emitting `INSERT ... VALUES` batches for a fifty-thousand-row CSV is slow, error-prone, and burns context. ## What an operator configures A Trino connection gains `scratch: {catalog, schema}` naming where registrations are written. A connection with no such block cannot hold one and the surfaces do not offer it there; both keys are required, and a block naming only one is ignored with a warning rather than half-honored, because a registration built on it would fail at the DDL. Per-instance `Config` is discarded after `NewMulti`, so the target is kept per connection on the toolkit the way the read-only flag is, maintained by `AddConnection` and `RemoveConnection` so a connection added through the admin API can hold a table from its first call rather than from the next restart. Behind the connection is a Hive catalog over the same object store the platform's resources and assets live in -- a file metastore is enough (`hive.metastore=file`, `hive.metastore.catalog.dir=s3:///trino-metastore/`, `fs.native-s3.enabled=true`, `s3.path-style-access=true` for an S3-compatible store), with Trino's OWN credentials to the bucket, separate from the platform's S3 connection. `hive.recursive-directories` stays false. Dynamic catalog management (`CREATE CATALOG`) is deliberately not the mechanism: it only creates connector instances, it is marked experimental, and the full statement including credentials is logged. One properties file is the whole setup. ## Two consequences a reader has to know A CSV TABLE'S COLUMNS ARE ALL `VARCHAR`. That is the Hive CSV storage format's rule and not a platform choice -- declaring a CSV table with any other type is refused by Trino itself ("Hive CSV storage format only supports VARCHAR (unbounded)") -- so a join to a typed warehouse column needs a `CAST`. Search hits, fetch documents, the portal panel and `manage_table action=list` all carry a sample statement showing it, because a reader who writes the obvious join otherwise gets a type error that explains nothing. A JSON-lines or Parquet table declares each column's type (#1833), its sample is the plain join, and every surface carries the declared types as `column_types`. A DIRECTORY HOLDING A SIBLING TRINO WOULD READ IS REFUSED, BY NAME. Trino reads every non-hidden object under an external location and parses it as CSV WITHOUT ERRORING: a `thumbnail.png` beside a `content.csv` comes back as rows of PNG bytes. There is no error to lean on, so the platform's refusal is the only protection, and it names the object in the way rather than reporting a generic failure. Hive skips names beginning with `.` or `_`, which is why the portal's derived thumbnails are written as `.thumbnail.png` / `.thumbnail_dark.png`, and the sibling check applies that same rule so a CSV asset registers with its thumbnails in place; nothing derives a thumbnail key to READ one (an asset row records the key that was written), so thumbnails captured under the older names keep serving, and the prune path covers both spellings. An asset still carrying a legacy thumbnail IS refused, because those names are ones Trino reads; the thumbnail refresh queue offers such an asset for capture (a recorded key under a legacy name is pending however current its version) and the capture endpoint deletes the object it supersedes once the row points at the new key, so having the portal open anywhere clears it with no bucket work. The same rule applies to the file being registered: a source object whose own name begins with `.` or `_` is REFUSED, because the table would be created, recorded and queried without error and return nothing. A subdirectory is invisible while `hive.recursive-directories` is false, so a resource's revisions under `v/` and an asset's versions under `//` are never read. A TABLE, A SCHEMA OR A PARTITION A PERSON POINTS AT THE PLATFORM'S OWN BUCKETS IS REFUSED (#2616). The scratch catalog's credentials reach the resource bucket, because that is where its registered tables read; a statement sent through the Trino tools naming a location there or in the portal bucket is refused for every persona, as is a location the platform cannot read before the statement runs. Registration goes through `manage_table`, which the platform runs itself (`pkg/toolkits/trino/location.go`). ## CSV or JSON lines (#1820) A registration reads its file through the reader its FORMAT names, decided by the file's content type or, when that is generic, its extension (`.csv`; `.jsonl` or `.ndjson`) -- and a `.jsonl`/`.ndjson` file typed `application/json` is JSON lines too, since one record on one line is also a JSON document and detection names it that -- and recorded on the registration as `format` (`table_registrations.format`, migration 000151, default `csv` for every row written before it) because the CREATE TABLE is written again at every follow and when a failed follow puts a table back. A JSON-lines table is `format = 'JSON'` with no header to skip and no escape to declare; its columns were declared `VARCHAR` like a CSV's until #1833, which types them from the values (see "Typed JSON lines and Parquet (#1833)" below). What each format carries was established against Trino 453: a JSON-lines table returns every string byte for byte -- LF, CR, CRLF, NUL, backslash, quotes, a leading `=`/`+`/`-`/`@`, tabs, emoji, private-use code points, U+2028 -- and a null or missing key as NULL, where a CSV table cannot carry a line break inside a value (refused unless `repair`, which joins the value's lines with single spaces after trimming each and dropping blank ones) and reads a null back as an empty string; no other character is altered by either. Columns are every key any record carries, lowercased, in first-seen order, because the JSON reader matches a key to its column without regard to case; a key cannot be renamed the way a CSV heading is, since a renamed column is one the reader never fills. `internal/platform/tablejsonl` refuses, by line number, the shapes the reader fails on or reads wrongly: a blank line anywhere but the end, a line that is not exactly one JSON object (a second object on one line is DROPPED without error, the one silent case), a key repeated in a record exactly or by case, a key whose values cannot be one type (#1833; until then every nested object or list value was refused, because the reader fails a query on one in a `VARCHAR` column), and a key that is non-ASCII (its column reads empty on every row), holds a comma, or has leading or trailing space (both refused by Hive as column names). A JSON-lines file is never corrected: `repair` does nothing for it. A file with no records declares no columns and is refused at registration, while a later version of a following registration's file that holds none moves the table and keeps its columns, so a day with nothing in it reads as zero rows. `trino_export` and a script's `platform.export` write the format as `format=jsonl` through one formatter (`pkg/toolkits/trino/format.go`): one object per row, keys in column order, a list or dict value written as its JSON text so the reader can read it and `json_parse` restores it, and a string that is not valid UTF-8 refused rather than replaced, since encoding/json would substitute U+FFFD silently. The portal's Query as a table panel appears for a JSON-lines file as it does for a CSV. ## Typed JSON lines and Parquet (#1833) A JSON-lines registration types each column from EVERY record (`internal/tabletype.Inferrer`, shared with a script's Parquet export so the two cannot disagree): all booleans `BOOLEAN`; all integers within int64 `BIGINT`; any number with a fraction or exponent, alone or among integers, `DOUBLE` (not `DECIMAL`: a JSON number carries no scale and one wide value would widen the whole column); all strings, a mix of scalar kinds, an integer too large for `BIGINT`, or nothing but nulls `VARCHAR` (verified on Trino 453: the JSON reader returns a number's or a boolean's text in a `VARCHAR` column, and a mixed list reads as `ARRAY(VARCHAR)`); an object a `ROW` over the union of its keys, lowercased, each inferred the same way; a list an `ARRAY` of its elements' type. A key holding an object on one line and a list or scalar on another is refused naming the key and line. No date or timestamp is inferred from a string. A NESTED field name may hold only letters, digits, `_`, `.`, `$` and spaces (`tabletype.CheckFieldName`): the metastore keeps a nested type as Hive type text, and on Trino 453 a table whose ROW declares `b-c`, `a:b` or a quote is CREATED and then fails every statement with "Could not read table schema", its DROP included, so the refusal is what keeps an undroppable table out of the scratch schema. A JSON-lines registration made before this change carries `all_varchar` (`table_registrations.all_varchar`, migration 000152, set true for every existing `jsonl` row): a follow keeps its columns `VARCHAR` and refuses a nested value as before, so a query written against it keeps working; registering the file again under the same name makes a typed registration. A PARQUET registration (`format = 'PARQUET'`, `internal/tableparquet`) reads the file's footer and nothing else: a ranged read learns the size, the last eight bytes give the footer length, a second ranged read fetches it (`ObjectReader.GetObjectRange`, over `GetObjectRange` added to txn2/mcp-s3 for this), so a Parquet file larger than the cap a CSV is read whole under still registers. Detection: content type `application/vnd.apache.parquet` (aliases `application/x-parquet`, `application/parquet`) or the `.parquet` extension; `pkg/contenttype` names Parquet from the `PAR1` magic, and with the whole payload in hand holds it to `PAR1` at both ends; a file named `.parquet` whose bytes are not Parquet is refused as not Parquet. Mapping: BOOLEAN -> BOOLEAN; INT32 (none / INT(32,signed)) -> INTEGER; INT(8|16,signed) -> TINYINT/SMALLINT; INT64 (none / INT(64,signed)) -> BIGINT; INT(8|16,unsigned) -> SMALLINT/INTEGER; FLOAT/DOUBLE -> REAL/DOUBLE; DECIMAL(p,s) on any physical type -> DECIMAL(p,s) (p <= 38); BYTE_ARRAY STRING/ENUM/JSON -> VARCHAR; plain BYTE_ARRAY -> VARBINARY; INT32 DATE -> DATE; INT64 TIMESTAMP (any unit) and INT96 -> TIMESTAMP(6); LIST -> ARRAY (the format's backward-compatible element rules), MAP -> MAP, group -> ROW; converted-type-only files map the same. TIME, UUID, FLOAT16, INTERVAL, plain FIXED_LEN_BYTE_ARRAY, an unsigned 32- or 64-bit integer (a UINT32 declared BIGINT reads 4294967295 as -1; a UINT64 declared DECIMAL(20,0) is refused by the connector), a repeated field outside LIST/MAP are refused naming the column and its Parquet type -- no partial registration -- as are two columns one apart by case (the reader matches by name case-insensitively) and a nested name the metastore cannot store. Every timestamp column is declared `TIMESTAMP(6)`: a Hive table's timestamps are read at the catalog's `hive.timestamp-precision` and the connector refuses a column declared at any other ("Incorrect timestamp precision for timestamp(3); the configured precision is MICROSECONDS"), so the scratch catalogs set `hive.timestamp-precision=MICROSECONDS`, which is also what reads a microsecond Parquet timestamp back exactly (the default MILLISECONDS truncates it). `repair` has nothing to correct in a Parquet file and is accepted as a no-op. A follow re-reads the new version's footer; an added, removed or retyped column is reported in the write's `table_changes` (`FollowOutcome.ColumnChanges`: "added region VARCHAR; id is now DOUBLE (was BIGINT)"), and a version that is not Parquet or holds a refused type sets `follow_error` and leaves the table where it was. EXPORT: `trino_export format=parquet` and a script's `platform.export(format="parquet")` write Parquet through one formatter (`pkg/toolkits/trino`, `tableparquet.Write`, parquet-go, ZSTD). `trino_export` reads the query with `QueryOptions.RawValues` and the column precision and scale `ColumnInfo` now reports (both added to txn2/mcp-trino, whose `convertValue` also stopped cutting fractional seconds with RFC3339), so a `TIMESTAMP(6)` keeps its microseconds, a `VARBINARY` its bytes and a `DECIMAL` its declared precision. Trino to Parquet: BOOLEAN; TINYINT/SMALLINT/INTEGER -> INT32 INT(8|16|32,signed); BIGINT -> INT64; REAL/DOUBLE -> FLOAT/DOUBLE; DECIMAL(p,s) -> DECIMAL(p,s) on INT32 (p<=9), INT64 (p<=18) or FIXED_LEN_BYTE_ARRAY; VARCHAR/CHAR/JSON/UUID/IPADDRESS/TIME/interval -> STRING; VARBINARY -> BYTE_ARRAY; DATE -> DATE; TIMESTAMP(p) -> TIMESTAMP MILLIS (p<=3) or MICROS, not adjusted to UTC; TIMESTAMP WITH TIME ZONE -> TIMESTAMP MICROS adjusted to UTC, the zone not kept and the result message saying so; ARRAY/MAP/ROW -> LIST/MAP/group, fields lowercased. The result message names every column that lost something, at any depth (a nested value loses what a top-level one does): a zone, a timestamp finer than the microsecond a table reads, or a type written as text. A `TIME WITH TIME ZONE` written as text keeps its offset, which the CSV and JSON exports of the same query also keep. `Write` holds every column and ROW field name to the rules `Columns` reads them by -- non-empty, no comma, no edging whitespace, ASCII, no two one apart by case, a ROW field only letters, digits, `_`, `.`, `$` and spaces -- and refuses before writing, so an export cannot store a file the registration it was made for would refuse. Columns and ROW fields are written in declaration order through an ordered group node, because parquet-go's `Group` is a map that lists fields alphabetically. Every file written registers. A script's rows carry no types, so the Parquet formatter infers them with the JSON-lines rules (a dict a ROW, a list an ARRAY), and a key that cannot be one type -- two of a dict, a list and a scalar across rows -- fails the export naming it; `register=` accepts `parquet`. The script's export record carries `column_types` as `{"name", "type"}` entries, the shape every other surface uses. VIEWERS: a JSON-lines asset opens on a Table view (the records' key union, first-seen order and spelling, the CSV viewer's search, sort and row dialog, a nested value as one-line JSON in the cell and indented in the dialog) when every line is an object of scalars or flat values and the records carry most of the columns, and on the Records view otherwise; a toggle switches. A Parquet asset or resource, and a public share of one, opens in a viewer that reads the file by HTTP range through hyparquet: a schema panel with each column's Parquet type, nullability and the Trino type a registration declares (the same mapping, in TypeScript), the row count, row groups, size, codecs and writer, and one row group's rows at a time. The tile is the content-type icon. ## A CSV a line-based reader cannot read (#1441) A BACKSLASH IS AN ORDINARY CHARACTER (#1819). Registration declares `csv_escape = U&'\0000'`, the value that tells the Hive CSV reader to escape nothing; its default escapes with a backslash, a dialect no writer of these files uses, under which `back\slash` read as `backslash` and a quoted cell holding a backslash beside a quote read as an empty string, row and column counts intact. `csv_escape='"'` does not help. NUL cannot collide with a value because a file with a NUL byte is refused before registration. A table registered before this keeps the reader's default until its file gets a version it follows or it is registered again. Trino's Hive CSV reader is LINE-BASED: the text input format splits records on `\n` before the quote-aware serde sees them, so a quoted line break TEARS one record into fragments, the first fragment ends on an unbalanced quote, and every field after it lands in the wrong column. This is the ordinary shape of a spreadsheet export -- a multi-line address in one cell -- and it parses without error under Go's `encoding/csv` and Python's `csv`, so nothing about the file looks wrong. The table is created, the row is recorded, the query returns rows, and the rows are fragments: there is no error anywhere on the path, which is why the file is inspected before the DDL rather than trusted. A real 34 KB file with 157 records of 27 fields each, 153 of them carrying an embedded line break, registered as a 530-row table -- 530 being exactly the count of `\n` bytes after the header -- with only the 2 records containing no line break correct. The bytes to see it were already in hand: `columnsFor` did a full `GetObject` and handed the whole body to `ReadHeaderColumns`, which read one record and discarded the rest. It now returns the body (`contentFor`) and the body is INSPECTED. Three conditions refuse, all wrapping `ErrNeedsRepair` as well as `ErrRefused`: lines that end in a bare `\r` and never in `\n`, any field containing `\r` or `\n`, and bytes that are not valid UTF-8 (which reach every cell as replacement marks). The refusal names how many rows carry a break and which columns they are in, using the SAME column names `ReadHeaderColumns` would declare. A parse failure part-way through STOPS the scan rather than failing it -- what was read is still evidence, and a file this reader cannot finish is one that registers today, so refusing it on that ground alone would take away a working registration. A LEADING UTF-8 BYTE-ORDER MARK IS DROPPED BEFORE ANYTHING READS A RECORD (#1774). It is not an encoding declaration to any reader here -- it is the first bytes of the first field -- so `encoding/csv` reads `"Post ID"` as an UNQUOTED field carrying a bare quote and fails the parse on line 1. A header whose first field is unquoted parsed and had the mark trimmed off the NAME afterwards (`tablecsv.ColumnsFrom`), which is why the defect was invisible for as long as it was: it only appears when the export QUOTES its strings, which Facebook Insights, Excel's "CSV UTF-8" and Google Ads all do, so no export from those surfaces could be registered at all. `ReadHeaderColumns` turned every read error into `ErrEmptyHeader`, so the answer was "the file has no header row, so the table has no column names" about a header the file has and the portal's own CSV viewer renders; `tablecsv.Inspect` runs first and died on the same line, recorded it as `Unreadable` and returned NIL, so the defects BEHIND the mark -- the line breaks inside cells the correction exists for -- were never found and `repair: true` did nothing. `tablecsv.TrimBOM` now drops it at the top of `Inspect` and `ReadHeaderColumns`, and only for bytes already established as UTF-8, because a code page assigns those three bytes three of its own characters and `decodeToUTF8` carries them rather than dropping them. A first line the reader cannot parse AT ALL is now a defect in its own right rather than nil: such a file never registered -- the registration meets the same line three lines later -- and the refusal carries the parse error ("this file's first line cannot be read as a CSV header (...)"), never "no header row". `ErrEmptyHeader` is kept for its one true case, a file with nothing in it. A COMMA IN A HEADING DOES NOT SURVIVE INTO THE COLUMN NAME (#1774). The Hive metastore stores a table's column list comma-separated, so the connector refuses a name holding one whatever the quoting -- `USER_ERROR: Hive column names must not contain commas` -- and a Facebook Insights export names a column `Reactions, Comments and Shares`, so no export from that surface could be registered even once the byte-order mark stopped hiding its header. It failed at the DDL, which is AFTER the correction of the file's rows had already been saved. `tablecsv.withoutCommas` turns each comma into a space and collapses the runs, in `ColumnsFrom`, on the same footing as the blank name filled in positionally and the repeat that is suffixed. Which characters Hive refuses was established against Trino 476 rather than assumed: a space, a dot, a colon, a parenthesis, a slash, a semicolon, a percent, an equals and a hyphen were each created without complaint, and the comma alone was refused, which is why it alone is dropped. A RECORD SHORT OF THE HEADER IS NOT A DEFECT (#1779). A CSV record may end before the header does -- an exporter writing nothing rather than trailing commas -- and those columns are ABSENT rather than wrong. Every reader supplies them: Go's encoding/csv and Python's csv return the short record, PapaParse fills the missing keys, Excel and Preview open the file, and the Hive CSV reader a registered table is served by reads the values it finds and leaves the rest null. Refusing such a file put this platform alone among them: a Facebook Insights export omitting two trailing columns for one post type (21 of 178 records) could not be registered, AND the short records withdrew the offer to correct the 148 torn rows it also had (Correctable() is false while Ragged is non-empty, #1449), so the file had no path forward at all. `noteRagged` and `checkFieldCounts` now flag only a record carrying MORE fields than the header, where dropping one to fit would lose a value the file holds; the correction writes a short record back as it came. `padding a short record invents data` was the stated reason and does not hold -- an absent trailing value is not invented by being read as empty. THE CSV VIEWER SHOWED THE PARSER'S ROWS AND DISCARDED ITS ERRORS (#1779). `CsvRenderer` parsed with `Papa.parse(content, {header: true})` and read `parsed.data` alone. PapaParse reports a record that does not have the header's fields as a FieldMismatch in `parsed.errors` and maps the row onto the header keys regardless, leaving the missing ones unset, which the table drew as empty cells. So a file whose exporter omits trailing fields looked COMPLETE in the portal while a registration over it named the same records -- which is why the viewer "rendering fine" was not evidence the file was rectangular. A note under the table now says how many rows end before the last column and how many carry more fields than the header names. A REFUSED REGISTRATION IS READ IN A DIALOG (#1780). The register form lives in the viewer's details column (`ViewerLayout`, `lg:w-80` = 320px) and a CSV refusal is several sentences naming rows and columns; wrapped into that column it was small red type below the fold, and #1617 had already had to make the repair control wrap like a paragraph (`h-auto max-w-full whitespace-normal`) to fit. `RefusalDialog` (extracted, since TablesPanel was at its 600-line budget) puts the reason at a readable measure on `ModalShell` and the action in a footer as an ordinary button; a refusal with no next step reads the same way with only a dismiss. THE DESTRUCTIVE TOKEN WAS A FILL BEING USED AS TEXT: `--destructive` was 0 84.2% 60.2% light and 0 62.8% 30.6% dark -- DARKER for dark mode, which is right for a fill and backwards for text -- putting every refusal in the product at 3.76:1 on a card in light and 1.78:1 in dark, both under WCAG AA. It is now the on-surface text colour (0 72% 42% light, 0 70% 65% dark; 6.47:1 and 5.39:1 on a card), with the old values under `--destructive-fill` for the button, badge and status dot. That inversion was chosen by counting: 100 places set text with it against 2 that fill a shape, so the common case gets the plain name and only the fills were migrated. A TABULAR CELL THAT DOES NOT FIT IS READ BY OPENING THE ROW (#1781). Cells are capped at 200px and the only way to see a longer value was the browser's `title` tooltip, which cannot be selected or copied, does not wrap for a paragraph, does not exist on touch and vanishes when the pointer moves; the columns cannot be resized and the row had no click, so on a 35-column export with paragraphs in Title and Description the table was a wall of ellipses over data that was all there. It was also the ONE list in the portal that did not open on row click. A row is now a focusable control (Enter and Space open it) and `RowDetailDialog` shows the record as key/value pairs on `ModalShell`, values wrapping and selectable, with copy per value and for the whole row and previous/next so reading several records is not close-and-re-aim. A field ABSENT from the record reads "not in this row" rather than as an empty value, because after #1779 the two are different facts. THE PATTERN THIS SETTLES, written into docs/server/content-viewers.md for the next dense table: truncate in the table, open the record in a dialog, never leave something a person needs to read reachable only through `title`. A REGISTRATION THAT FAILS SAYS WHERE IT STOPPED, AND IS ALWAYS AUDITED (#1775). A 500 answered "the registration could not be completed" -- no field, no reason, no code -- because the wrapped store or driver text may carry topology a caller should not see. The stage is the half that can be told: the registrar wraps each platform failure with `failedf(stage, err)` (reading the file, checking the table name, saving a corrected version of the file, listing the file's directory, registering the table, recording the registration, replacing the previous registration, removing the registration), `tableregister.StageOf` reads it back, and the detail becomes "the registration could not be completed while reading the file". The whole error still goes only to the log and the audit event. And it now GOES to an audit event: a registration that failed before it had corrected the caller's file was not audited at all, so a deployment where registrations were failing had a `table_register` history in which every attempt had succeeded -- one deployment's was 14 events, every one `success: true`, with neither of the two failures that prompted the ticket among them. `plan` fills the connection, source kind and source id onto the registration before the first check, so an attempt refused at the connection boundary still names what it was for, and `ErrConnectionDenied` is recorded `authorized: false` rather than `true`. THE READ IS NOT BOUNDED BY A FLAT 30 SECONDS (#1773). `contentFor` reads the WHOLE object by design -- the header row and the line-break scan both need the full bytes -- and neither `createPortalS3Client` nor the managed-resource layer passed a `Timeout`, so mcp-s3 filled in its 30 s default around the request AND the `io.ReadAll` of the body. On a full-object read that is a THROUGHPUT BUDGET rather than a timeout: a 126 MB CSV registered in 2.05 s on a healthy path and failed at exactly 30.0 s, 116 MB in, the day one deployment's DNS sent the pod to the other site's ingress and back over the WAN at ~3.8 MB/s -- so whether a customer's file could be registered turned on which A record the resolver handed out. The instance's documented `timeout` key reached the `s3_*` tools and nothing else, so an operator could not raise it either. `toolkitcfg.S3Config` now reads `timeout`, and `toolkitcfg.BlobReadTimeout(configured, maxObjectBytes)` is what both clients are built with: a configured value wins outright, and with none the deadline is the deployment's own object ceiling -- the larger of `resources.managed.max_upload_bytes` and `portal.max_content_size`, the same ceiling #1634 pinned the registration's own cap to -- at a floor of 1 MB/s, never below the 30 s mcp-s3 would have used. A 250 MB ceiling is a 250 s deadline; a deployment storing small objects keeps exactly the client it had. CARRIAGE-RETURN LINE ENDINGS ARE THE SAME FAILURE ONE LAYER EARLIER (#1445). Go's `encoding/csv` splits records on `\n` only, exactly as the Hive text input format does, so a CSV whose lines end in a bare `\r` -- the classic Mac ending some spreadsheet exports still write -- is ONE record to both. Before #1445 that made `InspectCSV` report `Rows: 1` with column names assembled out of a header line joined to the line after it (`address101`, `12 Mill Rd102`), and the offered correction, once taken, joined those lines with a space and saved a two-column header row with NO data rows as a new version of the person's file. `withLineFeeds` now rewrites every LONE `\r` -- one that is not part of a `\r\n`, which every reader here already folds -- as `\n` before anything is counted, in `InspectCSV` and again in `NormalizeCSV`. WHICH CARRIAGE RETURNS WERE LINE ENDINGS IS DECIDED FROM THE PARSE, NOT FROM THE BYTES, BY TWO MEASURES FOR TWO REGIMES (`recoversRecords`). A body with NO `\n` ANYWHERE is one record to every reader on this path and no ordinary CSV is written that way, so nothing in it is ambiguous and the PLAIN count (`recordCount`) decides. A body that ALREADY HAS `\n`-delimited records is ambiguous -- splitting a cell on a `\r` adds a record exactly as a real line ending does -- so records carrying the HEADER'S FIELD COUNT (`wellFormedRecords`) decide, since a record recovered from a line ending has the columns the header declares and a fragment torn out of one cell does not. THREE WEAKER RULES WERE TRIED AND ARE EACH WRONG, in ways only measurement found. (1) A byte test ("no `\n` anywhere") disqualifies an otherwise CR-delimited file over one stray line feed -- a tool that appended one, a cell pasted in from a Windows source -- and restores the exact pre-#1445 behaviour the correction then reports as a repair. (2) A plain record count EVERYWHERE is wrong for an UNQUOTED in-cell `\r` (`store_id,address\n101,12 Mill Rd\r9 Oak St\n102,4 Elm Ave\n`): the translation splits that cell, the count rises by one just as a recovered boundary would, and the file gets a false "lines end in a carriage return" plus a field-count refusal over the one-field fragment -- a REGRESSION against pre-#1445, which diagnosed the in-cell break and corrected it. The quoted shape cannot catch this: a `\r` inside quotes stays inside them, so the count cannot move and both rules agree, which is why the test carries an UNQUOTED case. (3) The header-width measure EVERYWHERE is wrong in the DESTRUCTIVE direction, and this is the #1445 failure itself: for an untranslated Mac file the parse returns the whole file as one record and `want` is taken from THAT record, so the original side always scores >= 1 and the translated side must reach >= 2 -- the header PLUS a data row of the header's width. A Mac file with no such row (an unquoted comma in an address, a header wider than its rows, rows wider than the header) never clears the bar, the translation is discarded, and the file is merged into one row and saved that way as a new version. Enumerating classic-Mac CSVs of 2-5 rows x 1-4 header widths x 1-4 row widths, 41 of those 64 shapes are silently flattened by the header-width measure and 0 by the shipped rule (at the narrower 2-4 x 1-3, 14 of 27 against 0); `TestNormalizeCSV_NeverMergesTheRecordsOfACarriageReturnFile` pins the property. Kept, those same files are refused HONESTLY by the field-count rule naming the record. ONE SHAPE STAYS AMBIGUOUS AND IS DECIDED RATHER THAN KNOWN: a SINGLE-COLUMN file with an unquoted `\r` in a value, where every fragment is also the header's width, so field counts cannot separate the readings and the `\r` is taken as a line ending; the quoted form a spreadsheet actually writes is correctly left alone. `wellFormedRecords` and `recordCount` both set `ReuseRecord` and read only `len(record)`, the header's width captured before the loop since the reused slice is the one the header came back in. The parse test also picks up the case a byte test cannot see at all: a CR-delimited file with a quoted `\n` in a cell fails `csv.Read` on its FIRST record, so the record scan returned nothing, `InspectCSV` returned nil, and the file reached `ReadHeaderColumns` to be refused with `ErrEmptyHeader` -- telling the person the one thing that was not wrong with it and offering no repair. A lone `\r` that recovers no record is left alone and stays what it is, a line break INSIDE A CELL, so nothing untrue is said about the file's lines. Translation is applied only to bytes the platform reads as single-byte text (`CSVDefect.convertibleEncoding`, the encoding half of `Correctable`), so a wide encoding is still named rather than rewritten. `CSVDefect.LineEndings` carries the finding, `Correctable` stays true (one line ending maps to another without guessing at anything), and the correction goes through the SAME version trail: `NormalizeReport.FromLineEndings` reports it and `repairSummary` renders it as "rewrote the carriage return line endings as newlines". Because the endings are settled first, the record scan sees the records the file actually holds, so a ragged CR file is refused by record number -- at the inspection, with no correction offered (#1449) -- and a CR file with a real break inside a cell names the column it is in. THE CORRECTION IS A NEW VERSION OF THE FILE ITSELF, not a derived copy beside it. `manage_table` gains `repair` (and the REST body `"repair": true`, and the portal a control on the refusal); with it, `NormalizeCSV` decodes as UTF-8 or, on invalid UTF-8, as windows-1252 (`golang.org/x/text/encoding/charmap`), drops a leading BOM, replaces each run of `\r`/`\n` inside a field with one space and trims it, and re-emits with `csv.Writer` as UTF-8 with no BOM. The bytes then go through the version mechanism the source kind ALREADY has -- `resource.ReviseContent` (extracted from the replace-content route so a revision written on somebody's behalf is the same revision, same trail, same retention) for a managed resource, `portaldomain.VersionStore.CreateVersion` for a portal asset -- both of which write a fresh per-version directory and move the head in one transaction, which is exactly the one-file directory `locationFor` requires. The uploaded bytes stay as the version before the correction, revertible from the same panel every other version is. The registrar reaches these through a `Reviser` port keyed by source kind, the way `ObjectReader` is, since the two kinds keep their trails in different tables; a kind with no reviser refuses instead of correcting. A record whose field count differs from the header is REFUSED, naming the records: padding a short record invents data and truncating a long one discards it, and neither is a correction the platform can make on somebody's behalf. THE OFFER IS TESTED AGAINST WHAT THE CORRECTION WILL ACTUALLY DO (#1449). Until then `Correctable` inspected the ENCODING AND NOTHING ELSE, while `NormalizeCSV` applied two further rules the offer knew nothing about, so a caller told to "register it again asking for the file to be corrected" asked for it and got a SECOND, DIFFERENT refusal naming a problem the first had not mentioned -- `a,b\n1,"x\ny"\n2\n` was offered the correction for its torn row and then refused by `checkFieldCounts` for its one-field record. The single reader pass in `scanRecords` (was `scanEmbeddedBreaks`) already visits every record, so it now also records the RAGGED RECORDS (`CSVDefect.HeaderFields`/`Ragged`, numbered as `checkFieldCounts` numbers them) and the PARSE ERROR that ended the read early (`CSVDefect.Unreadable`), and `Correctable` is the conjunction of all three: a convertible encoding, no ragged record, no truncated parse. THE HEADER READ IS THE SAME READ: a scan whose FIRST `Read` fails returns claiming nothing, and if that early return does not record the parse error the offer stands for exactly the files whose defect was settled BEFORE the scan -- a windows-1252 file or one with carriage-return endings, whose header carries a bare quote -- and the correction refuses them on its own `ReadAll`, which is the same two-answer bug one layer up. `raggedClause` and `unreadableClause` are the ONE wording for each condition, shared by the inspection that declines to offer and by `NormalizeCSV` which still refuses independently. NEITHER NEW CONDITION MAKES A DEFECT BY ITSELF: `InspectCSV` still returns nil unless there are torn rows, an encoding or carriage-return endings, so a ragged CSV with newline endings and no in-cell break registers exactly as it did, as does one the reader gives up on partway -- which is the invariant `scanEmbeddedBreaks` tolerated a parse failure for in the first place. The remedy sentence is now the defect's (`CSVDefect.remedy`) rather than the registrar's fixed "Re-export it as UTF-8 CSV and upload that", which was wrong advice for a file whose bytes were fine and whose records were not. A file that is already line-safe and valid UTF-8 behaves exactly as before -- no version, no rewrite, nothing extra in the result -- including when the repair was asked for unnecessarily. ONLY A SINGLE-BYTE CODE PAGE IS CONVERTED. `charmap.Windows1252` maps all 256 bytes and never errors, so "not valid UTF-8 therefore windows-1252" would decode a spreadsheet's UTF-16 "Unicode Text" export into one character per byte and write that mojibake back as a corrected version of somebody's file, reporting it as a repair. `sourceEncoding` checks the byte-order marks widest-first (a UTF-32LE mark begins with a UTF-16LE one) and treats a NUL byte in a markless file as "not single-byte text either"; `CSVDefect.convertibleEncoding` is false for all of those, and `correct` refuses them outright with `refusedf` rather than `needsRepairf`, so the surfaces offer nothing the platform cannot honestly do. WINDOWS-1252 IS THE LAST ANSWER, NOT THE FALLBACK FOR EVERYTHING THAT IS NOT UTF-8 (#1448): the code page leaves five byte values undefined (0x81, 0x8D, 0x8F, 0x90, 0x9D) and `charmap.Windows1252.NewDecoder().Bytes` emits U+FFFD for each of them and returns a NIL ERROR, so a file holding one converted "cleanly" into a file with replacement marks in it, was saved as a new version of the person's resource or asset, and reported `FromEncoding: windows-1252`. `sourceEncoding` therefore checks the source for those five bytes AFTER `utf8.Valid` (a valid UTF-8 file may carry any of them as a continuation byte) and returns `encodingUnidentified` for them, which `Correctable` is false for, so the refusal comes before anything is written and no correction is offered either way. The refusal names the evidence rather than an encoding -- "a byte windows-1252 does not define" -- because that byte rules the code page out without saying what the file is instead. THE NUL TEST RUNS BEFORE `utf8.Valid`, NOT AFTER IT (#1447): a NUL is valid UTF-8, so a markless UTF-16/UTF-32 export of ASCII content passes a UTF-8 test with a NUL beside every character and would register as a table whose column names and cells carry them. The refusal therefore never says its bytes "are not UTF-8", which that file's bytes are: an encoding identified by a byte-order mark is named ("look like UTF-16"), and one identified by the NUL alone is reported as the NUL, since nothing else about those bytes says what they are. `InspectCSV` returns on the encoding alone for anything `convertibleEncoding` is false for, claiming NOTHING about line endings, torn rows or column names: every reader below that point is a single-byte one, so over a UTF-16 file with Windows endings it takes the `\r` beside a NUL for a line break inside a cell and names the column out of the NUL-laden bytes around it, which would put a count nobody can check and a NUL into the refusal text and the audit event. A CORRECTION IS A WRITE THAT MAY OUTLIVE ITS REGISTRATION. It is written before `locationFor` and `ReadHeaderColumns` have run and before the DDL, so a refusal, an unreachable coordinator, or a store that cannot record the registration can arrive after the person's file has already changed. `plan` therefore returns its partial plan alongside the error, `Register` audits the correction on that path too (the record is filled in by `claim`, before the file is read, so the event names the table it was for rather than an empty one), and ALL FOUR failure paths wrap the error in `repaired`, whose message leads with what changed and which `RepairOf` reads back. The two store writes did not wrap it until #1446: a file that was corrected, whose DDL then succeeded and whose row then failed to insert, produced a 500 reading "the registration could not be completed" while the new version sat on the file unmentioned. `tablehttp.detailFor` uses that to keep the sentence about the file while still replacing a 500's own text, which is a wrapped driver error carrying topology the caller should not see. A revision of a managed resource additionally re-registers it with the MCP server and fires `resources/list_changed`, the same call the replace-content route makes, so a client that already read the resource does not keep serving the bytes the correction replaced. `plan` was reordered so nothing is written before every refusal that can happen has: the connection boundary, the derived table name and the name-ownership check are settled FIRST, then the body is read, then the correction, then the location and columns. A caller who may not take the name never gets their file rewritten on the way to being told so. The correction is recorded on the registration's own audit event (`repaired`), because it rewrote somebody's file for them. The REST refusal carries an RFC 9457 problem TYPE (`urn:mcp-data-platform:problem:csv-needs-repair`, via `httpjson.WriteErrorCode`) so the portal keys its offer on the code rather than on prose; the detail stays the sentence a person reads. An answer whose registration failed AFTER a correction carries `urn:mcp-data-platform:problem:file-corrected` on the same mechanism (#1450): the correction is written before the last checks and before the DDL, so a refusal or a platform failure can follow one and the file stays changed, and the version trail and the file's own record on the page are then behind what is stored. The register mutation refreshes them from `onError` on that type as it does from `onSuccess` on `repaired`. ## The surfaces One registrar serves both kinds, because a registration says the same thing about either: this object's directory is readable as this table, on this connection, with these columns. It checks the caller's persona against the connection (`connscope.Scope.AllowConnection`, the same predicate the authorizer applies to a tool call), reads the object's header line for column names, refuses a directory with a sibling, and issues `CREATE SCHEMA IF NOT EXISTS`, a `DROP TABLE IF EXISTS` only when replacing a registration the caller is entitled to replace, and the `CREATE TABLE`. Everything that can refuse does so BEFORE any statement runs, so a refused registration leaves nothing behind in Trino, and the record is written LAST, because a row naming a table that was never created is a lie a search hit repeats. EITHER STORE WRITE THAT FAILS AFTER THE `CREATE` TAKES THE TABLE BACK OUT (`rollBackTable`, #1446), because neither can be undone by the one that follows it. Unrecorded, the table stands with nothing naming it: no surface lists it, `BuildDDL` issues a `DROP` only when replacing a registration that EXISTS, and the second attempt the answer tells the caller to make would therefore meet it in Trino and fail. Recorded still by the registration it was REPLACING -- the `Delete` of that row failed after the DDL re-pointed the table -- it is worse, and is the case nothing else reports: the table now reads the new file with the new columns while the surviving row keeps advertising the old ones through `toolView` and `SampleJoinSQL`, and `IsStale` does not catch it, because a replacement registering the SAME key to pick up a changed header leaves the location it compares identical. What the rollback leaves instead is no row and no table. THE DDL FAILURE IN A REPLACEMENT IS THE SAME RECONCILIATION FROM THE OTHER SIDE (`forgetDroppedRegistration`): a replacement runs DROP then CREATE, so a coordinator that refuses the CREATE leaves the previous table gone with its row the only thing still claiming it exists -- and not marked stale either, for the same reason. That row is removed. When the DROP is the statement that FAILED, nothing ran that changed anything and the row is still accurate, so it is left alone; distinguishing the two is why `runDDL` returns the statements it got through rather than only an error, and why `dropTableStatement` is one function the three callers that must agree on its text all use. The drop runs on a `context.WithoutCancel` bounded by a 30s timeout, since taking cancellation off leaves nothing else between a wedged pool and a request goroutine that never returns (the audit write goes to the same pool the write that failed came from) -- the store write may have failed BECAUSE the caller disconnected, which is exactly when cleanup has to outlive the request -- and is audited, since the event written a moment earlier says the table was created; a drop that fails is logged and joined onto the cause on that event rather than replacing the store error the caller can act on. The DDL goes through `Toolkit.Exec(ctx, connection, sql)`, the platform's one write path into Trino, which runs the SAME `ReadOnlyInterceptor` the MCP tools run -- a `read_only: true` connection refuses registration exactly as `trino_execute` would. The two pre-existing direct callers of `Manager().Client(name).Query` (the HTTP query func and `trino_export`) run SELECT and reach the client without that check, and are not a model for a statement that writes. Three surfaces: the portal's *Query as a table* panel in both the managed-resource viewer's sidebar and the asset viewer's (ONE component, since the action is identical on either), the REST routes (`GET /api/v1/table-connections`, and `GET`/`POST /api/v1/{resources,portal/assets}/{id}/tables` with `DELETE .../{registrationID}`), and the `manage_table` tool, actions `register` / `list` / `unregister`. The connection picker is filled from the connections the caller reaches that CARRY a scratch target AND accept writes, so every option it offers is one the registrar accepts. Both halves are required: a scratch target is a destination and grants nothing, so a `read_only: true` connection naming one still refuses the CREATE TABLE, and offering it produced a 500 "the registration could not be completed" the moment it was chosen. Naming a read-only connection directly is refused by the registrar itself with `ErrConnectionReadOnly` -> 400, the sibling of `ErrNoScratchTarget`, before any DDL is attempted; reaching the DDL instead produced an error the layer could not classify and the surface could only call a 500. `tableregister.Executor.AcceptsWrites` is on the port rather than discovered by type assertion precisely so the picker cannot forget to ask; it mirrors `checkExecWritable` including its two asymmetries (no interceptor at all means a single-connection toolkit that was not configured read-only, so writes are ALLOWED; an empty connection name resolves to the default). THE TOOL IS KEYED BY REFERENCE, NOT BY AN ID (#1428). `manage_table` takes the `reference` a `search` hit emits and `fetch` dereferences -- `mcp:resource:` or `mcp:asset:` -- so ONE action serves every kind of stored file: the kind travels inside the reference, there is no per-kind argument, and there is no second tool. `register` takes `follow` (default true; false pins the table) and reports which rule the table was made under; `list` reports `follow` and `follow_error` beside `stale` (#1536). An id-keyed action could only ever reach one kind, which is why `manage_asset` carries no table actions: the case registration exists for is a file a PERSON uploaded, and the agent is on the other side of that upload. `manage_table` is registered by the portal toolkit rather than a new one, because `pkg/platform` sits at its LOC cap and a new toolkit would need construction there; the wiring is `wireTableToolRegistrar` in `internal/httpserver/tablemounts.go`, which hands the toolkit a `tableregister.ToolAdapter`. A reference the caller may not register -- missing, deleted, or somebody else's -- is answered as `ErrNoSuchFile` in every case, the way `fetch` answers one outside its reach, so the tool cannot enumerate what exists. A well-formed reference to something that is not a stored file (`mcp:knowledge_page:...`) is refused as `ErrBadReference` NAMING what was passed, because the caller can see that difference themselves. ## Registration is owner authority Registering puts a file's contents in a schema everyone granted the connection can read, so it is the owner's call, like sharing. The rule is AUTHORITY TO CHANGE THE FILE, NOT AUTHORITY TO READ IT, and it is the same for both kinds (#1428): an asset by its owner or an administrator (`assetVisibleTo`), a resource by `resource.CanModifyResource` -- its uploader, a platform administrator, or an administrator of the scope it lives in, which is exactly the rule for updating or deleting it. A read rule would not do: resource scopes are NOT carried into Trino, so anyone who could see a persona-scoped file could publish it to everyone with the connection. Both surfaces resolve a file through ONE `tableregister.Subject` per kind (`tableSubjects`, `internal/httpserver/tablemounts.go`), so the rule cannot drift between the REST routes and the tool. Table names are persona-prefixed (`_`, the slug from the filename by default) and the name is CLAIMED in a unique index on (connection, catalog, schema, table): re-registering your own name replaces it, taking someone else's is refused naming who holds it, and administrators are unrestricted. A table under the name that NO registration records (a `CREATE TABLE` the platform stopped waiting for -- deadline passed or caller gone -- that the coordinator completed anyway, which refused every later registration of the file "already exists", #2131) is ADOPTED when its `external_location` (read with `SHOW CREATE TABLE`) lies under the directory the source's id names, which holds every version of the file, so a scheduled export that registers its output recovers on its next run; one reading anything else is refused naming where it reads. After an abandoned CREATE the registrar also drops, under the same check and on a context the caller's cancellation does not reach, the table it may have made, and audits the drop; `scratch.statement_timeout` on the connection bounds each scratch statement. Administrators reconcile a connection's scratch schema against its registrations (#2136; the Reconcile tab of Scratch Tables; `GET /api/v1/admin/tables/reconcile?connection=`): `orphans` (tables no registration holds, each with its external_location and the stored file it belongs to; `provable` when the location is the directory of a managed resource or portal asset the platform holds, found by trying the location's path segments as ids through the source locator and checking the source's own directory, or lies under the managed-resources bucket's `resources/` prefix), `missing` (registrations whose table is gone; a webhook source's is not provable) and `drifted` (a table reading somewhere else; reported only), a webhook source's raw and compacted tables and a managed table (no external location, such as a managed script's working table; #2141) being none of these and a listing past 50,000 tables reported `truncated` with nothing missing. `POST` with `{"connection", "repair": [{"action": "drop", "table"} | {"action": "forget", "registration_id"}]}` proves each again as it is made, reports `{done, reason}` per item, refuses what is not the platform's ("not the platform's: it reads ...; left alone"), and audits each repair under the administrator with source `admin`; at most 500 a request. `GET /api/v1/admin/tables/registrations` lists every registration by `connection`, `persona` (the table-name prefix), `source_kind` + `source_id` and `q`. The prefix is collision avoidance and legibility, NOT a boundary -- resource scopes and asset ownership are not carried into Trino, and the scratch schema is a shared workspace by design. What keeps a registration off the warehouse is the Trino identity the scratch connection authenticates as. The platform's `read_only` is a statement-prefix denylist evaluated per connection name; nothing in the toolkit restricts a catalog or a schema, and `catalog`/`schema` on a connection are session defaults rather than bounds. ## Finding what is registered: the Scratch Tables section (#1472) Every read of `table_registrations` was keyed by ONE source -- by id, by qualified name, by source -- and the only surface a person saw was `TablesPanel`, rendered inside one asset's or one resource's detail view. So the way to find out what a deployment had registered was to open every asset and every resource in turn. That is worse than an inconvenience, because the scratch schema is a shared workspace: the unique index on (connection, catalog, schema, table) exists precisely because everyone granted the connection sees every table in it, which left a reader able to query a table through Trino that the portal gave them no way to find, no way to identify the source of, and no way to tell was current. `/scratch-tables` is the listing, in the portal's own section list rather than the administrator's, and `/scratch-tables/{registrationID}` is one registration at an address of its own. Behind them are `Store.List(ctx, Filter)` -- the first read here that spans sources -- and `GET /api/v1/tables` / `GET /api/v1/tables/{regID}`, in `internal/httpserver/tablehttp/listing.go`. A Trino connection saved through the admin API has its scratch target on every replica as soon as the save returns: a replica that has not heard of the save yet reads the connection from the connection store, as the api and graphql kinds do (#2218). VISIBILITY FOLLOWS THE CONNECTION, which is the boundary Trino itself applies and the same predicate `Unregister` already applied: a caller sees the registrations on connections their persona is granted (`connreach.ForPersona` narrowed to the Trino kind, which delegates to `connscope`), and an administrator sees all of them. It is deliberately NOT the register form's connection list, which narrows further to connections carrying a scratch target that also accept writes: a connection turned read-only after a registration would otherwise hide that table from the person who made it while Trino went on answering queries against it. The boundary is a `Filter.AllConnections` FLAG rather than the emptiness of a `Connections` slice, because the two states that separates are opposites and both are reachable -- a persona granted no connection reaches nothing, an administrator reaches everything -- and reading one as the other would either hide every table from an operator or show every table to a persona that may query none of them. The count is taken under the same predicate as the page, so a pager states the rows the caller may see rather than the rows that exist, and a caller who names a `connection` facet outside their reach is answered with an EMPTY PAGE rather than a 403, since the parameter is a facet of a listing they may read and a refusal would confirm the connection exists. `GET /api/v1/tables/{regID}` answers a registration outside the persona as 404, the same answer an id that never existed gets. The two things a cross-source read has to add to a stored registration are which file it is and whether the table is still reading that file's current contents, and neither is on the row: staleness needs the source's head key NOW. `tableregister.Sources` is the bulk form of `Subject` -- one read per kind for a page, `portal.AssetStore.GetByIDs` and a new `resource.Store.GetByIDs` -- and it returns a `SourceRef` carrying the name, the bucket, the head key, and `CanModify`. AUTHORITY IS A FIELD ON THE ANSWER RATHER THAN THE ANSWER ITSELF, which is what separates it from `Subject`: the listing shows what a caller may QUERY, decided by connection, while the unregister action needs authority over the SOURCE, and a row is shown either way. A source id absent from the map is a record that is gone, rendered as "Source deleted" rather than as an ordinary row -- deleting a file unregisters its tables, so it is the residue of a cleanup that did not complete. A source store that could not answer degrades the page (no name, no action) rather than failing it. UNREGISTER GOES THROUGH THE SOURCE'S OWN ROUTE (`DELETE /api/v1/{resources,portal/assets}/{sourceID}/tables/{regID}`), so the rule for who may drop a registration stays written once: authority over the source AND having registered the table or being an administrator. `can_unregister` on each row is that rule evaluated from the same bulk lookup that supplies the name and the head key, so the control is absent rather than present and refusing. REGISTERING STAYS ON THE FILE'S OWN PAGE, because it needs the file: the platform reads the header row to learn the columns. The listing is driven by the STORED ROWS rather than by what can be registered, so it carries no content-type gate of its own -- `TablesPanel` renders only for a content type containing "csv", which belongs to the register action, and a source of another Hive-readable format appears in the listing as soon as one exists with no change here. The empty state says what a scratch table is and where registration happens rather than showing an empty table, and it is distinguished from a filter that matched nothing, which keeps the table and the facets in front of the reader. ## The lifecycle, staleness, and deleting A FILE IS NOT LIMITED TO ONE REGISTRATION, which is why the portal panel keeps its Register control available after the first one and lists registrations as a set. Registering under a different name, or onto a different connection, ADDS a table and leaves the existing ones alone; registering the SAME name on the same connection REPLACES that registration, which is the repair for staleness below and the reason the panel's warning says to register again rather than to unregister first. Unregistering is a separate act with a separate consequence, and neither it nor a replacement touches the file. THE DISCOVERY LAYER REPORTS THE SET, NOT ITS NEWEST MEMBER (#1627): `fetch` on a stored file carries `tables`, one entry per registration over it, newest first, each with `registration_id`, `query_table`, `columns`, `sample_sql`, `stale`, `follow`, `repair` and `follow_error` -- the same facts and the same order `manage_table action=list` reports under `table_registrations`, so the document and the managing tool cannot disagree. THE TWO KEYS ARE THE TWO USES (#1666): `tables` is the query view a `fetch` document and a `search` hit carry, the DOCUMENT's rows carrying the columns so the query can be written without a second call while the hit's one `table` carries none (`preferredTable` clears them: a hit is a pointer chosen from a ranked page of them, and a page each carrying a wide table's column list is a large answer to the question of which record to read), and `table_registrations` is the maintenance view `manage_table action=list` and the per-file REST route answer with, carrying the `registration_id` an unregister takes. It answered under `registrations` until #1666 while every other surface said `tables`, so a script checking for an existing registration read `tables`, found nothing, and re-registered on every run -- the table survived, since registering the same name replaces the registration, but the registration id changed every time. A `search` hit still carries ONE `table`, because a hit is a pointer to somewhere the data can be queried rather than an inventory, and it is the newest registration whose `follow_error` is EMPTY; a file whose every registration is disowned gets no `table` on its hit and its reasons are in the document. `TableLookup.TablesFor` therefore returns the whole per-file list and the hit path chooses from it. Before that, both paths took `regs[0]` -- the newest -- whatever state it was in, so a file with a healthy table and a newer one a follow had reported gone was described by the gone one: the document named a table that did not exist, offered `sample_sql` over it, and said nothing about the table that would have answered. A new revision of a resource or a new version of an asset writes to a new directory and moves the head key, and a registration FOLLOWS that move by default (#1536): `Registrar.FollowSource` is called from the one place each kind's head moves -- `resource.ReviseContent` behind the replace-content and restore routes and behind `manage_resource replace_content`, every asset version writer (the portal's PUT content and revert, the admin console's, `manage_asset` update/patch/revert through `uploadContentUpdate`, and a script's `platform.export` / `publish_data` through scriptexec's `storeVersion`), and the correction path inside `Register` for every OTHER registration over the file -- through `TableSourceHooks.AssetRevised` / `ResourceRevised` beside the delete hooks, with a caller-less `tablesource.Locator` resolving the record. For each following registration it re-reads the new head exactly as a registration does (whole body, CSV inspection, the sibling check, the header), runs the same DDL a re-registration runs (DROP, CREATE at the new directory with the new columns), relocates the row, and audits a `table_follow` event under the REGISTRANT naming the version followed to and the columns before/after when the header changed. The follow NEVER fails the write: a refused CREATE after the DROP ran puts the old table back, the reason is kept on the row as `follow_error`, and the registration is behind the file exactly as a pinned one is, with the reason shown. After any write that ran DROP TABLE (a follow, an unregister, a replacing registration) the registrar asks the connection whether every OTHER registration on it still holds its table (`Executor.TableExists`, an information_schema lookup), records the ones that do not (`follow_error` opening with *The table no longer exists*) and reports them -- in the follow's `table_changes` sentences, in a replacing registration's result, and on the rows an unregister leaves (#1546): Trino's file metastore drops a table by listing its metadata directory, and an object store whose prefix listing does not stop at a directory boundary (SeaweedFS before 4.17) answers `x/` with `x_pinned/...` too, so one drop took a name-prefix sibling with it while every surface kept listing the sibling as registered. A lookup the connection cannot answer is logged, not reported. The write's result names every table over the file under `table_changes`, a change report rather than the `tables` a caller queries (#1666; `script.RunOutput` is STORED as well as served -- `script_runs.outputs` is a JSONB array unmarshalled back into it -- so migration 000141 rewrites the key on every recorded output, preserving call order, or every run already in the history would read back with no table report at all) -- on `replace_content` and the asset content results (also appended to the message), the portal/admin `statusResponse`, the export record and `RunOutput`, and the run log as `table_changes: : ` (echoed by the host for `platform.call` results too) -- so the write that leaves a table behind says so. `follow=false` / `"follow": false` / the unticked portal box PINS a table to the version it was registered over, stored on the row (`table_registrations.follow`, default true for existing rows too); a pinned table keeps serving the directory it was registered against and the recorded location compared against the head's directory NOW reports it stale on the portal panel, in Scratch Tables (Pinned / Follows the file / Behind the file, with the failure on the badge), on a `search` hit, on a `fetch` document and in `manage_table action=list`. Re-registering the name targets the current head and re-sets the choice. A pin holds only because every version has a directory of its own, since a table reads every file in the directory it points at (#1851): a script's `platform.export` / `publish_data` versions are written as `scripts/", "references": ["mcp://global/brand/logo.png", "mcp:asset:ast_7c1e"] } ``` The reference appears twice on purpose. In the markup it is what the reader's browser will load; in `references` it is the declaration, and only a declared reference is ever rewritten. A reference string that appears in the content but was never declared is served exactly as written and resolves to nothing, so the grant is always the declaration and never a string that happens to appear in the body. The rewrite is a whole-document replacement over textual content rather than an attribute rewrite, so a reference resolves wherever it is written: an `img` `src`, a `` `href`, a `fetch()` inside a ` ``` The glyphs and sprites the style draws with are not published to npm; they are checked in under `ui/vendor/maplibre/` at a pinned commit of `protomaps/basemaps-assets` by `scripts/sync-map-assets.sh`. The style asks for a town hall icon that sheet does not have, so a town hall's label is drawn without an icon and the browser console notes the missing image once. ## Thumbnails The tile worker draws a map asset like any HTML asset, in the platform's headless Chrome, which draws WebGL in software (SwiftShader). The page's reads of `/portal/vendor/maplibre/` and `/portal/maps/` are answered by the platform in-process, by range, so the tile shows the basemap and the data in light and dark with no outbound request. The tile is taken once every map on the page has finished drawing (MapLibre's `idle`), bounded at 15 seconds after the page's other files load, so a map whose tiles never arrive still gets a tile (#2087). Export PDF reads them the same way, and prints a document that draws a map once every map on it has finished drawing (MapLibre's `idle`, bounded at 20 seconds), on one page the size of its screen layout, since a map fitted to the screen's width and printed on a narrower paper size would be cut at the page edge. ## Telling agents The platform ships a knowledge page, `mcp:knowledge_page:platform-maps`, and `platform_info` names it to any caller that can save an asset. The page lists the regions this deployment serves, or says plainly that it has no basemap, and is rewritten whenever maps are turned on or off or a region becomes ready or is removed. It shows the document skeleton, how to draw points, a route and areas, how to fit the view, that the OpenStreetMap attribution stays on, what to do when no region covers the data, and a state choropleth from the served boundaries. ## Admin API | Method and path | What it does | |---|---| | `GET /api/v1/admin/settings/maps` | the settings, every region with its state and archive, the presets, the upload prefix | | `PUT /api/v1/admin/settings/maps` | `enabled`, `s3_connection`, `bucket`, `max_zoom`, `source_url`, `allowed_origins` (a JSON array; omitted or empty serves this deployment alone; a malformed entry is refused by name) | | `POST /api/v1/admin/settings/maps/regions` | `{"preset": "united-states"}`, or `{"id", "name", "bounds": {"min_lon", "min_lat", "max_lon", "max_lat"}}`; 201 with the queued region | | `POST /api/v1/admin/settings/maps/regions/{id}/refresh` | queue a fetch of the newest build at the current maximum zoom; 409 while the region is being fetched | | `DELETE /api/v1/admin/settings/maps/regions/{id}` | remove the region and its archive (an uploaded file included) | | `POST /api/v1/admin/settings/maps/estimate` | `{"preset"}` or `{"bounds"}`; the exact size, tile count and build, writing nothing | The settings live in the `maps` row of `platform_settings`; regions in the `map_regions` table (migration 000184). ## Out of scope The platform draws the geometry the data has. Turning a list of stops into the streets between them is a routing engine, and turning addresses into coordinates is a geocoder; neither is part of this. Satellite imagery, terrain and hillshade are not served. # Sites and pages The platform serves two kinds of browser traffic on hostnames other than its own: an application's browser pages, and static sites with environments. Both go through one serving layer that routes by `Host` and sits outside the platform's routes, so a request to a site or page origin never reaches a portal, admin, MCP or API route, and a request for any other hostname passes through untouched. People run sites from the portal's **Sites** section and agents through `manage_site`. Both act through one service, so they cannot disagree about who may do what. ## Publish, promote and roll back Two buttons sit on every environment card, and they do different things: - **Publish** turns files into a new release and puts it in `dev`. It is the only way a release is made. - **Promote** makes no new release. No files are sent and nothing is rebuilt: the next environment serves, unchanged, the release the environment before it serves, so what reaches `prod` is exactly what was checked in `dev` and `stage`. - **Roll back** returns an environment to a release it served before. With `manage_site`, a change reaches `prod` on a site with a `stage` in three calls: ```json {"command": "publish", "site": "marketing", "files": [{"path": "index.html", "content": "

Spring

"}]} {"command": "promote", "site": "marketing", "to": "stage"} {"command": "promote", "site": "marketing", "to": "prod"} ``` The publish makes release N in `dev`; each promote moves that same release N one environment along. ## Agents work in dev, people use what was promoted `dev` is a site's working copy. Every publish, patch and in-place edit lands there and nowhere else, whether a person or an agent makes it, and nothing anyone relies on is served from it. You change `dev`, review it at its address, and **promote** the exact release to an environment people use, such as `stage` or `prod`. Those environments are read-only: they move only by promote and rollback, with approval where an environment requires it. A publish, an overlay or a patch aimed at one is refused, naming `dev` and `promote`, even for an administrator. A new site starts with two environments: `dev`, and `prod`, which holds the main address. `dev` is always first and `prod` always last; an environment between them is placed when it is created and can be moved later, and a release moves one environment at a time, from `dev` to `prod` (see [Environments and promotion](#environments-and-promotion)). Access is decided per **address** (#2619): - **Every address on the pages domain** (the main address and each `--`) is **private**: it asks for the platform's sign-in and opens only for administrators, the site's owner, the people who manage the site, and whoever the environment is shared with. Anything finer is the site's own business, using the identity the platform hands it (see [Inside a private environment](#inside-a-private-environment)). - **An added domain** is private too, unless it is set **public**: then it opens for anyone at that one hostname. The platform asks no one to sign in there; a site that wants a sign-in builds its own. **An agent stops at dev** (#2643). `promote`, `rollback`, and `add_domain` or `set_domain` with `public: true`, on any environment other than `dev`, never carry out on an agent's word alone, whatever the role of the person it works for. Over MCP the platform asks the person through their client (elicitation), naming the site, the release, the environment, the address to look at and the files the move changes; accepting carries out exactly that move, and a site that changed in the meantime is asked about again. A client that cannot ask files a request in **Approvals** and answers `APPROVAL_REQUIRED`: a person decides it in the portal, and the agent's session can never decide it (`manage_approval decide` refuses a site request, and so does the portal's own API reached through the `platform-admin` connection, whose every call is served in process and marked as a tool call's whether or not it carries the caller's token, #2656). The portal's buttons are the person and are unchanged. An administrator can mark an environment **Agents may promote here** (`agents_may_promote`, off by default, set in the portal only) for a scratch or preview environment where unreviewed publishing is safe. History and the audit record name whose decision moved an environment an agent asked to move: `elicitation`, `approval` or `environment_setting`. The elicitation trusts the MCP client application to show the question to the person, which is what elicitation is. No domain is needed: an environment works at its pages addresses for people who sign in. Making an environment answer anyone takes two deliberate steps, adding a domain and setting that domain public, and only the owner or an administrator takes the second. ## How a site is used 1. Someone whose persona holds `manage_site` creates a site. They own it. It has `dev`, at `--dev.`, and `prod`, at `--prod.` and the site's main address, `.`. 2. The owner invites internal people to work on it (**Can manage**). They and their agents publish and edit `dev`. 3. They add the environments a release passes through on its way to `prod` (`stage`, `test`) with **New environment** or `set_environment`, placed between `dev` and `prod`, and promote releases one step at a time. 4. They share each environment with people and personas, and give the main address to the environment people should reach there, or to none. 5. They add domains such as `example.com` to any environment but `dev`. A domain is private until the owner or an administrator sets it public. 6. A system administrator adds an ingress rule for each domain. Admin > Domains lists every address that needs one. The pages domain needs one wildcard. Or an administrator chooses a Site routing script in Admin > Settings > Integrations, and the platform hands it every hostname it serves, and each one added or removed, to route through the ingress itself (#2659). A domain added then reads `pending` until the script answers, and `ready` or `failed` with the script's message after, on its row and in `manage_site`. The platform does not manage or check DNS, certificates or who owns a name, and TLS belongs to the ingress. ## Addresses | Address | What answers | |---|---| | `.` | The **main address**: the one environment the owner gives it to (`prod` on a new site), or, given to none, a "Nothing is published here" page. Always private | | `--.` | That environment, whichever environment holds the main address. Always private | | A domain added to an environment | That environment: private, or public when set public | Every address on the pages domain is one label under it, so one `*.` wildcard certificate and one wildcard ingress rule cover every site and environment, and moving the main address needs no DNS or ingress change. Moving the main address is the owner's or an administrator's, since it changes what people reach at the site's main address. No site or environment name holds `--`, and an application created since #2604 cannot either, so `--` is never another site's or application's address. An application whose name held `--` before then keeps its address. A site or environment whose address could not be one DNS label is refused with the reason: a composed label longer than 63 characters (a new site's `dev` and `prod` addresses count, so a site name is at most 57), and a label with `--` as its 3rd and 4th characters, the form RFC 5891 reserves for an encoded international name (`xn--`), which certificate authorities refuse to issue for. Every `--` of a two-character site has that form, so a site name cannot be two characters (#2611). A site created with such a name before this rule keeps its main address and its domains; its environments' `--` addresses are not reported (its `pages_addresses` are `""` for them), its JSON carries an `address_note` saying why, `GET /api/v1/admin/sites/domains` does not list them, and the platform logs the `site_reserved_label` configuration warning naming the site at startup. Give each environment people use a domain. ## Configuration ```yaml sites: enabled: true # default: on with a database and a portal bucket pages_domain: pages.example.net max_release_files: 20000 max_file_bytes: 67108864 # 64 MiB max_release_bytes: 2147483648 # 2 GiB cache: memory_bytes: 268435456 # per replica dir: /var/cache/platform-sites disk_bytes: 2147483648 crawl: allow_private_cidrs: [] max_pages: 2000 max_bytes: 536870912 identity: # an application's own identity provider (#2878) allow_private_cidrs: [] # ranges a provider on the internal network may be on reserved_hostnames: [] # names the deployment answers on itself releases: keep_default: 50 # releases each environment keeps; 0 keeps every one mode: delete # delete, or report: the cleanup counts and deletes nothing orphan_grace: 24h # how old an object no release names must be before it goes every: 24h # how often the cleanup runs tls: hsts: enabled: false # send Strict-Transport-Security on https answers (#2557) max_age: 31536000 # seconds a browser keeps the rule; 0 is a year include_subdomains: false # apply it to every name under each address too traffic: # each site's traffic and latency (#2647) enabled: true # default on minute_retention: 24h # minute rows: the last-hour and 24-hour views hour_retention: 2160h # hour rows (90 days): the 7-day and 30-day views typecheck: # type checks a site's _build.json asks for (#2793) enabled: true # default on; needs the portal bucket memory_limit: 3221225472 # bytes; default 3 GiB timeout: 5m registry: "" # default the npm registry dir: "" # writable directory a check works in; default the temp directory ``` `sites.identity.allow_private_cidrs` lists the private ranges an application's own identity provider may be on (#2878). Every provider is reached through the egress guard, which refuses private, loopback, link-local and metadata addresses unless a range here, or **Private provider addresses** under Admin > Settings > Sites, admits it. The ranges are seeded from the file and then read from the saved settings on every replica. A provider at an internal name (`localhost`, `*.internal`, `*.svc.cluster.local`) is reached only at addresses inside a listed range. The file's values are the seed. Once an administrator saves **Admin > Settings > Sites** (`PUT /api/v1/admin/settings/sites`), the pages domain and the limits come from `platform_settings` and apply on every replica within a few seconds, with no restart. `sites.verify` no longer exists, and `sites.tls` holds only `hsts`: a configuration that sets either's other keys is refused at startup. `sites.tls.hsts` sends `Strict-Transport-Security` on every https answer at a page origin, a site's addresses on the pages domain and its added domains. The platform does not verify who owns an added domain, so each one is held to it alike. It is off by default: once a browser holds the rule, it will not open those addresses over plain http until the rule expires, whatever the setting says then. Nothing is sent over http. `pages_domain` is the parent of every application's page origin (`.`) and every site address (`.` and `--.`). With none set, no page and no site address is served, and a domain added to a site still is. !!! warning "Use a registrable domain of its own" Give `pages_domain` a registrable domain the portal is not on. A sibling of the portal, such as `pages.example.com` beside `platform.example.com`, is same-site: browsers then send the portal's `SameSite=Lax` cookie on requests a page makes. The portal's cross-origin rules still refuse to let a page read the answer, and its writes need a CSRF token, but a separate domain removes the exposure. The platform refuses a `pages_domain` that holds the portal's host or sits under the session cookie's `Domain`. On https with no cookie `Domain`, the portal's session cookie carries the `__Host-` prefix, so a script on a sibling hostname cannot set it. Upgrading to this release signs everyone out once. ## How routing works ```mermaid flowchart LR R[Request] --> H{Host} H -- "portal or unknown" --> P[Platform routes] H -- "label.pages" --> N{Label} N -- "an application" --> A[Application's page origin] N -- "site--env" --> E[That environment] N -- "site" --> M[The environment holding the main address, or not found] H -- "added domain" --> V{Maps to} V --> E2[That environment, as the domain is set] V --> A E --> G{Signed in and let in} M --> G E2 --> X{Public domain?} X -- "no" --> G G --> F[Its release] X -- "yes" --> F ``` A hostname routes as soon as it is added. Which release it serves, and whether it is private, is read again every half second per replica and at once on the replica that changed it, so a promote, a rollback, a change of a domain's access or a move of the main address takes effect immediately. Whether a request is private is decided by the route its `Host` matched, an address on the pages domain or an added domain, and by no other header the client sends. File bytes are cached by content digest in memory and on disk, which never go stale. A site and an application cannot be created with one name; a pair from before that rule answers as the application. ## Who may do what | | Everyone with the Sites area | Shared with | Can manage | Owner | Administrator | |---|---|---|---|---|---| | See the site in the portal | Yes, and only the environments they can open | Yes | Yes | Yes | Yes | | Open an environment at its private addresses | Only if shared with them | The environments shared | Every one | Every one | Every one | | Publish and edit dev, promote, roll back, add domains, add and place environments | No | No | Yes | Yes | Yes | | Share an environment, make a domain private, set approval | No | No | Yes | Yes | Yes | | Make a domain public, move the main address | No | No | No | Yes | Yes | | Add or remove people who manage, edit, change owner | No | No | No | Yes | Yes | | Delete the site, map a domain to an application, take approval off, move an environment forward past one that requires approval | No | No | No | No | Yes | A share names **who** and **which environments**: - **A person**, by the email the identity provider reports. A person can also be given **Can manage**, which is site-wide and for internal people only. External people can be shared with, never made managers. When the provider says outright that it has not verified an address, the address matches no owner or grant, and the person is told why. A provider that sends no `email_verified` claim is trusted. - **A persona**. A persona share is matched on every request against the persona the viewer's roles resolve to in the live registry, so a change to the persona applies on their next request. A role changed at the identity provider applies at their next sign-in, as everywhere on the platform. - **Everyone internal** is a per-environment setting (`internal_view`): it opens that environment's private addresses to everyone signed in whose persona is not external. - **The application's sign-in** (`access: "application"`, #2878; **Who can open** in the portal) opens an environment that is a part of an application to the people that application environment's own identity provider signs in, in place of platform users: a visitor with no session goes to `/_auth/app/start`, grants, personas and `internal_view` no longer apply, and `/_viewer` answers `auth_type` `application` with `issuer`, `subject`, `email`, `email_verified`, `name` and `claims`, never a token. A request to `/endpoints/` is admitted by the endpoint's own access mode (a session, a bearer token, or anyone for a public endpoint), as on a public domain. The application environment must name a provider ([Applications](applications.md)). Opening an environment that requires approval this way, or an agent doing so outside dev, waits in Approvals (purpose `site_application`); `access: "platform"`, the default, goes back at once. A share naming no environments opens every environment. A share applies at every private address of an environment; at a public domain anyone opens it. Someone who does not manage a site sees, in the portal and in the site's API answers, only the environments they can open and the domains on them. The Sites area is a persona's `portal.sites` switch. Unset, it is on for a persona holding `manage_site`. An external persona never has it: its stored switch is kept and reported in the persona editor's capped areas (`capped_by_external`). Anyone a share names finds those environments on the portal's Home, under **Sites shared with you** (#2718), external people included: each environment a share to their verified email or to their persona opens, with its address and an Open link, an offline one marked Offline with its message and no link. Nothing else of the site is listed: not its other environments, not who else it is shared with, not who shared it. A person no share names sees no section. The list is `GET /api/v1/portal/shared-sites`, which every signed-in person may read. ## Making a domain public Public is a setting of a domain, not of an environment (#2619). `set_environment` with `public` is refused, naming the domain setting. A domain is added private unless public is asked for (`add_domain` with `public: true`), and its access changes later with `set_domain` (`public: true` or `false`), Make public and Make private on the Domains tab, or `PUT /api/v1/portal/sites/{site}/domains/{hostname}`. Only the owner or an administrator makes a domain public; anyone who manages the site makes one private. On an environment that requires approval, an owner's request files a request in Approvals (purpose `site_public`, naming the domain) and the domain stays private; once it is approved, the same request makes it public. An approval holds for the access it was asked against: a domain made private and then public again asks again. An administrator's own request goes through at once. Every address on the pages domain keeps asking for a sign-in whatever its environment's domains are set to. Caching follows the address: a public domain's answers are cacheable as public answers are (`immutable` on a fingerprinted name, `max-age=0, must-revalidate` otherwise), and every private address answers `Cache-Control: private, no-cache` with `Vary: Cookie`. ## Environments and promotion A site's environments have a stored order, the path a release takes (#2617): - `dev` is always first and `prod` always last. Neither can be moved, and neither can be deleted while the site exists. - A new environment is placed when it is created, with `after` naming the environment it follows: `dev` or one between `dev` and `prod`. Nothing goes after `prod`. With only `dev` and `prod` there is one place, and a new environment goes there; with more, leaving the place out is refused, naming the environments it could follow. - An environment between them can be moved later the same way (`set_environment` with `after`, or Move on its card). Moving one forward past an environment that requires approval is an administrator's: otherwise a release that environment never approved could feed the next one. - Every list of a site's environments follows the stored order: the cards, the Sites list, the Promote dialog and `manage_site get`. **Promotion goes one step.** An environment takes a release only from the environment immediately before it, and only the release that environment serves. With `dev`, `stage`, `prod`, `prod` takes only what `stage` serves. `promote` names the target (`to`); `from`, when given, must be the environment before it, and a `release`, when given, must be the one that environment serves. A refusal names the environment the release must come from, in the same words from the portal, the API and `manage_site`. Nothing is promoted to `dev`, which takes every publish and edit directly. Rollback is unchanged: an environment returns to a release it served before. **Applications.** An application release moves each coupled site environment part, and each linked part it names in `move_sites` (#2679), to what the environment before it serves, and `dev`, which has nothing before it, to the site's newest release. A linked part is otherwise moved only by promote and rollback here. A promotion into an environment that is a part of an application is refused when the release's `_application` file declares a contract range that excludes the application's contract version (see [Applications](applications.md#the-compatibility-contract)). Pins are read before any environment moves, so an application holding both `stage` and `prod` moves each one step in one release, as promoting each would. Application rollback is unchanged. ## Offline and redirecting Every environment other than `dev` has a status (#2631, #2632): **Online**, the default, serves its release; **Offline** answers every address and every path, `/endpoints/` included, with `503 Service Unavailable`, the platform's page showing the site's name and a message (plain text, at most 1,000 characters, with the runes that hide or reorder text removed), `Retry-After` while an expected-back time is set and ahead, `Cache-Control: no-store` and `X-Robots-Tag: noindex`; **Redirecting** answers every address with `302 Found` and `no-store` to an `https://` address, with the request's path and query appended when **Keep the path** is set. The request can only add path below the target: `//evil.example/x` lands at the target's `/evil.example/x`. One status applies at a time, and an environment moves between any two directly. - The access check runs first: on a private address someone not signed in is asked to sign in, and learns neither the message nor where the environment points. - The release pointer is untouched: promote, roll back and publish keep working, and Online serves exactly what the environment then points at. - Anyone who manages the site sets it, at once, even on an environment that requires approval: an outage cannot wait in a queue. The exception is a redirect on an environment that requires approval, set by someone who is not an administrator: it waits in Approvals (purpose `site_redirect`, naming the target), the environment keeps answering as it does, and the same request goes through once it is approved. Lifting a redirect is always immediate. - A redirect target must be an absolute `https://` URL with a host, no user name or password, no control character, at most 2,048 characters, and none of the environment's own domains, the pages domain or the platform's own hostnames, which would loop. - The expected-back time is only what visitors are told: the environment stays offline until someone brings it online. - History records `offline` with its message, `redirect` with its target, and `online`. ## Renaming and removing an environment The environments between `dev` and `prod` can be renamed and removed (#2630); `dev` and `prod` cannot. **Rename** (`set_environment` with `rename_to`, alone, or the PUT route with `rename_to`) takes a name that passes the environment-name and address rules and is not `dev`, `prod`, `default` or one the site uses. One transaction moves every reference: the environment, its domains, its history, its jobs, the main address, each share's environments, the application parts and pins written `/`, pending approvals that target it, and its tile (#2751). It answers at `--` at once; the old `--` answers "Nothing is published here", its domains keep answering, and `mcp:site:/` references written elsewhere stop resolving. **Remove** (`remove_environment`, or `DELETE .../environments/{name}`) is refused while the environment has a domain, holds the main address, is a part of an application or has a job running, each naming what to do first, and only an administrator removes one that requires approval. One transaction removes it, withdraws pending approvals that target it, deletes its tile (#2751), drops it from every share, and **deletes a share that named only it**: an empty list means every private environment, so emptying one would widen it. Its history stays, marked removed, and stops counting toward its release limit, so releases only it kept go at the next sweep; an environment created later with the same name starts with no history. ## Traffic The platform records each site's traffic and latency itself (#2647), so a site's people see it with no Prometheus backend and no grant beyond seeing the site. Each replica tallies every request the gateway answers in memory (one status-class count and one latency bucket, for the site and environment and for the replica: no allocation, no shared lock, no database call on the request path) and once a minute adds its counts into rows its replicas share, one per site and environment that had traffic, at the minute and the hour grain, and into its own row across all sites: a fixed two statements per replica per minute, however many sites or requests. A minute is never counted twice: a flush that fails before it commits is held and tried with the next minute (up to an hour of them), and one whose commit outcome is unknown is dropped. Minute rows are kept 24 hours and hour rows 90 days by default (`sites.traffic`, and Admin > Settings > Sites); the rows past their period are swept hourly. A row's key is the resolved route and the replica's `X-Platform-Instance` only: the request's path, query, host, client address, cookies and user agent never reach a row, a response or the portal. The Prometheus series `site_requests_total` and `site_request_duration_seconds` are unchanged. - `GET /api/v1/portal/sites/{site}/traffic?range=1h|24h|7d|30d&environment=` answers requests by status class and p50, p95 and p99 over time, the range's totals and the same by environment; someone who does not manage the site sees the environments they can open. - The Sites list carries each site's `traffic.requests_24h` and `traffic.p95_ms`. - `manage_site get` answers `traffic`: the last 24 hours, for the site and per environment. - `GET /api/v1/admin/sites/traffic/replicas?range=` answers each replica's figures across all sites, for administrators. ## Reading a site file `GET /api/v1/portal/sites/{site}/file/content?path=[&release=]` answers one file's bytes for the portal's viewer (#2629): dev's file without `release`, that release's with it. It reads as `/file` does: the people who manage the site read dev's source, someone dev is shared with what dev serves; a release's file is read by the people who manage the site, and by anyone else only while an environment they can open serves it. The bytes go out through the same writer every asset and resource uses: a sandbox `Content-Security-Policy`, `nosniff`, a parameter-free content type, private caching, HTML, SVG, JavaScript and XML as attachments, and byte ranges, so a video seeks without the file being read whole. `_redirects` and `_headers` answer their rendered text, and a path outside the tree is refused. ## Naming a new site What a person types in **New site** is input, not the name (#2636). The server turns it into the name every address uses (lowercase; spaces, underscores and other separators become `-`; any other character outside `a-z` and `0-9` is dropped; repeated hyphens collapse; hyphens at the ends go) and checks it: `My Website` becomes `my-website`. `POST /api/v1/portal/sites/check-name` with `{name}` answers the name, the dev and prod addresses, the longest environment name it leaves room for, and the reason it would be refused, creating nothing; `create` applies the same rule. A site name is at most 57 characters, since every address adds `--` and an environment name to it and one part of an address holds 63, and a two-character name makes a form DNS reserves. ## Response headers A `_redirects` rule with status 200 is a rewrite (#2558): the path is answered in place, with status 200, by the file of this site the target names, so a single-page application answers its own routes (`/* /index.html 200`, or `/products/* /index.html 200` for one section). The target is a local path; a file the release holds still answers itself first, and a rewrite to a file the release lacks answers the 404 page. A release may carry a `_headers` file (#2557). Like `_redirects` it is read into the release rather than served, it travels with the release, so a rollback restores the headers that release declared, and it reads and edits like any file (`manage_asset` on `mcp:site:/dev/_headers`). A path line starts a block, in the form a redirect's `from` takes (`/*` matches everything beneath), and each indented `Name: value` line under it is a header every answer under that path carries: ``` /* Content-Security-Policy: default-src 'self'; img-src 'self' data: Permissions-Policy: camera=(), microphone=() /embed/* Content-Security-Policy: frame-ancestors https://partner.example ``` A release may set only `Content-Security-Policy`, `Content-Security-Policy-Report-Only`, `Permissions-Policy`, `Cross-Origin-Opener-Policy`, `Cross-Origin-Embedder-Policy`, `Cross-Origin-Resource-Policy` and `X-Frame-Options`. Any other header (a cookie, caching, CORS), a value holding a control character, or a malformed line refuses the publish, naming the file and line. Where two blocks match a path, the later one's header replaces the earlier one's of the same name. A release that declares no framing rule is served with `Content-Security-Policy: frame-ancestors 'self'`, so nothing on another origin can frame it. Declaring `frame-ancestors` in a `Content-Security-Policy`, or `X-Frame-Options`, replaces the default; a `Content-Security-Policy` without `frame-ancestors` is sent beside it, and a browser enforces both. The platform's own sign-in, no-access and not-found pages keep their own policy, and nothing a release declares reaches them. ## Signing in to a private environment Every request to a private environment, on every path and for `HEAD`, on its pages address or a domain, is checked first, and a refusal holds nothing of the release. - A `GET` or `HEAD` with no valid sign-in goes straight to the portal's sign-in and comes back to the hostname and path it started on, so someone already signed in to the portal arrives with no click. Any other method gets a sign-in page, since it cannot be carried across a redirect. - Signing in hands the portal's session across by a code good for a minute, once, bound to the site, the hostname and the browser that started it. The portal's handoff (`/sites/handoff`) reads the hostname from the request only to choose: it sends the person back only to a hostname the store says serves a private environment of that site, and refuses any other. - The hostname then keeps its own HttpOnly, host-only cookie, bound to that site and that hostname, for an hour. It never receives the portal's session. - Who may open the environment is read on every request, so removing someone, or changing a persona, takes effect on their next one. Files are `Cache-Control: private, no-cache`, so a browser has to come back and be checked. - Administrator, external and persona are read from the live registry, never from the cookie. - API keys are not honored, and every answer carries `X-Robots-Tag: noindex`. - `/_auth`, `/_signin`, `/_signout`, `/_viewer` and, on an environment that is a part of an application, `/endpoints/` are answered before any file, so a release holding those paths cannot stand in for them. A domain beside the portal (portal `portal.example.com`, site `docs.example.com`) can be added and made private when the session cookie names no `Domain`, as it does by default (`__Host-` on https): the site signs people in on its own hostname and never receives the portal's session. A deployment whose session cookie names a `Domain` refuses hostnames under it. ## Inside a private environment A site builds its own access control (roles, per-page rules, what a person can see or do) and uses the platform's sign-in for who someone is. - `/_viewer` answers the signed-in person as JSON: `email`, `user_id`, `persona` and `name` (the directory's display name, empty when it has none). It never carries the cookie or anything signed. At a public domain it answers 401, "nobody is signed in on this site". - When the environment is a part of an application (`add_part kind=site`), its hosts also serve that application's endpoints at `/endpoints//...`, run as the signed-in person (`req["caller"]`), as on the application's page origin. Every site and environment under the pages domain is one site to a browser, so the viewer is attached only to a request the browser marks as coming from this origin (`Sec-Fetch-Site: same-origin`, or `none` for an address the person typed); a sibling site's page cannot call an environment's endpoints as its viewer. At a public domain the endpoints run as nobody. - The platform makes no decision inside the site beyond who may open the environment. ## Pages See the `platform-pages-and-sites` knowledge page for how to build one. What an operator should know: - A page origin answers `/endpoints/...`, `/_static/...`, `/_viewer` and `/_auth`, and every other path with the endpoint named after the application: `/` alone when its path is empty, any path when its path ends in a catch-all `/{route...}` (#2553), which the handler routes itself. Portal, admin and MCP routes do not exist there. - The portal's session never crosses. A signed-in person is handed over by a code good for a minute, once, bound to the browser that started the sign-in; the origin then keeps its own HttpOnly cookie, scoped to one application, for twelve hours. API keys are not honored on a page origin. The page origin answers on the port of `portal.public_base_url`, and the redirect back to it names the stored hostname and that port, nothing the request sent. - A page's content policy is built by the platform per binding: its own origin, `page_cdns` for scripts, styles, images and fonts, and `page_frame_origins`, `page_connect_origins` and `page_form_origins` for `frame-src`, `connect-src` and `form-action` (#2554). Endpoints that do not opt in keep `default-src 'none'; sandbox`, and a page requested on the portal's own origin stays sandboxed. - A handler on the application's origin reads and sets application cookies under the prefix `__Host-app-` (`app-` over http), which no platform cookie has (#2555), and so does one a site environment that is a part of the application calls at `/endpoints/` on the site's own address (#2558). A request with a method other than GET or HEAD carries them only when the browser says it came from that origin. Their values are replaced in every audit row the request writes. - `req["client_ip"]` and an endpoint's `ip_rate_limit` read the client's address through `server.trusted_proxies` (#2556); see [The client's address](configuration.md#the-clients-address). ## Sites A file's bytes are kept once per site, under `sites//objects/` in the portal bucket with their gzip and brotli variants beside them (files published before this stay under `sites//releases//`, named by `site_release_files.stored_in`). Promote and rollback only move an environment's pointer, and `site_deployments` records every move. Serving needs no CDN: strong ETags and `304`, `immutable` on fingerprinted names on a domain, range requests, redirects and a custom 404. A CDN can be put in front later with no change. ### Changing a site in place An agent changes a site with the tools it already has. `manage_asset`'s content actions (`outline`, `locate`, `get_content`, `stats`, `diff`, `patch`) take `mcp:site://` for one file, a path ending in `/` for a folder, and `mcp:site:/` for the whole tree. `version` is the release number, and `base_version` is refused when `dev` has moved past it, with nothing written. `patch` writes a new release derived from the current one. `manage_site publish` with `base` overlays that release: files sent are added or replaced, an entry with `delete: true` removes a path, and the rest carries over. Only `dev` takes a publish, an edit or an overlay, and `promote` moves a finished change to any other environment, so a change made in several patches reaches people in one step. A publish, overlay or patch aimed at any other environment is refused: "environment "prod" is read-only: publish, patch and edits change dev, and a release reaches prod by promote". A build pipeline publishes to `dev` and promotes. Patching needs manage access and a persona that holds `manage_site`, because `manage_asset` would otherwise reach further than `manage_site` does. `diff` and earlier releases need manage. A derived release stores only what differs from its parent, plus a removal row for each deleted path, and `Files` reads the whole set by walking the chain. Every 32nd link stores the whole set again, so a read walks at most 32 releases and a patch on a release of 20,000 files writes one row. The manifest digest is computed over the whole set, so a rollback is provably the same files. A file set is listed with `limit` and `offset`, and a search across a tree reports what it scanned and skipped, so a search that could not reach a file does not read as a clean result. ### Rendering A site with a `_layouts/` folder is rendered during publish, inside the platform, with no build tool: `_layouts/` and `_includes/` hold Liquid templates, `_data//` holds records as JSON, YAML or Markdown, and any `.html`, `.md`, `.xml`, `.json` or `.txt` file with front matter is a page. `for_each` generates one page per record or taxonomy value and `per_page` makes paged lists. A site with no `_layouts/` folder is served exactly as published. A rendered release holds two trees: the output, which is all the gateway reads, and the source, which is what `mcp:site:` references address and what someone who manages the site reads. Someone the site is shared with reads the output. Source is unservable because it is not in the tree that is served. The record of what each output read is stored with the release, and a patch re-renders only the outputs that read a changed file; a change to a layout renders every page using it, in one release. Templates are written by the people who manage a site and their agents, and they run in the platform's process, so each render is bounded: one render at a time per replica, a five-minute deadline, and limits on loop iterations (50,000,000), include depth (32), block nesting (64), the bytes one page can hold (`sites.max_file_bytes`), total output (`sites.max_release_bytes`), output files (`sites.max_release_files`) and records held in memory (256 MiB). A panic in the template engine fails the page. Source and output each count against the limits on their own. A render is a function of the source tree: `date` refuses `now`, loops over objects run in key order, and no template reaches the network or a file outside the tree. A `for` loop's range bounds, and a loop's `limit`, `offset` and `cols`, are whole numbers: a literal, a `size`, the result of integer arithmetic (`plus`, `minus`, `times`, `divided_by` or `modulo` on whole numbers) or a whole number in a JSON or YAML record (#2633). A float such as `6 | divided_by: 2.0` is refused as a bound; `| floor` makes it one. A template error refuses the release, lists every file and line that failed, and leaves the environment where it was. ### TypeScript, TSX and JSX A release with a `_build.json` at its root compiles its TypeScript, TSX and JSX during publish (#2774), with esbuild inside the platform: no Node, npm or `node_modules`. A release without one is published exactly as before. ```json { "entries": ["app.tsx", "admin/admin.tsx"], "imports": { "react": "https://esm.sh/react@18.3.1", "react-dom/client": "https://esm.sh/react-dom@18.3.1/client" }, "remote": "external", "sourcemap": false, "minify": false } ``` Each entry is bundled with the local modules it imports (`./`, `../` or `/`, resolved inside the tree and refused when they leave it) into one ES module at the same path ending `.js`: `app.tsx` is served as `/app.js`, and a CSS file it imports as `/app.css` (with the local stylesheets it `@import`s; its `url()` references and an `@import` of a stylesheet on the web are left as written). A bare import (`react`, `@tanstack/react-query`) is resolved only through `imports`: its own key, a key ending `/` that prefixes it, or, for a path inside a mapped package, that package's URL with the path added (`react/jsx-runtime` from `react`). Every URL is `https` at an exact version (`@18.3.1`); an unmapped bare import, a range such as `@18`, and an `http` URL refuse the publish, naming it. `remote: "external"` (the default) leaves URL imports for the browser to load and reads nothing from the network, so the compile stays a function of the source tree. `remote: "bundle"` fetches them at publish through the egress guard (public `https` only, no redirects, 8 MiB a module, 30 seconds a fetch, kept in the replica's memory by URL) and bundles them, so the release loads nothing from a CDN. `sourcemap: true` writes `app.js.map`, which holds the source text and is served; see `sourcemap` below for `"private"`. The `.ts`, `.tsx`, `.jsx`, `.mts` and `.cts` files and `_build.json` are source: they are stored as `text/plain`, read and patch through `manage_asset`, and are never served. So are a project's package and tooling files at the root of a release with `_build.json` (`package.json`, `package-lock.json`, `pnpm-lock.yaml`, `pnpm-workspace.yaml`, `yarn.lock`, `tsconfig*.json`, `*.config.{js,ts,mjs,cjs,mts,cts}`, and the dotfiles `.nvmrc`, `.node-version`, `.eslintrc*`, `.prettierrc*`, `.editorconfig`, `.browserslistrc`, which a release accepts at its root), and what `exclude` globs name (#2785). `.npmrc` is refused at publish, since it often holds a registry token. In every rendered release `_layouts/`, `_includes/`, `_data/` and the site's guide `AGENTS.md` are never served (#2779, #2782); a release holding any of them is rendered, Liquid running only where it has layouts or does not compile. A file in the release at an output's path, or under `_chunks/`, refuses the publish, naming both, also when a publish with `base` adds it beside an entry that did not change (#2777). A compile error refuses the release, naming each file, line and column, and the environment does not move. Each output records what it read and what it looked for, so a patch compiles again only the entries that read the changed file, and a newer compiler compiles everything again. The render's deadline and limits cover the compile: per entry 2,000 modules, 4 MiB a module, 64 MiB of modules, and `sites.max_file_bytes` of output, within the release's `sites.max_release_bytes` and `sites.max_release_files`. Types are removed, not checked. PostCSS, Sass and Vue or Svelte single-file components need a JavaScript toolchain and are not compiled. The rest of `_build.json`: | Key | What it does | |---|---| | `splitting` | Default `true` (#2778): each `import()` an entry makes becomes a chunk at `/_chunks/-.js` (`ChunkNames`), the entry keeping its path. An entry with no dynamic import is one file, as before; `false` is one file always. Two entries that load the same module write one chunk; the same path with different bytes refuses the publish. Chunks are served `public, max-age=31536000, immutable`; a chunk the current release lacks is served from one of the five releases before it that is not pruned, so a page loaded before a publish still loads its lazy routes. | | `imports` local prefixes | A key ending `/` may map to a folder of the site written from its root, `"@/": "/src/"` (#2781); it resolves through the local resolver, extensions, `index` files and incremental tracking included. | | `define` | `import.meta.env.X` and `process.env.X` replaced by JSON scalars (#2781). A read of an `import.meta.env.X` that `define` does not set, or of `import.meta.env` whole, refuses the publish naming the file, line and key. | | `imports_from` | `"package.json"`: the imports map generated at every publish from package.json and the lockfile, the explicit entries winning (#2785). A library mapped in `imports` publishes though the lockfile does not lock it, the singleton check still judging its URL; a specifier neither locked nor mapped refuses the publish naming it (#2790). `manage_site imports` returns the same map as a proposal; `missing` names only what neither resolves, and with `tailwind` set `tailwindcss` is never proposed. The build report's `start_imports`, `start_bytes`, `start_gzip_bytes` and `largest_inputs` describe the entry and the chunks it imports statically, `largest_inputs_lazy` the chunks loaded later, and the js budgets are judged against what loads at start (#2791). | | `singletons` | Packages beside `react` and `react-dom` only one copy of which may load. In `external` mode a publish is refused when two URLs name one at different versions, a `deps` pin names another version, or an esm.sh URL for a package that peers on one does not pin it; peers come from the lockfile, else the npm registry through the egress guard, and a registry that does not answer leaves them unjudged. | | `exclude` | Globs kept as source and never served. | | `sourcemap` | `true` serves maps to anyone; `"private"` writes them and serves them only on a private environment's own address to someone signed in there who manages the site (owner, a manage grant, or an administrator), recorded on the release as `site_releases.private_maps` (#2784); `false` writes none. `manage_site symbolicate` maps a stack trace through them. | | `tailwind`, `tailwind_input` | Tailwind CSS 4 at an exact version (#2780). `tailwindcss@` is fetched from the npm registry through the egress guard, held to the registry's sha512 integrity, its `dist/lib.js` rewritten for goja by esbuild and kept per version; the stylesheet importing `tailwindcss` is compiled with the release's files split into class candidates (`@source` and `@source not` widen and narrow them), and its output replaces the stylesheet in the entry. No module loader is given, so `@plugin` and `@config` refuse the publish naming the directive. A run is bounded by 30 seconds, 500,000 candidates, 64 MiB of files scanned and 8 MiB of output, and a refusal names the limit. | | `budgets` | Per entry `js`, `js_gzip`, `css`, `css_gzip`: a warning in the publish result past it, never a refusal (#2783). | A JavaScript import of a stylesheet by URL in `external` mode becomes an `@import` of it in the entry's stylesheet (#2779), and `import.meta.site` is defined as the release's `{release, published_at, site}` (#2784): the release's number is fixed before the compile, and a release written by another publish first is refused as a conflict to publish again. An entry that reads `import.meta.site` compiles at every publish. Every publish, patch and dry run returns `builds`, one report per compiled entry from esbuild's metafile (#2783): each output's bytes and gzip bytes, its change against the environment's previous release (a chunk compared by its name without the hash), the ten inputs contributing most bytes, the URLs the entry imports at start, and budget warnings. Reports are kept in the release's render index, which `manage_site build_report` reads. A dry run of an environment's first publish reports `release: null` (#2817). Type checks (#2793), read only by the site's managers since their errors quote the release's source: `"typecheck": {"tsconfig": "tsconfig.json"}` in `_build.json` (tsconfig a `.json` path in the site, default `tsconfig.json`) has each release type-checked after it publishes, a check and never a gate; `manage_site publish` reports the queued check as `typecheck: {id, status}`. Checks run one at a time per replica from `site_typechecks` (migration 000268), in a worker process (the binary run as `mcp-data-platform typecheck-worker`) running TypeScript 7's `@typescript/typescript-wasip1-wasm` `7.1.0-dev.20261030.1` under wazero with `sites.typecheck.memory_limit` (default a quarter of the container's memory limit, 512 MiB to 3 GiB, 3 GiB when none can be read, with a startup warning when the worker, the limit plus 512 MiB, could take more than half the container, #2828) and `timeout` (default 5m), laying the compiler and the release out under `sites.typecheck.dir` (default the temporary directory; an image with no `/tmp` names a volume, and a check that cannot write there fails naming the setting; the laid-out compiler, about 54 MiB, stays once a check has run, each check's files are removed when it ends, no compilation cache is kept on disk unless `sites.typecheck.compile_cache: true` keeps the compiled compiler, about 177 MiB, under `dir/compile-cache` between checks (read in under a second, where compiling it takes about 7 seconds of a fast core and about 100 seconds at a 0.5 CPU limit, holding the replica's CPU limit for the whole check; removed at a start with the setting off; a cache that cannot be read or written never fails a check; it is machine code the worker runs, so `dir` must be writable by the platform alone, #2833), and a volume of its own is advised since an emptyDir past its sizeLimit evicts the pod); the project is mounted at `/project` so a tsconfig `include` may name a file, and a crashed compiler is reported with its panic text (#2830); deleting a site deletes its checks and state (migration 000269); the compiler is fetched from `sites.typecheck.registry` (default the npm registry), verified against its pinned sha512 integrity and cached in the portal bucket under `sites/_typecheck`. Dependency types come from `package-lock.json`, `pnpm-lock.yaml` or a Yarn 1 `yarn.lock`: each package verified against the lockfile's integrity, only `package.json` and `.d.ts`/`.d.mts`/`.d.cts` kept, no install script run, fetched through the egress guard with no redirects, cached by integrity so a second check fetches nothing; a package without a SHA-256 or stronger integrity hash (SHA-1 alone does not count) or an `https` tarball is listed `unverifiable`; a Yarn 2+ lockfile fails the check. Each environment keeps its `.tsbuildinfo` (`site_typecheck_state`). Statuses: `queued`, `running`, `clean`, `errors` (diagnostics with file, line, column, category, code, message, at most 1,000, a diagnostic about the project rather than a file, such as TS18003 for an `include` matching no file, having an empty file and line and column 0, #2834, and `missing`: packages TS2307 could not find), `over_limit`, `unsupported` (no tsconfig at the path, or `compilerOptions.baseUrl`, which TypeScript 7 no longer reads), `failed` (a compiler that exited without a diagnostic is quoted, up to 4 KiB, #2834). Each check reports `duration_ms` and `compile_ms`, the part spent compiling the compiler before it read a file, and logs both in `site type check finished` (#2833). `manage_site build_report` carries the newest check as `typecheck`; `manage_site typecheck` queues it again; portal routes `GET /api/v1/portal/sites/{site}/typechecks`, `GET`/`POST /api/v1/portal/sites/{site}/releases/{number}/typecheck`. `sites.typecheck.enabled` (default on) and a portal bucket are required. `AGENTS.md` at a site's root is the site's guide (#2782): `manage_site get` returns it (up to 32 KiB, noting when it goes on), and the first `manage_asset` read or patch, or `manage_site publish`, on a site in an MCP session carries it as `site_guide`, once per session and site on each replica. The portal's Files tab marks such a site Compiled and opens its TypeScript in the editor. A publish or a copy from the portal runs in the background (`site_jobs`): it goes on if the browser goes away, and a copy can be stopped. A job nobody has reported on for fifteen minutes reads as failed, since the replica running it has stopped. An environment may require approval: a release reaches it only by promote, and someone who is not an administrator files a request in Approvals first. Promote and Approvals show the files changed, added and removed and the redirects added. Every `manage_site` call and every portal write is audited. Requests to a site are not audited individually; they are recorded under the HTTP route `site` (`pages` for an application's page origin) and counted per site and environment in `site_requests_total` and `site_request_duration_seconds`, with `site_cache_reads_total` counting where each file came from (see [Observability](observability.md)). A release is never rendered on the portal's origin. ## Releases kept Each environment keeps its last `keep_releases` distinct releases, the deployment's default (`sites.releases.keep_default`, 50, or **Releases kept per environment** in Admin > Settings > Sites) unless it has its own: `manage_site set_environment keep_releases=N`, `0` for every release, `"default"` to return to the default, also in the environment's Settings dialog in the portal. Only the owner or an administrator changes it, since a lower limit removes rollback history at the next cleanup. A release stays while it is in any environment's window, an environment points at it, an application release pins it, or a pending approval request names it. The daily cleanup (one replica at a time, under an advisory lock) removes every other release's file rows and the objects no kept release names, compressed forms included. A removed release keeps its record, marked `pruned`, so the deployments and approvals that name it read as before; it cannot be served, compared, promoted or rolled back to, and the refusal names the limits (a comparison's refusal names only the release). A move that started while a cleanup was deciding waits for it and is then refused if the cleanup removed its release. A kept release that read its files through a removed one is rewritten first, onto its nearest kept ancestor or whole, and checked to resolve to exactly the files it held. Files stored before v1.157.0 under a release's own prefix stay while any kept release names them. The same cleanup deletes objects under a site that no release names (a render that failed, a delete that failed) once they are older than `orphan_grace`, and refuses a site where more than half of what it holds reads as orphaned. In report mode it decides exactly as delete mode does and deletes nothing. A publish and a cleanup never overlap on one site's stored files. A publish holds them from its first stored file until its release is recorded, and a cleanup holds them from before it decides until its deletes finish (`site_object_holds`). The cleanup leaves a site with a publish in progress for the next run, and a publish that starts while a cleanup is deleting waits up to a minute and is then refused, saying the cleanup is running. Holds expire, so a replica that stopped while holding one blocks the other only for a few minutes; a publish whose hold ran out is refused rather than recorded. A site whose bucket cannot be listed still has its releases cleaned up, and the run reports `orphans_unchecked` for it. | Route | What it does | |---|---| | `GET /api/v1/admin/sites/retention` | The default, the mode, the grace, the interval, and the recent cleanups' counts | | `POST /api/v1/admin/sites/retention/run` | `{mode: "report" or "delete", site?}`: a cleanup now, answering which releases it removes per site and the files, bytes and orphans | `manage_site get` shows each environment's `keep_releases`, `keep_releases_default` and `releases_kept`; `releases` and the portal's release reads carry `pruned` and `kept_by` (the environments, `application ` and `approval` that keep each release). ## Media folders A site mounts managed-resource folders at URL prefixes for images, video and downloads that do not change with its pages: ``` manage_site command=update site=marketing media=[{"prefix":"/media/","scope":"global","folder":"sites/marketing/media"}] ``` `media` is the whole list (`[]` removes every mount), also `PATCH /api/v1/portal/sites/{site}` with `{"media": [...]}` and the Media tab in the portal. A prefix is a path under the site such as `/media/`, never `/`, `/_...` or `/.well-known/`; a site has at most 20. The gateway answers a path from the release first, then the longest mount whose prefix it starts with, then the redirects and the 404 page. A mounted file is served by range with its validators on every environment, with that environment's access; publish, promote and rollback leave media alone and it counts toward no release limit. A file replaced with `manage_resource replace_content` shows at once. A mount serves only what its folder holds now: a file moved out of it stops answering at its old address at once (the library's own reference to the old address keeps working for the file's readers), and a file moved within it answers at its new path. HTML, SVG, JavaScript and XML in a mount are sent as downloads, so a media folder cannot become a second, unreviewed site. Mounting publishes the folder: whoever mounts must manage the site and be able to read the folder, and its files are then public at a public domain. A file in a mounted folder is refused deletion (`manage_resource delete`, or `DELETE /api/v1/resources/{id}` answering 409) unless forced (`force=true`). ## Domains Whoever manages a site adds a domain with `add_domain`, or Add domain on the site page, naming the environment it serves; an environment that does not exist yet is created, placed by `after`; `requires_approval` sent with the domain applies to the environment whether the request creates it or it exists. The domain is **private** unless the request asks for public, which only the owner or an administrator can; on an environment that requires approval, someone who is not an administrator adds it private and the request to make it public goes to Approvals. `dev` cannot have a domain: it is the working copy, not an address people rely on. Only an administrator maps a hostname to an application, whose domain answers by the application's own rules and has no public setting. The gateway answers an added hostname before the platform's routes, so the portal's hostname, the OAuth and sign-in issuers' hostnames, anything under the pages domain and anything under the session cookie's `Domain` are refused. If the deployment answers on any other name, such as an internal service name, list it in `sites.reserved_hostnames`; that name and everything under it are refused too. A domain on an environment that requires approval can be removed only by an administrator, since moving it to another environment would publish to it unapproved. ### Primary and redirecting domains Most public websites answer at two hostnames and want one of them to win: `example.com` serves and `www.example.com` sends its visitors there, or the other way around (#2687). One domain of an environment can be its **primary**, the canonical hostname. Every other domain of that environment either **serves** the release (the default, and every domain added before this) or **redirects**: the gateway answers every request with a permanent redirect to the primary, path and query kept, `301 Moved Permanently` for `GET` and `HEAD` and `308 Permanent Redirect` for any other method, with `Cache-Control: public, max-age=3600`. A redirect domain reads no release and serves nothing. It answers anyone when the primary is public; when the primary is private it asks for the sign-in, as the primary would, before it redirects. Either direction works with no special case for `www.`: whichever domain is primary wins. `add_domain` and `set_domain` take `primary: true` and `mode: serve|redirect`, and the site page's Domains tab shows each domain's role, with **Make primary**, **Redirect to primary** and **Serve here**. Making a domain primary takes the mark from the previous primary, which keeps serving; a primary always serves. A domain cannot redirect on an environment with no primary, and a primary that other domains redirect to cannot be removed or given up until another domain is primary or those domains serve. A change takes effect at once on every replica, and promote and rollback leave it alone: it belongs to the environment's domains, not to a release. The environment's address, and the site's production address, is its primary; a redirect domain is never an address. The temporary, environment-wide redirect is a different thing: [Offline and redirecting](#offline-and-redirecting) answers `302` with `no-store`. `GET /api/v1/admin/sites/domains` lists every site address (each main address and each `--`) and every domain, with each domain's `primary`, `mode` and, for a redirect domain, `redirects_to`, for the system administrator's ingress rules. A redirect domain needs the same ingress and certificate as any other hostname; the gateway answers the redirect. A `--` no certificate can be issued for (a two-character site's, #2611) is left out. ## manage_site | Command | What it does | |---|---| | `create` | A site with `dev` and `prod`, `prod` holding the main address | | `set_environment` | Creates, places or changes an environment: `after` (the environment it goes after, or moves after), `internal_view`, `requires_approval`, `keep_releases` (owner and administrators), `access` (`platform` or `application`, #2878), and `main: true` to give it the main address. `public` is refused: it is a setting of a domain. `status` (`online`, `offline` with `message` and `back_at`, `redirect` with `redirect_to` and `keep_path`) changes what it answers; `rename_to`, alone, renames it; `agents_may_promote` is refused, an administrator's in the portal | | `remove_environment` | Removes an environment between dev and prod with no domain, main address, application part or running job | | `update` | `description`, `owner_email`, `main_environment` to move the main address (`""` gives it to none), and `media`, every mounted resource folder | | `publish` | A new release into `dev` (files, an archive or a folder; `base` overlays dev's release) | | `promote`, `rollback` | Move an environment's pointer; `promote` takes the release of the environment before `to` | | `grant` | `email` or `persona`, `level` (`view`; `manage` is for a person, site-wide), and `environments` the view grant opens (none is every private environment) | | `revoke` | `email` or `persona` | | `add_domain`, `set_domain`, `remove_domain`, `domains` | Domains. `add_domain` with `public` opens the domain to anyone; `set_domain` with `hostname` and `public` changes it later. `primary: true` makes a domain its environment's primary and `mode: redirect` answers it with a permanent redirect to the primary, on either command; `remove_domain` refuses a primary others redirect to. `after` places an environment `add_domain` creates, and `requires_approval` applies to the environment whether it creates it or it exists | | `crawl` | Copies an existing site into `dev` | | `typecheck` | Queues a release's type check again (`environment` default `dev`, `release` default the one it serves); `build_report` carries the newest check under `typecheck` | | `get`, `list`, `releases`, `deployments` | Read; `get` answers the environments in their order, each environment's `addresses` and `pages_addresses`, the site's `production_address` (the portal list's), the site's `domains` with each one's `public`, `primary`, `mode` and `redirects_to`, and `traffic`, the last 24 hours for the site and per environment. `list` takes `query` (a part of a name, description, owner or domain hostname), `limit` (at most 200) and `offset`, answering `total` and each site's `production_addresses` (#2658) | `default`, the old name of `dev`, is read as `dev` wherever an environment is named for one minor release, and the answer carries a `note` saying so. A reference `mcp:site:/default/...` reads as `mcp:site:/dev/...`, and an application part `/default` is added as `/dev`. ## Making a domain public Public is a setting of a domain, not of an environment (#2619). `set_environment` with `public` is refused, naming the domain setting. A domain is added private unless public is asked for (`add_domain` with `public: true`), and its access changes later with `set_domain` (`public: true` or `false`), Make public and Make private on the Domains tab, or `PUT /api/v1/portal/sites/{site}/domains/{hostname}`. Only the owner or an administrator makes a domain public; anyone who manages the site makes one private. On an environment that requires approval, an owner's request files a request in Approvals (purpose `site_public`, naming the domain) and the domain stays private; once it is approved, the same request makes it public. An approval holds for the access it was asked against: a domain made private and then public again asks again. An administrator's own request goes through at once. Every address on the pages domain keeps asking for a sign-in whatever its environment's domains are set to. Caching follows the address: a public domain's answers are cacheable as public answers are (`immutable` on a fingerprinted name, `max-age=0, must-revalidate` otherwise), and every private address answers `Cache-Control: private, no-cache` with `Vary: Cookie`. ## Environments and promotion A site's environments have a stored order, the path a release takes (#2617): - `dev` is always first and `prod` always last. Neither can be moved, and neither can be deleted while the site exists. - A new environment is placed when it is created, with `after` naming the environment it follows: `dev` or one between `dev` and `prod`. Nothing goes after `prod`. With only `dev` and `prod` there is one place, and a new environment goes there; with more, leaving the place out is refused, naming the environments it could follow. - An environment between them can be moved later the same way (`set_environment` with `after`, or Move on its card). Moving one forward past an environment that requires approval is an administrator's: otherwise a release that environment never approved could feed the next one. - Every list of a site's environments follows the stored order: the cards, the Sites list, the Promote dialog and `manage_site get`. **Promotion goes one step.** An environment takes a release only from the environment immediately before it, and only the release that environment serves. With `dev`, `stage`, `prod`, `prod` takes only what `stage` serves. `promote` names the target (`to`); `from`, when given, must be the environment before it, and a `release`, when given, must be the one that environment serves. A refusal names the environment the release must come from, in the same words from the portal, the API and `manage_site`. Nothing is promoted to `dev`, which takes every publish and edit directly. Rollback is unchanged: an environment returns to a release it served before. **Applications.** An application release moves each coupled site environment part, and each linked part it names in `move_sites` (#2679), to what the environment before it serves, and `dev`, which has nothing before it, to the site's newest release. A linked part is otherwise moved only by promote and rollback here. A promotion into an environment that is a part of an application is refused when the release's `_application` file declares a contract range that excludes the application's contract version (see [Applications](applications.md#the-compatibility-contract)). Pins are read before any environment moves, so an application holding both `stage` and `prod` moves each one step in one release, as promoting each would. Application rollback is unchanged. ## Offline and redirecting Every environment other than `dev` has a status (#2631, #2632): **Online**, the default, serves its release; **Offline** answers every address and every path, `/endpoints/` included, with `503 Service Unavailable`, the platform's page showing the site's name and a message (plain text, at most 1,000 characters, with the runes that hide or reorder text removed), `Retry-After` while an expected-back time is set and ahead, `Cache-Control: no-store` and `X-Robots-Tag: noindex`; **Redirecting** answers every address with `302 Found` and `no-store` to an `https://` address, with the request's path and query appended when **Keep the path** is set. The request can only add path below the target: `//evil.example/x` lands at the target's `/evil.example/x`. One status applies at a time, and an environment moves between any two directly. - The access check runs first: on a private address someone not signed in is asked to sign in, and learns neither the message nor where the environment points. - The release pointer is untouched: promote, roll back and publish keep working, and Online serves exactly what the environment then points at. - Anyone who manages the site sets it, at once, even on an environment that requires approval: an outage cannot wait in a queue. The exception is a redirect on an environment that requires approval, set by someone who is not an administrator: it waits in Approvals (purpose `site_redirect`, naming the target), the environment keeps answering as it does, and the same request goes through once it is approved. Lifting a redirect is always immediate. - A redirect target must be an absolute `https://` URL with a host, no user name or password, no control character, at most 2,048 characters, and none of the environment's own domains, the pages domain or the platform's own hostnames, which would loop. - The expected-back time is only what visitors are told: the environment stays offline until someone brings it online. - History records `offline` with its message, `redirect` with its target, and `online`. ## Renaming and removing an environment The environments between `dev` and `prod` can be renamed and removed (#2630); `dev` and `prod` cannot. **Rename** (`set_environment` with `rename_to`, alone, or the PUT route with `rename_to`) takes a name that passes the environment-name and address rules and is not `dev`, `prod`, `default` or one the site uses. One transaction moves every reference: the environment, its domains, its history, its jobs, the main address, each share's environments, the application parts and pins written `/`, pending approvals that target it, and its tile (#2751). It answers at `--` at once; the old `--` answers "Nothing is published here", its domains keep answering, and `mcp:site:/` references written elsewhere stop resolving. **Remove** (`remove_environment`, or `DELETE .../environments/{name}`) is refused while the environment has a domain, holds the main address, is a part of an application or has a job running, each naming what to do first, and only an administrator removes one that requires approval. One transaction removes it, withdraws pending approvals that target it, deletes its tile (#2751), drops it from every share, and **deletes a share that named only it**: an empty list means every private environment, so emptying one would widen it. Its history stays, marked removed, and stops counting toward its release limit, so releases only it kept go at the next sweep; an environment created later with the same name starts with no history. ## Traffic The platform records each site's traffic and latency itself (#2647), so a site's people see it with no Prometheus backend and no grant beyond seeing the site. Each replica tallies every request the gateway answers in memory (one status-class count and one latency bucket, for the site and environment and for the replica: no allocation, no shared lock, no database call on the request path) and once a minute adds its counts into rows its replicas share, one per site and environment that had traffic, at the minute and the hour grain, and into its own row across all sites: a fixed two statements per replica per minute, however many sites or requests. A minute is never counted twice: a flush that fails before it commits is held and tried with the next minute (up to an hour of them), and one whose commit outcome is unknown is dropped. Minute rows are kept 24 hours and hour rows 90 days by default (`sites.traffic`, and Admin > Settings > Sites); the rows past their period are swept hourly. A row's key is the resolved route and the replica's `X-Platform-Instance` only: the request's path, query, host, client address, cookies and user agent never reach a row, a response or the portal. The Prometheus series `site_requests_total` and `site_request_duration_seconds` are unchanged. - `GET /api/v1/portal/sites/{site}/traffic?range=1h|24h|7d|30d&environment=` answers requests by status class and p50, p95 and p99 over time, the range's totals and the same by environment; someone who does not manage the site sees the environments they can open. - The Sites list carries each site's `traffic.requests_24h` and `traffic.p95_ms`. - `manage_site get` answers `traffic`: the last 24 hours, for the site and per environment. - `GET /api/v1/admin/sites/traffic/replicas?range=` answers each replica's figures across all sites, for administrators. ## Reading a site file `GET /api/v1/portal/sites/{site}/file/content?path=[&release=]` answers one file's bytes for the portal's viewer (#2629): dev's file without `release`, that release's with it. It reads as `/file` does: the people who manage the site read dev's source, someone dev is shared with what dev serves; a release's file is read by the people who manage the site, and by anyone else only while an environment they can open serves it. The bytes go out through the same writer every asset and resource uses: a sandbox `Content-Security-Policy`, `nosniff`, a parameter-free content type, private caching, HTML, SVG, JavaScript and XML as attachments, and byte ranges, so a video seeks without the file being read whole. `_redirects` and `_headers` answer their rendered text, and a path outside the tree is refused. ## Naming a new site What a person types in **New site** is input, not the name (#2636). The server turns it into the name every address uses (lowercase; spaces, underscores and other separators become `-`; any other character outside `a-z` and `0-9` is dropped; repeated hyphens collapse; hyphens at the ends go) and checks it: `My Website` becomes `my-website`. `POST /api/v1/portal/sites/check-name` with `{name}` answers the name, the dev and prod addresses, the longest environment name it leaves room for, and the reason it would be refused, creating nothing; `create` applies the same rule. A site name is at most 57 characters, since every address adds `--` and an environment name to it and one part of an address holds 63, and a two-character name makes a form DNS reserves. ## Response headers A `_redirects` rule with status 200 is a rewrite (#2558): the path is answered in place, with status 200, by the file of this site the target names (`/* /index.html 200` for a single-page application); the target is a local path, a file the release holds still answers itself first, and a rewrite to a missing file answers the 404 page. Endpoints a site environment that is a part of an application calls on the site's address read and set the application's cookies as on the application's own address. A release may carry a `_headers` file (#2557). Like `_redirects` it is read into the release rather than served, it travels with the release, so a rollback restores the headers that release declared, and it reads and edits like any file (`manage_asset` on `mcp:site:/dev/_headers`). A path line starts a block, in the form a redirect's `from` takes (`/*` matches everything beneath), and each indented `Name: value` line under it is a header every answer under that path carries: ``` /* Content-Security-Policy: default-src 'self'; img-src 'self' data: Permissions-Policy: camera=(), microphone=() /embed/* Content-Security-Policy: frame-ancestors https://partner.example ``` A release may set only `Content-Security-Policy`, `Content-Security-Policy-Report-Only`, `Permissions-Policy`, `Cross-Origin-Opener-Policy`, `Cross-Origin-Embedder-Policy`, `Cross-Origin-Resource-Policy` and `X-Frame-Options`. Any other header (a cookie, caching, CORS), a value holding a control character, or a malformed line refuses the publish, naming the file and line. Where two blocks match a path, the later one's header replaces the earlier one's of the same name. A release that declares no framing rule is served with `Content-Security-Policy: frame-ancestors 'self'`, so nothing on another origin can frame it. Declaring `frame-ancestors` in a `Content-Security-Policy`, or `X-Frame-Options`, replaces the default; a `Content-Security-Policy` without `frame-ancestors` is sent beside it, and a browser enforces both. The platform's own sign-in, no-access and not-found pages keep their own policy, and nothing a release declares reaches them. ## Signing in to a private environment Every request to a private environment, on every path and for `HEAD`, on its pages address or a domain, is checked first, and a refusal holds nothing of the release. - A `GET` or `HEAD` with no valid sign-in goes straight to the portal's sign-in and comes back to the hostname and path it started on, so someone already signed in to the portal arrives with no click. Any other method gets a sign-in page, since it cannot be carried across a redirect. - Signing in hands the portal's session across by a code good for a minute, once, bound to the site, the hostname and the browser that started it. The portal's handoff (`/sites/handoff`) reads the hostname from the request only to choose: it sends the person back only to a hostname the store says serves a private environment of that site, and refuses any other. - The hostname then keeps its own HttpOnly, host-only cookie, bound to that site and that hostname, for an hour. It never receives the portal's session. - Who may open the environment is read on every request, so removing someone, or changing a persona, takes effect on their next one. Files are `Cache-Control: private, no-cache`, so a browser has to come back and be checked. - Administrator, external and persona are read from the live registry, never from the cookie. - API keys are not honored, and every answer carries `X-Robots-Tag: noindex`. - `/_auth`, `/_signin`, `/_signout`, `/_viewer` and, on an environment that is a part of an application, `/endpoints/` are answered before any file, so a release holding those paths cannot stand in for them. A domain beside the portal (portal `portal.example.com`, site `docs.example.com`) can be added and made private when the session cookie names no `Domain`, as it does by default (`__Host-` on https): the site signs people in on its own hostname and never receives the portal's session. A deployment whose session cookie names a `Domain` refuses hostnames under it. ## Inside a private environment A site builds its own access control (roles, per-page rules, what a person can see or do) and uses the platform's sign-in for who someone is. - `/_viewer` answers the signed-in person as JSON: `email`, `user_id`, `persona` and `name` (the directory's display name, empty when it has none). It never carries the cookie or anything signed. At a public domain it answers 401, "nobody is signed in on this site". - When the environment is a part of an application (`add_part kind=site`), its hosts also serve that application's endpoints at `/endpoints//...`, run as the signed-in person (`req["caller"]`), as on the application's page origin. Every site and environment under the pages domain is one site to a browser, so the viewer is attached only to a request the browser marks as coming from this origin (`Sec-Fetch-Site: same-origin`, or `none` for an address the person typed); a sibling site's page cannot call an environment's endpoints as its viewer. At a public domain the endpoints run as nobody. - The platform makes no decision inside the site beyond who may open the environment. ## Pages See the `platform-pages-and-sites` knowledge page for how to build one. What an operator should know: - A page origin answers only `/`, `/endpoints/...`, `/_static/...`, `/_viewer` and `/_auth`. Portal, admin and MCP routes do not exist there. - The portal's session never crosses. A signed-in person is handed over by a code good for a minute, once, bound to the browser that started the sign-in; the origin then keeps its own HttpOnly cookie, scoped to one application, for twelve hours. API keys are not honored on a page origin. The page origin answers on the port of `portal.public_base_url`, and the redirect back to it names the stored hostname and that port, nothing the request sent. - A page's content policy is built by the platform per binding. Endpoints that do not opt in keep `default-src 'none'; sandbox`, and a page requested on the portal's own origin stays sandboxed. ## Sites A file's bytes are kept once per site, under `sites//objects/` in the portal bucket with their gzip and brotli variants beside them (files published before this stay under `sites//releases//`, named by `site_release_files.stored_in`). Promote and rollback only move an environment's pointer, and `site_deployments` records every move. Serving needs no CDN: strong ETags and `304`, `immutable` on fingerprinted names on a domain, range requests, redirects and a custom 404. A CDN can be put in front later with no change. ### Changing a site in place An agent changes a site with the tools it already has. `manage_asset`'s content actions (`outline`, `locate`, `get_content`, `stats`, `diff`, `patch`) take `mcp:site://` for one file, a path ending in `/` for a folder, and `mcp:site:/` for the whole tree. `version` is the release number, and `base_version` is refused when `dev` has moved past it, with nothing written. `patch` writes a new release derived from the current one. `manage_site publish` with `base` overlays that release: files sent are added or replaced, an entry with `delete: true` removes a path, and the rest carries over. Only `dev` takes a publish, an edit or an overlay, and `promote` moves a finished change to any other environment, so a change made in several patches reaches people in one step. A publish, overlay or patch aimed at any other environment is refused: "environment "prod" is read-only: publish, patch and edits change dev, and a release reaches prod by promote". A build pipeline publishes to `dev` and promotes. Patching needs manage access and a persona that holds `manage_site`, because `manage_asset` would otherwise reach further than `manage_site` does. `diff` and earlier releases need manage. A derived release stores only what differs from its parent, plus a removal row for each deleted path, and `Files` reads the whole set by walking the chain. Every 32nd link stores the whole set again, so a read walks at most 32 releases and a patch on a release of 20,000 files writes one row. The manifest digest is computed over the whole set, so a rollback is provably the same files. A file set is listed with `limit` and `offset`, and a search across a tree reports what it scanned and skipped, so a search that could not reach a file does not read as a clean result. ### Rendering A site with a `_layouts/` folder is rendered during publish, inside the platform, with no build tool: `_layouts/` and `_includes/` hold Liquid templates, `_data//` holds records as JSON, YAML or Markdown, and any `.html`, `.md`, `.xml`, `.json` or `.txt` file with front matter is a page. `for_each` generates one page per record or taxonomy value and `per_page` makes paged lists. A site with no `_layouts/` folder is served exactly as published. A rendered release holds two trees: the output, which is all the gateway reads, and the source, which is what `mcp:site:` references address and what someone who manages the site reads. Someone the site is shared with reads the output. Source is unservable because it is not in the tree that is served. The record of what each output read is stored with the release, and a patch re-renders only the outputs that read a changed file; a change to a layout renders every page using it, in one release. Templates are written by the people who manage a site and their agents, and they run in the platform's process, so each render is bounded: one render at a time per replica, a five-minute deadline, and limits on loop iterations (50,000,000), include depth (32), block nesting (64), the bytes one page can hold (`sites.max_file_bytes`), total output (`sites.max_release_bytes`), output files (`sites.max_release_files`) and records held in memory (256 MiB). A panic in the template engine fails the page. Source and output each count against the limits on their own. A render is a function of the source tree: `date` refuses `now`, loops over objects run in key order, and no template reaches the network or a file outside the tree. A `for` loop's range bounds, and a loop's `limit`, `offset` and `cols`, are whole numbers: a literal, a `size`, the result of integer arithmetic (`plus`, `minus`, `times`, `divided_by` or `modulo` on whole numbers) or a whole number in a JSON or YAML record (#2633). A float such as `6 | divided_by: 2.0` is refused as a bound; `| floor` makes it one. A template error refuses the release, lists every file and line that failed, and leaves the environment where it was. ### TypeScript, TSX and JSX A release with a `_build.json` at its root compiles its TypeScript, TSX and JSX during publish (#2774), with esbuild inside the platform: no Node, npm or `node_modules`. A release without one is published exactly as before. ```json { "entries": ["app.tsx", "admin/admin.tsx"], "imports": { "react": "https://esm.sh/react@18.3.1", "react-dom/client": "https://esm.sh/react-dom@18.3.1/client" }, "remote": "external", "sourcemap": false, "minify": false } ``` Each entry is bundled with the local modules it imports (`./`, `../` or `/`, resolved inside the tree and refused when they leave it) into one ES module at the same path ending `.js`: `app.tsx` is served as `/app.js`, and a CSS file it imports as `/app.css` (with the local stylesheets it `@import`s; its `url()` references and an `@import` of a stylesheet on the web are left as written). A bare import (`react`, `@tanstack/react-query`) is resolved only through `imports`: its own key, a key ending `/` that prefixes it, or, for a path inside a mapped package, that package's URL with the path added (`react/jsx-runtime` from `react`). Every URL is `https` at an exact version (`@18.3.1`); an unmapped bare import, a range such as `@18`, and an `http` URL refuse the publish, naming it. `remote: "external"` (the default) leaves URL imports for the browser to load and reads nothing from the network, so the compile stays a function of the source tree. `remote: "bundle"` fetches them at publish through the egress guard (public `https` only, no redirects, 8 MiB a module, 30 seconds a fetch, kept in the replica's memory by URL) and bundles them, so the release loads nothing from a CDN. `sourcemap: true` writes `app.js.map`, which holds the source text and is served; see `sourcemap` below for `"private"`. The `.ts`, `.tsx`, `.jsx`, `.mts` and `.cts` files and `_build.json` are source: they are stored as `text/plain`, read and patch through `manage_asset`, and are never served. So are a project's package and tooling files at the root of a release with `_build.json` (`package.json`, `package-lock.json`, `pnpm-lock.yaml`, `pnpm-workspace.yaml`, `yarn.lock`, `tsconfig*.json`, `*.config.{js,ts,mjs,cjs,mts,cts}`, and the dotfiles `.nvmrc`, `.node-version`, `.eslintrc*`, `.prettierrc*`, `.editorconfig`, `.browserslistrc`, which a release accepts at its root), and what `exclude` globs name (#2785). `.npmrc` is refused at publish, since it often holds a registry token. In every rendered release `_layouts/`, `_includes/`, `_data/` and the site's guide `AGENTS.md` are never served (#2779, #2782); a release holding any of them is rendered, Liquid running only where it has layouts or does not compile. A file in the release at an output's path, or under `_chunks/`, refuses the publish, naming both, also when a publish with `base` adds it beside an entry that did not change (#2777). A compile error refuses the release, naming each file, line and column, and the environment does not move. Each output records what it read and what it looked for, so a patch compiles again only the entries that read the changed file, and a newer compiler compiles everything again. The render's deadline and limits cover the compile: per entry 2,000 modules, 4 MiB a module, 64 MiB of modules, and `sites.max_file_bytes` of output, within the release's `sites.max_release_bytes` and `sites.max_release_files`. Types are removed, not checked. PostCSS, Sass and Vue or Svelte single-file components need a JavaScript toolchain and are not compiled. The rest of `_build.json`: | Key | What it does | |---|---| | `splitting` | Default `true` (#2778): each `import()` an entry makes becomes a chunk at `/_chunks/-.js` (`ChunkNames`), the entry keeping its path. An entry with no dynamic import is one file, as before; `false` is one file always. Two entries that load the same module write one chunk; the same path with different bytes refuses the publish. Chunks are served `public, max-age=31536000, immutable`; a chunk the current release lacks is served from one of the five releases before it that is not pruned, so a page loaded before a publish still loads its lazy routes. | | `imports` local prefixes | A key ending `/` may map to a folder of the site written from its root, `"@/": "/src/"` (#2781); it resolves through the local resolver, extensions, `index` files and incremental tracking included. | | `define` | `import.meta.env.X` and `process.env.X` replaced by JSON scalars (#2781). A read of an `import.meta.env.X` that `define` does not set, or of `import.meta.env` whole, refuses the publish naming the file, line and key. | | `imports_from` | `"package.json"`: the imports map generated at every publish from package.json and the lockfile, the explicit entries winning (#2785). A library mapped in `imports` publishes though the lockfile does not lock it, the singleton check still judging its URL; a specifier neither locked nor mapped refuses the publish naming it (#2790). `manage_site imports` returns the same map as a proposal; `missing` names only what neither resolves, and with `tailwind` set `tailwindcss` is never proposed. The build report's `start_imports`, `start_bytes`, `start_gzip_bytes` and `largest_inputs` describe the entry and the chunks it imports statically, `largest_inputs_lazy` the chunks loaded later, and the js budgets are judged against what loads at start (#2791). | | `singletons` | Packages beside `react` and `react-dom` only one copy of which may load. In `external` mode a publish is refused when two URLs name one at different versions, a `deps` pin names another version, or an esm.sh URL for a package that peers on one does not pin it; peers come from the lockfile, else the npm registry through the egress guard, and a registry that does not answer leaves them unjudged. | | `exclude` | Globs kept as source and never served. | | `sourcemap` | `true` serves maps to anyone; `"private"` writes them and serves them only on a private environment's own address to someone signed in there who manages the site (owner, a manage grant, or an administrator), recorded on the release as `site_releases.private_maps` (#2784); `false` writes none. `manage_site symbolicate` maps a stack trace through them. | | `tailwind`, `tailwind_input` | Tailwind CSS 4 at an exact version (#2780). `tailwindcss@` is fetched from the npm registry through the egress guard, held to the registry's sha512 integrity, its `dist/lib.js` rewritten for goja by esbuild and kept per version; the stylesheet importing `tailwindcss` is compiled with the release's files split into class candidates (`@source` and `@source not` widen and narrow them), and its output replaces the stylesheet in the entry. No module loader is given, so `@plugin` and `@config` refuse the publish naming the directive. A run is bounded by 30 seconds, 500,000 candidates, 64 MiB of files scanned and 8 MiB of output, and a refusal names the limit. | | `budgets` | Per entry `js`, `js_gzip`, `css`, `css_gzip`: a warning in the publish result past it, never a refusal (#2783). | A JavaScript import of a stylesheet by URL in `external` mode becomes an `@import` of it in the entry's stylesheet (#2779), and `import.meta.site` is defined as the release's `{release, published_at, site}` (#2784): the release's number is fixed before the compile, and a release written by another publish first is refused as a conflict to publish again. An entry that reads `import.meta.site` compiles at every publish. Every publish, patch and dry run returns `builds`, one report per compiled entry from esbuild's metafile (#2783): each output's bytes and gzip bytes, its change against the environment's previous release (a chunk compared by its name without the hash), the ten inputs contributing most bytes, the URLs the entry imports at start, and budget warnings. Reports are kept in the release's render index, which `manage_site build_report` reads. A dry run of an environment's first publish reports `release: null` (#2817). Type checks (#2793), read only by the site's managers since their errors quote the release's source: `"typecheck": {"tsconfig": "tsconfig.json"}` in `_build.json` (tsconfig a `.json` path in the site, default `tsconfig.json`) has each release type-checked after it publishes, a check and never a gate; `manage_site publish` reports the queued check as `typecheck: {id, status}`. Checks run one at a time per replica from `site_typechecks` (migration 000268), in a worker process (the binary run as `mcp-data-platform typecheck-worker`) running TypeScript 7's `@typescript/typescript-wasip1-wasm` `7.1.0-dev.20261030.1` under wazero with `sites.typecheck.memory_limit` (default a quarter of the container's memory limit, 512 MiB to 3 GiB, 3 GiB when none can be read, with a startup warning when the worker, the limit plus 512 MiB, could take more than half the container, #2828) and `timeout` (default 5m), laying the compiler and the release out under `sites.typecheck.dir` (default the temporary directory; an image with no `/tmp` names a volume, and a check that cannot write there fails naming the setting; the laid-out compiler, about 54 MiB, stays once a check has run, each check's files are removed when it ends, no compilation cache is kept on disk unless `sites.typecheck.compile_cache: true` keeps the compiled compiler, about 177 MiB, under `dir/compile-cache` between checks (read in under a second, where compiling it takes about 7 seconds of a fast core and about 100 seconds at a 0.5 CPU limit, holding the replica's CPU limit for the whole check; removed at a start with the setting off; a cache that cannot be read or written never fails a check; it is machine code the worker runs, so `dir` must be writable by the platform alone, #2833), and a volume of its own is advised since an emptyDir past its sizeLimit evicts the pod); the project is mounted at `/project` so a tsconfig `include` may name a file, and a crashed compiler is reported with its panic text (#2830); deleting a site deletes its checks and state (migration 000269); the compiler is fetched from `sites.typecheck.registry` (default the npm registry), verified against its pinned sha512 integrity and cached in the portal bucket under `sites/_typecheck`. Dependency types come from `package-lock.json`, `pnpm-lock.yaml` or a Yarn 1 `yarn.lock`: each package verified against the lockfile's integrity, only `package.json` and `.d.ts`/`.d.mts`/`.d.cts` kept, no install script run, fetched through the egress guard with no redirects, cached by integrity so a second check fetches nothing; a package without a SHA-256 or stronger integrity hash (SHA-1 alone does not count) or an `https` tarball is listed `unverifiable`; a Yarn 2+ lockfile fails the check. Each environment keeps its `.tsbuildinfo` (`site_typecheck_state`). Statuses: `queued`, `running`, `clean`, `errors` (diagnostics with file, line, column, category, code, message, at most 1,000, a diagnostic about the project rather than a file, such as TS18003 for an `include` matching no file, having an empty file and line and column 0, #2834, and `missing`: packages TS2307 could not find), `over_limit`, `unsupported` (no tsconfig at the path, or `compilerOptions.baseUrl`, which TypeScript 7 no longer reads), `failed` (a compiler that exited without a diagnostic is quoted, up to 4 KiB, #2834). Each check reports `duration_ms` and `compile_ms`, the part spent compiling the compiler before it read a file, and logs both in `site type check finished` (#2833). `manage_site build_report` carries the newest check as `typecheck`; `manage_site typecheck` queues it again; portal routes `GET /api/v1/portal/sites/{site}/typechecks`, `GET`/`POST /api/v1/portal/sites/{site}/releases/{number}/typecheck`. `sites.typecheck.enabled` (default on) and a portal bucket are required. `AGENTS.md` at a site's root is the site's guide (#2782): `manage_site get` returns it (up to 32 KiB, noting when it goes on), and the first `manage_asset` read or patch, or `manage_site publish`, on a site in an MCP session carries it as `site_guide`, once per session and site on each replica. The portal's Files tab marks such a site Compiled and opens its TypeScript in the editor. A publish or a copy from the portal runs in the background (`site_jobs`): it goes on if the browser goes away, and a copy can be stopped. A job nobody has reported on for fifteen minutes reads as failed, since the replica running it has stopped. An environment may require approval: a release reaches it only by promote, and someone who is not an administrator files a request in Approvals first. Promote and Approvals show the files changed, added and removed and the redirects added. Every `manage_site` call and every portal write is audited. Requests to a site are not audited individually; they are recorded under the HTTP route `site` (`pages` for an application's page origin) and counted per site and environment in `site_requests_total` and `site_request_duration_seconds`, with `site_cache_reads_total` counting where each file came from (see [Observability](observability.md)). A release is never rendered on the portal's origin. ## Releases kept Each environment keeps its last `keep_releases` distinct releases, the deployment's default (`sites.releases.keep_default`, 50, or **Releases kept per environment** in Admin > Settings > Sites) unless it has its own: `manage_site set_environment keep_releases=N`, `0` for every release, `"default"` to return to the default, also in the environment's Settings dialog in the portal. Only the owner or an administrator changes it, since a lower limit removes rollback history at the next cleanup. A release stays while it is in any environment's window, an environment points at it, an application release pins it, or a pending approval request names it. The daily cleanup (one replica at a time, under an advisory lock) removes every other release's file rows and the objects no kept release names, compressed forms included. A removed release keeps its record, marked `pruned`, so the deployments and approvals that name it read as before; it cannot be served, compared, promoted or rolled back to, and the refusal names the limits (a comparison's refusal names only the release). A move that started while a cleanup was deciding waits for it and is then refused if the cleanup removed its release. A kept release that read its files through a removed one is rewritten first, onto its nearest kept ancestor or whole, and checked to resolve to exactly the files it held. Files stored before v1.157.0 under a release's own prefix stay while any kept release names them. The same cleanup deletes objects under a site that no release names (a render that failed, a delete that failed) once they are older than `orphan_grace`, and refuses a site where more than half of what it holds reads as orphaned. In report mode it decides exactly as delete mode does and deletes nothing. A publish and a cleanup never overlap on one site's stored files. A publish holds them from its first stored file until its release is recorded, and a cleanup holds them from before it decides until its deletes finish (`site_object_holds`). The cleanup leaves a site with a publish in progress for the next run, and a publish that starts while a cleanup is deleting waits up to a minute and is then refused, saying the cleanup is running. Holds expire, so a replica that stopped while holding one blocks the other only for a few minutes; a publish whose hold ran out is refused rather than recorded. A site whose bucket cannot be listed still has its releases cleaned up, and the run reports `orphans_unchecked` for it. | Route | What it does | |---|---| | `GET /api/v1/admin/sites/retention` | The default, the mode, the grace, the interval, and the recent cleanups' counts | | `POST /api/v1/admin/sites/retention/run` | `{mode: "report" or "delete", site?}`: a cleanup now, answering which releases it removes per site and the files, bytes and orphans | `manage_site get` shows each environment's `keep_releases`, `keep_releases_default` and `releases_kept`; `releases` and the portal's release reads carry `pruned` and `kept_by` (the environments, `application ` and `approval` that keep each release). ## Media folders A site mounts managed-resource folders at URL prefixes for images, video and downloads that do not change with its pages: ``` manage_site command=update site=marketing media=[{"prefix":"/media/","scope":"global","folder":"sites/marketing/media"}] ``` `media` is the whole list (`[]` removes every mount), also `PATCH /api/v1/portal/sites/{site}` with `{"media": [...]}` and the Media tab in the portal. A prefix is a path under the site such as `/media/`, never `/`, `/_...` or `/.well-known/`; a site has at most 20. The gateway answers a path from the release first, then the longest mount whose prefix it starts with, then the redirects and the 404 page. A mounted file is served by range with its validators on every environment, with that environment's access; publish, promote and rollback leave media alone and it counts toward no release limit. A file replaced with `manage_resource replace_content` shows at once. A mount serves only what its folder holds now: a file moved out of it stops answering at its old address at once (the library's own reference to the old address keeps working for the file's readers), and a file moved within it answers at its new path. HTML, SVG, JavaScript and XML in a mount are sent as downloads, so a media folder cannot become a second, unreviewed site. Mounting publishes the folder: whoever mounts must manage the site and be able to read the folder, and its files are then public at a public domain. A file in a mounted folder is refused deletion (`manage_resource delete`, or `DELETE /api/v1/resources/{id}` answering 409) unless forced (`force=true`). ## Domains Whoever manages a site adds a domain with `add_domain`, or Add domain on the site page, naming the environment it serves; an environment that does not exist yet is created, placed by `after`; `requires_approval` sent with the domain applies to the environment whether the request creates it or it exists. The domain is **private** unless the request asks for public, which only the owner or an administrator can; on an environment that requires approval, someone who is not an administrator adds it private and the request to make it public goes to Approvals. `dev` cannot have a domain: it is the working copy, not an address people rely on. Only an administrator maps a hostname to an application, whose domain answers by the application's own rules and has no public setting. Primary and redirecting domains (#2687): one domain of an environment can be its primary; every other domain serves the release (the default) or redirects, answered by the gateway with a permanent redirect to the primary, path and query kept (301 for GET and HEAD, 308 otherwise, Cache-Control public, max-age=3600), reading no release. It answers anyone when the primary is public and asks for the sign-in when the primary is private. `add_domain`/`set_domain` take `primary: true` and `mode: serve|redirect`; the portal's Domains tab has a Role column with Make primary, Redirect to primary and Serve here. A new primary takes the mark from the old one, which keeps serving; a redirect needs a primary; a primary others redirect to cannot be removed or given up. Promote and rollback leave it alone. The environment's address and the site's production address is the primary, never a redirect domain. `GET /api/v1/admin/sites/domains`, `manage_site get` and the Site routing items carry `primary`, `mode` and `redirects_to`. Migration 000258. The gateway answers an added hostname before the platform's routes, so the portal's hostname, the OAuth and sign-in issuers' hostnames, anything under the pages domain and anything under the session cookie's `Domain` are refused. If the deployment answers on any other name, such as an internal service name, list it in `sites.reserved_hostnames`; that name and everything under it are refused too. A domain on an environment that requires approval can be removed only by an administrator, since moving it to another environment would publish to it unapproved. `GET /api/v1/admin/sites/domains` lists every site address (each main address and each `--`) and every domain, for the system administrator's ingress rules. A `--` no certificate can be issued for (a two-character site's, #2611) is left out. ## manage_site | Command | What it does | |---|---| | `create` | A site with `dev` and `prod`, `prod` holding the main address | | `set_environment` | Creates, places or changes an environment: `after` (the environment it goes after, or moves after), `internal_view`, `requires_approval`, `keep_releases` (owner and administrators), and `main: true` to give it the main address. `public` is refused: it is a setting of a domain. `status` (`online`, `offline` with `message` and `back_at`, `redirect` with `redirect_to` and `keep_path`) changes what it answers; `rename_to`, alone, renames it; `agents_may_promote` is refused, an administrator's in the portal | | `remove_environment` | Removes an environment between dev and prod with no domain, main address, application part or running job | | `update` | `description`, `owner_email`, `main_environment` to move the main address (`""` gives it to none), and `media`, every mounted resource folder | | `publish` | A new release into `dev` (files, an archive or a folder; `base` overlays dev's release) | | `promote`, `rollback` | Move an environment's pointer; `promote` takes the release of the environment before `to` | | `grant` | `email` or `persona`, `level` (`view`; `manage` is for a person, site-wide), and `environments` the view grant opens (none is every private environment) | | `revoke` | `email` or `persona` | | `add_domain`, `set_domain`, `remove_domain`, `domains` | Domains. `add_domain` with `public` opens the domain to anyone; `set_domain` with `hostname` and `public` changes it later. `after` places an environment `add_domain` creates, and `requires_approval` applies to the environment whether it creates it or it exists | | `crawl` | Copies an existing site into `dev` | | `typecheck` | Queues a release's type check again (`environment` default `dev`, `release` default the one it serves); `build_report` carries the newest check under `typecheck` | | `get`, `list`, `releases`, `deployments` | Read; `get` answers the environments in their order, each environment's `addresses` and `pages_addresses`, the site's `production_address` (the portal list's), the site's `domains` with each one's `public`, and `traffic`, the last 24 hours for the site and per environment. `list` takes `query` (a part of a name, description, owner or domain hostname), `limit` (at most 200) and `offset`, answering `total` and each site's `production_addresses` (#2658) | `default`, the old name of `dev`, is read as `dev` wherever an environment is named for one minor release, and the answer carries a `note` saying so. A reference `mcp:site:/default/...` reads as `mcp:site:/dev/...`, and an application part `/default` is added as `/dev`. ## Portal routes | Route | What it does | |---|---| | `GET /api/v1/portal/shared-sites` | The environments a share to the caller's verified email or persona opens, each `{site, environment, address, online, message?}`, in site name order; `[]` for none. Every signed-in person, external included; nothing else of those sites is named (#2718) | | `GET /api/v1/portal/sites?q=&limit=&offset=` | The sites `q` names (a part of a name, description, owner or domain hostname, any case), `limit` at a time (at most 200, every match without it) from `offset`; `total` counts every match (#2658) | | `GET /api/v1/portal/sites/{site}/environments/{name}/tile` | The environment's tile, a PNG of the release it serves, to someone who may open the environment; 404 for none drawn yet for its current release, no release, offline or redirecting, or one the caller may not open (#2658). Tiles are drawn by the tile worker from the release's own files read in process, nothing fetched from any hostname, kept in site_tiles (migration 000253) under the release they are of and redrawn when it changes. A tile waits for the fonts and the images in its 1280x960 frame only, never one below the fold (lazy or not), an off-canvas slide or a content-visibility section (#2677); a page that misses the render deadline is the release's failure recorded on its first attempt, carried on the Sites list as the environment's tile_failure and shown as "Can't draw" with the reason; only a renderer that stops answering is retried (#2664) | | `PUT /api/v1/portal/sites/{site}/environments/{name}` | Creates, places or changes an environment. Body `{requires_approval?, internal_view?, keep_releases?, after?, agents_may_promote?, access?, status?, message?, back_at?, redirect_to?, keep_path?, reason?, rename_to?}`, a field left out left alone; `keep_releases` is a number or `"default"`, `agents_may_promote` is an administrator's, and `public` is refused. Answers `{site, status, note?, approval?}` | | `DELETE /api/v1/portal/sites/{site}/environments/{name}` | Removes an environment between dev and prod | | `POST /api/v1/portal/sites/check-name` | `{name}`: what the typed name becomes, its addresses, `environment_name_room` and `refusal?` | | `GET /api/v1/portal/sites/{site}/file/content?path=&release=` | One file's bytes for the viewer | | `GET /api/v1/portal/sites/{site}/traffic?range=&environment=` | The site's traffic | | `POST /api/v1/portal/sites/{site}/domains` | `{hostname, environment, public?, reason?, requires_approval?, before?, after?}`. Answers the domain with `status` (`done` or `awaiting_approval`) and `approval?` | | `PUT /api/v1/portal/sites/{site}/domains/{hostname}` | `{public, reason?}`: makes one domain public or private. Answers as above | | `PUT /api/v1/portal/sites/{site}/main-environment` | `{environment}`; `""` gives the main address to none. Owner and administrators | | `GET /api/v1/portal/sites/{site}/access` | `{owner_email, grants, personas}`: each grant's `email` or `persona`, `level` and `environments`, and every persona a share can name | | `PUT /api/v1/portal/sites/{site}/access` | `{email? or persona?, level, environments?, notify?}` | | `DELETE /api/v1/portal/sites/{site}/access?email=` or `?persona=` | Removes the grant; applies on the next request | | `POST /api/v1/portal/sites/{site}/publish` | `environment` is `dev`, and may be left out | A site's JSON carries `main_environment`, `address` (the production address: where the environment holding the main address is reached, its public domain first, then any other domain mapped to it, then its pages address, `""` when the main address is given to none, #2658), `more_domains` (how many other domains that environment answers at), `addresses` (where people reach each environment: a public domain first, then another domain, otherwise its pages address), `pages_addresses` (each environment's address on the pages domain: the main address for the one holding it, otherwise `--`, which answers only where the deployment's ingress routes it), `address_note` when a two-character name leaves its environments without a pages address, `domains` with each one's `public`, and per environment, in the site's order, `public_domains` and `internal_view`. `addresses` and `pages_addresses` are the ones `manage_site get` answers (#2607). ## In the portal The Sites section's Environments tab opens with **How this site works**: changes land in dev, promote what is ready one step at a time, and every pages address asks for a sign-in, with only a domain set public opening to anyone. It can be hidden. Each environment is a card, in the site's stored order, `dev` first and `prod` last, each marked **Always first** or **Always last**. A card shows a **Private** or **Public domain** badge, Requires approval, its release, its addresses and **Who can open it**, with Publish (dev only), Promote, Roll back, Share, Move (an environment between dev and prod, when there is somewhere to move it) and Settings. Each address carries its tag (**Domain**, **Main address** or **Pages address**) and its access: every pages address **Private**, each domain **Private** or **Public**. The domain people use comes first and every later address is muted (#2607). **Who can open it** names anyone at each public domain, then who opens the environment everywhere else after a sign-in. An environment with no domain says how to open it to anyone. A site with an `address_note` (#2611) shows it under **The environments of `` have no pages address**. **Main address**, **Add domain** and **New environment** sit above the cards. The **New site** dialog shows both environments and their addresses before the site is created, and refuses a two-character name, saying why. **New environment** shows the new address and the place it goes: with one place it says so, with more it offers each, drawn as the order it makes. **Move** offers the same places, marks the current one, and says what each environment takes from after the move. **Promote** names its one source, the environment before, and its release; with nothing there it says what to promote first. **Add domain** chooses **Private** (the default) or **Public**, which is the owner's or an administrator's; making a domain public asks for the domain's name to be typed, names that one domain, says the pages addresses keep asking for a sign-in, and waits in Approvals where the environment requires it. The Domains tab lists every pages address as Private and each domain with its access and **Make public** or **Make private**. The Access tab lists **Who manages** and **Shared with**. Someone a site is shared with sees only the environments open to them. A site that an application holds as one of its parts names it (#2735): an **Application** fact gives each application's name, linking to its page, and the site's environments it uses, and each environment card it uses says **Used by the application**. Only a reader whose persona reaches the Applications pages (Automations area) is told; the site read answers `applications` (`id`, `name`, `environments`; `[]` when none) and each environment's `application`. ## Worked examples **An intranet** for people who already have platform accounts. `dev` is for the people who develop it; `prod`, on the main address, is for a persona. No domain is needed: everyone signs in. ``` manage_site command=create name=intranet # dev and prod; prod holds the main address manage_site command=set_environment site=intranet environment=prod requires_approval=true manage_site command=grant site=intranet persona=management-team environments=["prod"] manage_site command=publish site=intranet files=[...] # lands in dev manage_site command=promote site=intranet to=prod # from dev, through Approvals ``` `intranet--dev.` opens for the owner, the people who manage the site and administrators; `intranet.` serves `prod` to `management-team`. **A client site** with a client review stage. `stage` is the client's, and `prod` answers anyone at the client's domain. ``` manage_site command=create name=cool-site manage_site command=grant site=cool-site persona=web-team environments=["dev"] manage_site command=set_environment site=cool-site environment=stage # between dev and prod manage_site command=set_environment site=cool-site environment=prod requires_approval=true manage_site command=grant site=cool-site email=client@example.com level=view environments=["stage"] manage_site command=add_domain site=cool-site hostname=cool-site.example.com environment=prod public=true # owner: through Approvals manage_site command=promote site=cool-site to=stage # from dev manage_site command=promote site=cool-site to=prod # from stage, through Approvals ``` `cool-site.` and `cool-site--prod.` still ask for a sign-in; only `cool-site.example.com` answers anyone. ## Upgrading to v1.162.0 (migrations 000249 and 000250) Migration 000249 gives every environment a status, Online for every existing one, and `agents_may_promote`, off; adds `detail`, `decided_by` and `removed_at` to the history and the `offline`, `online`, `redirect` and `rename` actions; and the Approvals purpose `site_redirect`. Migration 000250 adds the traffic rows. After the upgrade an agent's promote, rollback or public domain on an environment other than dev waits on a person (#2643): an administrator who wants a preview environment to keep taking agents' promotions marks it **Agents may promote here**. `create` now turns a typed name into an address (`My Site` becomes `my-site`) rather than refusing it, and a site name longer than 57 characters is refused at create time. ## Upgrading to v1.159.0 (migrations 000244 and 000245) - **Order (000244).** Every site's environments are stored in the order the portal drew them by until now: `dev` first, `prod`, `production` and `live` last, the rest by name between. Every site with no `prod` gets an empty one, last, with no release; its main address stays where it was. Promotion goes one step from here on, so a site that promoted `dev` straight to an environment past `stage` now promotes through `stage`. - **Access (000245).** An environment that was public keeps answering anyone at each of its domains, which become public. Its pages addresses (the main address and `--`) answer only to someone signed in from here on. - **A public environment with no domain stops answering anonymously.** Before 000245 runs, the platform logs the `site_public_without_domain` configuration warning for each one, naming the site and environment. Add a domain to it and set the domain public to open it to anyone again. A deployment already past 000245 is not warned: nothing recorded what was public. - A request still waiting in Approvals to make an environment public is withdrawn, with a note saying public is now a setting of each domain; ask again for a domain. - Existing grants open every environment they opened before, now at every private address of it. ## Upgrading to #2604 (migration 000239) - Every environment named `default` becomes `dev`, with its release, deployment history, domains, jobs and approval requests. A site that already held an environment named `dev` beside `default` has that one renamed first, to `development`, or `dev-previous` when that is taken too. - Every site keeps its main address on `dev`, so `.` serves what it served. - Every environment that already had a domain becomes public, so nothing that answered stops answering. Every other environment is private. - A site's "Everyone internal can view" moves onto `dev`, which is what it opened. - Existing grants name no environment, so they open every private environment. - An application part `/default` becomes `/dev`, in the parts and in every release's pins, so releasing and rolling back the application still move it. - An environment cannot be renamed, so a site whose `dev` was the team's real development environment keeps it as `development` (or `dev-previous`). Before 000239 runs, the platform logs the `site_environment_renamed` configuration warning for each site whose `dev` environment has a domain, naming the site, its domains and the name the environment is given (#2608). A deployment already past 000239 is not warned: nothing recorded what it renamed.