Skip to content
Merged
6 changes: 6 additions & 0 deletions .changeset/4079-reference-maintenance-admission.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@schlessera/brain-ui-server": patch
"@schlessera/brain-ui-sdk": patch
---

A turn's first `reference_source` call is no longer refused by the turn's own maintenance commands (#4079). Every maintenance command reserves the whole default 256 MiB maintenance budget, so a reference Git command that started while the turn's scratch check ran, or a boot-time `brain scratch prune`, was refused at once. The tool then answered the generic `unavailable` with no retry guidance. Now each reference Git command waits up to 30 seconds for the budget to free, and a request still refused after that answers `busy` with "nothing ran, retry" guidance, never `unavailable`. An awaited scratch check waits up to 3 seconds the same way, so a short reference command no longer leaves `.brain/scratch/` read-only for the turn. A longer holder, such as an index, still leaves it read-only after that wait. The synchronous scratch check and the bind-time revalidation of lapsed sources still refuse at once. Neither wait adds an allowance: both stay inside the existing budget.
12 changes: 6 additions & 6 deletions docs/decisions/managed-worktrees.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:59-194`).
(`createReferenceTools`, `packages/ui-server/src/brain/reference-tools.ts:60-200`).

**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
Expand All @@ -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:141-190`).
(`async call(turnId: string`, `packages/ui-server/src/brain/reference-tools.ts:147-196`).
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
Expand All @@ -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:745-776`).
(`async bindable(principalId: string`, `packages/ui-server/src/brain/reference-source.ts:747-778`).
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
Expand Down Expand Up @@ -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:569-607`):
(`async function settleView`, `packages/ui-server/src/brain/reference-source.ts:571-609`):

- 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
Expand All @@ -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:505-516`).
(`function suspendSource`, `packages/ui-server/src/brain/reference-source.ts:506-517`).
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.
Expand All @@ -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:613-622`).
(`function admissible`, `packages/ui-server/src/brain/reference-source.ts:615-624`).
The margin covers the moments between admission and the workers' mounts.

Suspension, restoration, withdrawal and publication of one source run one at a
Expand Down
12 changes: 6 additions & 6 deletions docs/decisions/reference-source-acquisition.md
Original file line number Diff line number Diff line change
Expand Up @@ -79,18 +79,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:407-460`):
(`acquire`, `packages/ui-server/src/brain/reference-source.ts:408-461`):

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:169-190`).
(`async fetch({ repository, ref, token, root, signal, wire })`, `packages/ui-server/src/brain/reference-transport.ts:198-219`).
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:191-200`).
(`async checkout({ root, commit, signal })`, `packages/ui-server/src/brain/reference-transport.ts:220-229`).
4. The live grant is read again, the root is sealed, the grant is read
again, and only then is the root published.

Expand Down Expand Up @@ -172,7 +172,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:366-382`).
`capacity` (`evictOne`, `packages/ui-server/src/brain/reference-source.ts:367-383`).
There is no idle expiry.

## Revocation and recovery
Expand All @@ -185,14 +185,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:655-675`).
(`revoke`, `packages/ui-server/src/brain/reference-source.ts:657-677`).

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:678-722`).
catalog lost, and deletions interrupted in `deleting` (`recover`, `packages/ui-server/src/brain/reference-source.ts:680-724`).

## Evidence

Expand Down
4 changes: 3 additions & 1 deletion docs/integration-contract/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -1244,7 +1244,9 @@ authenticated turn, and another principal's worktree identity reads as
backends, with `code` one of `unavailable`, `unauthorized`, `missing`,
`invalid`, `capacity`, `busy`, `released` or `cancelled`. Messages are at most
500 bytes; one that could name a host path is replaced by a fixed message for
its code, as is a stale source's `error`.
its code, as is a stale source's `error`. Each Git command of a request waits
up to 30 seconds for the host's maintenance budget; a request still refused
then is `busy` with retry guidance, and nothing ran (additive, 0.45.0, #4079).

`source` is `{ repository, revision, domain, commit, path, freshness,
refreshedAt, validatedAt, error }`. `freshness` is `fresh` or `stale`; a stale
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/reviewable-session-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:106-203`).
`packages/ui-server/src/brain/reference-transport.ts:116-213`).
- 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`).
Expand Down
11 changes: 11 additions & 0 deletions packages/ui-sdk/src/server/maintenance-temp-budget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,17 @@ export class MaintenanceTempBusyError extends WorkerStateError {
}
/** Resolves when the budget can take this allowance again; rejects with the signal's reason. */
freed(signal?: AbortSignal): Promise<void> { return waitFor(this.capacity, signal); }
/**
* A bounded `freed()` (#4079): true once the allowance would fit again,
* false when `ms` passes first. Rejects with the signal's reason.
*/
async freedWithin(ms: number, signal?: AbortSignal): Promise<boolean> {
const bound = new AbortController();
const timer = setTimeout(() => bound.abort(), Math.max(0, ms));
try { await this.freed(signal ? AbortSignal.any([signal, bound.signal]) : bound.signal); return true; }
catch (error) { if (bound.signal.aborted && !signal?.aborted) return false; throw error; }
finally { clearTimeout(timer); }
}
}

