From efb2631e4eff973a2339e70e0f8dfba6635cf053 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sat, 14 Nov 2026 19:47:05 +0000 Subject: [PATCH 01/27] CONTRACT: feat(ui-server): bind managed source to turn authority --- .../managed-reference-source-authority.md | 5 + docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/governed-writable-workers.md | 6 +- docs/decisions/http-api-boundary.md | 8 +- docs/decisions/managed-worktrees.md | 30 +- .../decisions/reference-source-acquisition.md | 61 +++- docs/decisions/scheduled-tasks.md | 2 +- docs/decisions/session-principals.md | 6 +- docs/integration-contract/package-api.md | 21 ++ .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-attachments.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- docs/plans/reviewable-session-safety.md | 6 +- .../migrations/089_reference_acquisitions.sql | 23 ++ .../ui-server/src/activity/ingestion-taint.ts | 5 +- packages/ui-server/src/app.ts | 10 +- .../src/brain/github-reference-access.ts | 3 +- .../src/brain/reference-acquisition.ts | 45 +++ .../src/brain/reference-source-writes.ts | 10 +- .../ui-server/src/brain/reference-source.ts | 153 +++++++++- .../ui-server/src/brain/reference-tools.ts | 16 +- .../src/brain/reference-transport.ts | 13 + .../src/brain/reference-worktrees.ts | 69 +++-- .../src/ws/session-run/backend-entry.ts | 5 + .../tests/github-reference-git.test.ts | 21 ++ .../tests/helpers/reference-pool-double.ts | 2 + .../ui-server/tests/ingestion-taint.test.ts | 10 + .../tests/reference-source-managed.test.ts | 268 ++++++++++++++++++ scripts/native-proof/README.md | 9 + .../native-proof/managed-reference-source.ts | 122 ++++++++ scripts/native-proof/reference-pool.native.ts | 11 + 32 files changed, 853 insertions(+), 97 deletions(-) create mode 100644 .changeset/managed-reference-source-authority.md create mode 100644 packages/ui-server/migrations/089_reference_acquisitions.sql create mode 100644 packages/ui-server/src/brain/reference-acquisition.ts create mode 100644 packages/ui-server/tests/reference-source-managed.test.ts create mode 100644 scripts/native-proof/managed-reference-source.ts diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md new file mode 100644 index 0000000000..40cca548c5 --- /dev/null +++ b/.changeset/managed-reference-source-authority.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 58d23e7af9..d9299a6208 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -64,7 +64,7 @@ next to it. of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, `packages/ui-server/src/brain/client.ts:180-248`, called at - `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:478`). + `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:504`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:507-511`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 7d7b70627e..cffabc3fec 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -4252,7 +4252,7 @@ outside the brain and the strict area root counts any such segment); a fetching or unclassified Bash call (only on a turn without the egress proxy since 2026-11-03, see below); and any MCP tool whose server is not brain-kit's own `brain` or `brain-ui` -(`inputTaintSource`, `packages/ui-server/src/activity/ingestion-taint.ts:95-105`). +(`inputTaintSource`, `packages/ui-server/src/activity/ingestion-taint.ts:99-109`). The fixed list of external-content MCP sources is therefore "every other MCP server", following the rule above that erring towards taint costs only tighter rules (maintainer ruling, 2026-10-22). Historically the first source was the @@ -4306,7 +4306,7 @@ proxy is up, the host tells the turn's recorder (`recorder?.setEgressProxied();`, `packages/ui-server/src/ws/run-session.ts:747`), and its shell calls skip the classifier (`const command = shellProxied ? null : commandTaintSource(tool, input);`, -`packages/ui-server/src/activity/ingestion-taint.ts:97`). A `curl` on such a +`packages/ui-server/src/activity/ingestion-taint.ts:101`). A `curl` on such a turn taints through the proxy's `egress_connection` record. Every non-shell source (web tools, other MCP servers, untrusted areas, marked files) still taints there. A turn without the proxy keeps the classifier unchanged @@ -4450,7 +4450,7 @@ admitted file-tool read of it as untrusted input: a `Read`, `Edit`, `Grep`, reader, whose normalized brain-relative path is marked, or a search whose output names it, records `taint` with `source: "user_marked"` as the session's first source (`fileSource`, -`packages/ui-server/src/activity/ingestion-taint.ts:81-86`). An untrusted area +`packages/ui-server/src/activity/ingestion-taint.ts:85-90`). An untrusted area still names its own source first, and an absolute path outside the brain's host path is not matched against marks. A mark is looked up when the call completes; a lookup that fails counts as marked diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 572ca155d1..f9d4d865a2 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:1019`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1040`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1261`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1081`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1102`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1330`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1285-1306`). That order establishes access; +`packages/ui-server/src/app.ts:1350-1371`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 94d2adf4ae..9194e65c7b 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -7,7 +7,7 @@ commit. It builds on the [acquisition service](reference-source-acquisition.md) and the pool's [checkpoints and access generations](reference-pool-accounting.md#worktree-checkpoints-and-access-generations-2430). This record names the concrete choices the rulings left to implementation. The service is `createReferenceWorktrees` -(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:150-694`), +(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:151-695`), created with the acquisition service. The agent tools that call it arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) ([agent tools](#agent-tools)). Hygiene findings, review and cleanup arrived with [#2431](https://github.com/schlessera/brain-kit/issues/2431) @@ -19,7 +19,7 @@ A request names the principal, a repository and a branch or tag, like a source request. The service asks the acquisition service for that source, so its authority, freshness and private boundary all apply, and then snapshots the sealed source root it was given -(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:427-455`). +(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:433-461`). The worktree's starting commit is the commit that source reported, and it never moves with the source. A read-only baseline checkpoint is taken at once. Each worktree gets the pool's per-operation allowance. A worktree belongs to one @@ -39,7 +39,7 @@ restricted (autonomous) turn holds no worktree. The generation records the owning process (PID, start time, boot and PID namespace). Access makes a worktree available to one open generation -(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:513-523`): +(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:525-535`): 1. The generation must be open in this process for a running turn, and belong to the requesting principal. @@ -77,10 +77,10 @@ own generation and its turn no longer runs; that record is process-wide, so every service instance in the process reads the same evidence. Closing a service ends the registration of the generations it opened. Any other case, such as an owner in another PID namespace, is **unknown** -(`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:205-211`). +(`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:206-212`). Reconciliation runs at startup and when a generation closes, never on a timer -(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:590-617`). +(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:613-640`). After three days without explicit activity, a worktree expires: - with a live holder it stays `active` and held, however long the turn runs; @@ -165,7 +165,7 @@ arrive only in the results that grant access. ## Cleanup eligibility facts Release and expiry record durable facts for hygiene review -(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:241-284`): +(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:242-285`): the reason, the holder (`none`, `live` or `unknown`) and whether work remains (`none`, `unpreserved` or `unknown`). Work is read from a fresh read-only checkpoint and a metadata delta against the baseline. Nothing of the worktree @@ -193,7 +193,7 @@ source and worktrees to agents through two bridge tools, `reference_source` and once in the SDK and registered identically by both backends ([MCP contract](../integration-contract/mcp.md#reference-source-and-managed-worktree-tools-additive-0440-2432)). The host side is `createReferenceTools` -(`createReferenceTools`, `packages/ui-server/src/brain/reference-tools.ts:60-200`). +(`createReferenceTools`, `packages/ui-server/src/brain/reference-tools.ts:61-196`). **The turn is the authority.** Before a governed or strict turn's workers start, the host records its principal and what those workers bind: the public @@ -203,7 +203,7 @@ opened A call carries only a repository, a revision or a worktree identity. The bridge adds the turn's own principal, and a call for a turn the host did not prepare, or under another principal, refuses -(`async call(turnId: string`, `packages/ui-server/src/brain/reference-tools.ts:147-196`). +(`async call(turnId: string`, `packages/ui-server/src/brain/reference-tools.ts:149-198`). Every operation then runs through the acquisition and worktree services, which check grants, validation and ownership again; a tool never repeats or skips their rules. Once the turn ends, its record is gone and its bridge holds @@ -215,7 +215,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:747-778`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:868-899`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -255,7 +255,7 @@ check before a new mount) applies to the bind itself. The maintainer ruled on before a turn's workers bind a view, every source in it whose validation lapsed is validated again, including sources a running turn reads; one that fails is withheld from the new bind, and a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:571-609`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:677-715`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -269,7 +269,7 @@ withheld from the new bind, and a running reader keeps its existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:506-517`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:610-621`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -288,7 +288,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:615-624`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:721-730`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a @@ -420,7 +420,7 @@ atomically with grants [pool accounting](reference-pool-accounting.md)), so a grant that lands between the last check and the release fails the removal instead of losing the grant. The worktree service is the only executor, through one effect -(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:333-370`). +(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:334-371`). Immediately before it, with no await between the last check and submission of the receipt: 1. the worktree is released or expired, and no removal of it was already @@ -456,13 +456,13 @@ without another release, which would fail or leave a tombstone identity. The lease owner holds a release's lease again when the pool never committed it (the root is still writable or sealed), so a failed removal stays assessable; it never does so over a newer release of the same identity -(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:377-412`). +(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:378-413`). Capacity is credited only when the pool reports the worktree `reclaimed`: until then its source root stays protected from eviction. **Automatic removal.** Release, expiry and the close of a holding generation remove a worktree only when its fresh assessment shows no holder and no work -(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:302-305`). +(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:303-306`). Reconciliation retries a clean worktree whose removal could not run. Nothing is archived or purged speculatively, and a worktree whose work or owner is unknown is never removed automatically. Arbitrary repositories and shared diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index ff73ddd391..38365bd77b 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:91-786`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:95-790`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -47,12 +47,17 @@ validation lifetime, so later private requests skip the public probe. ## Two clocks +The reuse/outage rules below describe legacy transports. Managed GitHub +requests always perform their own bounded metadata/ref validation, including +inside both windows, and do not serve stale results after identity refusal. +The validation window still governs what a pre-proxy bind may expose. + Each source records `validatedAt`, the last successful authority check of its exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:293-342`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:301-350`). - Inside both windows a request reuses the published source without any network call. @@ -79,18 +84,18 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:408-461`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:415-468`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. 2. The **network transport** fetches one ref into it. It is the only worker that may hold a credential: the granted host variable, delivered through a fixed credential helper, with one allowed protocol and no redirects - (`async fetch({ repository, ref, token, root, signal, wire })`, `packages/ui-server/src/brain/reference-transport.ts:198-219`). + (`async fetch({ repository, ref, token, root, signal, wire })`, `packages/ui-server/src/brain/reference-transport.ts:182-203`). 3. A separate **checkout worker** has no credential and no network. It checks out the commit and evaluates the repository's attributes. No filter or hook is configured, so none runs - (`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:220-229`). + (`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:204-213`). 4. The live grant is read again, the root is sealed, the grant is read again, and only then is the root published. @@ -142,24 +147,50 @@ revision is refused before metadata dispatch, fetch needs that acquisition's resolved full ref, and commit movement refuses before checkout. Failed final identity revalidation ends the acquisition. Cancellation, turn stop and a finite deadline close its sockets; a late successful command cannot outlive -the wire. This wire establishes neither sealed-root provenance nor qualified -immutable-read evidence and enables no repository trust rule by itself. +the wire. The wire alone establishes neither sealed-root provenance nor +qualified immutable-read evidence and enables no repository trust rule. + +Production GitHub acquisition now opens this service on the actual requesting +turn's proxy. Each request, including cache revalidation and worktree source +access, owns its own authority check and budget; it never joins a foreign +turn. The operation limit is 64 MiB or the remaining turn allowance, whichever +is smaller. Lapsed GitHub source found during pre-proxy bind preparation is +withheld without network, then restored only by an explicit admitted request. +Private GitHub acquisition requires the separately approved API credential +recipient even if an older Git-only grant exists; host credential availability +does not silently widen that grant. Other legacy transports retain their +existing access rules and qualify for no repository trust. + +After offline checkout/tree inspection and native sealing, publication +rechecks the acquiring turn, principal, selected grant and final fixed metadata +identity after the source's own exposure lock. It compares sealed/published +root ID, UUID and creation generation, then records those facts together with +the source catalog on the database worker. Lost authority after manager or +database waits withdraws the publication. Recovery compares the retained facts +to the current native sealed root, refusing a different root/generation or +contradictory brain/ref/commit. These host facts are outside repository content +and provider history and are not read receipts. Normal source/worktree file +tools remain workspace restriction signals; shell-local-read coverage retains +its documented limitation. Actual immutable regular-blob/range/digest evidence, +approved-owner matching and complete managed-path native/backend qualification +remain required before repository trust can be enabled. ## Admission At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:233-248`). Requests -for the same source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:251-276`). +(`admit`, `packages/ui-server/src/brain/reference-source.ts:241-256`). Requests +for the same legacy source in the same domain join one operation +(`function join`, `packages/ui-server/src/brain/reference-source.ts:259-284`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one holds only its own slot. At most 64 distinct operations wait; beyond that a request is refused as busy. A requester that cancels leaves its operation, and the operation is cancelled -when its last requester leaves. Readers are never admitted operations: a request -inside both windows only takes a reader lease. No manager lock is held across a +when its last requester leaves. Legacy readers are never admitted operations: a +legacy request inside both windows only takes a reader lease. Managed GitHub +cache validation uses an admitted operation and its own turn budget. No manager lock is held across a fetch; each pool call is one short serialized manager request. ## Readers, refresh and eviction @@ -172,7 +203,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:367-383`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:374-390`). There is no idle expiry. ## Revocation and recovery @@ -185,14 +216,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:657-677`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:775-795`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:680-724`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:798-842`). ## Evidence diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index bd14caa75e..0ac05608dc 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:557-573`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:586-602`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index aa2817c267..7f88e83423 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:1025` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1040`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:1049` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1261-1278` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:1087` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1102`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:1111` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1330-1347` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index d8abff8ab1..aa2b652ab4 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -82,6 +82,27 @@ header selects it. The internal entry also exports the existing DNS address before connecting to a checked IP. These are implementation sharing, with no supported public transport extension seam (#3613). +Production GitHub source requests use that wire through the actual admitted +turn's proxy, including cached-source revalidation and source acquisition for +managed worktrees. They do not join another turn's operation or use another +turn's allowance. A request without that host context refuses. The operation +ceiling is 64 MiB, further bounded by the remaining turn allowance; the finite +wire deadline and ordinary G6 recipient rules remain. Bind preparation happens +before the proxy exists, so expired GitHub source is withheld without network +until an explicit turn request validates it. Other legacy repository transports +remain unqualified for repository trust. + +Migration 089 records a retained source acquisition's host-issued identity, +brain/principal/turn, stable repository and owner identities, resolved ref, +commit/tree, sealed native root ID/UUID/creation generation, selected grant and +charged wire bytes. Publication commits these facts with the source catalog; +restart refuses contradictory root identities. They describe acquisition, +never actual model-content reads or an independently approved owner boundary. +File-tool reads under the reference/worktree worker roots continue to produce +ordinary workspace restriction signals. No repository trust capability is +enabled. Tool names, descriptions, input/result schemas and provider history +are unchanged; actual immutable blob/range/digest evidence remains required. + ## Prepared ordinary inference transport (internal #1665) The existing `WorkerSandbox` input adds optional `@internal egress`, a concrete host-created diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 534dbb27fd..34fa02e1b7 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1040`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1102`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 1efd091450..f41f6c70be 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1040`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1102`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-attachments.md b/docs/plans/chat-attachments.md index 12fa9f3b7c..7870fe9094 100644 --- a/docs/plans/chat-attachments.md +++ b/docs/plans/chat-attachments.md @@ -92,7 +92,7 @@ be up to 25,000,000 bytes, so opening a large original needs its own route ([§6.5](#65-reading-an-original-back)). **Taint.** Reading `.brain-ui/inbox/` or `workspaces/` taints the session -(`leadingArea`, `packages/ui-server/src/activity/ingestion-taint.ts:28-31`). A +(`leadingArea`, `packages/ui-server/src/activity/ingestion-taint.ts:29-32`). A new attachment area is not covered until it is added there. ## 2. Capability matrix diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 650327c382..35f3914a92 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1375-1425`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1440-1490`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:319-332`). A caller deadline diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 07946204a2..4b6e61e2aa 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -29,8 +29,8 @@ public design or its fixtures. Fictional examples use the Odysseus world. their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, - `packages/ui-server/src/activity/ingestion-taint.ts:150`; - `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:172`). + `packages/ui-server/src/activity/ingestion-taint.ts:154`; + `outputTaintSignals`, `packages/ui-server/src/activity/ingestion-taint.ts:176`). Workspace paths taint regardless of repository ownership. Awaited backend hooks commit before tool dispatch/result delivery; display frames alone never prove finalized delivery or complete coverage. @@ -56,7 +56,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. ([reference-source grants](../decisions/reference-source-grants.md)). Its fixed Git transport separates network acquisition from credential-free, network-free checkout (`createReferenceTransport`, - `packages/ui-server/src/brain/reference-transport.ts:116-213`). + `packages/ui-server/src/brain/reference-transport.ts:108-205`). - The Security and Devices & agents surfaces already exist; policy facts are currently read-only (`AgentPolicyGroup`, `packages/ui-react/src/components/settings/agent-policy-group.tsx:8-51`). diff --git a/packages/ui-server/migrations/089_reference_acquisitions.sql b/packages/ui-server/migrations/089_reference_acquisitions.sql new file mode 100644 index 0000000000..b00c8af397 --- /dev/null +++ b/packages/ui-server/migrations/089_reference_acquisitions.sql @@ -0,0 +1,23 @@ +-- Host acquisition bookkeeping, outside repository content and provider history. +-- A retained sealed root has at most one acquisition identity. This is not +-- evidence that any particular bytes were read by a model. +CREATE TABLE reference_acquisitions ( + root_id TEXT PRIMARY KEY REFERENCES reference_roots(id) ON DELETE CASCADE, + acquisition_id TEXT NOT NULL UNIQUE, + brain TEXT NOT NULL, + principal_id TEXT NOT NULL, + turn_id TEXT NOT NULL, + repository_id TEXT NOT NULL, + owner_id TEXT NOT NULL, + owner TEXT NOT NULL, + repository_name TEXT NOT NULL, + ref TEXT NOT NULL, + commit_id TEXT NOT NULL, + tree_id TEXT NOT NULL, + native_root_id TEXT NOT NULL, + native_uuid TEXT NOT NULL, + native_generation TEXT NOT NULL, + grant_id TEXT, + network_bytes INTEGER NOT NULL CHECK (network_bytes >= 0), + acquired_at INTEGER NOT NULL +); diff --git a/packages/ui-server/src/activity/ingestion-taint.ts b/packages/ui-server/src/activity/ingestion-taint.ts index cd1d0bef44..adc9a4e3d1 100644 --- a/packages/ui-server/src/activity/ingestion-taint.ts +++ b/packages/ui-server/src/activity/ingestion-taint.ts @@ -1,7 +1,7 @@ /** Which completed tool calls ingested untrusted content (G6); this grants no tool authority. */ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { posix } from "node:path"; -import { WORKER_AREA_ROOT } from "@schlessera/brain-ui-sdk/internal"; +import { WORKER_AREA_ROOT, WORKER_REFERENCE_ROOT, WORKER_WORKTREE_ROOT } from "@schlessera/brain-ui-sdk/internal"; import { commandTaintSource } from "./command-taint.js"; type IngestionSource = "web_fetch" | "web_search" | "staged_share" | "chat_attachment" | "workspace_read" | "mcp_document" @@ -52,6 +52,9 @@ function pathSource(path: string, brainPath: string | undefined): IngestionSourc return relative.startsWith("../") ? anyArea(relative) : leadingArea(relative); } const absolute = path.startsWith("/") ? posix.normalize(path) : posix.resolve(brainPath!, path); + // A sealed acquisition or writable snapshot alone proves no actual read + // provenance. Ordinary file tools retain the workspace restriction. + if ([WORKER_REFERENCE_ROOT, WORKER_WORKTREE_ROOT].some(root => isWithin(root, absolute, { includeRoot: true }))) return "workspace_read"; for (const root of [brainPath && posix.normalize(brainPath).replace(/\/$/, ""), WORKER_AREA_ROOT]) { if (root && isWithin(root, absolute, { includeRoot: false })) return leadingArea(absolute.slice(root.length + 1)); } diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 2a2a4ce018..caa3cd30ee 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -189,6 +189,7 @@ import type { AppEnv } from "./app-env.js"; import { createNativeBrainLeaseManager } from "./brain/native-brain-leases.js"; import { registerReferenceWrites } from "./brain/reference-writes.js"; import { createReferenceSources } from "./brain/reference-source.js"; +import { createGitHubReferenceAccess } from "./brain/github-reference-access.js"; import { createReferenceTools } from "./brain/reference-tools.js"; import { createComputeHost, readHostedComputeConfig } from "./brain/compute-host.js"; import { createReferenceTransport } from "./brain/reference-transport.js"; @@ -538,9 +539,12 @@ export async function createApp(options: CreateAppOptions = {}): Promise true, () => false); - const referenceSources = referencePoolConfigured ? createReferenceSources({ db, pool: nativeManager, brain: nativeReady.brainUuid, credentials: referenceCredentialValues(), - transport: createReferenceTransport({ brainPath: config.brainPath, ...(config.maintenanceTemp ? { tempLimits: config.maintenanceTemp } : {}), - ...(config.dbPath && config.dbPath !== ":memory:" ? { tempDomain: { statePath: resolve(config.dbPath) } } : {}) }), ...(config.referenceSource ? { limits: config.referenceSource } : {}), log: brainLog, + const referenceCredentials = referenceCredentialValues(); + const referenceTransport = createReferenceTransport({ brainPath: config.brainPath, ...(config.maintenanceTemp ? { tempLimits: config.maintenanceTemp } : {}), + ...(config.dbPath && config.dbPath !== ":memory:" ? { tempDomain: { statePath: resolve(config.dbPath) } } : {}) }); + const referenceSources = referencePoolConfigured ? createReferenceSources({ db, pool: nativeManager, brain: nativeReady.brainUuid, credentials: referenceCredentials, + transport: referenceTransport, github: createGitHubReferenceAccess({ db, brain: nativeReady.brainUuid, credentials: referenceCredentials, transport: referenceTransport }), + ...(config.referenceSource ? { limits: config.referenceSource } : {}), log: brainLog, // Managed worktrees (#2430) keep the source roots they were snapshotted from. dependents: rootId => referenceWorktreeDependents(db, rootId) }) : undefined; // Worktree lifecycle (#2430); every grant is covered by the turn journal first. diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 4075ebcd75..78293f4ca5 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -7,7 +7,7 @@ import { createGitHubReferenceWire } from "./github-reference-wire.js"; import { referenceRevision, ReferenceTransportError, type ReferenceCheck, type ReferenceTransport } from "./reference-transport.js"; type WireOptions = Parameters[0]; -type RequestBounds = Pick; +type RequestBounds = Pick & { current?: () => boolean }; export function createGitHubReferenceAccess(options: { db: Database; @@ -48,6 +48,7 @@ export function createGitHubReferenceAccess(options: { principal(input.principalId); let grant: ReferenceGrant | null = null, credential: string | null = null; const authorize = (recipient: "git" | "metadata", credentialed: boolean) => { + if (input.current && !input.current()) throw new ReferenceTransportError("denied", "the acquiring turn is no longer available"); principal(input.principalId); if (grant) { const current = coveringReferenceGrant(options.db, { brain: options.brain, principalId: input.principalId, repository, now: now() }); diff --git a/packages/ui-server/src/brain/reference-acquisition.ts b/packages/ui-server/src/brain/reference-acquisition.ts new file mode 100644 index 0000000000..c28e8beb62 --- /dev/null +++ b/packages/ui-server/src/brain/reference-acquisition.ts @@ -0,0 +1,45 @@ +/** Retained host acquisition facts. Neither a directory exemption nor a model read receipt. */ +import type { Database } from "bun:sqlite"; +import type { NativePoolRecord } from "@schlessera/brain-ui-sdk/internal"; +import type { GitHubReferenceIdentity } from "./github-reference-identity.js"; +import type { createGitHubReferenceAccess } from "./github-reference-access.js"; + +export interface ReferenceAcquisitionContext { + /** Both values come from the admitted host turn, never from tool input. */ + turnId: string; + egress: Parameters["open"]>[0]["egress"]; + /** Principal/turn and shared recorder health, read again after host waits. */ + current(): boolean; +} + +export interface ReferenceAcquisition { + id: string; + brain: string; + principalId: string; + turnId: string; + identity: GitHubReferenceIdentity; + ref: string; + commit: string; + tree: string; + root: NonNullable; + grantId: string | null; + networkBytes: number; + at: number; +} + +/** Compare retained facts to the manager's current sealed root; paths and names are not identities. */ +export function referenceAcquisitionMatches(db: Database, id: string, record: NativePoolRecord, expected: { + brain: string; commit: string; ref: string | null; identity?: GitHubReferenceIdentity; +}): boolean { + const row = db.query(`SELECT brain, commit_id, ref, repository_id, owner_id, owner, repository_name, native_root_id, native_uuid, native_generation + FROM reference_acquisitions WHERE root_id = ?`).get(id) as { + brain: string; commit_id: string; ref: string; + repository_id: string; owner_id: string; owner: string; repository_name: string; + native_root_id: string; native_uuid: string; native_generation: string; + } | null; + return Boolean(row && record.id === id && record.purpose === "source" && record.state === "sealed" && record.root + && row.brain === expected.brain && row.commit_id === expected.commit && row.ref === expected.ref + && row.native_root_id === record.root.rootId && row.native_uuid === record.root.uuid && row.native_generation === record.root.otransid + && (!expected.identity || row.repository_id === expected.identity.repositoryId && row.owner_id === expected.identity.ownerId + && row.owner === expected.identity.owner && row.repository_name === expected.identity.repository)); +} diff --git a/packages/ui-server/src/brain/reference-source-writes.ts b/packages/ui-server/src/brain/reference-source-writes.ts index 418127267d..bb8763732e 100644 --- a/packages/ui-server/src/brain/reference-source-writes.ts +++ b/packages/ui-server/src/brain/reference-source-writes.ts @@ -1,5 +1,6 @@ /** Reference catalog effects; acquisition and native pool calls stay with the caller (#2999). */ import type { Database } from "bun:sqlite"; +import type { ReferenceAcquisition } from "./reference-acquisition.js"; export function sourceWrites(db: Database) { function sourceView(domain: string, id: string): { id: string; hostPath: string | null } { @@ -41,8 +42,15 @@ export function sourceWrites(db: Database) { const view = sourceView(domain, viewId); return { roots, view }; }, - sourcePublish(path: string, domain: string, repository: string, revision: string, url: string, name: string, id: string, commit: string, ref: string, grantId: string | null, at: number) { + sourcePublish(path: string, domain: string, repository: string, revision: string, url: string, name: string, id: string, commit: string, ref: string, grantId: string | null, at: number, acquisition?: ReferenceAcquisition) { db.transaction(() => { + if (acquisition) db.query(`INSERT INTO reference_acquisitions + (root_id, acquisition_id, brain, principal_id, turn_id, repository_id, owner_id, owner, repository_name, ref, commit_id, tree_id, + native_root_id, native_uuid, native_generation, grant_id, network_bytes, acquired_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, acquisition.id, acquisition.brain, + acquisition.principalId, acquisition.turnId, acquisition.identity.repositoryId, acquisition.identity.ownerId, acquisition.identity.owner, + acquisition.identity.repository, ref, commit, acquisition.tree, acquisition.root.rootId, acquisition.root.uuid, acquisition.root.otransid, + acquisition.grantId, acquisition.networkBytes, acquisition.at); db.query("UPDATE reference_views SET host_path = ? WHERE domain = ?").run(path, domain); db.query("UPDATE reference_roots SET state = 'superseded' WHERE domain = ? AND repository = ? AND revision = ? AND state = 'published'").run(domain, repository, revision); db.query("UPDATE reference_roots SET state = 'published' WHERE id = ?").run(id); diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 5aba499e35..3124f2304d 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -26,6 +26,10 @@ import type { createNativeBrainManagerClient, NativePoolRecord } from "@schlesse import type { Logger } from "@opentelemetry/api-logs"; import { coveringReferenceGrant, isLiveReferenceGrant, referenceRepository, type ReferenceGrant, type ReferenceRepository } from "../db/reference-grants.js"; import { referenceRevision, ReferenceTransportError, type ReferenceTransport } from "./reference-transport.js"; +import type { createGitHubReferenceAccess } from "./github-reference-access.js"; +import { referenceAcquisitionMatches, type ReferenceAcquisition, type ReferenceAcquisitionContext } from "./reference-acquisition.js"; + +type GitHubAccess = Awaited["open"]>>; type Client = ReturnType; export type ReferencePool = Pick; @@ -92,6 +96,8 @@ export function createReferenceSources(options: { db: Database; pool: ReferencePool; transport: ReferenceTransport; brain: string; /** Host environment holding named credential values; a value alone never authorizes. */ credentials: Readonly>; + /** Production GitHub requests require the actual turn's bounded host wire. */ + github?: ReturnType; limits?: Partial; now?: () => number; log?: Logger; @@ -105,6 +111,8 @@ export function createReferenceSources(options: { const write = referenceWrites(db); const now = options.now ?? Date.now; const operations = new Map(); + const operating = (key: string) => [...operations.values()].some(operation => operation.key === key); + const isManaged = (repository: string) => Boolean(options.github && new URL(repository).hostname.toLowerCase() === "github.com"); const leases = new Map(); const withdrawn = new Set(); /** In-flight withdrawals; an acquisition of the same source waits for its withdrawal to finish. */ @@ -218,7 +226,7 @@ export function createReferenceSources(options: { const roots = db.query("SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ? AND state = 'superseded'") .all(domain, repository, revision) as { id: string }[]; for (const root of roots) await releaseRoot(root.id); - if (withdrawn.has(key) && !operations.has(key) && !withdrawals.has(key)) { + if (withdrawn.has(key) && !operating(key) && !withdrawals.has(key)) { await write("sourceForget", domain, repository, revision); withdrawn.delete(key); } @@ -368,7 +376,7 @@ export function createReferenceSources(options: { const candidates = db.query("SELECT * FROM reference_sources ORDER BY last_used_at ASC").all() as SourceRow[]; for (const candidate of candidates) { const key = sourceKey(candidate.domain, candidate.repository, candidate.revision); - if (key === protect || leases.get(key) || operations.has(key)) continue; + if (key === protect || leases.get(key) || operating(key)) continue; const roots = db.query("SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ?").all(candidate.domain, candidate.repository, candidate.revision) as { id: string }[]; if (roots.some(root => options.dependents?.(root.id))) continue; await withdraw(candidate.domain, candidate.repository, candidate.revision); @@ -376,7 +384,7 @@ export function createReferenceSources(options: { } // Superseded roots of sources no reader or operation holds; protected ones stay. const superseded = (db.query("SELECT id, domain, repository, revision FROM reference_roots WHERE state = 'superseded'").all() as { id: string; domain: string; repository: string; revision: string }[]) - .filter(root => { const key = sourceKey(root.domain, root.repository, root.revision); return !leases.get(key) && !operations.has(key) && !options.dependents?.(root.id); }); + .filter(root => { const key = sourceKey(root.domain, root.repository, root.revision); return !leases.get(key) && !operating(key) && !options.dependents?.(root.id); }); let freed = false; for (const root of superseded) { try { await releaseRoot(root.id); freed = true; } catch (error) { warn("reference eviction release failed", error); } } return freed; @@ -406,32 +414,59 @@ export function createReferenceSources(options: { } async function acquire(signal: AbortSignal, input: { domain: string; principalId: string | null; repository: ReferenceRepository; revision: string; grant: ReferenceGrant | null; - credential: string | null; ref: string; expectedCommit: string; previous: SourceRow | null }) { + credential: string | null; ref: string; expectedCommit: string; previous: SourceRow | null; + managed?: { access: GitHubAccess; context: ReferenceAcquisitionContext; id: string; assertCurrent(): void } }) { const { domain, repository, revision } = input, key = sourceKey(domain, repository.canonical, revision); const name = referenceSourceName(repository, revision), view = await viewFor(domain); const staging = { id: randomUUID() }; await write("sourceStage", staging.id, domain, repository.canonical, revision, now()); const previousRoot = input.previous?.root_id ?? null; - const recheck = () => { if (domain !== PUBLIC && (!input.grant || !isLiveReferenceGrant(db, input.grant.id, now()))) authorize(domain, input.principalId, repository); }; + const recheck = () => { + signal.throwIfAborted(); + input.managed?.assertCurrent(); + if (domain !== PUBLIC && (!input.grant || !isLiveReferenceGrant(db, input.grant.id, now()))) authorize(domain, input.principalId, repository); + }; let publishing = false; try { const record = await create(staging, previousRoot, signal, key); recheck(); - const { commit } = await transport.fetch({ repository, ref: input.ref, token: input.credential, root: record.path!, signal }); + const { commit } = input.managed ? await input.managed.access.fetch(record.path!) + : await transport.fetch({ repository, ref: input.ref, token: input.credential, root: record.path!, signal }); if (commit !== input.expectedCommit) throw new ReferenceTransportError("unavailable", "The reference moved after resolution; request it again."); await transport.checkout({ root: record.path!, commit, signal }); signal.throwIfAborted(); recheck(); - await pool.poolSeal(staging.id, signal); + const tree = input.managed ? await transport.tree?.({ root: record.path!, commit, signal }) : undefined; + if (input.managed && !tree) throw new ReferenceSourceError("unavailable", "Managed source tree inspection is unavailable."); + recheck(); + const sealed = await pool.poolSeal(staging.id, signal); + const sealedRoot = sealed.root ? { ...sealed.root } : null; + if (input.managed && (sealed.id !== staging.id || sealed.state !== "sealed" || sealed.purpose !== "source" || !sealed.root)) + throw new ReferenceSourceError("unavailable", "Managed source has no verified sealed root identity."); // Authority is read again immediately before the only step readers can observe. recheck(); signal.throwIfAborted(); await exclusive(key, async () => { + // The source exposure lock can wait independently of all earlier checks. + recheck(); + if (input.managed) await input.managed.access.revalidate(); + recheck(); publishing = true; hiddenRoots.delete(staging.id); const published = await pool.poolPublish(staging.id, view.id, name, signal); + recheck(); + let acquisition: ReferenceAcquisition | undefined; + if (input.managed) { + if (!published.root || published.state !== "sealed" || published.purpose !== "source" || published.id !== staging.id + || published.root.uuid !== sealedRoot!.uuid || published.root.rootId !== sealedRoot!.rootId || published.root.otransid !== sealedRoot!.otransid) + throw new ReferenceSourceError("unavailable", "Managed source root changed during publication."); + acquisition = { id: input.managed.id, brain: options.brain, principalId: input.principalId!, turnId: input.managed.context.turnId, + identity: input.managed.access.identity, ref: input.ref, commit, tree: tree!, root: published.root, + grantId: input.managed.access.grantId, networkBytes: input.managed.access.bytes().chargedBytes, at: now() }; + } const at = now(), grantId = domain === PUBLIC ? null : (input.grant && isLiveReferenceGrant(db, input.grant.id, at) ? input.grant.id : authorize(domain, input.principalId, repository)!.id); - await write("sourcePublish", dirname(published.path!), domain, repository.canonical, revision, repository.url, name, staging.id, commit, input.ref, grantId, at); + await write("sourcePublish", dirname(published.path!), domain, repository.canonical, revision, repository.url, name, staging.id, commit, input.ref, grantId, at, acquisition); + recheck(); withdrawn.delete(key); // A newly validated commit is exposed; the superseded roots leave the view at // once, so a later bind reaches only the commit this request validated. @@ -451,21 +486,91 @@ export function createReferenceSources(options: { // a suspended or lapsed one stays hidden and its name goes. Otherwise fence the source. if (publishing && previousRoot) { const previous = row(domain, repository.canonical, revision); - const exposed = !suspended.has(key) && previous?.root_id === previousRoot && validationLive(previous); + const exposed = !input.managed && !suspended.has(key) && previous?.root_id === previousRoot && validationLive(previous); await exclusive(key, async () => { if (exposed) await pool.poolPublish(previousRoot, view.id, name); else await pool.poolUnpublish(view.id, name); }).catch(async () => { await withdraw(domain, repository.canonical, revision).catch(cleanup => warn("reference source could not be fenced after a lost publication", cleanup)); }); } + if (publishing && input.managed) await withdraw(domain, repository.canonical, revision).catch(cleanup => warn("managed source withdrawal failed", cleanup)); throw error; } } - async function request(input: { principalId: string; repository: unknown; revision: unknown; signal?: AbortSignal }): Promise { + /** No cross-turn joining: every managed request opens and pays for its own live authority check. */ + async function managedRequest(input: { principalId: string; acquisition?: ReferenceAcquisitionContext; signal?: AbortSignal }, repository: ReferenceRepository, revision: string): Promise { + const context = input.acquisition; + if (!context || !context.turnId || !context.current()) throw new ReferenceSourceError("unavailable", "Managed GitHub acquisition needs a live admitted turn and its network budget."); + const controller = new AbortController(), signal = input.signal ? AbortSignal.any([input.signal, controller.signal]) : controller.signal; + const id = randomUUID(); + const operation: Operation = { key: sourceKey(PUBLIC, repository.canonical, revision), domain: PUBLIC, principalId: input.principalId, + grantId: null, controller, joiners: 1, promise: Promise.resolve(undefined as never) }; + const assertTurn = () => { signal.throwIfAborted(); if (closed || !context.current()) throw new ReferenceSourceError("cancelled", "The acquiring turn is no longer available."); }; + let result: ReferenceSourceLease | undefined; + operation.promise = (async () => { + const done = await admit(signal); + let access: GitHubAccess | undefined; + try { + assertTurn(); + const maxBytes = Math.min(64 * 1048576, context.egress.remainingBytes()); + if (maxBytes < 1) throw new ReferenceSourceError("capacity", "The acquiring turn has no network allowance left."); + access = await options.github!.open({ principalId: input.principalId, repository: repository.url, revision, egress: context.egress, maxBytes, signal, + current: () => !closed && context.current() }); + const currentAccess = access; + const assertCurrent = () => { assertTurn(); currentAccess.assertCurrent(); }; + assertCurrent(); + const domain = access.domain === "public" ? PUBLIC : privateDomain(input.principalId); + Object.assign(operation, { domain, grantId: access.grantId, key: sourceKey(domain, repository.canonical, revision) }); + await withdrawals.get(operation.key); + assertCurrent(); + const check = await access.resolve(); + assertCurrent(); + if (!check.ok) throw new ReferenceSourceError(check.reason === "missing" ? "missing" : check.reason === "denied" ? "unauthorized" : "unavailable", check.detail); + const previous = row(domain, repository.canonical, revision); + let reused = false; + if (usable(previous) && previous.commit_id === check.commit && previous.ref === check.ref) { + await exclusive(operation.key, async () => { + assertCurrent(); + const current = row(domain, repository.canonical, revision); + if (!usable(current) || current.root_id !== previous.root_id || withdrawn.has(operation.key)) return; + const record = await pool.poolSeal(current.root_id, signal); + assertCurrent(); + if (!referenceAcquisitionMatches(db, current.root_id, record, { brain: options.brain, commit: check.commit, ref: check.ref, identity: access!.identity })) return; + await access!.revalidate(); + assertCurrent(); + const at = now(); + await write("sourceValidate", at, at, check.ref, domain, repository.canonical, revision); + assertCurrent(); + reused = true; + }); + } + if (!reused) await acquire(signal, { domain, principalId: input.principalId, repository, revision, + grant: domain === PUBLIC ? null : authorize(domain, input.principalId, repository), credential: null, + ref: check.ref, expectedCommit: check.commit, previous, managed: { access, context, id, assertCurrent } }); + assertCurrent(); + const current = row(domain, repository.canonical, revision); + if (!usable(current)) throw new ReferenceSourceError("unavailable", "Managed source publication is unavailable."); + result = await restored(await lease(current, false, null), current, assertCurrent, signal); + assertCurrent(); + return { kind: "source", row: current, stale: false, error: null }; + } catch (error) { + result?.release(); result = undefined; + if (error instanceof ReferenceTransportError) throw new ReferenceSourceError(error.reason === "denied" ? "unauthorized" : error.reason, error.message); + throw error; + } finally { try { await access?.close(); } finally { done(); } } + })(); + operations.set(id, operation); + try { await operation.promise; assertTurn(); return result!; } + catch (error) { result?.release(); throw error; } + finally { operations.delete(id); void settle(...splitKey(operation.key)).catch(error => warn("managed source settle failed", error)); } + } + + async function request(input: { principalId: string; repository: unknown; revision: unknown; signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): Promise { if (closed) throw new ReferenceSourceError("unavailable", "Reference sources are closed."); if (input.signal?.aborted) throw new ReferenceSourceError("cancelled", "Reference acquisition request was cancelled."); let repository: ReferenceRepository, revision: string; try { repository = referenceRepository(input.repository); revision = referenceRevision(input.revision); } catch (error) { throw new ReferenceSourceError("invalid", (error as Error).message); } + if (isManaged(repository.canonical)) return managedRequest(input, repository, revision); const probeKey = `${repository.canonical}\u0000${revision}`; const fresh = (source: SourceRow | null) => usable(source) && validationLive(source) && now() < source.refreshed_at + limits.refreshMs; if (repository.scheme !== "file" && !((notPublic.get(probeKey) ?? 0) > now())) { @@ -522,6 +627,9 @@ export function createReferenceSources(options: { * revision is lost authority, as in a request. */ function revalidate(source: SourceRow & { root_id: string }): Promise { + // A bind occurs before a turn proxy exists. Its lapsed GitHub roots stay + // hidden until an explicit request can validate on that turn's own budget. + if (isManaged(source.repository)) return Promise.resolve(false); const key = sourceKey(source.domain, source.repository, source.revision); const running = revalidations.get(key); if (running) return running; @@ -574,7 +682,7 @@ export function createReferenceSources(options: { const key = sourceKey(source.domain, source.repository, source.revision); // A withdrawal or an operation decides first; then the source is judged as it is now. await abortable(withdrawals.get(key), signal); - await abortable(operations.get(key)?.promise, signal); + await abortable(Promise.allSettled([...operations.values()].filter(operation => operation.key === key).map(operation => operation.promise)), signal); await abortable(exposing.get(key), signal); const current = row(source.domain, source.repository, source.revision); if (!usable(current) || withdrawn.has(key)) continue; @@ -626,18 +734,19 @@ export function createReferenceSources(options: { * The lease is taken first, in the same turn as the outcome, so eviction can * never pick the source while it is being published again. */ - async function restored(held: ReferenceSourceLease, source: SourceRow): Promise { - try { await restore(source); return held; } catch (error) { held.release(); throw error; } + async function restored(held: ReferenceSourceLease, source: SourceRow, assertCurrent?: () => void, signal?: AbortSignal): Promise { + try { await restore(source, assertCurrent, signal); return held; } catch (error) { held.release(); throw error; } } /** * Publish a source a validated request returned, if it was suspended. Under * the source's exposure lock, and only if nothing withdrew, replaced or * outlived it meanwhile. */ - async function restore(source: SourceRow) { + async function restore(source: SourceRow, assertCurrent?: () => void, signal?: AbortSignal) { const key = sourceKey(source.domain, source.repository, source.revision); if (!suspended.has(key)) return; await exclusive(key, async () => { + assertCurrent?.(); if (!suspended.has(key)) return; const current = row(source.domain, source.repository, source.revision); if (withdrawn.has(key) || withdrawals.has(key) || !usable(current) || current.root_id !== source.root_id || !validationLive(current)) @@ -645,7 +754,18 @@ export function createReferenceSources(options: { if (current.domain !== PUBLIC) authorize(current.domain, current.domain.slice("private:".length), referenceRepository(current.repository)); // Until the pool confirms, the exposure is unknown: a failure leaves it for the next bind to take out again. unsettled.add(key); hiddenRoots.delete(current.root_id); - await pool.poolPublish(current.root_id, (await viewFor(current.domain)).id, current.name); + const view = await viewFor(current.domain); + assertCurrent?.(); + try { + await pool.poolPublish(current.root_id, view.id, current.name, signal); + assertCurrent?.(); + } catch (error) { + // A lost reply or authority after manager admission must not leave a + // newly restored name behind. A failed cleanup keeps it unsettled. + await pool.poolUnpublish(view.id, current.name); + await hideRoot(current.root_id); + throw error; + } suspended.delete(key); unsettled.delete(key); }); } @@ -693,6 +813,9 @@ export function createReferenceSources(options: { for (const source of db.query("SELECT * FROM reference_sources WHERE root_id IS NOT NULL").all() as SourceRow[]) { const record = byId.get(source.root_id!); let usableRoot = record?.purpose === "source" && record.state === "sealed"; + if (usableRoot && isManaged(source.repository)) usableRoot = referenceAcquisitionMatches(db, source.root_id!, record!, { + brain: options.brain, commit: source.commit_id!, ref: source.ref, + }); if (usableRoot && source.domain !== PUBLIC) { try { usableRoot = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: source.domain.slice("private:".length), repository: referenceRepository(source.repository), now: now() })); } catch { usableRoot = false; } diff --git a/packages/ui-server/src/brain/reference-tools.ts b/packages/ui-server/src/brain/reference-tools.ts index e701769a8b..49217db8d6 100644 --- a/packages/ui-server/src/brain/reference-tools.ts +++ b/packages/ui-server/src/brain/reference-tools.ts @@ -22,6 +22,7 @@ import { } from "@schlessera/brain-ui-sdk/tool-contracts"; import { ReferenceSourceError, type ReferenceSourceLease, type ReferenceSources } from "./reference-source.js"; import { ReferenceWorktreeError, type ReferenceWorktree, type ReferenceWorktreeGeneration, type ReferenceWorktrees } from "./reference-worktrees.js"; +import type { ReferenceAcquisitionContext } from "./reference-acquisition.js"; /** Distinct sources one turn keeps protected from capacity eviction while it reads them. */ const TURN_LEASES = 32; @@ -55,6 +56,7 @@ interface TurnAccess { views: { public: string; private: string } | null; generation: ReferenceWorktreeGeneration | null; leases: Map; + acquisition?: ReferenceAcquisitionContext; } export function createReferenceTools(options: { @@ -122,6 +124,12 @@ export function createReferenceTools(options: { const current = (turnId: string, access: TurnAccess) => turns.get(turnId) === access; return { + /** The real turn proxy exists only after bind preparation. Never accept a proxy from tool input. */ + attachEgress(turnId: string, principalId: string, input: Omit): void { + const access = turns.get(turnId); + if (!access || access.principalId !== principalId || access.acquisition) throw new ReferenceSourceError("unavailable", "Reference turn egress cannot be attached."); + access.acquisition = { turnId, egress: input.egress, current: () => current(turnId, access) && input.current() }; + }, /** * Record one turn's reference access before its workers start. Opens the * principal's views so the sandbox can bind them; a generation is passed @@ -153,7 +161,7 @@ export function createReferenceTools(options: { if (call.tool === "reference_source") { const input = REFERENCE_SOURCE_INPUT_SCHEMA.parse(call.input); if (!access.views) return { ok: false, code: "unavailable", message: "Shared reference source cannot be bound into this turn's workers." }; - const lease = await options.sources.request({ principalId: access.principalId, repository: input.repository, revision: input.revision, signal }); + const lease = await options.sources.request({ principalId: access.principalId, repository: input.repository, revision: input.revision, signal, acquisition: access.acquisition }); if (!current(turnId, access)) { lease.release(); return ended(); } if (!keep(access, lease)) return { ok: false, code: "busy", message: `This turn already reads ${TURN_LEASES} reference sources; use one of them, or request a worktree.` }; return { ok: true, source: source(access, lease), guidance: SOURCE_GUIDANCE }; @@ -181,13 +189,13 @@ export function createReferenceTools(options: { const generation = access.generation; if (!generation) return { ok: false, code: "unavailable", message: "This turn's workers hold no worktree generation, so no worktree can be made available to them; its change journal may not be recording." }; if (input.action === "access") { - const item = await worktrees.access({ worktreeId: input.worktreeId!, principalId: access.principalId, generation: generation.id, signal }); + const item = await worktrees.access({ worktreeId: input.worktreeId!, principalId: access.principalId, generation: generation.id, signal, acquisition: access.acquisition }); return { ok: true, action: "access", worktree: worktree(access, item, turnId), guidance: WORKTREE_GUIDANCE.access }; } - const allocated = await worktrees.allocate({ principalId: access.principalId, repository: input.repository, revision: input.revision, signal }); + const allocated = await worktrees.allocate({ principalId: access.principalId, repository: input.repository, revision: input.revision, signal, acquisition: access.acquisition }); try { if (!current(turnId, access)) throw new ReferenceWorktreeError("unavailable", "This turn ended before the worktree could be made available to it."); - const item = await worktrees.access({ worktreeId: allocated.id, principalId: access.principalId, generation: generation.id, signal }); + const item = await worktrees.access({ worktreeId: allocated.id, principalId: access.principalId, generation: generation.id, signal, acquisition: access.acquisition }); return { ok: true, action: "request", worktree: worktree(access, item, turnId), guidance: WORKTREE_GUIDANCE.request }; } catch (error) { // Nothing reached a worker: release the untouched worktree rather than leave it to expire. diff --git a/packages/ui-server/src/brain/reference-transport.ts b/packages/ui-server/src/brain/reference-transport.ts index 34227766c9..8374f24fa5 100644 --- a/packages/ui-server/src/brain/reference-transport.ts +++ b/packages/ui-server/src/brain/reference-transport.ts @@ -59,6 +59,8 @@ export interface ReferenceTransport { fetch(input: { repository: ReferenceRepository; ref: string; token: string | null; root: string; signal?: AbortSignal; wire?: GitHubReferenceWire }): Promise<{ commit: string }>; /** Check out `commit` into `root` without any credential or network. */ checkout(input: { root: string; commit: string; signal?: AbortSignal }): Promise; + /** Host-only, offline tree identity; required by managed acquisition, never supplied by a caller. */ + tree?(input: { root: string; commit: string; signal?: AbortSignal }): Promise; } function assertWireRepository(repository: ReferenceRepository, wire?: GitHubReferenceWire): void { @@ -165,6 +167,17 @@ export function createReferenceTransport(options: { return result; } return { + async tree({ root, commit, signal }) { + if (!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(commit)) throw new ReferenceTransportError("invalid", "tree inspection needs one commit id"); + const result = await run(command({ token: null, network: false, mirror: root, signal, + argv: [git(), "--git-dir", join(root, ".git"), "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", + "--no-replace-objects", "rev-parse", "--verify", `${commit}^{tree}`] })); + signal?.throwIfAborted(); + const tree = result.stdout.trim(); + if (result.killed || result.exitCode !== 0 || tree.length !== commit.length || !/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(tree)) + throw new ReferenceTransportError("unavailable", "acquired reference tree is unreadable"); + return tree; + }, async resolve({ repository, revision, token, signal, wire, admissionWaitMs: waitMs }) { revision = referenceRevision(revision); assertWireRepository(repository, wire); diff --git a/packages/ui-server/src/brain/reference-worktrees.ts b/packages/ui-server/src/brain/reference-worktrees.ts index ee8d782132..98dad65bd9 100644 --- a/packages/ui-server/src/brain/reference-worktrees.ts +++ b/packages/ui-server/src/brain/reference-worktrees.ts @@ -28,6 +28,7 @@ import type { Logger } from "@opentelemetry/api-logs"; import { parseNativeBrainDelta, type createNativeBrainManagerClient, type NativePoolCheckpoint, type NativePoolRecord } from "@schlessera/brain-ui-sdk/internal"; import { processAlive, SELF } from "./writer-gate.js"; import { ReferenceSourceError, type ReferenceSources } from "./reference-source.js"; +import type { ReferenceAcquisitionContext } from "./reference-acquisition.js"; /** * Generations whose turn runs in this process (`running`), and the subset that @@ -222,9 +223,9 @@ export function createReferenceWorktrees(options: { * its repository, whatever the revision's current visibility; the * repository's revision is then validated under the source's own clocks. */ - async function authorize(row: Pick, signal?: AbortSignal) { + async function authorize(row: Pick, signal?: AbortSignal, acquisition?: ReferenceAcquisitionContext) { covered(row); - try { (await options.sources.request({ principalId: row.principal_id, repository: row.repository, revision: row.revision, signal })).release(); } + try { (await options.sources.request({ principalId: row.principal_id, repository: row.repository, revision: row.revision, signal, acquisition })).release(); } catch (error) { if (error instanceof ReferenceSourceError) throw new ReferenceWorktreeError(error.code === "cancelled" || error.code === "busy" ? "unavailable" : error.code === "missing" || error.code === "invalid" ? "unauthorized" : error.code, `Worktree authority could not be confirmed: ${error.message}`); @@ -424,10 +425,15 @@ export function createReferenceWorktrees(options: { return worktree(row.id)!; } - async function allocate(input: { principalId: string; repository: unknown; revision: unknown; signal?: AbortSignal }): Promise { + function acquiringTurn(input: { signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): void { + input.signal?.throwIfAborted(); + if (input.acquisition && !input.acquisition.current()) throw new ReferenceWorktreeError("unavailable", "The acquiring turn is no longer available."); + } + + async function allocate(input: { principalId: string; repository: unknown; revision: unknown; signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): Promise { if (closed) throw new ReferenceWorktreeError("unavailable", "Managed worktrees are closed."); let lease; - try { lease = await options.sources.request({ principalId: input.principalId, repository: input.repository, revision: input.revision, signal: input.signal }); } + try { lease = await options.sources.request({ principalId: input.principalId, repository: input.repository, revision: input.revision, signal: input.signal, acquisition: input.acquisition }); } catch (error) { if (error instanceof ReferenceSourceError) throw new ReferenceWorktreeError(error.code === "cancelled" || error.code === "busy" ? "unavailable" : error.code, error.message); throw error; @@ -435,22 +441,28 @@ export function createReferenceWorktrees(options: { const id = randomUUID(), at = now(); try { const allowance = (await pool.poolStatus(input.signal)).limits.operationBytes; + acquiringTurn(input); // Recorded before the pool sees it: recovery and eviction protection both start here. await write("allocate", id, input.principalId, lease.domain === "public" ? "public" : `private:${input.principalId}`, lease.repository, lease.revision, lease.commit, lease.rootId, allowance, at, at); try { + acquiringTurn(input); const created = await pool.poolCreate(id, "worktree", lease.rootId, allowance, input.signal); await write("recordRoot", created.root?.uuid ?? null, id); + acquiringTurn(input); const baseline = randomUUID(); await write("recordBaseline", baseline, id); + acquiringTurn(input); await pool.poolCheckpoint(baseline, id, input.signal); + acquiringTurn(input); + // Allocation is an explicit access: the inactivity clock starts now. + await write("activate", now(), id); + acquiringTurn(input); + return view(worktree(id)!); } catch (error) { await discard(id).catch(cleanup => warn("unfinished worktree was not released; startup recovery retries it", cleanup)); const code = (error as { code?: string }).code; throw new ReferenceWorktreeError(code === "capacity" ? "capacity" : "unavailable", `The worktree could not be created: ${error instanceof Error ? error.message : String(error)}`); } - // Allocation is an explicit access: the inactivity clock starts now. - await write("activate", now(), id); - return view(worktree(id)!); } finally { lease.release(); } } /** Release an unfinished allocation's roots; its record goes only once the pool confirms. */ @@ -510,7 +522,7 @@ export function createReferenceWorktrees(options: { }); } - function access(input: { worktreeId: string; principalId: string; generation: string; signal?: AbortSignal }): Promise { + function access(input: { worktreeId: string; principalId: string; generation: string; signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): Promise { // Registered before any await, so retiring the generation waits for this access. if (!accepting.has(input.generation)) return Promise.reject(new ReferenceWorktreeError("unavailable", "This worker generation is not running; no worktree can be made available to it.")); @@ -521,7 +533,7 @@ export function createReferenceWorktrees(options: { void work.catch(() => {}).finally(() => { pending.delete(work); if (!pending.size) inflight.delete(input.generation); }); return work; } - function grant(input: { worktreeId: string; principalId: string; generation: string; signal?: AbortSignal }): Promise { + function grant(input: { worktreeId: string; principalId: string; generation: string; signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): Promise { return serial(input.worktreeId, async () => { if (closed) throw new ReferenceWorktreeError("unavailable", "Managed worktrees are closed."); const target = generation(input.generation); @@ -538,22 +550,33 @@ export function createReferenceWorktrees(options: { if (holder !== false) throw new ReferenceWorktreeError("busy", holder ? "Another running worker holds this worktree." : "Another worker may still hold this worktree; its liveness is unknown."); row = await recoverHolder(row, input.signal); } - await authorize(row, input.signal); - if (row.holder !== target.id) { - // Coverage first: no worker reaches a worktree its journal does not observe. - await options.coverage({ turnId: target.turn_id, worktreeId: row.id }, input.signal); - // Authority may have ended while revalidation or coverage awaited. - covered(row); - await pool.poolAccess(row.id, target.id, input.signal); - // A removal admitted elsewhere while the grant awaited wins: the grant is withdrawn, never recorded. - if (cleanupOf(row.id)) { - await pool.poolPark(row.id).catch(error => warn("withdrawn worktree grant was not parked", error)); - throw new ReferenceWorktreeError("released", "This worktree was released; request a new one."); + let dispatched = false; + try { + await authorize(row, input.signal, input.acquisition); + acquiringTurn(input); + if (row.holder !== target.id) { + // Coverage first: no worker reaches a worktree its journal does not observe. + await options.coverage({ turnId: target.turn_id, worktreeId: row.id }, input.signal); + // Authority may have ended while revalidation or coverage awaited. + covered(row); + acquiringTurn(input); + dispatched = true; + await pool.poolAccess(row.id, target.id, input.signal); + acquiringTurn(input); + // A removal admitted elsewhere while the grant awaited wins: the grant is withdrawn, never recorded. + if (cleanupOf(row.id)) { + await pool.poolPark(row.id).catch(error => warn("withdrawn worktree grant was not parked", error)); + throw new ReferenceWorktreeError("released", "This worktree was released; request a new one."); + } } + // Explicit access or resumption: the only events, with renewal, that move the clock. + await write("grant", target.id, now(), row.id); + acquiringTurn(input); + return view(worktree(row.id)!); + } catch (error) { + if (input.acquisition && dispatched) await recoverHolder(worktree(row.id) ?? row).catch(cleanup => warn("withdrawn managed worktree grant was not parked", cleanup)); + throw error; } - // Explicit access or resumption: the only events, with renewal, that move the clock. - await write("grant", target.id, now(), row.id); - return view(worktree(row.id)!); }); } /** `live`, when given, is read where the effect runs: a caller whose turn ended changes nothing (#2432). */ diff --git a/packages/ui-server/src/ws/session-run/backend-entry.ts b/packages/ui-server/src/ws/session-run/backend-entry.ts index 7f0dd0601f..cf693a1590 100644 --- a/packages/ui-server/src/ws/session-run/backend-entry.ts +++ b/packages/ui-server/src/ws/session-run/backend-entry.ts @@ -186,6 +186,11 @@ export async function prepareRelayedEgress(run: TurnRun, bridge: BackendBridge, // command classifier (#3429). recorder?.setEgressProxied(); const egress = held.turnEgress, hold = governedHold; + if (held.referenceTurn) host.referenceTools?.attachEgress(turn.turnId, turn.principalId!, { egress, current: () => { + if (abortController.signal.aborted || governanceWrites && !governanceWrites.recordingAvailable(turn.turnId, turn.sessionId ?? null)) return false; + try { const safety = bridge.admissionSafety?.read(); return !safety || safety.authorityCurrent && safety.recordingAvailable; } + catch { return false; } + } }); held.providerRelay = startProviderRelay({ egress, ...(host.cliProviderOrigins ? { origins: host.cliProviderOrigins } : {}), admit: async () => { if(abortController.signal.aborted||governanceWrites&&!governanceWrites.recordingAvailable(turn.turnId,turn.sessionId??null))return {allowed:false,message:"Input recording is unavailable; the turn was stopped."}; diff --git a/packages/ui-server/tests/github-reference-git.test.ts b/packages/ui-server/tests/github-reference-git.test.ts index 65e0a138bb..f5fbba5a83 100644 --- a/packages/ui-server/tests/github-reference-git.test.ts +++ b/packages/ui-server/tests/github-reference-git.test.ts @@ -8,6 +8,8 @@ import { join, resolve } from "node:path"; import { invocationChild } from "../../../scripts/test-invocation-child"; import { startEgressProxy } from "../../ui-sdk/src/server/egress-proxy"; import { createGitHubReferenceAccess } from "../src/brain/github-reference-access"; +import { createReferenceSources } from "../src/brain/reference-source"; +import { referencePoolDouble } from "./helpers/reference-pool-double"; import { createReferenceTransport } from "../src/brain/reference-transport"; import { createUiDb } from "../src/db/client"; import { createPrincipal } from "../src/db/principals"; @@ -165,5 +167,24 @@ test(NAME, async () => { expect(requests).toHaveLength(observed); } finally { await acquisition.close(); } } + // Exercise production source orchestration and offline tree inspection + // with real Git. The directory pool still does not prove native sealing. + privateSource = false; requests.length = 0; launched.length = 0; + const sources = createReferenceSources({ db, brain: "ithaca", pool: referencePoolDouble(join(root, "source-pool")), transport, + credentials: { GITHUB_TOKEN: token }, github: access }); + try { + const lease = await sources.request({ principalId: principal.id, repository: "https://github.com/odysseus/ithaca", revision: "main", + acquisition: { turnId: "odysseus-source-turn", egress, current: () => true } }); + try { + expect(readFileSync(join(lease.viewPath, lease.name, "README.md"), "utf8"), "REFERENCE_ACTUAL_GIT_SOURCE_PUBLICATION") + .toBe("Odysseus revises the Ithaca chart on 2026-07-12.\n"); + expect(db.query("SELECT commit_id, tree_id, turn_id FROM reference_acquisitions WHERE root_id = ?").get(lease.rootId), + "REFERENCE_ACTUAL_GIT_SOURCE_TREE_BOUND").toEqual({ commit_id: git(work, "rev-parse", "HEAD"), + tree_id: git(work, "rev-parse", "HEAD^{tree}"), turn_id: "odysseus-source-turn" }); + expect(launched.filter(value => !value.network)).toHaveLength(3); // fetched commit, checkout, tree. + expect(launched.filter(value => !value.network).every(value => !value.proxy && !value.credential)).toBe(true); + expect(requests.every(value => value.authorization === null)).toBe(true); + } finally { lease.release(); } + } finally { await sources.close(); } } finally { egress.stop(); server?.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } }, 90000); diff --git a/packages/ui-server/tests/helpers/reference-pool-double.ts b/packages/ui-server/tests/helpers/reference-pool-double.ts index cc572fa4fc..05efc36cab 100644 --- a/packages/ui-server/tests/helpers/reference-pool-double.ts +++ b/packages/ui-server/tests/helpers/reference-pool-double.ts @@ -57,6 +57,8 @@ export function referencePoolDouble(root: string, options: { capacityRoots?: num }, async poolSeal(id) { const record = records.get(id); + // The manager also verifies and returns an already sealed retained root. + if (record?.state === "sealed") return record; if (!record || record.state !== "writable") fail("released", "Only a writable reference pool root can be sealed."); note({ operation: "seal", id }); record!.state = "sealed"; diff --git a/packages/ui-server/tests/ingestion-taint.test.ts b/packages/ui-server/tests/ingestion-taint.test.ts index 689b742c61..564a495611 100644 --- a/packages/ui-server/tests/ingestion-taint.test.ts +++ b/packages/ui-server/tests/ingestion-taint.test.ts @@ -7,6 +7,16 @@ import { queryGovernanceEvents, recordGovernanceEvent } from "../src/governance/ const brain = "/srv/odysseus/brain"; +test("unqualified managed reference and worktree file reads retain ordinary workspace restrictions", () => { + for (const path of ["/tmp/brain-reference/public/ithaca/README.md", "/tmp/brain-reference/private/loom/README.md", + "/tmp/brain-worktrees/ithaca/README.md", "/tmp/brain-reference/public/ithaca/../loom/README.md"]) { + expect(inputTaintSource("Read", { file_path: path }, brain), "REFERENCE_PATH_IS_NOT_A_TRUST_EXEMPTION").toBe("workspace_read"); + expect(inputTaintSource("read_file", { path }, brain)).toBe("workspace_read"); + expect(outputTaintSource("Grep", `${path}:1: Odysseus`, brain)).toBe("workspace_read"); + } + expect(inputTaintSource("Read", { file_path: "/tmp/brain-reference-other/README.md" }, brain)).toBeNull(); +}); + test("web, external MCP and untrusted-area reads are taint sources on both backends", () => { for (const [tool, input, source] of [ ["WebFetch", { url: "https://ithaca.invalid" }, "web_fetch"], ["WebSearch", { query: "Ithaca" }, "web_search"], diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts new file mode 100644 index 0000000000..7d9186c343 --- /dev/null +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -0,0 +1,268 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { connect } from "node:net"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { startEgressProxy } from "../../ui-sdk/src/server/egress-proxy"; +import { createGitHubReferenceAccess } from "../src/brain/github-reference-access"; +import { createReferenceSources } from "../src/brain/reference-source"; +import type { ReferenceTransport } from "../src/brain/reference-transport"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal } from "../src/db/principals"; +import { createReferenceGrant, revokeReferenceGrant } from "../src/db/reference-grants"; +import { fixtureTls } from "./fixtures/fixture-tls"; +import { referencePoolDouble } from "./helpers/reference-pool-double"; +import { createReferenceTools } from "../src/brain/reference-tools"; +import { openSqliteWriter } from "../src/db/write-worker"; +import { registerReferenceWrites } from "../src/brain/reference-writes"; +import { createReferenceWorktrees } from "../src/brain/reference-worktrees"; + +const repository = "https://github.com/odysseus/ithaca", commit = "a".repeat(40), tree = "b".repeat(40), brain = "ithaca-brain"; +let root: string, tls: ReturnType; +beforeAll(() => { root = mkdtempSync(join(tmpdir(), "odysseus-managed-source-")); tls = fixtureTls(root, ["api.github.com"]); }); +afterAll(() => rmSync(root, { recursive: true, force: true })); + +async function fixture(options: { private?: boolean; worker?: boolean } = {}) { + const directory = mkdtempSync(join(root, "source-")), db = createUiDb(join(directory, "ui.db")); + const owner = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const other = createPrincipal(db, { authMethod: "password", label: "Telemachus", ttlSeconds: 3600 }); + const writer = options.worker ? openSqliteWriter(db) : undefined; + if (writer) registerReferenceWrites(db, writer); + const metadata: string[] = [], git: unknown[] = []; + const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0 }; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { + metadata.push(request.headers.get("authorization") ?? "anonymous"); + if (options.private && !request.headers.has("authorization")) return new Response(null, { status: 404 }); + return Response.json({ id: 101, owner: { id: state.ownerId, login: "Odysseus" }, name: "Ithaca", full_name: "Odysseus/Ithaca", + clone_url: `${repository}.git`, url: "https://api.github.com/repos/odysseus/ithaca", private: options.private ?? false }); + } }); + const records: unknown[] = []; + const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe(value) { records.push(value); } }); + const secondEgress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe() {} }); + const transport: ReferenceTransport = { + async resolve(input) { git.push(input); return { ok: true, commit, ref: "refs/heads/main" }; }, + async fetch(input) { git.push(input); state.fetches++; writeFileSync(join(input.root, "README.md"), "Odysseus charts Ithaca on 2026-07-12.\n"); return { commit }; }, + async checkout() {}, + async tree() { return tree; }, + }; + const pool = referencePoolDouble(join(directory, "pool")); + const access = (database = db) => createGitHubReferenceAccess({ db: database, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, transport, + wireTransport: { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], + connect: (() => connect({ host: "127.0.0.1", port: server.port! })) as typeof connect } }); + const github = access(); + const sourceOptions = { db, pool, transport, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, github, now: () => state.clock }; + const sources = createReferenceSources(sourceOptions); + const grant = () => createReferenceGrant(db, { brain, principalId: owner.id, createdBy: owner.id, repositoryPrefix: repository, + credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); + const request = (principalId = owner.id, turnId = "odysseus-turn", proxy = egress) => { + const input = { repository, revision: "main", principalId, acquisition: { turnId, egress: proxy, current: () => state.current } }; + return sources.request(input); + }; + return { sources, sourceOptions, request, db, pool, transport, github, owner, other, grant, state, egress, secondEgress, metadata, git, records, + restart(database: ReturnType) { return createReferenceSources({ ...sourceOptions, db: database, github: access(database) }); }, + databasePath: join(directory, "ui.db"), + async close() { await sources.close(); await writer?.close(); egress.stop(); secondEgress.stop(); server.stop(true); db.close(); } }; +} + +test("managed source publishes actual metadata, turn bytes and sealed root/tree facts in one catalog transaction", async () => { + const f = await fixture(); + try { + const lease = await f.request(); + try { + expect(readFileSync(join(lease.viewPath, lease.name, "README.md"), "utf8")).toContain("Odysseus"); + const record = f.pool.records.get(lease.rootId)!; + expect(f.db.query("SELECT * FROM reference_acquisitions WHERE root_id = ?").get(lease.rootId), "REFERENCE_MANAGED_ROOT_MAPPING").toMatchObject({ + brain, principal_id: f.owner.id, turn_id: "odysseus-turn", repository_id: "101", owner_id: "201", owner: "odysseus", + repository_name: "ithaca", ref: "refs/heads/main", commit_id: commit, tree_id: tree, + native_root_id: record.root!.rootId, native_uuid: record.root!.uuid, native_generation: record.root!.otransid, grant_id: null, + }); + expect(f.egress.usedBytes(), "REFERENCE_SOURCE_CHARGES_ACTUAL_TURN").toBeGreaterThan(0); + expect(f.metadata, "REFERENCE_SOURCE_FINAL_IDENTITY_REVALIDATED").toEqual(["anonymous", "anonymous"]); + expect(f.git.every(input => (input as { wire?: unknown }).wire !== undefined), "REFERENCE_SOURCE_NEVER_BYPASSES_WIRE").toBe(true); + } finally { lease.release(); } + } finally { await f.close(); } +}); + +test("managed GitHub requests without an admitted turn budget refuse before any source transport", async () => { + const f = await fixture(); + try { + await expect(f.sources.request({ principalId: f.owner.id, repository, revision: "main" }), "REFERENCE_SOURCE_REQUIRES_REAL_TURN").rejects.toMatchObject({ code: "unavailable" }); + expect(f.git).toEqual([]); expect(f.metadata).toEqual([]); + } finally { await f.close(); } +}); + +test("a cached shared root still uses the requesting principal and turn's own metadata budget", async () => { + const f = await fixture(); + try { + const first = await f.request(); + const second = await f.request(f.other.id, "telemachus-turn", f.secondEgress); + try { + expect(first.rootId).toBe(second.rootId); + expect(f.state.fetches).toBe(1); + expect(f.secondEgress.usedBytes(), "REFERENCE_SOURCE_CACHE_CANNOT_BORROW_TURN_BUDGET").toBeGreaterThan(0); + expect(f.metadata).toHaveLength(4); + } finally { first.release(); second.release(); } + } finally { await f.close(); } +}); + +test("pre-proxy bind preparation with expired GitHub authority withholds source without network", async () => { + const f = await fixture(); + try { + const lease = await f.request(); lease.release(); + f.state.clock += 400_000; + const count = f.git.length, metadata = f.metadata.length; + await f.sources.bindable(f.owner.id); + expect(f.git.length, "REFERENCE_BIND_NEVER_SPENDS_UNBOUND_NETWORK").toBe(count); + expect(f.metadata.length).toBe(metadata); + expect(f.pool.events.some(event => event.operation === "unpublish"), "REFERENCE_BIND_WITHHOLDS_EXPIRED_MANAGED_SOURCE").toBe(true); + } finally { await f.close(); } +}); + +for (const change of ["turn", "grant", "owner", "root"] as const) + test(`managed source refuses ${change} change while sealing before actual publication`, async () => { + const f = await fixture({ private: change === "grant" }), grant = change === "grant" ? f.grant() : null; + const seal = f.pool.poolSeal; + f.pool.poolSeal = async (id, signal) => { + const result = await seal(id, signal); + if (change === "turn") f.state.current = false; + if (change === "grant") revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: grant!.id, now: Date.now() }); + if (change === "owner") f.state.ownerId = 202; + if (change === "root") result.root = null; + return result; + }; + try { + await expect(f.request(), "REFERENCE_MANAGED_FINAL_PUBLICATION_FENCE").rejects.toThrow(); + expect(f.pool.events.filter(event => event.operation === "publish"), "REFERENCE_MANAGED_REFUSAL_HAS_NO_FILE_EFFECT").toEqual([]); + expect(f.db.query("SELECT * FROM reference_acquisitions").all()).toEqual([]); + } finally { await f.close(); } + }); + +test("the host tool attaches only its admitted turn's budget and expires it at turn end", async () => { + const f = await fixture(), tools = createReferenceTools({ sources: f.sources }); + try { + await tools.begin("odysseus-tool-turn", { principalId: f.owner.id, posture: "interactive", generation: null }); + const call = { tool: "reference_source" as const, input: { repository, revision: "main" } }; + expect(await tools.call("odysseus-tool-turn", f.owner.id, call)).toMatchObject({ ok: false, code: "unavailable" }); + expect(() => tools.attachEgress("odysseus-tool-turn", f.other.id, { egress: f.egress, current: () => true })).toThrow(); + tools.attachEgress("odysseus-tool-turn", f.owner.id, { egress: f.egress, current: () => f.state.current }); + expect(() => tools.attachEgress("odysseus-tool-turn", f.owner.id, { egress: f.secondEgress, current: () => true })).toThrow(); + const result = await tools.call("odysseus-tool-turn", f.owner.id, call); + expect(result, "REFERENCE_TOOL_USES_ACTUAL_HOST_TURN").toMatchObject({ ok: true, source: { domain: "public", commit } }); + expect(f.db.query("SELECT turn_id FROM reference_acquisitions").get()).toEqual({ turn_id: "odysseus-tool-turn" }); + tools.end("odysseus-tool-turn"); + expect(await tools.call("odysseus-tool-turn", f.owner.id, call)).toMatchObject({ ok: false, code: "unavailable" }); + } finally { tools.end("odysseus-tool-turn"); await f.close(); } +}); + +test("worker-owned publication persists acquisition facts across a fresh database connection and service restart", async () => { + const f = await fixture({ worker: true }); + try { + const lease = await f.request(), id = lease.rootId; lease.release(); + const original = f.db.query("SELECT * FROM reference_acquisitions").get(); + await f.sources.close(); + const db = createUiDb(f.databasePath), restarted = f.restart(db); + try { + const metadata = f.metadata.length; + await restarted.recover(); + expect(f.metadata.length, "REFERENCE_RESTART_NEVER_SPENDS_UNBOUND_NETWORK").toBe(metadata); + expect(db.query("SELECT * FROM reference_acquisitions WHERE root_id = ?").get(id), "REFERENCE_ACQUISITION_SURVIVES_RESTART").toEqual(original); + expect(db.query("SELECT root_id FROM reference_sources").get()).toEqual({ root_id: id }); + } finally { await restarted.close(); db.close(); } + } finally { await f.close(); } +}); + +for (const changed of ["uuid", "generation", "commit", "brain"] as const) + test(`restart refuses a retained managed root with a contradictory ${changed}`, async () => { + const f = await fixture(); + try { + const lease = await f.request(), id = lease.rootId; lease.release(); + await f.sources.close(); + const record = f.pool.records.get(id)!; + if (changed === "uuid") record.root = { ...record.root!, uuid: "another-root" }; + if (changed === "generation") record.root = { ...record.root!, otransid: "2" }; + if (changed === "commit") f.db.query("UPDATE reference_sources SET commit_id = ?").run("c".repeat(40)); + if (changed === "brain") f.db.query("UPDATE reference_acquisitions SET brain = 'troy-brain'").run(); + const restarted = f.restart(f.db); + try { + await restarted.recover(); + expect(f.db.query("SELECT * FROM reference_sources").all(), "REFERENCE_RESTART_REFUSES_CONTRADICTORY_ROOT").toEqual([]); + expect(record.state).toBe("reclaimed"); + } finally { await restarted.close(); } + } finally { await f.close(); } + }); + +test("two concurrent public requesters cannot join the first turn's in-flight acquisition", async () => { + const f = await fixture(); + let entered!: () => void, release!: () => void; + const reached = new Promise(resolve => { entered = resolve; }), held = new Promise(resolve => { release = resolve; }); + const fetch = f.transport.fetch; let calls = 0; + f.transport.fetch = async input => { if (++calls === 1) { entered(); await held; } return fetch(input); }; + const first = f.request(); + try { + await reached; + const second = await f.request(f.other.id, "telemachus-turn", f.secondEgress); + try { + expect(f.secondEgress.usedBytes(), "REFERENCE_CONCURRENT_REQUEST_PAYS_OWN_BUDGET").toBeGreaterThan(0); + expect(calls, "REFERENCE_CONCURRENT_REQUEST_NEVER_JOINS_FOREIGN_TURN").toBe(2); + } finally { second.release(); } + release(); (await first).release(); + } finally { release(); await first.then(lease => lease.release(), () => {}); await f.close(); } +}); + +test("authority lost after native publication removes the name and acquisition rather than returning bytes", async () => { + const f = await fixture(), publish = f.pool.poolPublish; + let path = ""; + f.pool.poolPublish = async (...args) => { + const result = await publish(...args); path = result.path!; f.state.current = false; return result; + }; + try { + await expect(f.request(), "REFERENCE_POST_MANAGER_AUTHORITY_FENCE").rejects.toThrow(); + expect(existsSync(path), "REFERENCE_POST_MANAGER_FAILURE_REMOVES_ROOT").toBe(false); + expect(f.db.query("SELECT * FROM reference_acquisitions").all()).toEqual([]); + } finally { await f.close(); } +}); + +test("a changed native root reply cannot be recorded as the root sealed before the publication wait", async () => { + const f = await fixture(), publish = f.pool.poolPublish; + let path = ""; + f.pool.poolPublish = async (...args) => { + const result = await publish(...args); path = result.path!; result.root = { ...result.root!, uuid: "a-different-native-root" }; return result; + }; + try { + await expect(f.request(), "REFERENCE_NATIVE_PUBLICATION_ROOT_MUST_MATCH_SEAL").rejects.toThrow(); + expect(existsSync(path)).toBe(false); + expect(f.db.query("SELECT * FROM reference_acquisitions").all()).toEqual([]); + } finally { await f.close(); } +}); + +test("principal revocation committed with the async publication receipt withdraws the just-published root", async () => { + const f = await fixture({ worker: true }), publish = f.pool.poolPublish; + let path = ""; + f.pool.poolPublish = async (...args) => { const result = await publish(...args); path = result.path!; return result; }; + f.db.exec(`CREATE TRIGGER odysseus_revoke_at_publication AFTER INSERT ON reference_acquisitions + BEGIN UPDATE principals SET revoked_at = 1 WHERE id = NEW.principal_id; END`); + try { + await expect(f.request(), "REFERENCE_POST_DATABASE_AUTHORITY_FENCE").rejects.toThrow(); + expect(existsSync(path), "REFERENCE_POST_DATABASE_FAILURE_REMOVES_ROOT").toBe(false); + expect(f.db.query("SELECT * FROM reference_acquisitions").all()).toEqual([]); + expect(f.db.query("SELECT * FROM reference_sources WHERE root_id IS NOT NULL").all()).toEqual([]); + } finally { await f.close(); } +}); + +for (const wait of ["coverage", "native-grant"] as const) + test(`managed worktree access fences acquiring-turn loss after its own ${wait} wait`, async () => { + const f = await fixture(); + const context = { turnId: "odysseus-worktree-turn", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, + coverage: async () => { if (wait === "coverage") f.state.current = false; } }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + const access = f.pool.poolAccess; + f.pool.poolAccess = async (...args) => { const result = await access(...args); if (wait === "native-grant") f.state.current = false; return result; }; + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }), + "REFERENCE_WORKTREE_FINAL_TURN_FENCE").rejects.toThrow(); + expect(f.pool.records.get(item.id)!.access, "REFERENCE_WORKTREE_STALE_GRANT_PARKED").toBeNull(); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } + }); diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index b6fe7bc88f..d2aec4e2aa 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -342,6 +342,15 @@ its transport workers against the pool: it fetches and checks out a its view. The container therefore also has `SETUID`, `SETGID` and `SETFCAP` and unconfined system paths, like the native host proof, so the transport workers can map their user namespace and mount their own `/proc`. + +The managed GitHub case (#3613) uses real TLS and Git through the bounded host +wire, actual production maintenance workers and native sealed publication. +Only fixed DNS/TCP and a fixture CA replace the remote service; the disposable +network-none container's system CA bundle is restored in cleanup. It verifies +commit/tree and actual native root/generation mapping, a credential-free +offline worker read, the kernel's `EROFS` refusal, turn byte charges and grant +revocation after native sealing. It enables no repository read-trust exemption +and does not claim both-backend equivalence for the managed path. A managed-worktree case ([#2430](https://github.com/schlessera/brain-kit/issues/2430)) edits a writable snapshot of sealed source, diffs two of its read-only checkpoints and grants it to a running non-root bubblewrap worker through an diff --git a/scripts/native-proof/managed-reference-source.ts b/scripts/native-proof/managed-reference-source.ts new file mode 100644 index 0000000000..86cbf37714 --- /dev/null +++ b/scripts/native-proof/managed-reference-source.ts @@ -0,0 +1,122 @@ +/** Actual managed Git/TLS acquisition, maintenance workers and native Btrfs publication. No read-trust exemption. */ +import { expect } from "bun:test"; +import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { connect } from "node:net"; +import { join } from "node:path"; +import type { createNativeBrainManagerClient } from "../../packages/ui-sdk/src/server/native-brain-manager-client.js"; +import { startEgressProxy } from "../../packages/ui-sdk/src/server/egress-proxy.js"; +import { runMaintenanceWorker } from "../../packages/ui-sdk/src/server/maintenance-worker.js"; +import { createUiDb } from "../../packages/ui-server/src/db/client.js"; +import { createPrincipal } from "../../packages/ui-server/src/db/principals.js"; +import { createReferenceGrant, revokeReferenceGrant } from "../../packages/ui-server/src/db/reference-grants.js"; +import { createReferenceSources } from "../../packages/ui-server/src/brain/reference-source.js"; +import { createReferenceTransport } from "../../packages/ui-server/src/brain/reference-transport.js"; +import { createGitHubReferenceAccess } from "../../packages/ui-server/src/brain/github-reference-access.js"; +import { fixtureTls } from "../../packages/ui-server/tests/fixtures/fixture-tls.js"; + +export async function proveManagedReferenceSource(client: ReturnType, brain: string, + note: (kind: string, facts: Record) => void): Promise { + const root = "/native-runtime/managed-source", repository = "https://github.com/odysseus/ithaca", servedBrain = "ithaca-managed-proof"; + mkdirSync(root, { recursive: true }); + const work = join(root, "work"), bare = join(root, "ithaca.git"); mkdirSync(work); + const gitEnv = { PATH: "/usr/bin:/bin", HOME: "/nonexistent", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" }; + const git = (...args: string[]) => { + const result = Bun.spawnSync(["/usr/bin/git", ...args], { env: gitEnv, stdout: "pipe", stderr: "pipe" }); + expect(result.exitCode, `MANAGED_NATIVE_FIXTURE_GIT: ${result.stderr}`).toBe(0); return result.stdout.toString().trim(); + }; + git("-C", work, "init", "-q", "-b", "main"); + writeFileSync(join(work, "README.md"), "Odysseus charts Ithaca on 2026-07-12.\n"); + git("-C", work, "add", "."); + git("-C", work, "-c", "user.name=Odysseus", "-c", "user.email=odysseus@ithaca.example", "commit", "-q", "-m", "Chart Ithaca"); + git("clone", "-q", "--bare", work, bare); + const commit = git("-C", work, "rev-parse", "HEAD"), tree = git("-C", work, "rev-parse", "HEAD^{tree}"); + const tls = fixtureTls(join(root, "tls"), ["github.com", "api.github.com"]); + // Only this disposable network-none proof container's system bundle changes. + // Real maintenance workers use their ordinary mounted system trust store. + const bundle = "/etc/ssl/certs/ca-certificates.crt", originalBundle = readFileSync(bundle); + writeFileSync(bundle, Buffer.concat([originalBundle, Buffer.from("\n"), readFileSync(tls.ca)])); + const token = "odysseus-native-fixture-token", basic = `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`; + let privateSource = false, revokeAtSeal = false; + const requests: { host: string; authorization: string | null }[] = []; + const db = createUiDb(join(root, "ui.db")); + const principal = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + let grantId: string | null = null; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, async fetch(request) { + const url = new URL(request.url), host = request.headers.get("host") ?? "", authorization = request.headers.get("authorization"); + requests.push({ host, authorization }); + if (host === "api.github.com" && url.pathname === "/repos/odysseus/ithaca") { + if (privateSource && authorization !== `Bearer ${token}`) return new Response(null, { status: 404 }); + return Response.json({ id: 101, owner: { id: 201, login: "Odysseus" }, name: "Ithaca", full_name: "Odysseus/Ithaca", + clone_url: `${repository}.git`, url: "https://api.github.com/repos/odysseus/ithaca", private: privateSource }); + } + if (host !== "github.com" || !url.pathname.startsWith("/odysseus/ithaca.git/")) return new Response(null, { status: 404 }); + if (privateSource && authorization !== basic) return new Response(null, { status: 401, headers: { "WWW-Authenticate": 'Basic realm="ithaca"' } }); + const child = Bun.spawn(["/usr/bin/git", "http-backend"], { stdin: new Uint8Array(await request.arrayBuffer()), stdout: "pipe", stderr: "pipe", + env: { ...gitEnv, GIT_PROJECT_ROOT: root, GIT_HTTP_EXPORT_ALL: "1", PATH_INFO: url.pathname.replace(/^\/odysseus/u, ""), + REQUEST_METHOD: request.method, QUERY_STRING: url.search.slice(1), CONTENT_TYPE: request.headers.get("content-type") ?? "", + CONTENT_LENGTH: request.headers.get("content-length") ?? "", HTTP_GIT_PROTOCOL: request.headers.get("git-protocol") ?? "" } }); + const [output, errors, code] = await Promise.all([new Response(child.stdout).arrayBuffer().then(value => Buffer.from(value)), new Response(child.stderr).text(), child.exited]); + expect(code, `MANAGED_NATIVE_HTTP_BACKEND: ${errors}`).toBe(0); + const separator = output.indexOf("\r\n\r\n"); expect(separator).toBeGreaterThan(0); + const headers = new Headers(); let status = 200; + for (const line of output.subarray(0, separator).toString().split("\r\n")) { + const colon = line.indexOf(":"); if (colon < 1) continue; + if (line.slice(0, colon).toLowerCase() === "status") status = Number(line.slice(colon + 1).trim().split(" ")[0]); + else headers.append(line.slice(0, colon), line.slice(colon + 1).trim()); + } + return new Response(output.subarray(separator + 4), { status, headers }); + } }); + const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 8 * 1048576, observe() {} }); + const transport = createReferenceTransport({ brainPath: brain, tempDomain: { statePath: join(root, "ui.db") } }); + const github = createGitHubReferenceAccess({ db, brain: servedBrain, credentials: { GITHUB_TOKEN: token }, transport, + wireTransport: { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], + connect: (() => connect({ host: "127.0.0.1", port: server.port! })) as typeof connect } }); + const created: string[] = []; + const sources = createReferenceSources({ db, brain: servedBrain, credentials: { GITHUB_TOKEN: token }, transport, github, + pool: { ...client, + async poolCreate(...args) { created.push(args[0]); return client.poolCreate(...args); }, + async poolSeal(...args) { + const record = await client.poolSeal(...args); + if (revokeAtSeal) revokeReferenceGrant(db, { brain: servedBrain, principalId: principal.id, id: grantId!, now: Date.now() }); + return record; + } } }); + const request = () => sources.request({ principalId: principal.id, repository, revision: "main", + acquisition: { turnId: "odysseus-native-managed", egress, current: () => true } }); + const releaseOwned = async () => { + await sources.close(); + const cleanup = await Promise.allSettled(created.map(id => client.poolRelease(id))); + const failure = cleanup.find(result => result.status === "rejected"); + if (failure?.status === "rejected") throw failure.reason; + }; + try { + const lease = await request(); + try { + const record = await client.poolSeal(lease.rootId); + expect(record.state, "MANAGED_NATIVE_SOURCE_IS_SEALED").toBe("sealed"); + let refusal = ""; + try { writeFileSync(join(record.path!, "intrusion.md"), "Circe alters the chart.\n"); } catch (error) { refusal = (error as NodeJS.ErrnoException).code ?? "unknown"; } + expect(refusal, "MANAGED_NATIVE_KERNEL_REFUSES_MUTATION").toBe("EROFS"); + const read = await runMaintenanceWorker({ brainPath: brain, credentials: false, env: { PATH: "/usr/bin:/bin" }, tempKind: "git", + tempDomain: { statePath: join(root, "ui.db") }, command: ["/usr/bin/cat", join(record.path!, "README.md")], + transport: { mirror: record.path!, readPaths: [], network: false } }); + expect(read.exitCode, `MANAGED_NATIVE_OFFLINE_WORKER_READ: ${read.stderr}`).toBe(0); + expect(read.stdout).toBe("Odysseus charts Ithaca on 2026-07-12.\n"); + const mapping = db.query("SELECT * FROM reference_acquisitions WHERE root_id = ?").get(lease.rootId); + expect(mapping, "MANAGED_NATIVE_ACQUISITION_BINDS_KERNEL_ROOT").toMatchObject({ commit_id: commit, tree_id: tree, + native_root_id: record.root!.rootId, native_uuid: record.root!.uuid, native_generation: record.root!.otransid }); + expect(requests.every(value => value.authorization === null), "MANAGED_NATIVE_PUBLIC_ANONYMOUS").toBe(true); + expect(egress.usedBytes(), "MANAGED_NATIVE_ACTUAL_TURN_NETWORK_CHARGED").toBeGreaterThan(0); + note("managed-source-native", { commit, tree, root: record.root, mapping, usedBytes: egress.usedBytes(), kernelWriteRefusal: refusal, + actualMaintenanceWorker: true, backendEquivalence: false, readTrustExemption: false }); + } finally { lease.release(); } + privateSource = true; revokeAtSeal = true; + grantId = createReferenceGrant(db, { brain: servedBrain, principalId: principal.id, createdBy: principal.id, repositoryPrefix: repository, + credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com", now: Date.now() }).id; + await expect(request(), "MANAGED_NATIVE_GRANT_REVOKED_AFTER_SEAL").rejects.toMatchObject({ code: "unauthorized" }); + expect(db.query("SELECT * FROM reference_sources WHERE domain != 'public' AND root_id IS NOT NULL").all(), "MANAGED_NATIVE_REVOKED_SOURCE_NOT_PUBLISHED").toEqual([]); + note("managed-source-native-revocation", { refused: true, livePublicMappingUnaffected: db.query("SELECT count(*) AS n FROM reference_acquisitions").get() }); + } finally { + try { await releaseOwned(); } + finally { egress.stop(); server.stop(true); db.close(); writeFileSync(bundle, originalBundle); } + } +} diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index fed136940c..c517b0b09f 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -928,6 +928,17 @@ const shapes = await create("staging", 32 * MIB); rmSync(srv, { recursive: true, force: true }); } +// Managed GitHub production wire -> actual maintenance workers -> native +// sealed publication. Its separate read-trust/backend limits stay explicit. +{ + const { proveManagedReferenceSource } = await import("./managed-reference-source.js"); + await manager.close(); + const served = await serveNativeBrainManager(config); + try { await proveManagedReferenceSource(createNativeBrainManagerClient({ socketPath: config.socketPath, timeoutMs: 20_000 }), "/brain-fixture/brain", note); } + finally { await served.close(); } + manager = await createNativeBrainManager(config); +} + // 14. Restart reconstruction and the deterministic host projection. { const kept = await create("source", 4 * MIB); From 1893359d1c1ff59cc328cdd68dfe39dff7e795e1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 13:25:48 +0000 Subject: [PATCH 02/27] test(ui-server): prepare TLS prerequisites for native source proof --- scripts/native-proof/Dockerfile | 2 +- scripts/native-proof/README.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/native-proof/Dockerfile b/scripts/native-proof/Dockerfile index db72248da0..cd5ff14c75 100644 --- a/scripts/native-proof/Dockerfile +++ b/scripts/native-proof/Dockerfile @@ -8,6 +8,6 @@ RUN timeout --kill-after=10s 600s sh -ec ' \ if [ "$attempt" = 3 ]; then exit 1; fi; \ sleep 5; \ done; \ - DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 bubblewrap libseccomp2 git iproute2; \ + DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=5 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 install -y --no-install-recommends btrfs-progs util-linux python3 bubblewrap libseccomp2 git iproute2 openssl ca-certificates; \ rm -rf /var/lib/apt/lists/*' ENTRYPOINT ["python3"] diff --git a/scripts/native-proof/README.md b/scripts/native-proof/README.md index d2aec4e2aa..4518ac74a8 100644 --- a/scripts/native-proof/README.md +++ b/scripts/native-proof/README.md @@ -345,6 +345,8 @@ workers can map their user namespace and mount their own `/proc`. The managed GitHub case (#3613) uses real TLS and Git through the bounded host wire, actual production maintenance workers and native sealed publication. +The image installs OpenSSL and the system CA bundle during dependency setup, +before offline execution; certificate generation never installs a package. Only fixed DNS/TCP and a fixture CA replace the remote service; the disposable network-none container's system CA bundle is restored in cleanup. It verifies commit/tree and actual native root/generation mapping, a credential-free From 7990834d3a53f7e881eaeb1ffb3e84b686916fba Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 11:41:59 +0000 Subject: [PATCH 03/27] docs: refresh application citations after main reconciliation --- docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/http-api-boundary.md | 8 ++++---- docs/decisions/scheduled-tasks.md | 2 +- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index d9299a6208..672697de7d 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -64,7 +64,7 @@ next to it. of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, `packages/ui-server/src/brain/client.ts:180-248`, called at - `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:504`). + `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:509`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:507-511`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index f9d4d865a2..b8e9ffe4c1 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:1081`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1102`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1330`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1098`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1119`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1358`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1350-1371`). That order establishes access; +`packages/ui-server/src/app.ts:1378-1399`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index 0ac05608dc..2f571ff0ff 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:586-602`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:591-607`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index 34fa02e1b7..ffef2265e6 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1102`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1119`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index f41f6c70be..08625ea53e 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1102`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1119`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 35f3914a92..644b076c16 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1440-1490`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1468-1518`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:319-332`). A caller deadline From fc396e59dc67aac528dac87ce1425d709eac1f4e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 20:42:29 +0000 Subject: [PATCH 04/27] test(ui-server): prove managed source maintenance waits --- docs/decisions/managed-worktrees.md | 35 +++++---- .../decisions/reference-source-acquisition.md | 16 ++-- docs/plans/reviewable-session-safety.md | 10 +-- .../tests/github-reference-git.test.ts | 76 ++++++++++++++++--- 4 files changed, 101 insertions(+), 36 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 9194e65c7b..b012ccaba1 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -97,7 +97,7 @@ unknown; what happens next is in [hygiene and cleanup](#hygiene-and-cleanup). Each governed or strict turn whose journal is recording opens one worker generation, and every worker of that turn binds the generation's root-owned directory whole at `/tmp/brain-worktrees`, inside the turn's own `/tmp` -(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/session-run/admission.ts:191-203`; +(`// Managed worktrees (#2430): a journaled turn's workers bind one empty generation.`, `packages/ui-server/src/ws/session-run/admission.ts:196-208`; `// Managed worktrees (#2430): the whole access generation`, `packages/ui-sdk/src/server/worker-launcher.ts:886-897`). A granted worktree appears there as `/tmp/brain-worktrees//` on the worker's next path lookup; the worker cannot create entries beside it, and a @@ -125,8 +125,8 @@ A managed worktree is not inside the brain, so the brain's checkpoints never cover it. The turn journal observes each covered worktree as its own root, through that worktree's read-only checkpoints and deltas and the same observer and capture as the brain -(`attachWorktree(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:596-608`; -`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:430-444`). +(`attachWorktree(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:626-638`; +`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:449-463`). Coverage starts with a baseline checkpoint and inventory before the grant, and every journal observation, periodic, at a scope cap or at the turn's end, then observes the worktree too. @@ -154,7 +154,7 @@ Ordinary brain and workspace journaling is unchanged. ## Guidance Workers with a bound generation receive fixed guidance in the existing sandbox -note (`const WORKTREE_GUIDANCE`, `packages/ui-sdk/src/server/worker-sandbox.ts:554-560`): +note (`const WORKTREE_GUIDANCE`, `packages/ui-sdk/src/server/worker-sandbox.ts:583-589`): shared source is read-only and moves, a worktree starts at a reported commit that never moves, where to work, that edits are journaled and scope-counted, that only explicit access or renewal resets the three-day clock, that expiry @@ -193,17 +193,17 @@ source and worktrees to agents through two bridge tools, `reference_source` and once in the SDK and registered identically by both backends ([MCP contract](../integration-contract/mcp.md#reference-source-and-managed-worktree-tools-additive-0440-2432)). The host side is `createReferenceTools` -(`createReferenceTools`, `packages/ui-server/src/brain/reference-tools.ts:61-196`). +(`createReferenceTools`, `packages/ui-server/src/brain/reference-tools.ts:62-197`). **The turn is the authority.** Before a governed or strict turn's workers start, the host records its principal and what those workers bind: the public view, the principal's private view and the turn's worker generation, if one opened -(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/session-run/admission.ts:204-210`). +(`// Reference tools (#2432): the turn's workers bind the principal's source`, `packages/ui-server/src/ws/session-run/admission.ts:209-215`). A call carries only a repository, a revision or a worktree identity. The bridge adds the turn's own principal, and a call for a turn the host did not prepare, or under another principal, refuses -(`async call(turnId: string`, `packages/ui-server/src/brain/reference-tools.ts:149-198`). +(`async call(turnId: string`, `packages/ui-server/src/brain/reference-tools.ts:155-204`). Every operation then runs through the acquisition and worktree services, which check grants, validation and ownership again; a tool never repeats or skips their rules. Once the turn ends, its record is gone and its bridge holds @@ -215,7 +215,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:868-899`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:870-901`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -244,7 +244,7 @@ access and their rosters do not name the tools. fixed roster with fixed descriptions; a turn without a handler refuses at call time. Lifecycle and freshness facts arrive only in the result of the call that produced them, and the sandbox note's reference guidance is fixed text -(`const REFERENCE_GUIDANCE`, `packages/ui-sdk/src/server/worker-sandbox.ts:551-553`), +(`const REFERENCE_GUIDANCE`, `packages/ui-sdk/src/server/worker-sandbox.ts:580-582`), so no earlier system prompt, tool or message changes ([provider history](provider-history.md)). @@ -252,10 +252,13 @@ so no earlier system prompt, tool or message changes published there, not only those this turn asks for, so the Q4 rule (a fresh check before a new mount) applies to the bind itself. The maintainer ruled on 2026-10-24 how ([option 1](https://github.com/schlessera/brain-kit/issues/2432)): -before a turn's workers bind a view, every source in it whose validation lapsed -is validated again, including sources a running turn reads; one that fails is -withheld from the new bind, and a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:677-715`): +before a turn's workers bind a view, a lapsed legacy source is validated +again without waiting for maintenance admission. A busy check withholds the +source. Managed GitHub sources are withheld without network access: their +validation needs an explicit request on the new turn's proxy and budget. +These rules cover sources a running turn reads; a running reader keeps its +existing mount +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:679-717`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -269,7 +272,7 @@ withheld from the new bind, and a running reader keeps its existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:610-621`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:611-622`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -288,7 +291,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:721-730`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:723-732`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a @@ -400,7 +403,7 @@ selects undone copy. Markdown findings and the host's by core's ordinal rules (severity, known urgency, age, identity), and every operation that names a host finding goes to the host, never to the CLI -(`async function cli(args`, `packages/ui-server/src/inbox/hygiene-review.ts:56-68`). +(`async function cli(args`, `packages/ui-server/src/inbox/hygiene-review.ts:57-69`). A retained or failed worktree offers one repair, `delete-worktree`; an unknown one offers none and stays kept and charged, and "check again" assesses it afresh, after a failed removal too. Selection assesses its winner again before diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 38365bd77b..6f808aa212 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -84,18 +84,18 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:415-468`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:416-469`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. 2. The **network transport** fetches one ref into it. It is the only worker that may hold a credential: the granted host variable, delivered through a fixed credential helper, with one allowed protocol and no redirects - (`async fetch({ repository, ref, token, root, signal, wire })`, `packages/ui-server/src/brain/reference-transport.ts:182-203`). + (`async fetch({ repository, ref, token, root, signal, wire })`, `packages/ui-server/src/brain/reference-transport.ts:211-232`). 3. A separate **checkout worker** has no credential and no network. It checks out the commit and evaluates the repository's attributes. No filter or hook is configured, so none runs - (`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:204-213`). + (`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:233-242`). 4. The live grant is read again, the root is sealed, the grant is read again, and only then is the root published. @@ -156,6 +156,10 @@ access, owns its own authority check and budget; it never joins a foreign turn. The operation limit is 64 MiB or the remaining turn allowance, whichever is smaller. Lapsed GitHub source found during pre-proxy bind preparation is withheld without network, then restored only by an explicit admitted request. +Maintenance admission may wait up to 30 seconds for each Git command, then +returns `busy`. Cancellation stops that wait; the wire still checks the live +turn and selected grant before dispatch, and the source service checks them +again before publication. Waiting grants no new authority. Private GitHub acquisition requires the separately approved API credential recipient even if an older Git-only grant exists; host credential availability does not silently widen that grant. Other legacy transports retain their @@ -203,7 +207,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:374-390`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:375-391`). There is no idle expiry. ## Revocation and recovery @@ -216,14 +220,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:775-795`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:777-797`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:798-842`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:800-844`). ## Evidence diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 4b6e61e2aa..d6109f0a4f 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -25,7 +25,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. - Taint recording retains every independently observed signal and reads a durable revisioned aggregate, including pending/failure and explicit unknown coverage (`safetyProjection`, - `packages/ui-server/src/governance/safety-store.ts:415-420`). Legacy rows prove + `packages/ui-server/src/governance/safety-store.ts:418-423`). Legacy rows prove their own event, never a complete history. Owner review transport and its mutation capability remain disabled by this foundation. - Tool ingestion collects input and output signals independently (`inputTaintSignals`, @@ -42,12 +42,12 @@ public design or its fixtures. Fictional examples use the Odysseus world. `packages/ui-server/src/ws/bridge-session-binding.ts:14-28`), without excluding independent pending input. A raw CONNECT reveals only an authority and opaque bytes, not a repository path or inner protocol - (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:124-359`). + (`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:200-435`). - Outward decisions read session taint at admission (`prepareOutwardPlan`, `packages/ui-sdk/src/server/outward-policy.ts:47-94`). Existing historical steering attribution must remain attribution at the time of a write. - Governance policy is protected Markdown, validated by a strict schema - (`GovernancePolicySchema`, `packages/common/src/governance-policy.ts:101-130`). + (`GovernancePolicySchema`, `packages/common/src/governance-policy.ts:132-161`). The privileged proposal writer already provides exact-base review, descriptor-bound publication, authority rechecks and crash receipts (`createPolicyProposals`, `packages/ui-server/src/brain/policy-proposal.ts:100-275`). @@ -56,7 +56,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. ([reference-source grants](../decisions/reference-source-grants.md)). Its fixed Git transport separates network acquisition from credential-free, network-free checkout (`createReferenceTransport`, - `packages/ui-server/src/brain/reference-transport.ts:108-205`). + `packages/ui-server/src/brain/reference-transport.ts:118-215`). - The Security and Devices & agents surfaces already exist; policy facts are currently read-only (`AgentPolicyGroup`, `packages/ui-react/src/components/settings/agent-policy-group.tsx:8-51`). @@ -323,7 +323,7 @@ Attach to the exact tool/message entry only with authoritative correlation; otherwise use a separate turn-scoped network event, without blaming the nearest message. Examples of accessible names are **Safety restrictions: 2 unresolved triggers** and **Marked safe by you: show details**. Reuse the kit's icon map -(`ICONS`, `packages/ui-kit/src/primitives/Icon.tsx:131-193`). +(`ICONS`, `packages/ui-kit/src/primitives/Icon.tsx:145-207`). The transcript uses a compact safety notice, not an assistant-generated message or modal interruption. It records every new trigger even when another trigger diff --git a/packages/ui-server/tests/github-reference-git.test.ts b/packages/ui-server/tests/github-reference-git.test.ts index f5fbba5a83..7a066c0d5f 100644 --- a/packages/ui-server/tests/github-reference-git.test.ts +++ b/packages/ui-server/tests/github-reference-git.test.ts @@ -7,13 +7,14 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { invocationChild } from "../../../scripts/test-invocation-child"; import { startEgressProxy } from "../../ui-sdk/src/server/egress-proxy"; +import { reserveMaintenanceTemp } from "@schlessera/brain-ui-sdk/internal"; import { createGitHubReferenceAccess } from "../src/brain/github-reference-access"; import { createReferenceSources } from "../src/brain/reference-source"; import { referencePoolDouble } from "./helpers/reference-pool-double"; import { createReferenceTransport } from "../src/brain/reference-transport"; import { createUiDb } from "../src/db/client"; import { createPrincipal } from "../src/db/principals"; -import { createReferenceGrant } from "../src/db/reference-grants"; +import { createReferenceGrant, revokeReferenceGrant } from "../src/db/reference-grants"; import { fixtureTls } from "./fixtures/fixture-tls"; const ROOT = resolve(import.meta.dir, "../../.."), OFFLINE = "BRAIN_TEST_REFERENCE_GIT_PARENT_NET"; @@ -115,18 +116,28 @@ test(NAME, async () => { const launched: { network: boolean; proxy: boolean; credential: boolean }[] = []; // Execute exactly the transport's fixed argv/environment. This proves real // Git and TLS composition, separately from production maintenance/native isolation. - const transport = createReferenceTransport({ brainPath: root, run: async input => { - launched.push({ network: input.transport?.network !== false, proxy: !!input.env.HTTPS_PROXY, credential: !!input.env.BRAIN_REFERENCE_TOKEN }); - const child = Bun.spawn([...input.command], { cwd: root, env: { ...input.env, GIT_SSL_CAINFO: tls.ca }, - stdout: "pipe", stderr: "pipe", signal: input.signal }); - const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); - return { stdout, stderr, exitCode, killed: child.signalCode !== null }; + const tempLimits = { allowanceBytes: 268435456, budgetBytes: 268435456 }; + mkdirSync(join(root, "maintenance")); + const tempDomain = { statePath: join(root, "maintenance", "ui.db") }; + let onAdmissionRefused: (() => void) | undefined; + const transport = createReferenceTransport({ brainPath: root, tempLimits, tempDomain, admissionWaitMs: 300, run: async input => { + let reservation: ReturnType; + try { reservation = reserveMaintenanceTemp(input.tempLimits!, input.tempDomain, input.tempKind); } + catch (error) { onAdmissionRefused?.(); throw error; } + try { + launched.push({ network: input.transport?.network !== false, proxy: !!input.env.HTTPS_PROXY, credential: !!input.env.BRAIN_REFERENCE_TOKEN }); + const child = Bun.spawn([...input.command], { cwd: root, env: { ...input.env, GIT_SSL_CAINFO: tls.ca }, + stdout: "pipe", stderr: "pipe", signal: input.signal }); + const [stdout, stderr, exitCode] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited]); + return { stdout, stderr, exitCode, killed: child.signalCode !== null }; + } finally { reservation.release(); } } }); const principal = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); - const access = createGitHubReferenceAccess({ db, brain: "ithaca", credentials: { GITHUB_TOKEN: token }, transport, wireTransport: { + const wireTransport = { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], connect: (() => connect({ host: "127.0.0.1", port: server!.port! })) as typeof connect, - } }); + }; + const access = createGitHubReferenceAccess({ db, brain: "ithaca", credentials: { GITHUB_TOKEN: token }, transport, wireTransport }); for (const mode of ["public", "private", "capacity", "movement"] as const) { privateSource = mode === "private"; requests.length = 0; launched.length = 0; if (privateSource) createReferenceGrant(db, { brain: "ithaca", principalId: principal.id, createdBy: principal.id, @@ -186,5 +197,52 @@ test(NAME, async () => { expect(requests.every(value => value.authorization === null)).toBe(true); } finally { lease.release(); } } finally { await sources.close(); } + // Compose the real private Git/TLS path with an actual shared maintenance + // ledger. Metadata may precede admission; no Git request or publication may + // cross a lost turn, cancelled request or revoked grant during the wait. + for (const mode of ["release", "busy", "cancel", "turn-ended", "grant-revoked"] as const) { + privateSource = true; requests.length = 0; launched.length = 0; + const waitingDb = createUiDb(":memory:"); + const reader = createPrincipal(waitingDb, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const grant = createReferenceGrant(waitingDb, { brain: "ithaca", principalId: reader.id, createdBy: reader.id, + repositoryPrefix: "https://github.com/odysseus/ithaca", credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); + const waitingSources = createReferenceSources({ db: waitingDb, brain: "ithaca", pool: referencePoolDouble(join(root, `waiting-${mode}`)), transport, + credentials: { GITHUB_TOKEN: token }, github: createGitHubReferenceAccess({ db: waitingDb, brain: "ithaca", credentials: { GITHUB_TOKEN: token }, transport, wireTransport }) }); + const controller = new AbortController(); let current = true; + const held = reserveMaintenanceTemp(tempLimits, tempDomain, "scratch_query"); + const refused = Promise.withResolvers(); onAdmissionRefused = refused.resolve; + const pending = waitingSources.request({ principalId: reader.id, repository: "https://github.com/odysseus/ithaca", revision: "main", signal: controller.signal, + acquisition: { turnId: `odysseus-wait-${mode}`, egress, current: () => current } }) + .then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await Promise.race([refused.promise, pending.then(() => { throw new Error("REFERENCE_MANAGED_REQUEST_MUST_REACH_MAINTENANCE_WAIT"); })]); + expect(launched, "REFERENCE_MANAGED_WAIT_HAS_NOT_LAUNCHED_GIT").toEqual([]); + expect(requests.some(request => request.host === "api.github.com" && request.authorization === `Bearer ${token}`), + "REFERENCE_MANAGED_WAIT_HAS_VALIDATED_PRIVATE_METADATA").toBe(true); + if (mode === "cancel") controller.abort(); + if (mode === "turn-ended") current = false; + if (mode === "grant-revoked") expect(revokeReferenceGrant(waitingDb, { brain: "ithaca", principalId: reader.id, id: grant.id, now: Date.now() })).not.toBeNull(); + if (mode !== "busy" && mode !== "cancel") held.release(); + const result = await pending; + if (mode === "release") { + expect(result.error, "REFERENCE_MANAGED_WAIT_RELEASE_SUCCEEDS").toBeUndefined(); + expect(result.lease, "REFERENCE_MANAGED_WAIT_RELEASE_PUBLISHES").toBeDefined(); + try { + expect(readFileSync(join(result.lease!.viewPath, result.lease!.name, "README.md"), "utf8")) + .toBe("Odysseus revises the Ithaca chart on 2026-07-12.\n"); + } finally { result.lease?.release(); } + } else { + expect(result.lease, "REFERENCE_MANAGED_WAIT_REFUSAL_RETURNS_NO_SOURCE").toBeUndefined(); + expect(result.error, "REFERENCE_MANAGED_WAIT_REFUSAL_IS_EXPLICIT").toBeDefined(); + if (mode === "busy") expect(result.error, "REFERENCE_MANAGED_WAIT_PRESERVES_BUSY").toMatchObject({ code: "busy" }); + expect(requests.filter(request => request.host === "github.com"), "REFERENCE_MANAGED_WAIT_LOST_AUTHORITY_SENDS_NO_GIT").toEqual([]); + expect(waitingDb.query("SELECT COUNT(*) AS count FROM reference_acquisitions").get(), "REFERENCE_MANAGED_WAIT_REFUSAL_NEVER_PUBLISHES").toEqual({ count: 0 }); + if (mode === "cancel") expect(launched, "REFERENCE_MANAGED_CANCELLED_WAIT_NEVER_LAUNCHES").toEqual([]); + } + } finally { + onAdmissionRefused = undefined; held.release(); controller.abort(); + const result = await pending; result.lease?.release(); await waitingSources.close(); waitingDb.close(); + } + } } finally { egress.stop(); server?.stop(true); db.close(); rmSync(root, { recursive: true, force: true }); } }, 90000); From a8512c2cdf1800d1d41a1e447f8b4f7a3755f15c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 23:57:17 +0000 Subject: [PATCH 05/27] docs: align citations after extraction judge integration --- docs/decisions/governed-writable-workers.md | 2 +- docs/decisions/http-api-boundary.md | 8 ++++---- docs/decisions/session-principals.md | 6 +++--- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- 6 files changed, 11 insertions(+), 11 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index cffabc3fec..ce5b3dbe14 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1695,7 +1695,7 @@ worker does: - **Only interactive turns are journaled, and they load project configuration.** Evidence is wired only into the session-run turn request for a governed turn with a journal (`export function turnRequest`, - `packages/ui-server/src/ws/session-run/backend-entry.ts:203-218`). That turn + `packages/ui-server/src/ws/session-run/backend-entry.ts:217-232`). That turn is never a restricted autonomous one. It runs with `settingSources: ["project"]` and without `strictMcpConfig` (`const sdkOptions: Options`, `packages/ui-backend-claude/src/sdk-options.ts:406-422`). diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index b8e9ffe4c1..41f5d48bec 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:1098`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1119`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1358`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1101`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1122`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1361`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1378-1399`). That order establishes access; +`packages/ui-server/src/app.ts:1381-1402`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 7f88e83423..2fb75eed1c 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:1087` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1102`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:1111` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1330-1347` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:1107` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1122`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:1131` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1361-1378` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index ffef2265e6..c14d55ca94 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1119`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1122`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 08625ea53e..d5ce2980aa 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1119`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1122`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 644b076c16..168ece29ff 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1468-1518`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1471-1521`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:319-332`). A caller deadline From 1a67b35c5bbd3b3ed9e0fcd4b8b3a9d137e172c8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 01:13:28 +0000 Subject: [PATCH 06/27] docs: align app citations after markup route integration --- docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/http-api-boundary.md | 8 ++++---- docs/decisions/scheduled-tasks.md | 2 +- docs/decisions/session-principals.md | 6 +++--- docs/plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- 7 files changed, 12 insertions(+), 12 deletions(-) diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 672697de7d..354755afd8 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -64,7 +64,7 @@ next to it. of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, `packages/ui-server/src/brain/client.ts:180-248`, called at - `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:509`). + `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:510`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:507-511`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 41f5d48bec..86362d84c0 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:1101`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1122`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1361`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1102`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1123`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1364`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1381-1402`). That order establishes access; +`packages/ui-server/src/app.ts:1384-1405`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index 2f571ff0ff..0de2fee2e7 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:591-607`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:592-608`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 2fb75eed1c..7b3f5c33df 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:1107` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1122`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:1131` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1361-1378` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:1108` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1123`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:1132` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1364-1381` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index c14d55ca94..b7f8d338d2 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1122`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1123`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index d5ce2980aa..8b9012eb2a 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1122`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1123`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 168ece29ff..0b4d12c462 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -334,7 +334,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1471-1521`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1474-1524`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:319-332`). A caller deadline From 3b7ac5d102e07ad6f8822c564e0bf3db83be16ca Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 02:38:44 +0000 Subject: [PATCH 07/27] fix(ui-server): fence managed reference authority after waits --- docs/decisions/managed-worktrees.md | 28 ++-- .../decisions/reference-source-acquisition.md | 13 +- .../src/brain/github-reference-access.ts | 2 +- .../ui-server/src/brain/reference-source.ts | 30 +++- .../src/brain/reference-worktree-writes.ts | 4 +- .../src/brain/reference-worktrees.ts | 38 +++-- .../tests/reference-source-managed.test.ts | 132 +++++++++++++++++- 7 files changed, 209 insertions(+), 38 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index b012ccaba1..2ec50545c3 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -7,7 +7,7 @@ commit. It builds on the [acquisition service](reference-source-acquisition.md) and the pool's [checkpoints and access generations](reference-pool-accounting.md#worktree-checkpoints-and-access-generations-2430). This record names the concrete choices the rulings left to implementation. The service is `createReferenceWorktrees` -(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:151-695`), +(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:151-703`), created with the acquisition service. The agent tools that call it arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) ([agent tools](#agent-tools)). Hygiene findings, review and cleanup arrived with [#2431](https://github.com/schlessera/brain-kit/issues/2431) @@ -19,7 +19,7 @@ A request names the principal, a repository and a branch or tag, like a source request. The service asks the acquisition service for that source, so its authority, freshness and private boundary all apply, and then snapshots the sealed source root it was given -(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:433-461`). +(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:437-469`). The worktree's starting commit is the commit that source reported, and it never moves with the source. A read-only baseline checkpoint is taken at once. Each worktree gets the pool's per-operation allowance. A worktree belongs to one @@ -31,6 +31,10 @@ record. While any worktree record names a source root, capacity eviction and startup recovery keep that root: a snapshot keeps its source's extents and owner charge, so releasing the source would free nothing. +The acquiring turn and live private grant are checked after pool and database +waits. Authority lost during allocation discards its roots and record, including +when the activation write completed before the final authority check. + ## Worker generations and access A worker generation is one access generation in the pool, opened for one @@ -39,7 +43,7 @@ restricted (autonomous) turn holds no worktree. The generation records the owning process (PID, start time, boot and PID namespace). Access makes a worktree available to one open generation -(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:525-535`): +(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:534-544`): 1. The generation must be open in this process for a running turn, and belong to the requesting principal. @@ -50,9 +54,11 @@ Access makes a worktree available to one open generation worktree of private source needs a live grant covering its repository at every access, even if its branch has since become public. The repository's revision is then validated through the acquisition service under its own - clocks, and the grant is read again after that and after coverage, just - before the move. A revoked grant, or an expired validation that cannot be - renewed, refuses. + clocks, and the grant is read again after revalidation, coverage, the native + move and the database grant write. A revoked grant, or an expired validation + that cannot be renewed, refuses. Failed access parks a newly dispatched + mount or one already held by this generation and clears its database holder; + another live generation's mount remains busy. 5. Journal coverage is established for the turn before the pool moves the worktree into the generation. Without coverage the service refuses access, so no worker reaches a worktree that is not journaled. @@ -80,7 +86,7 @@ such as an owner in another PID namespace, is **unknown** (`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:206-212`). Reconciliation runs at startup and when a generation closes, never on a timer -(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:613-640`). +(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:621-648`). After three days without explicit activity, a worktree expires: - with a live holder it stays `active` and held, however long the turn runs; @@ -215,7 +221,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:870-901`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:896-927`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -258,7 +264,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:679-717`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:705-743`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -272,7 +278,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:611-622`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:637-648`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -291,7 +297,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:723-732`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:749-758`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 6f808aa212..b81f108efb 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:95-790`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:95-816`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -76,6 +76,13 @@ default to five minutes and are configured separately outage, so no stale copy survives it. A public-to-private transition therefore never leaves the old copy under public authority; the principal needs a grant and gets a private copy. +- Managed metadata or Git authority refusal withdraws known public and + requesting-principal private copies, including while a reader holds a lease. + A successful private metadata check also withdraws the prior public copy. + An incomplete metadata check withholds cached roots until acquisition can + establish authority again. Private metadata responses of 401, 403 or 404 + are authority refusals; the selected private grant is checked once more + after the acquisition wire finishes shutting down. - A public check that gets no answer proves nothing. Only a principal with a covering grant goes on to the private path; anyone else is refused as `unavailable`. @@ -220,14 +227,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:777-797`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:803-823`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:800-844`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:826-870`). ## Evidence diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 78293f4ca5..cb71ab8659 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -75,7 +75,7 @@ export function createGitHubReferenceAccess(options: { result = await wire.metadata(credential); } authorize("metadata", credential !== null); - if (result.status !== 200) throw new ReferenceTransportError("unavailable", "GitHub repository identity is unavailable"); + if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable"); const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.canonical, result.value); if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); const assertCurrent = () => { diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 3124f2304d..551a901a51 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -520,6 +520,8 @@ export function createReferenceSources(options: { assertCurrent(); const domain = access.domain === "public" ? PUBLIC : privateDomain(input.principalId); Object.assign(operation, { domain, grantId: access.grantId, key: sourceKey(domain, repository.canonical, revision) }); + // Private metadata cannot renew a previously shared public copy. + if (domain !== PUBLIC) await withdraw(PUBLIC, repository.canonical, revision); await withdrawals.get(operation.key); assertCurrent(); const check = await access.resolve(); @@ -554,13 +556,37 @@ export function createReferenceSources(options: { return { kind: "source", row: current, stale: false, error: null }; } catch (error) { result?.release(); result = undefined; + const refusal = error instanceof ReferenceTransportError ? error.reason : error instanceof ReferenceSourceError ? error.code : null; + if (refusal === "denied" || refusal === "unauthorized" || refusal === "missing") { + // Opening metadata may fail before it selects a domain. Fence both + // known copies; neither the public cache nor this principal's cache + // may outlive an explicit authority refusal. + await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => withdraw(domain, repository.canonical, revision))); + } else if (!access) { + // An incomplete metadata check may already have refused anonymous + // access. Preserve the cached roots, but withhold them until a live + // acquisition establishes authority again. + await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => suspendSource(domain, repository.canonical, revision))); + } if (error instanceof ReferenceTransportError) throw new ReferenceSourceError(error.reason === "denied" ? "unauthorized" : error.reason, error.message); throw error; } finally { try { await access?.close(); } finally { done(); } } })(); operations.set(id, operation); - try { await operation.promise; assertTurn(); return result!; } - catch (error) { result?.release(); throw error; } + try { + await operation.promise; + assertTurn(); + // Closing the wire also awaits: its original private grant must still + // authorize the lease after shutdown, without inheriting a new grant. + if (operation.domain !== PUBLIC && authorize(operation.domain, input.principalId, repository)?.id !== operation.grantId) + throw new ReferenceSourceError("unauthorized", "The selected reference grant changed before acquisition completed."); + return result!; + } catch (error) { + const held = result; + held?.release(); + if (held && error instanceof ReferenceSourceError && error.code === "unauthorized") await withdraw(operation.domain, repository.canonical, revision); + throw error; + } finally { operations.delete(id); void settle(...splitKey(operation.key)).catch(error => warn("managed source settle failed", error)); } } diff --git a/packages/ui-server/src/brain/reference-worktree-writes.ts b/packages/ui-server/src/brain/reference-worktree-writes.ts index 6436a013b5..4ce173fc78 100644 --- a/packages/ui-server/src/brain/reference-worktree-writes.ts +++ b/packages/ui-server/src/brain/reference-worktree-writes.ts @@ -52,8 +52,8 @@ export function worktreeWrites(db: Database) { activate(at: number, id: string) { db.query("UPDATE reference_worktrees SET state = 'active', accessed_at = ? WHERE id = ?").run(at, id); }, - discard(id: string) { - db.query("DELETE FROM reference_worktrees WHERE id = ? AND state = 'creating'").run(id); + discard(id: string, activating = false) { + db.query("DELETE FROM reference_worktrees WHERE id = ? AND (state = 'creating' OR (? AND state = 'active' AND holder IS NULL))").run(id, activating); }, openGeneration(id: string, principalId: string, turnId: string, profile: string, path: string, pid: number, start: string, boot: string, pidNamespace: string, at: number) { db.query(`INSERT INTO reference_worktree_generations (id, principal_id, turn_id, profile, path, owner_pid, owner_start, owner_boot, owner_pid_namespace, opened_at) diff --git a/packages/ui-server/src/brain/reference-worktrees.ts b/packages/ui-server/src/brain/reference-worktrees.ts index 98dad65bd9..8bc623cd9a 100644 --- a/packages/ui-server/src/brain/reference-worktrees.ts +++ b/packages/ui-server/src/brain/reference-worktrees.ts @@ -429,6 +429,10 @@ export function createReferenceWorktrees(options: { input.signal?.throwIfAborted(); if (input.acquisition && !input.acquisition.current()) throw new ReferenceWorktreeError("unavailable", "The acquiring turn is no longer available."); } + function acquiringAuthority(input: { signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }, row: Pick): void { + acquiringTurn(input); + covered(row); + } async function allocate(input: { principalId: string; repository: unknown; revision: unknown; signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): Promise { if (closed) throw new ReferenceWorktreeError("unavailable", "Managed worktrees are closed."); @@ -439,39 +443,44 @@ export function createReferenceWorktrees(options: { throw error; } const id = randomUUID(), at = now(); + const authority = { principal_id: input.principalId, domain: lease.domain, repository: lease.repository }; try { + acquiringAuthority(input, authority); const allowance = (await pool.poolStatus(input.signal)).limits.operationBytes; - acquiringTurn(input); + acquiringAuthority(input, authority); // Recorded before the pool sees it: recovery and eviction protection both start here. await write("allocate", id, input.principalId, lease.domain === "public" ? "public" : `private:${input.principalId}`, lease.repository, lease.revision, lease.commit, lease.rootId, allowance, at, at); + let activating = false; try { - acquiringTurn(input); + acquiringAuthority(input, authority); const created = await pool.poolCreate(id, "worktree", lease.rootId, allowance, input.signal); await write("recordRoot", created.root?.uuid ?? null, id); - acquiringTurn(input); + acquiringAuthority(input, authority); const baseline = randomUUID(); await write("recordBaseline", baseline, id); - acquiringTurn(input); + acquiringAuthority(input, authority); await pool.poolCheckpoint(baseline, id, input.signal); - acquiringTurn(input); + acquiringAuthority(input, authority); // Allocation is an explicit access: the inactivity clock starts now. + activating = true; await write("activate", now(), id); - acquiringTurn(input); + acquiringAuthority(input, authority); return view(worktree(id)!); } catch (error) { - await discard(id).catch(cleanup => warn("unfinished worktree was not released; startup recovery retries it", cleanup)); + await discard(id, activating).catch(cleanup => warn("unfinished worktree was not released; startup recovery retries it", cleanup)); + if (error instanceof ReferenceWorktreeError) throw error; const code = (error as { code?: string }).code; throw new ReferenceWorktreeError(code === "capacity" ? "capacity" : "unavailable", `The worktree could not be created: ${error instanceof Error ? error.message : String(error)}`); } } finally { lease.release(); } } /** Release an unfinished allocation's roots; its record goes only once the pool confirms. */ - async function discard(id: string) { + async function discard(id: string, activating = false) { const row = worktree(id); if (!row) return; if (row.baseline) await pool.poolRelease(row.baseline); await pool.poolRelease(id); - await write("discard", id); + await write("discard", id, activating); } /** Open one worker generation of a running turn: an empty directory its workers bind whole. */ @@ -553,16 +562,15 @@ export function createReferenceWorktrees(options: { let dispatched = false; try { await authorize(row, input.signal, input.acquisition); - acquiringTurn(input); + acquiringAuthority(input, row); if (row.holder !== target.id) { // Coverage first: no worker reaches a worktree its journal does not observe. await options.coverage({ turnId: target.turn_id, worktreeId: row.id }, input.signal); // Authority may have ended while revalidation or coverage awaited. - covered(row); - acquiringTurn(input); + acquiringAuthority(input, row); dispatched = true; await pool.poolAccess(row.id, target.id, input.signal); - acquiringTurn(input); + acquiringAuthority(input, row); // A removal admitted elsewhere while the grant awaited wins: the grant is withdrawn, never recorded. if (cleanupOf(row.id)) { await pool.poolPark(row.id).catch(error => warn("withdrawn worktree grant was not parked", error)); @@ -571,10 +579,10 @@ export function createReferenceWorktrees(options: { } // Explicit access or resumption: the only events, with renewal, that move the clock. await write("grant", target.id, now(), row.id); - acquiringTurn(input); + acquiringAuthority(input, row); return view(worktree(row.id)!); } catch (error) { - if (input.acquisition && dispatched) await recoverHolder(worktree(row.id) ?? row).catch(cleanup => warn("withdrawn managed worktree grant was not parked", cleanup)); + if (dispatched || row.holder === target.id) await recoverHolder(worktree(row.id) ?? row).catch(cleanup => warn("withdrawn managed worktree grant was not parked", cleanup)); throw error; } }); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 7d9186c343..9e017d00c4 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeAll, expect, test } from "bun:test"; +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { connect } from "node:net"; import { tmpdir } from "node:os"; @@ -29,12 +29,13 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { const writer = options.worker ? openSqliteWriter(db) : undefined; if (writer) registerReferenceWrites(db, writer); const metadata: string[] = [], git: unknown[] = []; - const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0 }; + const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200 }; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { metadata.push(request.headers.get("authorization") ?? "anonymous"); - if (options.private && !request.headers.has("authorization")) return new Response(null, { status: 404 }); + if (state.status !== 200) return new Response(null, { status: state.status }); + if (state.private && !request.headers.has("authorization")) return new Response(null, { status: 404 }); return Response.json({ id: 101, owner: { id: state.ownerId, login: "Odysseus" }, name: "Ithaca", full_name: "Odysseus/Ithaca", - clone_url: `${repository}.git`, url: "https://api.github.com/repos/odysseus/ithaca", private: options.private ?? false }); + clone_url: `${repository}.git`, url: "https://api.github.com/repos/odysseus/ithaca", private: state.private }); } }); const records: unknown[] = []; const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe(value) { records.push(value); } }); @@ -266,3 +267,126 @@ for (const wait of ["coverage", "native-grant"] as const) expect(f.pool.records.get(item.id)!.access, "REFERENCE_WORKTREE_STALE_GRANT_PARKED").toBeNull(); } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } }); +describe("live managed authority", () => { + for (const refusal of ["metadata", "git-denial", "missing-ref"] as const) + test(`a known public source is hidden from another principal after ${refusal} refuses it`, async () => { + const f = await fixture(); + let held: Awaited> | undefined; + try { + held = await f.request(); + const path = join(held.viewPath, held.name, "README.md"); + expect(readFileSync(path, "utf8"), "PUBLIC_SOURCE_WAS_PUBLISHED_BEFORE_REFUSAL").toContain("Odysseus"); + if (refusal === "metadata") f.state.private = true; + else f.transport.resolve = async () => ({ ok: false, reason: refusal === "git-denial" ? "denied" : "missing", detail: "The published source is no longer available anonymously." }); + await expect(f.request(), "MANAGED_PUBLIC_AUTHORITY_REFUSAL_IS_REPORTED").rejects.toMatchObject({ code: refusal === "missing-ref" ? "missing" : "unauthorized" }); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, held.name, "README.md")), "MANAGED_PUBLIC_REFUSAL_FENCES_OTHER_PRINCIPALS").toBe(false); + expect(existsSync(path), "MANAGED_PUBLIC_REFUSAL_WITHDRAWS_NAME_WITH_A_HELD_LEASE").toBe(false); + } finally { held?.release(); await f.close(); } + }); + + for (const status of [401, 403, 404]) + test(`a private cached source is hidden after metadata returns ${status}`, async () => { + const f = await fixture({ private: true }); f.grant(); + let held: Awaited> | undefined; + try { + held = await f.request(); + expect(readFileSync(join(held.viewPath, held.name, "README.md"), "utf8")).toContain("Odysseus"); + f.state.status = status; + await expect(f.request(), "MANAGED_PRIVATE_METADATA_REFUSAL_IS_AUTHORITY_LOSS").rejects.toMatchObject({ code: "unauthorized" }); + const views = await f.sources.bindable(f.owner.id); + expect(existsSync(join(views.private, held.name, "README.md")), "MANAGED_PRIVATE_METADATA_REFUSAL_WITHDRAWS_COPY").toBe(false); + } finally { held?.release(); await f.close(); } + }); + + test("a revoked private grant during wire shutdown refuses and hides the cached source", async () => { + const f = await fixture({ private: true }), issued = f.grant(); + let held: Awaited> | undefined; + try { + held = await f.request(); + const open = f.github.open; + f.github.open = async input => { + const access = await open(input); + return Object.freeze({ ...access, async close() { + await access.close(); + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); + } }); + }; + await expect(f.request(), "MANAGED_PRIVATE_SHUTDOWN_RECHECKS_AUTHORITY").rejects.toMatchObject({ code: "unauthorized" }); + expect(existsSync(join(held.viewPath, held.name, "README.md")), "MANAGED_PRIVATE_SHUTDOWN_WITHDRAWS_COPY").toBe(false); + } finally { held?.release(); await f.close(); } + }); + + test("a newly private acquisition removes the prior public copy before returning private access", async () => { + const f = await fixture(); + let old: Awaited> | undefined, current: Awaited> | undefined; + try { + old = await f.request(); + expect(existsSync(join(old.viewPath, old.name, "README.md"))).toBe(true); + f.state.private = true; f.grant(); + current = await f.request(); + expect(current.domain, "PRIVATE_TRANSITION_USES_ITS_OWN_GRANTED_DOMAIN").toBe("private"); + expect(readFileSync(join(current.viewPath, current.name, "README.md"), "utf8")).toContain("Odysseus"); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, old.name, "README.md")), "MANAGED_PRIVATE_TRANSITION_WITHDRAWS_PUBLIC_COPY").toBe(false); + } finally { current?.release(); old?.release(); await f.close(); } + }); + + for (const wait of ["coverage", "native-grant", "grant-write", "held-refresh", "held-write"] as const) + test(`a private worktree loses mounted access when its grant is revoked during ${wait}`, async () => { + const f = await fixture({ private: true }), issued = f.grant(); + const revoke = () => { expect(revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() })).not.toBeNull(); }; + const context = { turnId: "odysseus-private-worktree", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, + coverage: async () => { if (wait === "coverage") revoke(); } }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + if (wait.startsWith("held-")) { + await worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }); + expect(existsSync(join(generation.path, item.id, "README.md")), "PRIVATE_WORKTREE_WAS_GRANTED_BEFORE_REVOCATION").toBe(true); + } + if (wait.endsWith("write")) f.db.exec(`CREATE TRIGGER odysseus_revoke_during_worktree_grant AFTER UPDATE OF holder ON reference_worktrees + WHEN NEW.holder IS NOT NULL BEGIN UPDATE reference_grants SET revoked_at = 1 WHERE revoked_at IS NULL; END`); + if (wait === "native-grant") { + const access = f.pool.poolAccess; + f.pool.poolAccess = async (...args) => { const result = await access(...args); revoke(); return result; }; + } + if (wait === "held-refresh") { + const request = f.sources.request; + f.sources.request = async input => { const result = await request(input); revoke(); return result; }; + } + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }), + "MANAGED_PRIVATE_WORKTREE_RECHECKS_POST_WAIT_GRANT").rejects.toMatchObject({ code: "unauthorized" }); + expect(f.pool.records.get(item.id)!.access, "MANAGED_PRIVATE_WORKTREE_REVOKED_MOUNT_IS_PARKED").toBeNull(); + expect(existsSync(join(generation.path, item.id, "README.md")), "MANAGED_PRIVATE_WORKTREE_REVOKED_FILES_ARE_HIDDEN").toBe(false); + expect(worktrees.get({ worktreeId: item.id, principalId: f.owner.id }).generation, "MANAGED_PRIVATE_WORKTREE_REVOKED_HOLDER_IS_CLEARED").toBeNull(); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } + }); + + for (const wait of ["native-create", "checkpoint", "activation-write"] as const) + test(`a private allocation is discarded when its grant is revoked during ${wait}`, async () => { + const f = await fixture({ private: true }), issued = f.grant(); + const context = { turnId: "odysseus-private-allocation", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => {} }); + const revoke = () => { expect(revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() })).not.toBeNull(); }; + try { + if (wait === "native-create") { + const create = f.pool.poolCreate; + f.pool.poolCreate = async (...args) => { const result = await create(...args); if (args[1] === "worktree") revoke(); return result; }; + } + if (wait === "checkpoint") { + const checkpoint = f.pool.poolCheckpoint; + f.pool.poolCheckpoint = async (...args) => { const result = await checkpoint(...args); revoke(); return result; }; + } + if (wait === "activation-write") f.db.exec(`CREATE TRIGGER odysseus_revoke_at_worktree_activation AFTER UPDATE OF state ON reference_worktrees + WHEN NEW.state = 'active' BEGIN UPDATE reference_grants SET revoked_at = 1 WHERE revoked_at IS NULL; END`); + await expect(worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }), + "MANAGED_PRIVATE_ALLOCATION_RECHECKS_POST_WAIT_GRANT").rejects.toMatchObject({ code: "unauthorized" }); + expect(worktrees.list(f.owner.id), "MANAGED_PRIVATE_REVOKED_ALLOCATION_IS_DISCARDED").toEqual([]); + expect([...f.pool.records.values()].filter(record => record.purpose === "worktree" && record.state !== "reclaimed"), + "MANAGED_PRIVATE_REVOKED_ALLOCATION_LEAVES_NO_ROOT").toEqual([]); + } finally { await worktrees.close(); await f.close(); } + }); +}); From efa99c1c6d7e648ce5979ad4d3b13616690877a9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 02:56:32 +0000 Subject: [PATCH 08/27] fix(ui-server): retain current private authority for worktree access --- docs/decisions/managed-worktrees.md | 20 ++++++++++-------- .../src/brain/reference-worktrees.ts | 20 ++++++++++++------ .../tests/reference-source-managed.test.ts | 21 +++++++++++++++++-- 3 files changed, 44 insertions(+), 17 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 2ec50545c3..47a626d9a3 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -7,7 +7,7 @@ commit. It builds on the [acquisition service](reference-source-acquisition.md) and the pool's [checkpoints and access generations](reference-pool-accounting.md#worktree-checkpoints-and-access-generations-2430). This record names the concrete choices the rulings left to implementation. The service is `createReferenceWorktrees` -(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:151-703`), +(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:151-711`), created with the acquisition service. The agent tools that call it arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) ([agent tools](#agent-tools)). Hygiene findings, review and cleanup arrived with [#2431](https://github.com/schlessera/brain-kit/issues/2431) @@ -19,7 +19,7 @@ A request names the principal, a repository and a branch or tag, like a source request. The service asks the acquisition service for that source, so its authority, freshness and private boundary all apply, and then snapshots the sealed source root it was given -(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:437-469`). +(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:445-477`). The worktree's starting commit is the commit that source reported, and it never moves with the source. A read-only baseline checkpoint is taken at once. Each worktree gets the pool's per-operation allowance. A worktree belongs to one @@ -43,7 +43,7 @@ restricted (autonomous) turn holds no worktree. The generation records the owning process (PID, start time, boot and PID namespace). Access makes a worktree available to one open generation -(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:534-544`): +(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:542-552`): 1. The generation must be open in this process for a running turn, and belong to the requesting principal. @@ -58,7 +58,9 @@ Access makes a worktree available to one open generation move and the database grant write. A revoked grant, or an expired validation that cannot be renewed, refuses. Failed access parks a newly dispatched mount or one already held by this generation and clears its database holder; - another live generation's mount remains busy. + another live generation's mount remains busy. A public starting snapshot + also needs the live private grant whenever the current source check requires + private access; its original public domain cannot bypass that requirement. 5. Journal coverage is established for the turn before the pool moves the worktree into the generation. Without coverage the service refuses access, so no worker reaches a worktree that is not journaled. @@ -86,7 +88,7 @@ such as an owner in another PID namespace, is **unknown** (`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:206-212`). Reconciliation runs at startup and when a generation closes, never on a timer -(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:621-648`). +(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:629-656`). After three days without explicit activity, a worktree expires: - with a live holder it stays `active` and held, however long the turn runs; @@ -171,7 +173,7 @@ arrive only in the results that grant access. ## Cleanup eligibility facts Release and expiry record durable facts for hygiene review -(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:242-285`): +(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:250-293`): the reason, the holder (`none`, `live` or `unknown`) and whether work remains (`none`, `unpreserved` or `unknown`). Work is read from a fresh read-only checkpoint and a metadata delta against the baseline. Nothing of the worktree @@ -429,7 +431,7 @@ atomically with grants [pool accounting](reference-pool-accounting.md)), so a grant that lands between the last check and the release fails the removal instead of losing the grant. The worktree service is the only executor, through one effect -(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:334-371`). +(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:342-379`). Immediately before it, with no await between the last check and submission of the receipt: 1. the worktree is released or expired, and no removal of it was already @@ -465,13 +467,13 @@ without another release, which would fail or leave a tombstone identity. The lease owner holds a release's lease again when the pool never committed it (the root is still writable or sealed), so a failed removal stays assessable; it never does so over a newer release of the same identity -(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:378-413`). +(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:386-421`). Capacity is credited only when the pool reports the worktree `reclaimed`: until then its source root stays protected from eviction. **Automatic removal.** Release, expiry and the close of a holding generation remove a worktree only when its fresh assessment shows no holder and no work -(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:303-306`). +(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:311-314`). Reconciliation retries a clean worktree whose removal could not run. Nothing is archived or purged speculatively, and a worktree whose work or owner is unknown is never removed automatically. Arbitrary repositories and shared diff --git a/packages/ui-server/src/brain/reference-worktrees.ts b/packages/ui-server/src/brain/reference-worktrees.ts index 8bc623cd9a..470abfdd09 100644 --- a/packages/ui-server/src/brain/reference-worktrees.ts +++ b/packages/ui-server/src/brain/reference-worktrees.ts @@ -225,7 +225,15 @@ export function createReferenceWorktrees(options: { */ async function authorize(row: Pick, signal?: AbortSignal, acquisition?: ReferenceAcquisitionContext) { covered(row); - try { (await options.sources.request({ principalId: row.principal_id, repository: row.repository, revision: row.revision, signal, acquisition })).release(); } + try { + const source = await options.sources.request({ principalId: row.principal_id, repository: row.repository, revision: row.revision, signal, acquisition }); + try { + // A public starting snapshot cannot bypass the private authority the + // current source check required. A private starting snapshot keeps its + // original grant requirement even if the repository is public now. + return { ...row, domain: row.domain !== "public" || source.domain !== "public" ? "private" : "public" }; + } finally { source.release(); } + } catch (error) { if (error instanceof ReferenceSourceError) throw new ReferenceWorktreeError(error.code === "cancelled" || error.code === "busy" ? "unavailable" : error.code === "missing" || error.code === "invalid" ? "unauthorized" : error.code, `Worktree authority could not be confirmed: ${error.message}`); @@ -561,16 +569,16 @@ export function createReferenceWorktrees(options: { } let dispatched = false; try { - await authorize(row, input.signal, input.acquisition); - acquiringAuthority(input, row); + const authority = await authorize(row, input.signal, input.acquisition); + acquiringAuthority(input, authority); if (row.holder !== target.id) { // Coverage first: no worker reaches a worktree its journal does not observe. await options.coverage({ turnId: target.turn_id, worktreeId: row.id }, input.signal); // Authority may have ended while revalidation or coverage awaited. - acquiringAuthority(input, row); + acquiringAuthority(input, authority); dispatched = true; await pool.poolAccess(row.id, target.id, input.signal); - acquiringAuthority(input, row); + acquiringAuthority(input, authority); // A removal admitted elsewhere while the grant awaited wins: the grant is withdrawn, never recorded. if (cleanupOf(row.id)) { await pool.poolPark(row.id).catch(error => warn("withdrawn worktree grant was not parked", error)); @@ -579,7 +587,7 @@ export function createReferenceWorktrees(options: { } // Explicit access or resumption: the only events, with renewal, that move the clock. await write("grant", target.id, now(), row.id); - acquiringAuthority(input, row); + acquiringAuthority(input, authority); return view(worktree(row.id)!); } catch (error) { if (dispatched || row.holder === target.id) await recoverHolder(worktree(row.id) ?? row).catch(cleanup => warn("withdrawn managed worktree grant was not parked", cleanup)); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 9e017d00c4..42fca603fd 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -332,9 +332,10 @@ describe("live managed authority", () => { } finally { current?.release(); old?.release(); await f.close(); } }); + for (const initialPrivate of [true, false]) for (const wait of ["coverage", "native-grant", "grant-write", "held-refresh", "held-write"] as const) - test(`a private worktree loses mounted access when its grant is revoked during ${wait}`, async () => { - const f = await fixture({ private: true }), issued = f.grant(); + test(`a ${initialPrivate ? "private" : "public-to-private"} worktree loses mounted access when its grant is revoked during ${wait}`, async () => { + const f = await fixture({ private: initialPrivate }), issued = f.grant(); const revoke = () => { expect(revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() })).not.toBeNull(); }; const context = { turnId: "odysseus-private-worktree", egress: f.egress, current: () => f.state.current }; const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, @@ -347,6 +348,7 @@ describe("live managed authority", () => { await worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }); expect(existsSync(join(generation.path, item.id, "README.md")), "PRIVATE_WORKTREE_WAS_GRANTED_BEFORE_REVOCATION").toBe(true); } + f.state.private = true; if (wait.endsWith("write")) f.db.exec(`CREATE TRIGGER odysseus_revoke_during_worktree_grant AFTER UPDATE OF holder ON reference_worktrees WHEN NEW.holder IS NOT NULL BEGIN UPDATE reference_grants SET revoked_at = 1 WHERE revoked_at IS NULL; END`); if (wait === "native-grant") { @@ -365,6 +367,21 @@ describe("live managed authority", () => { } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } }); + test("a public-to-private worktree can still be accessed while its private grant remains live", async () => { + const f = await fixture(); f.grant(); + const context = { turnId: "odysseus-transition-worktree", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => {} }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + f.state.private = true; + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + const accessed = await worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }); + expect(accessed.generation).toBe(generation.id); + expect(readFileSync(join(generation.path, item.id, "README.md"), "utf8")).toContain("Odysseus"); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } + }); + for (const wait of ["native-create", "checkpoint", "activation-write"] as const) test(`a private allocation is discarded when its grant is revoked during ${wait}`, async () => { const f = await fixture({ private: true }), issued = f.grant(); From 792094fc4e97e4931896c0c6eed791bc4f5e275d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 03:27:38 +0000 Subject: [PATCH 09/27] fix(ui-server): fence in-flight reference publication on authority loss --- docs/decisions/managed-worktrees.md | 8 +- .../decisions/reference-source-acquisition.md | 24 ++-- .../ui-server/src/brain/reference-source.ts | 102 +++++++++++---- .../tests/reference-source-managed.test.ts | 123 +++++++++++++++++- 4 files changed, 218 insertions(+), 39 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 47a626d9a3..1a4e2ff46b 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -223,7 +223,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:896-927`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:950-981`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -266,7 +266,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:705-743`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:754-792`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -280,7 +280,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:637-648`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:686-697`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -299,7 +299,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:749-758`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:798-807`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index b81f108efb..b19760d1b6 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:95-816`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:95-868`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:301-350`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:307-356`). - Inside both windows a request reuses the published source without any network call. @@ -83,6 +83,14 @@ default to five minutes and are configured separately establish authority again. Private metadata responses of 401, 403 or 404 are authority refusals; the selected private grant is checked once more after the acquisition wire finishes shutting down. + Repository metadata fences every cached and in-flight revision of that + repository. Older requests cannot publish or restore public state after a + newer private or refused observation, even before the first catalog row + exists. Withdrawal waits for dispatched publication, reads its resulting + catalog state and hides any native publication whose catalog receipt is + still pending. Private revocation includes those in-flight identities and + confirms they are hidden before returning; storage reclamation may finish + later. Concurrent valid private requests keep their own authority and budget. - A public check that gets no answer proves nothing. Only a principal with a covering grant goes on to the private path; anyone else is refused as `unavailable`. @@ -91,7 +99,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:416-469`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:452-506`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -190,9 +198,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:241-256`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:247-262`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:259-284`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:265-290`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -214,7 +222,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:375-391`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:381-397`). There is no idle expiry. ## Revocation and recovery @@ -227,14 +235,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:803-823`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:852-877`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:826-870`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:880-924`). ## Evidence diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 551a901a51..0cd43db101 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -115,6 +115,8 @@ export function createReferenceSources(options: { const isManaged = (repository: string) => Boolean(options.github && new URL(repository).hostname.toLowerCase() === "github.com"); const leases = new Map(); const withdrawn = new Set(); + /** A newer authority observation invalidates older managed requests, including before domain selection. */ + const authorityFences = new Map(); /** In-flight withdrawals; an acquisition of the same source waits for its withdrawal to finish. */ const withdrawals = new Map>(); /** @@ -128,6 +130,8 @@ export function createReferenceSources(options: { const suspended = new Set(), unsettled = new Set(); /** Root identities already moved out of their view: superseded, withdrawn or suspended. */ const hiddenRoots = new Set(); + /** Native publication may have taken effect before its catalog receipt exists. */ + const pendingPublications = new Map(); /** Bind-time revalidations in flight, joined by concurrent binds. */ const revalidations = new Map>(); /** Lapsed sources a bind checks at once. */ @@ -168,6 +172,7 @@ export function createReferenceSources(options: { await releaseRoot(id); } hiddenRoots.add(id); + pendingPublications.delete(id); } /** One change at a time to a source's exposure: suspension, restoration, withdrawal and publication. */ const exposing = new Map>(); @@ -236,6 +241,7 @@ export function createReferenceSources(options: { if (options.dependents?.(id)) return; await pool.poolRelease(id); await write("sourceReleaseRoot", id); + pendingPublications.delete(id); } async function admit(signal: AbortSignal): Promise<() => void> { @@ -392,26 +398,56 @@ export function createReferenceSources(options: { /** Remove a source's name now; release its roots once no reader protects them. */ function withdraw(domain: string, repository: string, revision: string): Promise { const key = sourceKey(domain, repository, revision); + fenceSource(key); const running = withdrawals.get(key); if (running) return running; - const source = row(domain, repository, revision); - if (!source) return Promise.resolve(); - // Fence in this turn, before any await: no new reader may lease the source, - // and only the roots it holds now are withdrawn, never a later acquisition's. + // Fence before any await, even when the first publication has no catalog + // row yet. A later acquisition waits for this withdrawal to finish. withdrawn.add(key); suspended.delete(key); unsettled.delete(key); - const recorded = write<{ roots: { id: string }[]; view: { id: string } }>("sourceWithdraw", domain, repository, revision, randomUUID()); - void recorded.catch(() => {}); - // After any publication in progress, so a restoration can never land after it. + // Observe the catalog after every already-dispatched publication settles, + // including one whose native reply or database receipt was still pending. const work = exclusive(key, async () => { - const { roots, view } = await recorded; - await pool.poolUnpublish(view.id, source.name); - // Every root leaves the view at once, so no reader reaches it by identity; storage waits for readers. - for (const root of roots) await hideRoot(root.id); + const source = row(domain, repository, revision); + if (source) { + const { roots, view } = await write<{ roots: { id: string }[]; view: { id: string } }>("sourceWithdraw", domain, repository, revision, randomUUID()); + await pool.poolUnpublish(view.id, source.name); + // Every root leaves the view at once, so no reader reaches it by identity; storage waits for readers. + for (const root of roots) await hideRoot(root.id); + } + // A first publication can have native exposure but still be staging in + // SQLite. Hide it here too, without waiting for storage reclamation. + for (const [id, publication] of pendingPublications) if (publication.key === key) { + await pool.poolUnpublish(publication.view, publication.name); + await hideRoot(id); + } }).finally(() => { withdrawals.delete(key); }); withdrawals.set(key, work); return work.then(() => settle(domain, repository, revision)); } + function fenceSource(key: string): void { + authorityFences.set(key, (authorityFences.get(key) ?? 0) + 1); + } + /** Repository metadata governs every cached or in-flight revision, not only the requested one. */ + function repositoryRevisions(domain: string, repository: string, revision: string): string[] { + const revisions = new Set([revision]); + for (const row of db.query(`SELECT revision FROM reference_sources WHERE domain = ? AND repository = ? + UNION SELECT revision FROM reference_roots WHERE domain = ? AND repository = ?`).all(domain, repository, domain, repository) as { revision: string }[]) + revisions.add(row.revision); + for (const operation of operations.values()) { + const [heldDomain, heldRepository, heldRevision] = splitKey(operation.key); + if (heldRepository === repository && (heldDomain === domain || (operation.principalId !== null && domain === privateDomain(operation.principalId)))) revisions.add(heldRevision); + } + return [...revisions]; + } + function withdrawRepository(domain: string, repository: string, revision: string): Promise { + return Promise.all(repositoryRevisions(domain, repository, revision).map(revision => withdraw(domain, repository, revision))); + } + function suspendRepository(domain: string, repository: string, revision: string): Promise { + const revisions = repositoryRevisions(domain, repository, revision); + for (const revision of revisions) fenceSource(sourceKey(domain, repository, revision)); + return Promise.all(revisions.map(revision => suspendSource(domain, repository, revision))); + } async function acquire(signal: AbortSignal, input: { domain: string; principalId: string | null; repository: ReferenceRepository; revision: string; grant: ReferenceGrant | null; credential: string | null; ref: string; expectedCommit: string; previous: SourceRow | null; @@ -452,6 +488,7 @@ export function createReferenceSources(options: { if (input.managed) await input.managed.access.revalidate(); recheck(); publishing = true; + pendingPublications.set(staging.id, { key, view: view.id, name }); hiddenRoots.delete(staging.id); const published = await pool.poolPublish(staging.id, view.id, name, signal); recheck(); @@ -467,6 +504,7 @@ export function createReferenceSources(options: { const at = now(), grantId = domain === PUBLIC ? null : (input.grant && isLiveReferenceGrant(db, input.grant.id, at) ? input.grant.id : authorize(domain, input.principalId, repository)!.id); await write("sourcePublish", dirname(published.path!), domain, repository.canonical, revision, repository.url, name, staging.id, commit, input.ref, grantId, at, acquisition); recheck(); + pendingPublications.delete(staging.id); withdrawn.delete(key); // A newly validated commit is exposed; the superseded roots leave the view at // once, so a later bind reaches only the commit this request validated. @@ -502,6 +540,12 @@ export function createReferenceSources(options: { if (!context || !context.turnId || !context.current()) throw new ReferenceSourceError("unavailable", "Managed GitHub acquisition needs a live admitted turn and its network budget."); const controller = new AbortController(), signal = input.signal ? AbortSignal.any([input.signal, controller.signal]) : controller.signal; const id = randomUUID(); + const publicFence = authorityFences.get(sourceKey(PUBLIC, repository.canonical, revision)) ?? 0; + const privateFence = authorityFences.get(sourceKey(privateDomain(input.principalId), repository.canonical, revision)) ?? 0; + const assertFence = (domain: string) => { + if ((authorityFences.get(sourceKey(domain, repository.canonical, revision)) ?? 0) !== (domain === PUBLIC ? publicFence : privateFence)) + controller.abort(new ReferenceSourceError("unauthorized", "A newer authority observation fenced this reference source.")); + }; const operation: Operation = { key: sourceKey(PUBLIC, repository.canonical, revision), domain: PUBLIC, principalId: input.principalId, grantId: null, controller, joiners: 1, promise: Promise.resolve(undefined as never) }; const assertTurn = () => { signal.throwIfAborted(); if (closed || !context.current()) throw new ReferenceSourceError("cancelled", "The acquiring turn is no longer available."); }; @@ -516,12 +560,15 @@ export function createReferenceSources(options: { access = await options.github!.open({ principalId: input.principalId, repository: repository.url, revision, egress: context.egress, maxBytes, signal, current: () => !closed && context.current() }); const currentAccess = access; - const assertCurrent = () => { assertTurn(); currentAccess.assertCurrent(); }; + const assertCurrent = () => { + assertFence(currentAccess.domain === "public" ? PUBLIC : privateDomain(input.principalId)); + assertTurn(); currentAccess.assertCurrent(); + }; assertCurrent(); const domain = access.domain === "public" ? PUBLIC : privateDomain(input.principalId); Object.assign(operation, { domain, grantId: access.grantId, key: sourceKey(domain, repository.canonical, revision) }); // Private metadata cannot renew a previously shared public copy. - if (domain !== PUBLIC) await withdraw(PUBLIC, repository.canonical, revision); + if (domain !== PUBLIC) await withdrawRepository(PUBLIC, repository.canonical, revision); await withdrawals.get(operation.key); assertCurrent(); const check = await access.resolve(); @@ -557,16 +604,17 @@ export function createReferenceSources(options: { } catch (error) { result?.release(); result = undefined; const refusal = error instanceof ReferenceTransportError ? error.reason : error instanceof ReferenceSourceError ? error.code : null; - if (refusal === "denied" || refusal === "unauthorized" || refusal === "missing") { + if (!signal.aborted && context.current() && (refusal === "denied" || refusal === "unauthorized" || refusal === "missing")) { // Opening metadata may fail before it selects a domain. Fence both // known copies; neither the public cache nor this principal's cache // may outlive an explicit authority refusal. - await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => withdraw(domain, repository.canonical, revision))); - } else if (!access) { + await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => refusal === "missing" + ? withdraw(domain, repository.canonical, revision) : withdrawRepository(domain, repository.canonical, revision))); + } else if (!signal.aborted && context.current() && !access) { // An incomplete metadata check may already have refused anonymous // access. Preserve the cached roots, but withhold them until a live // acquisition establishes authority again. - await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => suspendSource(domain, repository.canonical, revision))); + await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => suspendRepository(domain, repository.canonical, revision))); } if (error instanceof ReferenceTransportError) throw new ReferenceSourceError(error.reason === "denied" ? "unauthorized" : error.reason, error.message); throw error; @@ -575,6 +623,7 @@ export function createReferenceSources(options: { operations.set(id, operation); try { await operation.promise; + assertFence(operation.domain); assertTurn(); // Closing the wire also awaits: its original private grant must still // authorize the lease after shutdown, without inheriting a new grant. @@ -584,7 +633,7 @@ export function createReferenceSources(options: { } catch (error) { const held = result; held?.release(); - if (held && error instanceof ReferenceSourceError && error.code === "unauthorized") await withdraw(operation.domain, repository.canonical, revision); + if (held && !controller.signal.aborted && error instanceof ReferenceSourceError && error.code === "unauthorized") await withdraw(operation.domain, repository.canonical, revision); throw error; } finally { operations.delete(id); void settle(...splitKey(operation.key)).catch(error => warn("managed source settle failed", error)); } @@ -802,23 +851,28 @@ export function createReferenceSources(options: { */ async function revoke(input: { grantIds: readonly string[]; principalIds: readonly string[] }) { const principals = new Set(input.principalIds); + const keys = new Set(); for (const id of input.grantIds) { const owner = db.query("SELECT principal_id FROM reference_grants WHERE id = ?").get(id) as { principal_id: string } | null; if (owner) principals.add(owner.principal_id); } for (const operation of operations.values()) - if (operation.domain !== PUBLIC && (principals.has(operation.principalId!) || input.grantIds.includes(operation.grantId!))) + if (operation.domain !== PUBLIC && (principals.has(operation.principalId!) || input.grantIds.includes(operation.grantId!))) { + keys.add(operation.key); operation.controller.abort(new ReferenceSourceError("unauthorized", "Reference authority was revoked.")); + } // A publication submitted before revocation used to be visible here at once. // Wait for its receipt so even a source's first publication is withdrawn. await write.settled(); for (const principalId of principals) { const sources = db.query("SELECT * FROM reference_sources WHERE domain = ?").all(privateDomain(principalId)) as SourceRow[]; - for (const source of sources) { - let covered = false; - try { covered = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId, repository: referenceRepository(source.repository), now: now() })); } catch { covered = false; } - if (!covered) await withdraw(source.domain, source.repository, source.revision); - } + for (const source of sources) keys.add(sourceKey(source.domain, source.repository, source.revision)); + } + for (const key of keys) { + const [domain, repository, revision] = splitKey(key), principalId = domain.slice("private:".length); + let covered = false; + try { covered = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId, repository: referenceRepository(repository), now: now() })); } catch { covered = false; } + if (!covered) await withdraw(domain, repository, revision); } } diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 42fca603fd..120f805b82 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -28,6 +28,7 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { const other = createPrincipal(db, { authMethod: "password", label: "Telemachus", ttlSeconds: 3600 }); const writer = options.worker ? openSqliteWriter(db) : undefined; if (writer) registerReferenceWrites(db, writer); + const credentials: Record = { GITHUB_TOKEN: "odysseus-fixture-token" }; const metadata: string[] = [], git: unknown[] = []; const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200 }; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { @@ -41,13 +42,13 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe(value) { records.push(value); } }); const secondEgress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe() {} }); const transport: ReferenceTransport = { - async resolve(input) { git.push(input); return { ok: true, commit, ref: "refs/heads/main" }; }, + async resolve(input) { git.push(input); return { ok: true, commit, ref: `refs/heads/${input.revision}` }; }, async fetch(input) { git.push(input); state.fetches++; writeFileSync(join(input.root, "README.md"), "Odysseus charts Ithaca on 2026-07-12.\n"); return { commit }; }, async checkout() {}, async tree() { return tree; }, }; const pool = referencePoolDouble(join(directory, "pool")); - const access = (database = db) => createGitHubReferenceAccess({ db: database, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, transport, + const access = (database = db) => createGitHubReferenceAccess({ db: database, brain, credentials, transport, wireTransport: { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], connect: (() => connect({ host: "127.0.0.1", port: server.port! })) as typeof connect } }); const github = access(); @@ -59,7 +60,7 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { const input = { repository, revision: "main", principalId, acquisition: { turnId, egress: proxy, current: () => state.current } }; return sources.request(input); }; - return { sources, sourceOptions, request, db, pool, transport, github, owner, other, grant, state, egress, secondEgress, metadata, git, records, + return { sources, sourceOptions, request, db, pool, transport, github, credentials, owner, other, grant, state, egress, secondEgress, metadata, git, records, restart(database: ReturnType) { return createReferenceSources({ ...sourceOptions, db: database, github: access(database) }); }, databasePath: join(directory, "ui.db"), async close() { await sources.close(); await writer?.close(); egress.stop(); secondEgress.stop(); server.stop(true); db.close(); } }; @@ -268,6 +269,122 @@ for (const wait of ["coverage", "native-grant"] as const) } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } }); describe("live managed authority", () => { + test("private revocation waits for an in-flight first publication with no catalog row", async () => { + const f = await fixture({ private: true }), issued = f.grant(), arrived = Promise.withResolvers(), resume = Promise.withResolvers(); + const publish = f.pool.poolPublish, release = f.pool.poolRelease, releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(); + let publishedPath = "", publishedId = "", releasePaused = false, revocation: Promise | undefined; + f.pool.poolPublish = async (...args) => { + const result = await publish(...args); publishedPath = join(result.path!, "README.md"); publishedId = args[0]; + arrived.resolve(); await resume.promise; return result; + }; + f.pool.poolRelease = async (...args) => { + if (args[0] === publishedId && !releasePaused) { releasePaused = true; releaseStarted.resolve(); await resumeRelease.promise; } + return release(...args); + }; + const request = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; + expect(readFileSync(publishedPath, "utf8")).toContain("Odysseus"); + expect(f.db.query("SELECT 1 FROM reference_sources").get()).toBeNull(); + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); + let finished = false; + revocation = f.sources.revoke({ grantIds: [issued.id], principalIds: [] }).then(() => { finished = true; }); + await new Promise(resolve => setImmediate(resolve)); + expect(finished, "PRIVATE_REVOCATION_WAITS_FOR_DISPATCHED_PUBLICATION").toBe(false); + resume.resolve(); await releaseStarted.promise; await revocation; + expect(existsSync(publishedPath), "PRIVATE_REVOCATION_HIDES_FIRST_PUBLICATION_BEFORE_RETURNING").toBe(false); + resumeRelease.resolve(); + const result = await request; + expect(result.error).toMatchObject({ code: "unauthorized" }); result.lease?.release(); + } finally { resume.resolve(); resumeRelease.resolve(); await revocation; (await request).lease?.release(); await f.close(); } + }); + + test("concurrent private requests do not inherit another request's public fence", async () => { + const f = await fixture({ private: true }); f.grant(); + const secondOpened = Promise.withResolvers(), resumeSecond = Promise.withResolvers(), open = f.github.open; + let openings = 0, first: Awaited> | undefined, second: typeof first; + f.github.open = async input => { + const index = ++openings, access = await open(input); + if (index === 2) { secondOpened.resolve(); await resumeSecond.promise; } + return access; + }; + const earlier = f.request(), later = f.request(f.owner.id, "odysseus-second-private-turn", f.secondEgress); + void later.catch(() => {}); + try { + await secondOpened.promise; + first = await earlier; + resumeSecond.resolve(); second = await later; + expect(first.domain).toBe("private"); expect(second.domain).toBe("private"); + expect(f.egress.usedBytes()).toBeGreaterThan(0); expect(f.secondEgress.usedBytes()).toBeGreaterThan(0); + } finally { + resumeSecond.resolve(); + first ??= await earlier.catch(() => undefined); second ??= await later.catch(() => undefined); + second?.release(); first?.release(); await f.close(); + } + }); + + for (const olderRevision of ["main", "return-home"]) + for (const outcome of ["private", "denied", "unavailable"] as const) + test(`an older first public publication of ${olderRevision} cannot survive newer ${outcome} metadata authority`, async () => { + const f = await fixture(), arrived = Promise.withResolvers(), resume = Promise.withResolvers(), observed = Promise.withResolvers(); + const publish = f.pool.poolPublish, open = f.github.open; + let paused = false, publicName = "", publicRootId = "", first: Awaited> | undefined, second: Awaited> | undefined; + f.pool.poolPublish = async (...args) => { + const result = await publish(...args); + if (!paused) { + paused = true; publicName = args[2]; publicRootId = args[0]; + expect(readFileSync(join(result.path!, "README.md"), "utf8"), "OLDER_PUBLIC_NATIVE_PUBLICATION_HAS_READABLE_FILES").toContain("Odysseus"); + arrived.resolve(); await resume.promise; + } + return result; + }; + let earlier: Promise<{ lease?: Awaited>; error?: unknown }> | undefined; + try { + earlier = f.sources.request({ principalId: f.owner.id, repository, revision: olderRevision, + acquisition: { turnId: "odysseus-earlier-public-turn", egress: f.egress, current: () => f.state.current } }) + .then(lease => ({ lease }), error => ({ error })); + await arrived.promise; + expect(f.db.query("SELECT 1 FROM reference_sources").get(), "FIRST_PUBLIC_PUBLICATION_HAS_NO_CATALOG_ROW_YET").toBeNull(); + f.state.private = true; + if (outcome !== "denied") f.grant(); + if (outcome === "unavailable") f.credentials.GITHUB_TOKEN = undefined; + f.github.open = async input => { try { return await open(input); } finally { observed.resolve(); } }; + const later = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + await observed.promise; + // Let the source service process the completed metadata result before + // the older native reply arrives; no wall-clock race or external I/O. + await new Promise(resolve => setImmediate(resolve)); + resume.resolve(); + const old = await earlier, current = await later; + first = old.lease; second = current.lease; + if (outcome === "private") expect(second?.domain).toBe("private"); + else expect(current.error).toMatchObject({ code: outcome === "denied" ? "unauthorized" : "unavailable" }); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, publicName, "README.md")), "LATE_PUBLIC_PUBLICATION_CANNOT_REEXPOSE_SOURCE").toBe(false); + expect(existsSync(join(views.public, publicRootId, "README.md")), "LATE_PUBLIC_PUBLICATION_CANNOT_EXPOSE_ROOT_IDENTITY").toBe(false); + expect(f.db.query("SELECT 1 FROM reference_sources WHERE domain = 'public' AND root_id IS NOT NULL").get(), "LATE_PUBLIC_PUBLICATION_CANNOT_RECREATE_PUBLIC_CATALOG").toBeNull(); + expect(old.error, "OLDER_PUBLIC_PUBLICATION_IS_FENCED_BY_NEWER_AUTHORITY").toMatchObject({ code: "unauthorized" }); + } finally { + resume.resolve(); + first ??= (await earlier)?.lease; + second?.release(); first?.release(); await f.close(); + } + }); + + test("a private metadata observation withdraws every cached public revision of that repository", async () => { + const f = await fixture(); + let first: Awaited> | undefined, other: typeof first, current: typeof first; + try { + first = await f.request(); + other = await f.sources.request({ principalId: f.owner.id, repository, revision: "return-home", acquisition: { turnId: "odysseus-other-revision", egress: f.egress, current: () => f.state.current } }); + expect(readFileSync(join(other.viewPath, other.name, "README.md"), "utf8")).toContain("Odysseus"); + f.state.private = true; f.grant(); current = await f.request(); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, first.name, "README.md")), "PRIVATE_METADATA_FENCES_REQUESTED_PUBLIC_REVISION").toBe(false); + expect(existsSync(join(views.public, other.name, "README.md")), "PRIVATE_METADATA_FENCES_OTHER_PUBLIC_REVISIONS").toBe(false); + } finally { current?.release(); other?.release(); first?.release(); await f.close(); } + }); + for (const refusal of ["metadata", "git-denial", "missing-ref"] as const) test(`a known public source is hidden from another principal after ${refusal} refuses it`, async () => { const f = await fixture(); From 094d0c775ba4996304922471f59c29b0123db5ab Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 04:01:04 +0000 Subject: [PATCH 10/27] fix(ui-server): fence incomplete metadata and canonical GitHub aliases --- docs/decisions/managed-worktrees.md | 8 +- .../decisions/reference-source-acquisition.md | 25 ++-- .../src/brain/github-reference-access.ts | 14 +- .../ui-server/src/brain/reference-source.ts | 73 +++++++--- .../tests/reference-source-managed.test.ts | 128 +++++++++++++++++- 5 files changed, 212 insertions(+), 36 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 1a4e2ff46b..088c1075a1 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -223,7 +223,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:950-981`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:981-1012`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -266,7 +266,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:754-792`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:785-823`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -280,7 +280,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:686-697`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:712-728`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -299,7 +299,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:798-807`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:829-838`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index b19760d1b6..56a59f9bff 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:95-868`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:96-899`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:307-356`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:315-364`). - Inside both windows a request reuses the published source without any network call. @@ -91,6 +91,13 @@ default to five minutes and are configured separately still pending. Private revocation includes those in-flight identities and confirms they are hidden before returning; storage reclamation may finish later. Concurrent valid private requests keep their own authority and budget. + GitHub cache and grant checks use the fixed transport's canonical repository + identity. Repository-wide fences also cover retained catalog aliases with + different owner/repository casing. Incomplete initial or final metadata + withholds cached and pending native exposure, including before a first catalog + row exists. Final metadata failures are contained before staging cleanup; + ending the turn during cleanup cannot undo that observation. A later valid + metadata check may restore the withheld cache. - A public check that gets no answer proves nothing. Only a principal with a covering grant goes on to the private path; anyone else is refused as `unavailable`. @@ -99,7 +106,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:452-506`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:472-526`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -128,7 +135,7 @@ reclamation is observed. ## Fixed GitHub wire and identity authority (#3613) The concrete access owner (`createGitHubReferenceAccess`, -`packages/ui-server/src/brain/github-reference-access.ts:12-129`) uses the +`packages/ui-server/src/brain/github-reference-access.ts:19-141`) uses the fixed transport (`createGitHubReferenceWire`, `packages/ui-server/src/brain/github-reference-wire.ts:19-254`). @@ -198,9 +205,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:247-262`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:255-270`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:265-290`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:273-298`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -222,7 +229,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:381-397`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:389-405`). There is no idle expiry. ## Revocation and recovery @@ -235,14 +242,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:852-877`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:883-908`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:880-924`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:911-955`). ## Evidence diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index cb71ab8659..301af9ff84 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -9,6 +9,13 @@ import { referenceRevision, ReferenceTransportError, type ReferenceCheck, type R type WireOptions = Parameters[0]; type RequestBounds = Pick & { current?: () => boolean }; +/** A failed final identity observation makes existing cache authority uncertain too. */ +export class GitHubReferenceMetadataError extends ReferenceTransportError { + constructor(error: unknown) { + super(error instanceof ReferenceTransportError ? error.reason : "unavailable", error instanceof Error ? error.message : "GitHub repository identity is unavailable"); + } +} + export function createGitHubReferenceAccess(options: { db: Database; /** Actual served brain identity, never a tool argument. */ @@ -120,7 +127,12 @@ export function createGitHubReferenceAccess(options: { assertCurrent(); if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.canonical, result.value))) throw new ReferenceTransportError("denied", "GitHub repository identity changed during acquisition"); - } catch (error) { await wire.close(); throw error; } + } catch (error) { + const interrupted = input.signal?.aborted || (input.current && !input.current()); + await wire.close(); + if (interrupted) throw error; + throw new GitHubReferenceMetadataError(error); + } }, close: () => wire.close(), }); diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 0cd43db101..2ad40467a1 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -26,7 +26,8 @@ import type { createNativeBrainManagerClient, NativePoolRecord } from "@schlesse import type { Logger } from "@opentelemetry/api-logs"; import { coveringReferenceGrant, isLiveReferenceGrant, referenceRepository, type ReferenceGrant, type ReferenceRepository } from "../db/reference-grants.js"; import { referenceRevision, ReferenceTransportError, type ReferenceTransport } from "./reference-transport.js"; -import type { createGitHubReferenceAccess } from "./github-reference-access.js"; +import { GitHubReferenceMetadataError, type createGitHubReferenceAccess } from "./github-reference-access.js"; +import { githubReferenceRepository } from "./github-reference-identity.js"; import { referenceAcquisitionMatches, type ReferenceAcquisition, type ReferenceAcquisitionContext } from "./reference-acquisition.js"; type GitHubAccess = Awaited["open"]>>; @@ -113,10 +114,17 @@ export function createReferenceSources(options: { const operations = new Map(); const operating = (key: string) => [...operations.values()].some(operation => operation.key === key); const isManaged = (repository: string) => Boolean(options.github && new URL(repository).hostname.toLowerCase() === "github.com"); + /** Use the fixed transport's GitHub identity for cache keys and grant checks alike. */ + function repositoryLocation(input: unknown): ReferenceRepository { + const repository = referenceRepository(input); + return isManaged(repository.canonical) ? referenceRepository(githubReferenceRepository(repository.url).cloneUrl) : repository; + } const leases = new Map(); const withdrawn = new Set(); /** A newer authority observation invalidates older managed requests, including before domain selection. */ const authorityFences = new Map(); + /** One failed metadata observation is fenced once, before any staging cleanup. */ + const metadataFences = new WeakMap>(); /** In-flight withdrawals; an acquisition of the same source waits for its withdrawal to finish. */ const withdrawals = new Map>(); /** @@ -299,7 +307,7 @@ export function createReferenceSources(options: { /** Private work is authorized only while its principal still holds a live covering grant. */ function authorize(domain: string, principalId: string | null, repository: ReferenceRepository): ReferenceGrant | null { if (domain === PUBLIC) return null; - const grant = coveringReferenceGrant(db, { brain: options.brain, principalId: principalId!, repository, now: now() }); + const grant = coveringReferenceGrant(db, { brain: options.brain, principalId: principalId!, repository: repositoryLocation(repository.url), now: now() }); if (!grant) throw new ReferenceSourceError("unauthorized", "No live reference grant covers this repository for this principal."); return grant; } @@ -429,24 +437,36 @@ export function createReferenceSources(options: { authorityFences.set(key, (authorityFences.get(key) ?? 0) + 1); } /** Repository metadata governs every cached or in-flight revision, not only the requested one. */ - function repositoryRevisions(domain: string, repository: string, revision: string): string[] { - const revisions = new Set([revision]); - for (const row of db.query(`SELECT revision FROM reference_sources WHERE domain = ? AND repository = ? - UNION SELECT revision FROM reference_roots WHERE domain = ? AND repository = ?`).all(domain, repository, domain, repository) as { revision: string }[]) - revisions.add(row.revision); + function repositoryKeys(domain: string, repository: string, revision: string): string[] { + const keys = new Set([sourceKey(domain, repository, revision)]); + const equivalent = (candidate: string) => { + if (candidate === repository) return true; + try { return githubReferenceRepository(candidate).canonical === repository; } catch { return false; } + }; + for (const row of db.query(`SELECT repository, revision FROM reference_sources WHERE domain = ? + UNION SELECT repository, revision FROM reference_roots WHERE domain = ?`).all(domain, domain) as { repository: string; revision: string }[]) + if (equivalent(row.repository)) keys.add(sourceKey(domain, row.repository, row.revision)); for (const operation of operations.values()) { const [heldDomain, heldRepository, heldRevision] = splitKey(operation.key); - if (heldRepository === repository && (heldDomain === domain || (operation.principalId !== null && domain === privateDomain(operation.principalId)))) revisions.add(heldRevision); + if (equivalent(heldRepository) && (heldDomain === domain || (operation.principalId !== null && domain === privateDomain(operation.principalId)))) keys.add(sourceKey(domain, heldRepository, heldRevision)); } - return [...revisions]; + return [...keys]; } function withdrawRepository(domain: string, repository: string, revision: string): Promise { - return Promise.all(repositoryRevisions(domain, repository, revision).map(revision => withdraw(domain, repository, revision))); + return Promise.all(repositoryKeys(domain, repository, revision).map(key => withdraw(...splitKey(key)))); } function suspendRepository(domain: string, repository: string, revision: string): Promise { - const revisions = repositoryRevisions(domain, repository, revision); - for (const revision of revisions) fenceSource(sourceKey(domain, repository, revision)); - return Promise.all(revisions.map(revision => suspendSource(domain, repository, revision))); + const keys = repositoryKeys(domain, repository, revision); + for (const key of keys) fenceSource(key); + return Promise.all(keys.map(key => suspendSource(...splitKey(key)))); + } + function fenceMetadataFailure(error: GitHubReferenceMetadataError, principalId: string, repository: string, revision: string): Promise { + const pending = metadataFences.get(error); + if (pending) return pending; + const work = Promise.all([PUBLIC, privateDomain(principalId)].map(domain => error.reason === "denied" + ? withdrawRepository(domain, repository, revision) : suspendRepository(domain, repository, revision))).then(() => {}); + metadataFences.set(error, work); + return work; } async function acquire(signal: AbortSignal, input: { domain: string; principalId: string | null; repository: ReferenceRepository; revision: string; grant: ReferenceGrant | null; @@ -515,6 +535,8 @@ export function createReferenceSources(options: { } }); } catch (error) { + if (error instanceof GitHubReferenceMetadataError) await fenceMetadataFailure(error, input.principalId!, repository.canonical, revision) + .catch(cleanup => warn("metadata authority withdrawal is incomplete; bind preparation retries it", cleanup)); // Staging is never published; its reservation is released through the pool only now that the workers stopped. const id = staging.id; const state = (db.query("SELECT state FROM reference_roots WHERE id = ?").get(id) as { state: string } | null)?.state; @@ -604,7 +626,11 @@ export function createReferenceSources(options: { } catch (error) { result?.release(); result = undefined; const refusal = error instanceof ReferenceTransportError ? error.reason : error instanceof ReferenceSourceError ? error.code : null; - if (!signal.aborted && context.current() && (refusal === "denied" || refusal === "unauthorized" || refusal === "missing")) { + if (error instanceof GitHubReferenceMetadataError) { + // A known observation still fences cache authority if its turn ends + // while wire shutdown or staging cleanup is settling. + await fenceMetadataFailure(error, input.principalId, repository.canonical, revision); + } else if (!signal.aborted && context.current() && (refusal === "denied" || refusal === "unauthorized" || refusal === "missing")) { // Opening metadata may fail before it selects a domain. Fence both // known copies; neither the public cache nor this principal's cache // may outlive an explicit authority refusal. @@ -643,7 +669,7 @@ export function createReferenceSources(options: { if (closed) throw new ReferenceSourceError("unavailable", "Reference sources are closed."); if (input.signal?.aborted) throw new ReferenceSourceError("cancelled", "Reference acquisition request was cancelled."); let repository: ReferenceRepository, revision: string; - try { repository = referenceRepository(input.repository); revision = referenceRevision(input.revision); } + try { repository = repositoryLocation(input.repository); revision = referenceRevision(input.revision); } catch (error) { throw new ReferenceSourceError("invalid", (error as Error).message); } if (isManaged(repository.canonical)) return managedRequest(input, repository, revision); const probeKey = `${repository.canonical}\u0000${revision}`; @@ -687,11 +713,16 @@ export function createReferenceSources(options: { const key = sourceKey(domain, repository, revision); return exclusive(key, async () => { const source = row(domain, repository, revision); - if (!source?.root_id || withdrawn.has(key) || (suspended.has(key) && !unsettled.has(key))) return; - suspended.add(key); unsettled.add(key); const roots = db.query("SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ? AND state != 'staging'").all(domain, repository, revision) as { id: string }[]; - await pool.poolUnpublish((await viewFor(domain)).id, source.name); + const pending = [...pendingPublications].filter(([, publication]) => publication.key === key); + if ((!source?.root_id && !roots.length && !pending.length) || (suspended.has(key) && !unsettled.has(key) && !pending.length)) return; + suspended.add(key); unsettled.add(key); + if (source) await pool.poolUnpublish((await viewFor(domain)).id, source.name); for (const root of roots) await hideRoot(root.id); + for (const [id, publication] of pending) { + await pool.poolUnpublish(publication.view, publication.name); + await hideRoot(id); + } unsettled.delete(key); }); } @@ -871,7 +902,7 @@ export function createReferenceSources(options: { for (const key of keys) { const [domain, repository, revision] = splitKey(key), principalId = domain.slice("private:".length); let covered = false; - try { covered = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId, repository: referenceRepository(repository), now: now() })); } catch { covered = false; } + try { covered = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId, repository: repositoryLocation(repository), now: now() })); } catch { covered = false; } if (!covered) await withdraw(domain, repository, revision); } } @@ -897,7 +928,7 @@ export function createReferenceSources(options: { brain: options.brain, commit: source.commit_id!, ref: source.ref, }); if (usableRoot && source.domain !== PUBLIC) { - try { usableRoot = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: source.domain.slice("private:".length), repository: referenceRepository(source.repository), now: now() })); } + try { usableRoot = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: source.domain.slice("private:".length), repository: repositoryLocation(source.repository), now: now() })); } catch { usableRoot = false; } } if (usableRoot) { @@ -930,7 +961,7 @@ export function createReferenceSources(options: { request, /** Whether a live grant covers this repository for this principal now; private worktrees (#2430) need one for every access. */ covers(input: { principalId: string; repository: string }): boolean { - try { return Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: input.principalId, repository: referenceRepository(input.repository), now: now() })); } + try { return Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: input.principalId, repository: repositoryLocation(input.repository), now: now() })); } catch { return false; } }, revoke, diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 120f805b82..972cbcf34c 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -30,9 +30,11 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { if (writer) registerReferenceWrites(db, writer); const credentials: Record = { GITHUB_TOKEN: "odysseus-fixture-token" }; const metadata: string[] = [], git: unknown[] = []; - const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200 }; + const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200, invalidAt: 0, invalidJsonAt: 0 }; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { metadata.push(request.headers.get("authorization") ?? "anonymous"); + if (metadata.length === state.invalidJsonAt) return new Response("{", { headers: { "content-type": "application/json" } }); + if (metadata.length === state.invalidAt) return Response.json({ id: "invalid" }); if (state.status !== 200) return new Response(null, { status: state.status }); if (state.private && !request.headers.has("authorization")) return new Response(null, { status: 404 }); return Response.json({ id: 101, owner: { id: state.ownerId, login: "Odysseus" }, name: "Ithaca", full_name: "Odysseus/Ithaca", @@ -269,6 +271,130 @@ for (const wait of ["coverage", "native-grant"] as const) } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } }); describe("live managed authority", () => { + test("a malformed refresh hides the previous source before staging cleanup or turn cancellation", async () => { + const f = await fixture(), releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(), release = f.pool.poolRelease; + let held: Awaited> | undefined, request: Promise | undefined; + const controller = new AbortController(); + try { + held = await f.request(); + const nextCommit = "c".repeat(40), fetch = f.transport.fetch; + f.transport.resolve = async () => ({ ok: true, commit: nextCommit, ref: "refs/heads/main" }); + f.transport.fetch = async input => { await fetch(input); return { commit: nextCommit }; }; + f.state.invalidAt = f.metadata.length + 2; + f.pool.poolRelease = async (...args) => { releaseStarted.resolve(); await resumeRelease.promise; return release(...args); }; + request = f.sources.request({ principalId: f.owner.id, repository, revision: "main", signal: controller.signal, + acquisition: { turnId: "odysseus-malformed-refresh", egress: f.egress, current: () => f.state.current } }).then(lease => { lease.release(); return null; }, error => error); + await releaseStarted.promise; + expect(existsSync(join(held.viewPath, held.name, "README.md")), "MALFORMED_REFRESH_HIDES_CACHE_BEFORE_STAGING_CLEANUP").toBe(false); + f.state.current = false; controller.abort(); resumeRelease.resolve(); + expect(await request).toBeInstanceOf(Error); + expect(existsSync(join(held.viewPath, held.rootId, "README.md")), "TURN_END_CANNOT_RESTORE_KNOWN_INVALID_METADATA").toBe(false); + } finally { resumeRelease.resolve(); await request; held?.release(); await f.close(); } + }); + + for (const malformed of ["schema", "json"] as const) + test(`malformed final ${malformed} metadata withholds a cached public source`, async () => { + const f = await fixture(); let held: Awaited> | undefined; + try { + held = await f.request(); + expect(readFileSync(join(held.viewPath, held.name, "README.md"), "utf8")).toContain("Odysseus"); + if (malformed === "schema") f.state.invalidAt = f.metadata.length + 2; + else f.state.invalidJsonAt = f.metadata.length + 2; + await expect(f.request(), "FINAL_METADATA_REFUSES_THE_REVALIDATION").rejects.toThrow(); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, held.name, "README.md")), "MALFORMED_FINAL_METADATA_WITHHOLDS_CACHED_NAME").toBe(false); + expect(existsSync(join(views.public, held.rootId, "README.md")), "MALFORMED_FINAL_METADATA_WITHHOLDS_CACHED_ROOT").toBe(false); + f.state.invalidAt = 0; f.state.invalidJsonAt = 0; + const recovered = await f.request(); + try { + expect(recovered.rootId, "VALID_METADATA_RESTORES_THE_WITHHELD_CACHE").toBe(held.rootId); + expect(readFileSync(join(recovered.viewPath, recovered.name, "README.md"), "utf8")).toContain("Odysseus"); + } finally { recovered.release(); } + } finally { held?.release(); await f.close(); } + }); + + for (const alias of ["https://github.com/Odysseus/Ithaca", "https://GITHUB.COM/Odysseus/Ithaca.git"]) + test(`GitHub authority withdrawal covers the URL alias ${alias}`, async () => { + const f = await fixture(); let held: Awaited> | undefined; + try { + held = await f.sources.request({ principalId: f.owner.id, repository: alias, revision: "main", acquisition: { turnId: "odysseus-alias-turn", egress: f.egress, current: () => f.state.current } }); + expect(readFileSync(join(held.viewPath, held.name, "README.md"), "utf8")).toContain("Odysseus"); + f.state.private = true; + await expect(f.request()).rejects.toMatchObject({ code: "unauthorized" }); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, held.name, "README.md")), "GITHUB_ALIAS_CANNOT_BYPASS_PUBLIC_WITHDRAWAL").toBe(false); + expect(existsSync(join(views.public, held.rootId, "README.md")), "GITHUB_ALIAS_ROOT_CANNOT_BYPASS_WITHDRAWAL").toBe(false); + } finally { held?.release(); await f.close(); } + }); + + test("GitHub URL aliases share the transport's canonical cache identity", async () => { + const f = await fixture(); let first: Awaited> | undefined, second: typeof first; + try { + first = await f.sources.request({ principalId: f.owner.id, repository: "https://github.com/Odysseus/Ithaca.git", revision: "main", acquisition: { turnId: "odysseus-canonical-alias", egress: f.egress, current: () => f.state.current } }); + second = await f.request(f.other.id, "odysseus-canonical-second", f.secondEgress); + expect(first.repository, "GITHUB_CACHE_USES_TRANSPORT_CANONICAL_IDENTITY").toBe(repository); + expect(second.rootId, "GITHUB_ALIASES_REUSE_THE_SAME_SEALED_ROOT").toBe(first.rootId); + expect(f.state.fetches, "GITHUB_ALIASES_DO_NOT_FETCH_DUPLICATE_ROOTS").toBe(1); + expect(readFileSync(join(second.viewPath, second.name, "README.md"), "utf8")).toContain("Odysseus"); + } finally { second?.release(); first?.release(); await f.close(); } + }); + + test("authority withdrawal also fences an already stored noncanonical GitHub catalog key", async () => { + const f = await fixture(); let held: Awaited> | undefined; + try { + held = await f.request(); + // Simulate disposable catalog state retained from an earlier service. + f.db.transaction(() => { + f.db.query("UPDATE reference_sources SET repository = ? WHERE repository = ?").run("https://github.com/Odysseus/Ithaca", repository); + f.db.query("UPDATE reference_roots SET repository = ? WHERE repository = ?").run("https://github.com/Odysseus/Ithaca", repository); + })(); + expect(readFileSync(join(held.viewPath, held.name, "README.md"), "utf8")).toContain("Odysseus"); + f.state.private = true; + await expect(f.request()).rejects.toMatchObject({ code: "unauthorized" }); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, held.name, "README.md")), "STORED_GITHUB_ALIAS_IS_FENCED").toBe(false); + } finally { held?.release(); await f.close(); } + }); + + for (const initialPrivate of [false, true]) + test(`a retained ${initialPrivate ? "private" : "public"} worktree alias uses the actual transport's grant scope`, async () => { + const f = await fixture({ private: initialPrivate }); f.grant(); + const context = { turnId: "odysseus-retained-alias-turn", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => {} }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + f.db.query("UPDATE reference_worktrees SET repository = ? WHERE id = ?").run("https://github.com/Odysseus/Ithaca", item.id); + f.state.private = true; + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }), + "RETAINED_ALIAS_USES_LIVE_CANONICAL_GRANT").resolves.toMatchObject({ generation: generation.id }); + expect(readFileSync(join(generation.path, item.id, "README.md"), "utf8")).toContain("Odysseus"); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } + }); + + test("incomplete metadata hides a first native publication before delayed storage release", async () => { + const f = await fixture(), arrived = Promise.withResolvers(), resume = Promise.withResolvers(), observed = Promise.withResolvers(); + const releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(), publish = f.pool.poolPublish, release = f.pool.poolRelease, open = f.github.open; + let path = "", id = "", released = false; + f.pool.poolPublish = async (...args) => { const result = await publish(...args); path = join(result.path!, "README.md"); id = args[0]; arrived.resolve(); await resume.promise; return result; }; + f.pool.poolRelease = async (...args) => { if (args[0] === id && !released) { released = true; releaseStarted.resolve(); await resumeRelease.promise; } return release(...args); }; + const earlier = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + let later: Promise<{ lease: Awaited> | undefined; error: unknown }> | undefined; + try { + await arrived.promise; expect(readFileSync(path, "utf8")).toContain("Odysseus"); + f.state.private = true; f.grant(); f.credentials.GITHUB_TOKEN = undefined; + f.github.open = async input => { try { return await open(input); } finally { observed.resolve(); } }; + later = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + await observed.promise; await new Promise(resolve => setImmediate(resolve)); + resume.resolve(); await releaseStarted.promise; + const current = await later; current.lease?.release(); + expect(current.error).toMatchObject({ code: "unavailable" }); + expect(existsSync(path), "INCOMPLETE_METADATA_HIDES_NATIVE_EXPOSURE_WITHOUT_CATALOG").toBe(false); + resumeRelease.resolve(); expect((await earlier).error).toMatchObject({ code: "unauthorized" }); + } finally { resume.resolve(); resumeRelease.resolve(); (await earlier).lease?.release(); (await later)?.lease?.release(); await f.close(); } + }); + test("private revocation waits for an in-flight first publication with no catalog row", async () => { const f = await fixture({ private: true }), issued = f.grant(), arrived = Promise.withResolvers(), resume = Promise.withResolvers(); const publish = f.pool.poolPublish, release = f.pool.poolRelease, releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(); From 0b63883f5478d976c37e0dc4ad3ab57e2e90c472 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 04:46:20 +0000 Subject: [PATCH 11/27] CONTRACT: fix(ui-server): preserve grant aliases and contain authority loss durably --- docs/decisions/managed-worktrees.md | 2 +- .../decisions/reference-source-acquisition.md | 17 ++-- docs/decisions/reference-source-grants.md | 12 ++- docs/integration-contract/http.md | 7 ++ .../src/brain/reference-source-writes.ts | 3 + .../ui-server/src/brain/reference-source.ts | 70 ++++++++-------- packages/ui-server/src/db/reference-grants.ts | 19 ++++- .../ui-server/tests/reference-grants.test.ts | 34 +++++++- .../tests/reference-source-managed.test.ts | 82 ++++++++++++++++++- 9 files changed, 196 insertions(+), 50 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 088c1075a1..d20147a920 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -280,7 +280,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:712-728`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:711-728`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 56a59f9bff..264bb5a0dc 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:315-364`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:316-365`). - Inside both windows a request reuses the published source without any network call. @@ -98,6 +98,13 @@ default to five minutes and are configured separately row exists. Final metadata failures are contained before staging cleanup; ending the turn during cleanup cannot undo that observation. A later valid metadata check may restore the withheld cache. + Suspension also expires the stored validation clock, so restart cannot + republish uncertain authority into a newly bound view without fresh + validation. Post-publication authority loss hides native exposure before + storage cleanup begins. Managed failure containment runs once per request; + its later cleanup cannot unpublish a newer validated source. Refusal before + any metadata attempt, such as exhausted turn allowance, does not invalidate + another turn's cached authority. - A public check that gets no answer proves nothing. Only a principal with a covering grant goes on to the private path; anyone else is refused as `unavailable`. @@ -106,7 +113,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:472-526`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:465-519`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -205,9 +212,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:255-270`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:256-271`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:273-298`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:274-299`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -229,7 +236,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:389-405`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:390-406`). There is no idle expiry. ## Revocation and recovery diff --git a/docs/decisions/reference-source-grants.md b/docs/decisions/reference-source-grants.md index f2b34f2ff4..4720f10640 100644 --- a/docs/decisions/reference-source-grants.md +++ b/docs/decisions/reference-source-grants.md @@ -28,7 +28,7 @@ The maintainer selected **owner-managed grant records** on 2026-10-22 ## The record A grant is one row of the UI database's `reference_grants` table -(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:122-149`). +(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:127-155`). The table holds the served brain's identity, the principal, the canonical repository prefix, the credential name or null, the granting owner and the revocation time. It stores no credential value. A grant is **live** while it @@ -47,13 +47,19 @@ owner session ends when that session does. A repository location is HTTPS without user info, query or fragment; loopback `http://`; or an absolute `file:///` path -(`referenceRepository`, `packages/ui-server/src/db/reference-grants.ts:52-76`). +(`referenceRepository`, `packages/ui-server/src/db/reference-grants.ts:52-77`). SSH is refused: no grantable credential is an SSH key. The canonical form lowercases the origin and drops a trailing slash and a hosted `.git` suffix. A prefix covers itself and every path below it at a segment boundary, so `…/odysseus` never covers `…/odysseus-crew`. The longest covering live prefix wins, read at the moment of use -(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:169-175`). +(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:175-186`). + +GitHub HTTPS paths are normalized to lowercase, matching the qualified +transport. Retained mixed-case prefixes are normalized for matching and +duplicate detection without rewriting their receipts. Specificity uses the +canonical prefix length, so an older spelling cannot select a broader API +credential permission. Other hosts and local paths remain case-sensitive. A grant names its credential from a fixed list of existing host selectors, each with the one origin it may be sent to diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index 22a77073e0..67952d1bfa 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -1155,6 +1155,13 @@ transport or source-trust qualification and exposes no generic API relay. Changing recipient permission uses revoke/recreate; an existing grant with the same principal/prefix/credential remains a duplicate. +GitHub HTTPS owner/repository prefixes use lowercase canonical paths. Existing +mixed-case stored prefixes match the same canonical identity and count as +duplicates; the longest canonical prefix still selects the grant and its +independent API credential permission. Paths on other hosts and local file +paths retain their case-sensitive comparison. Receipt fields and credential +recipient permissions are unchanged. + ## Content renderer bootstrap declarations (additive, #2087) Authenticated `GET /api/status` includes optional `contentRenderers`, an array of diff --git a/packages/ui-server/src/brain/reference-source-writes.ts b/packages/ui-server/src/brain/reference-source-writes.ts index bb8763732e..a55e4f4229 100644 --- a/packages/ui-server/src/brain/reference-source-writes.ts +++ b/packages/ui-server/src/brain/reference-source-writes.ts @@ -23,6 +23,9 @@ export function sourceWrites(db: Database) { sourceValidate(at: number, refreshedAt: number, ref: string, domain: string, repository: string, revision: string) { db.query("UPDATE reference_sources SET validated_at = ?, refreshed_at = ?, last_error = NULL, ref = ? WHERE domain = ? AND repository = ? AND revision = ?").run(at, refreshedAt, ref, domain, repository, revision); }, + sourceSuspend(domain: string, repository: string, revision: string) { + db.query("UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ?").run(domain, repository, revision); + }, sourceFailed(detail: string, at: number, domain: string, repository: string, revision: string) { db.query("UPDATE reference_sources SET last_error = ?, last_failed_at = ? WHERE domain = ? AND repository = ? AND revision = ?").run(detail, at, domain, repository, revision); }, diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 2ad40467a1..030c7501fa 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -123,8 +123,6 @@ export function createReferenceSources(options: { const withdrawn = new Set(); /** A newer authority observation invalidates older managed requests, including before domain selection. */ const authorityFences = new Map(); - /** One failed metadata observation is fenced once, before any staging cleanup. */ - const metadataFences = new WeakMap>(); /** In-flight withdrawals; an acquisition of the same source waits for its withdrawal to finish. */ const withdrawals = new Map>(); /** @@ -231,6 +229,9 @@ export function createReferenceSources(options: { function warn(body: string, error: unknown) { options.log?.emit({ severityText: "WARN", body: `${body}: ${error instanceof Error ? error.message : String(error)}` }); } + function failureReason(error: unknown): string | null { + return error instanceof ReferenceTransportError ? error.reason : error instanceof ReferenceSourceError ? error.code : null; + } /** Release superseded and withdrawn roots once no reader protects them; forget a withdrawn source once nothing acts on it. */ async function settle(domain: string, repository: string, revision: string) { @@ -352,7 +353,7 @@ export function createReferenceSources(options: { if (signal.aborted) throw error; const detail = error instanceof Error ? error.message : String(error); // A denied fetch is lost authority, never an outage: no stale copy survives it. - if (error instanceof ReferenceTransportError && error.reason === "denied") { + if (failureReason(error) === "denied" || failureReason(error) === "unauthorized") { await withdraw(domain, repository.canonical, revision); if (domain === PUBLIC) { notPublic.set(`${repository.canonical}\u0000${revision}`, now() + limits.validationMs); return { kind: "not-public", reason: "denied", detail }; } throw new ReferenceSourceError("unauthorized", detail); @@ -460,18 +461,10 @@ export function createReferenceSources(options: { for (const key of keys) fenceSource(key); return Promise.all(keys.map(key => suspendSource(...splitKey(key)))); } - function fenceMetadataFailure(error: GitHubReferenceMetadataError, principalId: string, repository: string, revision: string): Promise { - const pending = metadataFences.get(error); - if (pending) return pending; - const work = Promise.all([PUBLIC, privateDomain(principalId)].map(domain => error.reason === "denied" - ? withdrawRepository(domain, repository, revision) : suspendRepository(domain, repository, revision))).then(() => {}); - metadataFences.set(error, work); - return work; - } async function acquire(signal: AbortSignal, input: { domain: string; principalId: string | null; repository: ReferenceRepository; revision: string; grant: ReferenceGrant | null; credential: string | null; ref: string; expectedCommit: string; previous: SourceRow | null; - managed?: { access: GitHubAccess; context: ReferenceAcquisitionContext; id: string; assertCurrent(): void } }) { + managed?: { access: GitHubAccess; context: ReferenceAcquisitionContext; id: string; assertCurrent(): void; containFailure(error: unknown, publishing: boolean): Promise } }) { const { domain, repository, revision } = input, key = sourceKey(domain, repository.canonical, revision); const name = referenceSourceName(repository, revision), view = await viewFor(domain); const staging = { id: randomUUID() }; @@ -535,8 +528,10 @@ export function createReferenceSources(options: { } }); } catch (error) { - if (error instanceof GitHubReferenceMetadataError) await fenceMetadataFailure(error, input.principalId!, repository.canonical, revision) - .catch(cleanup => warn("metadata authority withdrawal is incomplete; bind preparation retries it", cleanup)); + if (input.managed) await input.managed.containFailure(error, publishing) + .catch(cleanup => warn("reference authority containment is incomplete; bind preparation retries it", cleanup)); + else if (publishing && (failureReason(error) === "denied" || failureReason(error) === "unauthorized")) + await withdraw(domain, repository.canonical, revision).catch(cleanup => warn("revoked reference publication could not be hidden", cleanup)); // Staging is never published; its reservation is released through the pool only now that the workers stopped. const id = staging.id; const state = (db.query("SELECT state FROM reference_roots WHERE id = ?").get(id) as { state: string } | null)?.state; @@ -544,14 +539,13 @@ export function createReferenceSources(options: { // A publication whose reply was lost may have moved the name to the released root. // Point it back only to a previous root that is exposed under live validation; // a suspended or lapsed one stays hidden and its name goes. Otherwise fence the source. - if (publishing && previousRoot) { + if (publishing && previousRoot && !input.managed) { const previous = row(domain, repository.canonical, revision); const exposed = !input.managed && !suspended.has(key) && previous?.root_id === previousRoot && validationLive(previous); await exclusive(key, async () => { if (exposed) await pool.poolPublish(previousRoot, view.id, name); else await pool.poolUnpublish(view.id, name); }).catch(async () => { await withdraw(domain, repository.canonical, revision).catch(cleanup => warn("reference source could not be fenced after a lost publication", cleanup)); }); } - if (publishing && input.managed) await withdraw(domain, repository.canonical, revision).catch(cleanup => warn("managed source withdrawal failed", cleanup)); throw error; } } @@ -572,6 +566,25 @@ export function createReferenceSources(options: { grantId: null, controller, joiners: 1, promise: Promise.resolve(undefined as never) }; const assertTurn = () => { signal.throwIfAborted(); if (closed || !context.current()) throw new ReferenceSourceError("cancelled", "The acquiring turn is no longer available."); }; let result: ReferenceSourceLease | undefined; + let accessOpened = false, openAttempted = false, containment: Promise | undefined; + const containFailure = (error: unknown, publishing: boolean): Promise => { + if (containment) return containment; + const reason = failureReason(error), domains = [PUBLIC, privateDomain(input.principalId)]; + let work: Promise = Promise.resolve(); + if (error instanceof GitHubReferenceMetadataError) { + work = Promise.all(domains.map(domain => reason === "denied" ? withdrawRepository(domain, repository.canonical, revision) + : suspendRepository(domain, repository.canonical, revision))); + } else if (!signal.aborted && context.current() && (reason === "denied" || reason === "unauthorized" || reason === "missing")) { + work = Promise.all(domains.map(domain => reason === "missing" ? withdraw(domain, repository.canonical, revision) + : withdrawRepository(domain, repository.canonical, revision))); + } else if (publishing) { + work = withdraw(operation.domain, repository.canonical, revision); + } else if (!signal.aborted && context.current() && openAttempted && !accessOpened) { + work = Promise.all(domains.map(domain => suspendRepository(domain, repository.canonical, revision))); + } + containment = work.then(() => {}); + return containment; + }; operation.promise = (async () => { const done = await admit(signal); let access: GitHubAccess | undefined; @@ -579,8 +592,10 @@ export function createReferenceSources(options: { assertTurn(); const maxBytes = Math.min(64 * 1048576, context.egress.remainingBytes()); if (maxBytes < 1) throw new ReferenceSourceError("capacity", "The acquiring turn has no network allowance left."); + openAttempted = true; access = await options.github!.open({ principalId: input.principalId, repository: repository.url, revision, egress: context.egress, maxBytes, signal, current: () => !closed && context.current() }); + accessOpened = true; const currentAccess = access; const assertCurrent = () => { assertFence(currentAccess.domain === "public" ? PUBLIC : privateDomain(input.principalId)); @@ -616,7 +631,7 @@ export function createReferenceSources(options: { } if (!reused) await acquire(signal, { domain, principalId: input.principalId, repository, revision, grant: domain === PUBLIC ? null : authorize(domain, input.principalId, repository), credential: null, - ref: check.ref, expectedCommit: check.commit, previous, managed: { access, context, id, assertCurrent } }); + ref: check.ref, expectedCommit: check.commit, previous, managed: { access, context, id, assertCurrent, containFailure } }); assertCurrent(); const current = row(domain, repository.canonical, revision); if (!usable(current)) throw new ReferenceSourceError("unavailable", "Managed source publication is unavailable."); @@ -625,23 +640,7 @@ export function createReferenceSources(options: { return { kind: "source", row: current, stale: false, error: null }; } catch (error) { result?.release(); result = undefined; - const refusal = error instanceof ReferenceTransportError ? error.reason : error instanceof ReferenceSourceError ? error.code : null; - if (error instanceof GitHubReferenceMetadataError) { - // A known observation still fences cache authority if its turn ends - // while wire shutdown or staging cleanup is settling. - await fenceMetadataFailure(error, input.principalId, repository.canonical, revision); - } else if (!signal.aborted && context.current() && (refusal === "denied" || refusal === "unauthorized" || refusal === "missing")) { - // Opening metadata may fail before it selects a domain. Fence both - // known copies; neither the public cache nor this principal's cache - // may outlive an explicit authority refusal. - await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => refusal === "missing" - ? withdraw(domain, repository.canonical, revision) : withdrawRepository(domain, repository.canonical, revision))); - } else if (!signal.aborted && context.current() && !access) { - // An incomplete metadata check may already have refused anonymous - // access. Preserve the cached roots, but withhold them until a live - // acquisition establishes authority again. - await Promise.all([PUBLIC, privateDomain(input.principalId)].map(domain => suspendRepository(domain, repository.canonical, revision))); - } + await containFailure(error, false); if (error instanceof ReferenceTransportError) throw new ReferenceSourceError(error.reason === "denied" ? "unauthorized" : error.reason, error.message); throw error; } finally { try { await access?.close(); } finally { done(); } } @@ -659,7 +658,7 @@ export function createReferenceSources(options: { } catch (error) { const held = result; held?.release(); - if (held && !controller.signal.aborted && error instanceof ReferenceSourceError && error.code === "unauthorized") await withdraw(operation.domain, repository.canonical, revision); + if (held) await containFailure(error, false); throw error; } finally { operations.delete(id); void settle(...splitKey(operation.key)).catch(error => warn("managed source settle failed", error)); } @@ -717,6 +716,7 @@ export function createReferenceSources(options: { const pending = [...pendingPublications].filter(([, publication]) => publication.key === key); if ((!source?.root_id && !roots.length && !pending.length) || (suspended.has(key) && !unsettled.has(key) && !pending.length)) return; suspended.add(key); unsettled.add(key); + await write("sourceSuspend", domain, repository, revision); if (source) await pool.poolUnpublish((await viewFor(domain)).id, source.name); for (const root of roots) await hideRoot(root.id); for (const [id, publication] of pending) { diff --git a/packages/ui-server/src/db/reference-grants.ts b/packages/ui-server/src/db/reference-grants.ts index 72b5d13c6a..ce44505ffd 100644 --- a/packages/ui-server/src/db/reference-grants.ts +++ b/packages/ui-server/src/db/reference-grants.ts @@ -68,6 +68,7 @@ export function referenceRepository(input: unknown, options: { prefix?: boolean if (segments.some(segment => !segment || segment === "." || segment === "..")) throw new ReferenceRepositoryError("repository path must not contain empty, '.' or '..' segments"); if (!segments.length && (scheme === "file" || !options.prefix)) throw new ReferenceRepositoryError("repository must name a path"); + if (url.origin === GITHUB) for (let index = 0; index < segments.length; index++) segments[index] = segments[index]!.toLowerCase(); const origin = scheme === "file" ? "file://" : url.origin; const location = `${origin}${segments.length ? "/" + segments.join("/") : ""}`; // A hosted `.git` suffix names the same repository; a local path keeps it. @@ -78,6 +79,10 @@ export function referenceRepository(input: unknown, options: { prefix?: boolean /** Exact match or a path-segment boundary: `…/odysseus` never covers `…/odysseus-crew`. */ export const coversRepository = (prefix: string, repository: string) => repository === prefix || repository.startsWith(`${prefix}/`); +function storedPrefix(input: string): string | null { + try { return referenceRepository(input, { prefix: true }).canonical; } catch { return null; } +} + /** Refuse a credential name outside the fixed list, or one whose recipient is not this prefix's origin. */ export function assertGrantCredential(credential: string | null, prefix: ReferenceRepository): void { if (credential === null) return; @@ -140,8 +145,9 @@ export function createReferenceGrant(db: Database, input: { db.prepare("DELETE FROM reference_grants WHERE revoked_at IS NOT NULL AND revoked_at < ?").run(input.now - REFERENCE_GRANT_RETENTION_MS); const live = db.prepare(`SELECT COUNT(*) AS count FROM reference_grants g JOIN principals p ON p.id = g.principal_id WHERE ${LIVE}`).get(input.now) as { count: number }; if (live.count >= MAX_LIVE_REFERENCE_GRANTS) throw new ReferenceGrantLimitError(); - if (db.prepare(`SELECT 1 FROM reference_grants g WHERE g.revoked_at IS NULL AND g.brain = ? AND g.principal_id = ? AND g.repository_prefix = ? AND g.credential IS ?`) - .get(grant.brain, grant.principalId, grant.repositoryPrefix, grant.credential)) throw new ReferenceGrantDuplicateError(); + const duplicates = db.prepare(`SELECT repository_prefix FROM reference_grants g WHERE g.revoked_at IS NULL AND g.brain = ? AND g.principal_id = ? AND g.credential IS ?`) + .all(grant.brain, grant.principalId, grant.credential) as { repository_prefix: string }[]; + if (duplicates.some(row => storedPrefix(row.repository_prefix) === grant.repositoryPrefix)) throw new ReferenceGrantDuplicateError(); db.prepare(`INSERT INTO reference_grants (id, brain, principal_id, repository_prefix, credential, created_by, created_at, metadata_credential_recipient) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`) .run(grant.id, grant.brain, grant.principalId, grant.repositoryPrefix, grant.credential, grant.createdBy, grant.createdAt, metadataRecipient); }).immediate(); @@ -168,9 +174,14 @@ export function revokeReferenceGrant(db: Database, input: { brain: string; princ */ export function coveringReferenceGrant(db: Database, input: { brain: string; principalId: string; repository: ReferenceRepository; now: number }): ReferenceGrant | null { const rows = db.prepare(`SELECT ${COLUMNS} FROM reference_grants g JOIN principals p ON p.id = g.principal_id - WHERE ${LIVE} AND g.brain = ? AND g.principal_id = ? ORDER BY length(g.repository_prefix) DESC, g.created_at DESC, g.id ASC`) + WHERE ${LIVE} AND g.brain = ? AND g.principal_id = ? ORDER BY g.created_at DESC, g.id ASC`) .all(input.now, input.brain, input.principalId) as GrantRow[]; - const row = rows.find(candidate => coversRepository(candidate.repository_prefix, input.repository.canonical)); + const repository = referenceRepository(input.repository.url, { prefix: true }).canonical; + const matches = rows.flatMap(row => { + const prefix = storedPrefix(row.repository_prefix); + return prefix !== null && coversRepository(prefix, repository) ? [{ row, prefix }] : []; + }).sort((a, b) => b.prefix.length - a.prefix.length); + const row = matches[0]?.row; return row ? fromRow(row) : null; } diff --git a/packages/ui-server/tests/reference-grants.test.ts b/packages/ui-server/tests/reference-grants.test.ts index 9ddad3bae3..b03ea0f678 100644 --- a/packages/ui-server/tests/reference-grants.test.ts +++ b/packages/ui-server/tests/reference-grants.test.ts @@ -57,6 +57,38 @@ describe("reference repository locations", () => { }); describe("reference grant records", () => { + test("GitHub grant prefixes normalize case while other repository paths stay exact", () => { + const penelope = owner(); + const github = grant(penelope.id, penelope.id, "https://github.com/Odysseus/Ithaca.GIT", "GITHUB_TOKEN"); + expect(github.repositoryPrefix, "GITHUB_GRANT_PREFIX_CANONICAL_CASE").toBe("https://github.com/odysseus/ithaca"); + expect(covering(penelope.id, "https://github.com/ODYSSEUS/ITHACA")?.id).toBe(github.id); + expect(covering(penelope.id, "https://github.com/odysseus/ithaca-crew")).toBeNull(); + const local = grant(penelope.id, penelope.id, "file:///srv/fixtures/Ithaca"); + expect(covering(penelope.id, "file:///srv/fixtures/Ithaca/records")?.id).toBe(local.id); + expect(covering(penelope.id, "file:///srv/fixtures/ithaca/records"), "FILE_GRANT_PATH_CASE_REMAINS_SIGNIFICANT").toBeNull(); + const other = grant(penelope.id, penelope.id, "https://forge.example/Odysseus"); + expect(covering(penelope.id, "https://forge.example/odysseus/ithaca"), "OTHER_HOST_GRANT_PATH_CASE_REMAINS_SIGNIFICANT").toBeNull(); + expect(covering(penelope.id, "https://forge.example/Odysseus/ithaca")?.id).toBe(other.id); + }); + + test("retained GitHub prefix aliases match and cannot create duplicate live grants", () => { + const penelope = owner(), existing = grant(penelope.id, penelope.id, "https://github.com/odysseus/ithaca", "GITHUB_TOKEN"); + db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run("https://github.com/Odysseus/Ithaca.GIT", existing.id); + expect(covering(penelope.id, "https://github.com/odysseus/ithaca")?.id, "RETAINED_GITHUB_PREFIX_ALIAS_MATCHES").toBe(existing.id); + expect(() => grant(penelope.id, penelope.id, "https://github.com/ODYSSEUS/ITHACA", "GITHUB_TOKEN"), "RETAINED_GITHUB_ALIAS_PREVENTS_DUPLICATE_GRANTS").toThrow("identical live reference grant"); + }); + + test("normalized prefix length preserves the narrower API permission boundary", () => { + const penelope = owner(), narrow = grant(penelope.id, penelope.id, "https://github.com/odysseus/x", "GITHUB_TOKEN"); + const broad = createReferenceGrant(db, { brain: BRAIN, principalId: penelope.id, createdBy: penelope.id, + repositoryPrefix: "https://github.com/odysseus", credential: "GITHUB_TOKEN", now: narrow.createdAt + 1, + metadataCredentialRecipient: "https://api.github.com" }); + db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run("https://github.com/Odysseus.GIT", broad.id); + const selected = covering(penelope.id, "https://github.com/odysseus/x"); + expect(selected?.id, "NORMALIZED_LONGEST_PREFIX_RETAINS_PERMISSION_BOUNDARY").toBe(narrow.id); + expect(selected?.metadataCredentialRecipient).toBeUndefined(); + }); + test("a live covering grant authorizes only its own brain, principal and path-segment prefix", () => { const penelope = owner(), telemachus = agent(penelope.id); const record = grant(telemachus.id, penelope.id, "https://github.com/odysseus", "BRAIN_UI_SYNC_GITHUB_TOKEN"); @@ -179,7 +211,7 @@ describe("owner-only reference grant routes", () => { test("an owner creates, lists and revokes a principal's grants", async () => { const penelope = owner(), telemachus = agent(penelope.id), header = await cookie(penelope.id), instance = app(); const created = await instance.request(`/api/auth/principals/${telemachus.id}/reference-grants`, json("POST", header, - { repositoryPrefix: "https://github.com/odysseus/ithaca.git", credential: "BRAIN_UI_SYNC_GITHUB_TOKEN" })); + { repositoryPrefix: "https://github.com/Odysseus/Ithaca.GIT", credential: "BRAIN_UI_SYNC_GITHUB_TOKEN" })); expect(created.status).toBe(201); const body = await created.json() as { id: string }; expect(body).toMatchObject({ principal_id: telemachus.id, repository_prefix: "https://github.com/odysseus/ithaca", credential: "BRAIN_UI_SYNC_GITHUB_TOKEN", created_by: penelope.id }); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 972cbcf34c..2518df30c0 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -56,7 +56,7 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { const github = access(); const sourceOptions = { db, pool, transport, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, github, now: () => state.clock }; const sources = createReferenceSources(sourceOptions); - const grant = () => createReferenceGrant(db, { brain, principalId: owner.id, createdBy: owner.id, repositoryPrefix: repository, + const grant = (repositoryPrefix = repository) => createReferenceGrant(db, { brain, principalId: owner.id, createdBy: owner.id, repositoryPrefix, credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); const request = (principalId = owner.id, turnId = "odysseus-turn", proxy = egress) => { const input = { repository, revision: "main", principalId, acquisition: { turnId, egress: proxy, current: () => state.current } }; @@ -271,6 +271,86 @@ for (const wait of ["coverage", "native-grant"] as const) } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } }); describe("live managed authority", () => { + test("older failed publication cleanup cannot unpublish a newly validated source", async () => { + const f = await fixture(), releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(); + let held: Awaited> | undefined, current: typeof held, failedId = "", failed = false, pending: Promise | undefined; + const publish = f.pool.poolPublish, release = f.pool.poolRelease; + try { + held = await f.request(); + const nextCommit = "c".repeat(40), fetch = f.transport.fetch; + f.transport.resolve = async () => ({ ok: true, commit: nextCommit, ref: "refs/heads/main" }); + f.transport.fetch = async input => { await fetch(input); return { commit: nextCommit }; }; + f.pool.poolPublish = async (...args) => { const result = await publish(...args); if (!failed) { failed = true; failedId = args[0]; f.state.current = false; } return result; }; + f.pool.poolRelease = async (...args) => { if (args[0] === failedId) { releaseStarted.resolve(); await resumeRelease.promise; } return release(...args); }; + pending = f.request().then(lease => { lease.release(); return null; }, error => error); + await releaseStarted.promise; + current = await f.sources.request({ principalId: f.owner.id, repository, revision: "main", acquisition: { turnId: "odysseus-new-valid-source", egress: f.secondEgress, current: () => true } }); + expect(readFileSync(join(current.viewPath, current.name, "README.md"), "utf8")).toContain("Odysseus"); + resumeRelease.resolve(); expect(await pending).toBeInstanceOf(Error); + expect(existsSync(join(current.viewPath, current.name, "README.md")), "OLDER_FAILED_PUBLICATION_CANNOT_UNPUBLISH_NEW_VALID_SOURCE").toBe(true); + } finally { resumeRelease.resolve(); await pending; current?.release(); held?.release(); await f.close(); } + }); + + for (const prefix of ["https://github.com/Odysseus", "https://github.com/Odysseus/Ithaca.GIT"]) + for (const retained of [false, true]) + test(`a ${retained ? "retained" : "new"} mixed-case GitHub grant covers ${prefix}`, async () => { + const f = await fixture({ private: true }), issued = f.grant(prefix); + try { + if (retained) f.db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run(prefix, issued.id); + expect(f.sources.covers({ principalId: f.owner.id, repository }), "MIXED_CASE_GITHUB_GRANT_COVERS_TRANSPORT_IDENTITY").toBe(true); + const lease = await f.request(); + try { expect(lease.domain).toBe("private"); expect(readFileSync(join(lease.viewPath, lease.name, "README.md"), "utf8")).toContain("Odysseus"); } + finally { lease.release(); } + expect(f.sources.covers({ principalId: f.owner.id, repository: "https://github.com/odysseus-crew/ithaca" })).toBe(false); + } finally { await f.close(); } + }); + + for (const managed of [true, false]) + test(`${managed ? "managed" : "legacy"} publication authority loss hides files before staging release`, async () => { + const f = await fixture({ private: true }), issued = f.grant(), releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(); + if (!managed) f.transport.resolve = async input => input.token ? { ok: true, commit, ref: "refs/heads/main" } : { ok: false, reason: "denied", detail: "A live private grant is required." }; + const sources = managed ? f.sources : createReferenceSources({ ...f.sourceOptions, github: undefined }); + const publish = f.pool.poolPublish, release = f.pool.poolRelease; + let path = ""; + f.pool.poolPublish = async (...args) => { const result = await publish(...args); path = join(result.path!, "README.md"); revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); return result; }; + f.pool.poolRelease = async (...args) => { releaseStarted.resolve(); await resumeRelease.promise; return release(...args); }; + const pending = sources.request({ principalId: f.owner.id, repository, revision: "main", acquisition: { turnId: "odysseus-post-publication-denial", egress: f.egress, current: () => f.state.current } }).then(lease => { lease.release(); return null; }, error => error); + try { + await releaseStarted.promise; + expect(existsSync(path), "PUBLICATION_DENIAL_HIDES_ROOT_BEFORE_STORAGE_CLEANUP").toBe(false); + resumeRelease.resolve(); expect(await pending).toMatchObject({ code: "unauthorized" }); + } finally { resumeRelease.resolve(); await pending; if (!managed) await sources.close(); await f.close(); } + }); + + for (const final of [false, true]) + test(`suspension from ${final ? "final" : "initial"} incomplete metadata survives restart`, async () => { + const f = await fixture({ worker: final }); let held: Awaited> | undefined, restarted: typeof f.sources | undefined; + try { + held = await f.request(); held.release(); + f.state.invalidAt = f.metadata.length + (final ? 2 : 1); + await expect(f.request()).rejects.toThrow(); + expect(existsSync(join(held.viewPath, held.name, "README.md"))).toBe(false); + await f.sources.close(); restarted = f.restart(f.db); await restarted.recover(); + const count = f.metadata.length, views = await restarted.bindable(f.other.id); + expect(existsSync(join(views.public, held.name, "README.md")), "RESTART_CANNOT_REEXPOSE_UNCERTAIN_SOURCE_AUTHORITY").toBe(false); + expect(f.metadata.length, "RESTART_BIND_DOES_NOT_BORROW_NETWORK_BUDGET").toBe(count); + f.state.invalidAt = 0; + const restored = await restarted.request({ principalId: f.owner.id, repository, revision: "main", acquisition: { turnId: "odysseus-restarted-validation", egress: f.egress, current: () => f.state.current } }); + try { expect(readFileSync(join(restored.viewPath, restored.name, "README.md"), "utf8")).toContain("Odysseus"); } finally { restored.release(); } + } finally { held?.release(); await restarted?.close(); await f.close(); } + }); + + test("a request without network allowance cannot invalidate another turn's cached authority", async () => { + const f = await fixture(), remaining = f.secondEgress.remainingBytes; let held: Awaited> | undefined; + try { + held = await f.request(); const observations = f.metadata.length; + f.secondEgress.remainingBytes = () => 0; + await expect(f.request(f.other.id, "odysseus-budget-refusal", f.secondEgress)).rejects.toMatchObject({ code: "capacity" }); + expect(f.metadata.length).toBe(observations); + expect(existsSync(join(held.viewPath, held.name, "README.md")), "BUDGET_REFUSAL_IS_NOT_A_REPOSITORY_AUTHORITY_OBSERVATION").toBe(true); + } finally { f.secondEgress.remainingBytes = remaining; held?.release(); await f.close(); } + }); + test("a malformed refresh hides the previous source before staging cleanup or turn cancellation", async () => { const f = await fixture(), releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(), release = f.pool.poolRelease; let held: Awaited> | undefined, request: Promise | undefined; From b2a9b5e816124858447c0f8977c219e0c46a78f9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 05:19:00 +0000 Subject: [PATCH 12/27] fix(ui-server): withdraw anonymous cache before private metadata retry --- docs/decisions/managed-worktrees.md | 8 ++-- .../decisions/reference-source-acquisition.md | 12 ++++-- .../src/brain/github-reference-access.ts | 18 ++++++-- .../ui-server/src/brain/reference-source.ts | 7 +-- .../tests/reference-source-managed.test.ts | 43 ++++++++++++++++--- 5 files changed, 68 insertions(+), 20 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index d20147a920..9cc1e366e7 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -223,7 +223,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:981-1012`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:982-1013`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -266,7 +266,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:785-823`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:786-824`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -280,7 +280,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:711-728`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:712-729`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -299,7 +299,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:829-838`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:830-839`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 264bb5a0dc..ff15f4352d 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -101,7 +101,11 @@ default to five minutes and are configured separately Suspension also expires the stored validation clock, so restart cannot republish uncertain authority into a newly bound view without fresh validation. Post-publication authority loss hides native exposure before - storage cleanup begins. Managed failure containment runs once per request; + storage cleanup begins. Anonymous identity refusal withdraws public exposure + before any credentialed retry, so cancellation during the retry cannot retain + the refused public copy. Initial metadata failures are captured before wire + shutdown, just as final metadata failures are. + Managed failure containment runs once per request; its later cleanup cannot unpublish a newer validated source. Refusal before any metadata attempt, such as exhausted turn allowance, does not invalidate another turn's cached authority. @@ -142,7 +146,7 @@ reclamation is observed. ## Fixed GitHub wire and identity authority (#3613) The concrete access owner (`createGitHubReferenceAccess`, -`packages/ui-server/src/brain/github-reference-access.ts:19-141`) uses the +`packages/ui-server/src/brain/github-reference-access.ts:19-151`) uses the fixed transport (`createGitHubReferenceWire`, `packages/ui-server/src/brain/github-reference-wire.ts:19-254`). @@ -249,14 +253,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:883-908`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:884-909`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:911-955`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:912-956`). ## Evidence diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 301af9ff84..7d2a68f22f 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -9,7 +9,7 @@ import { referenceRevision, ReferenceTransportError, type ReferenceCheck, type R type WireOptions = Parameters[0]; type RequestBounds = Pick & { current?: () => boolean }; -/** A failed final identity observation makes existing cache authority uncertain too. */ +/** A failed identity observation makes existing cache authority uncertain too. */ export class GitHubReferenceMetadataError extends ReferenceTransportError { constructor(error: unknown) { super(error instanceof ReferenceTransportError ? error.reason : "unavailable", error instanceof Error ? error.message : "GitHub repository identity is unavailable"); @@ -49,7 +49,9 @@ export function createGitHubReferenceAccess(options: { }, /** Open one host-only budget; anonymous metadata always precedes any permitted private retry. */ - async open(input: RequestBounds & { principalId: string; repository: unknown; revision: unknown }) { + async open(input: RequestBounds & { principalId: string; repository: unknown; revision: unknown; + /** The source host must hide prior public exposure before a credentialed retry can await. */ + withdrawPublic?: () => Promise }) { const location = githubReferenceRepository(input.repository), repository = referenceRepository(location.cloneUrl); const revision = referenceRevision(input.revision); principal(input.principalId); @@ -69,10 +71,12 @@ export function createGitHubReferenceAccess(options: { } else if (credentialed) throw new ReferenceTransportError("denied", "anonymous acquisition cannot dispatch a credential"); }; const wire = await createGitHubReferenceWire({ ...input, repository: location.canonical, ...options.wireTransport, authorize }); + let openingMetadata = true; try { let result = await wire.metadata(null); - principal(input.principalId); if (result.status === 401 || result.status === 404) { + await input.withdrawPublic?.(); + principal(input.principalId); grant = coveringReferenceGrant(options.db, { brain: options.brain, principalId: input.principalId, repository, now: now() }); if (!grant?.credential || grant.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) throw new ReferenceTransportError("denied", "private identity needs a live reference grant and explicit API credential permission"); @@ -85,6 +89,7 @@ export function createGitHubReferenceAccess(options: { if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable"); const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.canonical, result.value); if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); + openingMetadata = false; const assertCurrent = () => { wire.signal.throwIfAborted(); authorize("git", credential !== null); authorize("metadata", credential !== null); @@ -136,7 +141,12 @@ export function createGitHubReferenceAccess(options: { }, close: () => wire.close(), }); - } catch (error) { await wire.close(); throw error; } + } catch (error) { + // Retain an observed metadata failure before shutdown can outlive its turn. + const failure = openingMetadata && !input.signal?.aborted && (!input.current || input.current()) + ? new GitHubReferenceMetadataError(error) : error; + await wire.close(); throw failure; + } }, }; } diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 030c7501fa..a8637fad3f 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -130,8 +130,8 @@ export function createReferenceSources(options: { * it was not renewed (#2432). Their roots stay charged and cached; the next * request that validates them publishes them again. `unsettled` holds those * whose suspension did not finish: a bind retries it and refuses until it - * does. In memory only: startup recovery republishes every source, and the - * next bind suspends again. + * does. Suspension also expires durable validation, so a new service's + * bind preparation withholds uncertain authority before exposing its view. */ const suspended = new Set(), unsettled = new Set(); /** Root identities already moved out of their view: superseded, withdrawn or suspended. */ @@ -594,7 +594,8 @@ export function createReferenceSources(options: { if (maxBytes < 1) throw new ReferenceSourceError("capacity", "The acquiring turn has no network allowance left."); openAttempted = true; access = await options.github!.open({ principalId: input.principalId, repository: repository.url, revision, egress: context.egress, maxBytes, signal, - current: () => !closed && context.current() }); + current: () => !closed && context.current(), + withdrawPublic: async () => { await withdrawRepository(PUBLIC, repository.canonical, revision); } }); accessOpened = true; const currentAccess = access; const assertCurrent = () => { diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 2518df30c0..b57ef95509 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -30,13 +30,14 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { if (writer) registerReferenceWrites(db, writer); const credentials: Record = { GITHUB_TOKEN: "odysseus-fixture-token" }; const metadata: string[] = [], git: unknown[] = []; - const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200, invalidAt: 0, invalidJsonAt: 0 }; + const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200, invalidAt: 0, invalidJsonAt: 0, endOnPrivateMetadata: false }; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { metadata.push(request.headers.get("authorization") ?? "anonymous"); if (metadata.length === state.invalidJsonAt) return new Response("{", { headers: { "content-type": "application/json" } }); if (metadata.length === state.invalidAt) return Response.json({ id: "invalid" }); if (state.status !== 200) return new Response(null, { status: state.status }); if (state.private && !request.headers.has("authorization")) return new Response(null, { status: 404 }); + if (state.endOnPrivateMetadata && request.headers.has("authorization")) state.current = false; return Response.json({ id: 101, owner: { id: state.ownerId, login: "Odysseus" }, name: "Ithaca", full_name: "Odysseus/Ithaca", clone_url: `${repository}.git`, url: "https://api.github.com/repos/odysseus/ithaca", private: state.private }); } }); @@ -271,6 +272,35 @@ for (const wait of ["coverage", "native-grant"] as const) } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } }); describe("live managed authority", () => { + test("anonymous public refusal is fenced before a private retry ends its turn", async () => { + const f = await fixture(); let held: Awaited> | undefined; + try { + held = await f.request(); expect(readFileSync(join(held.viewPath, held.name, "README.md"), "utf8")).toContain("Odysseus"); + f.state.private = true; f.grant(); f.state.endOnPrivateMetadata = true; + await expect(f.request()).rejects.toThrow(); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, held.name, "README.md")), "PRIVATE_RETRY_TURN_END_CANNOT_UNDO_ANONYMOUS_REFUSAL").toBe(false); + expect(existsSync(join(views.public, held.rootId, "README.md")), "ANONYMOUS_REFUSAL_REMOVES_PUBLIC_ROOT_IDENTITY").toBe(false); + } finally { held?.release(); await f.close(); } + }); + + for (const malformed of ["schema", "json"] as const) + test(`initial ${malformed} metadata failure survives a turn ending during access shutdown`, async () => { + const f = await fixture(); let held: Awaited> | undefined; + try { + held = await f.request(); + expect(readFileSync(join(held.viewPath, held.name, "README.md"), "utf8")).toContain("Odysseus"); + if (malformed === "schema") f.state.invalidAt = f.metadata.length + 1; + else f.state.invalidJsonAt = f.metadata.length + 1; + const open = f.github.open; + f.github.open = async input => { try { return await open(input); } finally { f.state.current = false; } }; + await expect(f.request()).rejects.toThrow(); + const views = await f.sources.bindable(f.other.id); + expect(existsSync(join(views.public, held.name, "README.md")), "INITIAL_METADATA_FAILURE_SURVIVES_ACCESS_SHUTDOWN").toBe(false); + expect(existsSync(join(views.public, held.rootId, "README.md")), "INITIAL_METADATA_FAILURE_HIDES_ROOT_IDENTITY").toBe(false); + } finally { held?.release(); await f.close(); } + }); + test("older failed publication cleanup cannot unpublish a newly validated source", async () => { const f = await fixture(), releaseStarted = Promise.withResolvers(), resumeRelease = Promise.withResolvers(); let held: Awaited> | undefined, current: typeof held, failedId = "", failed = false, pending: Promise | undefined; @@ -463,7 +493,7 @@ describe("live managed authority", () => { let later: Promise<{ lease: Awaited> | undefined; error: unknown }> | undefined; try { await arrived.promise; expect(readFileSync(path, "utf8")).toContain("Odysseus"); - f.state.private = true; f.grant(); f.credentials.GITHUB_TOKEN = undefined; + f.state.invalidAt = f.metadata.length + 1; f.github.open = async input => { try { return await open(input); } finally { observed.resolve(); } }; later = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); await observed.promise; await new Promise(resolve => setImmediate(resolve)); @@ -554,11 +584,14 @@ describe("live managed authority", () => { f.state.private = true; if (outcome !== "denied") f.grant(); if (outcome === "unavailable") f.credentials.GITHUB_TOKEN = undefined; - f.github.open = async input => { try { return await open(input); } finally { observed.resolve(); } }; + f.github.open = async input => { + try { return await open({ ...input, withdrawPublic: async () => { observed.resolve(); await input.withdrawPublic?.(); } }); } + finally { observed.resolve(); } + }; const later = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); await observed.promise; - // Let the source service process the completed metadata result before - // the older native reply arrives; no wall-clock race or external I/O. + // The public withdrawal has started before the older native reply + // arrives; no wall-clock race or external I/O. await new Promise(resolve => setImmediate(resolve)); resume.resolve(); const old = await earlier, current = await later; From c05109931bafe466be49db9b6a746d1fc0588e2f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 05:37:46 +0000 Subject: [PATCH 13/27] fix(ui-server): retain source authority across worktree waits --- docs/decisions/managed-worktrees.md | 35 +++++---- .../decisions/reference-source-acquisition.md | 22 +++--- .../src/brain/github-reference-access.ts | 7 +- .../ui-server/src/brain/reference-source.ts | 19 ++++- .../src/brain/reference-worktrees.ts | 13 +++- .../tests/reference-source-managed.test.ts | 78 ++++++++++++++++++- 6 files changed, 140 insertions(+), 34 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 9cc1e366e7..d414e371a6 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -7,7 +7,7 @@ commit. It builds on the [acquisition service](reference-source-acquisition.md) and the pool's [checkpoints and access generations](reference-pool-accounting.md#worktree-checkpoints-and-access-generations-2430). This record names the concrete choices the rulings left to implementation. The service is `createReferenceWorktrees` -(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:151-711`), +(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:152-712`), created with the acquisition service. The agent tools that call it arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) ([agent tools](#agent-tools)). Hygiene findings, review and cleanup arrived with [#2431](https://github.com/schlessera/brain-kit/issues/2431) @@ -19,7 +19,7 @@ A request names the principal, a repository and a branch or tag, like a source request. The service asks the acquisition service for that source, so its authority, freshness and private boundary all apply, and then snapshots the sealed source root it was given -(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:445-477`). +(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:452-484`). The worktree's starting commit is the commit that source reported, and it never moves with the source. A read-only baseline checkpoint is taken at once. Each worktree gets the pool's per-operation allowance. A worktree belongs to one @@ -32,8 +32,13 @@ startup recovery keep that root: a snapshot keeps its source's extents and owner charge, so releasing the source would free nothing. The acquiring turn and live private grant are checked after pool and database -waits. Authority lost during allocation discards its roots and record, including -when the activation write completed before the final authority check. +waits. The host source lease also retains a live authority check after its wire +closes: newer withdrawal or suspension, validation expiry, principal or selected +private grant/credential loss invalidates waiting allocation and access. An +originally public worktree cannot finish a wait using authority that a newer +metadata observation refused. Authority lost during allocation discards its +roots and record, including when the activation write completed before the +final authority check; an access that dispatched is parked and its holder cleared. ## Worker generations and access @@ -43,7 +48,7 @@ restricted (autonomous) turn holds no worktree. The generation records the owning process (PID, start time, boot and PID namespace). Access makes a worktree available to one open generation -(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:542-552`): +(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:549-559`): 1. The generation must be open in this process for a running turn, and belong to the requesting principal. @@ -85,10 +90,10 @@ own generation and its turn no longer runs; that record is process-wide, so every service instance in the process reads the same evidence. Closing a service ends the registration of the generations it opened. Any other case, such as an owner in another PID namespace, is **unknown** -(`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:206-212`). +(`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:207-213`). Reconciliation runs at startup and when a generation closes, never on a timer -(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:629-656`). +(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:636-663`). After three days without explicit activity, a worktree expires: - with a live holder it stays `active` and held, however long the turn runs; @@ -173,7 +178,7 @@ arrive only in the results that grant access. ## Cleanup eligibility facts Release and expiry record durable facts for hygiene review -(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:250-293`): +(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:251-294`): the reason, the holder (`none`, `live` or `unknown`) and whether work remains (`none`, `unpreserved` or `unknown`). Work is read from a fresh read-only checkpoint and a metadata delta against the baseline. Nothing of the worktree @@ -223,7 +228,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:982-1013`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:995-1026`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -266,7 +271,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:786-824`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:799-837`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -280,7 +285,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:712-729`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:725-742`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -299,7 +304,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:830-839`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:843-852`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a @@ -431,7 +436,7 @@ atomically with grants [pool accounting](reference-pool-accounting.md)), so a grant that lands between the last check and the release fails the removal instead of losing the grant. The worktree service is the only executor, through one effect -(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:342-379`). +(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:343-380`). Immediately before it, with no await between the last check and submission of the receipt: 1. the worktree is released or expired, and no removal of it was already @@ -467,13 +472,13 @@ without another release, which would fail or leave a tombstone identity. The lease owner holds a release's lease again when the pool never committed it (the root is still writable or sealed), so a failed removal stays assessable; it never does so over a newer release of the same identity -(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:386-421`). +(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:387-422`). Capacity is credited only when the pool reports the worktree `reclaimed`: until then its source root stays protected from eviction. **Automatic removal.** Release, expiry and the close of a holding generation remove a worktree only when its fresh assessment shows no holder and no work -(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:311-314`). +(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:312-315`). Reconciliation retries a clean worktree whose removal could not run. Nothing is archived or purged speculatively, and a worktree whose work or owner is unknown is never removed automatically. Arbitrary repositories and shared diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index ff15f4352d..b38629126b 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:96-899`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:98-901`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:316-365`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:327-376`). - Inside both windows a request reuses the published source without any network call. @@ -108,7 +108,11 @@ default to five minutes and are configured separately Managed failure containment runs once per request; its later cleanup cannot unpublish a newer validated source. Refusal before any metadata attempt, such as exhausted turn allowance, does not invalidate - another turn's cached authority. + another turn's cached authority. Host source leases retain their authority + fence, validation lifetime and acquiring principal/private grant/credential + checks after wire shutdown. Worktree allocation and access read them after + waits; a previously public snapshot cannot bypass a newer restrictive + observation. This host check grants no source trust or read provenance. - A public check that gets no answer proves nothing. Only a principal with a covering grant goes on to the private path; anyone else is refused as `unavailable`. @@ -117,7 +121,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:465-519`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:476-530`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -216,9 +220,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:256-271`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:267-282`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:274-299`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:285-310`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -240,7 +244,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:390-406`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:401-417`). There is no idle expiry. ## Revocation and recovery @@ -253,14 +257,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:884-909`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:897-922`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:912-956`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:925-969`). ## Evidence diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 7d2a68f22f..6da8e9b6fa 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -90,10 +90,11 @@ export function createGitHubReferenceAccess(options: { const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.canonical, result.value); if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); openingMetadata = false; - const assertCurrent = () => { - wire.signal.throwIfAborted(); + // Source/worktree effects outlive wire shutdown, but not this authority. + const assertAuthority = () => { authorize("git", credential !== null); authorize("metadata", credential !== null); }; + const assertCurrent = () => { wire.signal.throwIfAborted(); assertAuthority(); }; let resolved: Extract | undefined; assertCurrent(); return Object.freeze({ @@ -103,7 +104,7 @@ export function createGitHubReferenceAccess(options: { revision, signal: wire.signal, bytes: wire.bytes, - assertCurrent, + assertCurrent, assertAuthority, async resolve() { assertCurrent(); const result = await options.transport.resolve({ repository, revision, token: credential, wire, signal: wire.signal }); diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index a8637fad3f..0a4e6c2950 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -70,6 +70,8 @@ export interface ReferenceSourceLease { /** True when the latest refresh failed and the previous authorized revision is returned. */ stale: boolean; error: string | null; + /** Host-only lifetime check for effects awaiting after this acquisition; never a source trust capability. */ + assertAuthority(): void; /** Ends this reader's protection against capacity eviction. Idempotent. */ release(): void; } @@ -205,9 +207,18 @@ export function createReferenceSources(options: { Boolean(source?.root_id && source.commit_id && source.refreshed_at !== null && source.validated_at !== null); const validationLive = (source: SourceRow) => source.validated_at !== null && now() < source.validated_at + limits.validationMs; - async function lease(source: SourceRow, stale: boolean, error: string | null): Promise { + async function lease(source: SourceRow, stale: boolean, error: string | null, authority?: () => void): Promise { if (!usable(source)) throw new ReferenceSourceError("unavailable", "No usable authorized reference source exists."); const key = sourceKey(source.domain, source.repository, source.revision); + const fence = authorityFences.get(key) ?? 0; + const assertAuthority = () => { + if (closed) throw new ReferenceSourceError("unavailable", "Reference sources are closed."); + if (fence !== (authorityFences.get(key) ?? 0) || withdrawn.has(key)) + throw new ReferenceSourceError(suspended.has(key) ? "unavailable" : "unauthorized", "A newer observation invalidated this source's authority."); + if (suspended.has(key) || !validationLive(source)) + throw new ReferenceSourceError("unavailable", "This source's authority needs fresh validation."); + authority?.(); + }; leases.set(key, (leases.get(key) ?? 0) + 1); let released = false; const release = () => { @@ -222,7 +233,7 @@ export function createReferenceSources(options: { await write("sourceTouch", now(), source.domain, source.repository, source.revision); return { domain: source.domain === PUBLIC ? "public" : "private", view: view.id, viewPath: view.hostPath!, name: source.name, repository: source.repository, revision: source.revision, commit: source.commit_id, rootId: source.root_id, refreshedAt: source.refreshed_at, validatedAt: source.validated_at, stale, error, - release }; + assertAuthority, release }; } catch (error) { release(); throw error; } } @@ -636,7 +647,9 @@ export function createReferenceSources(options: { assertCurrent(); const current = row(domain, repository.canonical, revision); if (!usable(current)) throw new ReferenceSourceError("unavailable", "Managed source publication is unavailable."); - result = await restored(await lease(current, false, null), current, assertCurrent, signal); + result = await restored(await lease(current, false, null, () => { + assertTurn(); currentAccess.assertAuthority(); + }), current, assertCurrent, signal); assertCurrent(); return { kind: "source", row: current, stale: false, error: null }; } catch (error) { diff --git a/packages/ui-server/src/brain/reference-worktrees.ts b/packages/ui-server/src/brain/reference-worktrees.ts index 470abfdd09..a17b8ccc9a 100644 --- a/packages/ui-server/src/brain/reference-worktrees.ts +++ b/packages/ui-server/src/brain/reference-worktrees.ts @@ -28,6 +28,7 @@ import type { Logger } from "@opentelemetry/api-logs"; import { parseNativeBrainDelta, type createNativeBrainManagerClient, type NativePoolCheckpoint, type NativePoolRecord } from "@schlessera/brain-ui-sdk/internal"; import { processAlive, SELF } from "./writer-gate.js"; import { ReferenceSourceError, type ReferenceSources } from "./reference-source.js"; +import { ReferenceTransportError } from "./reference-transport.js"; import type { ReferenceAcquisitionContext } from "./reference-acquisition.js"; /** @@ -231,7 +232,7 @@ export function createReferenceWorktrees(options: { // A public starting snapshot cannot bypass the private authority the // current source check required. A private starting snapshot keeps its // original grant requirement even if the repository is public now. - return { ...row, domain: row.domain !== "public" || source.domain !== "public" ? "private" : "public" }; + return { ...row, domain: row.domain !== "public" || source.domain !== "public" ? "private" : "public", assertAuthority: source.assertAuthority }; } finally { source.release(); } } catch (error) { @@ -437,8 +438,14 @@ export function createReferenceWorktrees(options: { input.signal?.throwIfAborted(); if (input.acquisition && !input.acquisition.current()) throw new ReferenceWorktreeError("unavailable", "The acquiring turn is no longer available."); } - function acquiringAuthority(input: { signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }, row: Pick): void { + function acquiringAuthority(input: { signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }, row: Pick & { assertAuthority(): void }): void { acquiringTurn(input); + try { row.assertAuthority(); } + catch (error) { + if (error instanceof ReferenceSourceError) throw new ReferenceWorktreeError(error.code === "cancelled" || error.code === "busy" ? "unavailable" : error.code, error.message); + if (error instanceof ReferenceTransportError) throw new ReferenceWorktreeError(error.reason === "denied" ? "unauthorized" : "unavailable", error.message); + throw error; + } covered(row); } @@ -451,7 +458,7 @@ export function createReferenceWorktrees(options: { throw error; } const id = randomUUID(), at = now(); - const authority = { principal_id: input.principalId, domain: lease.domain, repository: lease.repository }; + const authority = { principal_id: input.principalId, domain: lease.domain, repository: lease.repository, assertAuthority: lease.assertAuthority }; try { acquiringAuthority(input, authority); const allowance = (await pool.poolStatus(input.signal)).limits.operationBytes; diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index b57ef95509..ec7ef7a336 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -8,7 +8,7 @@ import { createGitHubReferenceAccess } from "../src/brain/github-reference-acces import { createReferenceSources } from "../src/brain/reference-source"; import type { ReferenceTransport } from "../src/brain/reference-transport"; import { createUiDb } from "../src/db/client"; -import { createPrincipal } from "../src/db/principals"; +import { createPrincipal, revokePrincipal } from "../src/db/principals"; import { createReferenceGrant, revokeReferenceGrant } from "../src/db/reference-grants"; import { fixtureTls } from "./fixtures/fixture-tls"; import { referencePoolDouble } from "./helpers/reference-pool-double"; @@ -688,6 +688,82 @@ describe("live managed authority", () => { } finally { current?.release(); old?.release(); await f.close(); } }); + for (const observation of ["private", "unknown"] as const) + for (const wait of ["coverage", "native-grant", "held-refresh"] as const) + test(`a public worktree cannot outlive newer ${observation} authority during ${wait}`, async () => { + const f = await fixture(); + const context = { turnId: "odysseus-public-worktree", egress: f.egress, current: () => f.state.current }; + const invalidate = async () => { + if (observation === "private") f.state.private = true; else f.state.status = 503; + await expect(f.request(f.other.id, "telemachus-newer-authority", f.secondEgress)).rejects.toMatchObject({ code: observation === "private" ? "unauthorized" : "unavailable" }); + }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, + coverage: async () => { if (wait === "coverage") await invalidate(); } }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + if (wait === "native-grant") { + const access = f.pool.poolAccess; + f.pool.poolAccess = async (...args) => { const result = await access(...args); await invalidate(); return result; }; + } + if (wait === "held-refresh") { + await worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }); + expect(readFileSync(join(generation.path, item.id, "README.md"), "utf8")).toContain("Odysseus"); + const request = f.sources.request; + f.sources.request = async input => { const lease = await request(input); if (input.principalId === f.owner.id) await invalidate(); return lease; }; + } + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }), + "PUBLIC_WORKTREE_RECHECKS_NEWER_SOURCE_AUTHORITY").rejects.toMatchObject({ code: observation === "private" ? "unauthorized" : "unavailable" }); + expect(f.pool.records.get(item.id)!.access, "INVALIDATED_PUBLIC_WORKTREE_IS_PARKED").toBeNull(); + expect(existsSync(join(generation.path, item.id, "README.md")), "INVALIDATED_PUBLIC_WORKTREE_FILES_ARE_HIDDEN").toBe(false); + expect(worktrees.get({ worktreeId: item.id, principalId: f.owner.id }).generation, "INVALIDATED_PUBLIC_WORKTREE_HOLDER_IS_CLEARED").toBeNull(); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } + }); + + for (const authority of ["principal", "credential"] as const) + test(`worktree coverage cannot outlive its acquiring ${authority} after wire shutdown`, async () => { + const f = await fixture({ private: authority === "credential" }); if (authority === "credential") f.grant(); + const context = { turnId: "odysseus-live-worktree-authority", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => { + if (authority === "principal") revokePrincipal(f.db, f.owner.id, Date.now()); else f.credentials.GITHUB_TOKEN = undefined; + } }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }), + "WORKTREE_RETAINS_LIVE_AUTHORITY_AFTER_WIRE_SHUTDOWN").rejects.toMatchObject({ code: "unauthorized" }); + expect(f.pool.records.get(item.id)!.access, "LOST_ACQUISITION_AUTHORITY_CANNOT_MOUNT_WORKTREE").toBeNull(); + expect(existsSync(join(generation.path, item.id, "README.md")), "LOST_ACQUISITION_AUTHORITY_HIDES_WORKTREE_FILES").toBe(false); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } + }); + + for (const wait of ["native-create", "checkpoint"] as const) + test(`a public allocation cannot outlive newer private authority during ${wait}`, async () => { + const f = await fixture(); + const context = { turnId: "odysseus-public-allocation", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => {} }); + const invalidate = async () => { + f.state.private = true; + await expect(f.request(f.other.id, "telemachus-newer-authority", f.secondEgress)).rejects.toMatchObject({ code: "unauthorized" }); + }; + try { + if (wait === "native-create") { + const create = f.pool.poolCreate; + f.pool.poolCreate = async (...args) => { const result = await create(...args); if (args[1] === "worktree") await invalidate(); return result; }; + } else { + const checkpoint = f.pool.poolCheckpoint; + f.pool.poolCheckpoint = async (...args) => { const result = await checkpoint(...args); await invalidate(); return result; }; + } + await expect(worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }), + "PUBLIC_ALLOCATION_RECHECKS_NEWER_SOURCE_AUTHORITY").rejects.toMatchObject({ code: "unauthorized" }); + expect(worktrees.list(f.owner.id), "INVALIDATED_PUBLIC_ALLOCATION_IS_DISCARDED").toEqual([]); + expect([...f.pool.records.values()].filter(record => record.purpose === "worktree" && record.state !== "reclaimed"), + "INVALIDATED_PUBLIC_ALLOCATION_LEAVES_NO_ROOT").toEqual([]); + } finally { await worktrees.close(); await f.close(); } + }); + for (const initialPrivate of [true, false]) for (const wait of ["coverage", "native-grant", "grant-write", "held-refresh", "held-write"] as const) test(`a ${initialPrivate ? "private" : "public-to-private"} worktree loses mounted access when its grant is revoked during ${wait}`, async () => { From 7a91843a3ca0f2ae8285a01893e652da1730eb33 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 06:02:49 +0000 Subject: [PATCH 14/27] CONTRACT: fix(ui-server): condition failed grant cleanup on native holder --- .../managed-reference-source-authority.md | 3 +- api-report/ui-server.txt | 2 +- docs/decisions/governed-writable-workers.md | 2 +- docs/decisions/managed-worktrees.md | 12 +++++-- docs/decisions/reference-pool-accounting.md | 7 +++- docs/hosting/agent-workers.md | 2 +- docs/integration-contract/package-api.md | 9 +++++ .../src/server/native-brain-manager-client.ts | 2 +- .../server/native-brain-manager-protocol.ts | 2 +- .../ui-sdk/src/server/native-brain-manager.ts | 2 +- .../src/server/native-reference-pool.ts | 5 +-- .../ui-sdk/tests/native-brain-manager.test.ts | 18 ++++++++++ .../src/brain/native-brain-leases.ts | 4 +-- .../src/brain/reference-worktrees.ts | 17 ++++----- .../tests/helpers/reference-pool-double.ts | 3 +- .../tests/native-brain-leases.test.ts | 8 +++-- .../tests/reference-source-managed.test.ts | 35 +++++++++++++++++++ scripts/native-proof/reference-pool.native.ts | 8 +++-- 18 files changed, 113 insertions(+), 28 deletions(-) diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md index 40cca548c5..4592227db3 100644 --- a/.changeset/managed-reference-source-authority.md +++ b/.changeset/managed-reference-source-authority.md @@ -1,5 +1,6 @@ --- "@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-sdk": minor --- -Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. +Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 8ce3db8965..5d9d800dfb 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2566,7 +2566,7 @@ signatures (every public export and the types it is made of) poolDelta: (from: string, to: string, signal?: AbortSignal) => Promise; poolGrowth: (signal?: AbortSignal) => Promise; poolListCheckpoint: (id: string, path: string, expectedWorkerUid: number, signal?: AbortSignal) => Promise; - poolPark: (id: string, signal?: AbortSignal) => Promise; + poolPark: (id: string, signal?: AbortSignal, expectedAccess?: string) => Promise; poolPublish: (id: string, view: string, name: string, signal?: AbortSignal) => Promise; poolReadCheckpoint: (id: string, path: string, maximum: number, expectedWorkerUid: number, signal?: AbortSignal) => Promise; poolRelease: (id: string, signal?: AbortSignal) => Promise; diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index f5cee7c14f..b07e0ca712 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -2047,7 +2047,7 @@ fresh globals per request, with the path as its only argument, and answers with the program's output, its exit status and the traceback a fresh launch printed, without the loop's own frame. The manager turns a failure into the same refusal a failed launch produced (`async function inspection`, -`packages/ui-sdk/src/server/native-brain-manager.ts:189-193`). Every +`packages/ui-sdk/src/server/native-brain-manager.ts:215-219`). Every `qualify` and `verifyOwned` still inspects the live path on every operation; nothing is cached between requests. An interrupted, timed-out, oversized or malformed exchange, or one with an interpreter that died, kills the diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index d414e371a6..8cc034f407 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -19,7 +19,7 @@ A request names the principal, a repository and a branch or tag, like a source request. The service asks the acquisition service for that source, so its authority, freshness and private boundary all apply, and then snapshots the sealed source root it was given -(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:452-484`). +(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:456-488`). The worktree's starting commit is the commit that source reported, and it never moves with the source. A read-only baseline checkpoint is taken at once. Each worktree gets the pool's per-operation allowance. A worktree belongs to one @@ -39,6 +39,12 @@ originally public worktree cannot finish a wait using authority that a newer metadata observation refused. Authority lost during allocation discards its roots and record, including when the activation write completed before the final authority check; an access that dispatched is parked and its holder cleared. +Cleanup supplies its requesting generation to native parking. The manager +compares that expected holder under its mutation lock, so a refused or +lost-reply grant cannot park another process's live generation during its +native-grant/database-receipt gap. A native refusal still cleans a grant of +this request whose reply was lost. Database holder clearing names only the +expected generation; a mismatched native holder is retained. ## Worker generations and access @@ -48,7 +54,7 @@ restricted (autonomous) turn holds no worktree. The generation records the owning process (PID, start time, boot and PID namespace). Access makes a worktree available to one open generation -(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:549-559`): +(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:553-563`): 1. The generation must be open in this process for a running turn, and belong to the requesting principal. @@ -93,7 +99,7 @@ such as an owner in another PID namespace, is **unknown** (`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:207-213`). Reconciliation runs at startup and when a generation closes, never on a timer -(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:636-663`). +(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:637-664`). After three days without explicit activity, a worktree expires: - with a live holder it stays `active` and held, however long the turn runs; diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index 69f2ad0db6..96c63383d4 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:1095-1098`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:1096-1099`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). @@ -268,6 +268,11 @@ release's check and its delete. The worker cannot create entries in the generati directory itself. `access/` joins the mandatory worker masks. Census accepts a writable worktree only in the directory its intent records, and measurement adopts a grant or park interrupted between its rename and its record. +The optional `expectedAccess` on `poolPark(id, signal?, expectedAccess?)` +compares the manager's current native holder under its serialized mutation +lock. A different holder returns unchanged without relocation. Failed host +grant cleanup uses this precondition rather than inferring native ownership +from a database row whose receipt may still be pending (#3613). ## Background deduplication is rejected; residual growth is reported (#3515) diff --git a/docs/hosting/agent-workers.md b/docs/hosting/agent-workers.md index 3c91b7ff01..bb0e0c9bf2 100644 --- a/docs/hosting/agent-workers.md +++ b/docs/hosting/agent-workers.md @@ -1065,7 +1065,7 @@ root-owned files and connect to root-owned and abstract Unix sockets. Native storage accepts the server's fixed UID/GID, including UID 0 under this same warning (`validateNativeBrainManagerConfig`, -`packages/ui-sdk/src/server/native-brain-manager.ts:53-75`). This does not give +`packages/ui-sdk/src/server/native-brain-manager.ts:68-90`). This does not give the worker capabilities or remove its masks, filesystem filter or read-only root `/proc`. The host still has to qualify for user namespaces. Since Linux 5.12, mapping a child namespace to parent UID 0 requires `CAP_SETFCAP` at the diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index a256c6cc44..08f92df0ea 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4514,6 +4514,15 @@ writable worktree, else `null`; earlier records read as `access: null`. `poolCreate` refuses the `checkpoint` purpose and a checkpoint as its source. `poolRelease` refuses a writable worktree whose record names an access generation with `invalid`, deleting nothing; park it first (#2729). +The host client also accepts `poolPark(id, signal?, expectedAccess?)` (#3613). +With a generated `expectedAccess` UUID, the manager parks only while its native +record still names that generation, under the same mutation lock as grants. +A mismatch returns the unchanged record, including its current `access`, and +never moves the root. Omitting the argument retains unconditional parking. +This optional internal control field is additive; an older strict manager +refuses it, so failed cleanup stays explicit rather than falling back to an +unconditional park. + The lease owner checkpoints only a held worktree, reads and diffs only held checkpoints, and moves only held worktrees; its lease table migrates in place. No call accepts a host path, UID or mount. Worker masks now include the pool's diff --git a/packages/ui-sdk/src/server/native-brain-manager-client.ts b/packages/ui-sdk/src/server/native-brain-manager-client.ts index 9632283832..00f9d93519 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-client.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-client.ts @@ -315,7 +315,7 @@ export function createNativeBrainManagerClient(input: { socketPath: string; time }, poolAccessOpen: async (access: string, signal?: AbortSignal): Promise => control({ operation: "poolAccessOpen", access }, signal), poolAccess: async (id: string, access: string, signal?: AbortSignal): Promise => control({ operation: "poolAccess", id, access }, signal), - poolPark: async (id: string, signal?: AbortSignal): Promise => control({ operation: "poolPark", id }, signal), + poolPark: async (id: string, signal?: AbortSignal, expectedAccess?: string): Promise => control({ operation: "poolPark", id, ...(expectedAccess === undefined ? {} : { expectedAccess }) }, signal), poolAccessClose: async (access: string, signal?: AbortSignal): Promise => control({ operation: "poolAccessClose", access }, signal), listRecovery: async (after: string | null = null, signal?: AbortSignal): Promise<{ records: NativeRecoveryRecord[]; next: string | null }> => control({ operation: "listRecovery", after }, signal), delta: async (from: string, to: string, signal?: AbortSignal): Promise => { diff --git a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts index 90c1671f2c..a922065c61 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts @@ -60,7 +60,7 @@ export const nativeManagerRequest = z.discriminatedUnion("operation", [ }).strict(), z.object({ operation: z.literal("poolAccessOpen"), access: nativeCheckpointId }).strict(), z.object({ operation: z.literal("poolAccess"), id: nativeCheckpointId, access: nativeCheckpointId }).strict(), - z.object({ operation: z.literal("poolPark"), id: nativeCheckpointId }).strict(), + z.object({ operation: z.literal("poolPark"), id: nativeCheckpointId, expectedAccess: nativeCheckpointId.optional() }).strict(), z.object({ operation: z.literal("poolAccessClose"), access: nativeCheckpointId }).strict(), ]); export type NativeManagerRequest = z.infer; diff --git a/packages/ui-sdk/src/server/native-brain-manager.ts b/packages/ui-sdk/src/server/native-brain-manager.ts index b771cca38b..a5946cc983 100644 --- a/packages/ui-sdk/src/server/native-brain-manager.ts +++ b/packages/ui-sdk/src/server/native-brain-manager.ts @@ -503,7 +503,7 @@ export async function createNativeBrainManager(config: NativeBrainManagerConfig, if (request.operation === "poolCheckpoint") return Response.json(await pool().checkpoint(request, signal)); if (request.operation === "poolAccessOpen") return Response.json(pool().accessOpen(request.access)); if (request.operation === "poolAccess") return Response.json(await pool().grant(request, signal)); - if (request.operation === "poolPark") return Response.json(await pool().park(request.id, signal)); + if (request.operation === "poolPark") return Response.json(await pool().park(request.id, signal, request.expectedAccess)); if (request.operation === "poolAccessClose") return Response.json(await pool().accessClose(request.access, signal)); if (request.operation === "poolDelta") { const roots = await pool().deltaRoots(request.from, request.to, signal); diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index cd9b8eb59c..fc0b086c48 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -1041,10 +1041,11 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { await verifyRoot(intent, signal); return publicRecord(await relocate(intent, request.access, signal)); } - /** Return a worktree to the masked roots directory; its generation no longer reaches it by name or identity. */ - async function park(id: string, signal?: AbortSignal): Promise { + /** Return a worktree to masked roots, optionally only if its serialized native holder still matches. */ + async function park(id: string, signal?: AbortSignal, expectedAccess?: string): Promise { const intent = intents.get(id); if (!intent || intent.purpose !== "worktree") throw new NativeBrainManagerError("unknown", "Only a recorded worktree root can be parked."); + if (expectedAccess !== undefined && intent.access !== expectedAccess) return publicRecord(intent); if (!intent.access) return publicRecord(intent); await verifyRoot(intent, signal); return publicRecord(await relocate(intent, null, signal)); diff --git a/packages/ui-sdk/tests/native-brain-manager.test.ts b/packages/ui-sdk/tests/native-brain-manager.test.ts index 0e7fcb5d2f..2d2ba7f90d 100644 --- a/packages/ui-sdk/tests/native-brain-manager.test.ts +++ b/packages/ui-sdk/tests/native-brain-manager.test.ts @@ -114,6 +114,24 @@ test("Unix client sends only fixed identities and returns raw delta plus complet expect(requests).toEqual([{ operation: "delta", from: ID, to: SECOND }, { operation: "release", id: ID }]); }); +test("Unix park requests retain an optional native generation expectation", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-native-park-")), socketPath = join(root, "manager.sock"); + cleanups.push(() => rmSync(root, { recursive: true, force: true })); + const requests: NativeManagerRequest[] = []; + const service = Bun.serve({ unix: socketPath, async fetch(request) { + requests.push(nativeManagerRequest.parse(await request.json())); + return Response.json({ id: ID, access: null }); + } }); + cleanups.push(() => service.stop(true)); + const client = createNativeBrainManagerClient({ socketPath, timeoutMs: 1000, maxDeltaBytes: 64 }); + await client.poolPark(ID, undefined, SECOND); await client.poolPark(ID); + expect(requests, "NATIVE_PARK_EXPECTATION_REACHES_MANAGER").toEqual([ + { operation: "poolPark", id: ID, expectedAccess: SECOND }, { operation: "poolPark", id: ID }, + ]); + for (const expectedAccess of ["../other", "/srv/ithaca", null, 1]) + expect(nativeManagerRequest.safeParse({ operation: "poolPark", id: ID, expectedAccess }).success, "NATIVE_PARK_EXPECTATION_IS_ONE_GENERATED_IDENTITY").toBe(false); +}); + test("lost Unix response is unknown and never an inferred absence or automatic retry", async () => { const root = mkdtempSync(join(tmpdir(), "odysseus-native-lost-")), socketPath = join(root, "manager.sock"); cleanups.push(() => rmSync(root, { recursive: true, force: true })); diff --git a/packages/ui-server/src/brain/native-brain-leases.ts b/packages/ui-server/src/brain/native-brain-leases.ts index eeba7b9214..472cf52c71 100644 --- a/packages/ui-server/src/brain/native-brain-leases.ts +++ b/packages/ui-server/src/brain/native-brain-leases.ts @@ -225,9 +225,9 @@ export async function createNativeBrainLeaseManager(raw: Client, options: { if (poolRow(id)?.purpose !== "worktree" || poolRow(id)?.state !== "held") throw new NativeBrainManagerError("unknown", "Only this app's held worktree can be made accessible."); return raw.poolAccess(id, access, signal); }); }, - poolPark(id, signal) { return operation(async () => { + poolPark(id, signal, expectedAccess) { return operation(async () => { if (poolRow(id)?.purpose !== "worktree" || poolRow(id)?.state !== "held") throw new NativeBrainManagerError("unknown", "Only this app's held worktree can be parked."); - return raw.poolPark(id, signal); + return raw.poolPark(id, signal, expectedAccess); }); }, poolAccessOpen(access, signal) { return operation(() => raw.poolAccessOpen(access, signal)); }, poolAccessClose(access, signal) { return operation(() => raw.poolAccessClose(access, signal)); }, diff --git a/packages/ui-server/src/brain/reference-worktrees.ts b/packages/ui-server/src/brain/reference-worktrees.ts index a17b8ccc9a..3a21debf02 100644 --- a/packages/ui-server/src/brain/reference-worktrees.ts +++ b/packages/ui-server/src/brain/reference-worktrees.ts @@ -428,9 +428,13 @@ export function createReferenceWorktrees(options: { for (const { id } of open) await serial(id, () => settle(id, signal)); } /** Return a worktree whose holder is provably gone to the masked roots, then forget the holder. */ - async function recoverHolder(row: WorktreeRow, signal?: AbortSignal): Promise { - await pool.poolPark(row.id, signal); - await write("recoverHolder", row.id, row.holder); + async function recoverHolder(row: WorktreeRow, signal?: AbortSignal, expectedHolder = row.holder): Promise { + if (!expectedHolder) return row; + // The native grant can precede its database receipt in another process. + // Check and park under the manager's one mutation lock, never a stale read. + const parked = await pool.poolPark(row.id, signal, expectedHolder); + if (parked.access !== null) throw new ReferenceWorktreeError("busy", "Another worker generation holds this worktree; its access was retained."); + await write("recoverHolder", row.id, expectedHolder); return worktree(row.id)!; } @@ -587,17 +591,14 @@ export function createReferenceWorktrees(options: { await pool.poolAccess(row.id, target.id, input.signal); acquiringAuthority(input, authority); // A removal admitted elsewhere while the grant awaited wins: the grant is withdrawn, never recorded. - if (cleanupOf(row.id)) { - await pool.poolPark(row.id).catch(error => warn("withdrawn worktree grant was not parked", error)); - throw new ReferenceWorktreeError("released", "This worktree was released; request a new one."); - } + if (cleanupOf(row.id)) throw new ReferenceWorktreeError("released", "This worktree was released; request a new one."); } // Explicit access or resumption: the only events, with renewal, that move the clock. await write("grant", target.id, now(), row.id); acquiringAuthority(input, authority); return view(worktree(row.id)!); } catch (error) { - if (dispatched || row.holder === target.id) await recoverHolder(worktree(row.id) ?? row).catch(cleanup => warn("withdrawn managed worktree grant was not parked", cleanup)); + if (dispatched || row.holder === target.id) await recoverHolder(worktree(row.id) ?? row, undefined, target.id).catch(cleanup => warn("withdrawn managed worktree grant was not parked", cleanup)); throw error; } }); diff --git a/packages/ui-server/tests/helpers/reference-pool-double.ts b/packages/ui-server/tests/helpers/reference-pool-double.ts index 05efc36cab..af190b0947 100644 --- a/packages/ui-server/tests/helpers/reference-pool-double.ts +++ b/packages/ui-server/tests/helpers/reference-pool-double.ts @@ -166,9 +166,10 @@ export function referencePoolDouble(root: string, options: { capacityRoots?: num record!.access = generation; record!.path = location(record!); return record!; }, - async poolPark(id) { + async poolPark(id, _signal, expectedAccess) { const record = records.get(id); if (!record || record.purpose !== "worktree") fail("unknown", "Only a recorded worktree root can be parked."); + if (expectedAccess !== undefined && record!.access !== expectedAccess) return record!; if (!record!.access) return record!; note({ operation: "park", id }); renameSync(location(record!), join(roots, id)); diff --git a/packages/ui-server/tests/native-brain-leases.test.ts b/packages/ui-server/tests/native-brain-leases.test.ts index 35f8b6fb2c..d91675011c 100644 --- a/packages/ui-server/tests/native-brain-leases.test.ts +++ b/packages/ui-server/tests/native-brain-leases.test.ts @@ -226,7 +226,10 @@ test("worktree checkpoints, deltas, reads and access moves need this app's held f.native.client.poolDelta = async (from, to) => { calls.push(`delta:${from}:${to}`); return { stream: new ReadableStream(), completed: Promise.resolve({ exitCode: 0 as const, bytes: 0 }) }; }; f.native.client.poolStatCheckpoint = async id => { calls.push(`stat:${id}`); return null; }; f.native.client.poolAccess = async (id, access) => { calls.push(`access:${id}:${access}`); return record(id, "worktree", SOURCE, "writable", { access }); }; - f.native.client.poolPark = async id => { calls.push(`park:${id}`); return record(id, "worktree", SOURCE, "writable"); }; + f.native.client.poolPark = async (id, _signal, expectedAccess) => { + calls.push(`park:${id}`); + return record(id, "worktree", SOURCE, "writable", { access: expectedAccess !== undefined && expectedAccess !== ACCESS ? ACCESS : null }); + }; try { await f.owner.client.poolCreate(SOURCE, "source", null, 4096); await expectRejection(f.owner.client.poolCheckpoint(CHECKPOINT, SOURCE), "held worktree", "REFERENCE_CHECKPOINT_ONLY_OF_A_HELD_WORKTREE"); @@ -238,8 +241,9 @@ test("worktree checkpoints, deltas, reads and access moves need this app's held await f.owner.client.poolDelta(CHECKPOINT, CHECKPOINT); await f.owner.client.poolStatCheckpoint(CHECKPOINT, "", 1000); await f.owner.client.poolAccess(WORKTREE, ACCESS); + expect((await f.owner.client.poolPark(WORKTREE, undefined, CHECKPOINT)).access, "LEASE_OWNER_PRESERVES_NATIVE_PARK_PRECONDITION").toBe(ACCESS); await f.owner.client.poolPark(WORKTREE); - expect(calls).toEqual([`create:${SOURCE}`, `create:${WORKTREE}`, `checkpoint:${CHECKPOINT}`, `delta:${CHECKPOINT}:${CHECKPOINT}`, `stat:${CHECKPOINT}`, `access:${WORKTREE}:${ACCESS}`, `park:${WORKTREE}`]); + expect(calls).toEqual([`create:${SOURCE}`, `create:${WORKTREE}`, `checkpoint:${CHECKPOINT}`, `delta:${CHECKPOINT}:${CHECKPOINT}`, `stat:${CHECKPOINT}`, `access:${WORKTREE}:${ACCESS}`, `park:${WORKTREE}`, `park:${WORKTREE}`]); expect(f.state.query("SELECT state FROM native_pool_leases WHERE id=?").get(CHECKPOINT)).toEqual({ state: "held" }); } finally { await f.close(); } }); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index ec7ef7a336..46ba8f0489 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -688,6 +688,41 @@ describe("live managed authority", () => { } finally { current?.release(); old?.release(); await f.close(); } }); + for (const outcome of ["foreign-refusal", "lost-reply", "foreign-before-cleanup"] as const) + test(`failed worktree access cleans only its own native generation after ${outcome}`, async () => { + const f = await fixture(); + const context = { turnId: "odysseus-competing-worktree", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => {} }); + let first: Awaited> | undefined, other: typeof first; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + first = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + other = await worktrees.openGeneration({ principalId: f.owner.id, turnId: "odysseus-other-process", profile: "governed" }); + const access = f.pool.poolAccess, park = f.pool.poolPark; + if (outcome === "foreign-refusal") { + await access(item.id, other.id); + expect(readFileSync(join(other.path, item.id, "README.md"), "utf8")).toContain("Odysseus"); + } else { + f.pool.poolAccess = async (...args) => { await access(...args); throw Object.assign(new Error("The native reply was lost."), { code: "unavailable" }); }; + } + if (outcome === "foreign-before-cleanup") { + let changed = false; + f.pool.poolPark = async (...args) => { + if (!changed) { changed = true; await park(item.id); await access(item.id, other!.id); } + return park(...args); + }; + } + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: first.id, acquisition: context })).rejects.toMatchObject({ code: outcome === "foreign-refusal" ? "invalid" : "unavailable" }); + if (outcome === "lost-reply") { + expect(f.pool.records.get(item.id)!.access, "LOST_NATIVE_REPLY_STILL_PARKS_OWN_GRANT").toBeNull(); + expect(existsSync(join(first.path, item.id, "README.md")), "LOST_NATIVE_REPLY_HIDES_OWN_FILES").toBe(false); + } else { + expect(f.pool.records.get(item.id)!.access, "FAILED_ACCESS_CANNOT_PARK_FOREIGN_NATIVE_HOLDER").toBe(other.id); + expect(readFileSync(join(other.path, item.id, "README.md"), "utf8"), "FAILED_ACCESS_PRESERVES_OTHER_GENERATION_FILES").toContain("Odysseus"); + } + } finally { if (first) await worktrees.closeGeneration(first.id); if (other) await worktrees.closeGeneration(other.id); await worktrees.close(); await f.close(); } + }); + for (const observation of ["private", "unknown"] as const) for (const wait of ["coverage", "native-grant", "held-refresh"] as const) test(`a public worktree cannot outlive newer ${observation} authority during ${wait}`, async () => { diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index c517b0b09f..e2f45c9415 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -580,8 +580,12 @@ const shapes = await create("staging", 32 * MIB); const heldAfter = await heldCharge(); expect({ code: heldRefusal.code, state: heldRecord?.state, access: heldRecord?.access, read: await ask("read"), charged: heldAfter }, "REFERENCE_ACCESS_HELD_NOT_RELEASED").toEqual({ code: "invalid", state: "writable", access: ACCESS, read: "Telemachus returns", charged: heldBefore }); - // Parking returns the worktree to the masked roots: the next lookup misses it. - expect((await call({ operation: "poolPark", id: tree.id })).access, "REFERENCE_ACCESS_PARKED_RECORD").toBeNull(); + // Competing cleanup must compare the actual native holder atomically. + const retained = await call({ operation: "poolPark", id: tree.id, expectedAccess: SECOND_ACCESS }); + expect(retained.access, "REFERENCE_ACCESS_FOREIGN_CLEANUP_RETAINS_NATIVE_HOLDER").toBe(ACCESS); + expect(await ask("read"), "REFERENCE_ACCESS_FOREIGN_CLEANUP_RETAINS_WORKER_READ").toBe("Telemachus returns"); + // Parking our own grant returns it to masked roots: the next lookup misses it. + expect((await call({ operation: "poolPark", id: tree.id, expectedAccess: ACCESS })).access, "REFERENCE_ACCESS_PARKED_RECORD").toBeNull(); expect(await ask("read"), "REFERENCE_ACCESS_PARKED_GONE").toBe("MISSING"); // A grant interrupted after its rename, before its record: restart adopts the actual generation. renameSync(join(POOL, "roots", tree.id), join(opened.path, tree.id)); From 47e56883482cbbc75bc79de09896f3c80f3a4449 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 06:32:13 +0000 Subject: [PATCH 15/27] fix(ui-server): recheck source authority after wire shutdown --- docs/decisions/managed-worktrees.md | 8 +-- .../decisions/reference-source-acquisition.md | 11 ++-- .../ui-server/src/brain/reference-source.ts | 24 ++++++--- .../tests/reference-source-managed.test.ts | 52 +++++++++++++++++++ 4 files changed, 80 insertions(+), 15 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 8cc034f407..3c57ba058d 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:995-1026`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1005-1036`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:799-837`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:809-847`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:725-742`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:734-751`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:843-852`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:853-862`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index b38629126b..2f41069122 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -81,8 +81,11 @@ default to five minutes and are configured separately A successful private metadata check also withdraws the prior public copy. An incomplete metadata check withholds cached roots until acquisition can establish authority again. Private metadata responses of 401, 403 or 404 - are authority refusals; the selected private grant is checked once more - after the acquisition wire finishes shutting down. + are authority refusals. The retained lease guard is checked after wire + shutdown, including validation lifetime, principal, selected grant, + credential and API-recipient permission. A failed close also checks and + contains authority loss. Shutdown expiry withholds the expired source under + its exposure lock, while a newer successful validation stays exposed. Repository metadata fences every cached and in-flight revision of that repository. Older requests cannot publish or restore public state after a newer private or refused observation, even before the first catalog row @@ -257,14 +260,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:897-922`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:907-932`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:925-969`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:935-979`). ## Evidence diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 0a4e6c2950..7afb492950 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -588,6 +588,10 @@ export function createReferenceSources(options: { } else if (!signal.aborted && context.current() && (reason === "denied" || reason === "unauthorized" || reason === "missing")) { work = Promise.all(domains.map(domain => reason === "missing" ? withdraw(domain, repository.canonical, revision) : withdrawRepository(domain, repository.canonical, revision))); + } else if (result && reason === "unavailable") { + // Wire shutdown may outlive the lease's validation. A newer live + // validation wins when this expiry cleanup reaches the exposure lock. + work = suspendSource(operation.domain, repository.canonical, revision, true); } else if (publishing) { work = withdraw(operation.domain, repository.canonical, revision); } else if (!signal.aborted && context.current() && openAttempted && !accessOpened) { @@ -664,15 +668,20 @@ export function createReferenceSources(options: { await operation.promise; assertFence(operation.domain); assertTurn(); - // Closing the wire also awaits: its original private grant must still - // authorize the lease after shutdown, without inheriting a new grant. - if (operation.domain !== PUBLIC && authorize(operation.domain, input.principalId, repository)?.id !== operation.grantId) - throw new ReferenceSourceError("unauthorized", "The selected reference grant changed before acquisition completed."); + // The retained guard includes validation, principal and selected + // grant/credential/recipient authority after wire shutdown completes. + result!.assertAuthority(); return result!; } catch (error) { const held = result; - held?.release(); - if (held) await containFailure(error, false); + if (held) { + // A failed close can hide an authority loss too; contain that loss + // even when the wire itself never returned successfully. + try { held.assertAuthority(); } catch (authorityError) { error = authorityError; } + held.release(); + await containFailure(error, false); + } + if (error instanceof ReferenceTransportError) throw new ReferenceSourceError(error.reason === "denied" ? "unauthorized" : error.reason, error.message); throw error; } finally { operations.delete(id); void settle(...splitKey(operation.key)).catch(error => warn("managed source settle failed", error)); } @@ -722,10 +731,11 @@ export function createReferenceSources(options: { * unsettled until the pool confirms, so a bind retries it and refuses until * it does. */ - function suspendSource(domain: string, repository: string, revision: string): Promise { + function suspendSource(domain: string, repository: string, revision: string, onlyExpired = false): Promise { const key = sourceKey(domain, repository, revision); return exclusive(key, async () => { const source = row(domain, repository, revision); + if (onlyExpired && (!source || validationLive(source))) return; const roots = db.query("SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ? AND state != 'staging'").all(domain, repository, revision) as { id: string }[]; const pending = [...pendingPublications].filter(([, publication]) => publication.key === key); if ((!source?.root_id && !roots.length && !pending.length) || (suspended.has(key) && !unsettled.has(key) && !pending.length)) return; diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 46ba8f0489..33793e2bfc 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -655,6 +655,58 @@ describe("live managed authority", () => { } finally { held?.release(); await f.close(); } }); + for (const loss of ["credential", "recipient", "principal", "expiry"] as const) + for (const closeFails of [false, true]) + test(`source authority lost to ${loss} during ${closeFails ? "failed" : "successful"} wire shutdown is contained`, async () => { + const f = await fixture({ private: loss === "credential" || loss === "recipient" }); + if (loss === "credential" || loss === "recipient") f.grant(); + let held: Awaited> | undefined, delivered: typeof held; + try { + held = await f.request(); + expect(readFileSync(join(held.viewPath, held.name, "README.md"), "utf8")).toContain("Odysseus"); + const open = f.github.open; + f.github.open = async input => { + const access = await open(input); + return Object.freeze({ ...access, async close() { + await access.close(); + if (loss === "credential") f.credentials.GITHUB_TOKEN = undefined; + else if (loss === "recipient") f.db.query("UPDATE reference_grants SET metadata_credential_recipient = NULL").run(); + else if (loss === "principal") revokePrincipal(f.db, f.owner.id, Date.now()); + else f.state.clock += 400_000; + if (closeFails) throw new Error("Wire shutdown did not complete."); + } }); + }; + const outcome = await f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + delivered = outcome.lease; + expect(delivered, "SOURCE_MUST_NOT_RETURN_ALREADY_INVALID_AUTHORITY").toBeUndefined(); + expect(existsSync(join(held.viewPath, held.name, "README.md")), "WIRE_SHUTDOWN_FAILURE_CONTAINS_INVALID_SOURCE_NAME").toBe(false); + expect(existsSync(join(held.viewPath, held.rootId, "README.md")), "WIRE_SHUTDOWN_FAILURE_CONTAINS_INVALID_SOURCE_ROOT").toBe(false); + expect(outcome.error).toMatchObject({ code: loss === "expiry" ? "unavailable" : "unauthorized" }); + } finally { delivered?.release(); held?.release(); await f.close(); } + }); + + test("expiry during an older wire shutdown cannot suspend a newer validation", async () => { + const f = await fixture(), closing = Promise.withResolvers(), resumeClose = Promise.withResolvers(); + let held: Awaited> | undefined, current: typeof held, older: Promise<{ lease: typeof held; error: unknown }> | undefined; + try { + held = await f.request(); + const open = f.github.open; let openings = 0; + f.github.open = async input => { + const access = await open(input), paused = ++openings === 1; + return Object.freeze({ ...access, async close() { await access.close(); if (paused) { closing.resolve(); await resumeClose.promise; } } }); + }; + older = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + await closing.promise; f.state.clock += 400_000; + current = await f.request(f.other.id, "telemachus-newer-validation", f.secondEgress); + resumeClose.resolve(); const outcome = await older; + outcome.lease?.release(); + expect(outcome.error, "OLDER_EXPIRED_LEASE_IS_NOT_RETURNED").toMatchObject({ code: "unavailable" }); + expect(existsSync(join(current.viewPath, current.name, "README.md")), "OLDER_EXPIRY_CANNOT_HIDE_NEW_VALIDATION").toBe(true); + expect(readFileSync(join(current.viewPath, current.name, "README.md"), "utf8")).toContain("Odysseus"); + expect(() => current!.assertAuthority(), "NEW_VALIDATION_SURVIVES_OLDER_SHUTDOWN_EXPIRY").not.toThrow(); + } finally { resumeClose.resolve(); (await older)?.lease?.release(); current?.release(); held?.release(); await f.close(); } + }); + test("a revoked private grant during wire shutdown refuses and hides the cached source", async () => { const f = await fixture({ private: true }), issued = f.grant(); let held: Awaited> | undefined; From bae8874b10c1e75447b77f41e5fc187b76f8721c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 06:37:58 +0000 Subject: [PATCH 16/27] fix(ui-server): preserve shutdown failure without assigning catch parameter --- packages/ui-server/src/brain/reference-source.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 7afb492950..7ae2990662 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -674,15 +674,16 @@ export function createReferenceSources(options: { return result!; } catch (error) { const held = result; + let failure = error; if (held) { // A failed close can hide an authority loss too; contain that loss // even when the wire itself never returned successfully. - try { held.assertAuthority(); } catch (authorityError) { error = authorityError; } + try { held.assertAuthority(); } catch (authorityError) { failure = authorityError; } held.release(); - await containFailure(error, false); + await containFailure(failure, false); } - if (error instanceof ReferenceTransportError) throw new ReferenceSourceError(error.reason === "denied" ? "unauthorized" : error.reason, error.message); - throw error; + if (failure instanceof ReferenceTransportError) throw new ReferenceSourceError(failure.reason === "denied" ? "unauthorized" : failure.reason, failure.message); + throw failure; } finally { operations.delete(id); void settle(...splitKey(operation.key)).catch(error => warn("managed source settle failed", error)); } } From c5f8b96aff1cf626b9da54b646a6318352466bdd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 06:45:53 +0000 Subject: [PATCH 17/27] docs: align source authority citations after shutdown containment --- docs/decisions/managed-worktrees.md | 8 ++++---- docs/decisions/reference-source-acquisition.md | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 3c57ba058d..b41ac4be62 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1005-1036`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1006-1037`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:809-847`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:810-848`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:734-751`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:735-752`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:853-862`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:854-863`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 2f41069122..36caebade2 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -260,14 +260,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:907-932`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:908-933`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:935-979`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:936-980`). ## Evidence From da1797a08b6bf087871a75c7fb8564e779bfe0f1 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 07:43:58 +0000 Subject: [PATCH 18/27] fix(ui-server): preserve literal suffixes in canonical reference grants --- .../managed-reference-source-authority.md | 2 +- docs/decisions/reference-source-grants.md | 16 +++++-- docs/http-api.md | 7 +++- packages/ui-server/src/db/reference-grants.ts | 6 ++- .../ui-server/tests/reference-grants.test.ts | 42 +++++++++++++++++-- .../tests/reference-source-managed.test.ts | 4 +- 6 files changed, 64 insertions(+), 13 deletions(-) diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md index 4592227db3..59d9a3c6df 100644 --- a/.changeset/managed-reference-source-authority.md +++ b/.changeset/managed-reference-source-authority.md @@ -3,4 +3,4 @@ "@schlessera/brain-ui-sdk": minor --- -Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. +Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. Keep stored canonical grant suffixes literal during lookup and duplicate checks, so a repository grant cannot authorize a neighboring repository. diff --git a/docs/decisions/reference-source-grants.md b/docs/decisions/reference-source-grants.md index 4720f10640..b7de6a0d8a 100644 --- a/docs/decisions/reference-source-grants.md +++ b/docs/decisions/reference-source-grants.md @@ -28,7 +28,7 @@ The maintainer selected **owner-managed grant records** on 2026-10-22 ## The record A grant is one row of the UI database's `reference_grants` table -(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:127-155`). +(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:129-157`). The table holds the served brain's identity, the principal, the canonical repository prefix, the credential name or null, the granting owner and the revocation time. It stores no credential value. A grant is **live** while it @@ -49,11 +49,11 @@ A repository location is HTTPS without user info, query or fragment; loopback `http://`; or an absolute `file:///` path (`referenceRepository`, `packages/ui-server/src/db/reference-grants.ts:52-77`). SSH is refused: no grantable credential is an SSH key. The canonical form -lowercases the origin and drops a trailing slash and a hosted `.git` suffix. A -prefix covers itself and every path below it at a segment boundary, so +lowercases the origin and drops a trailing slash and one hosted `.git` clone +suffix. A prefix covers itself and every path below it at a segment boundary, so `…/odysseus` never covers `…/odysseus-crew`. The longest covering live prefix wins, read at the moment of use -(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:175-186`). +(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:177-188`). GitHub HTTPS paths are normalized to lowercase, matching the qualified transport. Retained mixed-case prefixes are normalized for matching and @@ -61,6 +61,14 @@ duplicate detection without rewriting their receipts. Specificity uses the canonical prefix length, so an older spelling cannot select a broader API credential permission. Other hosts and local paths remain case-sensitive. +Raw hosted input removes one clone `.git` suffix when its canonical key is +created. Stored prefixes already hold that key: later validation and GitHub +case normalization preserve any remaining `.git` as literal path content. +Reapplying clone-suffix removal would let a grant for `ithaca.git.git` cover +the distinct `ithaca` repository and defeat duplicate/specificity checks. +Retained mixed-case fixtures therefore store canonical keys, not raw clone +URLs; mixed-case literal suffixes stay literal. File paths remain exact. + A grant names its credential from a fixed list of existing host selectors, each with the one origin it may be sent to (`REFERENCE_HOST_CREDENTIALS`, `packages/ui-server/src/db/reference-grants.ts:27-31`): diff --git a/docs/http-api.md b/docs/http-api.md index 75b01c70a7..f7d9f2d4b1 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -539,8 +539,11 @@ itself. HTTPS URL without user info, query or fragment, a loopback `http://` URL, or an absolute `file:///` path; it may be a bare HTTPS origin. Empty, `.` and `..` segments, whitespace, control characters, backslashes and percent-encoding - are 400. Hosted prefixes are stored lowercase-origin without a trailing slash - or `.git`; a prefix covers itself and paths below it at a segment boundary. + are 400. Hosted inputs lose one trailing `.git` clone suffix and a trailing + slash; the stored canonical key retains any remaining literal `.git`. + GitHub path casing is normalized, while other hosts and file paths keep + their case. Lookup never removes another suffix from a stored key. A prefix + covers itself and paths below it at a segment boundary. `credential` defaults to null. Otherwise it is exactly `BRAIN_UI_SYNC_GITHUB_TOKEN`, `BRAIN_UI_SKILLS_GITHUB_TOKEN` or `GITHUB_TOKEN`, and the prefix origin must be `https://github.com` or a diff --git a/packages/ui-server/src/db/reference-grants.ts b/packages/ui-server/src/db/reference-grants.ts index ce44505ffd..b07705d929 100644 --- a/packages/ui-server/src/db/reference-grants.ts +++ b/packages/ui-server/src/db/reference-grants.ts @@ -31,7 +31,7 @@ export const REFERENCE_HOST_CREDENTIALS: Readonly> = Obje }); export interface ReferenceRepository { - /** Authority and sharing key: lowercase origin, path without a trailing slash or `.git`. */ + /** Authority/sharing key: lowercase origin, no trailing slash, one hosted clone suffix removed on input. */ canonical: string; /** The requested location, normalized but otherwise as given; transports fetch this. */ url: string; @@ -80,7 +80,9 @@ export function referenceRepository(input: unknown, options: { prefix?: boolean export const coversRepository = (prefix: string, repository: string) => repository === prefix || repository.startsWith(`${prefix}/`); function storedPrefix(input: string): string | null { - try { return referenceRepository(input, { prefix: true }).canonical; } catch { return null; } + // This value is already canonical: validate and normalize GitHub case, but + // keep any remaining literal .git instead of removing another clone suffix. + try { return referenceRepository(input, { prefix: true }).url; } catch { return null; } } /** Refuse a credential name outside the fixed list, or one whose recipient is not this prefix's origin. */ diff --git a/packages/ui-server/tests/reference-grants.test.ts b/packages/ui-server/tests/reference-grants.test.ts index b03ea0f678..842510c748 100644 --- a/packages/ui-server/tests/reference-grants.test.ts +++ b/packages/ui-server/tests/reference-grants.test.ts @@ -73,22 +73,58 @@ describe("reference grant records", () => { test("retained GitHub prefix aliases match and cannot create duplicate live grants", () => { const penelope = owner(), existing = grant(penelope.id, penelope.id, "https://github.com/odysseus/ithaca", "GITHUB_TOKEN"); - db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run("https://github.com/Odysseus/Ithaca.GIT", existing.id); + db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run("https://github.com/Odysseus/Ithaca", existing.id); expect(covering(penelope.id, "https://github.com/odysseus/ithaca")?.id, "RETAINED_GITHUB_PREFIX_ALIAS_MATCHES").toBe(existing.id); expect(() => grant(penelope.id, penelope.id, "https://github.com/ODYSSEUS/ITHACA", "GITHUB_TOKEN"), "RETAINED_GITHUB_ALIAS_PREVENTS_DUPLICATE_GRANTS").toThrow("identical live reference grant"); }); - test("normalized prefix length preserves the narrower API permission boundary", () => { + test("canonical prefix specificity preserves the narrower API permission boundary", () => { const penelope = owner(), narrow = grant(penelope.id, penelope.id, "https://github.com/odysseus/x", "GITHUB_TOKEN"); const broad = createReferenceGrant(db, { brain: BRAIN, principalId: penelope.id, createdBy: penelope.id, repositoryPrefix: "https://github.com/odysseus", credential: "GITHUB_TOKEN", now: narrow.createdAt + 1, metadataCredentialRecipient: "https://api.github.com" }); - db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run("https://github.com/Odysseus.GIT", broad.id); + db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run("https://github.com/Odysseus", broad.id); const selected = covering(penelope.id, "https://github.com/odysseus/x"); expect(selected?.id, "NORMALIZED_LONGEST_PREFIX_RETAINS_PERMISSION_BOUNDARY").toBe(narrow.id); expect(selected?.metadataCredentialRecipient).toBeUndefined(); }); + for (const prefix of ["http://127.0.0.1:8418/odysseus/ithaca.git.git", "https://github.com/Odysseus/Ithaca.git.git", "https://forge.example/Odysseus/Ithaca.git.git"]) + test(`stored grant suffix preserves the intended repository boundary for ${prefix}`, () => { + const penelope = owner(), credential = prefix.startsWith("https://forge.example") ? null : "GITHUB_TOKEN"; + const record = grant(penelope.id, penelope.id, prefix, credential), neighbor = prefix.slice(0, -8); + expect(covering(penelope.id, neighbor), "STORED_PREFIX_CANNOT_STRIP_ANOTHER_CLONE_SUFFIX").toBeNull(); + expect(covering(penelope.id, prefix)?.id, "CANONICAL_SUFFIX_GRANT_COVERS_INTENDED_REPOSITORY").toBe(record.id); + const distinct = grant(penelope.id, penelope.id, neighbor, credential); + expect(distinct.id).not.toBe(record.id); + expect(covering(penelope.id, neighbor)?.id).toBe(distinct.id); + expect(covering(penelope.id, prefix)?.id).toBe(record.id); + }); + + for (const prefix of ["http://127.0.0.1:8418/odysseus/ithaca.git.git", "https://github.com/Odysseus/Ithaca.git.git", "https://forge.example/Odysseus/Ithaca.git.git"]) + test(`a stored canonical suffix still rejects an identical grant for ${prefix}`, () => { + const penelope = owner(), credential = prefix.startsWith("https://forge.example") ? null : "GITHUB_TOKEN"; + grant(penelope.id, penelope.id, prefix, credential); + expect(() => grant(penelope.id, penelope.id, prefix, credential), "CANONICAL_SUFFIX_CANNOT_BYPASS_DUPLICATE_GRANT_CHECK").toThrow("identical live reference grant"); + }); + + test("a retained mixed-case literal GitHub suffix cannot authorize its neighbor", () => { + const penelope = owner(), record = grant(penelope.id, penelope.id, "https://github.com/odysseus/ithaca.git.git", "GITHUB_TOKEN"); + db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run("https://github.com/Odysseus/Ithaca.GIT", record.id); + expect(covering(penelope.id, "https://github.com/odysseus/ithaca"), "RETAINED_CANONICAL_SUFFIX_STAYS_LITERAL").toBeNull(); + expect(covering(penelope.id, "https://github.com/odysseus/ithaca.git.git")?.id).toBe(record.id); + }); + + test("a canonical suffix keeps the narrower API permission boundary", () => { + const penelope = owner(); + createReferenceGrant(db, { brain: BRAIN, principalId: penelope.id, createdBy: penelope.id, + repositoryPrefix: "https://github.com/odysseus", credential: "GITHUB_TOKEN", now: Date.now(), metadataCredentialRecipient: "https://api.github.com" }); + const narrow = grant(penelope.id, penelope.id, "https://github.com/odysseus/ithaca.git.git", "GITHUB_TOKEN"); + const selected = covering(penelope.id, "https://github.com/odysseus/ithaca.git.git"); + expect(selected?.id, "CANONICAL_SUFFIX_RETAINS_NARROW_API_PERMISSION_SCOPE").toBe(narrow.id); + expect(selected?.metadataCredentialRecipient).toBeUndefined(); + }); + test("a live covering grant authorizes only its own brain, principal and path-segment prefix", () => { const penelope = owner(), telemachus = agent(penelope.id); const record = grant(telemachus.id, penelope.id, "https://github.com/odysseus", "BRAIN_UI_SYNC_GITHUB_TOKEN"); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 33793e2bfc..89c582b4b6 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -326,7 +326,9 @@ describe("live managed authority", () => { test(`a ${retained ? "retained" : "new"} mixed-case GitHub grant covers ${prefix}`, async () => { const f = await fixture({ private: true }), issued = f.grant(prefix); try { - if (retained) f.db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?").run(prefix, issued.id); + // Retained rows contain canonical keys, with legacy path casing. + if (retained) f.db.query("UPDATE reference_grants SET repository_prefix = ? WHERE id = ?") + .run(issued.repositoryPrefix.replace("/odysseus", "/Odysseus").replace("/ithaca", "/Ithaca"), issued.id); expect(f.sources.covers({ principalId: f.owner.id, repository }), "MIXED_CASE_GITHUB_GRANT_COVERS_TRANSPORT_IDENTITY").toBe(true); const lease = await f.request(); try { expect(lease.domain).toBe("private"); expect(readFileSync(join(lease.viewPath, lease.name, "README.md"), "utf8")).toContain("Odysseus"); } From 6908f62241c40dd3f3faa52e60f500ab46e8bbc4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 08:06:42 +0000 Subject: [PATCH 19/27] fix(ui-server): recheck durable source authority after worktree waits --- .../managed-reference-source-authority.md | 2 +- docs/decisions/managed-worktrees.md | 8 +-- .../decisions/reference-source-acquisition.md | 22 ++++--- .../ui-server/src/brain/reference-source.ts | 7 ++- .../tests/reference-source-managed.test.ts | 62 +++++++++++++++++++ 5 files changed, 87 insertions(+), 14 deletions(-) diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md index 59d9a3c6df..79b33f43f6 100644 --- a/.changeset/managed-reference-source-authority.md +++ b/.changeset/managed-reference-source-authority.md @@ -3,4 +3,4 @@ "@schlessera/brain-ui-sdk": minor --- -Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. Keep stored canonical grant suffixes literal during lookup and duplicate checks, so a repository grant cannot authorize a neighboring repository. +Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. Keep stored canonical grant suffixes literal during lookup and duplicate checks, so a repository grant cannot authorize a neighboring repository. Waiting worktree effects reread shared source authority, including durable invalidation by another app or cron owner. diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index b41ac4be62..8a48847e59 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1006-1037`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1011-1042`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:810-848`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:815-853`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:735-752`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:740-757`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:854-863`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:859-868`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 36caebade2..8979e28e41 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:98-901`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:98-906`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:327-376`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:332-381`). - Inside both windows a request reuses the published source without any network call. @@ -86,6 +86,12 @@ default to five minutes and are configured separately credential and API-recipient permission. A failed close also checks and contains authority loss. Shutdown expiry withholds the expired source under its exposure lock, while a newer successful validation stays exposed. + Each retained lease also rereads the shared catalog before new effects: + its root, commit and ref must still match the authoritative publication and + both its captured validation and the current validation must be live. + Another app or cron owner's durable suspension, withdrawal or replacement + therefore fences waiting worktree effects too. A valid same-root check by + another owner preserves access. Repository metadata fences every cached and in-flight revision of that repository. Older requests cannot publish or restore public state after a newer private or refused observation, even before the first catalog row @@ -124,7 +130,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:476-530`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:481-535`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -223,9 +229,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:267-282`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:272-287`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:285-310`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:290-315`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -247,7 +253,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:401-417`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:406-422`). There is no idle expiry. ## Revocation and recovery @@ -260,14 +266,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:908-933`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:913-938`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:936-980`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:941-985`). ## Evidence diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 7ae2990662..0b82cb6942 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -215,7 +215,12 @@ export function createReferenceSources(options: { if (closed) throw new ReferenceSourceError("unavailable", "Reference sources are closed."); if (fence !== (authorityFences.get(key) ?? 0) || withdrawn.has(key)) throw new ReferenceSourceError(suspended.has(key) ? "unavailable" : "unauthorized", "A newer observation invalidated this source's authority."); - if (suspended.has(key) || !validationLive(source)) + // App/cron owners share the catalog, not these process-local fences. + // New effects must still name this publication after their own waits. + const current = row(source.domain, source.repository, source.revision); + if (!usable(current) || current.root_id !== source.root_id || current.commit_id !== source.commit_id || current.ref !== source.ref) + throw new ReferenceSourceError("unauthorized", "This source publication is no longer authoritative."); + if (suspended.has(key) || !validationLive(source) || !validationLive(current)) throw new ReferenceSourceError("unavailable", "This source's authority needs fresh validation."); authority?.(); }; diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 89c582b4b6..d7c317dd07 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -777,6 +777,68 @@ describe("live managed authority", () => { } finally { if (first) await worktrees.closeGeneration(first.id); if (other) await worktrees.closeGeneration(other.id); await worktrees.close(); await f.close(); } }); + for (const observation of ["private", "unknown", "replacement"] as const) + for (const wait of ["coverage", "native-grant", "held-refresh"] as const) + test(`another source service's ${observation} observation fences a worktree during ${wait}`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const context = { turnId: "odysseus-shared-source-authority", egress: f.egress, current: () => f.state.current }; + const invalidate = async () => { + if (observation === "private") f.state.private = true; + else if (observation === "unknown") f.state.status = 503; + else f.state.ownerId = 202; + const pending = otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-other-source-owner", egress: f.secondEgress, current: () => true } }); + if (observation === "replacement") (await pending).release(); + else await expect(pending).rejects.toMatchObject({ code: observation === "private" ? "unauthorized" : "unavailable" }); + if (observation === "unknown") expect(otherDb.query("SELECT validated_at FROM reference_sources WHERE domain = 'public'").get(), + "OTHER_SERVICE_SUSPENSION_IS_DURABLE").toEqual({ validated_at: 0 }); + }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, + coverage: async () => { if (wait === "coverage") await invalidate(); } }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + if (wait === "native-grant") { + const access = f.pool.poolAccess; + f.pool.poolAccess = async (...args) => { const result = await access(...args); await invalidate(); return result; }; + } + if (wait === "held-refresh") { + await worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }); + const request = f.sources.request; + f.sources.request = async input => { const lease = await request(input); await invalidate(); return lease; }; + } + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }), + "WORKTREE_RECHECKS_OTHER_SERVICE_DURABLE_AUTHORITY").rejects.toMatchObject({ code: observation === "unknown" ? "unavailable" : "unauthorized" }); + expect(f.pool.records.get(item.id)!.access, "OTHER_SERVICE_INVALIDATION_PARKS_WORKTREE").toBeNull(); + expect(existsSync(join(generation.path, item.id, "README.md")), "OTHER_SERVICE_INVALIDATION_HIDES_WORKTREE_FILES").toBe(false); + expect(worktrees.get({ worktreeId: item.id, principalId: f.owner.id }).generation).toBeNull(); + } finally { + if (generation) await worktrees.closeGeneration(generation.id); + await worktrees.close(); await otherSources.close(); otherDb.close(); await f.close(); + } + }); + + test("another service's valid check preserves the waiting source lease", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const context = { turnId: "odysseus-shared-valid-authority", egress: f.egress, current: () => f.state.current }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => { + const lease = await otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-valid-source-check", egress: f.secondEgress, current: () => true } }); + lease.release(); + } }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository, revision: "main", acquisition: context }); + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + await worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }); + expect(readFileSync(join(generation.path, item.id, "README.md"), "utf8"), "OTHER_SERVICE_VALIDATION_PRESERVES_AUTHORIZED_WORKTREE").toContain("Odysseus"); + } finally { + if (generation) await worktrees.closeGeneration(generation.id); + await worktrees.close(); await otherSources.close(); otherDb.close(); await f.close(); + } + }); + for (const observation of ["private", "unknown"] as const) for (const wait of ["coverage", "native-grant", "held-refresh"] as const) test(`a public worktree cannot outlive newer ${observation} authority during ${wait}`, async () => { From b75e3637c1310aaeadd252fab6cfd8761883d06f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 08:45:23 +0000 Subject: [PATCH 20/27] fix(ui-server): share source invalidation across publication owners --- .../managed-reference-source-authority.md | 2 +- docs/decisions/managed-worktrees.md | 8 +- .../decisions/reference-source-acquisition.md | 26 ++++-- .../091_reference_authority_fences.sql | 9 ++ .../src/brain/github-reference-access.ts | 6 +- .../src/brain/reference-source-authority.ts | 28 ++++++ .../src/brain/reference-source-writes.ts | 30 +++++-- .../ui-server/src/brain/reference-source.ts | 86 +++++++++++++------ .../tests/github-reference-access.test.ts | 39 +++++++++ .../tests/reference-source-authority.test.ts | 54 ++++++++++++ .../tests/reference-source-managed.test.ts | 86 +++++++++++++++++++ .../tests/reference-writes-offloop.test.ts | 2 + 12 files changed, 331 insertions(+), 45 deletions(-) create mode 100644 packages/ui-server/migrations/091_reference_authority_fences.sql create mode 100644 packages/ui-server/src/brain/reference-source-authority.ts create mode 100644 packages/ui-server/tests/reference-source-authority.test.ts diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md index 79b33f43f6..45881b378b 100644 --- a/.changeset/managed-reference-source-authority.md +++ b/.changeset/managed-reference-source-authority.md @@ -3,4 +3,4 @@ "@schlessera/brain-ui-sdk": minor --- -Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. Keep stored canonical grant suffixes literal during lookup and duplicate checks, so a repository grant cannot authorize a neighboring repository. Waiting worktree effects reread shared source authority, including durable invalidation by another app or cron owner. +Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. Keep stored canonical grant suffixes literal during lookup and duplicate checks, so a repository grant cannot authorize a neighboring repository. Waiting worktree effects reread shared source authority, including durable invalidation by another app or cron owner. Shared repository/revision invalidation versions also fence first publication across app and cron owners, with validation/publication commit checks and retirement of invalidated sealed staging identities. Failed-attempt cleanup preserves another owner's newer publication. Metadata and Git wiring preserve the requested repository's literal canonical suffix, including when metadata reports it missing. diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 8a48847e59..804ca911be 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1011-1042`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1049-1080`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:815-853`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:853-891`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:740-757`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:778-795`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:859-868`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:897-906`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 8979e28e41..7a0e411e51 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:98-906`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:99-907`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:332-381`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:352-401`). - Inside both windows a request reuses the published source without any network call. @@ -92,6 +92,16 @@ default to five minutes and are configured separately Another app or cron owner's durable suspension, withdrawal or replacement therefore fences waiting worktree effects too. A valid same-root check by another owner preserves access. + Repository and revision invalidation versions are shared durable catalog + facts. Every managed request retains its starting versions; checks after + waits and the publication/validation write transaction refuse changed + versions. Repository observations cover all revisions in the affected + sharing domain, including requests with no source catalog row yet. + Withdrawal inspects staging roots from other owners too: a sealed staging + identity is retired before returning, so a delayed native publication + cannot expose it. A still-writing root stays masked and its acquiring + owner releases it after its worker stops. Cleanup of a failed attempt + discards only that attempt's root and preserves a newer valid publication. Repository metadata fences every cached and in-flight revision of that repository. Older requests cannot publish or restore public state after a newer private or refused observation, even before the first catalog row @@ -130,7 +140,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:481-535`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:504-558`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -229,9 +239,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:272-287`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:292-307`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:290-315`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:310-335`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -253,7 +263,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:406-422`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:426-442`). There is no idle expiry. ## Revocation and recovery @@ -266,14 +276,14 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:913-938`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:951-976`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:941-985`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:979-1023`). ## Evidence diff --git a/packages/ui-server/migrations/091_reference_authority_fences.sql b/packages/ui-server/migrations/091_reference_authority_fences.sql new file mode 100644 index 0000000000..44c0b7ed3a --- /dev/null +++ b/packages/ui-server/migrations/091_reference_authority_fences.sql @@ -0,0 +1,9 @@ +-- Invalidation survives separate app/cron owners and precedes publication. +-- Empty revision fences every revision of a repository in this sharing domain. +CREATE TABLE reference_authority_fences ( + domain TEXT NOT NULL, + repository TEXT NOT NULL, + revision TEXT NOT NULL, + generation TEXT NOT NULL, + PRIMARY KEY (domain, repository, revision) +); diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 6da8e9b6fa..50abb79404 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -70,7 +70,7 @@ export function createGitHubReferenceAccess(options: { throw new ReferenceTransportError("denied", "the selected host credential changed"); } else if (credentialed) throw new ReferenceTransportError("denied", "anonymous acquisition cannot dispatch a credential"); }; - const wire = await createGitHubReferenceWire({ ...input, repository: location.canonical, ...options.wireTransport, authorize }); + const wire = await createGitHubReferenceWire({ ...input, repository: location.cloneUrl, ...options.wireTransport, authorize }); let openingMetadata = true; try { let result = await wire.metadata(null); @@ -87,7 +87,7 @@ export function createGitHubReferenceAccess(options: { } authorize("metadata", credential !== null); if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable"); - const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.canonical, result.value); + const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.cloneUrl, result.value); if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); openingMetadata = false; // Source/worktree effects outlive wire shutdown, but not this authority. @@ -131,7 +131,7 @@ export function createGitHubReferenceAccess(options: { assertCurrent(); const result = await wire.metadata(credential); assertCurrent(); - if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.canonical, result.value))) + if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.cloneUrl, result.value))) throw new ReferenceTransportError("denied", "GitHub repository identity changed during acquisition"); } catch (error) { const interrupted = input.signal?.aborted || (input.current && !input.current()); diff --git a/packages/ui-server/src/brain/reference-source-authority.ts b/packages/ui-server/src/brain/reference-source-authority.ts new file mode 100644 index 0000000000..e7756811b2 --- /dev/null +++ b/packages/ui-server/src/brain/reference-source-authority.ts @@ -0,0 +1,28 @@ +/** Shared invalidation versions, not source trust or private-access grants. */ +import type { Database } from "bun:sqlite"; +import { referenceRepository } from "../db/reference-grants.js"; + +export interface SourceAuthority { + domain: string; + repository: string; + revision: string; + repositoryFence: string; + revisionFence: string; +} + +/** Keys are already canonical: normalize GitHub casing without removing a suffix. */ +export const authorityRepository = (repository: string) => referenceRepository(repository, { prefix: true }).url; + +export function sourceAuthority(db: Database, domain: string, repository: string, revision: string): SourceAuthority { + repository = authorityRepository(repository); + const rows = db.query("SELECT revision, generation FROM reference_authority_fences WHERE domain = ? AND repository = ? AND revision IN ('', ?)") + .all(domain, repository, revision) as { revision: string; generation: string }[]; + return { domain, repository, revision, repositoryFence: rows.find(row => row.revision === "")?.generation ?? "", + revisionFence: rows.find(row => row.revision === revision)?.generation ?? "" }; +} + +/** The writer also calls this inside its publication/validation transaction. */ +export function sourceAuthorityCurrent(db: Database, expected: SourceAuthority): boolean { + const current = sourceAuthority(db, expected.domain, expected.repository, expected.revision); + return current.repositoryFence === expected.repositoryFence && current.revisionFence === expected.revisionFence; +} diff --git a/packages/ui-server/src/brain/reference-source-writes.ts b/packages/ui-server/src/brain/reference-source-writes.ts index a55e4f4229..52323db534 100644 --- a/packages/ui-server/src/brain/reference-source-writes.ts +++ b/packages/ui-server/src/brain/reference-source-writes.ts @@ -1,6 +1,7 @@ /** Reference catalog effects; acquisition and native pool calls stay with the caller (#2999). */ import type { Database } from "bun:sqlite"; import type { ReferenceAcquisition } from "./reference-acquisition.js"; +import { sourceAuthorityCurrent, type SourceAuthority } from "./reference-source-authority.js"; export function sourceWrites(db: Database) { function sourceView(domain: string, id: string): { id: string; hostPath: string | null } { @@ -11,6 +12,10 @@ export function sourceWrites(db: Database) { } return { sourceView, + sourceFence(domain: string, repository: string, revision: string, generation: string) { + db.query(`INSERT INTO reference_authority_fences (domain, repository, revision, generation) VALUES (?, ?, ?, ?) + ON CONFLICT (domain, repository, revision) DO UPDATE SET generation = excluded.generation`).run(domain, repository, revision, generation); + }, sourceTouch(at: number, domain: string, repository: string, revision: string) { db.query("UPDATE reference_sources SET last_used_at = ? WHERE domain = ? AND repository = ? AND revision = ?").run(at, domain, repository, revision); }, @@ -20,8 +25,21 @@ export function sourceWrites(db: Database) { sourceReleaseRoot(id: string) { db.query("DELETE FROM reference_roots WHERE id = ?").run(id); }, - sourceValidate(at: number, refreshedAt: number, ref: string, domain: string, repository: string, revision: string) { - db.query("UPDATE reference_sources SET validated_at = ?, refreshed_at = ?, last_error = NULL, ref = ? WHERE domain = ? AND repository = ? AND revision = ?").run(at, refreshedAt, ref, domain, repository, revision); + sourceDiscard(id: string) { + return db.transaction(() => { + const root = db.query("SELECT id, state FROM reference_roots WHERE id = ?").get(id) as { id: string; state: string } | null; + db.query("UPDATE reference_sources SET root_id = NULL WHERE root_id = ?").run(id); + db.query("UPDATE reference_roots SET state = 'superseded' WHERE id = ? AND state = 'published'").run(id); + return root; + }).immediate(); + }, + sourceValidate(at: number, refreshedAt: number, ref: string, domain: string, repository: string, revision: string, expected?: SourceAuthority, rootId?: string) { + return db.transaction(() => { + if (expected && !sourceAuthorityCurrent(db, expected)) return false; + return db.query(`UPDATE reference_sources SET validated_at = ?, refreshed_at = ?, last_error = NULL, ref = ? + WHERE domain = ? AND repository = ? AND revision = ? AND (? IS NULL OR root_id = ?)`) + .run(at, refreshedAt, ref, domain, repository, revision, rootId ?? null, rootId ?? null).changes === 1; + }).immediate(); }, sourceSuspend(domain: string, repository: string, revision: string) { db.query("UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ?").run(domain, repository, revision); @@ -40,13 +58,14 @@ export function sourceWrites(db: Database) { }, sourceWithdraw(domain: string, repository: string, revision: string, viewId: string) { db.query("UPDATE reference_sources SET root_id = NULL WHERE domain = ? AND repository = ? AND revision = ?").run(domain, repository, revision); - const roots = db.query("SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ? AND state != 'staging'").all(domain, repository, revision) as { id: string }[]; + const roots = db.query("SELECT id, state FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ?").all(domain, repository, revision) as { id: string; state: string }[]; db.query("UPDATE reference_roots SET state = 'superseded' WHERE domain = ? AND repository = ? AND revision = ? AND state = 'published'").run(domain, repository, revision); const view = sourceView(domain, viewId); return { roots, view }; }, - sourcePublish(path: string, domain: string, repository: string, revision: string, url: string, name: string, id: string, commit: string, ref: string, grantId: string | null, at: number, acquisition?: ReferenceAcquisition) { - db.transaction(() => { + sourcePublish(path: string, domain: string, repository: string, revision: string, url: string, name: string, id: string, commit: string, ref: string, grantId: string | null, at: number, acquisition?: ReferenceAcquisition, expected?: SourceAuthority) { + return db.transaction(() => { + if (expected && !sourceAuthorityCurrent(db, expected)) return false; if (acquisition) db.query(`INSERT INTO reference_acquisitions (root_id, acquisition_id, brain, principal_id, turn_id, repository_id, owner_id, owner, repository_name, ref, commit_id, tree_id, native_root_id, native_uuid, native_generation, grant_id, network_bytes, acquired_at) @@ -62,6 +81,7 @@ export function sourceWrites(db: Database) { ON CONFLICT (domain, repository, revision) DO UPDATE SET url = excluded.url, name = excluded.name, root_id = excluded.root_id, commit_id = excluded.commit_id, ref = excluded.ref, grant_id = excluded.grant_id, refreshed_at = excluded.refreshed_at, validated_at = excluded.validated_at, last_error = NULL`) .run(domain, repository, revision, url, name, id, commit, ref, grantId, at, at, at); + return true; }).immediate(); }, }; diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 0b82cb6942..2d13429b9d 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -29,6 +29,7 @@ import { referenceRevision, ReferenceTransportError, type ReferenceTransport } f import { GitHubReferenceMetadataError, type createGitHubReferenceAccess } from "./github-reference-access.js"; import { githubReferenceRepository } from "./github-reference-identity.js"; import { referenceAcquisitionMatches, type ReferenceAcquisition, type ReferenceAcquisitionContext } from "./reference-acquisition.js"; +import { authorityRepository, sourceAuthority, sourceAuthorityCurrent, type SourceAuthority } from "./reference-source-authority.js"; type GitHubAccess = Awaited["open"]>>; @@ -182,6 +183,22 @@ export function createReferenceSources(options: { hiddenRoots.add(id); pendingPublications.delete(id); } + /** Another owner can have native publication but only a staging catalog row. */ + async function hideRecordedRoot(root: { id: string; state: string }) { + if (root.state !== "staging") return hideRoot(root.id); + try { + const record = await pool.poolWithdraw(root.id); + // A sealed staging root has no active writer. Retire its identity so a + // delayed publication RPC cannot expose it after this owner returns. + if (record.state !== "writable" && record.state !== "reserved") await releaseRoot(root.id); + } catch (error) { + if (!["unknown", "released"].includes((error as { code?: string }).code ?? "")) throw error; + // Release also fences a create that has not arrived at the manager yet. + await releaseRoot(root.id); + } + hiddenRoots.add(root.id); + pendingPublications.delete(root.id); + } /** One change at a time to a source's exposure: suspension, restoration, withdrawal and publication. */ const exposing = new Map>(); function exclusive(key: string, work: () => Promise): Promise { @@ -211,6 +228,7 @@ export function createReferenceSources(options: { if (!usable(source)) throw new ReferenceSourceError("unavailable", "No usable authorized reference source exists."); const key = sourceKey(source.domain, source.repository, source.revision); const fence = authorityFences.get(key) ?? 0; + const durable = sourceAuthority(db, source.domain, source.repository, source.revision); const assertAuthority = () => { if (closed) throw new ReferenceSourceError("unavailable", "Reference sources are closed."); if (fence !== (authorityFences.get(key) ?? 0) || withdrawn.has(key)) @@ -222,6 +240,8 @@ export function createReferenceSources(options: { throw new ReferenceSourceError("unauthorized", "This source publication is no longer authoritative."); if (suspended.has(key) || !validationLive(source) || !validationLive(current)) throw new ReferenceSourceError("unavailable", "This source's authority needs fresh validation."); + if (!sourceAuthorityCurrent(db, durable)) + throw new ReferenceSourceError("unauthorized", "A newer durable observation invalidated this source's authority."); authority?.(); }; leases.set(key, (leases.get(key) ?? 0) + 1); @@ -423,9 +443,9 @@ export function createReferenceSources(options: { /** Remove a source's name now; release its roots once no reader protects them. */ function withdraw(domain: string, repository: string, revision: string): Promise { const key = sourceKey(domain, repository, revision); - fenceSource(key); + const fenced = fenceSource(key); const running = withdrawals.get(key); - if (running) return running; + if (running) return Promise.all([running, fenced]).then(() => {}); // Fence before any await, even when the first publication has no catalog // row yet. A later acquisition waits for this withdrawal to finish. withdrawn.add(key); @@ -433,13 +453,12 @@ export function createReferenceSources(options: { // Observe the catalog after every already-dispatched publication settles, // including one whose native reply or database receipt was still pending. const work = exclusive(key, async () => { + await fenced; const source = row(domain, repository, revision); - if (source) { - const { roots, view } = await write<{ roots: { id: string }[]; view: { id: string } }>("sourceWithdraw", domain, repository, revision, randomUUID()); - await pool.poolUnpublish(view.id, source.name); - // Every root leaves the view at once, so no reader reaches it by identity; storage waits for readers. - for (const root of roots) await hideRoot(root.id); - } + const { roots, view } = await write<{ roots: { id: string; state: string }[]; view: { id: string } }>("sourceWithdraw", domain, repository, revision, randomUUID()); + if (source) await pool.poolUnpublish(view.id, source.name); + // Include another owner's staging row, even before a source catalog exists. + for (const root of roots) await hideRecordedRoot(root); // A first publication can have native exposure but still be staging in // SQLite. Hide it here too, without waiting for storage reclamation. for (const [id, publication] of pendingPublications) if (publication.key === key) { @@ -450,15 +469,17 @@ export function createReferenceSources(options: { withdrawals.set(key, work); return work.then(() => settle(domain, repository, revision)); } - function fenceSource(key: string): void { + function fenceSource(key: string): Promise { authorityFences.set(key, (authorityFences.get(key) ?? 0) + 1); + const [domain, repository, revision] = splitKey(key); + return write("sourceFence", domain, authorityRepository(repository), revision, randomUUID()); } /** Repository metadata governs every cached or in-flight revision, not only the requested one. */ function repositoryKeys(domain: string, repository: string, revision: string): string[] { const keys = new Set([sourceKey(domain, repository, revision)]); const equivalent = (candidate: string) => { if (candidate === repository) return true; - try { return githubReferenceRepository(candidate).canonical === repository; } catch { return false; } + try { return authorityRepository(candidate) === repository; } catch { return false; } }; for (const row of db.query(`SELECT repository, revision FROM reference_sources WHERE domain = ? UNION SELECT repository, revision FROM reference_roots WHERE domain = ?`).all(domain, domain) as { repository: string; revision: string }[]) @@ -469,18 +490,20 @@ export function createReferenceSources(options: { } return [...keys]; } - function withdrawRepository(domain: string, repository: string, revision: string): Promise { + async function withdrawRepository(domain: string, repository: string, revision: string): Promise { + await fenceSource(sourceKey(domain, repository, "")); return Promise.all(repositoryKeys(domain, repository, revision).map(key => withdraw(...splitKey(key)))); } - function suspendRepository(domain: string, repository: string, revision: string): Promise { + async function suspendRepository(domain: string, repository: string, revision: string): Promise { + await fenceSource(sourceKey(domain, repository, "")); const keys = repositoryKeys(domain, repository, revision); - for (const key of keys) fenceSource(key); + await Promise.all(keys.map(key => fenceSource(key))); return Promise.all(keys.map(key => suspendSource(...splitKey(key)))); } async function acquire(signal: AbortSignal, input: { domain: string; principalId: string | null; repository: ReferenceRepository; revision: string; grant: ReferenceGrant | null; credential: string | null; ref: string; expectedCommit: string; previous: SourceRow | null; - managed?: { access: GitHubAccess; context: ReferenceAcquisitionContext; id: string; assertCurrent(): void; containFailure(error: unknown, publishing: boolean): Promise } }) { + managed?: { access: GitHubAccess; context: ReferenceAcquisitionContext; id: string; authority: SourceAuthority; assertCurrent(): void; containFailure(error: unknown, publishing: boolean, publicationId?: string): Promise } }) { const { domain, repository, revision } = input, key = sourceKey(domain, repository.canonical, revision); const name = referenceSourceName(repository, revision), view = await viewFor(domain); const staging = { id: randomUUID() }; @@ -531,7 +554,8 @@ export function createReferenceSources(options: { grantId: input.managed.access.grantId, networkBytes: input.managed.access.bytes().chargedBytes, at: now() }; } const at = now(), grantId = domain === PUBLIC ? null : (input.grant && isLiveReferenceGrant(db, input.grant.id, at) ? input.grant.id : authorize(domain, input.principalId, repository)!.id); - await write("sourcePublish", dirname(published.path!), domain, repository.canonical, revision, repository.url, name, staging.id, commit, input.ref, grantId, at, acquisition); + if (!await write("sourcePublish", dirname(published.path!), domain, repository.canonical, revision, repository.url, name, staging.id, commit, input.ref, grantId, at, acquisition, input.managed?.authority)) + throw new ReferenceSourceError("unauthorized", "A newer durable authority observation refused this publication."); recheck(); pendingPublications.delete(staging.id); withdrawn.delete(key); @@ -544,7 +568,7 @@ export function createReferenceSources(options: { } }); } catch (error) { - if (input.managed) await input.managed.containFailure(error, publishing) + if (input.managed) await input.managed.containFailure(error, publishing, staging.id) .catch(cleanup => warn("reference authority containment is incomplete; bind preparation retries it", cleanup)); else if (publishing && (failureReason(error) === "denied" || failureReason(error) === "unauthorized")) await withdraw(domain, repository.canonical, revision).catch(cleanup => warn("revoked reference publication could not be hidden", cleanup)); @@ -574,8 +598,14 @@ export function createReferenceSources(options: { const id = randomUUID(); const publicFence = authorityFences.get(sourceKey(PUBLIC, repository.canonical, revision)) ?? 0; const privateFence = authorityFences.get(sourceKey(privateDomain(input.principalId), repository.canonical, revision)) ?? 0; + const publicRepositoryFence = authorityFences.get(sourceKey(PUBLIC, repository.canonical, "")) ?? 0; + const privateRepositoryFence = authorityFences.get(sourceKey(privateDomain(input.principalId), repository.canonical, "")) ?? 0; + const publicAuthority = sourceAuthority(db, PUBLIC, repository.canonical, revision); + const privateAuthority = sourceAuthority(db, privateDomain(input.principalId), repository.canonical, revision); const assertFence = (domain: string) => { - if ((authorityFences.get(sourceKey(domain, repository.canonical, revision)) ?? 0) !== (domain === PUBLIC ? publicFence : privateFence)) + if ((authorityFences.get(sourceKey(domain, repository.canonical, revision)) ?? 0) !== (domain === PUBLIC ? publicFence : privateFence) + || (authorityFences.get(sourceKey(domain, repository.canonical, "")) ?? 0) !== (domain === PUBLIC ? publicRepositoryFence : privateRepositoryFence) + || !sourceAuthorityCurrent(db, domain === PUBLIC ? publicAuthority : privateAuthority)) controller.abort(new ReferenceSourceError("unauthorized", "A newer authority observation fenced this reference source.")); }; const operation: Operation = { key: sourceKey(PUBLIC, repository.canonical, revision), domain: PUBLIC, principalId: input.principalId, @@ -583,7 +613,7 @@ export function createReferenceSources(options: { const assertTurn = () => { signal.throwIfAborted(); if (closed || !context.current()) throw new ReferenceSourceError("cancelled", "The acquiring turn is no longer available."); }; let result: ReferenceSourceLease | undefined; let accessOpened = false, openAttempted = false, containment: Promise | undefined; - const containFailure = (error: unknown, publishing: boolean): Promise => { + const containFailure = (error: unknown, publishing: boolean, publicationId?: string): Promise => { if (containment) return containment; const reason = failureReason(error), domains = [PUBLIC, privateDomain(input.principalId)]; let work: Promise = Promise.resolve(); @@ -597,8 +627,13 @@ export function createReferenceSources(options: { // Wire shutdown may outlive the lease's validation. A newer live // validation wins when this expiry cleanup reaches the exposure lock. work = suspendSource(operation.domain, repository.canonical, revision, true); - } else if (publishing) { - work = withdraw(operation.domain, repository.canonical, revision); + } else if (publishing && publicationId) { + // Cleanup is not a new metadata observation. Discard just this + // attempt; another owner may already have published a valid root. + work = (async () => { + const root = await write<{ id: string; state: string } | null>("sourceDiscard", publicationId); + await hideRecordedRoot(root ?? { id: publicationId, state: "staging" }); + })(); } else if (!signal.aborted && context.current() && openAttempted && !accessOpened) { work = Promise.all(domains.map(domain => suspendRepository(domain, repository.canonical, revision))); } @@ -645,14 +680,17 @@ export function createReferenceSources(options: { await access!.revalidate(); assertCurrent(); const at = now(); - await write("sourceValidate", at, at, check.ref, domain, repository.canonical, revision); + if (!await write("sourceValidate", at, at, check.ref, domain, repository.canonical, revision, + domain === PUBLIC ? publicAuthority : privateAuthority, current.root_id)) + throw new ReferenceSourceError("unauthorized", "A newer durable authority observation refused this validation."); assertCurrent(); reused = true; }); } if (!reused) await acquire(signal, { domain, principalId: input.principalId, repository, revision, grant: domain === PUBLIC ? null : authorize(domain, input.principalId, repository), credential: null, - ref: check.ref, expectedCommit: check.commit, previous, managed: { access, context, id, assertCurrent, containFailure } }); + ref: check.ref, expectedCommit: check.commit, previous, managed: { access, context, id, + authority: domain === PUBLIC ? publicAuthority : privateAuthority, assertCurrent, containFailure } }); assertCurrent(); const current = row(domain, repository.canonical, revision); if (!usable(current)) throw new ReferenceSourceError("unavailable", "Managed source publication is unavailable."); @@ -742,13 +780,13 @@ export function createReferenceSources(options: { return exclusive(key, async () => { const source = row(domain, repository, revision); if (onlyExpired && (!source || validationLive(source))) return; - const roots = db.query("SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ? AND state != 'staging'").all(domain, repository, revision) as { id: string }[]; + const roots = db.query("SELECT id, state FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ?").all(domain, repository, revision) as { id: string; state: string }[]; const pending = [...pendingPublications].filter(([, publication]) => publication.key === key); if ((!source?.root_id && !roots.length && !pending.length) || (suspended.has(key) && !unsettled.has(key) && !pending.length)) return; suspended.add(key); unsettled.add(key); await write("sourceSuspend", domain, repository, revision); if (source) await pool.poolUnpublish((await viewFor(domain)).id, source.name); - for (const root of roots) await hideRoot(root.id); + for (const root of roots) await hideRecordedRoot(root); for (const [id, publication] of pending) { await pool.poolUnpublish(publication.view, publication.name); await hideRoot(id); diff --git a/packages/ui-server/tests/github-reference-access.test.ts b/packages/ui-server/tests/github-reference-access.test.ts index 8a5632f616..cc8fbbcc3e 100644 --- a/packages/ui-server/tests/github-reference-access.test.ts +++ b/packages/ui-server/tests/github-reference-access.test.ts @@ -55,6 +55,45 @@ async function fixture(options: { async close() { egress.stop(); server.stop(true); db.close(); } }; } +test("a missing suffix repository cannot dispatch metadata credentials to its neighbor", async () => { + const f = await fixture({ metadata: request => { + if (new URL(request.url).pathname === "/repos/odysseus/ithaca.git" || !request.headers.has("authorization")) return new Response(null, { status: 404 }); + return Response.json(identity(true)); + } }); + f.grant({ repositoryPrefix: "https://github.com/odysseus/ithaca.git.git" }); + try { + const pending = f.service().open({ ...f.bounds, principalId: f.agent.id, repository: "odysseus/ithaca.git.git", revision: "main" }); + try { await expect(pending, "SUFFIX_GRANT_CANNOT_OPEN_NEIGHBOR_METADATA").rejects.toMatchObject({ reason: "denied" }); } + finally { await pending.then(value => value.close(), () => {}); } + expect(f.received, "SUFFIX_CREDENTIAL_DISPATCH_RETAINS_REQUESTED_REPOSITORY").toEqual([ + { path: "/repos/odysseus/ithaca.git", authorization: null }, + { path: "/repos/odysseus/ithaca.git", authorization: `Bearer ${token}` }, + ]); + expect(f.git).toEqual([]); + } finally { await f.close(); } +}); + +test("a literal suffix stays bound across metadata, Git wiring and final validation", async () => { + const f = await fixture({ metadata: request => !request.headers.has("authorization") ? new Response(null, { status: 404 }) + : Response.json({ ...identity(true), name: "Ithaca.git", full_name: "Odysseus/Ithaca.git", + clone_url: "https://github.com/Odysseus/Ithaca.git.git", url: "https://api.github.com/repos/Odysseus/Ithaca.git" }) }); + f.grant({ repositoryPrefix: "https://github.com/odysseus/ithaca.git.git" }); + try { + const pending = f.service().open({ ...f.bounds, principalId: f.agent.id, repository: "odysseus/ithaca.git.git", revision: "main" }); + await expect(pending, "SUFFIX_ACQUISITION_RETAINS_LITERAL_IDENTITY").resolves.toMatchObject({ identity: { repository: "ithaca.git" } }); + const access = await pending; + try { + await access.resolve(); await access.fetch("/unused"); + await expect(access.revalidate(), "SUFFIX_FINAL_METADATA_RETAINS_LITERAL_IDENTITY").resolves.toBeUndefined(); + expect(f.received.every(value => value.path === "/repos/odysseus/ithaca.git"), "SUFFIX_METADATA_NEVER_SELECTS_NEIGHBOR").toBe(true); + for (const input of f.git) expect(input, "SUFFIX_GIT_WIRE_MATCHES_REQUESTED_REPOSITORY").toMatchObject({ + repository: { canonical: "https://github.com/odysseus/ithaca.git", url: "https://github.com/odysseus/ithaca.git.git" }, + wire: { repository: "https://github.com/odysseus/ithaca.git" }, + }); + } finally { await access.close(); } + } finally { await f.close(); } +}); + test("public identity and scripted Git binding stay anonymous even with a host token and covering private grant", async () => { const f = await fixture(); f.grant(); try { diff --git a/packages/ui-server/tests/reference-source-authority.test.ts b/packages/ui-server/tests/reference-source-authority.test.ts new file mode 100644 index 0000000000..70308e3979 --- /dev/null +++ b/packages/ui-server/tests/reference-source-authority.test.ts @@ -0,0 +1,54 @@ +import { afterEach, expect, test } from "bun:test"; +import { createUiDb } from "../src/db/client"; +import { sourceAuthority, sourceAuthorityCurrent } from "../src/brain/reference-source-authority"; +import { sourceWrites } from "../src/brain/reference-source-writes"; + +const repository = "https://github.com/odysseus/ithaca", at = Date.parse("2026-07-12T12:00:00Z"); +const db = createUiDb(":memory:"), writes = sourceWrites(db); +afterEach(() => { db.exec("DELETE FROM reference_acquisitions; DELETE FROM reference_roots; DELETE FROM reference_sources; DELETE FROM reference_authority_fences;"); }); + +test("a repository observation fences every revision in just its own sharing domain", () => { + const main = sourceAuthority(db, "public", repository, "main"), other = sourceAuthority(db, "public", repository, "return-home"); + const privateSource = sourceAuthority(db, "private:penelope", repository, "main"); + writes.sourceFence("public", repository, "", "odysseus-first-observation"); + expect(sourceAuthorityCurrent(db, main), "SHARED_REPOSITORY_FENCE_INVALIDATES_MAIN").toBe(false); + expect(sourceAuthorityCurrent(db, other), "SHARED_REPOSITORY_FENCE_INVALIDATES_OTHER_REVISION").toBe(false); + expect(sourceAuthorityCurrent(db, privateSource), "SHARED_FENCE_PRESERVES_OTHER_DOMAIN").toBe(true); + const fresh = sourceAuthority(db, "public", repository, "main"); + expect(sourceAuthorityCurrent(db, fresh)).toBe(true); + writes.sourceFence("public", repository, "main", "odysseus-missing-ref"); + expect(sourceAuthorityCurrent(db, fresh)).toBe(false); + expect(sourceAuthorityCurrent(db, sourceAuthority(db, "public", repository, "return-home"))).toBe(true); +}); + +test("a canonical literal suffix is separate from its neighbor in shared authority", () => { + const suffix = `${repository}.git`, expected = sourceAuthority(db, "public", suffix, "main"); + writes.sourceFence("public", repository, "", "odysseus-neighbor-observation"); + expect(sourceAuthorityCurrent(db, expected), "SHARED_AUTHORITY_RETAINS_LITERAL_SUFFIX").toBe(true); + writes.sourceFence("public", suffix, "", "odysseus-suffix-observation"); + expect(sourceAuthorityCurrent(db, expected)).toBe(false); +}); + +test("the publication transaction refuses authority invalidated after submission", () => { + writes.sourceStage("odysseus-root", "public", repository, "main", at); + const expected = sourceAuthority(db, "public", repository, "main"); + writes.sourceFence("public", repository, "", "odysseus-newer-private-observation"); + expect(writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", `${repository}.git`, "ithaca", "odysseus-root", "a".repeat(40), "refs/heads/main", null, at, undefined, expected), + "PUBLICATION_COMMIT_RECHECKS_SHARED_AUTHORITY").toBe(false); + expect(db.query("SELECT 1 FROM reference_sources").get()).toBeNull(); + const current = sourceAuthority(db, "public", repository, "main"); + expect(writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", `${repository}.git`, "ithaca", "odysseus-root", "a".repeat(40), "refs/heads/main", null, at, undefined, current)).toBe(true); +}); + +test("the validation transaction cannot renew a durably invalidated or replaced source", () => { + writes.sourceStage("odysseus-root", "public", repository, "main", at); + writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", `${repository}.git`, "ithaca", "odysseus-root", "a".repeat(40), "refs/heads/main", null, at); + const expected = sourceAuthority(db, "public", repository, "main"); + writes.sourceFence("public", repository, "", "odysseus-unknown-metadata"); writes.sourceSuspend("public", repository, "main"); + expect(writes.sourceValidate(at + 1, at + 1, "refs/heads/main", "public", repository, "main", expected, "odysseus-root"), + "VALIDATION_COMMIT_RECHECKS_SHARED_AUTHORITY").toBe(false); + expect(db.query("SELECT validated_at FROM reference_sources").get()).toEqual({ validated_at: 0 }); + const fresh = sourceAuthority(db, "public", repository, "main"); + expect(writes.sourceValidate(at + 1, at + 1, "refs/heads/main", "public", repository, "main", fresh, "telemachus-root"), "VALIDATION_COMMIT_RETAINS_ROOT_BINDING").toBe(false); + expect(writes.sourceValidate(at + 1, at + 1, "refs/heads/main", "public", repository, "main", fresh, "odysseus-root")).toBe(true); +}); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index d7c317dd07..9327b9a375 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -777,6 +777,92 @@ describe("live managed authority", () => { } finally { if (first) await worktrees.closeGeneration(first.id); if (other) await worktrees.closeGeneration(other.id); await worktrees.close(); await f.close(); } }); + for (const observation of ["private", "unknown"] as const) + for (const revision of ["main", "return-home"]) + test(`another source service fences a first ${revision} publication after ${observation} metadata`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; + let path = "", paused = false; + f.pool.poolPublish = async (...args) => { + const result = await publish(...args); + if (!paused) { paused = true; path = join(result.path!, "README.md"); arrived.resolve(); await resume.promise; } + return result; + }; + const older = f.sources.request({ principalId: f.owner.id, repository, revision, + acquisition: { turnId: "odysseus-first-publication", egress: f.egress, current: () => true } }) + .then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; + expect(readFileSync(path, "utf8")).toContain("Odysseus"); + expect(f.db.query("SELECT 1 FROM reference_sources").get()).toBeNull(); + if (observation === "private") f.state.private = true; else f.state.status = 503; + await expect(otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-newer-metadata", egress: f.secondEgress, current: () => true } })) + .rejects.toMatchObject({ code: observation === "private" ? "unauthorized" : "unavailable" }); + expect(existsSync(path), "OTHER_SERVICE_HIDES_PENDING_FIRST_PUBLICATION").toBe(false); + resume.resolve(); + const result = await older; + expect(result.lease, "DURABLE_FENCE_REFUSES_OLDER_FIRST_PUBLICATION").toBeUndefined(); + expect(result.error).toMatchObject({ code: "unauthorized" }); + expect(f.db.query("SELECT 1 FROM reference_sources WHERE root_id IS NOT NULL").get(), "OLDER_PUBLICATION_CANNOT_RECREATE_CATALOG").toBeNull(); + } finally { + resume.resolve(); (await older).lease?.release(); await otherSources.close(); otherDb.close(); await f.close(); + } + }); + + test("another source owner retires a sealed staging identity before its delayed native publication", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; + let exposed = false, id = ""; + f.pool.poolPublish = async (...args) => { id = args[0]; arrived.resolve(); await resume.promise; const result = await publish(...args); exposed = true; return result; }; + const older = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; f.state.status = 503; + await expect(otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-delayed-native-observation", egress: f.secondEgress, current: () => true } })).rejects.toMatchObject({ code: "unavailable" }); + expect(f.pool.records.get(id)?.state, "INVALIDATED_SEALED_STAGING_IDENTITY_IS_RETIRED").toBe("reclaimed"); + resume.resolve(); const result = await older; + expect(result.lease).toBeUndefined(); expect(result.error).toBeDefined(); + expect(exposed, "DELAYED_NATIVE_PUBLICATION_CANNOT_EXPOSE_INVALIDATED_ROOT").toBe(false); + } finally { resume.resolve(); (await older).lease?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + + test("an older fenced publisher cannot hide another service's fresh replacement", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; + let paused = false, current: Awaited> | undefined; + f.pool.poolPublish = async (...args) => { const result = await publish(...args); if (!paused) { paused = true; arrived.resolve(); await resume.promise; } return result; }; + const older = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; f.state.status = 503; + await expect(otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-unknown-observation", egress: f.secondEgress, current: () => true } })).rejects.toMatchObject({ code: "unavailable" }); + f.state.status = 200; + current = await otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-new-valid-publication", egress: f.secondEgress, current: () => true } }); + resume.resolve(); const result = await older; + expect(result.error).toMatchObject({ code: "unauthorized" }); + expect(existsSync(join(current.viewPath, current.name, "README.md")), "OLDER_FENCED_PUBLISHER_PRESERVES_OTHER_SERVICE_PUBLICATION").toBe(true); + expect(readFileSync(join(current.viewPath, current.name, "README.md"), "utf8")).toContain("Odysseus"); + expect(() => current!.assertAuthority(), "OLDER_CLEANUP_CANNOT_REVOKE_NEW_PUBLICATION").not.toThrow(); + } finally { resume.resolve(); (await older).lease?.release(); current?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + + test("fresh validation cannot revive another service's invalidated older lease", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + let held: Awaited> | undefined, current: typeof held; + const request = () => otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-shared-validation", egress: f.secondEgress, current: () => true } }); + try { + held = await f.request(); f.state.status = 503; + await expect(request()).rejects.toMatchObject({ code: "unavailable" }); + f.state.status = 200; current = await request(); + expect(current.rootId).toBe(held.rootId); + expect(() => held!.assertAuthority(), "DURABLE_GENERATION_CANNOT_REVIVE_INVALIDATED_LEASE").toThrow(); + expect(() => current!.assertAuthority(), "NEW_DURABLE_GENERATION_RETAINS_VALID_LEASE").not.toThrow(); + } finally { current?.release(); held?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + for (const observation of ["private", "unknown", "replacement"] as const) for (const wait of ["coverage", "native-grant", "held-refresh"] as const) test(`another source service's ${observation} observation fences a worktree during ${wait}`, async () => { diff --git a/packages/ui-server/tests/reference-writes-offloop.test.ts b/packages/ui-server/tests/reference-writes-offloop.test.ts index 46ec7fd6da..f9d7621e47 100644 --- a/packages/ui-server/tests/reference-writes-offloop.test.ts +++ b/packages/ui-server/tests/reference-writes-offloop.test.ts @@ -290,6 +290,7 @@ test("source refresh, failed-refresh bookkeeping, bind-time revalidation and sup test("revocation sees a first private publication submitted before it and withdraws it after its commit", async () => { const f = await fixture(); + const fences = await watchWriteSites(f.db, f.writer, ["reference_authority_fences"]); try { f.state.private = true; const publish = f.pool.poolPublish; @@ -311,6 +312,7 @@ test("revocation sees a first private publication submitted before it and withdr expect(f.db.query("SELECT root_id FROM reference_sources WHERE root_id IS NOT NULL").all(), "REFERENCE_REVOCATION_WITHDRAWS_FIRST_PUBLICATION").toEqual([]); expect(f.db.query("SELECT id FROM reference_roots").all(), "REFERENCE_REVOKED_ROOT_RELEASE_COMMITTED").toEqual([]); expect(f.pool.events.map(event => event.operation), "REFERENCE_REVOKED_SOURCE_UNPUBLISHED").toContain("unpublish"); + expect(await fences.log(), "REFERENCE_AUTHORITY_FENCES_COMMIT_ON_FULL_WORKER").toContain("reference_authority_fences"); } finally { await f.close(); } }); From 644803bb5ffb4b22d315f3dec041ed24d4af2c66 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 08:55:13 +0000 Subject: [PATCH 21/27] fix(ui-server): include staged sources in cross-owner revocation --- docs/decisions/managed-worktrees.md | 2 +- docs/decisions/reference-source-acquisition.md | 2 +- .../ui-server/src/brain/reference-source.ts | 6 ++++-- .../tests/reference-source-managed.test.ts | 17 +++++++++++++++++ 4 files changed, 23 insertions(+), 4 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 804ca911be..13f02917d6 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1049-1080`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1051-1082`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 7a0e411e51..ec33de413e 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -283,7 +283,7 @@ recorded source survives only if its sealed root still exists, its name can be published again (which repairs a publication whose reply was lost) and, when private, a live grant still covers it. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:979-1023`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:981-1025`). ## Evidence diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 2d13429b9d..6b0c1f9bc2 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -964,8 +964,10 @@ export function createReferenceSources(options: { // Wait for its receipt so even a source's first publication is withdrawn. await write.settled(); for (const principalId of principals) { - const sources = db.query("SELECT * FROM reference_sources WHERE domain = ?").all(privateDomain(principalId)) as SourceRow[]; - for (const source of sources) keys.add(sourceKey(source.domain, source.repository, source.revision)); + const sources = db.query(`SELECT repository, revision FROM reference_sources WHERE domain = ? + UNION SELECT repository, revision FROM reference_roots WHERE domain = ?`) + .all(privateDomain(principalId), privateDomain(principalId)) as { repository: string; revision: string }[]; + for (const source of sources) keys.add(sourceKey(privateDomain(principalId), source.repository, source.revision)); } for (const key of keys) { const [domain, repository, revision] = splitKey(key), principalId = domain.slice("private:".length); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 9327b9a375..c3270d1c88 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -810,6 +810,23 @@ describe("live managed authority", () => { } }); + test("another source owner revokes the grant of a first private publication before its catalog receipt", async () => { + const f = await fixture({ private: true }), issued = f.grant(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; + let path = ""; + f.pool.poolPublish = async (...args) => { const result = await publish(...args); path = join(result.path!, "README.md"); arrived.resolve(); await resume.promise; return result; }; + const older = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; + expect(f.db.query("SELECT 1 FROM reference_sources").get()).toBeNull(); + revokeReferenceGrant(otherDb, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); + await otherSources.revoke({ grantIds: [issued.id], principalIds: [] }); + expect(existsSync(path), "OTHER_OWNER_REVOCATION_HIDES_PENDING_PRIVATE_PUBLICATION").toBe(false); + resume.resolve(); + expect((await older).error).toMatchObject({ code: "unauthorized" }); + } finally { resume.resolve(); (await older).lease?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + test("another source owner retires a sealed staging identity before its delayed native publication", async () => { const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; From abcce4d59725c209525f46254b59877e946e2fb0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 11:13:11 +0000 Subject: [PATCH 22/27] CONTRACT: fence managed source publication after permanent withdrawal --- .../managed-reference-source-authority.md | 2 + api-report/ui-server.txt | 3 +- docs/decisions/managed-worktrees.md | 8 +- docs/decisions/reference-pool-accounting.md | 6 +- .../decisions/reference-source-acquisition.md | 37 +++-- docs/decisions/reference-source-grants.md | 4 +- docs/integration-contract/package-api.md | 15 ++ docs/plans/chat-history-deletion.md | 2 +- .../src/server/native-brain-manager-client.ts | 4 +- .../server/native-brain-manager-protocol.ts | 4 +- .../src/server/native-reference-pool.ts | 39 ++++- .../ui-sdk/tests/native-brain-manager.test.ts | 20 +++ .../src/brain/github-reference-access.ts | 4 + .../src/brain/native-brain-leases.ts | 7 +- .../src/brain/reference-source-writes.ts | 22 ++- .../ui-server/src/brain/reference-source.ts | 132 ++++++++++----- .../src/brain/reference-worktrees.ts | 4 +- packages/ui-server/src/db/reference-grants.ts | 6 + .../tests/helpers/reference-pool-double.ts | 6 +- .../tests/native-brain-leases.test.ts | 14 ++ .../tests/reference-source-authority.test.ts | 15 ++ .../tests/reference-source-managed.test.ts | 150 ++++++++++++++++-- .../ui-server/tests/reference-tools.test.ts | 7 +- scripts/native-proof/reference-pool.native.ts | 32 ++++ 24 files changed, 449 insertions(+), 94 deletions(-) diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md index 45881b378b..776c7b133e 100644 --- a/.changeset/managed-reference-source-authority.md +++ b/.changeset/managed-reference-source-authority.md @@ -4,3 +4,5 @@ --- Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. Keep stored canonical grant suffixes literal during lookup and duplicate checks, so a repository grant cannot authorize a neighboring repository. Waiting worktree effects reread shared source authority, including durable invalidation by another app or cron owner. Shared repository/revision invalidation versions also fence first publication across app and cron owners, with validation/publication commit checks and retirement of invalidated sealed staging identities. Failed-attempt cleanup preserves another owner's newer publication. Metadata and Git wiring preserve the requested repository's literal canonical suffix, including when metadata reports it missing. + +Keep stored worktree repository keys separate from raw clone input so revocation cannot borrow a neighboring repository's grant. Managed roots opt into durable, permanent native publication withdrawal: delayed publication cannot revive a revoked identity, while fresh authorized acquisition uses a new root and legacy withdrawal stays reversible. Recovery keeps invalidated roots masked, and committing a shared invalidation atomically expires matching cached validation. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index a434b80450..c1f653e2d1 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1696,6 +1696,7 @@ signatures (every public export and the types it is made of) NativePoolRecord (packages/ui-sdk/src/server/native-brain-manager-protocol.ts) export interface NativePoolRecord { id: string; + publicationRevoked?: boolean; purpose: "source" | "worktree" | "staging" | "checkpoint"; from: string | null; allowanceBytes: number; @@ -2564,7 +2565,7 @@ signatures (every public export and the types it is made of) poolAccessClose: (access: string, signal?: AbortSignal) => Promise; poolAccessOpen: (access: string, signal?: AbortSignal) => Promise; poolCheckpoint: (id: string, from: string, signal?: AbortSignal) => Promise; - poolCreate: (id: string, purpose: NativePoolCreatePurpose, from: null | string, allowanceBytes: number, signal?: AbortSignal) => Promise; + poolCreate: (id: string, purpose: NativePoolCreatePurpose, from: null | string, allowanceBytes: number, signal?: AbortSignal, permanentWithdrawal?: true) => Promise; poolDelta: (from: string, to: string, signal?: AbortSignal) => Promise; poolGrowth: (signal?: AbortSignal) => Promise; poolListCheckpoint: (id: string, path: string, expectedWorkerUid: number, signal?: AbortSignal) => Promise; diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 13f02917d6..caea92083b 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1051-1082`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1107-1138`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:853-891`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:902-940`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:778-795`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:814-831`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:897-906`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:946-955`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index 96c63383d4..d1985656d7 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -8,7 +8,7 @@ actual allocated disk. That decision left the mechanism to implementation. This record names the mechanism, the primary sources it relies on and the native observations that qualified it. The pool is managed by the existing host-only native manager -(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:380-1129`). +(`createNativeReferencePool`, `packages/ui-sdk/src/server/native-reference-pool.ts:381-1130`). No consumer uses it yet. ## A separate volume, not another subvolume of the brain store @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:1096-1099`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:1119-1122`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). @@ -292,7 +292,7 @@ found three reasons, each a conflict with a rule above: happened, and frees nothing while the older checkpoint lives. Residual growth is reported instead, by `brain-native-store pool growth` -(`referencePoolGrowth`, `packages/ui-sdk/src/server/native-reference-pool.ts:266-338`). +(`referencePoolGrowth`, `packages/ui-sdk/src/server/native-reference-pool.ts:267-339`). It reads one stable observation and the same owner charges as admission, with no reconciliation, so it commits, deletes, resets and reserves nothing. Every source chain starts at a cold acquisition, a source with no `from`. The charge diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index ec33de413e..6ed8f0c4ab 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:99-907`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:102-910`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:352-401`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:355-404`). - Inside both windows a request reuses the published source without any network call. @@ -116,7 +116,17 @@ default to five minutes and are configured separately withholds cached and pending native exposure, including before a first catalog row exists. Final metadata failures are contained before staging cleanup; ending the turn during cleanup cannot undo that observation. A later valid - metadata check may restore the withheld cache. + metadata check may acquire a fresh root from the retained sealed bytes. + Managed roots opt into native permanent withdrawal when created. Once + withdrawn, their identity can never publish again; a new authorized request + obtains a different root. This closes delayed native restoration after a + completed revocation without relying on a process-local lock or a check + after exposure. Valid, still-published roots retain normal cache reuse. + The shared fence transaction expires matching catalog validation atomically, + including aliases; recovery retains invalidated roots masked and charged + without spending network or republishing them. Native restart completes an + interrupted permanent withdrawal before admitting requests. Legacy roots + keep their prior semantics and cannot be reused as a managed cache entry. Suspension also expires the stored validation clock, so restart cannot republish uncertain authority into a newly bound view without fresh validation. Post-publication authority loss hides native exposure before @@ -140,7 +150,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:504-558`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:518-572`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -239,9 +249,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:292-307`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:295-310`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:310-335`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:313-338`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -263,7 +273,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:426-442`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:429-445`). There is no idle expiry. ## Revocation and recovery @@ -276,14 +286,17 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:951-976`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1000-1025`). The catalog lives in the UI database and is disposable bookkeeping. At start, a -recorded source survives only if its sealed root still exists, its name can be -published again (which repairs a publication whose reply was lost) and, when -private, a live grant still covers it. Every other owned source root is +recorded source survives only if its sealed root still exists and, when +private, a live grant still covers it. A source with live validation may have +its name repaired after a lost publication reply. Expired, durably suspended +or permanently withdrawn roots remain masked until a fresh authorized request; +startup never renews their authority or exposes them to already-bound views. +Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:981-1025`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1030-1074`). ## Evidence diff --git a/docs/decisions/reference-source-grants.md b/docs/decisions/reference-source-grants.md index b7de6a0d8a..14560ded72 100644 --- a/docs/decisions/reference-source-grants.md +++ b/docs/decisions/reference-source-grants.md @@ -28,7 +28,7 @@ The maintainer selected **owner-managed grant records** on 2026-10-22 ## The record A grant is one row of the UI database's `reference_grants` table -(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:129-157`). +(`createReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:135-163`). The table holds the served brain's identity, the principal, the canonical repository prefix, the credential name or null, the granting owner and the revocation time. It stores no credential value. A grant is **live** while it @@ -53,7 +53,7 @@ lowercases the origin and drops a trailing slash and one hosted `.git` clone suffix. A prefix covers itself and every path below it at a segment boundary, so `…/odysseus` never covers `…/odysseus-crew`. The longest covering live prefix wins, read at the moment of use -(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:177-188`). +(`coveringReferenceGrant`, `packages/ui-server/src/db/reference-grants.ts:183-194`). GitHub HTTPS paths are normalized to lowercase, matching the qualified transport. Retained mixed-case prefixes are normalized for matching and diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 2f14037e09..fd87331596 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4517,6 +4517,21 @@ directories, and a sealed root's top directory becomes `0755 root:root`. The mechanism is recorded in the [pool decision](../decisions/reference-pool-accounting.md#publication-views-2429). +Managed acquisition (#3613) opts a new source root into permanent withdrawal +with `poolCreate(id, purpose, from, allowanceBytes, signal?, true)` (the native +control request adds `permanentWithdrawal?: true`). Only `source` roots accept +the option. Their records include `publicationRevoked: false` initially; +`poolWithdraw` durably changes it to `true` under the publication mutation +lock before hiding the root. Every later `poolPublish` of that identity +refuses with `released`, even across restart. Interrupted withdrawal finishes +before the keeper serves requests. Retained sealed bytes stay charged and +may seed a newly authorized root with a different identity. An identity's +withdrawal mode cannot change on a create retry. Legacy calls and version-1 +roots retain reversible withdrawal. Opted-in roots use version-2 durable +intents, which older keepers refuse rather than ignoring the guard; older +strict control schemas also reject the new option before creating a root. +The managed host refuses missing support, without an unguarded fallback. + ### Reference source acquisition (additive, #2429) `ServerConfig.referenceSource?` is `{ validationMs, refreshMs, operations }`. diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index 9b12388913..e4b4ad6ba0 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -337,7 +337,7 @@ until genuine settlement, rather than authorizing their replacement `close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1474-1524`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, -`packages/ui-server/src/brain/native-brain-leases.ts:319-332`). A caller deadline +`packages/ui-server/src/brain/native-brain-leases.ts:320-333`). A caller deadline is not proof that native I/O stopped, cleanup succeeded or deletion completed. Keep the proposed partial/unknown outcome and identity fence while that cleanup remains owned; follow the existing [shutdown ownership contract](../decisions/sqlite-write-worker.md#bounded-caller-waits-retain-real-cleanup-ownership-3185). diff --git a/packages/ui-sdk/src/server/native-brain-manager-client.ts b/packages/ui-sdk/src/server/native-brain-manager-client.ts index 00f9d93519..2a1e9dd52f 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-client.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-client.ts @@ -295,8 +295,8 @@ export function createNativeBrainManagerClient(input: { socketPath: string; time poolStatus: async (signal?: AbortSignal): Promise => control({ operation: "poolStatus" }, signal), /** Read-only residual-growth status (#3515); reports measured charges and thresholds only. */ poolGrowth: async (signal?: AbortSignal): Promise => control({ operation: "poolGrowth" }, signal), - poolCreate: async (id: string, purpose: NativePoolCreatePurpose, from: string | null, allowanceBytes: number, signal?: AbortSignal): Promise => - control({ operation: "poolCreate", id, purpose, from, allowanceBytes }, signal), + poolCreate: async (id: string, purpose: NativePoolCreatePurpose, from: string | null, allowanceBytes: number, signal?: AbortSignal, permanentWithdrawal?: true): Promise => + control({ operation: "poolCreate", id, purpose, from, allowanceBytes, ...(permanentWithdrawal ? { permanentWithdrawal } : {}) }, signal), poolSeal: async (id: string, signal?: AbortSignal): Promise => control({ operation: "poolSeal", id }, signal), poolRelease: async (id: string, signal?: AbortSignal): Promise => control({ operation: "poolRelease", id }, signal), listPoolRecovery: async (after: string | null = null, signal?: AbortSignal): Promise<{ records: NativePoolRecord[]; next: string | null }> => diff --git a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts index a922065c61..08d9189672 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts @@ -36,7 +36,7 @@ export const nativeManagerRequest = z.discriminatedUnion("operation", [ // Read-only residual-growth status (#3515) over the same observation and owner charges. z.object({ operation: z.literal("poolGrowth") }).strict(), z.object({ operation: z.literal("poolCreate"), id: nativeCheckpointId, purpose: z.enum(["source", "worktree", "staging"]), - from: nativeCheckpointId.nullable(), allowanceBytes: z.number().int().positive() }).strict(), + from: nativeCheckpointId.nullable(), allowanceBytes: z.number().int().positive(), permanentWithdrawal: z.literal(true).optional() }).strict(), z.object({ operation: z.literal("poolSeal"), id: nativeCheckpointId }).strict(), z.object({ operation: z.literal("poolRelease"), id: nativeCheckpointId }).strict(), z.object({ operation: z.literal("listPoolRecovery"), after: nativeCheckpointId.nullable() }).strict(), @@ -145,6 +145,8 @@ export interface NativePoolRootIdentity { } export interface NativePoolRecord { id: string; + /** Present only on opted-in source roots. Once true, publication is permanently refused. */ + publicationRevoked?: boolean; /** `checkpoint` (#2430): a read-only snapshot of one writable worktree, created only by `poolCheckpoint`. */ purpose: "source" | "worktree" | "staging" | "checkpoint"; /** Pool root this one was snapshotted from (sealed, or the writable worktree of a checkpoint), or null for an empty root. */ diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index fc0b086c48..666e1ee877 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -19,7 +19,7 @@ import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { constants, closeSync, existsSync, fstatSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, renameSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync, ftruncateSync, chownSync, chmodSync, realpathSync } from "node:fs"; import { randomUUID } from "node:crypto"; -import { dirname, isAbsolute, join } from "node:path"; +import { basename, dirname, isAbsolute, join } from "node:path"; import { NativeBrainManagerError, nativeCheckpointId, nativePoolName, NATIVE_CONTROL_BYTES, REFERENCE_POOL_CHECKPOINT_BYTES, type NativePoolAccess, type NativePoolCheckpoint, type NativePoolRecord, type NativePoolGrowth, type NativePoolGrowthComparison, type NativePoolGrowthFlag, type NativePoolGrowthSources, type NativePoolSpace, type NativePoolState, type NativePoolStatus } from "./native-brain-manager-protocol.js"; @@ -134,7 +134,8 @@ export const reservePhysical = (bytes: number, factor: { numerator: number; deno bytes <= 0 ? 0 : Math.ceil(bytes * factor.numerator / factor.denominator); export interface PoolIntent extends NativePoolRecord { - version: 1; + /** Version 2 roots opt into permanent publication withdrawal; old keepers refuse them. */ + version: 1 | 2; fsid: string; /** Filesystem generation at reservation; an adopted root must be created at or after it. */ reservedGeneration: string; @@ -504,7 +505,9 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { // Roots sealed before the growth status (#3515) carry no seal-time charge. intent.sealedBytes ??= null; const root = intent.root; - if (intent.version !== 1 || intent.id !== id || intent.fsid !== pool.fsid || !STATES.includes(intent.state) || !PURPOSES.includes(intent.purpose) + if (!((intent.version === 1 && intent.publicationRevoked === undefined) + || (intent.version === 2 && intent.purpose === "source" && typeof intent.publicationRevoked === "boolean")) + || intent.id !== id || intent.fsid !== pool.fsid || !STATES.includes(intent.state) || !PURPOSES.includes(intent.purpose) || (intent.from !== null && !nativeCheckpointId.safeParse(intent.from).success) || !page(intent.allowanceBytes) || !digits(intent.reservedGeneration) || (root !== null && (!digits(root?.rootId) || !/^[0-9a-f]{32}$/.test(root?.uuid ?? "") || !digits(root?.otransid))) || (intent.ownerBytes !== null && !count(intent.ownerBytes)) || (intent.sealedBytes !== null && !count(intent.sealedBytes)) || (intent.reason !== null && typeof intent.reason !== "string") @@ -574,6 +577,16 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { if (!existsSync(path)) continue; const info = (await helper(["inspect", path])).value; if (info.rootId === intent.root?.rootId && info.uuid === intent.root?.uuid && !info.readOnly) await helper(["seal", path]); + if (intent.publicationRevoked && info.rootId === intent.root?.rootId && info.uuid === intent.root?.uuid) { + // Complete a withdrawal interrupted after its fence commit. Existing + // workers may already bind this view, so app recovery is too late. + const actualView = path === rootPath(intent.id) ? null : basename(dirname(path)); + const actual = { ...intent, view: actualView }; + await verifyRoot(actual); + if (intent.view) unlinkNames(intent.view, intent.id); + if (actualView) { unlinkNames(actualView, intent.id); await move(actual, null); } + else if (intent.view) await commit(actual, true); + } } } } catch (error) { index.close(); closeSync(stateFd); throw error; } @@ -748,7 +761,7 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { function publicRecord(intent: PoolIntent, owner?: number): NativePoolRecord { return { id: intent.id, purpose: intent.purpose, from: intent.from, allowanceBytes: intent.allowanceBytes, state: intent.state, root: intent.root, path: intent.state === "writable" || intent.state === "sealed" ? location(intent) : null, ownerBytes: owner ?? intent.ownerBytes, reason: intent.reason, view: intent.view, - access: intent.access }; + access: intent.access, ...(intent.publicationRevoked === undefined ? {} : { publicationRevoked: intent.publicationRevoked }) }; } async function verifyRoot(intent: PoolIntent, signal?: AbortSignal) { const info = (await helper(["inspect", location(intent)], signal)).value; @@ -756,12 +769,14 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { throw new NativeBrainManagerError("unknown", "Recorded reference pool root identity changed; no use or deletion is authorized."); return info as { readOnly: boolean; ctransid: string; parentUuid: string }; } - async function create(request: { id: string; purpose: NativePoolRecord["purpose"]; from: string | null; allowanceBytes: number }, signal?: AbortSignal): Promise { + async function create(request: { id: string; purpose: NativePoolRecord["purpose"]; from: string | null; allowanceBytes: number; permanentWithdrawal?: true }, signal?: AbortSignal): Promise { + if (request.permanentWithdrawal && request.purpose !== "source") throw new NativeBrainManagerError("invalid", "Permanent publication withdrawal applies only to source roots."); if ((request.purpose as string) === "checkpoint") throw new NativeBrainManagerError("invalid", "Worktree checkpoints are created only from their writable worktree."); if (!page(request.allowanceBytes) || request.allowanceBytes > pool.operationLimitBytes) throw new NativeBrainManagerError("capacity", "Requested reference allowance exceeds the configured per-operation allowance; nothing ran."); const existing = intents.get(request.id); - if (existing && (existing.purpose !== request.purpose || existing.from !== request.from || existing.allowanceBytes !== request.allowanceBytes)) + if (existing && (existing.purpose !== request.purpose || existing.from !== request.from || existing.allowanceBytes !== request.allowanceBytes + || (existing.publicationRevoked !== undefined) !== Boolean(request.permanentWithdrawal))) throw new NativeBrainManagerError("invalid", "An existing reference pool identity cannot change its purpose, source or allowance."); if (existing && ["deleting", "deleted", "reclaimed"].includes(existing.state)) throw new NativeBrainManagerError("released", "This reference pool identity was released; it cannot be recreated."); const measured = await measure(signal), refreshed = intents.get(request.id); @@ -781,7 +796,8 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { const needed = reservePhysical(request.allowanceBytes, measured.accounting.reservationFactor); if (needed > measured.accounting.availableBytes) throw new NativeBrainManagerError("capacity", `Reference pool combined allowance cannot reserve ${needed} physical bytes (${measured.accounting.availableBytes} available); nothing was admitted.`); - await commit({ version: 1, fsid: pool.fsid, id: request.id, purpose: request.purpose, from: request.from, allowanceBytes: request.allowanceBytes, state: "reserved", + await commit({ version: request.permanentWithdrawal ? 2 : 1, ...(request.permanentWithdrawal ? { publicationRevoked: false } : {}), + fsid: pool.fsid, id: request.id, purpose: request.purpose, from: request.from, allowanceBytes: request.allowanceBytes, state: "reserved", root: null, path: null, ownerBytes: null, reason: null, view: null, access: null, reservedGeneration: measured.observation.generation }, false); } const reserved = intents.get(request.id)!; @@ -911,6 +927,7 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { nativePoolName.parse(request.name); let intent = intents.get(request.id); if (!intent || intent.purpose !== "source") throw new NativeBrainManagerError("unknown", "Only a recorded reference source root can be published."); + if (intent.publicationRevoked) throw new NativeBrainManagerError("released", "This source root's publication authority was permanently withdrawn."); if (intent.state !== "sealed") throw new NativeBrainManagerError(["deleting", "deleted", "reclaimed"].includes(intent.state) ? "released" : "invalid", "Only a sealed reference source root can be published."); if (intent.view && intent.view !== request.view) throw new NativeBrainManagerError("invalid", "A published reference root belongs to exactly one view."); await verifyRoot(intent, signal); @@ -1080,8 +1097,14 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { * what they already hold; the root stays charged until released. */ async function withdraw(id: string, signal?: AbortSignal): Promise { - const intent = intents.get(id); + let intent = intents.get(id); if (!intent || intent.purpose !== "source") throw new NativeBrainManagerError("unknown", "Only a recorded reference source root can be withdrawn."); + // The manager serializes this durable fence with every publication. A + // delayed RPC cannot re-expose the retained root after withdrawal returns. + if (intent.publicationRevoked === false) { + await commit({ ...intent, publicationRevoked: true }, true); + intent = intents.get(id)!; + } if (!intent.view) return publicRecord(intent); if (intent.state !== "sealed") throw new NativeBrainManagerError("released", "Only a sealed published root can be withdrawn; release it instead."); await verifyRoot(intent, signal); diff --git a/packages/ui-sdk/tests/native-brain-manager.test.ts b/packages/ui-sdk/tests/native-brain-manager.test.ts index 2d2ba7f90d..15e97330d8 100644 --- a/packages/ui-sdk/tests/native-brain-manager.test.ts +++ b/packages/ui-sdk/tests/native-brain-manager.test.ts @@ -132,6 +132,26 @@ test("Unix park requests retain an optional native generation expectation", asyn expect(nativeManagerRequest.safeParse({ operation: "poolPark", id: ID, expectedAccess }).success, "NATIVE_PARK_EXPECTATION_IS_ONE_GENERATED_IDENTITY").toBe(false); }); +test("Unix source creation explicitly opts into permanent withdrawal without changing legacy calls", async () => { + const root = mkdtempSync(join(tmpdir(), "odysseus-native-withdrawal-")), socketPath = join(root, "manager.sock"); + cleanups.push(() => rmSync(root, { recursive: true, force: true })); + const requests: NativeManagerRequest[] = []; + const service = Bun.serve({ unix: socketPath, async fetch(request) { + const input = nativeManagerRequest.parse(await request.json()); requests.push(input); + return Response.json({ id: ID, ...(input.operation === "poolCreate" && input.permanentWithdrawal ? { publicationRevoked: false } : {}) }); + } }); + cleanups.push(() => service.stop(true)); + const client = createNativeBrainManagerClient({ socketPath, timeoutMs: 1000, maxDeltaBytes: 64 }); + expect(await client.poolCreate(ID, "source", null, 4096, undefined, true), "PERMANENT_WITHDRAWAL_RECEIPT_REACHES_CALLER").toMatchObject({ publicationRevoked: false }); + await client.poolCreate(SECOND, "source", null, 4096); + expect(requests, "PERMANENT_WITHDRAWAL_OPTION_REACHES_NATIVE_KEEPER").toEqual([ + { operation: "poolCreate", id: ID, purpose: "source", from: null, allowanceBytes: 4096, permanentWithdrawal: true }, + { operation: "poolCreate", id: SECOND, purpose: "source", from: null, allowanceBytes: 4096 }, + ]); + for (const permanentWithdrawal of [false, null, 1, "true"]) + expect(nativeManagerRequest.safeParse({ operation: "poolCreate", id: ID, purpose: "source", from: null, allowanceBytes: 4096, permanentWithdrawal }).success).toBe(false); +}); + test("lost Unix response is unknown and never an inferred absence or automatic retry", async () => { const root = mkdtempSync(join(tmpdir(), "odysseus-native-lost-")), socketPath = join(root, "manager.sock"); cleanups.push(() => rmSync(root, { recursive: true, force: true })); diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 50abb79404..8a75f33bbb 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -76,6 +76,9 @@ export function createGitHubReferenceAccess(options: { let result = await wire.metadata(null); if (result.status === 401 || result.status === 404) { await input.withdrawPublic?.(); + // That observation is already contained. A missing private grant + // is not a second metadata observation after the withdrawal waits. + openingMetadata = false; principal(input.principalId); grant = coveringReferenceGrant(options.db, { brain: options.brain, principalId: input.principalId, repository, now: now() }); if (!grant?.credential || grant.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) @@ -83,6 +86,7 @@ export function createGitHubReferenceAccess(options: { credential = options.credentials[grant.credential] ?? null; if (!credential) throw new ReferenceTransportError("unavailable", "the granted host credential is not configured"); authorize("metadata", true); + openingMetadata = true; result = await wire.metadata(credential); } authorize("metadata", credential !== null); diff --git a/packages/ui-server/src/brain/native-brain-leases.ts b/packages/ui-server/src/brain/native-brain-leases.ts index 472cf52c71..3f41f40da1 100644 --- a/packages/ui-server/src/brain/native-brain-leases.ts +++ b/packages/ui-server/src/brain/native-brain-leases.ts @@ -170,11 +170,12 @@ export async function createNativeBrainLeaseManager(raw: Client, options: { if (!mine(lease) && lease.state !== "deleting" && live(lease) !== false) throw new NativeBrainManagerError("unknown", "This turn tree is still held by another live app or cron owner."); return releaseOwned(lease, signal); }); }, - poolCreate(id, purpose, from, allowanceBytes, signal) { return operation(async () => { + poolCreate(id, purpose, from, allowanceBytes, signal, permanentWithdrawal) { return operation(async () => { signal?.throwIfAborted(); await leases.call("poolIntent", id, purpose, from, allowanceBytes); - const record = await raw.poolCreate(id, purpose, from, allowanceBytes, signal); - if (record.id !== id || record.purpose !== purpose || record.from !== from || record.allowanceBytes !== allowanceBytes || !["writable", "sealed"].includes(record.state)) + const record = await raw.poolCreate(id, purpose, from, allowanceBytes, signal, permanentWithdrawal); + if (record.id !== id || record.purpose !== purpose || record.from !== from || record.allowanceBytes !== allowanceBytes || !["writable", "sealed"].includes(record.state) + || (permanentWithdrawal && record.publicationRevoked !== false)) throw new NativeBrainManagerError("unknown", "Reference pool reply does not match its durable lease identity."); await run("UPDATE native_pool_leases SET state='held' WHERE id=? AND state='creating'", id); return record; diff --git a/packages/ui-server/src/brain/reference-source-writes.ts b/packages/ui-server/src/brain/reference-source-writes.ts index 52323db534..6cf0bb45b5 100644 --- a/packages/ui-server/src/brain/reference-source-writes.ts +++ b/packages/ui-server/src/brain/reference-source-writes.ts @@ -1,7 +1,7 @@ /** Reference catalog effects; acquisition and native pool calls stay with the caller (#2999). */ import type { Database } from "bun:sqlite"; import type { ReferenceAcquisition } from "./reference-acquisition.js"; -import { sourceAuthorityCurrent, type SourceAuthority } from "./reference-source-authority.js"; +import { authorityRepository, sourceAuthorityCurrent, type SourceAuthority } from "./reference-source-authority.js"; export function sourceWrites(db: Database) { function sourceView(domain: string, id: string): { id: string; hostPath: string | null } { @@ -13,8 +13,24 @@ export function sourceWrites(db: Database) { return { sourceView, sourceFence(domain: string, repository: string, revision: string, generation: string) { - db.query(`INSERT INTO reference_authority_fences (domain, repository, revision, generation) VALUES (?, ?, ?, ?) - ON CONFLICT (domain, repository, revision) DO UPDATE SET generation = excluded.generation`).run(domain, repository, revision, generation); + return db.transaction(() => { + db.query(`INSERT INTO reference_authority_fences (domain, repository, revision, generation) VALUES (?, ?, ?, ?) + ON CONFLICT (domain, repository, revision) DO UPDATE SET generation = excluded.generation`).run(domain, repository, revision, generation); + // A crash after this commit must not leave old positive validation + // available to startup recovery, including legacy GitHub casing aliases. + const matches = (source: { repository: string; revision: string }) => { + try { return (revision === "" || source.revision === revision) && authorityRepository(source.repository) === repository; } + catch { return false; } + }; + for (const source of db.query("SELECT repository, revision FROM reference_sources WHERE domain = ?").all(domain) as { repository: string; revision: string }[]) { + if (matches(source)) + db.query("UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ?").run(domain, source.repository, source.revision); + } + // Cleanup affects exactly the identities invalidated at this commit, + // never a fresh acquisition that publishes while native hiding waits. + return (db.query("SELECT id, state, repository, revision FROM reference_roots WHERE domain = ?").all(domain) as + { id: string; state: string; repository: string; revision: string }[]).filter(matches); + }).immediate(); }, sourceTouch(at: number, domain: string, repository: string, revision: string) { db.query("UPDATE reference_sources SET last_used_at = ? WHERE domain = ? AND repository = ? AND revision = ?").run(at, domain, repository, revision); diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 6b0c1f9bc2..b1c7e22ba0 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -24,7 +24,7 @@ import { createHash, randomUUID } from "node:crypto"; import { dirname } from "node:path"; import type { createNativeBrainManagerClient, NativePoolRecord } from "@schlessera/brain-ui-sdk/internal"; import type { Logger } from "@opentelemetry/api-logs"; -import { coveringReferenceGrant, isLiveReferenceGrant, referenceRepository, type ReferenceGrant, type ReferenceRepository } from "../db/reference-grants.js"; +import { coveringReferenceGrant, isLiveReferenceGrant, referenceRepository, referenceRepositoryFromKey, type ReferenceGrant, type ReferenceRepository } from "../db/reference-grants.js"; import { referenceRevision, ReferenceTransportError, type ReferenceTransport } from "./reference-transport.js"; import { GitHubReferenceMetadataError, type createGitHubReferenceAccess } from "./github-reference-access.js"; import { githubReferenceRepository } from "./github-reference-identity.js"; @@ -82,7 +82,10 @@ interface SourceRow { grant_id: string | null; refreshed_at: number | null; validated_at: number | null; last_error: string | null; last_failed_at: number | null; last_used_at: number; } interface Operation { key: string; domain: string; principalId: string | null; grantId: string | null; controller: AbortController; joiners: number; promise: Promise } +interface InvalidatedRoot { id: string; state: string; repository: string; revision: string } type Outcome = { kind: "source"; row: SourceRow; stale: boolean; error: string | null } | { kind: "not-public"; reason: "denied" | "unavailable"; detail: string }; +/** Only host callers reading the catalog use repositoryKey; tool inputs remain raw strings. */ +type RepositoryInput = { repository: unknown; repositoryKey?: never } | { repository?: never; repositoryKey: string }; const PUBLIC = "public"; const privateDomain = (principalId: string) => `private:${principalId}`; @@ -411,7 +414,7 @@ export function createReferenceSources(options: { allowance ??= (await pool.poolStatus(signal)).limits.operationBytes; for (;;) { signal.throwIfAborted(); - try { return await pool.poolCreate(staging.id, "source", from, allowance, signal); } + try { return await pool.poolCreate(staging.id, "source", from, allowance, signal, isManaged(splitKey(protect)[1]) ? true : undefined); } catch (error) { if ((error as { code?: string }).code !== "capacity") throw error; // A refused identity created nothing; settle it and use a fresh one once eviction made room. @@ -441,11 +444,9 @@ export function createReferenceSources(options: { return freed; } /** Remove a source's name now; release its roots once no reader protects them. */ - function withdraw(domain: string, repository: string, revision: string): Promise { + function withdraw(domain: string, repository: string, revision: string, captured?: InvalidatedRoot[]): Promise { const key = sourceKey(domain, repository, revision); - const fenced = fenceSource(key); - const running = withdrawals.get(key); - if (running) return Promise.all([running, fenced]).then(() => {}); + const fenced = captured ? Promise.resolve(captured) : fenceSource(key); // Fence before any await, even when the first publication has no catalog // row yet. A later acquisition waits for this withdrawal to finish. withdrawn.add(key); @@ -453,7 +454,16 @@ export function createReferenceSources(options: { // Observe the catalog after every already-dispatched publication settles, // including one whose native reply or database receipt was still pending. const work = exclusive(key, async () => { - await fenced; + const invalidated = await fenced; + if (isManaged(repository)) { + for (const root of invalidated) { + const recorded = await write<{ id: string; state: string } | null>("sourceDiscard", root.id); + await hideRecordedRoot(recorded ?? root); + } + const current = row(domain, repository, revision); + if (current?.root_id && !invalidated.some(root => root.id === current.root_id)) withdrawn.delete(key); + return; + } const source = row(domain, repository, revision); const { roots, view } = await write<{ roots: { id: string; state: string }[]; view: { id: string } }>("sourceWithdraw", domain, repository, revision, randomUUID()); if (source) await pool.poolUnpublish(view.id, source.name); @@ -465,11 +475,11 @@ export function createReferenceSources(options: { await pool.poolUnpublish(publication.view, publication.name); await hideRoot(id); } - }).finally(() => { withdrawals.delete(key); }); + }).finally(() => { if (withdrawals.get(key) === work) withdrawals.delete(key); }); withdrawals.set(key, work); return work.then(() => settle(domain, repository, revision)); } - function fenceSource(key: string): Promise { + function fenceSource(key: string): Promise { authorityFences.set(key, (authorityFences.get(key) ?? 0) + 1); const [domain, repository, revision] = splitKey(key); return write("sourceFence", domain, authorityRepository(repository), revision, randomUUID()); @@ -491,14 +501,18 @@ export function createReferenceSources(options: { return [...keys]; } async function withdrawRepository(domain: string, repository: string, revision: string): Promise { - await fenceSource(sourceKey(domain, repository, "")); - return Promise.all(repositoryKeys(domain, repository, revision).map(key => withdraw(...splitKey(key)))); + const captured = await fenceSource(sourceKey(domain, repository, "")); + return Promise.all(repositoryKeys(domain, repository, revision).map(key => { + const parts = splitKey(key); + return withdraw(...parts, captured.filter(root => root.repository === parts[1] && root.revision === parts[2])); + })); } async function suspendRepository(domain: string, repository: string, revision: string): Promise { - await fenceSource(sourceKey(domain, repository, "")); - const keys = repositoryKeys(domain, repository, revision); - await Promise.all(keys.map(key => fenceSource(key))); - return Promise.all(keys.map(key => suspendSource(...splitKey(key)))); + const captured = await fenceSource(sourceKey(domain, repository, "")); + return Promise.all(repositoryKeys(domain, repository, revision).map(key => { + const parts = splitKey(key); + return suspendSource(...parts, false, captured.filter(root => root.repository === parts[1] && root.revision === parts[2])); + })); } async function acquire(signal: AbortSignal, input: { domain: string; principalId: string | null; repository: ReferenceRepository; revision: string; grant: ReferenceGrant | null; @@ -518,6 +532,8 @@ export function createReferenceSources(options: { try { const record = await create(staging, previousRoot, signal, key); recheck(); + if (input.managed && record.publicationRevoked !== false) + throw new ReferenceSourceError("unavailable", "The native keeper cannot guarantee permanent source withdrawal."); const { commit } = input.managed ? await input.managed.access.fetch(record.path!) : await transport.fetch({ repository, ref: input.ref, token: input.credential, root: record.path!, signal }); if (commit !== input.expectedCommit) throw new ReferenceTransportError("unavailable", "The reference moved after resolution; request it again."); @@ -613,6 +629,7 @@ export function createReferenceSources(options: { const assertTurn = () => { signal.throwIfAborted(); if (closed || !context.current()) throw new ReferenceSourceError("cancelled", "The acquiring turn is no longer available."); }; let result: ReferenceSourceLease | undefined; let accessOpened = false, openAttempted = false, containment: Promise | undefined; + let publicWithdrawal: Promise | undefined; const containFailure = (error: unknown, publishing: boolean, publicationId?: string): Promise => { if (containment) return containment; const reason = failureReason(error), domains = [PUBLIC, privateDomain(input.principalId)]; @@ -621,8 +638,8 @@ export function createReferenceSources(options: { work = Promise.all(domains.map(domain => reason === "denied" ? withdrawRepository(domain, repository.canonical, revision) : suspendRepository(domain, repository.canonical, revision))); } else if (!signal.aborted && context.current() && (reason === "denied" || reason === "unauthorized" || reason === "missing")) { - work = Promise.all(domains.map(domain => reason === "missing" ? withdraw(domain, repository.canonical, revision) - : withdrawRepository(domain, repository.canonical, revision))); + work = Promise.all(domains.map(domain => domain === PUBLIC && !accessOpened && publicWithdrawal && reason !== "missing" ? publicWithdrawal + : reason === "missing" ? withdraw(domain, repository.canonical, revision) : withdrawRepository(domain, repository.canonical, revision))); } else if (result && reason === "unavailable") { // Wire shutdown may outlive the lease's validation. A newer live // validation wins when this expiry cleanup reaches the exposure lock. @@ -635,7 +652,7 @@ export function createReferenceSources(options: { await hideRecordedRoot(root ?? { id: publicationId, state: "staging" }); })(); } else if (!signal.aborted && context.current() && openAttempted && !accessOpened) { - work = Promise.all(domains.map(domain => suspendRepository(domain, repository.canonical, revision))); + work = Promise.all(domains.map(domain => domain === PUBLIC && publicWithdrawal ? publicWithdrawal : suspendRepository(domain, repository.canonical, revision))); } containment = work.then(() => {}); return containment; @@ -650,7 +667,7 @@ export function createReferenceSources(options: { openAttempted = true; access = await options.github!.open({ principalId: input.principalId, repository: repository.url, revision, egress: context.egress, maxBytes, signal, current: () => !closed && context.current(), - withdrawPublic: async () => { await withdrawRepository(PUBLIC, repository.canonical, revision); } }); + withdrawPublic: async () => { await (publicWithdrawal ??= withdrawRepository(PUBLIC, repository.canonical, revision)); } }); accessOpened = true; const currentAccess = access; const assertCurrent = () => { @@ -669,13 +686,17 @@ export function createReferenceSources(options: { if (!check.ok) throw new ReferenceSourceError(check.reason === "missing" ? "missing" : check.reason === "denied" ? "unauthorized" : "unavailable", check.detail); const previous = row(domain, repository.canonical, revision); let reused = false; - if (usable(previous) && previous.commit_id === check.commit && previous.ref === check.ref) { + if (usable(previous) && previous.validated_at !== 0 && previous.commit_id === check.commit && previous.ref === check.ref) { await exclusive(operation.key, async () => { assertCurrent(); const current = row(domain, repository.canonical, revision); if (!usable(current) || current.root_id !== previous.root_id || withdrawn.has(operation.key)) return; const record = await pool.poolSeal(current.root_id, signal); assertCurrent(); + // Hidden/revoked roots never regain publication authority. Fresh + // acquisition uses a new identity, including across service owners. + if (record.publicationRevoked !== false || record.view !== (await viewFor(domain)).id) return; + assertCurrent(); if (!referenceAcquisitionMatches(db, current.root_id, record, { brain: options.brain, commit: check.commit, ref: check.ref, identity: access!.identity })) return; await access!.revalidate(); assertCurrent(); @@ -694,9 +715,12 @@ export function createReferenceSources(options: { assertCurrent(); const current = row(domain, repository.canonical, revision); if (!usable(current)) throw new ReferenceSourceError("unavailable", "Managed source publication is unavailable."); - result = await restored(await lease(current, false, null, () => { + // Managed roots are published exactly once. Restoring an old identity + // would race a completed native withdrawal; only acquire() publishes. + suspended.delete(operation.key); unsettled.delete(operation.key); + result = await lease(current, false, null, () => { assertTurn(); currentAccess.assertAuthority(); - }), current, assertCurrent, signal); + }); assertCurrent(); return { kind: "source", row: current, stale: false, error: null }; } catch (error) { @@ -731,11 +755,23 @@ export function createReferenceSources(options: { finally { operations.delete(id); void settle(...splitKey(operation.key)).catch(error => warn("managed source settle failed", error)); } } - async function request(input: { principalId: string; repository: unknown; revision: unknown; signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): Promise { + async function request(input: RepositoryInput & { principalId: string; revision: unknown; signal?: AbortSignal; acquisition?: ReferenceAcquisitionContext }): Promise { if (closed) throw new ReferenceSourceError("unavailable", "Reference sources are closed."); if (input.signal?.aborted) throw new ReferenceSourceError("cancelled", "Reference acquisition request was cancelled."); let repository: ReferenceRepository, revision: string; - try { repository = repositoryLocation(input.repository); revision = referenceRevision(input.revision); } + try { + revision = referenceRevision(input.revision); + if (input.repositoryKey !== undefined) { + repository = referenceRepositoryFromKey(input.repositoryKey); + // Keep the actual retained endpoint spelling for other Git hosts too. + const known = row(privateDomain(input.principalId), repository.canonical, revision) ?? row(PUBLIC, repository.canonical, revision); + if (known) { + const location = repositoryLocation(known.url); + if (location.canonical !== repository.canonical) throw new Error("The retained URL does not match its repository key."); + repository = location; + } + } else repository = repositoryLocation(input.repository); + } catch (error) { throw new ReferenceSourceError("invalid", (error as Error).message); } if (isManaged(repository.canonical)) return managedRequest(input, repository, revision); const probeKey = `${repository.canonical}\u0000${revision}`; @@ -775,12 +811,25 @@ export function createReferenceSources(options: { * unsettled until the pool confirms, so a bind retries it and refuses until * it does. */ - function suspendSource(domain: string, repository: string, revision: string, onlyExpired = false): Promise { + function suspendSource(domain: string, repository: string, revision: string, onlyExpired = false, captured?: InvalidatedRoot[]): Promise { const key = sourceKey(domain, repository, revision); return exclusive(key, async () => { const source = row(domain, repository, revision); if (onlyExpired && (!source || validationLive(source))) return; - const roots = db.query("SELECT id, state FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ?").all(domain, repository, revision) as { id: string; state: string }[]; + // Bind expiry is shared invalidation too, rather than a local flag that + // another owner can renew while native withdrawal is still outstanding. + const managed = isManaged(repository); + const roots = managed ? captured ?? await fenceSource(key) + : db.query("SELECT id, state FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ?").all(domain, repository, revision) as { id: string; state: string }[]; + if (managed) { + const current = row(domain, repository, revision); + const replaced = current?.root_id && !roots.some(root => root.id === current.root_id); + if (!replaced) { suspended.add(key); unsettled.add(key); } + for (const root of roots) await hideRecordedRoot(root); + if (replaced) suspended.delete(key); + unsettled.delete(key); + return; + } const pending = [...pendingPublications].filter(([, publication]) => publication.key === key); if ((!source?.root_id && !roots.length && !pending.length) || (suspended.has(key) && !unsettled.has(key) && !pending.length)) return; suspended.add(key); unsettled.add(key); @@ -809,7 +858,7 @@ export function createReferenceSources(options: { if (running) return running; const work = (async () => { try { - const repository = referenceRepository(source.repository); + const repository = referenceRepository(source.url); const principalId = source.domain === PUBLIC ? null : source.domain.slice("private:".length); const grant = principalId === null ? null : coveringReferenceGrant(db, { brain: options.brain, principalId, repository, now: now() }); if (principalId !== null && !grant) return false; @@ -925,7 +974,7 @@ export function createReferenceSources(options: { const current = row(source.domain, source.repository, source.revision); if (withdrawn.has(key) || withdrawals.has(key) || !usable(current) || current.root_id !== source.root_id || !validationLive(current)) throw new ReferenceSourceError("unavailable", "The reference source changed while it was being published again; request it again."); - if (current.domain !== PUBLIC) authorize(current.domain, current.domain.slice("private:".length), referenceRepository(current.repository)); + if (current.domain !== PUBLIC) authorize(current.domain, current.domain.slice("private:".length), referenceRepository(current.url)); // Until the pool confirms, the exposure is unknown: a failure leaves it for the next bind to take out again. unsettled.add(key); hiddenRoots.delete(current.root_id); const view = await viewFor(current.domain); @@ -972,7 +1021,7 @@ export function createReferenceSources(options: { for (const key of keys) { const [domain, repository, revision] = splitKey(key), principalId = domain.slice("private:".length); let covered = false; - try { covered = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId, repository: repositoryLocation(repository), now: now() })); } catch { covered = false; } + try { covered = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId, repository: referenceRepositoryFromKey(repository), now: now() })); } catch { covered = false; } if (!covered) await withdraw(domain, repository, revision); } } @@ -988,8 +1037,8 @@ export function createReferenceSources(options: { after = page.next; } const byId = new Map(records.map(record => [record.id, record])); - // A recorded source survives only with its sealed root, its name re-asserted - // (repairing a publication whose reply was lost) and, if private, a live grant. + // Recovery never renews metadata authority. Invalidated roots stay masked + // and charged until an explicit request obtains a new authorized root. const keep = new Set(); for (const source of db.query("SELECT * FROM reference_sources WHERE root_id IS NOT NULL").all() as SourceRow[]) { const record = byId.get(source.root_id!); @@ -998,14 +1047,22 @@ export function createReferenceSources(options: { brain: options.brain, commit: source.commit_id!, ref: source.ref, }); if (usableRoot && source.domain !== PUBLIC) { - try { usableRoot = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: source.domain.slice("private:".length), repository: repositoryLocation(source.repository), now: now() })); } + try { usableRoot = Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: source.domain.slice("private:".length), repository: repositoryLocation(source.url), now: now() })); } catch { usableRoot = false; } } if (usableRoot) { + if (!validationLive(source) || source.validated_at === 0 || (isManaged(source.repository) && record!.publicationRevoked !== false)) { + const key = sourceKey(source.domain, source.repository, source.revision); + suspended.add(key); unsettled.add(key); + await hideRoot(source.root_id!); + unsettled.delete(key); + keep.add(source.root_id!); + continue; + } try { await pool.poolPublish(source.root_id!, sourceWrites(db).sourceView(source.domain, randomUUID()).id, source.name); keep.add(source.root_id!); continue; } catch (error) { warn("reference source publication could not be restored", error); } } - db.query("UPDATE reference_sources SET root_id = NULL WHERE domain = ? AND repository = ? AND revision = ?").run(source.domain, source.repository, source.revision); + db.query("UPDATE reference_sources SET root_id = NULL WHERE domain = ? AND repository = ? AND revision = ? AND root_id = ?").run(source.domain, source.repository, source.revision, source.root_id); } // Everything else this app owns goes: interrupted staging, superseded or // withdrawn roots, roots the catalog lost and interrupted deletions. @@ -1017,11 +1074,9 @@ export function createReferenceSources(options: { catch { retained.push(record.id); } } for (const { id } of db.query("SELECT id FROM reference_roots").all() as { id: string }[]) - if (!keep.has(id) && !retained.includes(id)) db.query("DELETE FROM reference_roots WHERE id = ?").run(id); + if (byId.has(id) && !keep.has(id) && !retained.includes(id)) db.query("DELETE FROM reference_roots WHERE id = ?").run(id); db.query("UPDATE reference_roots SET state = 'published' WHERE id IN (SELECT root_id FROM reference_sources WHERE root_id IS NOT NULL)").run(); db.query("DELETE FROM reference_sources WHERE root_id IS NULL").run(); - // Every kept source is published again: the next bind judges each afresh. - suspended.clear(); unsettled.clear(); hiddenRoots.clear(); // A root kept only for a worktree is never left where a bound view reaches it. for (const id of retained) await hideRoot(id).catch(error => warn("retained reference root stays in its view until the next bind hides it", error)); return { released, retained }; @@ -1030,8 +1085,9 @@ export function createReferenceSources(options: { return { request, /** Whether a live grant covers this repository for this principal now; private worktrees (#2430) need one for every access. */ - covers(input: { principalId: string; repository: string }): boolean { - try { return Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: input.principalId, repository: repositoryLocation(input.repository), now: now() })); } + covers(input: RepositoryInput & { principalId: string }): boolean { + try { return Boolean(coveringReferenceGrant(db, { brain: options.brain, principalId: input.principalId, + repository: input.repositoryKey === undefined ? repositoryLocation(input.repository) : referenceRepositoryFromKey(input.repositoryKey), now: now() })); } catch { return false; } }, revoke, diff --git a/packages/ui-server/src/brain/reference-worktrees.ts b/packages/ui-server/src/brain/reference-worktrees.ts index 3a21debf02..37228055e6 100644 --- a/packages/ui-server/src/brain/reference-worktrees.ts +++ b/packages/ui-server/src/brain/reference-worktrees.ts @@ -227,7 +227,7 @@ export function createReferenceWorktrees(options: { async function authorize(row: Pick, signal?: AbortSignal, acquisition?: ReferenceAcquisitionContext) { covered(row); try { - const source = await options.sources.request({ principalId: row.principal_id, repository: row.repository, revision: row.revision, signal, acquisition }); + const source = await options.sources.request({ principalId: row.principal_id, repositoryKey: row.repository, revision: row.revision, signal, acquisition }); try { // A public starting snapshot cannot bypass the private authority the // current source check required. A private starting snapshot keeps its @@ -243,7 +243,7 @@ export function createReferenceWorktrees(options: { } /** A private worktree's grant, read live; checked again after every await before a grant. */ function covered(row: Pick) { - if (row.domain !== "public" && !options.sources.covers({ principalId: row.principal_id, repository: row.repository })) + if (row.domain !== "public" && !options.sources.covers({ principalId: row.principal_id, repositoryKey: row.repository })) throw new ReferenceWorktreeError("unauthorized", "No live reference grant covers this private worktree's repository."); } diff --git a/packages/ui-server/src/db/reference-grants.ts b/packages/ui-server/src/db/reference-grants.ts index b07705d929..d491efa73e 100644 --- a/packages/ui-server/src/db/reference-grants.ts +++ b/packages/ui-server/src/db/reference-grants.ts @@ -76,6 +76,12 @@ export function referenceRepository(input: unknown, options: { prefix?: boolean return { canonical, url: location, origin, scheme, loopback }; } +/** Decode a stored authority key, preserving its literal suffix. Not raw clone input. */ +export function referenceRepositoryFromKey(input: unknown): ReferenceRepository { + const key = referenceRepository(input); + return key.scheme === "file" ? key : referenceRepository(`${key.url}.git`); +} + /** Exact match or a path-segment boundary: `…/odysseus` never covers `…/odysseus-crew`. */ export const coversRepository = (prefix: string, repository: string) => repository === prefix || repository.startsWith(`${prefix}/`); diff --git a/packages/ui-server/tests/helpers/reference-pool-double.ts b/packages/ui-server/tests/helpers/reference-pool-double.ts index af190b0947..56fb575224 100644 --- a/packages/ui-server/tests/helpers/reference-pool-double.ts +++ b/packages/ui-server/tests/helpers/reference-pool-double.ts @@ -42,13 +42,13 @@ export function referencePoolDouble(root: string, options: { capacityRoots?: num limits: { combinedBytes: 64 * 1024 ** 2, operationBytes: options.operationBytes ?? 8 * 1024 ** 2, emergencyBytes: 4096, physicalFloorBytes: 4096, maxIdentities: 4096 }, accounting: null, physical: null, counts: { reserved: 0, writable: 0, sealed: 0, deleting: 0, deleted: 0, reclaimed: 0 }, identities: records.size } as NativePoolStatus; }, - async poolCreate(id, purpose, from, allowanceBytes) { + async poolCreate(id, purpose, from, allowanceBytes, _signal, permanentWithdrawal) { note({ operation: "create", id }); const existing = records.get(id); if (existing && ["deleting", "deleted", "reclaimed"].includes(existing.state)) fail("released", "This reference pool identity was released; it cannot be recreated."); if (existing) return existing; if (live().length >= pool.capacityRoots) fail("capacity", "Reference pool combined allowance cannot reserve its allowance; nothing was admitted."); - const record: NativePoolRecord = { id, purpose, from, allowanceBytes, state: "writable", root: { rootId: String(256 + records.size), uuid: createHash("sha256").update(id).digest("hex").slice(0, 32), otransid: "1" }, + const record: NativePoolRecord = { id, ...(permanentWithdrawal ? { publicationRevoked: false } : {}), purpose, from, allowanceBytes, state: "writable", root: { rootId: String(256 + records.size), uuid: createHash("sha256").update(id).digest("hex").slice(0, 32), otransid: "1" }, path: join(roots, id), ownerBytes: 0, reason: null, view: null, access: null }; if (from) { const source = records.get(from); if (!source || source.state !== "sealed") fail("unknown", "A reference snapshot requires one retained sealed pool root."); cpSync(location(source!), record.path!, { recursive: true, verbatimSymlinks: true }); } else mkdirSync(record.path!); @@ -67,6 +67,7 @@ export function referencePoolDouble(root: string, options: { capacityRoots?: num async poolPublish(id, view, name) { const record = records.get(id); if (!record || record.purpose !== "source") fail("unknown", "Only a recorded reference source root can be published."); + if (record!.publicationRevoked) fail("released", "This source root's publication authority was permanently withdrawn."); if (record!.state !== "sealed") fail("invalid", "Only a sealed reference source root can be published."); if (record!.view && record!.view !== view) fail("invalid", "A published reference root belongs to exactly one view."); mkdirSync(join(views, view), { recursive: true }); @@ -91,6 +92,7 @@ export function referencePoolDouble(root: string, options: { capacityRoots?: num async poolWithdraw(id) { const record = records.get(id); if (!record || record.purpose !== "source") fail("unknown", "Only a recorded reference source root can be withdrawn."); + if (record!.publicationRevoked === false) record!.publicationRevoked = true; note({ operation: "withdraw", id }); if (!record!.view) return record!; // Like the manager: a released root keeps its view in its record, and is never withdrawn. diff --git a/packages/ui-server/tests/native-brain-leases.test.ts b/packages/ui-server/tests/native-brain-leases.test.ts index d91675011c..df0c13b7d3 100644 --- a/packages/ui-server/tests/native-brain-leases.test.ts +++ b/packages/ui-server/tests/native-brain-leases.test.ts @@ -178,6 +178,20 @@ test("unknown stage creation pins its lower root until confirmed stage deletion } finally { await second.close(); await f.close(); } }); +test("source leases forward permanent withdrawal and refuse a keeper without its receipt", async () => { + const f = await fixture(); let supported = false; + f.native.client.poolCreate = async (id, purpose, from, allowanceBytes, _signal, permanentWithdrawal) => { + expect(permanentWithdrawal, "LEASE_OWNER_PRESERVES_PERMANENT_WITHDRAWAL").toBe(true); + return { id, purpose, from, allowanceBytes, state: "writable", root: null, path: null, ownerBytes: null, reason: null, view: null, access: null, + ...(supported ? { publicationRevoked: false } : {}) }; + }; + try { + await expectRejection(f.owner.client.poolCreate(ID, "source", null, 4096, undefined, true), "durable lease identity"); + supported = true; + expect(await f.owner.client.poolCreate(ID, "source", null, 4096, undefined, true)).toMatchObject({ publicationRevoked: false }); + } finally { await f.close(); } +}); + test("reference pool roots are durable app leases that dead-owner recovery and close never delete", async () => { const f = await fixture(), calls: string[] = []; const record = (id: string, purpose: "source" | "worktree" | "staging" | "checkpoint", from: string | null, allowanceBytes: number, state: string) => diff --git a/packages/ui-server/tests/reference-source-authority.test.ts b/packages/ui-server/tests/reference-source-authority.test.ts index 70308e3979..a941d8bbb8 100644 --- a/packages/ui-server/tests/reference-source-authority.test.ts +++ b/packages/ui-server/tests/reference-source-authority.test.ts @@ -52,3 +52,18 @@ test("the validation transaction cannot renew a durably invalidated or replaced expect(writes.sourceValidate(at + 1, at + 1, "refs/heads/main", "public", repository, "main", fresh, "telemachus-root"), "VALIDATION_COMMIT_RETAINS_ROOT_BINDING").toBe(false); expect(writes.sourceValidate(at + 1, at + 1, "refs/heads/main", "public", repository, "main", fresh, "odysseus-root")).toBe(true); }); + + +test("a committed fence atomically expires matching validation across aliases and revisions", () => { + const cases = [["public", repository, "main"], ["public", "https://github.com/Odysseus/Ithaca", "return-home"], + ["public", `${repository}.git`, "main"], ["private:penelope", repository, "main"]]; + for (const [domain, key, revision] of cases) { + const id = `${domain}:${key}:${revision}`; + writes.sourceStage(id!, domain!, key!, revision!, at); + writes.sourcePublish("/srv/fixtures/view", domain!, key!, revision!, `${key}.git`, "ithaca", id, "a".repeat(40), `refs/heads/${revision}`, null, at); + } + writes.sourceFence("public", repository, "", "odysseus-crash-after-commit"); + const rows = db.query("SELECT domain, repository, validated_at FROM reference_sources").all() as { domain: string; repository: string; validated_at: number }[]; + for (const row of rows) expect(row.validated_at, "FENCE_COMMIT_CANNOT_LEAVE_OLD_POSITIVE_VALIDATION") + .toBe(row.domain === "public" && row.repository !== `${repository}.git` ? 0 : at); +}); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index c3270d1c88..a3902ab4e4 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -5,6 +5,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { startEgressProxy } from "../../ui-sdk/src/server/egress-proxy"; import { createGitHubReferenceAccess } from "../src/brain/github-reference-access"; +import { githubReferenceRepository } from "../src/brain/github-reference-identity"; import { createReferenceSources } from "../src/brain/reference-source"; import type { ReferenceTransport } from "../src/brain/reference-transport"; import { createUiDb } from "../src/db/client"; @@ -22,24 +23,27 @@ let root: string, tls: ReturnType; beforeAll(() => { root = mkdtempSync(join(tmpdir(), "odysseus-managed-source-")); tls = fixtureTls(root, ["api.github.com"]); }); afterAll(() => rmSync(root, { recursive: true, force: true })); -async function fixture(options: { private?: boolean; worker?: boolean } = {}) { +async function fixture(options: { private?: boolean; worker?: boolean; repository?: string; neighbor?: boolean } = {}) { + const fixtureRepository = options.repository ?? repository, location = githubReferenceRepository(fixtureRepository); const directory = mkdtempSync(join(root, "source-")), db = createUiDb(join(directory, "ui.db")); const owner = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); const other = createPrincipal(db, { authMethod: "password", label: "Telemachus", ttlSeconds: 3600 }); const writer = options.worker ? openSqliteWriter(db) : undefined; if (writer) registerReferenceWrites(db, writer); const credentials: Record = { GITHUB_TOKEN: "odysseus-fixture-token" }; - const metadata: string[] = [], git: unknown[] = []; + const metadata: string[] = [], metadataPaths: string[] = [], git: unknown[] = []; const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200, invalidAt: 0, invalidJsonAt: 0, endOnPrivateMetadata: false }; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { metadata.push(request.headers.get("authorization") ?? "anonymous"); + metadataPaths.push(new URL(request.url).pathname); if (metadata.length === state.invalidJsonAt) return new Response("{", { headers: { "content-type": "application/json" } }); if (metadata.length === state.invalidAt) return Response.json({ id: "invalid" }); if (state.status !== 200) return new Response(null, { status: state.status }); if (state.private && !request.headers.has("authorization")) return new Response(null, { status: 404 }); if (state.endOnPrivateMetadata && request.headers.has("authorization")) state.current = false; - return Response.json({ id: 101, owner: { id: state.ownerId, login: "Odysseus" }, name: "Ithaca", full_name: "Odysseus/Ithaca", - clone_url: `${repository}.git`, url: "https://api.github.com/repos/odysseus/ithaca", private: state.private }); + const selected = options.neighbor && new URL(request.url).pathname === "/repos/odysseus/ithaca" ? githubReferenceRepository(repository) : location; + return Response.json({ id: selected.repository === "ithaca" ? 101 : 102, owner: { id: state.ownerId, login: "Odysseus" }, name: selected.repository, + full_name: `Odysseus/${selected.repository}`, clone_url: selected.cloneUrl, url: selected.metadataUrl, private: state.private }); } }); const records: unknown[] = []; const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe(value) { records.push(value); } }); @@ -57,13 +61,13 @@ async function fixture(options: { private?: boolean; worker?: boolean } = {}) { const github = access(); const sourceOptions = { db, pool, transport, brain, credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, github, now: () => state.clock }; const sources = createReferenceSources(sourceOptions); - const grant = (repositoryPrefix = repository) => createReferenceGrant(db, { brain, principalId: owner.id, createdBy: owner.id, repositoryPrefix, + const grant = (repositoryPrefix = fixtureRepository) => createReferenceGrant(db, { brain, principalId: owner.id, createdBy: owner.id, repositoryPrefix, credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); const request = (principalId = owner.id, turnId = "odysseus-turn", proxy = egress) => { - const input = { repository, revision: "main", principalId, acquisition: { turnId, egress: proxy, current: () => state.current } }; + const input = { repository: fixtureRepository, revision: "main", principalId, acquisition: { turnId, egress: proxy, current: () => state.current } }; return sources.request(input); }; - return { sources, sourceOptions, request, db, pool, transport, github, credentials, owner, other, grant, state, egress, secondEgress, metadata, git, records, + return { sources, sourceOptions, request, db, pool, transport, github, credentials, owner, other, grant, state, egress, secondEgress, metadata, metadataPaths, git, records, restart(database: ReturnType) { return createReferenceSources({ ...sourceOptions, db: database, github: access(database) }); }, databasePath: join(directory, "ui.db"), async close() { await sources.close(); await writer?.close(); egress.stop(); secondEgress.stop(); server.stop(true); db.close(); } }; @@ -96,6 +100,16 @@ test("managed GitHub requests without an admitted turn budget refuse before any } finally { await f.close(); } }); +test("managed acquisition refuses a keeper without permanent withdrawal before fetching source bytes", async () => { + const f = await fixture(), create = f.pool.poolCreate; + f.pool.poolCreate = async (...args) => { const record = await create(...args); delete record.publicationRevoked; return record; }; + try { + await expect(f.request(), "MANAGED_SOURCE_REQUIRES_NATIVE_WITHDRAWAL_SUPPORT").rejects.toMatchObject({ code: "unavailable" }); + expect(f.state.fetches).toBe(0); + expect(f.pool.events.filter(event => event.operation === "publish")).toEqual([]); + } finally { await f.close(); } +}); + test("a cached shared root still uses the requesting principal and turn's own metadata budget", async () => { const f = await fixture(); try { @@ -119,7 +133,7 @@ test("pre-proxy bind preparation with expired GitHub authority withholds source await f.sources.bindable(f.owner.id); expect(f.git.length, "REFERENCE_BIND_NEVER_SPENDS_UNBOUND_NETWORK").toBe(count); expect(f.metadata.length).toBe(metadata); - expect(f.pool.events.some(event => event.operation === "unpublish"), "REFERENCE_BIND_WITHHOLDS_EXPIRED_MANAGED_SOURCE").toBe(true); + expect(existsSync(join(lease.viewPath, lease.name, "README.md")), "REFERENCE_BIND_WITHHOLDS_EXPIRED_MANAGED_SOURCE").toBe(false); } finally { await f.close(); } }); @@ -419,7 +433,7 @@ describe("live managed authority", () => { f.state.invalidAt = 0; f.state.invalidJsonAt = 0; const recovered = await f.request(); try { - expect(recovered.rootId, "VALID_METADATA_RESTORES_THE_WITHHELD_CACHE").toBe(held.rootId); + expect(recovered.rootId, "VALID_METADATA_ACQUIRES_NEW_PUBLICATION_AUTHORITY").not.toBe(held.rootId); expect(readFileSync(join(recovered.viewPath, recovered.name, "README.md"), "utf8")).toContain("Odysseus"); } finally { recovered.release(); } } finally { held?.release(); await f.close(); } @@ -777,6 +791,122 @@ describe("live managed authority", () => { } finally { if (first) await worktrees.closeGeneration(first.id); if (other) await worktrees.closeGeneration(other.id); await worktrees.close(); await f.close(); } }); + test("a stored suffix worktree cannot borrow its neighbor's grant after revocation", async () => { + const suffix = `${repository}.git.git`, f = await fixture({ private: true, repository: suffix, neighbor: true }), issued = f.grant(); + f.grant(repository); + const context = { turnId: "odysseus-literal-source-worktree", egress: f.egress, current: () => true }; + const worktrees = createReferenceWorktrees({ db: f.db, pool: f.pool, sources: f.sources, coverage: async () => {} }); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: f.owner.id, repository: suffix, revision: "main", acquisition: context }); + expect(item.repository).toBe(`${repository}.git`); + generation = await worktrees.openGeneration({ principalId: f.owner.id, turnId: context.turnId, profile: "governed" }); + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); + await f.sources.revoke({ grantIds: [issued.id], principalIds: [] }); + const sent = f.metadataPaths.length, git = f.git.length; + await expect(worktrees.access({ worktreeId: item.id, principalId: f.owner.id, generation: generation.id, acquisition: context }), + "STORED_WORKTREE_KEY_CANNOT_BORROW_NEIGHBOR_GRANT").rejects.toMatchObject({ code: "unauthorized" }); + expect(f.metadataPaths.length, "REVOKED_SUFFIX_WORKTREE_SENDS_NO_NEIGHBOR_METADATA").toBe(sent); + expect(f.git.length).toBe(git); + expect(existsSync(join(generation.path, item.id, "README.md"))).toBe(false); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await f.close(); } + }); + + test("another service restores a freshly validated root hidden by bind expiry", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + let held: Awaited> | undefined, current: typeof held; + try { + held = await f.request(); held.release(); f.state.clock += 400_000; + await f.sources.bindable(f.owner.id); + expect(f.pool.records.get(held.rootId)?.view).toBeNull(); + current = await otherSources.request({ principalId: f.owner.id, repository, revision: "main", + acquisition: { turnId: "odysseus-other-owner-restore", egress: f.secondEgress, current: () => true } }); + expect(() => current!.assertAuthority()).not.toThrow(); + expect(existsSync(join(current.viewPath, current.name, "README.md")), "FRESH_SHARED_CACHE_LEASE_HAS_PUBLISHED_BYTES").toBe(true); + expect(current.rootId, "WITHDRAWN_ROOT_AUTHORITY_IS_NEVER_REUSED").not.toBe(held.rootId); + } finally { current?.release(); held?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + + test("startup recovery keeps durably suspended metadata hidden from already-bound views", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + let held: Awaited> | undefined; + try { + held = await f.request(); held.release(); f.state.status = 503; + await expect(f.request()).rejects.toMatchObject({ code: "unavailable" }); + const path = join(held.viewPath, held.name, "README.md"), metadata = f.metadata.length; + expect(existsSync(path)).toBe(false); + const publish = f.pool.poolPublish; let publications = 0; + f.pool.poolPublish = async (...args) => { publications++; return publish(...args); }; + await otherSources.recover(); + expect(publications, "RECOVERY_PERFORMS_NO_UNVALIDATED_PUBLICATION").toBe(0); + expect(f.metadata.length).toBe(metadata); + expect(existsSync(path), "RECOVERY_CANNOT_REEXPOSE_SUSPENDED_SOURCE").toBe(false); + expect(f.pool.records.get(held.rootId)?.view).toBeNull(); + } finally { held?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + + test("a delayed cached restoration cannot republish after another owner observes private metadata", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; + let held: Awaited> | undefined, observerHeld: typeof held, older: Promise<{ lease?: typeof held; error?: unknown }> | undefined, exposed = false; + try { + held = await f.request(); held.release(); + observerHeld = await otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-held-source", egress: f.secondEgress, current: () => true } }); + f.state.clock += 400_000; await f.sources.bindable(f.owner.id); + f.pool.poolPublish = async (...args) => { arrived.resolve(); await resume.promise; const result = await publish(...args); exposed = true; return result; }; + older = f.request().then(lease => ({ lease }), error => ({ error })); + await arrived.promise; f.state.private = true; + await expect(otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-restoration-fence", egress: f.secondEgress, current: () => true } })).rejects.toMatchObject({ code: "unauthorized" }); + resume.resolve(); const result = await older; + expect(result.lease).toBeUndefined(); + expect(exposed, "DELAYED_RESTORATION_CANNOT_EXPOSE_REVOKED_PUBLIC_SOURCE").toBe(false); + } finally { resume.resolve(); (await older)?.lease?.release(); observerHeld?.release(); held?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + + test("a delayed recovery publication cannot expose a retained root after completed revocation", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; + let observer: Awaited> | undefined, recovery: Promise | undefined, exposed = false; + try { + (await f.request()).release(); + observer = await otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-retained-public-root", egress: f.secondEgress, current: () => true } }); + f.pool.poolPublish = async (...args) => { arrived.resolve(); await resume.promise; const record = await publish(...args); exposed = true; return record; }; + recovery = f.sources.recover(); + await arrived.promise; f.state.private = true; + await expect(otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-completed-revocation", egress: f.secondEgress, current: () => true } })).rejects.toMatchObject({ code: "unauthorized" }); + expect(f.pool.records.get(observer.rootId)?.publicationRevoked).toBe(true); + expect(existsSync(join(observer.viewPath, observer.rootId, "README.md"))).toBe(false); + resume.resolve(); await recovery; + expect(exposed, "NATIVE_WITHDRAWAL_REFUSES_DELAYED_RETAINED_ROOT_PUBLICATION").toBe(false); + } finally { resume.resolve(); await recovery; observer?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + + for (const observation of ["private", "unknown"] as const) + test(`an older ${observation} invalidation cannot remove a fresh publication from another owner`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(); + const unpublish = f.pool.poolUnpublish, withdraw = f.pool.poolWithdraw; + let paused = false, old: Awaited> | undefined, fresh: typeof old, invalidating: Promise | undefined; + const pause = async () => { if (!paused) { paused = true; arrived.resolve(); await resume.promise; } }; + try { + old = await f.request(); + f.pool.poolUnpublish = async (...args) => { await pause(); return unpublish(...args); }; + f.pool.poolWithdraw = async (...args) => { await pause(); return withdraw(...args); }; + if (observation === "private") f.state.private = true; else f.state.status = 503; + invalidating = f.request().then(lease => { lease.release(); return undefined; }, error => error); + await arrived.promise; f.state.private = false; f.state.status = 200; + fresh = await otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-newer-authorized-publication", egress: f.secondEgress, current: () => true } }); + resume.resolve(); await invalidating; + expect(() => fresh!.assertAuthority(), "OLD_INVALIDATION_PRESERVES_FRESH_AUTHORITY").not.toThrow(); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md")), "OLD_INVALIDATION_PRESERVES_FRESH_PUBLICATION").toBe(true); + } finally { resume.resolve(); await invalidating; fresh?.release(); old?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + for (const observation of ["private", "unknown"] as const) for (const revision of ["main", "return-home"]) test(`another source service fences a first ${revision} publication after ${observation} metadata`, async () => { @@ -874,7 +1004,7 @@ describe("live managed authority", () => { held = await f.request(); f.state.status = 503; await expect(request()).rejects.toMatchObject({ code: "unavailable" }); f.state.status = 200; current = await request(); - expect(current.rootId).toBe(held.rootId); + expect(current.rootId).not.toBe(held.rootId); expect(() => held!.assertAuthority(), "DURABLE_GENERATION_CANNOT_REVIVE_INVALIDATED_LEASE").toThrow(); expect(() => current!.assertAuthority(), "NEW_DURABLE_GENERATION_RETAINS_VALID_LEASE").not.toThrow(); } finally { current?.release(); held?.release(); await otherSources.close(); otherDb.close(); await f.close(); } diff --git a/packages/ui-server/tests/reference-tools.test.ts b/packages/ui-server/tests/reference-tools.test.ts index 65509d34c1..0e503968ca 100644 --- a/packages/ui-server/tests/reference-tools.test.ts +++ b/packages/ui-server/tests/reference-tools.test.ts @@ -496,7 +496,7 @@ describe("exposure changes are serialized (#2432 review)", () => { expect(readdirSync(first.views!.private), "REFERENCE_TOOLS_REVOCATION_WINS_OVER_RESTORE").toEqual([]); }); - test("after recovery republishes everything, the next bind judges each source again", async () => { + test("recovery keeps suspended sources hidden until an explicit request validates them", async () => { const { turn, sources, tools, state } = host(); const penelope = principal(), telemachus = principal("Telemachus"); const first = await turn(penelope.id); @@ -507,9 +507,12 @@ describe("exposure changes are serialized (#2432 review)", () => { const withheld = await turn(telemachus.id); expect(publicEntries(withheld.views)).toEqual([]); await sources.recover(); - expect(publicEntries(withheld.views) ?? [], "REFERENCE_TOOLS_RECOVERY_REPUBLISHES").toContain(name); + expect(publicEntries(withheld.views), "REFERENCE_TOOLS_RECOVERY_CANNOT_REPUBLISH_UNVALIDATED_SOURCE").toEqual([]); state.failResolves = 1; expect(publicEntries((await turn(telemachus.id)).views), "REFERENCE_TOOLS_RECOVERY_THEN_BIND_SUSPENDS").toEqual([]); + state.failResolves = 0; + expect(nameOf(await withheld.call(source(PUBLIC)))).toBe(name); + expect(publicEntries(withheld.views), "REFERENCE_TOOLS_FRESH_REQUEST_RESTORES_SOURCE").toContain(name); }); }); diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index e2f45c9415..8869e516a8 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -432,6 +432,38 @@ const shapes = await create("staging", 32 * MIB); "REFERENCE_VIEW_RELEASE_REMOVES_ITS_NAMES").toBe(false); } +// Managed roots opt into irreversible withdrawal. Retained storage may seed +// a fresh identity, but neither delayed RPCs nor restart can revive the old one. +{ + const VIEW = randomUUID(), id = randomUUID(); + const first = await call({ operation: "poolCreate", id, purpose: "source", from: null, allowanceBytes: 4 * MIB, permanentWithdrawal: true }); + expect(first.publicationRevoked, "REFERENCE_PERMANENT_WITHDRAWAL_OPT_IN").toBe(false); + writeFileSync(join(first.path!, "README.md"), "Odysseus charts Ithaca.\n"); + await seal(id); + await call({ operation: "poolPublish", id, view: VIEW, name: "ithaca" }); + // Crash after the durable revocation fence, before the root's move. + const path = join(POOL, ".reference-native/state", `${id}.json`); + const intent = JSON.parse(readFileSync(path, "utf8")); + writeFileSync(path, JSON.stringify({ ...intent, publicationRevoked: true })); + manager = await restart({}); + expect(existsSync(join(POOL, "views", VIEW, id)), "REFERENCE_RESTART_COMPLETES_PERMANENT_WITHDRAWAL").toBe(false); + expect((await refusal({ operation: "poolPublish", id, view: VIEW, name: "ithaca" })).code, + "REFERENCE_NATIVE_REVOKED_ROOT_CANNOT_PUBLISH").toBe("released"); + const freshId = randomUUID(); + await call({ operation: "poolCreate", id: freshId, purpose: "source", from: id, allowanceBytes: 4 * MIB, permanentWithdrawal: true }); + await seal(freshId); + await call({ operation: "poolPublish", id: freshId, view: VIEW, name: "ithaca" }); + await call({ operation: "poolWithdraw", id }); + expect(readFileSync(join(POOL, "views", VIEW, "ithaca", "README.md"), "utf8"), "OLD_WITHDRAWAL_PRESERVES_NEW_ROOT").toContain("Odysseus"); + expect((await call({ operation: "poolWithdraw", id: freshId })).publicationRevoked).toBe(true); + expect((await refusal({ operation: "poolPublish", id: freshId, view: VIEW, name: "ithaca" })).code, + "REFERENCE_NATIVE_COMPLETED_WITHDRAWAL_IS_PERMANENT").toBe("released"); + manager = await restart({}); + expect((await call({ operation: "poolSeal", id: freshId })).publicationRevoked, + "REFERENCE_NATIVE_WITHDRAWAL_SURVIVES_RESTART").toBe(true); + await release(freshId); await release(id); +} + // 16. Acquisition (#2429): the real reference service and its real transport // workers fetch and check out a 1,200-file Odysseus repository into a // quota-limited pool root, publish it, and a sandbox bound to its view reads it. From 1170652f2c67200d60de13e9c0861ad77749573e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 11:55:20 +0000 Subject: [PATCH 23/27] CONTRACT: preserve newer source publications and worktree endpoints --- .../managed-reference-source-authority.md | 2 + api-report/ui-server.txt | 2 +- docs/decisions/managed-worktrees.md | 26 +++---- docs/decisions/reference-pool-accounting.md | 2 +- .../decisions/reference-source-acquisition.md | 26 +++++-- docs/integration-contract/package-api.md | 18 +++++ .../src/server/native-brain-manager-client.ts | 3 +- .../server/native-brain-manager-protocol.ts | 3 +- .../src/server/native-reference-pool.ts | 13 +++- .../ui-sdk/tests/native-brain-manager.test.ts | 5 ++ .../092_reference_worktree_urls.sql | 9 +++ .../src/brain/native-brain-leases.ts | 4 +- .../src/brain/reference-source-writes.ts | 4 +- .../ui-server/src/brain/reference-source.ts | 78 +++++++++++++------ .../src/brain/reference-worktree-writes.ts | 6 +- .../src/brain/reference-worktrees.ts | 8 +- .../tests/helpers/reference-pool-double.ts | 6 +- .../tests/native-brain-leases.test.ts | 5 ++ .../tests/reference-source-authority.test.ts | 10 +++ .../tests/reference-source-managed.test.ts | 60 +++++++++++++- .../tests/reference-worktrees.test.ts | 30 +++++++ scripts/native-proof/reference-pool.native.ts | 10 ++- 22 files changed, 264 insertions(+), 66 deletions(-) create mode 100644 packages/ui-server/migrations/092_reference_worktree_urls.sql diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md index 776c7b133e..8b2e46d22f 100644 --- a/.changeset/managed-reference-source-authority.md +++ b/.changeset/managed-reference-source-authority.md @@ -6,3 +6,5 @@ Bind managed GitHub source acquisition and cached-source revalidation to the requesting turn's network budget and live authority. Retain sealed-root and tree acquisition facts outside source content; refuse contradictory retained roots after restart. Managed source and worktree file reads remain restricted until actual immutable-read provenance is qualified. Failed worktree grants condition native parking on their requesting generation, preserving another generation's access while still withdrawing a lost-reply grant of their own. Keep stored canonical grant suffixes literal during lookup and duplicate checks, so a repository grant cannot authorize a neighboring repository. Waiting worktree effects reread shared source authority, including durable invalidation by another app or cron owner. Shared repository/revision invalidation versions also fence first publication across app and cron owners, with validation/publication commit checks and retirement of invalidated sealed staging identities. Failed-attempt cleanup preserves another owner's newer publication. Metadata and Git wiring preserve the requested repository's literal canonical suffix, including when metadata reports it missing. Keep stored worktree repository keys separate from raw clone input so revocation cannot borrow a neighboring repository's grant. Managed roots opt into durable, permanent native publication withdrawal: delayed publication cannot revive a revoked identity, while fresh authorized acquisition uses a new root and legacy withdrawal stays reversible. Recovery keeps invalidated roots masked, and committing a shared invalidation atomically expires matching cached validation. + +Condition native publication and catalog updates on the previously observed root so concurrent acquisitions cannot roll a source back to an older revision. Worktrees retain their original acquisition URL after source-catalog cleanup, preserving authorized legacy endpoints without guessing clone suffixes. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index c1f653e2d1..6fb09c1c7d 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2570,7 +2570,7 @@ signatures (every public export and the types it is made of) poolGrowth: (signal?: AbortSignal) => Promise; poolListCheckpoint: (id: string, path: string, expectedWorkerUid: number, signal?: AbortSignal) => Promise; poolPark: (id: string, signal?: AbortSignal, expectedAccess?: string) => Promise; - poolPublish: (id: string, view: string, name: string, signal?: AbortSignal) => Promise; + poolPublish: (id: string, view: string, name: string, signal?: AbortSignal, expectedRoots?: readonly (null | string)[]) => Promise; poolReadCheckpoint: (id: string, path: string, maximum: number, expectedWorkerUid: number, signal?: AbortSignal) => Promise; poolRelease: (id: string, signal?: AbortSignal) => Promise; poolSeal: (id: string, signal?: AbortSignal) => Promise; diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index caea92083b..0033a6b12e 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -7,7 +7,7 @@ commit. It builds on the [acquisition service](reference-source-acquisition.md) and the pool's [checkpoints and access generations](reference-pool-accounting.md#worktree-checkpoints-and-access-generations-2430). This record names the concrete choices the rulings left to implementation. The service is `createReferenceWorktrees` -(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:152-712`), +(`createReferenceWorktrees`, `packages/ui-server/src/brain/reference-worktrees.ts:153-713`), created with the acquisition service. The agent tools that call it arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) ([agent tools](#agent-tools)). Hygiene findings, review and cleanup arrived with [#2431](https://github.com/schlessera/brain-kit/issues/2431) @@ -19,7 +19,7 @@ A request names the principal, a repository and a branch or tag, like a source request. The service asks the acquisition service for that source, so its authority, freshness and private boundary all apply, and then snapshots the sealed source root it was given -(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:456-488`). +(`async function allocate`, `packages/ui-server/src/brain/reference-worktrees.ts:458-490`). The worktree's starting commit is the commit that source reported, and it never moves with the source. A read-only baseline checkpoint is taken at once. Each worktree gets the pool's per-operation allowance. A worktree belongs to one @@ -54,7 +54,7 @@ restricted (autonomous) turn holds no worktree. The generation records the owning process (PID, start time, boot and PID namespace). Access makes a worktree available to one open generation -(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:553-563`): +(`function access(input`, `packages/ui-server/src/brain/reference-worktrees.ts:555-565`): 1. The generation must be open in this process for a running turn, and belong to the requesting principal. @@ -96,10 +96,10 @@ own generation and its turn no longer runs; that record is process-wide, so every service instance in the process reads the same evidence. Closing a service ends the registration of the generations it opened. Any other case, such as an owner in another PID namespace, is **unknown** -(`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:207-213`). +(`function live`, `packages/ui-server/src/brain/reference-worktrees.ts:208-214`). Reconciliation runs at startup and when a generation closes, never on a timer -(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:637-664`). +(`async function reconcile`, `packages/ui-server/src/brain/reference-worktrees.ts:639-666`). After three days without explicit activity, a worktree expires: - with a live holder it stays `active` and held, however long the turn runs; @@ -184,7 +184,7 @@ arrive only in the results that grant access. ## Cleanup eligibility facts Release and expiry record durable facts for hygiene review -(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:251-294`): +(`async function assessWork`, `packages/ui-server/src/brain/reference-worktrees.ts:253-296`): the reason, the holder (`none`, `live` or `unknown`) and whether work remains (`none`, `unpreserved` or `unknown`). Work is read from a fresh read-only checkpoint and a metadata delta against the baseline. Nothing of the worktree @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1107-1138`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1137-1168`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:902-940`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:931-969`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:814-831`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:843-860`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:946-955`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:975-984`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a @@ -442,7 +442,7 @@ atomically with grants [pool accounting](reference-pool-accounting.md)), so a grant that lands between the last check and the release fails the removal instead of losing the grant. The worktree service is the only executor, through one effect -(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:343-380`). +(`async function removeWorktree`, `packages/ui-server/src/brain/reference-worktrees.ts:345-382`). Immediately before it, with no await between the last check and submission of the receipt: 1. the worktree is released or expired, and no removal of it was already @@ -478,13 +478,13 @@ without another release, which would fail or leave a tombstone identity. The lease owner holds a release's lease again when the pool never committed it (the root is still writable or sealed), so a failed removal stays assessable; it never does so over a newer release of the same identity -(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:387-422`). +(`async function settle(`, `packages/ui-server/src/brain/reference-worktrees.ts:389-424`). Capacity is credited only when the pool reports the worktree `reclaimed`: until then its source root stays protected from eviction. **Automatic removal.** Release, expiry and the close of a holding generation remove a worktree only when its fresh assessment shows no holder and no work -(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:312-315`). +(`function removeClean`, `packages/ui-server/src/brain/reference-worktrees.ts:314-317`). Reconciliation retries a clean worktree whose removal could not run. Nothing is archived or purged speculatively, and a worktree whose work or owner is unknown is never removed automatically. Arbitrary repositories and shared diff --git a/docs/decisions/reference-pool-accounting.md b/docs/decisions/reference-pool-accounting.md index d1985656d7..27debe08a3 100644 --- a/docs/decisions/reference-pool-accounting.md +++ b/docs/decisions/reference-pool-accounting.md @@ -224,7 +224,7 @@ directory its intent records. Sealing also makes the root's top directory `roots/` and `views/` join the mandatory worker masks. A worker sees reference source only through a view bound for it, and other domains' views stay invisible. `poolView` (#2432) opens a view's directory before its first -publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:1119-1122`), +publication (`function viewOpen`, `packages/ui-sdk/src/server/native-reference-pool.ts:1128-1131`), so a worker that binds it at its start sees the domain's first publication on a later lookup ([agent tools](managed-worktrees.md#agent-tools)). diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 6ed8f0c4ab..abc21aa3eb 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:102-910`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:105-913`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:355-404`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:358-407`). - Inside both windows a request reuses the published source without any network call. @@ -102,6 +102,16 @@ default to five minutes and are configured separately cannot expose it. A still-writing root stays masked and its acquiring owner releases it after its worker stops. Cleanup of a failed attempt discards only that attempt's root and preserves a newer valid publication. + Source freshness has a separate comparison: native publication accepts only + the previously observed root or an absent alias, and the catalog transaction + compares the previous root again. A delayed fetch cannot overwrite a newer + commit even when no authority invalidation occurred. Cache/recovery repair + cannot replace a different native alias target. A concurrent acquisition of + the exact independently resolved commit can validate the new cache using + its own turn's wire and allowance; it never joins the other turn's operation + or reports a different commit as fresh. Failed staging cleanup is separate + from authority containment, so recovering from this conflict cannot suppress + a later actual authority refusal. Repository metadata fences every cached and in-flight revision of that repository. Older requests cannot publish or restore public state after a newer private or refused observation, even before the first catalog row @@ -150,7 +160,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:518-572`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:521-575`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -249,9 +259,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:295-310`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:298-313`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:313-338`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:316-341`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -273,7 +283,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:429-445`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:432-448`). There is no idle expiry. ## Revocation and recovery @@ -286,7 +296,7 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1000-1025`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1029-1054`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists and, when @@ -296,7 +306,7 @@ or permanently withdrawn roots remain masked until a fresh authorized request; startup never renews their authority or exposes them to already-bound views. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1030-1074`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1059-1103`). ## Evidence diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index fd87331596..a9cb3576b1 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4532,6 +4532,17 @@ intents, which older keepers refuse rather than ignoring the guard; older strict control schemas also reject the new option before creating a root. The managed host refuses missing support, without an unguarded fallback. +The client also accepts `poolPublish(id, view, name, signal?, expectedRoots?)`. +The optional native `expectedRoots` is a list of one or two generated root +identities or `null` for an absent name. Under its mutation lock, the keeper +refuses with `unavailable` unless the current alias target is in that list, +before moving a root or replacing the alias. Managed publication binds this +native comparison and an atomic catalog comparison to the publication it +observed before acquisition. A concurrent newer revision cannot be replaced +by a delayed request. Live cache/recovery repair accepts only its own root or +an absent alias; it cannot overwrite another root. An older strict keeper +refuses this optional field and the host never retries it unconditionally. + ### Reference source acquisition (additive, #2429) `ServerConfig.referenceSource?` is `{ validationMs, refreshMs, operations }`. @@ -4560,6 +4571,13 @@ checkpoint through the fixed worker-UID reader, with the bounds of caller-generated UUID naming one worker generation. `NativePoolRecord.purpose` gains `checkpoint`, and records gain `access`, the generation holding a writable worktree, else `null`; earlier records read as `access: null`. +Host worktree records retain `repository_url` separately from their canonical +repository key, populated from the actual source endpoint at allocation. +Migration 092 backfills retained catalog endpoints. Revalidation binds that +URL to the stored key before dispatch, including after grant revocation has +removed the source catalog row. Historical legacy records with neither a +retained URL nor a catalog endpoint refuse with `unavailable` until the source +is explicitly requested; they never guess an endpoint by adding `.git`. `poolCreate` refuses the `checkpoint` purpose and a checkpoint as its source. `poolRelease` refuses a writable worktree whose record names an access generation with `invalid`, deleting nothing; park it first (#2729). diff --git a/packages/ui-sdk/src/server/native-brain-manager-client.ts b/packages/ui-sdk/src/server/native-brain-manager-client.ts index 2a1e9dd52f..5984818270 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-client.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-client.ts @@ -301,7 +301,8 @@ export function createNativeBrainManagerClient(input: { socketPath: string; time poolRelease: async (id: string, signal?: AbortSignal): Promise => control({ operation: "poolRelease", id }, signal), listPoolRecovery: async (after: string | null = null, signal?: AbortSignal): Promise<{ records: NativePoolRecord[]; next: string | null }> => control({ operation: "listPoolRecovery", after }, signal), - poolPublish: async (id: string, view: string, name: string, signal?: AbortSignal): Promise => control({ operation: "poolPublish", id, view, name }, signal), + poolPublish: async (id: string, view: string, name: string, signal?: AbortSignal, expectedRoots?: readonly (string | null)[]): Promise => + control({ operation: "poolPublish", id, view, name, ...(expectedRoots ? { expectedRoots: [...expectedRoots] } : {}) }, signal), poolUnpublish: async (view: string, name: string, signal?: AbortSignal): Promise<{ view: string; name: string; removed: boolean }> => control({ operation: "poolUnpublish", view, name }, signal), poolWithdraw: async (id: string, signal?: AbortSignal): Promise => control({ operation: "poolWithdraw", id }, signal), diff --git a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts index 08d9189672..bfb9b44c30 100644 --- a/packages/ui-sdk/src/server/native-brain-manager-protocol.ts +++ b/packages/ui-sdk/src/server/native-brain-manager-protocol.ts @@ -42,7 +42,8 @@ export const nativeManagerRequest = z.discriminatedUnion("operation", [ z.object({ operation: z.literal("listPoolRecovery"), after: nativeCheckpointId.nullable() }).strict(), // Reference publication (#2429). A view is one caller-generated sharing // domain; the manager owns its directory and swaps one name atomically. - z.object({ operation: z.literal("poolPublish"), id: nativeCheckpointId, view: nativeCheckpointId, name: nativePoolName }).strict(), + z.object({ operation: z.literal("poolPublish"), id: nativeCheckpointId, view: nativeCheckpointId, name: nativePoolName, + expectedRoots: z.array(nativeCheckpointId.nullable()).min(1).max(2).optional() }).strict(), z.object({ operation: z.literal("poolUnpublish"), view: nativeCheckpointId, name: nativePoolName }).strict(), // A view's directory, opened before its first publication so a worker can bind it (#2432). z.object({ operation: z.literal("poolView"), view: nativeCheckpointId }).strict(), diff --git a/packages/ui-sdk/src/server/native-reference-pool.ts b/packages/ui-sdk/src/server/native-reference-pool.ts index 666e1ee877..d269a48f05 100644 --- a/packages/ui-sdk/src/server/native-reference-pool.ts +++ b/packages/ui-sdk/src/server/native-reference-pool.ts @@ -923,13 +923,22 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { * single rename, so a reader that binds the view resolves either the whole * previous root or the whole new one, never staging. */ - async function publish(request: { id: string; view: string; name: string }, signal?: AbortSignal): Promise { + async function publish(request: { id: string; view: string; name: string; expectedRoots?: readonly (string | null)[] }, signal?: AbortSignal): Promise { nativePoolName.parse(request.name); let intent = intents.get(request.id); if (!intent || intent.purpose !== "source") throw new NativeBrainManagerError("unknown", "Only a recorded reference source root can be published."); if (intent.publicationRevoked) throw new NativeBrainManagerError("released", "This source root's publication authority was permanently withdrawn."); if (intent.state !== "sealed") throw new NativeBrainManagerError(["deleting", "deleted", "reclaimed"].includes(intent.state) ? "released" : "invalid", "Only a sealed reference source root can be published."); if (intent.view && intent.view !== request.view) throw new NativeBrainManagerError("invalid", "A published reference root belongs to exactly one view."); + const name = join(viewPath(request.view), request.name); + if (request.expectedRoots) { + // Serialized with every publisher, before any root move or name swap. + // A delayed acquisition cannot replace another owner's newer revision. + if ((existsSync(name) && !isLink(name)) || (isLink(name) && !nativeCheckpointId.safeParse(readlinkSync(name)).success)) + throw new NativeBrainManagerError("unknown", "The current reference publication is not a recorded root name."); + const current = isLink(name) ? readlinkSync(name) : null; + if (!request.expectedRoots.includes(current)) throw new NativeBrainManagerError("unavailable", "The reference publication changed; request it again."); + } await verifyRoot(intent, signal); ensureView(request.view); if (!intent.view) intent = await move(intent, request.view, signal); @@ -938,7 +947,7 @@ export async function createNativeReferencePool(context: ReferencePoolContext) { await helper(["seal", location(intent)], signal); if (!(await verifyRoot(intent, signal)).readOnly) throw new NativeBrainManagerError("unknown", "A published reference root did not reseal."); } - const name = join(viewPath(request.view), request.name), temporary = join(viewPath(request.view), `.${request.name}.${randomUUID()}`); + const temporary = join(viewPath(request.view), `.${request.name}.${randomUUID()}`); if (existsSync(name) && !lstatSync(name).isSymbolicLink()) throw new NativeBrainManagerError("unknown", "A reference view name is occupied by something other than a published name."); symlinkSync(intent.id, temporary); try { renameSync(temporary, name); } catch (error) { unlinkSync(temporary); throw error; } diff --git a/packages/ui-sdk/tests/native-brain-manager.test.ts b/packages/ui-sdk/tests/native-brain-manager.test.ts index 15e97330d8..de0ea63c22 100644 --- a/packages/ui-sdk/tests/native-brain-manager.test.ts +++ b/packages/ui-sdk/tests/native-brain-manager.test.ts @@ -144,12 +144,17 @@ test("Unix source creation explicitly opts into permanent withdrawal without cha const client = createNativeBrainManagerClient({ socketPath, timeoutMs: 1000, maxDeltaBytes: 64 }); expect(await client.poolCreate(ID, "source", null, 4096, undefined, true), "PERMANENT_WITHDRAWAL_RECEIPT_REACHES_CALLER").toMatchObject({ publicationRevoked: false }); await client.poolCreate(SECOND, "source", null, 4096); + await client.poolPublish(ID, SECOND, "ithaca", undefined, [ID, null]); expect(requests, "PERMANENT_WITHDRAWAL_OPTION_REACHES_NATIVE_KEEPER").toEqual([ { operation: "poolCreate", id: ID, purpose: "source", from: null, allowanceBytes: 4096, permanentWithdrawal: true }, { operation: "poolCreate", id: SECOND, purpose: "source", from: null, allowanceBytes: 4096 }, + { operation: "poolPublish", id: ID, view: SECOND, name: "ithaca", expectedRoots: [ID, null] }, ]); for (const permanentWithdrawal of [false, null, 1, "true"]) expect(nativeManagerRequest.safeParse({ operation: "poolCreate", id: ID, purpose: "source", from: null, allowanceBytes: 4096, permanentWithdrawal }).success).toBe(false); + for (const expectedRoots of [[], [ID, null, SECOND], ["../ithaca"], [1]]) + expect(nativeManagerRequest.safeParse({ operation: "poolPublish", id: ID, view: SECOND, name: "ithaca", expectedRoots }).success, + "NATIVE_PUBLICATION_EXPECTATION_IS_BOUNDED_ROOT_IDENTITIES").toBe(false); }); test("lost Unix response is unknown and never an inferred absence or automatic retry", async () => { diff --git a/packages/ui-server/migrations/092_reference_worktree_urls.sql b/packages/ui-server/migrations/092_reference_worktree_urls.sql new file mode 100644 index 0000000000..e230b267bb --- /dev/null +++ b/packages/ui-server/migrations/092_reference_worktree_urls.sql @@ -0,0 +1,9 @@ +-- Canonical authority keys do not reconstruct the endpoint used to acquire a +-- legacy source. Keep it with the worktree after source/grant cache cleanup. +ALTER TABLE reference_worktrees ADD COLUMN repository_url TEXT; +UPDATE reference_worktrees SET repository_url = ( + SELECT s.url FROM reference_sources s + WHERE s.domain = reference_worktrees.domain + AND s.repository = reference_worktrees.repository + AND s.revision = reference_worktrees.revision +); diff --git a/packages/ui-server/src/brain/native-brain-leases.ts b/packages/ui-server/src/brain/native-brain-leases.ts index 3f41f40da1..d74790d104 100644 --- a/packages/ui-server/src/brain/native-brain-leases.ts +++ b/packages/ui-server/src/brain/native-brain-leases.ts @@ -184,9 +184,9 @@ export async function createNativeBrainLeaseManager(raw: Client, options: { if (poolRow(id)?.state !== "held") throw new NativeBrainManagerError("unknown", "Only this app's held reference pool root can be sealed."); return raw.poolSeal(id, signal); }); }, - poolPublish(id, view, name, signal) { return operation(async () => { + poolPublish(id, view, name, signal, expectedRoots) { return operation(async () => { if (poolRow(id)?.state !== "held") throw new NativeBrainManagerError("unknown", "Only this app's held reference pool root can be published."); - const record = await raw.poolPublish(id, view, name, signal); + const record = await raw.poolPublish(id, view, name, signal, expectedRoots); if (record.id !== id || record.view !== view || record.state !== "sealed") throw new NativeBrainManagerError("unknown", "Reference publication reply does not match its durable lease identity."); return record; }); }, diff --git a/packages/ui-server/src/brain/reference-source-writes.ts b/packages/ui-server/src/brain/reference-source-writes.ts index 6cf0bb45b5..25b61ac5b9 100644 --- a/packages/ui-server/src/brain/reference-source-writes.ts +++ b/packages/ui-server/src/brain/reference-source-writes.ts @@ -79,9 +79,11 @@ export function sourceWrites(db: Database) { const view = sourceView(domain, viewId); return { roots, view }; }, - sourcePublish(path: string, domain: string, repository: string, revision: string, url: string, name: string, id: string, commit: string, ref: string, grantId: string | null, at: number, acquisition?: ReferenceAcquisition, expected?: SourceAuthority) { + sourcePublish(path: string, domain: string, repository: string, revision: string, url: string, name: string, id: string, commit: string, ref: string, grantId: string | null, at: number, acquisition?: ReferenceAcquisition, expected?: SourceAuthority, publication?: { rootId: string | null }) { return db.transaction(() => { if (expected && !sourceAuthorityCurrent(db, expected)) return false; + const current = db.query("SELECT root_id FROM reference_sources WHERE domain = ? AND repository = ? AND revision = ?").get(domain, repository, revision) as { root_id: string | null } | null; + if (publication && (current?.root_id ?? null) !== publication.rootId) return false; if (acquisition) db.query(`INSERT INTO reference_acquisitions (root_id, acquisition_id, brain, principal_id, turn_id, repository_id, owner_id, owner, repository_name, ref, commit_id, tree_id, native_root_id, native_uuid, native_generation, grant_id, network_bytes, acquired_at) diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index b1c7e22ba0..e850b9982e 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -61,6 +61,8 @@ export interface ReferenceSourceLease { /** Entry inside the view that resolves to the current complete revision. */ name: string; repository: string; + /** Actual fetched endpoint, retained independently of the canonical authority key. Host-only. */ + repositoryUrl: string; revision: string; commit: string; /** Sealed pool root holding `commit`; a managed worktree (#2430) snapshots it. */ @@ -85,7 +87,8 @@ interface Operation { key: string; domain: string; principalId: string | null; g interface InvalidatedRoot { id: string; state: string; repository: string; revision: string } type Outcome = { kind: "source"; row: SourceRow; stale: boolean; error: string | null } | { kind: "not-public"; reason: "denied" | "unavailable"; detail: string }; /** Only host callers reading the catalog use repositoryKey; tool inputs remain raw strings. */ -type RepositoryInput = { repository: unknown; repositoryKey?: never } | { repository?: never; repositoryKey: string }; +type RepositoryInput = { repository: unknown; repositoryKey?: never; repositoryUrl?: never } + | { repository?: never; repositoryKey: string; repositoryUrl?: string }; const PUBLIC = "public"; const privateDomain = (principalId: string) => `private:${principalId}`; @@ -259,7 +262,7 @@ export function createReferenceSources(options: { try { const view = await viewFor(source.domain); await write("sourceTouch", now(), source.domain, source.repository, source.revision); - return { domain: source.domain === PUBLIC ? "public" : "private", view: view.id, viewPath: view.hostPath!, name: source.name, repository: source.repository, + return { domain: source.domain === PUBLIC ? "public" : "private", view: view.id, viewPath: view.hostPath!, name: source.name, repository: source.repository, repositoryUrl: source.url, revision: source.revision, commit: source.commit_id, rootId: source.root_id, refreshedAt: source.refreshed_at, validatedAt: source.validated_at, stale, error, assertAuthority, release }; } catch (error) { release(); throw error; } @@ -555,10 +558,12 @@ export function createReferenceSources(options: { recheck(); if (input.managed) await input.managed.access.revalidate(); recheck(); + if (input.managed && (row(domain, repository.canonical, revision)?.root_id ?? null) !== previousRoot) + throw new ReferenceSourceError("unavailable", "A newer source was published while this acquisition waited; request it again."); publishing = true; pendingPublications.set(staging.id, { key, view: view.id, name }); hiddenRoots.delete(staging.id); - const published = await pool.poolPublish(staging.id, view.id, name, signal); + const published = await pool.poolPublish(staging.id, view.id, name, signal, input.managed ? [previousRoot, null] : undefined); recheck(); let acquisition: ReferenceAcquisition | undefined; if (input.managed) { @@ -570,8 +575,11 @@ export function createReferenceSources(options: { grantId: input.managed.access.grantId, networkBytes: input.managed.access.bytes().chargedBytes, at: now() }; } const at = now(), grantId = domain === PUBLIC ? null : (input.grant && isLiveReferenceGrant(db, input.grant.id, at) ? input.grant.id : authorize(domain, input.principalId, repository)!.id); - if (!await write("sourcePublish", dirname(published.path!), domain, repository.canonical, revision, repository.url, name, staging.id, commit, input.ref, grantId, at, acquisition, input.managed?.authority)) - throw new ReferenceSourceError("unauthorized", "A newer durable authority observation refused this publication."); + if (!await write("sourcePublish", dirname(published.path!), domain, repository.canonical, revision, repository.url, name, staging.id, commit, input.ref, grantId, at, acquisition, input.managed?.authority, + input.managed ? { rootId: previousRoot } : undefined)) { + recheck(); + throw new ReferenceSourceError("unavailable", "A newer source or authority observation refused this publication; request it again."); + } recheck(); pendingPublications.delete(staging.id); withdrawn.delete(key); @@ -583,6 +591,7 @@ export function createReferenceSources(options: { try { await hideRoot(id); } catch (error) { warn("superseded reference root stays in its view until the next bind hides it", error); } } }); + return staging.id; } catch (error) { if (input.managed) await input.managed.containFailure(error, publishing, staging.id) .catch(cleanup => warn("reference authority containment is incomplete; bind preparation retries it", cleanup)); @@ -633,7 +642,7 @@ export function createReferenceSources(options: { const containFailure = (error: unknown, publishing: boolean, publicationId?: string): Promise => { if (containment) return containment; const reason = failureReason(error), domains = [PUBLIC, privateDomain(input.principalId)]; - let work: Promise = Promise.resolve(); + let work: Promise | undefined; if (error instanceof GitHubReferenceMetadataError) { work = Promise.all(domains.map(domain => reason === "denied" ? withdrawRepository(domain, repository.canonical, revision) : suspendRepository(domain, repository.canonical, revision))); @@ -647,13 +656,14 @@ export function createReferenceSources(options: { } else if (publishing && publicationId) { // Cleanup is not a new metadata observation. Discard just this // attempt; another owner may already have published a valid root. - work = (async () => { + return (async () => { const root = await write<{ id: string; state: string } | null>("sourceDiscard", publicationId); await hideRecordedRoot(root ?? { id: publicationId, state: "staging" }); })(); } else if (!signal.aborted && context.current() && openAttempted && !accessOpened) { work = Promise.all(domains.map(domain => domain === PUBLIC && publicWithdrawal ? publicWithdrawal : suspendRepository(domain, repository.canonical, revision))); } + if (!work) return Promise.resolve(); containment = work.then(() => {}); return containment; }; @@ -685,12 +695,12 @@ export function createReferenceSources(options: { assertCurrent(); if (!check.ok) throw new ReferenceSourceError(check.reason === "missing" ? "missing" : check.reason === "denied" ? "unauthorized" : "unavailable", check.detail); const previous = row(domain, repository.canonical, revision); - let reused = false; - if (usable(previous) && previous.validated_at !== 0 && previous.commit_id === check.commit && previous.ref === check.ref) { - await exclusive(operation.key, async () => { + const validateCached = async (candidate: SourceRow | null): Promise => { + if (!usable(candidate) || candidate.validated_at === 0 || candidate.commit_id !== check.commit || candidate.ref !== check.ref) return; + return exclusive(operation.key, async () => { assertCurrent(); const current = row(domain, repository.canonical, revision); - if (!usable(current) || current.root_id !== previous.root_id || withdrawn.has(operation.key)) return; + if (!usable(current) || current.root_id !== candidate.root_id || withdrawn.has(operation.key)) return; const record = await pool.poolSeal(current.root_id, signal); assertCurrent(); // Hidden/revoked roots never regain publication authority. Fresh @@ -700,23 +710,41 @@ export function createReferenceSources(options: { if (!referenceAcquisitionMatches(db, current.root_id, record, { brain: options.brain, commit: check.commit, ref: check.ref, identity: access!.identity })) return; await access!.revalidate(); assertCurrent(); + if (row(domain, repository.canonical, revision)?.root_id !== current.root_id) + throw new ReferenceSourceError("unavailable", "A newer source replaced this cached publication; request it again."); + // Repair a lost alias only while it is absent or still names this + // root. The native lock preserves a concurrent newer publication. + await pool.poolPublish(current.root_id, (await viewFor(domain)).id, current.name, signal, [current.root_id, null]); + assertCurrent(); const at = now(); if (!await write("sourceValidate", at, at, check.ref, domain, repository.canonical, revision, - domain === PUBLIC ? publicAuthority : privateAuthority, current.root_id)) - throw new ReferenceSourceError("unauthorized", "A newer durable authority observation refused this validation."); + domain === PUBLIC ? publicAuthority : privateAuthority, current.root_id)) { + assertCurrent(); + throw new ReferenceSourceError("unavailable", "A newer source or authority observation refused this validation; request it again."); + } assertCurrent(); - reused = true; + return current.root_id; }); - } - if (!reused) await acquire(signal, { domain, principalId: input.principalId, repository, revision, + }; + let selectedRoot = await validateCached(previous); + if (!selectedRoot) try { selectedRoot = await acquire(signal, { domain, principalId: input.principalId, repository, revision, grant: domain === PUBLIC ? null : authorize(domain, input.principalId, repository), credential: null, ref: check.ref, expectedCommit: check.commit, previous, managed: { access, context, id, authority: domain === PUBLIC ? publicAuthority : privateAuthority, assertCurrent, containFailure } }); + } catch (error) { + // A concurrent request may have supplied this exact independently + // resolved target. Validate it on this turn's wire; never join its + // operation or return a different commit as a fresh result. + const replacement = row(domain, repository.canonical, revision); + if (signal.aborted || !context.current() || (failureReason(error) !== "unavailable" && (error as { code?: string }).code !== "unavailable") + || replacement?.root_id === previous?.root_id) throw error; + selectedRoot = await validateCached(replacement); + if (!selectedRoot) throw error; + } assertCurrent(); const current = row(domain, repository.canonical, revision); - if (!usable(current)) throw new ReferenceSourceError("unavailable", "Managed source publication is unavailable."); - // Managed roots are published exactly once. Restoring an old identity - // would race a completed native withdrawal; only acquire() publishes. + if (!usable(current) || current.root_id !== selectedRoot) throw new ReferenceSourceError("unavailable", "Managed source publication changed; request it again."); + // A withdrawn identity is never restored; live cache repair is conditional. suspended.delete(operation.key); unsettled.delete(operation.key); result = await lease(current, false, null, () => { assertTurn(); currentAccess.assertAuthority(); @@ -765,14 +793,15 @@ export function createReferenceSources(options: { repository = referenceRepositoryFromKey(input.repositoryKey); // Keep the actual retained endpoint spelling for other Git hosts too. const known = row(privateDomain(input.principalId), repository.canonical, revision) ?? row(PUBLIC, repository.canonical, revision); - if (known) { - const location = repositoryLocation(known.url); + const retainedUrl = input.repositoryUrl ?? known?.url; + if (retainedUrl) { + const location = repositoryLocation(retainedUrl); if (location.canonical !== repository.canonical) throw new Error("The retained URL does not match its repository key."); repository = location; - } + } else if (!isManaged(repository.canonical)) throw new ReferenceSourceError("unavailable", "The original repository endpoint is no longer retained; request it explicitly before accessing this worktree."); } else repository = repositoryLocation(input.repository); } - catch (error) { throw new ReferenceSourceError("invalid", (error as Error).message); } + catch (error) { if (error instanceof ReferenceSourceError) throw error; throw new ReferenceSourceError("invalid", (error as Error).message); } if (isManaged(repository.canonical)) return managedRequest(input, repository, revision); const probeKey = `${repository.canonical}\u0000${revision}`; const fresh = (source: SourceRow | null) => usable(source) && validationLive(source) && now() < source.refreshed_at + limits.refreshMs; @@ -1059,7 +1088,8 @@ export function createReferenceSources(options: { keep.add(source.root_id!); continue; } - try { await pool.poolPublish(source.root_id!, sourceWrites(db).sourceView(source.domain, randomUUID()).id, source.name); keep.add(source.root_id!); continue; } + try { await pool.poolPublish(source.root_id!, sourceWrites(db).sourceView(source.domain, randomUUID()).id, source.name, undefined, + isManaged(source.repository) ? [source.root_id!, null] : undefined); keep.add(source.root_id!); continue; } catch (error) { warn("reference source publication could not be restored", error); } } db.query("UPDATE reference_sources SET root_id = NULL WHERE domain = ? AND repository = ? AND revision = ? AND root_id = ?").run(source.domain, source.repository, source.revision, source.root_id); diff --git a/packages/ui-server/src/brain/reference-worktree-writes.ts b/packages/ui-server/src/brain/reference-worktree-writes.ts index 4ce173fc78..ff00c07fcc 100644 --- a/packages/ui-server/src/brain/reference-worktree-writes.ts +++ b/packages/ui-server/src/brain/reference-worktree-writes.ts @@ -39,9 +39,9 @@ export function worktreeWrites(db: Database) { recoverHolder(id: string, holder: string | null) { db.query("UPDATE reference_worktrees SET holder = NULL WHERE id = ? AND holder = ?").run(id, holder); }, - allocate(id: string, principalId: string, domain: string, repository: string, revision: string, commit: string, sourceRoot: string, allowance: number, at: number, accessedAt: number) { - db.query(`INSERT INTO reference_worktrees (id, principal_id, domain, repository, revision, base_commit, source_root, baseline, allowance, state, created_at, accessed_at) - VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, 'creating', ?, ?)`).run(id, principalId, domain, repository, revision, commit, sourceRoot, allowance, at, accessedAt); + allocate(id: string, principalId: string, domain: string, repository: string, revision: string, commit: string, sourceRoot: string, allowance: number, at: number, accessedAt: number, repositoryUrl?: string) { + db.query(`INSERT INTO reference_worktrees (id, principal_id, domain, repository, revision, base_commit, source_root, baseline, allowance, state, created_at, accessed_at, repository_url) + VALUES (?, ?, ?, ?, ?, ?, ?, NULL, ?, 'creating', ?, ?, ?)`).run(id, principalId, domain, repository, revision, commit, sourceRoot, allowance, at, accessedAt, repositoryUrl ?? null); }, recordRoot(uuid: string | null, id: string) { db.query("UPDATE reference_worktrees SET root_uuid = ? WHERE id = ?").run(uuid, id); diff --git a/packages/ui-server/src/brain/reference-worktrees.ts b/packages/ui-server/src/brain/reference-worktrees.ts index 37228055e6..1b9b35599c 100644 --- a/packages/ui-server/src/brain/reference-worktrees.ts +++ b/packages/ui-server/src/brain/reference-worktrees.ts @@ -115,6 +115,7 @@ export interface ReferenceWorktreeRow { id: string; principal_id: string; domain: string; repository: string; revision: string; base_commit: string | null; source_root: string; baseline: string | null; allowance: number; state: "creating" | "active" | "released" | "expired"; created_at: number; accessed_at: number; released_at: number | null; holder: string | null; cleanup: string | null; root_uuid: string | null; + repository_url: string | null; } type WorktreeRow = ReferenceWorktreeRow; /** A removal's durable receipt (#2431). */ @@ -224,10 +225,11 @@ export function createReferenceWorktrees(options: { * its repository, whatever the revision's current visibility; the * repository's revision is then validated under the source's own clocks. */ - async function authorize(row: Pick, signal?: AbortSignal, acquisition?: ReferenceAcquisitionContext) { + async function authorize(row: Pick, signal?: AbortSignal, acquisition?: ReferenceAcquisitionContext) { covered(row); try { - const source = await options.sources.request({ principalId: row.principal_id, repositoryKey: row.repository, revision: row.revision, signal, acquisition }); + const location = { repositoryKey: row.repository, ...(row.repository_url ? { repositoryUrl: row.repository_url } : {}) }; + const source = await options.sources.request({ principalId: row.principal_id, ...location, revision: row.revision, signal, acquisition }); try { // A public starting snapshot cannot bypass the private authority the // current source check required. A private starting snapshot keeps its @@ -468,7 +470,7 @@ export function createReferenceWorktrees(options: { const allowance = (await pool.poolStatus(input.signal)).limits.operationBytes; acquiringAuthority(input, authority); // Recorded before the pool sees it: recovery and eviction protection both start here. - await write("allocate", id, input.principalId, lease.domain === "public" ? "public" : `private:${input.principalId}`, lease.repository, lease.revision, lease.commit, lease.rootId, allowance, at, at); + await write("allocate", id, input.principalId, lease.domain === "public" ? "public" : `private:${input.principalId}`, lease.repository, lease.revision, lease.commit, lease.rootId, allowance, at, at, lease.repositoryUrl); let activating = false; try { acquiringAuthority(input, authority); diff --git a/packages/ui-server/tests/helpers/reference-pool-double.ts b/packages/ui-server/tests/helpers/reference-pool-double.ts index 56fb575224..3939d85951 100644 --- a/packages/ui-server/tests/helpers/reference-pool-double.ts +++ b/packages/ui-server/tests/helpers/reference-pool-double.ts @@ -64,12 +64,16 @@ export function referencePoolDouble(root: string, options: { capacityRoots?: num record!.state = "sealed"; return record!; }, - async poolPublish(id, view, name) { + async poolPublish(id, view, name, _signal, expectedRoots) { const record = records.get(id); if (!record || record.purpose !== "source") fail("unknown", "Only a recorded reference source root can be published."); if (record!.publicationRevoked) fail("released", "This source root's publication authority was permanently withdrawn."); if (record!.state !== "sealed") fail("invalid", "Only a sealed reference source root can be published."); if (record!.view && record!.view !== view) fail("invalid", "A published reference root belongs to exactly one view."); + const entry = join(views, view, name); + let current: string | null = null; + try { current = readlinkSync(entry); } catch { /* no published alias */ } + if (expectedRoots && !expectedRoots.includes(current)) fail("unavailable", "The reference publication changed; request it again."); mkdirSync(join(views, view), { recursive: true }); if (!record!.view) { renameSync(join(roots, id), join(views, view, id)); record!.view = view; record!.path = location(record!); } const temporary = join(views, view, `.${name}.${id}`); diff --git a/packages/ui-server/tests/native-brain-leases.test.ts b/packages/ui-server/tests/native-brain-leases.test.ts index df0c13b7d3..632400cd3e 100644 --- a/packages/ui-server/tests/native-brain-leases.test.ts +++ b/packages/ui-server/tests/native-brain-leases.test.ts @@ -189,6 +189,11 @@ test("source leases forward permanent withdrawal and refuse a keeper without its await expectRejection(f.owner.client.poolCreate(ID, "source", null, 4096, undefined, true), "durable lease identity"); supported = true; expect(await f.owner.client.poolCreate(ID, "source", null, 4096, undefined, true)).toMatchObject({ publicationRevoked: false }); + f.native.client.poolPublish = async (id, view, _name, _signal, expectedRoots) => { + expect(expectedRoots, "LEASE_OWNER_FORWARDS_PUBLICATION_EXPECTATIONS").toEqual([ID, null]); + return { id, purpose: "source", from: null, allowanceBytes: 4096, state: "sealed", root: null, path: null, ownerBytes: null, reason: null, view, access: null }; + }; + await f.owner.client.poolPublish(ID, OTHER, "ithaca", undefined, [ID, null]); } finally { await f.close(); } }); diff --git a/packages/ui-server/tests/reference-source-authority.test.ts b/packages/ui-server/tests/reference-source-authority.test.ts index a941d8bbb8..67d501e1eb 100644 --- a/packages/ui-server/tests/reference-source-authority.test.ts +++ b/packages/ui-server/tests/reference-source-authority.test.ts @@ -67,3 +67,13 @@ test("a committed fence atomically expires matching validation across aliases an for (const row of rows) expect(row.validated_at, "FENCE_COMMIT_CANNOT_LEAVE_OLD_POSITIVE_VALIDATION") .toBe(row.domain === "public" && row.repository !== `${repository}.git` ? 0 : at); }); + +test("publication commit cannot replace a newer root while authority versions remain valid", () => { + const expected = sourceAuthority(db, "public", repository, "main"); + for (const id of ["odysseus-old-root", "telemachus-new-root"]) writes.sourceStage(id, "public", repository, "main", at); + writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", repository, "ithaca", "telemachus-new-root", "c".repeat(40), "refs/heads/main", null, at); + expect(sourceAuthorityCurrent(db, expected)).toBe(true); + expect(writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", repository, "ithaca", "odysseus-old-root", "a".repeat(40), "refs/heads/main", null, at, undefined, expected, { rootId: null }), + "PUBLICATION_TRANSACTION_PRESERVES_NEWER_ROOT").toBe(false); + expect(db.query("SELECT root_id, commit_id FROM reference_sources").get()).toEqual({ root_id: "telemachus-new-root", commit_id: "c".repeat(40) }); +}); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index a3902ab4e4..2d262c5090 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -32,7 +32,7 @@ async function fixture(options: { private?: boolean; worker?: boolean; repositor if (writer) registerReferenceWrites(db, writer); const credentials: Record = { GITHUB_TOKEN: "odysseus-fixture-token" }; const metadata: string[] = [], metadataPaths: string[] = [], git: unknown[] = []; - const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200, invalidAt: 0, invalidJsonAt: 0, endOnPrivateMetadata: false }; + const state = { current: true, ownerId: 201, clock: Date.now(), fetches: 0, private: options.private ?? false, status: 200, invalidAt: 0, invalidJsonAt: 0, endOnPrivateMetadata: false, commit }; const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { metadata.push(request.headers.get("authorization") ?? "anonymous"); metadataPaths.push(new URL(request.url).pathname); @@ -49,8 +49,8 @@ async function fixture(options: { private?: boolean; worker?: boolean; repositor const egress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe(value) { records.push(value); } }); const secondEgress = await startEgressProxy({ mode: "record", allow: [], deny: [], outwardHosts: [], maxBytes: 4 * 1048576, observe() {} }); const transport: ReferenceTransport = { - async resolve(input) { git.push(input); return { ok: true, commit, ref: `refs/heads/${input.revision}` }; }, - async fetch(input) { git.push(input); state.fetches++; writeFileSync(join(input.root, "README.md"), "Odysseus charts Ithaca on 2026-07-12.\n"); return { commit }; }, + async resolve(input) { git.push(input); return { ok: true, commit: state.commit, ref: `refs/heads/${input.revision}` }; }, + async fetch(input) { git.push(input); state.fetches++; writeFileSync(join(input.root, "README.md"), "Odysseus charts Ithaca on 2026-07-12.\n"); writeFileSync(join(input.root, ".reference-commit"), state.commit); return { commit: state.commit }; }, async checkout() {}, async tree() { return tree; }, }; @@ -124,6 +124,58 @@ test("a cached shared root still uses the requesting principal and turn's own me } finally { await f.close(); } }); +for (const wait of ["seal", "native-publication"] as const) +test(`an older managed acquisition cannot replace a newer revision after ${wait}`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), seal = f.pool.poolSeal, publish = f.pool.poolPublish; + let paused = false, fresh: Awaited> | undefined, exposedOlder = false; + const pause = async () => { if (!paused) { paused = true; arrived.resolve(); await resume.promise; } }; + if (wait === "seal") f.pool.poolSeal = async (...args) => { const record = await seal(...args); await pause(); return record; }; + else f.pool.poolPublish = async (...args) => { const older = !paused; await pause(); const record = await publish(...args); if (older) exposedOlder = true; return record; }; + const older = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; f.state.commit = "c".repeat(40); + fresh = await otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-newer-source-revision", egress: f.secondEgress, current: () => true } }); + expect(fresh.commit).toBe(f.state.commit); + resume.resolve(); const result = await older; + expect((f.db.query("SELECT commit_id FROM reference_sources WHERE domain = 'public'").get() as { commit_id: string }).commit_id, + "OLDER_ACQUISITION_CANNOT_ROLL_BACK_NEWER_COMMIT").toBe(f.state.commit); + expect(result.lease, "SUPERSEDED_ACQUISITION_RETURNS_NO_FRESH_LEASE").toBeUndefined(); + expect(exposedOlder, "DELAYED_NATIVE_PUBLICATION_CANNOT_REPLACE_NEWER_ROOT").toBe(false); + expect(readFileSync(join(fresh.viewPath, fresh.name, ".reference-commit"), "utf8")).toBe(f.state.commit); + } finally { resume.resolve(); (await older).lease?.release(); fresh?.release(); await otherSources.close(); otherDb.close(); await f.close(); } +}); + +test("recovering a same-commit publication conflict still contains a later private grant loss", async () => { + const f = await fixture({ private: true }), issued = f.grant(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), seal = f.pool.poolSeal, publish = f.pool.poolPublish; + let paused = false, fresh: Awaited> | undefined; + f.pool.poolSeal = async (...args) => { const record = await seal(...args); if (!paused) { paused = true; arrived.resolve(); await resume.promise; } return record; }; + const older = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; + fresh = await otherSources.request({ principalId: f.owner.id, repository, revision: "main", + acquisition: { turnId: "penelope-same-commit-publication", egress: f.secondEgress, current: () => true } }); + f.pool.poolPublish = async (...args) => { const record = await publish(...args); if (args[0] === fresh!.rootId) + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); return record; }; + resume.resolve(); const outcome = await older; + expect(outcome.lease).toBeUndefined(); + expect(existsSync(join(fresh.viewPath, fresh.rootId, "README.md")), "RECOVERED_CONFLICT_STILL_CONTAINS_LATER_GRANT_REVOCATION").toBe(false); + expect(() => fresh!.assertAuthority()).toThrow(); + } finally { resume.resolve(); (await older).lease?.release(); fresh?.release(); await otherSources.close(); otherDb.close(); await f.close(); } +}); + +test("a retained worktree endpoint must still name its canonical authority key before dispatch", async () => { + const f = await fixture(); + try { + await expect(f.sources.request({ principalId: f.owner.id, repositoryKey: repository, repositoryUrl: "https://github.com/odysseus/return-home", revision: "main", + acquisition: { turnId: "odysseus-mismatched-retained-endpoint", egress: f.egress, current: () => true } }), + "RETAINED_ENDPOINT_MUST_MATCH_AUTHORITY_KEY").rejects.toMatchObject({ code: "invalid" }); + expect(f.metadata).toEqual([]); expect(f.git).toEqual([]); + } finally { await f.close(); } +}); + test("pre-proxy bind preparation with expired GitHub authority withholds source without network", async () => { const f = await fixture(); try { @@ -895,7 +947,7 @@ describe("live managed authority", () => { try { old = await f.request(); f.pool.poolUnpublish = async (...args) => { await pause(); return unpublish(...args); }; - f.pool.poolWithdraw = async (...args) => { await pause(); return withdraw(...args); }; + f.pool.poolWithdraw = async (...args) => { const record = await withdraw(...args); await pause(); return record; }; if (observation === "private") f.state.private = true; else f.state.status = 503; invalidating = f.request().then(lease => { lease.release(); return undefined; }, error => error); await arrived.promise; f.state.private = false; f.state.status = 200; diff --git a/packages/ui-server/tests/reference-worktrees.test.ts b/packages/ui-server/tests/reference-worktrees.test.ts index 91179e2ef2..0bce6ac5f0 100644 --- a/packages/ui-server/tests/reference-worktrees.test.ts +++ b/packages/ui-server/tests/reference-worktrees.test.ts @@ -93,6 +93,36 @@ describe("allocation", () => { }); describe("access", () => { + test("a restored grant revalidates the original unsuffixed endpoint after source catalog removal", async () => { + const repository = "http://127.0.0.1:8418/odysseus/ithaca", penelope = owner(), calls: string[] = []; + const pool = referencePoolDouble(join(root, "legacy-pool")); + const transport: ReferenceTransport = { + async resolve(input) { calls.push(input.repository.url); return input.repository.url === repository && input.token === TOKEN + ? { ok: true, commit: "a".repeat(40), ref: "refs/heads/main" } : { ok: false, reason: "denied", detail: "Only the original endpoint is authorized." }; }, + async fetch(input) { writeFileSync(join(input.root, "odyssey.md"), "Odysseus charts Ithaca.\n"); return { commit: "a".repeat(40) }; }, + async checkout() {}, + }; + let worktrees: ReturnType | undefined; + const sources = createReferenceSources({ db, pool, transport, brain: BRAIN, credentials: { GITHUB_TOKEN: TOKEN }, + dependents: id => Boolean(worktrees && referenceWorktreeDependents(db, id)) }); + worktrees = createReferenceWorktrees({ db, pool, sources, coverage: async () => {} }); + const issueGrant = () => createReferenceGrant(db, { brain: BRAIN, principalId: penelope.id, createdBy: penelope.id, + repositoryPrefix: repository, credential: "GITHUB_TOKEN", now: Date.now() }); + const issued = issueGrant(); + let generation: Awaited> | undefined; + try { + const item = await worktrees.allocate({ principalId: penelope.id, repository, revision: "main" }); + revokeReferenceGrant(db, { brain: BRAIN, principalId: penelope.id, id: issued.id, now: Date.now() }); + await sources.revoke({ grantIds: [issued.id], principalIds: [] }); + expect(db.query("SELECT 1 FROM reference_sources").get()).toBeNull(); + issueGrant(); generation = await worktrees.openGeneration({ principalId: penelope.id, turnId: "penelope-restored-source", profile: "governed" }); + const outcome = await worktrees.access({ worktreeId: item.id, principalId: penelope.id, generation: generation.id }).then(value => ({ value, error: undefined }), error => ({ value: undefined, error })); + expect(outcome.error, "RESTORED_GRANT_USES_ORIGINAL_ENDPOINT").toBeUndefined(); + expect(calls.every(url => url === repository), "STORED_KEY_IS_NEVER_GUESSED_AS_A_CLONE_URL").toBe(true); + expect(readFileSync(join(generation.path, item.id, "odyssey.md"), "utf8")).toContain("Odysseus"); + } finally { if (generation) await worktrees.closeGeneration(generation.id); await worktrees.close(); await sources.close(); } + }); + test("only an open generation of the owning principal receives a grant, after journal coverage", async () => { const { worktrees, order, pool } = service(); const penelope = owner(), telemachus = owner("Telemachus"); diff --git a/scripts/native-proof/reference-pool.native.ts b/scripts/native-proof/reference-pool.native.ts index 8869e516a8..273a901a29 100644 --- a/scripts/native-proof/reference-pool.native.ts +++ b/scripts/native-proof/reference-pool.native.ts @@ -453,6 +453,14 @@ const shapes = await create("staging", 32 * MIB); await call({ operation: "poolCreate", id: freshId, purpose: "source", from: id, allowanceBytes: 4 * MIB, permanentWithdrawal: true }); await seal(freshId); await call({ operation: "poolPublish", id: freshId, view: VIEW, name: "ithaca" }); + const delayedId = randomUUID(); + await call({ operation: "poolCreate", id: delayedId, purpose: "source", from: id, allowanceBytes: 4 * MIB, permanentWithdrawal: true }); + await seal(delayedId); + expect((await refusal({ operation: "poolPublish", id: delayedId, view: VIEW, name: "ithaca", expectedRoots: [id, null] })).code, + "REFERENCE_NATIVE_DELAYED_PUBLICATION_PRESERVES_NEWER_ROOT").toBe("unavailable"); + expect(readlinkSync(join(POOL, "views", VIEW, "ithaca"))).toBe(freshId); + await call({ operation: "poolPublish", id: delayedId, view: VIEW, name: "ithaca", expectedRoots: [freshId, null] }); + expect(readlinkSync(join(POOL, "views", VIEW, "ithaca")), "REFERENCE_NATIVE_MATCHING_PUBLICATION_CAN_ADVANCE").toBe(delayedId); await call({ operation: "poolWithdraw", id }); expect(readFileSync(join(POOL, "views", VIEW, "ithaca", "README.md"), "utf8"), "OLD_WITHDRAWAL_PRESERVES_NEW_ROOT").toContain("Odysseus"); expect((await call({ operation: "poolWithdraw", id: freshId })).publicationRevoked).toBe(true); @@ -461,7 +469,7 @@ const shapes = await create("staging", 32 * MIB); manager = await restart({}); expect((await call({ operation: "poolSeal", id: freshId })).publicationRevoked, "REFERENCE_NATIVE_WITHDRAWAL_SURVIVES_RESTART").toBe(true); - await release(freshId); await release(id); + await release(delayedId); await release(freshId); await release(id); } // 16. Acquisition (#2429): the real reference service and its real transport From 5ddadd45ed147a722d7cd3c7483cbee47ff3f31d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 12:59:32 +0000 Subject: [PATCH 24/27] CONTRACT: bind source withholding to confirmed root validation --- docs/decisions/managed-worktrees.md | 8 +- .../decisions/reference-source-acquisition.md | 23 ++-- docs/integration-contract/package-api.md | 5 + .../src/brain/reference-source-writes.ts | 6 +- .../ui-server/src/brain/reference-source.ts | 62 +++++++--- .../tests/reference-source-managed.test.ts | 108 ++++++++++++++++++ 6 files changed, 183 insertions(+), 29 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 0033a6b12e..227ca886be 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1137-1168`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1168-1199`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:931-969`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:951-989`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:843-860`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:858-875`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:975-984`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:997-1006`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index abc21aa3eb..6cd4696e8b 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -7,7 +7,7 @@ over the [reference pool](reference-pool-accounting.md). It uses the [owner-managed grants](reference-source-grants.md) as its only private authority. This record names the concrete choices the rulings left to implementation. The service is `createReferenceSources` -(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:105-913`), +(`createReferenceSources`, `packages/ui-server/src/brain/reference-source.ts:106-914`), created at host start when the native manager reports a reference pool, and closed with the app. The agent tool that requests source arrived with [#2432](https://github.com/schlessera/brain-kit/issues/2432) @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:358-407`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:371-420`). - Inside both windows a request reuses the published source without any network call. @@ -160,7 +160,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:521-575`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:536-590`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -232,6 +232,10 @@ access, owns its own authority check and budget; it never joins a foreign turn. The operation limit is 64 MiB or the remaining turn allowance, whichever is smaller. Lapsed GitHub source found during pre-proxy bind preparation is withheld without network, then restored only by an explicit admitted request. +Bind preparation treats a local suspension or withdrawal as settled only for +the exact catalog root and validation timestamp whose native hiding succeeded. +A replacement root or renewed validation is checked again when it expires; +failed catalog writes or native hiding never excuse that check. Maintenance admission may wait up to 30 seconds for each Git command, then returns `busy`. Cancellation stops that wait; the wire still checks the live turn and selected grant before dispatch, and the source service checks them @@ -259,9 +263,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:298-313`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:311-326`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:316-341`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:329-354`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -283,7 +287,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:432-448`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:438-454`). There is no idle expiry. ## Revocation and recovery @@ -296,7 +300,7 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1029-1054`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1053-1078`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists and, when @@ -304,9 +308,12 @@ private, a live grant still covers it. A source with live validation may have its name repaired after a lost publication reply. Expired, durably suspended or permanently withdrawn roots remain masked until a fresh authorized request; startup never renews their authority or exposes them to already-bound views. +Recovery rereads each catalog entry and expires validation only if its root +and validation timestamp still match, preserving another owner's renewal or +replacement after the initial scan. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1059-1103`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1083-1127`). ## Evidence diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index a9cb3576b1..2aa45c8026 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4545,6 +4545,11 @@ refuses this optional field and the host never retries it unconditionally. ### Reference source acquisition (additive, #2429) +Bind preparation skips an invalidated source only while its exact catalog root +and validation timestamp still match confirmed native hiding. A replacement or +renewal expires independently, and incomplete hiding is retried before binding. +Startup recovery preserves validation another owner renewed after its scan. + `ServerConfig.referenceSource?` is `{ validationMs, refreshMs, operations }`. The host edge resolves it from `BRAIN_UI_REFERENCE_VALIDATION_SECONDS` and `BRAIN_UI_REFERENCE_REFRESH_SECONDS` (default 300 each, 1–86400) and from diff --git a/packages/ui-server/src/brain/reference-source-writes.ts b/packages/ui-server/src/brain/reference-source-writes.ts index 25b61ac5b9..e59d94877a 100644 --- a/packages/ui-server/src/brain/reference-source-writes.ts +++ b/packages/ui-server/src/brain/reference-source-writes.ts @@ -57,8 +57,10 @@ export function sourceWrites(db: Database) { .run(at, refreshedAt, ref, domain, repository, revision, rootId ?? null, rootId ?? null).changes === 1; }).immediate(); }, - sourceSuspend(domain: string, repository: string, revision: string) { - db.query("UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ?").run(domain, repository, revision); + sourceSuspend(domain: string, repository: string, revision: string, rootId?: string, validatedAt?: number | null) { + return db.query(`UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ? + AND (? IS NULL OR root_id = ?) AND (? = 0 OR validated_at IS ?)`) + .run(domain, repository, revision, rootId ?? null, rootId ?? null, validatedAt === undefined ? 0 : 1, validatedAt ?? null).changes === 1; }, sourceFailed(detail: string, at: number, domain: string, repository: string, revision: string) { db.query("UPDATE reference_sources SET last_error = ?, last_failed_at = ? WHERE domain = ? AND repository = ? AND revision = ?").run(detail, at, domain, repository, revision); diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index e850b9982e..6f0e08d40e 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -85,6 +85,7 @@ interface SourceRow { } interface Operation { key: string; domain: string; principalId: string | null; grantId: string | null; controller: AbortController; joiners: number; promise: Promise } interface InvalidatedRoot { id: string; state: string; repository: string; revision: string } +interface WithheldSource { rootId: string | null; validatedAt: number | null } type Outcome = { kind: "source"; row: SourceRow; stale: boolean; error: string | null } | { kind: "not-public"; reason: "denied" | "unavailable"; detail: string }; /** Only host callers reading the catalog use repositoryKey; tool inputs remain raw strings. */ type RepositoryInput = { repository: unknown; repositoryKey?: never; repositoryUrl?: never } @@ -129,7 +130,7 @@ export function createReferenceSources(options: { return isManaged(repository.canonical) ? referenceRepository(githubReferenceRepository(repository.url).cloneUrl) : repository; } const leases = new Map(); - const withdrawn = new Set(); + const withdrawn = new Map(); /** A newer authority observation invalidates older managed requests, including before domain selection. */ const authorityFences = new Map(); /** In-flight withdrawals; an acquisition of the same source waits for its withdrawal to finish. */ @@ -142,7 +143,7 @@ export function createReferenceSources(options: { * does. Suspension also expires durable validation, so a new service's * bind preparation withholds uncertain authority before exposing its view. */ - const suspended = new Set(), unsettled = new Set(); + const suspended = new Map(), unsettled = new Set(); /** Root identities already moved out of their view: superseded, withdrawn or suspended. */ const hiddenRoots = new Set(); /** Native publication may have taken effect before its catalog receipt exists. */ @@ -229,6 +230,14 @@ export function createReferenceSources(options: { const usable = (source: SourceRow | null): source is SourceRow & { root_id: string; commit_id: string; refreshed_at: number; validated_at: number } => Boolean(source?.root_id && source.commit_id && source.refreshed_at !== null && source.validated_at !== null); const validationLive = (source: SourceRow) => source.validated_at !== null && now() < source.validated_at + limits.validationMs; + const sourceStamp = (source: SourceRow | null): WithheldSource => ({ rootId: source?.root_id ?? null, validatedAt: source?.validated_at ?? null }); + /** A key can name a different publication, or the same root validated anew by another owner. */ + function withholding(source: SourceRow | null): "live" | "hidden" | "unknown" { + if (!source?.root_id) return "live"; + const key = sourceKey(source.domain, source.repository, source.revision); + const matches = [suspended.get(key), withdrawn.get(key)].some(stamp => stamp?.rootId === source.root_id && stamp.validatedAt === source.validated_at); + return !matches ? "live" : hiddenRoots.has(source.root_id) ? "hidden" : "unknown"; + } async function lease(source: SourceRow, stale: boolean, error: string | null, authority?: () => void): Promise { if (!usable(source)) throw new ReferenceSourceError("unavailable", "No usable authorized reference source exists."); @@ -283,8 +292,12 @@ export function createReferenceSources(options: { .all(domain, repository, revision) as { id: string }[]; for (const root of roots) await releaseRoot(root.id); if (withdrawn.has(key) && !operating(key) && !withdrawals.has(key)) { + // A failed withdrawal still needs retrying; a replacement keeps its own + // lifetime. Neither is forgotten just because older readers finished. + if (row(domain, repository, revision)?.root_id) return; + const stamp = withdrawn.get(key); await write("sourceForget", domain, repository, revision); - withdrawn.delete(key); + if (withdrawn.get(key) === stamp) withdrawn.delete(key); } } /** A reservation is released only through the pool, after its writers stopped; a failure keeps the record for recovery. */ @@ -449,22 +462,24 @@ export function createReferenceSources(options: { /** Remove a source's name now; release its roots once no reader protects them. */ function withdraw(domain: string, repository: string, revision: string, captured?: InvalidatedRoot[]): Promise { const key = sourceKey(domain, repository, revision); + const stamp = sourceStamp(row(domain, repository, revision)); const fenced = captured ? Promise.resolve(captured) : fenceSource(key); // Fence before any await, even when the first publication has no catalog // row yet. A later acquisition waits for this withdrawal to finish. - withdrawn.add(key); + withdrawn.set(key, stamp); suspended.delete(key); unsettled.delete(key); // Observe the catalog after every already-dispatched publication settles, // including one whose native reply or database receipt was still pending. const work = exclusive(key, async () => { const invalidated = await fenced; + stamp.validatedAt = 0; if (isManaged(repository)) { for (const root of invalidated) { const recorded = await write<{ id: string; state: string } | null>("sourceDiscard", root.id); await hideRecordedRoot(recorded ?? root); } const current = row(domain, repository, revision); - if (current?.root_id && !invalidated.some(root => root.id === current.root_id)) withdrawn.delete(key); + if (current?.root_id && !invalidated.some(root => root.id === current.root_id) && withdrawn.get(key) === stamp) withdrawn.delete(key); return; } const source = row(domain, repository, revision); @@ -845,6 +860,7 @@ export function createReferenceSources(options: { return exclusive(key, async () => { const source = row(domain, repository, revision); if (onlyExpired && (!source || validationLive(source))) return; + const priorWithdrawal = withdrawn.get(key); // Bind expiry is shared invalidation too, rather than a local flag that // another owner can renew while native withdrawal is still outstanding. const managed = isManaged(repository); @@ -853,15 +869,16 @@ export function createReferenceSources(options: { if (managed) { const current = row(domain, repository, revision); const replaced = current?.root_id && !roots.some(root => root.id === current.root_id); - if (!replaced) { suspended.add(key); unsettled.add(key); } + if (!replaced) { suspended.set(key, { rootId: current?.root_id ?? null, validatedAt: 0 }); unsettled.add(key); } for (const root of roots) await hideRecordedRoot(root); + if (priorWithdrawal && withdrawn.get(key) === priorWithdrawal && roots.some(root => root.id === priorWithdrawal.rootId)) withdrawn.delete(key); if (replaced) suspended.delete(key); unsettled.delete(key); return; } const pending = [...pendingPublications].filter(([, publication]) => publication.key === key); - if ((!source?.root_id && !roots.length && !pending.length) || (suspended.has(key) && !unsettled.has(key) && !pending.length)) return; - suspended.add(key); unsettled.add(key); + if ((!source?.root_id && !roots.length && !pending.length) || (withholding(source) === "hidden" && !unsettled.has(key) && !pending.length)) return; + suspended.set(key, { rootId: source?.root_id ?? null, validatedAt: 0 }); unsettled.add(key); await write("sourceSuspend", domain, repository, revision); if (source) await pool.poolUnpublish((await viewFor(domain)).id, source.name); for (const root of roots) await hideRecordedRoot(root); @@ -869,6 +886,9 @@ export function createReferenceSources(options: { await pool.poolUnpublish(publication.view, publication.name); await hideRoot(id); } + // A settled suspension supersedes that earlier failed withdrawal, not + // any newer observation recorded while native hiding awaited its reply. + if (priorWithdrawal && withdrawn.get(key) === priorWithdrawal && roots.some(root => root.id === priorWithdrawal.rootId)) withdrawn.delete(key); unsettled.delete(key); }); } @@ -937,9 +957,11 @@ export function createReferenceSources(options: { await abortable(Promise.allSettled([...operations.values()].filter(operation => operation.key === key).map(operation => operation.promise)), signal); await abortable(exposing.get(key), signal); const current = row(source.domain, source.repository, source.revision); - if (!usable(current) || withdrawn.has(key)) continue; + if (!usable(current)) continue; if (unsettled.has(key)) { await abortable(suspendSource(current.domain, current.repository, current.revision), signal, false); continue; } - if (suspended.has(key) || validFor(current) > BIND_MARGIN()) continue; + const exposure = withholding(current); + if (exposure === "unknown") { await abortable(suspendSource(current.domain, current.repository, current.revision), signal, false); continue; } + if (exposure === "hidden" || validFor(current) > BIND_MARGIN()) continue; lapsed.push(current); } // Every lapsed source is checked again, a few at a time; one that fails is withheld. @@ -950,7 +972,7 @@ export function createReferenceSources(options: { batch.forEach((source, at) => { if (!outcomes?.[at]) failed.push(source); }); } for (const source of failed) { - if (withdrawn.has(sourceKey(source.domain, source.repository, source.revision))) continue; + if (withholding(row(source.domain, source.repository, source.revision)) === "hidden") continue; await abortable(suspendSource(source.domain, source.repository, source.revision), signal, false); } // No root other than a source's current one stays in the view: superseded, @@ -976,7 +998,9 @@ export function createReferenceSources(options: { for (const source of db.query("SELECT * FROM reference_sources WHERE domain = ? AND root_id IS NOT NULL").all(domain) as SourceRow[]) { const key = sourceKey(source.domain, source.repository, source.revision); if (unsettled.has(key)) return false; - if (withdrawn.has(key) || suspended.has(key)) continue; + const exposure = withholding(source); + if (exposure === "unknown") return false; + if (exposure === "hidden") continue; if (validFor(source) <= BIND_MARGIN()) return false; } return !(db.query(`SELECT r.id FROM reference_roots r WHERE r.domain = ? AND NOT EXISTS (SELECT 1 FROM reference_sources s WHERE s.root_id = r.id)`).all(domain) as { id: string }[]) @@ -1069,7 +1093,12 @@ export function createReferenceSources(options: { // Recovery never renews metadata authority. Invalidated roots stay masked // and charged until an explicit request obtains a new authorized root. const keep = new Set(); - for (const source of db.query("SELECT * FROM reference_sources WHERE root_id IS NOT NULL").all() as SourceRow[]) { + for (const snapshot of db.query("SELECT * FROM reference_sources WHERE root_id IS NOT NULL").all() as SourceRow[]) { + const source = row(snapshot.domain, snapshot.repository, snapshot.revision); + if (!source?.root_id) continue; + // Another owner can publish or renew validation after the catalog scan. + // Its publication belongs to a later recovery pass, not this snapshot. + if (source.root_id !== snapshot.root_id) { keep.add(source.root_id); continue; } const record = byId.get(source.root_id!); let usableRoot = record?.purpose === "source" && record.state === "sealed"; if (usableRoot && isManaged(source.repository)) usableRoot = referenceAcquisitionMatches(db, source.root_id!, record!, { @@ -1082,7 +1111,9 @@ export function createReferenceSources(options: { if (usableRoot) { if (!validationLive(source) || source.validated_at === 0 || (isManaged(source.repository) && record!.publicationRevoked !== false)) { const key = sourceKey(source.domain, source.repository, source.revision); - suspended.add(key); unsettled.add(key); + const expired = await write("sourceSuspend", source.domain, source.repository, source.revision, source.root_id, source.validated_at); + if (!expired) { keep.add(source.root_id!); continue; } + suspended.set(key, { rootId: source.root_id, validatedAt: 0 }); unsettled.add(key); await hideRoot(source.root_id!); unsettled.delete(key); keep.add(source.root_id!); @@ -1158,7 +1189,8 @@ export function createReferenceSources(options: { for (const domain of domains) for (const source of db.query("SELECT * FROM reference_sources WHERE domain = ? AND root_id IS NOT NULL").all(domain) as SourceRow[]) { const key = sourceKey(source.domain, source.repository, source.revision); - if (withdrawn.has(key) || (suspended.has(key) && !unsettled.has(key)) || validFor(source) > BIND_MARGIN()) continue; + const exposure = withholding(source); + if ((exposure === "hidden" && !unsettled.has(key)) || (exposure === "live" && validFor(source) > BIND_MARGIN())) continue; await abortable(suspendSource(source.domain, source.repository, source.revision), signal, false); } signal?.throwIfAborted(); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 2d262c5090..3c01486834 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -17,6 +17,7 @@ import { createReferenceTools } from "../src/brain/reference-tools"; import { openSqliteWriter } from "../src/db/write-worker"; import { registerReferenceWrites } from "../src/brain/reference-writes"; import { createReferenceWorktrees } from "../src/brain/reference-worktrees"; +import { sourceWrites } from "../src/brain/reference-source-writes"; const repository = "https://github.com/odysseus/ithaca", commit = "a".repeat(40), tree = "b".repeat(40), brain = "ithaca-brain"; let root: string, tls: ReturnType; @@ -879,6 +880,113 @@ describe("live managed authority", () => { } finally { current?.release(); held?.release(); await otherSources.close(); otherDb.close(); await f.close(); } }); + for (const invalidation of ["suspension", "withdrawal"] as const) + test(`a bind rechecks a replacement published by another owner after local ${invalidation}`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + let old: Awaited> | undefined, fresh: typeof old; + try { + old = await f.request(); + if (invalidation === "suspension") { old.release(); f.state.clock += 400_000; await f.sources.bindable(f.owner.id); } + else { f.state.private = true; await expect(f.request()).rejects.toMatchObject({ code: "unauthorized" }); f.state.private = false; } + expect(existsSync(join(old.viewPath, old.rootId, "README.md"))).toBe(false); + fresh = await otherSources.request({ principalId: f.other.id, repository, revision: "main", + acquisition: { turnId: "telemachus-replacement-validation", egress: f.secondEgress, current: () => true } }); + expect(fresh.rootId).not.toBe(old.rootId); + await f.sources.bindable(f.owner.id); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md"))).toBe(true); + f.state.clock += 400_000; + expect(() => fresh!.assertAuthority()).toThrow(); + const metadata = f.metadata.length; + await f.sources.bindable(f.owner.id); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md")), "BIND_RECHECKS_REPLACEMENT_VALIDATION_AFTER_LOCAL_WITHHOLDING").toBe(false); + expect(existsSync(join(fresh.viewPath, fresh.rootId, "README.md"))).toBe(false); + expect(f.metadata.length, "BIND_REVALIDATION_SPENDS_NO_UNBOUND_NETWORK").toBe(metadata); + } finally { fresh?.release(); old?.release(); await otherSources.close(); otherDb.close(); await f.close(); } + }); + + test("a bind rechecks legacy validation renewed on the same root by another owner", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), options = { ...f.sourceOptions, github: undefined }; + const first = createReferenceSources(options), second = createReferenceSources({ ...options, db: otherDb }); + const resolve = f.transport.resolve, input = { principalId: f.owner.id, repository, revision: "main" }; + let old: Awaited> | undefined, fresh: typeof old; + try { + old = await first.request(input); old.release(); f.state.clock += 400_000; + f.transport.resolve = async () => ({ ok: false, reason: "unavailable", detail: "The sea route is unavailable." }); + await first.bindable(f.owner.id); + f.transport.resolve = resolve; + fresh = await second.request(input); await second.recover(); + expect(fresh.rootId).toBe(old.rootId); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md"))).toBe(true); + await first.bindable(f.owner.id); f.state.clock += 400_000; + f.transport.resolve = async () => ({ ok: false, reason: "unavailable", detail: "The sea route is unavailable." }); + await first.bindable(f.owner.id); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md")), "BIND_RECHECKS_RENEWED_VALIDATION_ON_THE_SAME_ROOT").toBe(false); + } finally { fresh?.release(); old?.release(); await first.close(); await second.close(); otherDb.close(); await f.close(); } + }); + + test("a settled suspension replaces a failed withdrawal mark before legacy validation is renewed", async () => { + const f = await fixture(), issued = f.grant(), otherDb = createUiDb(f.databasePath), options = { ...f.sourceOptions, github: undefined }; + const first = createReferenceSources(options), second = createReferenceSources({ ...options, db: otherDb }); + const resolve = f.transport.resolve, input = { principalId: f.owner.id, repository, revision: "main" }; + f.transport.resolve = async value => value.token ? resolve(value) : { ok: false, reason: "denied", detail: "A private chart needs its grant." }; + let old: Awaited> | undefined, fresh: typeof old; + try { + old = await first.request(input); + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); + f.db.exec("PRAGMA query_only = ON"); + const fault = await first.revoke({ grantIds: [issued.id], principalIds: [] }).then(() => undefined, error => error); + expect(fault).toBeInstanceOf(Error); + f.db.exec("PRAGMA query_only = OFF"); f.grant(); + await first.bindable(f.owner.id); + expect(existsSync(join(old.viewPath, old.name, "README.md")), "BIND_RETRIES_UNCONFIRMED_WITHDRAWAL_HIDING").toBe(false); + fresh = await second.request(input); await second.recover(); + expect(fresh.rootId).toBe(old.rootId); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md"))).toBe(true); + f.state.clock += 400_000; + f.transport.resolve = async () => ({ ok: false, reason: "unavailable", detail: "The sea route is unavailable." }); + await first.bindable(f.owner.id); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md")), "SETTLED_SUSPENSION_CONSUMES_THE_OLDER_WITHDRAWAL_MARK").toBe(false); + } finally { f.db.exec("PRAGMA query_only = OFF"); fresh?.release(); old?.release(); await first.close(); await second.close(); otherDb.close(); await f.close(); } + }); + + for (const phase of ["catalog snapshot", "suspension commit"] as const) + test(`recovery preserves validation committed by another owner before ${phase}`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), first = createReferenceSources({ ...f.sourceOptions, github: undefined }); + const descriptor = Object.getOwnPropertyDescriptor(f.db, "query"), query = f.db.query.bind(f.db); + let held: Awaited> | undefined, injected = false; + try { + held = await first.request({ principalId: f.owner.id, repository, revision: "main" }); held.release(); + f.state.clock += 400_000; + const renew = () => { + injected = true; + expect(sourceWrites(otherDb).sourceValidate(f.state.clock, f.state.clock, "refs/heads/main", "public", repository, "main", undefined, held!.rootId)).toBe(true); + }; + f.db.query = ((sql: string) => { + const statement = query(sql); + if (phase === "catalog snapshot" && sql === "SELECT * FROM reference_sources WHERE root_id IS NOT NULL") { + const all = statement.all.bind(statement); + statement.all = ((...args: unknown[]) => { + const snapshot = all(...args as []); statement.all = all; + renew(); + return snapshot; + }) as typeof statement.all; + } + if (phase === "suspension commit" && sql.startsWith("UPDATE reference_sources SET validated_at = 0")) { + const run = statement.run.bind(statement); + statement.run = ((...args: unknown[]) => { statement.run = run; renew(); return run(...args as []); }) as typeof statement.run; + } + return statement; + }) as typeof f.db.query; + await first.recover(); + expect(injected).toBe(true); + expect(existsSync(join(held.viewPath, held.name, "README.md")), "RECOVERY_PRESERVES_VALIDATION_COMMITTED_AFTER_ITS_SNAPSHOT").toBe(true); + expect(f.db.query("SELECT validated_at FROM reference_sources").get()).toEqual({ validated_at: f.state.clock }); + } finally { + if (descriptor) Object.defineProperty(f.db, "query", descriptor); else Reflect.deleteProperty(f.db, "query"); + held?.release(); await first.close(); otherDb.close(); await f.close(); + } + }); + test("startup recovery keeps durably suspended metadata hidden from already-bound views", async () => { const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); let held: Awaited> | undefined; From 8bf9a7bd092b73e03ca2ac6daf6ec7007c282338 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 13:21:51 +0000 Subject: [PATCH 25/27] CONTRACT: reconfirm reversible source hiding for each bind --- docs/decisions/managed-worktrees.md | 8 ++--- .../decisions/reference-source-acquisition.md | 17 +++++---- docs/integration-contract/package-api.md | 2 ++ .../ui-server/src/brain/reference-source.ts | 27 +++++++++----- .../tests/reference-source-managed.test.ts | 36 +++++++++++++++++++ 5 files changed, 71 insertions(+), 19 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 227ca886be..dacc997143 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1168-1199`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1179-1210`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:951-989`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:957-995`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:858-875`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:864-881`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:997-1006`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:1008-1017`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 6cd4696e8b..507d00b454 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:371-420`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:377-426`). - Inside both windows a request reuses the published source without any network call. @@ -160,7 +160,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:536-590`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:542-596`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -236,6 +236,9 @@ Bind preparation treats a local suspension or withdrawal as settled only for the exact catalog root and validation timestamp whose native hiding succeeded. A replacement root or renewed validation is checked again when it expires; failed catalog writes or native hiding never excuse that check. +Only a root's confirmed permanent native withdrawal can be reused across +binds. Reversible roots, including catalog orphans, need fresh hiding +confirmation for each bind because another owner may have republished them. Maintenance admission may wait up to 30 seconds for each Git command, then returns `busy`. Cancellation stops that wait; the wire still checks the live turn and selected grant before dispatch, and the source service checks them @@ -263,9 +266,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:311-326`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:317-332`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:329-354`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:335-360`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -287,7 +290,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:438-454`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:444-460`). There is no idle expiry. ## Revocation and recovery @@ -300,7 +303,7 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1053-1078`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1064-1089`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists and, when @@ -313,7 +316,7 @@ and validation timestamp still match, preserving another owner's renewal or replacement after the initial scan. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1083-1127`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1094-1138`). ## Evidence diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 2aa45c8026..a20612cd91 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4548,6 +4548,8 @@ refuses this optional field and the host never retries it unconditionally. Bind preparation skips an invalidated source only while its exact catalog root and validation timestamp still match confirmed native hiding. A replacement or renewal expires independently, and incomplete hiding is retried before binding. +Only permanent native withdrawal can retain hiding confirmation across binds; +reversible roots and catalog orphans are confirmed again for each bind. Startup recovery preserves validation another owner renewed after its scan. `ServerConfig.referenceSource?` is `{ validationMs, refreshMs, operations }`. diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 6f0e08d40e..5bc8a6691d 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -144,8 +144,8 @@ export function createReferenceSources(options: { * bind preparation withholds uncertain authority before exposing its view. */ const suspended = new Map(), unsettled = new Set(); - /** Root identities already moved out of their view: superseded, withdrawn or suspended. */ - const hiddenRoots = new Set(); + /** Confirmed hiding; only permanent native withdrawal survives another bind. */ + const hiddenRoots = new Map(); /** Native publication may have taken effect before its catalog receipt exists. */ const pendingPublications = new Map(); /** Bind-time revalidations in flight, joined by concurrent binds. */ @@ -182,28 +182,33 @@ export function createReferenceSources(options: { * may have been lost, is settled instead. */ async function hideRoot(id: string) { - try { await pool.poolWithdraw(id); } + let permanent = false; + try { permanent = (await pool.poolWithdraw(id)).publicationRevoked === true; } catch (error) { if ((error as { code?: string }).code !== "released") throw error; await releaseRoot(id); + permanent = true; } - hiddenRoots.add(id); + hiddenRoots.set(id, permanent); pendingPublications.delete(id); } /** Another owner can have native publication but only a staging catalog row. */ async function hideRecordedRoot(root: { id: string; state: string }) { if (root.state !== "staging") return hideRoot(root.id); + let permanent = false; try { const record = await pool.poolWithdraw(root.id); + permanent = record.publicationRevoked === true; // A sealed staging root has no active writer. Retire its identity so a // delayed publication RPC cannot expose it after this owner returns. - if (record.state !== "writable" && record.state !== "reserved") await releaseRoot(root.id); + if (record.state !== "writable" && record.state !== "reserved") { const released = await releaseRoot(root.id); permanent ||= released; } } catch (error) { if (!["unknown", "released"].includes((error as { code?: string }).code ?? "")) throw error; // Release also fences a create that has not arrived at the manager yet. - await releaseRoot(root.id); + const released = await releaseRoot(root.id); + permanent = released || (error as { code?: string }).code === "released"; } - hiddenRoots.add(root.id); + hiddenRoots.set(root.id, permanent); pendingPublications.delete(root.id); } /** One change at a time to a source's exposure: suspension, restoration, withdrawal and publication. */ @@ -302,10 +307,11 @@ export function createReferenceSources(options: { } /** A reservation is released only through the pool, after its writers stopped; a failure keeps the record for recovery. */ async function releaseRoot(id: string) { - if (options.dependents?.(id)) return; + if (options.dependents?.(id)) return false; await pool.poolRelease(id); await write("sourceReleaseRoot", id); pendingPublications.delete(id); + return true; } async function admit(signal: AbortSignal): Promise<() => void> { @@ -949,6 +955,11 @@ export function createReferenceSources(options: { } } async function settleView(domain: string, signal?: AbortSignal) { + // Another owner can republish a reversibly withdrawn root, including one + // whose catalog row a failed withdrawal already removed. Reconfirm hiding + // for this bind rather than inheriting an earlier preparation's receipt. + for (const { id } of db.query("SELECT id FROM reference_roots WHERE domain = ?").all(domain) as { id: string }[]) + if (hiddenRoots.get(id) === false) hiddenRoots.delete(id); const lapsed: (SourceRow & { root_id: string })[] = []; for (const source of db.query("SELECT * FROM reference_sources WHERE domain = ? AND root_id IS NOT NULL").all(domain) as SourceRow[]) { const key = sourceKey(source.domain, source.repository, source.revision); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index 3c01486834..f21fa5f06d 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -987,6 +987,42 @@ describe("live managed authority", () => { } }); + for (const failure of ["catalog write", "native withdrawal"] as const) + test(`a bind retries ${failure} failure after another owner republishes a previously hidden legacy root`, async () => { + const f = await fixture(), issued = f.grant(), otherDb = createUiDb(f.databasePath), options = { ...f.sourceOptions, github: undefined }; + const first = createReferenceSources(options), second = createReferenceSources({ ...options, db: otherDb }); + const resolve = f.transport.resolve, withdraw = f.pool.poolWithdraw, input = { principalId: f.owner.id, repository, revision: "main" }; + const authorized = async (value: Parameters[0]) => value.token ? resolve(value) : { ok: false as const, reason: "denied" as const, detail: "A private chart needs its grant." }; + f.transport.resolve = authorized; + let old: Awaited> | undefined, fresh: typeof old, withdrawCalls = 0; + try { + old = await first.request(input); old.release(); f.state.clock += 400_000; + f.transport.resolve = async () => ({ ok: false, reason: "unavailable", detail: "The sea route is unavailable." }); + await first.bindable(f.owner.id); + expect(existsSync(join(old.viewPath, old.rootId, "README.md"))).toBe(false); + f.transport.resolve = authorized; fresh = await second.request(input); await second.recover(); + expect(fresh.rootId).toBe(old.rootId); + expect(existsSync(join(fresh.viewPath, fresh.rootId, "README.md"))).toBe(true); + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: issued.id, now: Date.now() }); + if (failure === "catalog write") f.db.exec("PRAGMA query_only = ON"); + f.pool.poolWithdraw = async (...args) => { + withdrawCalls++; + if (failure === "native withdrawal" && withdrawCalls === 1) throw new Error("The keeper reply was unavailable."); + return withdraw(...args); + }; + const fault = await first.revoke({ grantIds: [issued.id], principalIds: [] }).then(() => undefined, error => error); + expect(fault).toBeInstanceOf(Error); f.db.exec("PRAGMA query_only = OFF"); f.state.clock += 400_000; + const before = withdrawCalls; + await first.bindable(f.owner.id); + expect(existsSync(join(fresh.viewPath, fresh.rootId, "README.md")), "BIND_RETRIES_HIDING_AFTER_FOREIGN_LEGACY_REPUBLICATION").toBe(false); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md"))).toBe(false); + expect(withdrawCalls, "OLD_HIDING_CONFIRMATION_CANNOT_SKIP_THE_NEW_NATIVE_WITHDRAWAL").toBeGreaterThan(before); + } finally { + f.db.exec("PRAGMA query_only = OFF"); f.pool.poolWithdraw = withdraw; + fresh?.release(); old?.release(); await first.close(); await second.close(); otherDb.close(); await f.close(); + } + }); + test("startup recovery keeps durably suspended metadata hidden from already-bound views", async () => { const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); let held: Awaited> | undefined; From 55143cbe21dddb212f734cf89e0e5f469a00a44e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 13:41:13 +0000 Subject: [PATCH 26/27] CONTRACT: preserve unpublished acquisition roots during bind preparation --- docs/decisions/managed-worktrees.md | 8 ++-- .../decisions/reference-source-acquisition.md | 18 +++++--- docs/integration-contract/package-api.md | 2 + .../ui-server/src/brain/reference-source.ts | 23 ++++++++-- .../tests/reference-source-managed.test.ts | 45 +++++++++++++++++++ 5 files changed, 82 insertions(+), 14 deletions(-) diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index dacc997143..cc1bc63149 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1179-1210`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1196-1227`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:957-995`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:965-1003`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:864-881`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:872-889`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:1008-1017`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:1025-1034`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 507d00b454..03ad4a999f 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:377-426`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:385-434`). - Inside both windows a request reuses the published source without any network call. @@ -160,7 +160,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:542-596`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:550-604`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -239,6 +239,10 @@ failed catalog writes or native hiding never excuse that check. Only a root's confirmed permanent native withdrawal can be reused across binds. Reversible roots, including catalog orphans, need fresh hiding confirmation for each bind because another owner may have republished them. +An unpublished staging root remains outside those views while a concurrent +acquisition writes or seals it. Bind preparation reads the native catalog to +confirm that absence without permanently withdrawing its publication authority. +A staging root already in a view still needs settlement or hiding. Maintenance admission may wait up to 30 seconds for each Git command, then returns `busy`. Cancellation stops that wait; the wire still checks the live turn and selected grant before dispatch, and the source service checks them @@ -266,9 +270,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:317-332`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:325-340`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:335-360`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:343-368`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -290,7 +294,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:444-460`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:452-468`). There is no idle expiry. ## Revocation and recovery @@ -303,7 +307,7 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1064-1089`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1081-1106`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists and, when @@ -316,7 +320,7 @@ and validation timestamp still match, preserving another owner's renewal or replacement after the initial scan. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1094-1138`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1111-1155`). ## Evidence diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index a20612cd91..20e3815126 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4550,6 +4550,8 @@ and validation timestamp still match confirmed native hiding. A replacement or renewal expires independently, and incomplete hiding is retried before binding. Only permanent native withdrawal can retain hiding confirmation across binds; reversible roots and catalog orphans are confirmed again for each bind. +Native-confirmed unpublished staging stays outside worker views without losing +publication authority; staging already exposed in a view is still contained. Startup recovery preserves validation another owner renewed after its scan. `ServerConfig.referenceSource?` is `{ validationMs, refreshMs, operations }`. diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 5bc8a6691d..fa32b27fb4 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -144,7 +144,7 @@ export function createReferenceSources(options: { * bind preparation withholds uncertain authority before exposing its view. */ const suspended = new Map(), unsettled = new Set(); - /** Confirmed hiding; only permanent native withdrawal survives another bind. */ + /** Confirmed absence from views; only permanent native withdrawal survives another bind. */ const hiddenRoots = new Map(); /** Native publication may have taken effect before its catalog receipt exists. */ const pendingPublications = new Map(); @@ -211,6 +211,14 @@ export function createReferenceSources(options: { hiddenRoots.set(root.id, permanent); pendingPublications.delete(root.id); } + async function nativeRoot(id: string): Promise { + for (let after: string | null = null; ;) { + const page = await pool.listPoolRecovery(after); + const record = page.records.find(record => record.id === id); + if (record || !page.next) return record; + after = page.next; + } + } /** One change at a time to a source's exposure: suspension, restoration, withdrawal and publication. */ const exposing = new Map>(); function exclusive(key: string, work: () => Promise): Promise { @@ -988,12 +996,21 @@ export function createReferenceSources(options: { } // No root other than a source's current one stays in the view: superseded, // withdrawn, retained for a worktree, or staging whose publication reply was lost. - for (const { id, repository, revision } of db.query(`SELECT r.id, r.repository, r.revision FROM reference_roots r WHERE r.domain = ? - AND NOT EXISTS (SELECT 1 FROM reference_sources s WHERE s.root_id = r.id)`).all(domain) as { id: string; repository: string; revision: string }[]) { + for (const { id, repository, revision, state } of db.query(`SELECT r.id, r.repository, r.revision, r.state FROM reference_roots r WHERE r.domain = ? + AND NOT EXISTS (SELECT 1 FROM reference_sources s WHERE s.root_id = r.id)`).all(domain) as { id: string; repository: string; revision: string; state: string }[]) { if (hiddenRoots.has(id)) continue; await abortable(exclusive(sourceKey(domain, repository, revision), async () => { // An acquisition may have published it meanwhile as the current root. if (db.query("SELECT 1 FROM reference_sources WHERE root_id = ?").get(id)) return; + if (state === "staging") { + const record = await nativeRoot(id); + // Unpublished staging is outside the worker's views already. Taking + // its publication authority would cancel a valid concurrent fetch. + if (record?.purpose === "source" && record.view === null && ["reserved", "writable", "sealed"].includes(record.state)) { + hiddenRoots.set(id, record.publicationRevoked === true); + return; + } + } await hideRoot(id); }), signal, false); } diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index f21fa5f06d..a7bacd1d44 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -125,6 +125,51 @@ test("a cached shared root still uses the requesting principal and turn's own me } finally { await f.close(); } }); +for (const phase of ["fetch", "seal"] as const) +for (const owner of ["same service", "another service"] as const) +test(`a concurrent bind from ${owner} preserves an unpublished managed source during ${phase}`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), fetch = f.transport.fetch, seal = f.pool.poolSeal; + const pause = async () => { arrived.resolve(); await resume.promise; }; + if (phase === "fetch") f.transport.fetch = async input => { const result = await fetch(input); await pause(); return result; }; + else f.pool.poolSeal = async (...args) => { const result = await seal(...args); await pause(); return result; }; + const pending = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; + const staging = [...f.pool.records.values()].find(record => record.purpose === "source")!; + expect(staging.view).toBeNull(); expect(staging.publicationRevoked).toBe(false); + const view = await (owner === "same service" ? f.sources : otherSources).bindable(f.other.id); + expect(existsSync(join(view.public, staging.id, "README.md"))).toBe(false); + expect(staging.publicationRevoked, "BIND_PRESERVES_UNPUBLISHED_SOURCE_AUTHORITY").toBe(false); + resume.resolve(); const result = await pending; + expect(result.error, "CONCURRENT_BIND_DOES_NOT_CANCEL_VALID_SOURCE_PUBLICATION").toBeUndefined(); + expect(result.lease!.rootId).toBe(staging.id); + expect(existsSync(join(view.public, result.lease!.name, "README.md"))).toBe(true); + } finally { + resume.resolve(); const result = await pending; result.lease?.release(); + f.transport.fetch = fetch; f.pool.poolSeal = seal; + await otherSources.close(); otherDb.close(); await f.close(); + } +}); + +test("a bind withdraws staging already exposed without a source catalog receipt", async () => { + const f = await fixture(); + let held: Awaited> | undefined; + try { + held = await f.request(); + // Reconstruct the durable state after native publication but before its + // catalog receipt: the sealed root is in a view and its row is staging. + f.db.query("DELETE FROM reference_sources WHERE root_id = ?").run(held.rootId); + f.db.query("DELETE FROM reference_acquisitions WHERE root_id = ?").run(held.rootId); + f.db.query("UPDATE reference_roots SET state = 'staging' WHERE id = ?").run(held.rootId); + expect(existsSync(join(held.viewPath, held.rootId, "README.md"))).toBe(true); + await f.sources.bindable(f.other.id); + expect(existsSync(join(held.viewPath, held.rootId, "README.md")), "PUBLISHED_STAGING_ROOT_MUST_BE_HIDDEN_BEFORE_BIND").toBe(false); + expect(existsSync(join(held.viewPath, held.name, "README.md"))).toBe(false); + expect(f.pool.records.get(held.rootId)!.publicationRevoked).toBe(true); + } finally { held?.release(); await f.close(); } +}); + for (const wait of ["seal", "native-publication"] as const) test(`an older managed acquisition cannot replace a newer revision after ${wait}`, async () => { const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); From ea8f20b7bf7529e34edd6ee31a2de8d749841925 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Tue, 17 Nov 2026 14:18:53 +0000 Subject: [PATCH 27/27] CONTRACT: retire exact source publications without cancelling fresh acquisition --- .../managed-reference-source-authority.md | 2 + docs/decisions/managed-worktrees.md | 8 +-- .../decisions/reference-source-acquisition.md | 21 ++++-- docs/integration-contract/package-api.md | 4 ++ .../src/brain/reference-source-writes.ts | 62 +++++++++++----- .../ui-server/src/brain/reference-source.ts | 41 +++++++---- .../tests/reference-source-authority.test.ts | 20 ++++++ .../tests/reference-source-managed.test.ts | 70 ++++++++++++++++++- .../ui-server/tests/reference-tools.test.ts | 4 +- 9 files changed, 184 insertions(+), 48 deletions(-) diff --git a/.changeset/managed-reference-source-authority.md b/.changeset/managed-reference-source-authority.md index 8b2e46d22f..fc3d136329 100644 --- a/.changeset/managed-reference-source-authority.md +++ b/.changeset/managed-reference-source-authority.md @@ -8,3 +8,5 @@ Bind managed GitHub source acquisition and cached-source revalidation to the req Keep stored worktree repository keys separate from raw clone input so revocation cannot borrow a neighboring repository's grant. Managed roots opt into durable, permanent native publication withdrawal: delayed publication cannot revive a revoked identity, while fresh authorized acquisition uses a new root and legacy withdrawal stays reversible. Recovery keeps invalidated roots masked, and committing a shared invalidation atomically expires matching cached validation. Condition native publication and catalog updates on the previously observed root so concurrent acquisitions cannot roll a source back to an older revision. Worktrees retain their original acquisition URL after source-catalog cleanup, preserving authorized legacy endpoints without guessing clone suffixes. + +Compare expiry against the current root and validation inside the catalog transaction. Preserve independent authorized acquisitions while retiring expired roots, and refuse late publication or validation of retired identities. diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index cc1bc63149..d6652c4293 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -234,7 +234,7 @@ public view and their principal's private view whole and read-only at (`// Shared reference source (#2432)`, `packages/ui-sdk/src/server/worker-launcher.ts:898-909`). A view the domain has not published to yet is opened empty first, so the turn sees its own first acquisition -(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1196-1227`). +(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:1209-1240`). A refresh renames the name a later lookup resolves, so reads stay live and nothing pins a revision. A view is the domain's authorized cache: its names are published under that domain's authority and withdrawn when the authority is @@ -277,7 +277,7 @@ source. Managed GitHub sources are withheld without network access: their validation needs an explicit request on the new turn's proxy and budget. These rules cover sources a running turn reads; a running reader keeps its existing mount -(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:965-1003`): +(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:976-1014`): - a source with less than the bind margin of validation left counts as lapsed: a minute, or half of a shorter configured lifetime, so it does not @@ -291,7 +291,7 @@ existing mount one kept only for a worktree or staging whose publication reply was lost. Withholding takes a source's name and roots out of the view -(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:872-889`). +(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:873-890`). Its cache and charge stay, and the next request that validates it publishes it again. A running reader keeps its bind of the view and the files it has open; its later lookups of a withheld name fail until a request validates the source. @@ -310,7 +310,7 @@ withheld rather than checked again; withholding takes only short pool calls, so the bind converges whatever the cache size. A bind that still cannot be admitted, because a pool change stays unconfirmed, refuses, and the turn runs without shared source views -(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:1025-1034`). +(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:1038-1047`). The margin covers the moments between admission and the workers' mounts. Suspension, restoration, withdrawal and publication of one source run one at a diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 03ad4a999f..2171baf75d 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -57,7 +57,7 @@ exact published commit, and `refreshedAt`, the last successful refresh. Both default to five minutes and are configured separately (`BRAIN_UI_REFERENCE_VALIDATION_SECONDS`, `BRAIN_UI_REFERENCE_REFRESH_SECONDS`). Nothing runs on a timer -(`operate`, `packages/ui-server/src/brain/reference-source.ts:385-434`). +(`operate`, `packages/ui-server/src/brain/reference-source.ts:386-435`). - Inside both windows a request reuses the published source without any network call. @@ -160,7 +160,7 @@ default to five minutes and are configured separately Acquisition reserves a pool root before any work. The root is a snapshot of the previous root, so a refresh fetches only new objects. Then -(`acquire`, `packages/ui-server/src/brain/reference-source.ts:550-604`): +(`acquire`, `packages/ui-server/src/brain/reference-source.ts:551-605`): 1. The host writes fixed Git metadata into the root: no hooks, no fsmonitor, fsck on transfer, no repository-controlled configuration. @@ -243,6 +243,13 @@ An unpublished staging root remains outside those views while a concurrent acquisition writes or seals it. Bind preparation reads the native catalog to confirm that absence without permanently withdrawing its publication authority. A staging root already in a view still needs settlement or hiding. +Expiry compares the observed root, validation timestamp and freshness inside +the catalog transaction. A concurrent renewal wins that comparison. Managed +expiry retires only that publication, preserving another turn's authorized +staging roots; validation cannot renew a retired root. Revocation and unknown +metadata still invalidate all affected acquisitions. Hiding exposed staging +first retires its catalog identity, and publication commits require a staging +identity, so a delayed native reply cannot create a fresh lease for hidden bytes. Maintenance admission may wait up to 30 seconds for each Git command, then returns `busy`. Cancellation stops that wait; the wire still checks the live turn and selected grant before dispatch, and the source service checks them @@ -270,9 +277,9 @@ remain required before repository trust can be enabled. At most `BRAIN_UI_REFERENCE_ACQUISITIONS` (default two) acquisitions or refreshes run across the host -(`admit`, `packages/ui-server/src/brain/reference-source.ts:325-340`). Requests +(`admit`, `packages/ui-server/src/brain/reference-source.ts:326-341`). Requests for the same legacy source in the same domain join one operation -(`function join`, `packages/ui-server/src/brain/reference-source.ts:343-368`). +(`function join`, `packages/ui-server/src/brain/reference-source.ts:344-369`). Each principal's private source is its own domain, so two principals requesting the same private repository at once run two operations, each with its own credential and view. Admitted operations finish independently: a stalled one @@ -294,7 +301,7 @@ superseded root is released when the last reader of that source releases. When the pool refuses a reservation for capacity, the service withdraws the least recently used source that has no reader, no running operation and no worktree dependency, then retries. If nothing is eligible it refuses with -`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:452-468`). +`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:453-469`). There is no idle expiry. ## Revocation and recovery @@ -307,7 +314,7 @@ removes the name and moves every one of those roots out of the view (`poolWithdraw`), so no reader reaches them by name or identity. Storage is released once readers finish. An acquisition of the same source waits for the withdrawal to finish -(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1081-1106`). +(`revoke`, `packages/ui-server/src/brain/reference-source.ts:1094-1119`). The catalog lives in the UI database and is disposable bookkeeping. At start, a recorded source survives only if its sealed root still exists and, when @@ -320,7 +327,7 @@ and validation timestamp still match, preserving another owner's renewal or replacement after the initial scan. Every other owned source root is released: interrupted staging, superseded or withdrawn roots, roots the -catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1111-1155`). +catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:1124-1168`). ## Evidence diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 20e3815126..6a453d8cbd 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4553,6 +4553,10 @@ reversible roots and catalog orphans are confirmed again for each bind. Native-confirmed unpublished staging stays outside worker views without losing publication authority; staging already exposed in a view is still contained. Startup recovery preserves validation another owner renewed after its scan. +Expiry compares the observed root, validation timestamp and freshness atomically; +a newer renewal survives. Managed expiry retires that publication while a +separate authorized acquisition can finish. Retired roots cannot renew validation, +and retired staging cannot commit a delayed publication after native hiding. `ServerConfig.referenceSource?` is `{ validationMs, refreshMs, operations }`. The host edge resolves it from `BRAIN_UI_REFERENCE_VALIDATION_SECONDS` and diff --git a/packages/ui-server/src/brain/reference-source-writes.ts b/packages/ui-server/src/brain/reference-source-writes.ts index e59d94877a..582a2d191c 100644 --- a/packages/ui-server/src/brain/reference-source-writes.ts +++ b/packages/ui-server/src/brain/reference-source-writes.ts @@ -10,26 +10,42 @@ export function sourceWrites(db: Database) { db.query("INSERT INTO reference_views (domain, view_id) VALUES (?, ?)").run(domain, id); return { id, hostPath: null }; } + function fence(domain: string, repository: string, revision: string, generation: string) { + db.query(`INSERT INTO reference_authority_fences (domain, repository, revision, generation) VALUES (?, ?, ?, ?) + ON CONFLICT (domain, repository, revision) DO UPDATE SET generation = excluded.generation`).run(domain, repository, revision, generation); + // A crash after this commit must not leave old positive validation + // available to startup recovery, including legacy GitHub casing aliases. + const matches = (source: { repository: string; revision: string }) => { + try { return (revision === "" || source.revision === revision) && authorityRepository(source.repository) === repository; } + catch { return false; } + }; + for (const source of db.query("SELECT repository, revision FROM reference_sources WHERE domain = ?").all(domain) as { repository: string; revision: string }[]) { + if (matches(source)) + db.query("UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ?").run(domain, source.repository, source.revision); + } + // Cleanup affects exactly the identities invalidated at this commit, + // never a fresh acquisition that publishes while native hiding waits. + return (db.query("SELECT id, state, repository, revision FROM reference_roots WHERE domain = ?").all(domain) as + { id: string; state: string; repository: string; revision: string }[]).filter(matches); + } return { sourceView, sourceFence(domain: string, repository: string, revision: string, generation: string) { + return db.transaction(() => fence(domain, repository, revision, generation)).immediate(); + }, + sourceFenceCurrent(domain: string, repository: string, revision: string, generation: string, rootId: string | null, validatedAt: number | null, before?: number, permanent = false) { return db.transaction(() => { - db.query(`INSERT INTO reference_authority_fences (domain, repository, revision, generation) VALUES (?, ?, ?, ?) - ON CONFLICT (domain, repository, revision) DO UPDATE SET generation = excluded.generation`).run(domain, repository, revision, generation); - // A crash after this commit must not leave old positive validation - // available to startup recovery, including legacy GitHub casing aliases. - const matches = (source: { repository: string; revision: string }) => { - try { return (revision === "" || source.revision === revision) && authorityRepository(source.repository) === repository; } - catch { return false; } - }; - for (const source of db.query("SELECT repository, revision FROM reference_sources WHERE domain = ?").all(domain) as { repository: string; revision: string }[]) { - if (matches(source)) - db.query("UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ?").run(domain, source.repository, source.revision); - } - // Cleanup affects exactly the identities invalidated at this commit, - // never a fresh acquisition that publishes while native hiding waits. - return (db.query("SELECT id, state, repository, revision FROM reference_roots WHERE domain = ?").all(domain) as - { id: string; state: string; repository: string; revision: string }[]).filter(matches); + const current = db.query("SELECT root_id, validated_at FROM reference_sources WHERE domain = ? AND repository = ? AND revision = ?") + .get(domain, repository, revision) as { root_id: string | null; validated_at: number | null } | null; + if (!current || current.root_id !== rootId || current.validated_at !== validatedAt || (before !== undefined && current.validated_at !== null && current.validated_at > before)) return null; + if (!permanent) return fence(domain, authorityRepository(repository), revision, generation); + // Expiry retires this publication, not another turn's independently + // authorized staging root. Cache validation can never revive it. + const roots = db.query("SELECT id, state, repository, revision FROM reference_roots WHERE id = ?").all(rootId) as + { id: string; state: string; repository: string; revision: string }[]; + db.query("UPDATE reference_sources SET validated_at = 0 WHERE domain = ? AND repository = ? AND revision = ?").run(domain, repository, revision); + db.query("UPDATE reference_roots SET state = 'superseded' WHERE id = ? AND state = 'published'").run(rootId); + return roots; }).immediate(); }, sourceTouch(at: number, domain: string, repository: string, revision: string) { @@ -41,11 +57,18 @@ export function sourceWrites(db: Database) { sourceReleaseRoot(id: string) { db.query("DELETE FROM reference_roots WHERE id = ?").run(id); }, + sourceRetireStaging(id: string) { + return db.transaction(() => { + if (db.query("SELECT 1 FROM reference_sources WHERE root_id = ?").get(id)) return false; + db.query("UPDATE reference_roots SET state = 'superseded' WHERE id = ? AND state = 'staging'").run(id); + return true; + }).immediate(); + }, sourceDiscard(id: string) { return db.transaction(() => { const root = db.query("SELECT id, state FROM reference_roots WHERE id = ?").get(id) as { id: string; state: string } | null; db.query("UPDATE reference_sources SET root_id = NULL WHERE root_id = ?").run(id); - db.query("UPDATE reference_roots SET state = 'superseded' WHERE id = ? AND state = 'published'").run(id); + db.query("UPDATE reference_roots SET state = 'superseded' WHERE id = ? AND state IN ('staging', 'published')").run(id); return root; }).immediate(); }, @@ -53,7 +76,8 @@ export function sourceWrites(db: Database) { return db.transaction(() => { if (expected && !sourceAuthorityCurrent(db, expected)) return false; return db.query(`UPDATE reference_sources SET validated_at = ?, refreshed_at = ?, last_error = NULL, ref = ? - WHERE domain = ? AND repository = ? AND revision = ? AND (? IS NULL OR root_id = ?)`) + WHERE domain = ? AND repository = ? AND revision = ? AND (? IS NULL OR root_id = ?) + AND root_id IN (SELECT id FROM reference_roots WHERE state = 'published')`) .run(at, refreshedAt, ref, domain, repository, revision, rootId ?? null, rootId ?? null).changes === 1; }).immediate(); }, @@ -84,6 +108,8 @@ export function sourceWrites(db: Database) { sourcePublish(path: string, domain: string, repository: string, revision: string, url: string, name: string, id: string, commit: string, ref: string, grantId: string | null, at: number, acquisition?: ReferenceAcquisition, expected?: SourceAuthority, publication?: { rootId: string | null }) { return db.transaction(() => { if (expected && !sourceAuthorityCurrent(db, expected)) return false; + const staging = db.query("SELECT state FROM reference_roots WHERE id = ?").get(id) as { state: string } | null; + if (staging?.state !== "staging") return false; const current = db.query("SELECT root_id FROM reference_sources WHERE domain = ? AND repository = ? AND revision = ?").get(domain, repository, revision) as { root_id: string | null } | null; if (publication && (current?.root_id ?? null) !== publication.rootId) return false; if (acquisition) db.query(`INSERT INTO reference_acquisitions diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index fa32b27fb4..23f9bd3a01 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -301,7 +301,8 @@ export function createReferenceSources(options: { async function settle(domain: string, repository: string, revision: string) { const key = sourceKey(domain, repository, revision); if (leases.get(key)) return; - const roots = db.query("SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ? AND state = 'superseded'") + const roots = db.query(`SELECT id FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ? AND state = 'superseded' + AND NOT EXISTS (SELECT 1 FROM reference_sources s WHERE s.root_id = reference_roots.id)`) .all(domain, repository, revision) as { id: string }[]; for (const root of roots) await releaseRoot(root.id); if (withdrawn.has(key) && !operating(key) && !withdrawals.has(key)) { @@ -681,7 +682,7 @@ export function createReferenceSources(options: { } else if (result && reason === "unavailable") { // Wire shutdown may outlive the lease's validation. A newer live // validation wins when this expiry cleanup reaches the exposure lock. - work = suspendSource(operation.domain, repository.canonical, revision, true); + work = suspendSource(operation.domain, repository.canonical, revision, "source"); } else if (publishing && publicationId) { // Cleanup is not a new metadata observation. Discard just this // attempt; another owner may already have published a valid root. @@ -869,16 +870,26 @@ export function createReferenceSources(options: { * unsettled until the pool confirms, so a bind retries it and refuses until * it does. */ - function suspendSource(domain: string, repository: string, revision: string, onlyExpired = false, captured?: InvalidatedRoot[]): Promise { + function suspendSource(domain: string, repository: string, revision: string, expiry: false | "source" | "bind" = false, captured?: InvalidatedRoot[], observed?: SourceRow): Promise { const key = sourceKey(domain, repository, revision); return exclusive(key, async () => { const source = row(domain, repository, revision); - if (onlyExpired && (!source || validationLive(source))) return; + const expected = observed ?? (expiry ? source : undefined); + const before = expiry === "bind" ? now() + BIND_MARGIN() - limits.validationMs : expiry === "source" ? now() - limits.validationMs : undefined; + if (expiry && !source) return; + if (expected && (!source || source.root_id !== expected.root_id || source.validated_at !== expected.validated_at + || (before !== undefined && source.validated_at !== null && source.validated_at > before))) return; const priorWithdrawal = withdrawn.get(key); - // Bind expiry is shared invalidation too, rather than a local flag that - // another owner can renew while native withdrawal is still outstanding. + // Retire the observed publication in the shared catalog; cache validation + // cannot revive it while native withdrawal is still outstanding. const managed = isManaged(repository); - const roots = managed ? captured ?? await fenceSource(key) + let roots: { id: string; state: string }[]; + if (expected) { + const expired = await write("sourceFenceCurrent", domain, repository, revision, randomUUID(), expected.root_id, expected.validated_at, before, managed); + if (!expired) return; + if (!managed) authorityFences.set(key, (authorityFences.get(key) ?? 0) + 1); + roots = expired; + } else roots = managed ? captured ?? await fenceSource(key) : db.query("SELECT id, state FROM reference_roots WHERE domain = ? AND repository = ? AND revision = ?").all(domain, repository, revision) as { id: string; state: string }[]; if (managed) { const current = row(domain, repository, revision); @@ -893,8 +904,8 @@ export function createReferenceSources(options: { const pending = [...pendingPublications].filter(([, publication]) => publication.key === key); if ((!source?.root_id && !roots.length && !pending.length) || (withholding(source) === "hidden" && !unsettled.has(key) && !pending.length)) return; suspended.set(key, { rootId: source?.root_id ?? null, validatedAt: 0 }); unsettled.add(key); - await write("sourceSuspend", domain, repository, revision); - if (source) await pool.poolUnpublish((await viewFor(domain)).id, source.name); + if (!expected) await write("sourceSuspend", domain, repository, revision); + if (source && !expected) await pool.poolUnpublish((await viewFor(domain)).id, source.name); for (const root of roots) await hideRecordedRoot(root); for (const [id, publication] of pending) { await pool.poolUnpublish(publication.view, publication.name); @@ -977,9 +988,9 @@ export function createReferenceSources(options: { await abortable(exposing.get(key), signal); const current = row(source.domain, source.repository, source.revision); if (!usable(current)) continue; - if (unsettled.has(key)) { await abortable(suspendSource(current.domain, current.repository, current.revision), signal, false); continue; } + if (unsettled.has(key)) { await abortable(suspendSource(current.domain, current.repository, current.revision, false, undefined, current), signal, false); continue; } const exposure = withholding(current); - if (exposure === "unknown") { await abortable(suspendSource(current.domain, current.repository, current.revision), signal, false); continue; } + if (exposure === "unknown") { await abortable(suspendSource(current.domain, current.repository, current.revision, false, undefined, current), signal, false); continue; } if (exposure === "hidden" || validFor(current) > BIND_MARGIN()) continue; lapsed.push(current); } @@ -992,7 +1003,7 @@ export function createReferenceSources(options: { } for (const source of failed) { if (withholding(row(source.domain, source.repository, source.revision)) === "hidden") continue; - await abortable(suspendSource(source.domain, source.repository, source.revision), signal, false); + await abortable(suspendSource(source.domain, source.repository, source.revision, "bind", undefined, source), signal, false); } // No root other than a source's current one stays in the view: superseded, // withdrawn, retained for a worktree, or staging whose publication reply was lost. @@ -1007,10 +1018,12 @@ export function createReferenceSources(options: { // Unpublished staging is outside the worker's views already. Taking // its publication authority would cancel a valid concurrent fetch. if (record?.purpose === "source" && record.view === null && ["reserved", "writable", "sealed"].includes(record.state)) { + if (record.publicationRevoked === true) await write("sourceDiscard", id); hiddenRoots.set(id, record.publicationRevoked === true); return; } } + if (state === "staging" && !await write("sourceRetireStaging", id)) return; await hideRoot(id); }), signal, false); } @@ -1164,7 +1177,7 @@ export function createReferenceSources(options: { } for (const { id } of db.query("SELECT id FROM reference_roots").all() as { id: string }[]) if (byId.has(id) && !keep.has(id) && !retained.includes(id)) db.query("DELETE FROM reference_roots WHERE id = ?").run(id); - db.query("UPDATE reference_roots SET state = 'published' WHERE id IN (SELECT root_id FROM reference_sources WHERE root_id IS NOT NULL)").run(); + db.query("UPDATE reference_roots SET state = 'published' WHERE state != 'superseded' AND id IN (SELECT root_id FROM reference_sources WHERE root_id IS NOT NULL)").run(); db.query("DELETE FROM reference_sources WHERE root_id IS NULL").run(); // A root kept only for a worktree is never left where a bound view reaches it. for (const id of retained) await hideRoot(id).catch(error => warn("retained reference root stays in its view until the next bind hides it", error)); @@ -1219,7 +1232,7 @@ export function createReferenceSources(options: { const key = sourceKey(source.domain, source.repository, source.revision); const exposure = withholding(source); if ((exposure === "hidden" && !unsettled.has(key)) || (exposure === "live" && validFor(source) > BIND_MARGIN())) continue; - await abortable(suspendSource(source.domain, source.repository, source.revision), signal, false); + await abortable(suspendSource(source.domain, source.repository, source.revision, exposure === "live" ? "bind" : false, undefined, source), signal, false); } signal?.throwIfAborted(); if (domains.every(admissible)) return paths; diff --git a/packages/ui-server/tests/reference-source-authority.test.ts b/packages/ui-server/tests/reference-source-authority.test.ts index 67d501e1eb..538a462a8b 100644 --- a/packages/ui-server/tests/reference-source-authority.test.ts +++ b/packages/ui-server/tests/reference-source-authority.test.ts @@ -77,3 +77,23 @@ test("publication commit cannot replace a newer root while authority versions re "PUBLICATION_TRANSACTION_PRESERVES_NEWER_ROOT").toBe(false); expect(db.query("SELECT root_id, commit_id FROM reference_sources").get()).toEqual({ root_id: "telemachus-new-root", commit_id: "c".repeat(40) }); }); + +test("a discarded staging identity cannot commit publication after native withdrawal", () => { + const id = "odysseus-retired-staging"; + writes.sourceStage(id, "public", repository, "main", at); + writes.sourceDiscard(id); + expect(writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", repository, "ithaca", id, "a".repeat(40), "refs/heads/main", null, at), + "RETIRED_STAGING_TRANSACTION_CANNOT_RESURRECT_PUBLICATION").toBe(false); + expect(db.query("SELECT 1 FROM reference_sources").get()).toBeNull(); +}); + +test("managed expiry retires its root without cancelling an independent acquisition", () => { + const expected = sourceAuthority(db, "public", repository, "main"); + for (const id of ["odysseus-expired-root", "telemachus-staging"]) writes.sourceStage(id, "public", repository, "main", at); + writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", repository, "ithaca", "odysseus-expired-root", "a".repeat(40), "refs/heads/main", null, at); + const roots = writes.sourceFenceCurrent("public", repository, "main", "odysseus-expiry", "odysseus-expired-root", at, at, true); + expect(roots?.map(root => root.id)).toEqual(["odysseus-expired-root"]); + expect(sourceAuthorityCurrent(db, expected)).toBe(true); + expect(writes.sourceValidate(at + 1, at + 1, "refs/heads/main", "public", repository, "main", expected, "odysseus-expired-root"), "RETIRED_EXPIRY_CANNOT_RENEW_OLD_ROOT").toBe(false); + expect(writes.sourcePublish("/srv/fixtures/view", "public", repository, "main", repository, "ithaca", "telemachus-staging", "c".repeat(40), "refs/heads/main", null, at + 1, undefined, expected, { rootId: "odysseus-expired-root" })).toBe(true); +}); diff --git a/packages/ui-server/tests/reference-source-managed.test.ts b/packages/ui-server/tests/reference-source-managed.test.ts index a7bacd1d44..1c4f8511d6 100644 --- a/packages/ui-server/tests/reference-source-managed.test.ts +++ b/packages/ui-server/tests/reference-source-managed.test.ts @@ -126,9 +126,11 @@ test("a cached shared root still uses the requesting principal and turn's own me }); for (const phase of ["fetch", "seal"] as const) -for (const owner of ["same service", "another service"] as const) -test(`a concurrent bind from ${owner} preserves an unpublished managed source during ${phase}`, async () => { +for (const { owner, refresh } of [{ owner: "same service", refresh: false }, { owner: "another service", refresh: false }, { owner: "another service", refresh: true }] as const) +test(`a concurrent bind from ${owner} preserves an unpublished managed source during ${phase}${refresh ? " with an expired source" : ""}`, async () => { const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + let previousRoot: string | undefined; + if (refresh) { const previous = await f.request(); previousRoot = previous.rootId; previous.release(); f.state.clock += 400_000; f.state.commit = "c".repeat(40); } const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), fetch = f.transport.fetch, seal = f.pool.poolSeal; const pause = async () => { arrived.resolve(); await resume.promise; }; if (phase === "fetch") f.transport.fetch = async input => { const result = await fetch(input); await pause(); return result; }; @@ -136,7 +138,7 @@ test(`a concurrent bind from ${owner} preserves an unpublished managed source du const pending = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); try { await arrived.promise; - const staging = [...f.pool.records.values()].find(record => record.purpose === "source")!; + const staging = [...f.pool.records.values()].find(record => record.purpose === "source" && record.id !== previousRoot)!; expect(staging.view).toBeNull(); expect(staging.publicationRevoked).toBe(false); const view = await (owner === "same service" ? f.sources : otherSources).bindable(f.other.id); expect(existsSync(join(view.public, staging.id, "README.md"))).toBe(false); @@ -170,6 +172,24 @@ test("a bind withdraws staging already exposed without a source catalog receipt" } finally { held?.release(); await f.close(); } }); +test("a publisher cannot commit a fresh lease after another service retires its exposed staging root", async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); + const arrived = Promise.withResolvers(), resume = Promise.withResolvers(), publish = f.pool.poolPublish; + f.pool.poolPublish = async (...args) => { const record = structuredClone(await publish(...args)); arrived.resolve(); await resume.promise; return record; }; + const pending = f.request().then(lease => ({ lease, error: undefined }), error => ({ lease: undefined, error })); + try { + await arrived.promise; + await otherSources.bindable(f.other.id); + resume.resolve(); const result = await pending; + expect(result.lease, "RETIRED_STAGING_CANNOT_COMMIT_AN_AUTHORITATIVE_LEASE").toBeUndefined(); + expect(result.error).toMatchObject({ code: "unavailable" }); + expect(f.db.query("SELECT root_id FROM reference_sources").get()).toBeNull(); + } finally { + resume.resolve(); const result = await pending; result.lease?.release(); f.pool.poolPublish = publish; + await otherSources.close(); otherDb.close(); await f.close(); + } +}); + for (const wait of ["seal", "native-publication"] as const) test(`an older managed acquisition cannot replace a newer revision after ${wait}`, async () => { const f = await fixture(), otherDb = createUiDb(f.databasePath), otherSources = f.restart(otherDb); @@ -1032,6 +1052,50 @@ describe("live managed authority", () => { } }); + for (const phase of ["failed scan", "expiry transaction"] as const) + test(`bind expiry preserves another owner's renewal committed after ${phase}`, async () => { + const f = await fixture(), otherDb = createUiDb(f.databasePath); + const queryDescriptor = Object.getOwnPropertyDescriptor(f.db, "query"), transactionDescriptor = Object.getOwnPropertyDescriptor(f.db, "transaction"); + const query = f.db.query.bind(f.db), transaction = f.db.transaction.bind(f.db); + let held: Awaited> | undefined, injected = false; + const renew = () => { injected = true; sourceWrites(otherDb).sourceValidate(f.state.clock, f.state.clock, "refs/heads/main", "public", repository, "main", undefined, held!.rootId); }; + try { + held = await f.request(); f.state.clock += 400_000; + if (phase === "failed scan") f.db.query = ((sql: string) => { + const statement = query(sql); + if (!injected && sql === "SELECT * FROM reference_sources WHERE domain = ? AND repository = ? AND revision = ?") { + const get = statement.get.bind(statement); + statement.get = ((...args: unknown[]) => { const snapshot = get(...args as []); statement.get = get; if (!injected) queueMicrotask(renew); return snapshot; }) as typeof statement.get; + } + return statement; + }) as typeof f.db.query; + else f.db.transaction = ((fn: (...args: unknown[]) => unknown) => { if (!injected) renew(); return transaction(fn); }) as typeof f.db.transaction; + await f.sources.bindable(f.other.id); + expect(injected).toBe(true); + expect(f.db.query("SELECT validated_at FROM reference_sources").get(), "EXPIRY_TRANSACTION_PRESERVES_NEWER_VALIDATION").toEqual({ validated_at: f.state.clock }); + expect(f.pool.records.get(held.rootId)!.publicationRevoked).toBe(false); + expect(existsSync(join(held.viewPath, held.rootId, "README.md"))).toBe(true); + } finally { + if (queryDescriptor) Object.defineProperty(f.db, "query", queryDescriptor); else Reflect.deleteProperty(f.db, "query"); + if (transactionDescriptor) Object.defineProperty(f.db, "transaction", transactionDescriptor); else Reflect.deleteProperty(f.db, "transaction"); + held?.release(); otherDb.close(); await f.close(); + } + }); + + test("recovery preserves a retired managed publication until fresh acquisition replaces it", async () => { + const f = await fixture(); + let old: Awaited> | undefined, fresh: typeof old; + try { + old = await f.request(); f.state.clock += 400_000; + await f.sources.bindable(f.other.id); await f.sources.recover(); + expect(sourceWrites(f.db).sourceValidate(f.state.clock, f.state.clock, "refs/heads/main", "public", repository, "main", undefined, old.rootId), + "RECOVERY_CANNOT_REVIVE_RETIRED_VALIDATION").toBe(false); + old.release(); fresh = await f.request(); + expect(fresh.rootId).not.toBe(old.rootId); + expect(existsSync(join(fresh.viewPath, fresh.name, "README.md"))).toBe(true); + } finally { fresh?.release(); old?.release(); await f.close(); } + }); + for (const failure of ["catalog write", "native withdrawal"] as const) test(`a bind retries ${failure} failure after another owner republishes a previously hidden legacy root`, async () => { const f = await fixture(), issued = f.grant(), otherDb = createUiDb(f.databasePath), options = { ...f.sourceOptions, github: undefined }; diff --git a/packages/ui-server/tests/reference-tools.test.ts b/packages/ui-server/tests/reference-tools.test.ts index 0e503968ca..8495571489 100644 --- a/packages/ui-server/tests/reference-tools.test.ts +++ b/packages/ui-server/tests/reference-tools.test.ts @@ -377,9 +377,9 @@ describe("exposure changes are serialized (#2432 review)", () => { tools.end(first.turnId); clock += 301_000; state.failResolves = 2; - const unpublish = pool.poolUnpublish; + const withdraw = pool.poolWithdraw; let failures = 1; - pool.poolUnpublish = async (view, entry, signal) => { if (failures-- > 0) throw new Error("manager reply lost"); return unpublish(view, entry, signal); }; + pool.poolWithdraw = async (id, signal) => { if (failures-- > 0) throw new Error("manager reply lost"); return withdraw(id, signal); }; await expect(sources.bindable(telemachus.id), "REFERENCE_TOOLS_FAILED_SUSPENSION_FAILS_CLOSED").rejects.toMatchObject({ code: "unavailable" }); expect(publicEntries(await sources.bindable(telemachus.id)), "REFERENCE_TOOLS_FAILED_SUSPENSION_RETRIED").toEqual([]); });