From 2616ed6d2557d35cb2d40679728520a887ff083a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 08:05:19 +0000 Subject: [PATCH 1/5] CONTRACT: fix(ui-server,ui-sdk): wait for a turn's own maintenance before refusing its first reference call (#4079) Every maintenance command reserves the whole default 256 MiB maintenance budget, and admission refuses rather than waits. A reference Git command that overlapped the turn's scratch check, or the boot-time scratch prune, was refused at once, and the tool answered the generic `unavailable` with no retry guidance. The scratch check refused the other way round left `.brain/scratch/` read-only for the turn. - The reference transport waits up to REFERENCE_ADMISSION_WAIT_MS (30 s) per Git command for the budget to free, then refuses as `busy`. The reference source maps that to its existing `busy` code on resolution and on fetch or checkout. The tool classifies any raw maintenance-busy error that reaches it as `busy` too, never `unavailable`. - An awaited scratch check waits up to SCRATCH_ADMISSION_WAIT_MS (3 s) on one deadline across its Git queries. The synchronous check and bind-time revalidation of lapsed sources still refuse at once. - MaintenanceTempBusyError gains freedWithin(ms, signal), a bounded freed(). Neither wait adds an allowance; both stay inside the existing budget. The MCP contract component states the new bound for `busy`. Co-Authored-By: Claude Opus 5.5 --- .../4079-reference-maintenance-admission.md | 6 + docs/decisions/managed-worktrees.md | 12 +- .../decisions/reference-source-acquisition.md | 12 +- docs/integration-contract/mcp.md | 4 +- docs/plans/reviewable-session-safety.md | 2 +- .../src/server/maintenance-temp-budget.ts | 11 ++ .../ui-sdk/src/server/maintenance-worker.ts | 2 + packages/ui-sdk/src/server/worker-sandbox.ts | 34 ++++- .../tests/maintenance-temp-holders.test.ts | 47 ++++++- .../ui-server/src/brain/reference-source.ts | 8 +- .../ui-server/src/brain/reference-tools.ts | 8 +- .../src/brain/reference-transport.ts | 45 +++++-- .../reference-maintenance-admission.test.ts | 123 ++++++++++++++++++ 13 files changed, 282 insertions(+), 32 deletions(-) create mode 100644 .changeset/4079-reference-maintenance-admission.md create mode 100644 packages/ui-server/tests/reference-maintenance-admission.test.ts diff --git a/.changeset/4079-reference-maintenance-admission.md b/.changeset/4079-reference-maintenance-admission.md new file mode 100644 index 0000000000..341a5933e3 --- /dev/null +++ b/.changeset/4079-reference-maintenance-admission.md @@ -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. diff --git a/docs/decisions/managed-worktrees.md b/docs/decisions/managed-worktrees.md index 2dfea0817e..94d2adf4ae 100644 --- a/docs/decisions/managed-worktrees.md +++ b/docs/decisions/managed-worktrees.md @@ -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 @@ -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 @@ -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 @@ -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 @@ -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. @@ -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 diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 883ebcbf7a..ff73ddd391 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -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. @@ -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 @@ -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 diff --git a/docs/integration-contract/mcp.md b/docs/integration-contract/mcp.md index 0106f612fd..ff9291132b 100644 --- a/docs/integration-contract/mcp.md +++ b/docs/integration-contract/mcp.md @@ -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 diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 4f158d1d02..49f5c69421 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -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`). diff --git a/packages/ui-sdk/src/server/maintenance-temp-budget.ts b/packages/ui-sdk/src/server/maintenance-temp-budget.ts index 207825ed72..c21a05446f 100644 --- a/packages/ui-sdk/src/server/maintenance-temp-budget.ts +++ b/packages/ui-sdk/src/server/maintenance-temp-budget.ts @@ -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 { 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 { + 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. */ diff --git a/packages/ui-sdk/src/server/maintenance-worker.ts b/packages/ui-sdk/src/server/maintenance-worker.ts index eecb179dc6..1c3ba9c827 100644 --- a/packages/ui-sdk/src/server/maintenance-worker.ts +++ b/packages/ui-sdk/src/server/maintenance-worker.ts @@ -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 { diff --git a/packages/ui-sdk/src/server/worker-sandbox.ts b/packages/ui-sdk/src/server/worker-sandbox.ts index f106935a08..b94f814aee 100644 --- a/packages/ui-sdk/src/server/worker-sandbox.ts +++ b/packages/ui-sdk/src/server/worker-sandbox.ts @@ -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"; /** @@ -410,20 +411,47 @@ function unlinkScanned(dir: string, alias: ScannedAlias): void { function* scratchIgnoredByGit(brain: string, maintenance?: import("./maintenance-worker.js").MaintenanceHost): WorkerSteps { 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 { + 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(() => { 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` : ""); diff --git a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts index 9016c8c03b..610314c096 100644 --- a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts +++ b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts @@ -5,7 +5,7 @@ import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceTempReservation } from "../src/server/maintenance-temp-budget"; -import { prepareWorkerSandboxAsync } from "../src/server/worker-launcher"; +import { prepareWorkerSandbox, prepareWorkerSandboxAsync } from "../src/server/worker-launcher"; import { FIRST_PARTY_FAILURE_CLASSES } from "../src/protocol"; // #3461: production limits (one 256 MiB allowance in a 256 MiB budget) on a @@ -92,12 +92,53 @@ test("freed() settles on an in-process release and rejects with its signal's rea await expect(waiting, "MAINTENANCE_FREED_ENDS_WITH_ITS_SIGNAL").rejects.toBe(reason); }); -test("opposite order: a turn's scratch check refused while an index holds the budget stays read-only and names the index", async () => { +test("freedWithin() reports a release inside its bound, false past it, and rejects with its signal's reason (#4079)", async () => { + const holder = hold("scratch_query"); + const error = refusal() as MaintenanceTempBusyError; + setTimeout(() => holder.release(), 50); + expect(await error.freedWithin(5_000), "MAINTENANCE_FREED_WITHIN_SEES_A_RELEASE").toBe(true); + + hold("scratch_query"); + const again = refusal() as MaintenanceTempBusyError; + const started = performance.now(); + expect(await again.freedWithin(150), "MAINTENANCE_FREED_WITHIN_ENDS_FALSE_AT_ITS_BOUND").toBe(false); + expect(performance.now() - started, "MAINTENANCE_FREED_WITHIN_WAITS_ITS_BOUND").toBeGreaterThanOrEqual(140); + const ending = new AbortController(), reason = new Error("Server shutting down"); + const waiting = again.freedWithin(5_000, ending.signal); + ending.abort(reason); + await expect(waiting, "MAINTENANCE_FREED_WITHIN_ENDS_WITH_ITS_SIGNAL").rejects.toBe(reason); +}); + +test("a turn's scratch check that starts while a reference Git command holds the budget waits for it, and scratch stays writable (#4079)", async () => { const brain = join(root, "brain"); mkdirSync(brain); - hold("index"); + // The turn's first reference_source call is running its short ls-remote. + const reference = hold("git"); + setTimeout(() => reference.release(), 250); const sandbox = await prepareWorkerSandboxAsync(brain, { areas: ["scratch"], maintenance: { tempLimits: LIMITS, tempDomain: domain } }); const scratch = sandbox.areas.find(area => area.name === "scratch"); + const reason = scratch?.mount.writable === false ? scratch.mount.reason : ""; + expect(reason, "TURN_SCRATCH_CHECK_IS_NOT_REFUSED_BY_A_SHORT_REFERENCE_COMMAND").not.toContain("Maintenance temporary storage is busy"); + expect(scratch?.mount.writable, "TURN_SCRATCH_STAYS_WRITABLE_AFTER_A_SHORT_REFERENCE_COMMAND").toBe(true); +}); + +test("a synchronous scratch check still refuses at once while maintenance holds the budget (#4079)", () => { + const brain = join(root, "brain"); + mkdirSync(brain); + hold("git"); + const started = performance.now(); + const sandbox = prepareWorkerSandbox(brain, { areas: ["scratch"], maintenance: { tempLimits: LIMITS, tempDomain: domain } }); + const scratch = sandbox.areas.find(area => area.name === "scratch"); + expect(scratch?.mount.writable === false ? scratch.mount.reason : "", "SYNC_SCRATCH_CHECK_KEEPS_ITS_BUSY_OUTCOME").toContain("(held by: git)"); + expect(performance.now() - started, "SYNC_SCRATCH_CHECK_NEVER_WAITS").toBeLessThan(2_000); +}); + +test("opposite order: a turn's scratch check refused while an index holds the budget past its wait stays read-only and names the index", async () => { + const brain = join(root, "brain"); + mkdirSync(brain); + hold("index"); + const sandbox = await prepareWorkerSandboxAsync(brain, { areas: ["scratch"], maintenance: { tempLimits: LIMITS, tempDomain: domain, admissionWaitMs: 200 } }); + const scratch = sandbox.areas.find(area => area.name === "scratch"); expect(scratch?.mount.writable, "TURN_SCRATCH_CHECK_LOSES_TO_HELD_INDEX").toBe(false); const reason = scratch?.mount.writable === false ? scratch.mount.reason : ""; expect(reason, "TURN_SCRATCH_CHECK_KEEPS_ITS_DOCUMENTED_OUTCOME") diff --git a/packages/ui-server/src/brain/reference-source.ts b/packages/ui-server/src/brain/reference-source.ts index 63e0af6d2e..5aba499e35 100644 --- a/packages/ui-server/src/brain/reference-source.ts +++ b/packages/ui-server/src/brain/reference-source.ts @@ -300,7 +300,7 @@ export function createReferenceSources(options: { const credential = token(grant); const existing = row(domain, repository.canonical, revision); const check = await transport.resolve({ repository, revision, token: credential, signal }).catch((error: unknown) => { - if (error instanceof ReferenceTransportError && error.reason === "invalid") throw new ReferenceSourceError("invalid", error.message); + if (error instanceof ReferenceTransportError && (error.reason === "invalid" || error.reason === "busy")) throw new ReferenceSourceError(error.reason, error.message); throw error; }); signal.throwIfAborted(); @@ -337,7 +337,8 @@ export function createReferenceSources(options: { } // The previous revision stays usable only inside its own still-valid authority. if (existing && usable(existing) && validationLive(existing)) return failed(existing, detail); - throw error instanceof ReferenceSourceError ? error : new ReferenceSourceError(error instanceof ReferenceTransportError && error.reason === "capacity" ? "capacity" : "unavailable", detail); + throw error instanceof ReferenceSourceError ? error + : new ReferenceSourceError(error instanceof ReferenceTransportError && (error.reason === "capacity" || error.reason === "busy") ? error.reason : "unavailable", detail); } } /** Record a failed refresh without advancing its successful refresh time. */ @@ -531,7 +532,8 @@ export function createReferenceSources(options: { const grant = principalId === null ? null : coveringReferenceGrant(db, { brain: options.brain, principalId, repository, now: now() }); if (principalId !== null && !grant) return false; // Shared by every bind waiting on it, so no one binder's cancellation decides it. - const check = await transport.resolve({ repository, revision: source.revision, token: token(grant) }); + // A bind never waits for busy maintenance (#4079): the source is withheld from it instead. + const check = await transport.resolve({ repository, revision: source.revision, token: token(grant), admissionWaitMs: 0 }); if (!check.ok) { if (check.reason !== "unavailable") { if (source.domain === PUBLIC) notPublic.set(`${repository.canonical}\u0000${source.revision}`, now() + limits.validationMs); diff --git a/packages/ui-server/src/brain/reference-tools.ts b/packages/ui-server/src/brain/reference-tools.ts index 231cd7e252..e701769a8b 100644 --- a/packages/ui-server/src/brain/reference-tools.ts +++ b/packages/ui-server/src/brain/reference-tools.ts @@ -15,7 +15,7 @@ */ import { ZodError } from "zod"; import type { Logger } from "@opentelemetry/api-logs"; -import { WORKER_REFERENCE_ROOT, WORKER_WORKTREE_ROOT } from "@schlessera/brain-ui-sdk/internal"; +import { MaintenanceTempBusyError, WORKER_REFERENCE_ROOT, WORKER_WORKTREE_ROOT } from "@schlessera/brain-ui-sdk/internal"; import { REFERENCE_SOURCE_INPUT_SCHEMA, REFERENCE_WORKTREE_INPUT_SCHEMA, REFERENCE_WORKTREE_LIST_LIMIT, type ReferenceSourceView, type ReferenceToolCall, type ReferenceToolRefusalCode, type ReferenceToolResult, type ReferenceWorktreeView, @@ -38,6 +38,7 @@ const PUBLIC_MESSAGES: Record = { cancelled: "The request was cancelled.", }; +const MAINTENANCE_BUSY = "Host maintenance is busy, so nothing ran. Retry this request in a minute."; const SOURCE_GUIDANCE = "Read only under path. Shared source is read-only and moves: a later read may see a newer commit. To edit it, or to read one fixed commit across several steps, request a managed worktree."; const WORKTREE_GUIDANCE: Record<"request" | "access" | "renew" | "release", string> = { request: "Work only under path. The starting commit never moves. Edits are journaled and count toward this turn's scope limits. Only access or renewal resets the inactivity clock; release the worktree when you are done.", @@ -67,6 +68,11 @@ export function createReferenceTools(options: { if (error instanceof ZodError) return { ok: false, code: "invalid", message: scrub(error.issues.map(issue => issue.message).join("; "), "invalid") }; if (error instanceof ReferenceSourceError || error instanceof ReferenceWorktreeError) return { ok: false, code: error.code as ReferenceToolRefusalCode, message: scrub(error.message, error.code as ReferenceToolRefusalCode) }; + // Nothing ran: busy host maintenance is a retry, never an outage (#4079). + if (error instanceof MaintenanceTempBusyError) { + options.log?.emit({ severityText: "INFO", body: `reference tool refusal (busy): ${error.message}` }); + return { ok: false, code: "busy", message: MAINTENANCE_BUSY }; + } options.log?.emit({ severityText: "WARN", body: `reference tool failed: ${error instanceof Error ? error.message : String(error)}` }); return { ok: false, code: "unavailable", message: "The reference service could not complete this request." }; } diff --git a/packages/ui-server/src/brain/reference-transport.ts b/packages/ui-server/src/brain/reference-transport.ts index 761fc7b2d4..34227766c9 100644 --- a/packages/ui-server/src/brain/reference-transport.ts +++ b/packages/ui-server/src/brain/reference-transport.ts @@ -8,7 +8,7 @@ import { chmodSync, constants, closeSync, lstatSync, mkdirSync, mkdtempSync, openSync, rmSync, writeSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { runMaintenanceWorker, type MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; +import { MaintenanceTempBusyError, runMaintenanceWorker, type MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; import type { ReferenceRepository } from "../db/reference-grants.js"; import { githubReferenceRepository } from "./github-reference-identity.js"; import type { GitHubReferenceWire } from "./github-reference-wire.js"; @@ -38,13 +38,23 @@ export type ReferenceCheck = | { ok: false; reason: "missing" | "denied" | "unavailable"; detail: string }; export class ReferenceTransportError extends Error { - constructor(readonly reason: "denied" | "unavailable" | "capacity" | "invalid", message: string) { super(message); this.name = "ReferenceTransportError"; } + constructor(readonly reason: "denied" | "unavailable" | "capacity" | "invalid" | "busy", message: string) { super(message); this.name = "ReferenceTransportError"; } } +/** + * How long one reference Git command waits for the shared maintenance budget + * (#4079). The turn that asked holds its own short maintenance commands at the + * same moment, such as its scratch check; they finish well inside this. A + * longer holder, such as an index, makes the request answer `busy`. + */ +export const REFERENCE_ADMISSION_WAIT_MS = 30_000; + /** The concrete operations acquisition needs; tests substitute this one host-only owner. */ export interface ReferenceTransport { /** Resolve a branch or tag through the transport, with the grant's credential value or anonymously. */ - resolve(input: { repository: ReferenceRepository; revision: string; token: string | null; signal?: AbortSignal; wire?: GitHubReferenceWire }): Promise; + resolve(input: { repository: ReferenceRepository; revision: string; token: string | null; signal?: AbortSignal; wire?: GitHubReferenceWire; + /** Overrides the transport's admission wait for this call; 0 refuses at once (#4079). */ + admissionWaitMs?: number }): Promise; /** Fetch exactly one resolved ref into `/.git` and report the fetched commit. */ 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. */ @@ -107,8 +117,27 @@ export function createReferenceTransport(options: { brainPath: string; timeoutMs?: number; tempLimits?: MaintenanceCommand["tempLimits"]; tempDomain?: MaintenanceCommand["tempDomain"]; /** Test seam for the exact launched commands; production uses the maintenance worker. */ run?: typeof runMaintenanceWorker; + /** How long each command waits for a busy maintenance budget; default `REFERENCE_ADMISSION_WAIT_MS`. */ + admissionWaitMs?: number; }): ReferenceTransport { - const run = options.run ?? runMaintenanceWorker; + const launch = options.run ?? runMaintenanceWorker; + const admissionWaitMs = options.admissionWaitMs ?? REFERENCE_ADMISSION_WAIT_MS; + /** + * One command, admitted within the bound. A busy refusal ran nothing, so the + * command waits for the budget to free and tries again; past the bound it is + * a `busy` refusal the caller can retry, never an outage. + */ + async function run(input: Parameters[0], waitMs = admissionWaitMs) { + const deadline = Date.now() + waitMs; + for (;;) { + try { return await launch(input); } + catch (error) { + if (!(error instanceof MaintenanceTempBusyError)) throw error; + if (Date.now() >= deadline || !(await error.freedWithin(deadline - Date.now(), input.signal))) + throw new ReferenceTransportError("busy", `Host maintenance stayed busy for ${Math.ceil(waitMs / 1000)} s, so nothing ran. Retry this request in a minute.`); + } + } + } const timeoutMs = options.timeoutMs ?? 120_000; function command(input: { argv: string[]; mirror: string; token: string | null; repository?: ReferenceRepository; network: boolean; signal?: AbortSignal; wire?: GitHubReferenceWire }) : MaintenanceCommand & { signal?: AbortSignal; timeoutMs: number } { @@ -129,21 +158,21 @@ export function createReferenceTransport(options: { ...(input.wire ? { signal: input.signal ? AbortSignal.any([input.signal, input.wire.signal]) : input.wire.signal } : input.signal ? { signal: input.signal } : {}), timeoutMs }; } - async function network(input: Parameters[0]) { - const result = await run(command(input)); + async function network(input: Parameters[0], waitMs?: number) { + const result = await run(command(input), waitMs); const failure = input.wire?.failure(); if (failure) throw failure; if (input.wire && input.repository) assertWireRepository(input.repository, input.wire); return result; } return { - async resolve({ repository, revision, token, signal, wire }) { + async resolve({ repository, revision, token, signal, wire, admissionWaitMs: waitMs }) { revision = referenceRevision(revision); assertWireRepository(repository, wire); const scratch = mkdtempSync(join(tmpdir(), "brain-reference-resolve-")); try { const result = await network({ repository, token, network: true, mirror: scratch, signal, wire, argv: [git(), ...networkArgs(repository, token), "ls-remote", "--exit-code", "--", repository.url, - `refs/heads/${revision}`, `refs/tags/${revision}`, `refs/tags/${revision}^{}`] }); + `refs/heads/${revision}`, `refs/tags/${revision}`, `refs/tags/${revision}^{}`] }, waitMs); if (result.killed) return { ok: false, reason: "unavailable", detail: "reference resolution timed out or was cancelled" }; if (result.exitCode === 2) return { ok: false, reason: "missing", detail: `no branch or tag named ${revision}` }; if (result.exitCode !== 0) return { ok: false, reason: classify(result.stderr), detail: result.stderr.trim().slice(-500) || `exit ${result.exitCode}` }; diff --git a/packages/ui-server/tests/reference-maintenance-admission.test.ts b/packages/ui-server/tests/reference-maintenance-admission.test.ts new file mode 100644 index 0000000000..15ef03687e --- /dev/null +++ b/packages/ui-server/tests/reference-maintenance-admission.test.ts @@ -0,0 +1,123 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { Database } from "bun:sqlite"; +import { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceCommand, type MaintenanceTempReservation } from "@schlessera/brain-ui-sdk/internal"; +import type { ReferenceToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { createUiDb } from "../src/db/client"; +import { createPrincipal } from "../src/db/principals"; +import { createReferenceSources } from "../src/brain/reference-source"; +import { createReferenceTransport } from "../src/brain/reference-transport"; +import { createReferenceTools } from "../src/brain/reference-tools"; +import { referencePoolDouble } from "./helpers/reference-pool-double"; + +// #4079: a turn's first reference_source call shares one maintenance budget +// with that turn's own maintenance commands, such as its scratch check. +// Production limits: one 256 MiB allowance in a 256 MiB budget, so two +// commands never overlap. A private shared-state domain keeps this ledger +// apart from every other test's. +const LIMITS = { allowanceBytes: 268435456, budgetBytes: 268435456 }; +/** The stated bound: each reference Git command waits at most this long for admission (`REFERENCE_ADMISSION_WAIT_MS`). */ +const BOUND_MS = 30_000; +const BRAIN = "ithaca-brain", PUBLIC = "https://github.com/odysseus/ithaca", TIP = "1".repeat(40); +let root: string, db: Database, domain: { statePath: string }; +const held: MaintenanceTempReservation[] = []; +beforeEach(() => { + root = realpathSync(mkdtempSync(join(tmpdir(), "odysseus-reference-admission-"))); + mkdirSync(join(root, "brain")); mkdirSync(join(root, "state")); + domain = { statePath: join(root, "state", "ui.db") }; + db = createUiDb(":memory:"); +}); +afterEach(() => { + for (const reservation of held.splice(0)) reservation.release(); + db.close(); + rmSync(root, { recursive: true, force: true }); +}); + +/** + * The transport's launcher, taking the real maintenance admission before + * launch as `runMaintenanceWorker` does, with the limits, domain and kind the + * transport names. Admission is the only part under test: no worker starts, + * and each Git command answers as the fixture repository would. + */ +function admittingRun(launches: string[], afterStep?: (step: string) => void) { + return async (command: MaintenanceCommand & { signal?: AbortSignal }) => { + const step = ["ls-remote", "fetch", "rev-parse", "checkout"].find(name => command.command.includes(name))!; + let reservation: MaintenanceTempReservation; + try { reservation = reserveMaintenanceTemp(command.tempLimits!, command.tempDomain, command.tempKind); } + catch (error) { launches.push(`${step}:refused`); throw error; } + launches.push(`${step}:admitted`); + try { + if (step === "ls-remote") return { stdout: `${TIP}\trefs/heads/main\n`, stderr: "", exitCode: 0, killed: false }; + if (step === "rev-parse") return { stdout: `${TIP}\n`, stderr: "", exitCode: 0, killed: false }; + if (step === "checkout") writeFileSync(join(command.transport!.mirror, "odyssey.md"), "Sing, Muse, of the man of many ways.\n"); + return { stdout: "", stderr: "", exitCode: 0, killed: false }; + } finally { reservation.release(); afterStep?.(step); } + }; +} + +/** One app's reference service over the real transport, and one interactive turn prepared as admission prepares it. */ +async function turn(options: { admissionWaitMs?: number; afterStep?: (step: string) => void } = {}) { + const launches: string[] = []; + const transport = createReferenceTransport({ brainPath: join(root, "brain"), tempLimits: LIMITS, tempDomain: domain, run: admittingRun(launches, options.afterStep) as never, + ...(options.admissionWaitMs !== undefined ? { admissionWaitMs: options.admissionWaitMs } : {}) }); + const sources = createReferenceSources({ db, pool: referencePoolDouble(join(root, "pool")), transport, brain: BRAIN, credentials: {} }); + const tools = createReferenceTools({ sources }); + const principalId = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 86_400 }).id; + const turnId = crypto.randomUUID(); + expect(await tools.begin(turnId, { principalId, posture: "interactive", generation: null }), "REFERENCE_TURN_BINDS_ITS_VIEWS").not.toBeNull(); + const call = () => tools.call(turnId, principalId, { tool: "reference_source", input: { repository: PUBLIC, revision: "main" } }); + return { call, launches }; +} +/** What holds the budget when the turn's first call starts: its own scratch check. */ +const scratchCheck = () => { const reservation = reserveMaintenanceTemp(LIMITS, domain, "scratch_query"); held.push(reservation); return reservation; }; + +test("a turn's first reference_source call waits for the turn's own scratch check, then succeeds", async () => { + const check = scratchCheck(); + const { call, launches } = await turn(); + const started = performance.now(); + const answer = call(); + // The scratch check finishes 250 ms into the call, as a short git query does. + await Bun.sleep(250); + expect(launches, "REFERENCE_CALL_WAS_REFUSED_WHILE_THE_SCRATCH_CHECK_HELD").toEqual(["ls-remote:refused"]); + check.release(); + const result: ReferenceToolResult = await answer; + const elapsed = performance.now() - started; + expect(result, "REFERENCE_CALL_SUCCEEDS_ONCE_THE_SCRATCH_CHECK_FINISHES").toMatchObject({ ok: true, source: { repository: PUBLIC, commit: TIP } }); + expect(elapsed, "REFERENCE_CALL_IS_ADMITTED_WITHIN_ITS_STATED_BOUND").toBeLessThan(BOUND_MS); + expect(launches, "REFERENCE_CALL_RUNS_EVERY_GIT_COMMAND_AFTER_ITS_WAIT") + .toEqual(["ls-remote:refused", "ls-remote:admitted", "fetch:admitted", "rev-parse:admitted", "checkout:admitted"]); +}); + +test("a reference_source call answers busy with retry guidance when maintenance stays held past its bound", async () => { + scratchCheck(); + const { call, launches } = await turn({ admissionWaitMs: 300 }); + const started = performance.now(); + const result = await call(); + expect(result, "REFERENCE_CALL_PAST_ITS_BOUND_IS_BUSY_NOT_UNAVAILABLE").toMatchObject({ ok: false, code: "busy" }); + expect(result.ok === false && result.message, "REFERENCE_BUSY_REFUSAL_TELLS_THE_AGENT_TO_RETRY").toMatch(/nothing ran\. Retry this request/); + expect(performance.now() - started, "REFERENCE_CALL_WAITS_ITS_BOUND_BEFORE_REFUSING").toBeGreaterThanOrEqual(290); + expect(launches.every(launch => launch === "ls-remote:refused"), "REFERENCE_CALL_NEVER_RAN_A_COMMAND").toBe(true); +}); + +test("a fetch refused past its bound after a successful resolution is busy too, and nothing is published", async () => { + // A longer maintenance command, such as an index, starts between the resolution and the fetch. + const { call, launches } = await turn({ admissionWaitMs: 300, afterStep: step => { if (step === "ls-remote") held.push(reserveMaintenanceTemp(LIMITS, domain, "index")); } }); + const result = await call(); + expect(result, "REFERENCE_FETCH_PAST_ITS_BOUND_IS_BUSY_NOT_UNAVAILABLE").toMatchObject({ ok: false, code: "busy" }); + expect(launches.slice(0, 2), "REFERENCE_FETCH_WAS_REFUSED_AFTER_ITS_RESOLUTION").toEqual(["ls-remote:admitted", "fetch:refused"]); + expect(launches, "REFERENCE_FETCH_NEVER_CHECKED_OUT").not.toContain("checkout:admitted"); +}); + +test("a maintenance-busy refusal that reaches the tool unconverted is still busy", async () => { + const principalId = createPrincipal(db, { authMethod: "password", label: "Penelope", ttlSeconds: 86_400 }).id; + scratchCheck(); + let busy: unknown; + try { held.push(reserveMaintenanceTemp(LIMITS, domain, "git")); } catch (error) { busy = error; } + expect(busy, "FIXTURE_HOLDS_A_REAL_BUSY_REFUSAL").toBeInstanceOf(MaintenanceTempBusyError); + const tools = createReferenceTools({ sources: { bindable: async () => ({ public: "/views/public", private: "/views/private" }), request: async () => { throw busy; } } }); + await tools.begin("ithaca-turn", { principalId, posture: "interactive", generation: null }); + const result = await tools.call("ithaca-turn", principalId, { tool: "reference_source", input: { repository: PUBLIC, revision: "main" } }); + expect(result, "RAW_MAINTENANCE_BUSY_IS_A_BUSY_REFUSAL").toEqual({ ok: false, code: "busy", message: "Host maintenance is busy, so nothing ran. Retry this request in a minute." }); +}); From 9ac89992c6b6e0315bd308dcbd263ec5409509c5 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 22:14:07 +0000 Subject: [PATCH 2/5] chore(scripts): TEMPORARY hosted probe running the integrated reference cell (#4079) Copied from #4072's probe so hosted runtime_host runs the integrated cell. Reverted before the PR is ready. Co-Authored-By: Claude Opus 5.5 --- scripts/prove-reference-pool.ts | 37 ++++++++++++++++++++------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 54c9374880..34c5e98af8 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -37,19 +37,28 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); - const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); - mkdirSync(output, { recursive: true }); - const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); - console.log(`Reference pool proof artifacts: ${artifact}`); - const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); - const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; - const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; - const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); - const forward = (signal: NodeJS.Signals) => child.kill(signal); - for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); - const code = await child.exited; - for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); - if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); - console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); + // TEMPORARY (#3513) hosted feedback probe, reverted before the PR is ready: the hosted runtime_host cell runs this + // script without arguments, and the integrated cell has no hosted cell of its own, so run both cells here. + const cells = selected.length ? [integrated] : [undefined, { backends: ["claude", "pi"] }]; + const failures: string[] = []; + for (const integrated of cells) { + try { + const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); + mkdirSync(output, { recursive: true }); + const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); + console.log(`Reference pool proof artifacts: ${artifact}`); + const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); + const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; + const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; + const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const forward = (signal: NodeJS.Signals) => child.kill(signal); + for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); + const code = await child.exited; + for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); + if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); + console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); + } catch (error) { failures.push(String(error instanceof Error ? error.message : error)); } + } + if (failures.length) throw Error(failures.join("\n")); } catch (error) { console.error(String(error instanceof Error ? error.message : error)); process.exitCode = 1; } } From f7624397eb58ea85e3a9aced92032b7eace0889e Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 12:05:11 +0000 Subject: [PATCH 3/5] test(ui-sdk,ui-server): place the scratch admission brain where a maintenance worker sees it; import an exported type (#4079) Hosted heavy feedback showed two test faults in this PR, not in the fix: - The writable-scratch test built its brain under the OS /tmp, which a maintenance worker replaces with its own, so the worker's git query could not see it and scratch stayed read-only after the wait had worked. The brain now lives in the repository's gitignored tmp/, as the worker sandbox tests place theirs, and the assertion prints the mount's reason. - The reference admission test imported MaintenanceTempReservation, which the SDK's internal entry does not export (TS2305 in strict typecheck). Co-Authored-By: Claude Opus 5.5 --- .../ui-sdk/tests/maintenance-temp-holders.test.ts | 15 ++++++++++++--- .../tests/reference-maintenance-admission.test.ts | 3 ++- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts index 610314c096..13585fdd02 100644 --- a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts +++ b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts @@ -3,7 +3,7 @@ import { Database } from "bun:sqlite"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, readlinkSync, realpathSync, rmSync } from "node:fs"; import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { join, resolve } from "node:path"; import { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceTempReservation } from "../src/server/maintenance-temp-budget"; import { prepareWorkerSandbox, prepareWorkerSandboxAsync } from "../src/server/worker-launcher"; import { FIRST_PARTY_FAILURE_CLASSES } from "../src/protocol"; @@ -14,6 +14,7 @@ const LIMITS = { allowanceBytes: 268435456, budgetBytes: 268435456 }; let root: string; let domain: { statePath: string }; const held: MaintenanceTempReservation[] = []; +const cleanups: (() => void)[] = []; beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), "odysseus-maintenance-holders-"))); mkdirSync(join(root, "state")); @@ -21,6 +22,7 @@ beforeEach(() => { }); afterEach(() => { for (const reservation of held.splice(0)) reservation.release(); + for (const cleanup of cleanups.splice(0)) cleanup(); rmSync(root, { recursive: true, force: true }); }); const hold = (kind: Parameters[2]) => { @@ -110,7 +112,14 @@ test("freedWithin() reports a release inside its bound, false past it, and rejec }); test("a turn's scratch check that starts while a reference Git command holds the budget waits for it, and scratch stays writable (#4079)", async () => { - const brain = join(root, "brain"); + // The worker's git query must see the brain: not under /tmp, which a + // maintenance worker replaces with its own, and inside the repository's + // gitignored tmp/, as the worker sandbox tests place theirs. + const repo = resolve(import.meta.dir, "../../.."); + mkdirSync(join(repo, "tmp"), { recursive: true }); + const brainRoot = mkdtempSync(join(repo, "tmp/odysseus-scratch-admission-")); + cleanups.push(() => rmSync(brainRoot, { recursive: true, force: true })); + const brain = join(brainRoot, "brain"); mkdirSync(brain); // The turn's first reference_source call is running its short ls-remote. const reference = hold("git"); @@ -119,7 +128,7 @@ test("a turn's scratch check that starts while a reference Git command holds the const scratch = sandbox.areas.find(area => area.name === "scratch"); const reason = scratch?.mount.writable === false ? scratch.mount.reason : ""; expect(reason, "TURN_SCRATCH_CHECK_IS_NOT_REFUSED_BY_A_SHORT_REFERENCE_COMMAND").not.toContain("Maintenance temporary storage is busy"); - expect(scratch?.mount.writable, "TURN_SCRATCH_STAYS_WRITABLE_AFTER_A_SHORT_REFERENCE_COMMAND").toBe(true); + expect(scratch?.mount, "TURN_SCRATCH_STAYS_WRITABLE_AFTER_A_SHORT_REFERENCE_COMMAND").toMatchObject({ writable: true }); }); test("a synchronous scratch check still refuses at once while maintenance holds the budget (#4079)", () => { diff --git a/packages/ui-server/tests/reference-maintenance-admission.test.ts b/packages/ui-server/tests/reference-maintenance-admission.test.ts index 15ef03687e..b031efe9b5 100644 --- a/packages/ui-server/tests/reference-maintenance-admission.test.ts +++ b/packages/ui-server/tests/reference-maintenance-admission.test.ts @@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "nod import { tmpdir } from "node:os"; import { join } from "node:path"; import type { Database } from "bun:sqlite"; -import { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceCommand, type MaintenanceTempReservation } from "@schlessera/brain-ui-sdk/internal"; +import { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; import type { ReferenceToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; import { createUiDb } from "../src/db/client"; import { createPrincipal } from "../src/db/principals"; @@ -22,6 +22,7 @@ const LIMITS = { allowanceBytes: 268435456, budgetBytes: 268435456 }; const BOUND_MS = 30_000; const BRAIN = "ithaca-brain", PUBLIC = "https://github.com/odysseus/ithaca", TIP = "1".repeat(40); let root: string, db: Database, domain: { statePath: string }; +type MaintenanceTempReservation = ReturnType; const held: MaintenanceTempReservation[] = []; beforeEach(() => { root = realpathSync(mkdtempSync(join(tmpdir(), "odysseus-reference-admission-"))); From 2407cb4067bbd1ef2b17ddc5747c2725c4d8d535 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 12:05:11 +0000 Subject: [PATCH 4/5] Revert "chore(scripts): TEMPORARY hosted probe running the integrated reference cell (#4079)" The probe ran the integrated cell on hosted runtime_host in heavy feedback run 43854394276: Integrated reference proof passed (claude, pi). Co-Authored-By: Claude Opus 5.5 --- scripts/prove-reference-pool.ts | 37 +++++++++++++-------------------- 1 file changed, 14 insertions(+), 23 deletions(-) diff --git a/scripts/prove-reference-pool.ts b/scripts/prove-reference-pool.ts index 34c5e98af8..54c9374880 100644 --- a/scripts/prove-reference-pool.ts +++ b/scripts/prove-reference-pool.ts @@ -37,28 +37,19 @@ if (import.meta.main) { const security = Bun.spawnSync(["docker", "info", "--format", "{{json .SecurityOptions}}"], { stdout: "pipe", stderr: "pipe" }); if (security.exitCode !== 0) throw Error("Cannot inspect Docker runtime security prerequisites."); const apparmor = (JSON.parse(new TextDecoder().decode(security.stdout)) as string[]).some(value => value.startsWith("name=apparmor")); - // TEMPORARY (#3513) hosted feedback probe, reverted before the PR is ready: the hosted runtime_host cell runs this - // script without arguments, and the integrated cell has no hosted cell of its own, so run both cells here. - const cells = selected.length ? [integrated] : [undefined, { backends: ["claude", "pi"] }]; - const failures: string[] = []; - for (const integrated of cells) { - try { - const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); - mkdirSync(output, { recursive: true }); - const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); - console.log(`Reference pool proof artifacts: ${artifact}`); - const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); - const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; - const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; - const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); - const forward = (signal: NodeJS.Signals) => child.kill(signal); - for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); - const code = await child.exited; - for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); - if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); - console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); - } catch (error) { failures.push(String(error instanceof Error ? error.message : error)); } - } - if (failures.length) throw Error(failures.join("\n")); + const root = resolve(import.meta.dir, ".."), output = join(root, "tmp", "reference-pool-proof"); + mkdirSync(output, { recursive: true }); + const artifact = mkdtempSync(join(output, integrated ? "run-integrated-" : "run-pool-")); chmodSync(artifact, 0o755); + console.log(`Reference pool proof artifacts: ${artifact}`); + const head = Bun.spawnSync(["git", "-C", root, "rev-parse", "HEAD"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim(); + const dirty = Bun.spawnSync(["git", "-C", root, "status", "--porcelain", "--untracked-files=no"], { stdout: "pipe", stderr: "ignore" }).stdout.toString().trim() !== ""; + const candidate = /^[0-9a-f]{40}$/.test(head) ? `${head}${dirty ? "+dirty" : ""}` : undefined; + const child = Bun.spawn(referencePoolDockerArgs(root, artifact, apparmor, realpathSync(process.execPath), integrated, candidate), { stdin: "ignore", stdout: "inherit", stderr: "inherit" }); + const forward = (signal: NodeJS.Signals) => child.kill(signal); + for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, forward); + const code = await child.exited; + for (const signal of ["SIGINT", "SIGTERM"] as const) process.off(signal, forward); + if (code !== 0) throw Error(`Reference pool proof failed with exit ${code}; inspect ${artifact}.`); + console.log(integrated ? `Integrated reference proof passed (${integrated.backends.join(", ")}).` : "Reference pool proof passed."); } catch (error) { console.error(String(error instanceof Error ? error.message : error)); process.exitCode = 1; } } From 62934ee91fa214c81dbfa1aa152be7ad2de2d5bd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Mon, 16 Nov 2026 18:53:21 +0000 Subject: [PATCH 5/5] test(ui-sdk): give the scratch admission test's maintenance worker a fixture input lease (#4079) Candidate confirmation showed the writable-scratch test still read-only: "git could not run to confirm .brain/scratch/ is gitignored". The wait had worked, but the worker never ran git. It had no prepared startup view, which every real-worker writable test supplies through createFixtureMaintenanceHost. The test now uses that host, with its ledger state beside the brain in the repository's gitignored tmp/ and masked from the worker, as maintenance-temp-helpers.test.ts does. It passes locally, where the worker now runs, and still fails on main with the "(held by: git)" busy refusal. Co-Authored-By: Claude Opus 5.5 --- .../tests/maintenance-temp-holders.test.ts | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts index 13585fdd02..e964c832df 100644 --- a/packages/ui-sdk/tests/maintenance-temp-holders.test.ts +++ b/packages/ui-sdk/tests/maintenance-temp-holders.test.ts @@ -7,6 +7,7 @@ import { join, resolve } from "node:path"; import { MaintenanceTempBusyError, reserveMaintenanceTemp, type MaintenanceTempReservation } from "../src/server/maintenance-temp-budget"; import { prepareWorkerSandbox, prepareWorkerSandboxAsync } from "../src/server/worker-launcher"; import { FIRST_PARTY_FAILURE_CLASSES } from "../src/protocol"; +import { createFixtureMaintenanceHost } from "./helpers/worker-startup-view-fixture.js"; // #3461: production limits (one 256 MiB allowance in a 256 MiB budget) on a // private shared-state domain, so no other test's ledger is involved. @@ -112,19 +113,21 @@ test("freedWithin() reports a release inside its bound, false past it, and rejec }); test("a turn's scratch check that starts while a reference Git command holds the budget waits for it, and scratch stays writable (#4079)", async () => { - // The worker's git query must see the brain: not under /tmp, which a - // maintenance worker replaces with its own, and inside the repository's - // gitignored tmp/, as the worker sandbox tests place theirs. + // As the writable-area tests run a real maintenance worker: the brain and + // its ledger state sit in the repository's gitignored tmp/, outside the + // worker's own /tmp, and the worker reads a prepared fixture input lease. const repo = resolve(import.meta.dir, "../../.."); mkdirSync(join(repo, "tmp"), { recursive: true }); - const brainRoot = mkdtempSync(join(repo, "tmp/odysseus-scratch-admission-")); - cleanups.push(() => rmSync(brainRoot, { recursive: true, force: true })); - const brain = join(brainRoot, "brain"); - mkdirSync(brain); + const fixture = mkdtempSync(join(repo, "tmp/odysseus-scratch-admission-")); + cleanups.push(() => rmSync(fixture, { recursive: true, force: true })); + const brain = join(fixture, "brain"), state = join(fixture, "state"); + mkdirSync(brain); mkdirSync(state); + const maintenance = createFixtureMaintenanceHost(brain, { tempLimits: LIMITS, tempDomain: { statePath: join(state, "ui.db") }, maskPaths: [state] }); + cleanups.unshift(() => maintenance.cleanup()); // The turn's first reference_source call is running its short ls-remote. - const reference = hold("git"); + const reference = reserveMaintenanceTemp(LIMITS, maintenance.tempDomain, "git"); held.push(reference); setTimeout(() => reference.release(), 250); - const sandbox = await prepareWorkerSandboxAsync(brain, { areas: ["scratch"], maintenance: { tempLimits: LIMITS, tempDomain: domain } }); + const sandbox = await prepareWorkerSandboxAsync(brain, { areas: ["scratch"], maintenance }); const scratch = sandbox.areas.find(area => area.name === "scratch"); const reason = scratch?.mount.writable === false ? scratch.mount.reason : ""; expect(reason, "TURN_SCRATCH_CHECK_IS_NOT_REFUSED_BY_A_SHORT_REFERENCE_COMMAND").not.toContain("Maintenance temporary storage is busy");