/** In-process releases wake waiters at once; another process's release is found by the bounded recheck. */
Expand Down
2 changes: 2 additions & 0 deletions packages/ui-sdk/src/server/maintenance-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ export interface MaintenanceHost {
tempLimits?: WorkerStateLimits;
tempDomain?: MaintenanceTempDomain;
maskPaths?: readonly string[];
/** @internal How long an awaited scratch check waits for a busy budget; default `SCRATCH_ADMISSION_WAIT_MS` (#4079). */
admissionWaitMs?: number;
}

export interface MaintenanceResult {
Expand Down
34 changes: 31 additions & 3 deletions packages/ui-sdk/src/server/worker-sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import { closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, open
import { join, relative } from "node:path";
import { BRAIN_SCRATCH_DIR, BRAIN_WORKSPACES_DIR, linkRule, READ_ONLY_BRAIN_RULE, TURN_TEMP_RULE } from "@schlessera/brain-common/internal/worker-areas";
import { brainGitSteps } from "./maintenance-worker.js";
import { runWorkerStepsSync, type WorkerSteps } from "./worker-steps.js";
import { MaintenanceTempBusyError } from "./maintenance-temp-budget.js";
import { runWorkerStepsSync, workerStep, type WorkerSteps } from "./worker-steps.js";
import { WORKER_XDG_HOME } from "./worker-xdg.js";

/**
Expand Down Expand Up @@ -410,20 +411,47 @@ function unlinkScanned(dir: string, alias: ScannedAlias): void {
function* scratchIgnoredByGit(brain: string, maintenance?: import("./maintenance-worker.js").MaintenanceHost): WorkerSteps<true | { refused: string }> {
const git = Bun.which("git");
const own = Boolean(lstatSync(join(brain, ".git"), { throwIfNoEntry: false }));
const deadline = Date.now() + (maintenance?.admissionWaitMs ?? SCRATCH_ADMISSION_WAIT_MS);
if (!own) {
if (!git) return true;
const inRepo = yield* brainGitSteps(brain, ["rev-parse", "--git-dir"], { ...maintenance, tempKind: "scratch_query" });
const inRepo = yield* admittedGitSteps(brain, ["rev-parse", "--git-dir"], deadline, maintenance);
if (inRepo === 127) return { refused: "git could not run to confirm .brain/scratch/ is gitignored" };
if (inRepo !== 0) return true;
}
if (!git) return { refused: "git is not available to confirm .brain/scratch/ is gitignored" };
const exitCode = yield* brainGitSteps(brain, ["check-ignore", "-q", "--no-index", "--", BRAIN_SCRATCH_DIR], { ...maintenance, tempKind: "scratch_query" });
const exitCode = yield* admittedGitSteps(brain, ["check-ignore", "-q", "--no-index", "--", BRAIN_SCRATCH_DIR], deadline, maintenance);
if (exitCode === 0) return true;
return { refused: exitCode === 1
? ".brain/scratch/ is not gitignored, so a file written there could be committed; run `brain doctor --fix` outside a hosted turn"
: "git could not confirm .brain/scratch/ is gitignored" };
}

/**
* How long an awaited scratch check waits for a busy maintenance budget
* (#4079). A turn's own short maintenance commands, such as a reference
* resolution or another turn's check, finish well inside it; a long holder,
* such as an index, still leaves scratch read-only after it rather than
* holding the turn's start.
*/
export const SCRATCH_ADMISSION_WAIT_MS = 3_000;

/**
* One scratch-check Git query, admitted by `deadline`. An awaited runner
* waits for the budget to free and tries again; a synchronous one refuses
* at once, as before.
*/
function* admittedGitSteps(brain: string, args: readonly string[], deadline: number, maintenance?: import("./maintenance-worker.js").MaintenanceHost): WorkerSteps<number> {
const { admissionWaitMs: _wait, ...host } = maintenance ?? {};
for (;;) {
try { return yield* brainGitSteps(brain, args, { ...host, tempKind: "scratch_query" }); }
catch (error) {
if (!(error instanceof MaintenanceTempBusyError) || Date.now() >= deadline) throw error;
const freed = yield* workerStep<boolean>(() => { throw error; }, () => error.freedWithin(deadline - Date.now()));
if (!freed) throw error;
}
}
}

/** Repo-relative path for a server log line or the note; never an absolute host path. */
function shown(paths: readonly string[]): string {
return paths.slice(0, 3).join(", ") + (paths.length > 3 ? ` and ${paths.length - 3} more` : "");
Expand Down
Loading
Loading